{
  "version": 3,
  "sources": ["../../../node_modules/@rails/actioncable/src/adapters.js", "../../../node_modules/@rails/actioncable/src/logger.js", "../../../node_modules/@rails/actioncable/src/connection_monitor.js", "../../../node_modules/@rails/actioncable/src/internal.js", "../../../node_modules/@rails/actioncable/src/connection.js", "../../../node_modules/@rails/actioncable/src/subscription.js", "../../../node_modules/@rails/actioncable/src/subscription_guarantor.js", "../../../node_modules/@rails/actioncable/src/subscriptions.js", "../../../node_modules/@rails/actioncable/src/consumer.js", "../../../node_modules/@rails/actioncable/src/index.js", "../../../node_modules/slugify/slugify.js", "../../../node_modules/@uppy/utils/lib/getTimeStamp.js", "../../../node_modules/@uppy/core/lib/loggers.js", "../../../node_modules/nanoid/non-secure/index.cjs", "../../../node_modules/@transloadit/prettier-bytes/prettierBytes.js", "../../../node_modules/wildcard/index.js", "../../../node_modules/mime-match/index.js", "../../../node_modules/@uppy/core/lib/Restricter.js", "../../../node_modules/@uppy/utils/lib/hasProperty.js", "../../../node_modules/@uppy/utils/lib/Translator.js", "../../../node_modules/namespace-emitter/index.js", "../../../node_modules/lodash.throttle/index.js", "../../../node_modules/@uppy/store-default/lib/index.js", "../../../node_modules/@uppy/utils/lib/getFileNameAndExtension.js", "../../../node_modules/@uppy/utils/lib/mimeTypes.js", "../../../node_modules/@uppy/utils/lib/getFileType.js", "../../../node_modules/@uppy/utils/lib/generateFileID.js", "../../../node_modules/@uppy/core/lib/supportsUploadProgress.js", "../../../node_modules/@uppy/core/lib/getFileName.js", "../../../node_modules/@uppy/core/lib/locale.js", "../../../node_modules/@uppy/core/lib/Uppy.js", "../../../node_modules/preact/src/constants.js", "../../../node_modules/preact/src/util.js", "../../../node_modules/preact/src/options.js", "../../../node_modules/preact/src/create-element.js", "../../../node_modules/preact/src/component.js", "../../../node_modules/preact/src/diff/props.js", "../../../node_modules/preact/src/create-context.js", "../../../node_modules/preact/src/diff/children.js", "../../../node_modules/preact/src/diff/index.js", "../../../node_modules/preact/src/render.js", "../../../node_modules/preact/src/clone-element.js", "../../../node_modules/preact/src/diff/catch-error.js", "../../../node_modules/@uppy/utils/lib/isDOMElement.js", "../../../node_modules/@uppy/utils/lib/findDOMElement.js", "../../../node_modules/@uppy/utils/lib/getTextDirection.js", "../../../node_modules/@uppy/core/lib/BasePlugin.js", "../../../node_modules/@uppy/core/lib/UIPlugin.js", "../../../node_modules/@uppy/core/lib/index.js", "../../../node_modules/@uppy/utils/lib/NetworkError.js", "../../../node_modules/@uppy/utils/lib/fetchWithNetworkError.js", "../../../node_modules/@uppy/utils/lib/ErrorWithCause.js", "../../../node_modules/@uppy/companion-client/lib/AuthError.js", "../../../node_modules/@uppy/companion-client/lib/RequestClient.js", "../../../node_modules/@uppy/companion-client/lib/tokenStorage.js", "../../../node_modules/@uppy/companion-client/lib/Provider.js", "../../../node_modules/@uppy/companion-client/lib/SearchProvider.js", "../../../node_modules/@uppy/companion-client/lib/Socket.js", "../../../node_modules/@uppy/companion-client/lib/index.js", "../../../node_modules/@uppy/provider-views/lib/ProviderView/AuthView.js", "../../../node_modules/@uppy/provider-views/lib/ProviderView/User.js", "../../../node_modules/@uppy/provider-views/lib/Breadcrumbs.js", "../../../node_modules/@uppy/provider-views/lib/ProviderView/Header.js", "../../../node_modules/classnames/index.js", "../../../node_modules/@uppy/utils/lib/remoteFileObjToLocal.js", "../../../node_modules/@uppy/provider-views/lib/Filter.js", "../../../node_modules/@uppy/provider-views/lib/FooterActions.js", "../../../node_modules/@uppy/provider-views/lib/Item/components/ItemIcon.js", "../../../node_modules/@uppy/provider-views/lib/Item/components/GridLi.js", "../../../node_modules/@uppy/provider-views/lib/Item/components/ListLi.js", "../../../node_modules/@uppy/provider-views/lib/Item/index.js", "../../../node_modules/@uppy/provider-views/lib/Browser.js", "../../../node_modules/@uppy/provider-views/lib/Loader.js", "../../../node_modules/@uppy/provider-views/lib/CloseWrapper.js", "../../../node_modules/@uppy/utils/lib/isPreviewSupported.js", "../../../node_modules/@uppy/provider-views/lib/SharedHandler.js", "../../../node_modules/@uppy/provider-views/lib/View.js", "../../../node_modules/@uppy/provider-views/lib/ProviderView/ProviderView.js", "../../../node_modules/@uppy/provider-views/lib/ProviderView/index.js", "../../../node_modules/@uppy/provider-views/lib/SearchProviderView/InputView.js", "../../../node_modules/@uppy/provider-views/lib/SearchProviderView/Header.js", "../../../node_modules/@uppy/provider-views/lib/SearchProviderView/SearchProviderView.js", "../../../node_modules/@uppy/provider-views/lib/SearchProviderView/index.js", "../../../node_modules/@uppy/provider-views/lib/index.js", "../../../node_modules/@uppy/store-redux/lib/index.js", "../../../node_modules/@uppy/utils/lib/toArray.js", "../../../node_modules/@uppy/utils/lib/FOCUSABLE_ELEMENTS.js", "../../../node_modules/@uppy/dashboard/lib/utils/getActiveOverlayEl.js", "../../../node_modules/@uppy/dashboard/lib/utils/trapFocus.js", "../../../node_modules/@uppy/utils/lib/getSpeed.js", "../../../node_modules/@uppy/utils/lib/getBytesRemaining.js", "../../../node_modules/@uppy/status-bar/lib/StatusBarStates.js", "../../../node_modules/@uppy/utils/lib/secondsToTime.js", "../../../node_modules/@uppy/utils/lib/prettyETA.js", "../../../node_modules/@uppy/status-bar/lib/Components.js", "../../../node_modules/@uppy/status-bar/lib/calculateProcessingProgress.js", "../../../node_modules/@uppy/status-bar/lib/StatusBar.js", "../../../node_modules/@uppy/status-bar/lib/locale.js", "../../../node_modules/@uppy/status-bar/lib/_StatusBar.js", "../../../node_modules/@uppy/status-bar/lib/index.js", "../../../node_modules/@uppy/informer/lib/FadeIn.js", "../../../node_modules/@uppy/informer/lib/TransitionGroup.js", "../../../node_modules/@uppy/informer/lib/Informer.js", "../../../node_modules/@uppy/informer/lib/index.js", "../../../node_modules/exifr/dist/mini.umd.js", "../../../node_modules/@uppy/utils/lib/dataURItoBlob.js", "../../../node_modules/@uppy/utils/lib/isObjectURL.js", "../../../node_modules/@uppy/thumbnail-generator/lib/locale.js", "../../../node_modules/@uppy/thumbnail-generator/lib/index.js", "../../../node_modules/@uppy/utils/lib/findAllDOMElements.js", "../../../node_modules/@uppy/utils/lib/getDroppedFiles/utils/webkitGetAsEntryApi/getFilesAndDirectoriesFromDirectory.js", "../../../node_modules/@uppy/utils/lib/getDroppedFiles/utils/webkitGetAsEntryApi/index.js", "../../../node_modules/@uppy/utils/lib/getDroppedFiles/utils/fallbackApi.js", "../../../node_modules/@uppy/utils/lib/getDroppedFiles/index.js", "../../../node_modules/memoize-one/dist/memoize-one.cjs.js", "../../../node_modules/lodash.debounce/index.js", "../../../node_modules/@uppy/dashboard/lib/utils/createSuperFocus.js", "../../../node_modules/@uppy/utils/lib/isDragDropSupported.js", "../../../node_modules/is-shallow-equal/index.js", "../../../node_modules/@uppy/dashboard/lib/utils/getFileTypeIcon.js", "../../../node_modules/@uppy/dashboard/lib/components/FilePreview.js", "../../../node_modules/@uppy/dashboard/lib/components/FileItem/MetaErrorMessage.js", "../../../node_modules/@uppy/dashboard/lib/components/FileItem/FilePreviewAndLink/index.js", "../../../node_modules/@uppy/dashboard/lib/components/FileItem/FileProgress/index.js", "../../../node_modules/@uppy/utils/lib/truncateString.js", "../../../node_modules/@uppy/dashboard/lib/components/FileItem/FileInfo/index.js", "../../../node_modules/@uppy/dashboard/lib/utils/copyToClipboard.js", "../../../node_modules/@uppy/dashboard/lib/components/FileItem/Buttons/index.js", "../../../node_modules/@uppy/dashboard/lib/components/FileItem/index.js", "../../../node_modules/@uppy/dashboard/lib/components/VirtualList.js", "../../../node_modules/@uppy/dashboard/lib/components/FileList.js", "../../../node_modules/@uppy/dashboard/lib/components/AddFiles.js", "../../../node_modules/@uppy/dashboard/lib/components/AddFilesPanel.js", "../../../node_modules/@uppy/dashboard/lib/utils/ignoreEvent.js", "../../../node_modules/@uppy/dashboard/lib/components/PickerPanelContent.js", "../../../node_modules/@uppy/dashboard/lib/components/EditorPanel.js", "../../../node_modules/@uppy/dashboard/lib/components/PickerPanelTopBar.js", "../../../node_modules/@uppy/dashboard/lib/components/FileCard/index.js", "../../../node_modules/@uppy/dashboard/lib/components/Slide.js", "../../../node_modules/@uppy/dashboard/lib/components/Dashboard.js", "../../../node_modules/@uppy/dashboard/lib/locale.js", "../../../node_modules/@uppy/dashboard/lib/Dashboard.js", "../../../node_modules/@uppy/dashboard/lib/index.js", "../../../node_modules/@uppy/drag-drop/lib/locale.js", "../../../node_modules/@uppy/drag-drop/lib/DragDrop.js", "../../../node_modules/@uppy/drag-drop/lib/index.js", "../../../node_modules/@uppy/drop-target/lib/index.js", "../../../node_modules/@uppy/file-input/lib/locale.js", "../../../node_modules/@uppy/file-input/lib/FileInput.js", "../../../node_modules/@uppy/file-input/lib/index.js", "../../../node_modules/cropperjs/dist/cropper.js", "../../../node_modules/@uppy/image-editor/lib/Editor.js", "../../../node_modules/@uppy/image-editor/lib/locale.js", "../../../node_modules/@uppy/image-editor/lib/ImageEditor.js", "../../../node_modules/@uppy/image-editor/lib/index.js", "../../../node_modules/@uppy/progress-bar/lib/ProgressBar.js", "../../../node_modules/@uppy/progress-bar/lib/index.js", "../../../node_modules/@uppy/utils/lib/getFileTypeExtension.js", "../../../node_modules/@uppy/audio/lib/supportsMediaRecorder.js", "../../../node_modules/preact/hooks/src/index.js", "../../../node_modules/@uppy/audio/lib/RecordButton.js", "../../../node_modules/@uppy/audio/lib/formatSeconds.js", "../../../node_modules/@uppy/audio/lib/RecordingLength.js", "../../../node_modules/@uppy/audio/lib/AudioSourceSelect.js", "../../../node_modules/@uppy/audio/lib/audio-oscilloscope/index.js", "../../../node_modules/@uppy/audio/lib/SubmitButton.js", "../../../node_modules/@uppy/audio/lib/DiscardButton.js", "../../../node_modules/@uppy/audio/lib/RecordingScreen.js", "../../../node_modules/@uppy/audio/lib/PermissionsScreen.js", "../../../node_modules/@uppy/audio/lib/locale.js", "../../../node_modules/@uppy/audio/lib/Audio.js", "../../../node_modules/@uppy/audio/lib/index.js", "../../../node_modules/@uppy/box/lib/locale.js", "../../../node_modules/@uppy/box/lib/Box.js", "../../../node_modules/@uppy/box/lib/index.js", "../../../node_modules/@uppy/dropbox/lib/locale.js", "../../../node_modules/@uppy/dropbox/lib/Dropbox.js", "../../../node_modules/@uppy/dropbox/lib/index.js", "../../../node_modules/@uppy/facebook/lib/locale.js", "../../../node_modules/@uppy/facebook/lib/Facebook.js", "../../../node_modules/@uppy/facebook/lib/index.js", "../../../node_modules/@uppy/google-drive/lib/DriveProviderViews.js", "../../../node_modules/@uppy/google-drive/lib/locale.js", "../../../node_modules/@uppy/google-drive/lib/GoogleDrive.js", "../../../node_modules/@uppy/google-drive/lib/index.js", "../../../node_modules/@uppy/instagram/lib/locale.js", "../../../node_modules/@uppy/instagram/lib/Instagram.js", "../../../node_modules/@uppy/instagram/lib/index.js", "../../../node_modules/@uppy/onedrive/lib/locale.js", "../../../node_modules/@uppy/onedrive/lib/OneDrive.js", "../../../node_modules/@uppy/onedrive/lib/index.js", "../../../node_modules/@uppy/unsplash/lib/Unsplash.js", "../../../node_modules/@uppy/unsplash/lib/index.js", "../../../node_modules/@uppy/url/lib/UrlUI.js", "../../../node_modules/@uppy/url/lib/utils/forEachDroppedOrPastedUrl.js", "../../../node_modules/@uppy/url/lib/locale.js", "../../../node_modules/@uppy/url/lib/Url.js", "../../../node_modules/@uppy/url/lib/index.js", "../../../node_modules/@uppy/zoom/lib/locale.js", "../../../node_modules/@uppy/zoom/lib/Zoom.js", "../../../node_modules/@uppy/zoom/lib/index.js", "../../../node_modules/@uppy/remote-sources/lib/index.js", "../../../node_modules/@uppy/screen-capture/lib/ScreenRecIcon.js", "../../../node_modules/@uppy/screen-capture/lib/RecordButton.js", "../../../node_modules/@uppy/screen-capture/lib/SubmitButton.js", "../../../node_modules/@uppy/screen-capture/lib/StopWatch.js", "../../../node_modules/@uppy/screen-capture/lib/StreamStatus.js", "../../../node_modules/@uppy/screen-capture/lib/CaptureScreen.js", "../../../node_modules/@uppy/screen-capture/lib/locale.js", "../../../node_modules/@uppy/screen-capture/lib/ScreenCapture.js", "../../../node_modules/@uppy/screen-capture/lib/index.js", "../../../node_modules/@uppy/utils/lib/canvasToBlob.js", "../../../node_modules/@uppy/webcam/lib/supportsMediaRecorder.js", "../../../node_modules/@uppy/webcam/lib/CameraIcon.js", "../../../node_modules/@uppy/webcam/lib/SnapshotButton.js", "../../../node_modules/@uppy/webcam/lib/RecordButton.js", "../../../node_modules/@uppy/webcam/lib/formatSeconds.js", "../../../node_modules/@uppy/webcam/lib/RecordingLength.js", "../../../node_modules/@uppy/webcam/lib/VideoSourceSelect.js", "../../../node_modules/@uppy/webcam/lib/SubmitButton.js", "../../../node_modules/@uppy/webcam/lib/DiscardButton.js", "../../../node_modules/@uppy/webcam/lib/CameraScreen.js", "../../../node_modules/@uppy/webcam/lib/PermissionsScreen.js", "../../../node_modules/@uppy/webcam/lib/locale.js", "../../../node_modules/@uppy/webcam/lib/Webcam.js", "../../../node_modules/@uppy/webcam/lib/index.js", "../../../node_modules/@uppy/utils/lib/RateLimitedQueue.js", "../../../node_modules/@uppy/utils/lib/emitSocketProgress.js", "../../../node_modules/@uppy/utils/lib/getSocketHost.js", "../../../node_modules/@uppy/utils/lib/EventTracker.js", "../../../node_modules/@uppy/utils/lib/ProgressTimeout.js", "../../../node_modules/@uppy/utils/lib/isNetworkError.js", "../../../node_modules/@uppy/aws-s3/lib/MiniXHRUpload.js", "../../../node_modules/@uppy/aws-s3/lib/isXml.js", "../../../node_modules/@uppy/aws-s3/lib/locale.js", "../../../node_modules/@uppy/aws-s3/lib/index.js", "../../../node_modules/@uppy/utils/lib/AbortController.js", "../../../node_modules/@uppy/utils/lib/delay.js", "../../../node_modules/@uppy/aws-s3-multipart/lib/MultipartUploader.js", "../../../node_modules/@uppy/aws-s3-multipart/lib/index.js", "../../../node_modules/js-base64/base64.js", "../../../node_modules/requires-port/index.js", "../../../node_modules/querystringify/index.js", "../../../node_modules/url-parse/index.js", "../../../node_modules/tus-js-client/lib.es5/error.js", "../../../node_modules/tus-js-client/lib.es5/logger.js", "../../../node_modules/tus-js-client/lib.es5/uuid.js", "../../../node_modules/tus-js-client/lib.es5/upload.js", "../../../node_modules/tus-js-client/lib.es5/noopUrlStorage.js", "../../../node_modules/tus-js-client/lib.es5/browser/urlStorage.js", "../../../node_modules/tus-js-client/lib.es5/browser/httpStack.js", "../../../node_modules/tus-js-client/lib.es5/browser/isReactNative.js", "../../../node_modules/tus-js-client/lib.es5/browser/uriToBlob.js", "../../../node_modules/tus-js-client/lib.es5/browser/sources/isCordova.js", "../../../node_modules/tus-js-client/lib.es5/browser/sources/readAsByteArray.js", "../../../node_modules/tus-js-client/lib.es5/browser/sources/FileSource.js", "../../../node_modules/tus-js-client/lib.es5/browser/sources/StreamSource.js", "../../../node_modules/tus-js-client/lib.es5/browser/fileReader.js", "../../../node_modules/tus-js-client/lib.es5/browser/fingerprint.js", "../../../node_modules/tus-js-client/lib.es5/browser/index.js", "../../../node_modules/@uppy/utils/lib/settle.js", "../../../node_modules/@uppy/tus/lib/getFingerprint.js", "../../../node_modules/@uppy/tus/lib/index.js", "../../../node_modules/component-emitter/index.js", "../../../node_modules/@uppy/transloadit/lib/parseUrl.js", "../../../node_modules/engine.io-parser/build/cjs/commons.js", "../../../node_modules/engine.io-parser/build/cjs/encodePacket.browser.js", "../../../node_modules/engine.io-parser/build/cjs/contrib/base64-arraybuffer.js", "../../../node_modules/engine.io-parser/build/cjs/decodePacket.browser.js", "../../../node_modules/engine.io-parser/build/cjs/index.js", "../../../node_modules/@socket.io/component-emitter/lib/cjs/index.js", "../../../node_modules/engine.io-client/build/cjs/globals.js", "../../../node_modules/engine.io-client/build/cjs/util.js", "../../../node_modules/engine.io-client/build/cjs/contrib/parseqs.js", "../../../node_modules/ms/index.js", "../../../node_modules/debug/src/common.js", "../../../node_modules/debug/src/browser.js", "../../../node_modules/engine.io-client/build/cjs/transport.js", "../../../node_modules/engine.io-client/build/cjs/transports/polling.js", "../../../node_modules/engine.io-client/build/cjs/contrib/has-cors.js", "../../../node_modules/engine.io-client/build/cjs/transports/polling-xhr.js", "../../../node_modules/engine.io-client/build/cjs/transports/websocket.js", "../../../node_modules/engine.io-client/build/cjs/transports/webtransport.js", "../../../node_modules/engine.io-client/build/cjs/transports/index.js", "../../../node_modules/engine.io-client/build/cjs/contrib/parseuri.js", "../../../node_modules/engine.io-client/build/cjs/socket.js", "../../../node_modules/engine.io-client/build/cjs/transports/polling-fetch.js", "../../../node_modules/engine.io-client/build/cjs/index.js", "../../../node_modules/socket.io-client/build/cjs/url.js", "../../../node_modules/socket.io-parser/build/cjs/is-binary.js", "../../../node_modules/socket.io-parser/build/cjs/binary.js", "../../../node_modules/socket.io-parser/build/cjs/index.js", "../../../node_modules/socket.io-client/build/cjs/on.js", "../../../node_modules/socket.io-client/build/cjs/socket.js", "../../../node_modules/socket.io-client/build/cjs/contrib/backo2.js", "../../../node_modules/socket.io-client/build/cjs/manager.js", "../../../node_modules/socket.io-client/build/cjs/index.js", "../../../node_modules/@uppy/transloadit/lib/Assembly.js", "../../../node_modules/@uppy/transloadit/lib/Client.js", "../../../node_modules/@uppy/transloadit/lib/AssemblyOptions.js", "../../../node_modules/@uppy/transloadit/lib/AssemblyWatcher.js", "../../../node_modules/@uppy/transloadit/lib/locale.js", "../../../node_modules/@uppy/transloadit/lib/index.js", "../../../node_modules/@uppy/xhr-upload/lib/locale.js", "../../../node_modules/@uppy/xhr-upload/lib/index.js", "../../../node_modules/@uppy/compressor/node_modules/@transloadit/prettier-bytes/prettierBytes.js", "../../../node_modules/compressorjs/dist/compressor.common.js", "../../../node_modules/@uppy/compressor/lib/locale.js", "../../../node_modules/@uppy/compressor/lib/index.js", "../../../node_modules/get-form-data/lib/index.js", "../../../node_modules/@uppy/form/lib/index.js", "../../../node_modules/@uppy/golden-retriever/lib/ServiceWorkerStore.js", "../../../node_modules/@uppy/golden-retriever/lib/IndexedDBStore.js", "../../../node_modules/@uppy/golden-retriever/lib/MetaDataStore.js", "../../../node_modules/@uppy/golden-retriever/lib/index.js", "../../../node_modules/@uppy/redux-dev-tools/lib/index.js", "../../../node_modules/@uppy/locales/lib/fr_FR.js", "../../../node_modules/leaflet/src/core/Util.js", "../../../node_modules/leaflet/src/core/Class.js", "../../../node_modules/leaflet/src/core/Events.js", "../../../node_modules/leaflet/src/geometry/Point.js", "../../../node_modules/leaflet/src/geometry/Bounds.js", "../../../node_modules/leaflet/src/geo/LatLngBounds.js", "../../../node_modules/leaflet/src/geo/LatLng.js", "../../../node_modules/leaflet/src/geo/crs/CRS.js", "../../../node_modules/leaflet/src/geo/crs/CRS.Earth.js", "../../../node_modules/leaflet/src/geo/projection/Projection.SphericalMercator.js", "../../../node_modules/leaflet/src/geometry/Transformation.js", "../../../node_modules/leaflet/src/geo/crs/CRS.EPSG3857.js", "../../../node_modules/leaflet/src/layer/vector/SVG.Util.js", "../../../node_modules/leaflet/src/core/Browser.js", "../../../node_modules/leaflet/src/dom/DomEvent.Pointer.js", "../../../node_modules/leaflet/src/dom/DomEvent.DoubleTap.js", "../../../node_modules/leaflet/src/dom/DomUtil.js", "../../../node_modules/leaflet/src/dom/DomEvent.js", "../../../node_modules/leaflet/src/dom/PosAnimation.js", "../../../node_modules/leaflet/src/map/Map.js", "../../../node_modules/leaflet/src/control/Control.js", "../../../node_modules/leaflet/src/control/Control.Layers.js", "../../../node_modules/leaflet/src/control/Control.Zoom.js", "../../../node_modules/leaflet/src/control/Control.Scale.js", "../../../node_modules/leaflet/src/control/Control.Attribution.js", "../../../node_modules/leaflet/src/control/index.js", "../../../node_modules/leaflet/src/core/Handler.js", "../../../node_modules/leaflet/src/core/index.js", "../../../node_modules/leaflet/src/dom/Draggable.js", "../../../node_modules/leaflet/src/geometry/PolyUtil.js", "../../../node_modules/leaflet/src/geometry/LineUtil.js", "../../../node_modules/leaflet/src/geo/projection/Projection.LonLat.js", "../../../node_modules/leaflet/src/geo/projection/Projection.Mercator.js", "../../../node_modules/leaflet/src/geo/projection/index.js", "../../../node_modules/leaflet/src/geo/crs/CRS.EPSG3395.js", "../../../node_modules/leaflet/src/geo/crs/CRS.EPSG4326.js", "../../../node_modules/leaflet/src/geo/crs/CRS.Simple.js", "../../../node_modules/leaflet/src/geo/crs/index.js", "../../../node_modules/leaflet/src/layer/Layer.js", "../../../node_modules/leaflet/src/layer/LayerGroup.js", "../../../node_modules/leaflet/src/layer/FeatureGroup.js", "../../../node_modules/leaflet/src/layer/marker/Icon.js", "../../../node_modules/leaflet/src/layer/marker/Icon.Default.js", "../../../node_modules/leaflet/src/layer/marker/Marker.Drag.js", "../../../node_modules/leaflet/src/layer/marker/Marker.js", "../../../node_modules/leaflet/src/layer/vector/Path.js", "../../../node_modules/leaflet/src/layer/vector/CircleMarker.js", "../../../node_modules/leaflet/src/layer/vector/Circle.js", "../../../node_modules/leaflet/src/layer/vector/Polyline.js", "../../../node_modules/leaflet/src/layer/vector/Polygon.js", "../../../node_modules/leaflet/src/layer/GeoJSON.js", "../../../node_modules/leaflet/src/layer/ImageOverlay.js", "../../../node_modules/leaflet/src/layer/VideoOverlay.js", "../../../node_modules/leaflet/src/layer/SVGOverlay.js", "../../../node_modules/leaflet/src/layer/DivOverlay.js", "../../../node_modules/leaflet/src/layer/Popup.js", "../../../node_modules/leaflet/src/layer/Tooltip.js", "../../../node_modules/leaflet/src/layer/marker/DivIcon.js", "../../../node_modules/leaflet/src/layer/marker/index.js", "../../../node_modules/leaflet/src/layer/tile/GridLayer.js", "../../../node_modules/leaflet/src/layer/tile/TileLayer.js", "../../../node_modules/leaflet/src/layer/tile/TileLayer.WMS.js", "../../../node_modules/leaflet/src/layer/tile/index.js", "../../../node_modules/leaflet/src/layer/vector/Renderer.js", "../../../node_modules/leaflet/src/layer/vector/Canvas.js", "../../../node_modules/leaflet/src/layer/vector/SVG.VML.js", "../../../node_modules/leaflet/src/layer/vector/SVG.js", "../../../node_modules/leaflet/src/layer/vector/Renderer.getRenderer.js", "../../../node_modules/leaflet/src/layer/vector/Rectangle.js", "../../../node_modules/leaflet/src/layer/vector/index.js", "../../../node_modules/leaflet/src/layer/index.js", "../../../node_modules/leaflet/src/map/handler/Map.BoxZoom.js", "../../../node_modules/leaflet/src/map/handler/Map.DoubleClickZoom.js", "../../../node_modules/leaflet/src/map/handler/Map.Drag.js", "../../../node_modules/leaflet/src/map/handler/Map.Keyboard.js", "../../../node_modules/leaflet/src/map/handler/Map.ScrollWheelZoom.js", "../../../node_modules/leaflet/src/map/handler/Map.TapHold.js", "../../../node_modules/leaflet/src/map/handler/Map.TouchZoom.js", "../../../node_modules/leaflet/src/map/index.js", "../../../node_modules/leaflet-rastercoords/rastercoords.js", "../../../node_modules/ev-emitter/ev-emitter.js", "../../../node_modules/get-size/get-size.js", "../../../node_modules/desandro-matches-selector/matches-selector.js", "../../../node_modules/fizzy-ui-utils/utils.js", "../../../node_modules/flickity/js/cell.js", "../../../node_modules/flickity/js/slide.js", "../../../node_modules/flickity/js/animate.js", "../../../node_modules/flickity/js/flickity.js", "../../../node_modules/unipointer/unipointer.js", "../../../node_modules/unidragger/unidragger.js", "../../../node_modules/flickity/js/drag.js", "../../../node_modules/flickity/js/prev-next-button.js", "../../../node_modules/flickity/js/page-dots.js", "../../../node_modules/flickity/js/player.js", "../../../node_modules/flickity/js/add-remove-cell.js", "../../../node_modules/flickity/js/lazyload.js", "../../../node_modules/flickity/js/index.js", "../../../node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/snakeize.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable_stream_source_element.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/fetch_requests.js", "../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js", "../../../node_modules/@hotwired/stimulus/dist/stimulus.js", "../../javascript/controllers/application.js", "../../../node_modules/fast-blurhash/index.js", "../../javascript/controllers/lightness_controller.js", "../../javascript/controllers/index.js", "../../components/activities/filters_component/filters_component.js", "../../components/admin/brand_component/brand_component.js", "../../components/admin/button_component/button_component.js", "../../components/admin/button_group_component/button_group_component.js", "../../components/admin/dashboard/section_component/section_component.js", "../../components/admin/dashboard/tile_component/tile_component.js", "../../components/admin/form/actions_component/actions_component.js", "../../components/admin/form/content_editor_component/content_editor_component.js", "../../../node_modules/orderedmap/dist/index.js", "../../../node_modules/prosemirror-model/dist/index.js", "../../../node_modules/prosemirror-transform/dist/index.js", "../../../node_modules/prosemirror-state/dist/index.js", "../../../node_modules/prosemirror-view/dist/index.js", "../../../node_modules/w3c-keyname/index.js", "../../../node_modules/prosemirror-keymap/dist/index.js", "../../../node_modules/prosemirror-commands/dist/index.js", "../../../node_modules/prosemirror-schema-list/dist/index.js", "../../../node_modules/@tiptap/core/src/helpers/createChainableState.ts", "../../../node_modules/@tiptap/core/src/CommandManager.ts", "../../../node_modules/@tiptap/core/src/EventEmitter.ts", "../../../node_modules/@tiptap/core/src/helpers/getExtensionField.ts", "../../../node_modules/@tiptap/core/src/helpers/splitExtensions.ts", "../../../node_modules/@tiptap/core/src/helpers/getAttributesFromExtensions.ts", "../../../node_modules/@tiptap/core/src/helpers/getNodeType.ts", "../../../node_modules/@tiptap/core/src/utilities/mergeAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/getRenderedAttributes.ts", "../../../node_modules/@tiptap/core/src/utilities/isFunction.ts", "../../../node_modules/@tiptap/core/src/utilities/callOrReturn.ts", "../../../node_modules/@tiptap/core/src/utilities/isEmptyObject.ts", "../../../node_modules/@tiptap/core/src/utilities/fromString.ts", "../../../node_modules/@tiptap/core/src/helpers/injectExtensionAttributesToParseRule.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchemaByResolvedExtensions.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchemaTypeByName.ts", "../../../node_modules/@tiptap/core/src/helpers/isExtensionRulesEnabled.ts", "../../../node_modules/@tiptap/core/src/helpers/getHTMLFromFragment.ts", "../../../node_modules/@tiptap/core/src/helpers/getTextContentFromNodes.ts", "../../../node_modules/@tiptap/core/src/utilities/isRegExp.ts", "../../../node_modules/@tiptap/core/src/InputRule.ts", "../../../node_modules/@tiptap/core/src/utilities/isPlainObject.ts", "../../../node_modules/@tiptap/core/src/utilities/mergeDeep.ts", "../../../node_modules/@tiptap/core/src/Mark.ts", "../../../node_modules/@tiptap/core/src/utilities/isNumber.ts", "../../../node_modules/@tiptap/core/src/PasteRule.ts", "../../../node_modules/@tiptap/core/src/utilities/findDuplicates.ts", "../../../node_modules/@tiptap/core/src/ExtensionManager.ts", "../../../node_modules/@tiptap/core/src/Extension.ts", "../../../node_modules/@tiptap/core/src/helpers/getTextBetween.ts", "../../../node_modules/@tiptap/core/src/helpers/getTextSerializersFromSchema.ts", "../../../node_modules/@tiptap/core/src/extensions/clipboardTextSerializer.ts", "../../../node_modules/@tiptap/core/src/commands/blur.ts", "../../../node_modules/@tiptap/core/src/commands/clearContent.ts", "../../../node_modules/@tiptap/core/src/commands/clearNodes.ts", "../../../node_modules/@tiptap/core/src/commands/command.ts", "../../../node_modules/@tiptap/core/src/commands/createParagraphNear.ts", "../../../node_modules/@tiptap/core/src/commands/cut.ts", "../../../node_modules/@tiptap/core/src/commands/deleteCurrentNode.ts", "../../../node_modules/@tiptap/core/src/commands/deleteNode.ts", "../../../node_modules/@tiptap/core/src/commands/deleteRange.ts", "../../../node_modules/@tiptap/core/src/commands/deleteSelection.ts", "../../../node_modules/@tiptap/core/src/commands/enter.ts", "../../../node_modules/@tiptap/core/src/commands/exitCode.ts", "../../../node_modules/@tiptap/core/src/utilities/objectIncludes.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarkRange.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarkType.ts", "../../../node_modules/@tiptap/core/src/commands/extendMarkRange.ts", "../../../node_modules/@tiptap/core/src/commands/first.ts", "../../../node_modules/@tiptap/core/src/helpers/isTextSelection.ts", "../../../node_modules/@tiptap/core/src/utilities/minMax.ts", "../../../node_modules/@tiptap/core/src/helpers/resolveFocusPosition.ts", "../../../node_modules/@tiptap/core/src/utilities/isAndroid.ts", "../../../node_modules/@tiptap/core/src/utilities/isiOS.ts", "../../../node_modules/@tiptap/core/src/utilities/isSafari.ts", "../../../node_modules/@tiptap/core/src/commands/focus.ts", "../../../node_modules/@tiptap/core/src/commands/forEach.ts", "../../../node_modules/@tiptap/core/src/commands/insertContent.ts", "../../../node_modules/@tiptap/core/src/utilities/elementFromString.ts", "../../../node_modules/@tiptap/core/src/helpers/createNodeFromContent.ts", "../../../node_modules/@tiptap/core/src/helpers/selectionToInsertionEnd.ts", "../../../node_modules/@tiptap/core/src/commands/insertContentAt.ts", "../../../node_modules/@tiptap/core/src/commands/join.ts", "../../../node_modules/@tiptap/core/src/commands/joinItemBackward.ts", "../../../node_modules/@tiptap/core/src/commands/joinItemForward.ts", "../../../node_modules/@tiptap/core/src/commands/joinTextblockBackward.ts", "../../../node_modules/@tiptap/core/src/commands/joinTextblockForward.ts", "../../../node_modules/@tiptap/core/src/utilities/isMacOS.ts", "../../../node_modules/@tiptap/core/src/commands/keyboardShortcut.ts", "../../../node_modules/@tiptap/core/src/helpers/isNodeActive.ts", "../../../node_modules/@tiptap/core/src/commands/lift.ts", "../../../node_modules/@tiptap/core/src/commands/liftEmptyBlock.ts", "../../../node_modules/@tiptap/core/src/commands/liftListItem.ts", "../../../node_modules/@tiptap/core/src/commands/newlineInCode.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchemaTypeNameByName.ts", "../../../node_modules/@tiptap/core/src/utilities/deleteProps.ts", "../../../node_modules/@tiptap/core/src/commands/resetAttributes.ts", "../../../node_modules/@tiptap/core/src/commands/scrollIntoView.ts", "../../../node_modules/@tiptap/core/src/commands/selectAll.ts", "../../../node_modules/@tiptap/core/src/commands/selectNodeBackward.ts", "../../../node_modules/@tiptap/core/src/commands/selectNodeForward.ts", "../../../node_modules/@tiptap/core/src/commands/selectParentNode.ts", "../../../node_modules/@tiptap/core/src/commands/selectTextblockEnd.ts", "../../../node_modules/@tiptap/core/src/commands/selectTextblockStart.ts", "../../../node_modules/@tiptap/core/src/helpers/createDocument.ts", "../../../node_modules/@tiptap/core/src/commands/setContent.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarkAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/combineTransactionSteps.ts", "../../../node_modules/@tiptap/core/src/helpers/defaultBlockAt.ts", "../../../node_modules/@tiptap/core/src/helpers/findChildren.ts", "../../../node_modules/@tiptap/core/src/helpers/findChildrenInRange.ts", "../../../node_modules/@tiptap/core/src/helpers/findParentNodeClosestToPos.ts", "../../../node_modules/@tiptap/core/src/helpers/findParentNode.ts", "../../../node_modules/@tiptap/core/src/helpers/getSchema.ts", "../../../node_modules/@tiptap/core/src/helpers/generateHTML.ts", "../../../node_modules/@tiptap/core/src/helpers/generateJSON.ts", "../../../node_modules/@tiptap/core/src/helpers/getText.ts", "../../../node_modules/@tiptap/core/src/helpers/generateText.ts", "../../../node_modules/@tiptap/core/src/helpers/getNodeAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/getAttributes.ts", "../../../node_modules/@tiptap/core/src/utilities/removeDuplicates.ts", "../../../node_modules/@tiptap/core/src/helpers/getChangedRanges.ts", "../../../node_modules/@tiptap/core/src/helpers/getDebugJSON.ts", "../../../node_modules/@tiptap/core/src/helpers/getMarksBetween.ts", "../../../node_modules/@tiptap/core/src/helpers/getNodeAtPosition.ts", "../../../node_modules/@tiptap/core/src/helpers/getSplittedAttributes.ts", "../../../node_modules/@tiptap/core/src/helpers/isMarkActive.ts", "../../../node_modules/@tiptap/core/src/helpers/isActive.ts", "../../../node_modules/@tiptap/core/src/helpers/isAtEndOfNode.ts", "../../../node_modules/@tiptap/core/src/helpers/isAtStartOfNode.ts", "../../../node_modules/@tiptap/core/src/helpers/isList.ts", "../../../node_modules/@tiptap/core/src/helpers/isNodeEmpty.ts", "../../../node_modules/@tiptap/core/src/helpers/isNodeSelection.ts", "../../../node_modules/@tiptap/core/src/helpers/posToDOMRect.ts", "../../../node_modules/@tiptap/core/src/helpers/rewriteUnknownContent.ts", "../../../node_modules/@tiptap/core/src/commands/setMark.ts", "../../../node_modules/@tiptap/core/src/commands/setMeta.ts", "../../../node_modules/@tiptap/core/src/commands/setNode.ts", "../../../node_modules/@tiptap/core/src/commands/setNodeSelection.ts", "../../../node_modules/@tiptap/core/src/commands/setTextSelection.ts", "../../../node_modules/@tiptap/core/src/commands/sinkListItem.ts", "../../../node_modules/@tiptap/core/src/commands/splitBlock.ts", "../../../node_modules/@tiptap/core/src/commands/splitListItem.ts", "../../../node_modules/@tiptap/core/src/commands/toggleList.ts", "../../../node_modules/@tiptap/core/src/commands/toggleMark.ts", "../../../node_modules/@tiptap/core/src/commands/toggleNode.ts", "../../../node_modules/@tiptap/core/src/commands/toggleWrap.ts", "../../../node_modules/@tiptap/core/src/commands/undoInputRule.ts", "../../../node_modules/@tiptap/core/src/commands/unsetAllMarks.ts", "../../../node_modules/@tiptap/core/src/commands/unsetMark.ts", "../../../node_modules/@tiptap/core/src/commands/updateAttributes.ts", "../../../node_modules/@tiptap/core/src/commands/wrapIn.ts", "../../../node_modules/@tiptap/core/src/commands/wrapInList.ts", "../../../node_modules/@tiptap/core/src/extensions/commands.ts", "../../../node_modules/@tiptap/core/src/extensions/drop.ts", "../../../node_modules/@tiptap/core/src/extensions/editable.ts", "../../../node_modules/@tiptap/core/src/extensions/focusEvents.ts", "../../../node_modules/@tiptap/core/src/extensions/keymap.ts", "../../../node_modules/@tiptap/core/src/extensions/paste.ts", "../../../node_modules/@tiptap/core/src/extensions/tabindex.ts", "../../../node_modules/@tiptap/core/src/NodePos.ts", "../../../node_modules/@tiptap/core/src/style.ts", "../../../node_modules/@tiptap/core/src/utilities/createStyleTag.ts", "../../../node_modules/@tiptap/core/src/Editor.ts", "../../../node_modules/@tiptap/core/src/inputRules/markInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/nodeInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/textblockTypeInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/textInputRule.ts", "../../../node_modules/@tiptap/core/src/inputRules/wrappingInputRule.ts", "../../../node_modules/@tiptap/core/src/Node.ts", "../../../node_modules/@tiptap/core/src/NodeView.ts", "../../../node_modules/@tiptap/core/src/pasteRules/markPasteRule.ts", "../../../node_modules/@tiptap/core/src/utilities/canInsertNode.ts", "../../../node_modules/@tiptap/core/src/utilities/escapeForRegEx.ts", "../../../node_modules/@tiptap/core/src/utilities/isString.ts", "../../../node_modules/@tiptap/core/src/pasteRules/nodePasteRule.ts", "../../../node_modules/@tiptap/core/src/pasteRules/textPasteRule.ts", "../../../node_modules/@tiptap/core/src/Tracker.ts", "../../../node_modules/@popperjs/core/lib/enums.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getWindow.js", "../../../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js", "../../../node_modules/@popperjs/core/lib/modifiers/applyStyles.js", "../../../node_modules/@popperjs/core/lib/utils/getBasePlacement.js", "../../../node_modules/@popperjs/core/lib/utils/math.js", "../../../node_modules/@popperjs/core/lib/utils/userAgent.js", "../../../node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/contains.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js", "../../../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js", "../../../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js", "../../../node_modules/@popperjs/core/lib/utils/within.js", "../../../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js", "../../../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js", "../../../node_modules/@popperjs/core/lib/utils/expandToHashMap.js", "../../../node_modules/@popperjs/core/lib/modifiers/arrow.js", "../../../node_modules/@popperjs/core/lib/utils/getVariation.js", "../../../node_modules/@popperjs/core/lib/modifiers/computeStyles.js", "../../../node_modules/@popperjs/core/lib/modifiers/eventListeners.js", "../../../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js", "../../../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js", "../../../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js", "../../../node_modules/@popperjs/core/lib/utils/rectToClientRect.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js", "../../../node_modules/@popperjs/core/lib/utils/computeOffsets.js", "../../../node_modules/@popperjs/core/lib/utils/detectOverflow.js", "../../../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js", "../../../node_modules/@popperjs/core/lib/modifiers/flip.js", "../../../node_modules/@popperjs/core/lib/modifiers/hide.js", "../../../node_modules/@popperjs/core/lib/modifiers/offset.js", "../../../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js", "../../../node_modules/@popperjs/core/lib/utils/getAltAxis.js", "../../../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js", "../../../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js", "../../../node_modules/@popperjs/core/lib/utils/orderModifiers.js", "../../../node_modules/@popperjs/core/lib/utils/debounce.js", "../../../node_modules/@popperjs/core/lib/utils/mergeByName.js", "../../../node_modules/@popperjs/core/lib/createPopper.js", "../../../node_modules/@popperjs/core/lib/popper.js", "../../../node_modules/tippy.js/src/constants.ts", "../../../node_modules/tippy.js/src/utils.ts", "../../../node_modules/tippy.js/src/dom-utils.ts", "../../../node_modules/tippy.js/src/bindGlobalEventListeners.ts", "../../../node_modules/tippy.js/src/browser.ts", "../../../node_modules/tippy.js/src/validation.ts", "../../../node_modules/tippy.js/src/props.ts", "../../../node_modules/tippy.js/src/template.ts", "../../../node_modules/tippy.js/src/createTippy.ts", "../../../node_modules/tippy.js/src/index.ts", "../../../node_modules/tippy.js/src/addons/createSingleton.ts", "../../../node_modules/tippy.js/src/addons/delegate.ts", "../../../node_modules/tippy.js/src/plugins/animateFill.ts", "../../../node_modules/tippy.js/src/plugins/followCursor.ts", "../../../node_modules/tippy.js/src/plugins/inlinePositioning.ts", "../../../node_modules/tippy.js/src/plugins/sticky.ts", "../../../node_modules/tippy.js/build/base.js", "../../../node_modules/@tiptap/extension-floating-menu/src/floating-menu-plugin.ts", "../../../node_modules/@tiptap/extension-floating-menu/src/floating-menu.ts", "../../../node_modules/linkifyjs/dist/linkify.mjs", "../../../node_modules/@tiptap/extension-link/src/helpers/whitespace.ts", "../../../node_modules/@tiptap/extension-link/src/helpers/autolink.ts", "../../../node_modules/@tiptap/extension-link/src/helpers/clickHandler.ts", "../../../node_modules/@tiptap/extension-link/src/helpers/pasteHandler.ts", "../../../node_modules/@tiptap/extension-link/src/link.ts", "../../../node_modules/@tiptap/extension-blockquote/src/blockquote.ts", "../../../node_modules/@tiptap/extension-bold/src/bold.ts", "../../../node_modules/@tiptap/extension-bullet-list/src/bullet-list.ts", "../../../node_modules/@tiptap/extension-code/src/code.ts", "../../../node_modules/@tiptap/extension-code-block/src/code-block.ts", "../../../node_modules/@tiptap/extension-document/src/document.ts", "../../../node_modules/prosemirror-dropcursor/dist/index.js", "../../../node_modules/@tiptap/extension-dropcursor/src/dropcursor.ts", "../../../node_modules/prosemirror-gapcursor/dist/index.js", "../../../node_modules/@tiptap/extension-gapcursor/src/gapcursor.ts", "../../../node_modules/@tiptap/extension-hard-break/src/hard-break.ts", "../../../node_modules/@tiptap/extension-heading/src/heading.ts", "../../../node_modules/rope-sequence/dist/index.js", "../../../node_modules/prosemirror-history/dist/index.js", "../../../node_modules/@tiptap/extension-history/src/history.ts", "../../../node_modules/@tiptap/extension-horizontal-rule/src/horizontal-rule.ts", "../../../node_modules/@tiptap/extension-italic/src/italic.ts", "../../../node_modules/@tiptap/extension-list-item/src/list-item.ts", "../../../node_modules/@tiptap/extension-ordered-list/src/ordered-list.ts", "../../../node_modules/@tiptap/extension-paragraph/src/paragraph.ts", "../../../node_modules/@tiptap/extension-strike/src/strike.ts", "../../../node_modules/@tiptap/extension-text/src/text.ts", "../../../node_modules/@tiptap/starter-kit/src/starter-kit.ts", "../../components/admin/form/content_editor_component/extensions/table_of_contents.js", "../../components/admin/form/content_editor_component/extensions/prompts_block.js", "../../components/admin/form/content_editor_component/extensions/image_block.js", "../../components/admin/form/fieldset_component/fieldset_component.js", "../../components/admin/form/group_component/group_component.js", "../../components/admin/form/grouped_collection_select_component/grouped_collection_select_component.js", "../../../node_modules/tom-select/src/contrib/microevent.ts", "../../../node_modules/tom-select/src/contrib/microplugin.ts", "../../../node_modules/@orchidjs/unicode-variants/lib/regex.ts", "../../../node_modules/@orchidjs/unicode-variants/lib/strings.ts", "../../../node_modules/@orchidjs/unicode-variants/lib/index.ts", "../../../node_modules/@orchidjs/sifter/lib/utils.ts", "../../../node_modules/@orchidjs/sifter/lib/sifter.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/contrib/highlight.ts", "../../../node_modules/tom-select/src/constants.ts", "../../../node_modules/tom-select/src/defaults.ts", "../../../node_modules/tom-select/src/getSettings.ts", "../../../node_modules/tom-select/src/tom-select.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/plugins/change_listener/plugin.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/checkbox_options/plugin.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/clear_button/plugin.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/drag_drop/plugin.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/dropdown_header/plugin.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/caret_position/plugin.ts", "../../../node_modules/tom-select/src/constants.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/dropdown_input/plugin.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/plugins/input_autogrow/plugin.ts", "../../../node_modules/tom-select/src/plugins/no_backspace_delete/plugin.ts", "../../../node_modules/tom-select/src/plugins/no_active_items/plugin.ts", "../../../node_modules/tom-select/src/constants.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/optgroup_columns/plugin.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/remove_button/plugin.ts", "../../../node_modules/tom-select/src/plugins/restore_on_backspace/plugin.ts", "../../../node_modules/tom-select/src/utils.ts", "../../../node_modules/tom-select/src/vanilla.ts", "../../../node_modules/tom-select/src/plugins/virtual_scroll/plugin.ts", "../../../node_modules/tom-select/src/tom-select.complete.ts", "../../components/admin/form/image_field_component/image_field_component.js", "../../../node_modules/uppy/index.mjs", "../../components/admin/form/link_select_component/link_select_component.js", "../../components/admin/form/switch_box_component/switch_box_component.js", "../../components/admin/form/text_field_component/text_field_component.js", "../../components/admin/gate_component/gate_component.js", "../../components/admin/header_component/header_component.js", "../../components/admin/heading_component/heading_component.js", "../../components/admin/layout_component/layout_component.js", "../../../node_modules/hotkeys-js/src/utils.ts", "../../../node_modules/hotkeys-js/src/var.ts", "../../../node_modules/hotkeys-js/src/index.ts", "../../../node_modules/stimulus-use/dist/index.js", "../../components/admin/list/item_component/item_component.js", "../../components/admin/list/tree/item_component/item_component.js", "../../components/admin/list/tree_component/tree_component.js", "../../../node_modules/sortablejs/modular/sortable.esm.js", "../../components/admin/list_component/list_component.js", "../../components/admin/menu_component/menu_component.js", "../../components/admin/sections/activities_grid_component/activities_grid_component.js", "../../components/admin/sections/agenda_component/agenda_component.js", "../../components/admin/sections/features_grid_component/features_grid_component.js", "../../components/admin/sections/hero_component/hero_component.js", "../../components/admin/sections/slate_component/slate_component.js", "../../components/admin/tabs_component/tabs_component.js", "../../components/admin/toaster/toast_component/toast_component.js", "../../components/admin/toaster_component/toaster_component.js", "../../components/article_component/article_component.js", "../../components/blocks/button_component/button_component.js", "../../components/blocks/figure_component/figure_component.js", "../../components/blocks/gallery_component/gallery_component.js", "../../components/blocks/map_component/map_component.js", "../../../node_modules/maplibre-gl/package.json", "../../../node_modules/maplibre-gl/node_modules/@mapbox/point-geometry/index.js", "../../../node_modules/maplibre-gl/node_modules/@mapbox/unitbezier/index.js", "../../../node_modules/maplibre-gl/src/util/offscreen_canvas_supported.ts", "../../../node_modules/maplibre-gl/src/util/offscreen_canvas_distorted.ts", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/common.js", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/mat2.js", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/mat3.js", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/mat4.js", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/vec3.js", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/vec4.js", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/quat.js", "../../../node_modules/maplibre-gl/node_modules/gl-matrix/esm/vec2.js", "../../../node_modules/maplibre-gl/src/data/extent.ts", "../../../node_modules/maplibre-gl/src/source/pixels_to_tile_units.ts", "../../../node_modules/maplibre-gl/src/util/util.ts", "../../../node_modules/maplibre-gl/src/util/abort_error.ts", "../../../node_modules/maplibre-gl/src/util/browser.ts", "../../../node_modules/maplibre-gl/src/util/time_control.ts", "../../../node_modules/maplibre-gl/src/util/dom.ts", "../../../node_modules/maplibre-gl/src/util/config.ts", "../../../node_modules/maplibre-gl/src/source/protocol_crud.ts", "../../../node_modules/maplibre-gl/src/util/ajax.ts", "../../../node_modules/maplibre-gl/src/util/evented.ts", "../../../node_modules/maplibre-gl/src/util/transferable_grid_index.ts", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/reference/v8.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/reference/latest.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/ref_properties.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/deref.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/deep_equal.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/diff.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/error/validation_error.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/color_spaces.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/get_own.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/parse_css_color.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/interpolate-primitives.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/color.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/formatted.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/padding.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/number_array.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/color_array.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/runtime_error.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/variable_anchor_offset_collection.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/resolved_image.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/projection_definition.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/collator.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/values.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/literal.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/evaluation_context.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/stops.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/step.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/node_modules/@mapbox/unitbezier/index.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/interpolate.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/format.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/node_modules/quickselect/index.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/classify_rings.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/assertion.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/coercion.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/let.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/var.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/at.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/in.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/index_of.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/match.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/case.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/slice.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/coalesce.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/comparison.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/collator.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/number_format.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/image.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/length.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/geometry_util.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/within.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/node_modules/tinyqueue/index.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/cheap_ruler.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/distance.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/semiliteral.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/global_state.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/index.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/parsing_error.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/scope.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/parsing_context.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/compound_expression.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/properties.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/extend.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/get_type.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/function/index.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/result.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/index.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/feature_filter/index.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/empty.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_constants.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/unbundle_jsonlint.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_object.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_array.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_number.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_function.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_expression.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_boolean.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_color.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_enum.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_filter.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_property.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_paint_property.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_layout_property.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_layer.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_string.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_raster_dem_source.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_source.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_light.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_sky.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_terrain.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_formatted.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_image.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_padding.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_number_array.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_color_array.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_variable_anchor_offset_collection.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_sprite.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_projection.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_projectiondefinition.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/util/is_object_literal.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_state.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_font_faces.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_glyphs_url.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/validate_style.min.mjs", "../../../node_modules/maplibre-gl/node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/visibility.mjs", "../../../node_modules/maplibre-gl/src/util/web_worker_transfer.ts", "../../../node_modules/maplibre-gl/src/util/throttled_invoker.ts", "../../../node_modules/maplibre-gl/src/util/actor.ts", "../../../node_modules/maplibre-gl/src/util/web_worker.ts", "../../../node_modules/maplibre-gl/src/util/worker_pool.ts", "../../../node_modules/maplibre-gl/src/util/global_worker_pool.ts", "../../../node_modules/maplibre-gl/src/util/global_dispatcher.ts", "../../../node_modules/maplibre-gl/src/util/image_request.ts", "../../../node_modules/maplibre-gl/src/util/request_manager.ts", "../../../node_modules/maplibre-gl/src/ui/events.ts", "../../../node_modules/maplibre-gl/src/style/validate_style.ts", "../../../node_modules/maplibre-gl/src/style/zoom_history.ts", "../../../node_modules/maplibre-gl/src/style/evaluation_parameters.ts", "../../../node_modules/maplibre-gl/src/style/properties.ts", "../../../node_modules/maplibre-gl/src/style/style_layer.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/raster_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/raster_style_layer.ts", "../../../node_modules/maplibre-gl/src/util/struct_array.ts", "../../../node_modules/maplibre-gl/src/data/array_types.g.ts", "../../../node_modules/maplibre-gl/src/data/bucket/circle_attributes.ts", "../../../node_modules/maplibre-gl/src/data/segment.ts", "../../../node_modules/maplibre-gl/src/shaders/encode_attribute.ts", "../../../node_modules/maplibre-gl/src/data/bucket/pattern_attributes.ts", "../../../node_modules/maplibre-gl/src/data/bucket/dash_attributes.ts", "../../../node_modules/maplibre-gl/node_modules/murmurhash-js/murmurhash3_gc.js", "../../../node_modules/maplibre-gl/node_modules/murmurhash-js/murmurhash2_gc.js", "../../../node_modules/maplibre-gl/node_modules/murmurhash-js/index.js", "../../../node_modules/maplibre-gl/src/data/feature_position_map.ts", "../../../node_modules/maplibre-gl/src/webgl/uniform_binding.ts", "../../../node_modules/maplibre-gl/src/data/program_configuration.ts", "../../../node_modules/maplibre-gl/src/data/load_geometry.ts", "../../../node_modules/maplibre-gl/src/data/evaluation_feature.ts", "../../../node_modules/maplibre-gl/src/geo/bounds.ts", "../../../node_modules/maplibre-gl/src/data/extent_bounds.ts", "../../../node_modules/maplibre-gl/src/data/bucket/circle_bucket.ts", "../../../node_modules/maplibre-gl/src/util/intersection_tests.ts", "../../../node_modules/maplibre-gl/src/style/query_utils.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/circle_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/circle_style_layer.ts", "../../../node_modules/maplibre-gl/src/data/bucket/heatmap_bucket.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/heatmap_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/util/image.ts", "../../../node_modules/maplibre-gl/src/util/color_ramp.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/heatmap_style_layer.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/hillshade_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/hillshade_style_layer.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/color_relief_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/webgl/texture.ts", "../../../node_modules/maplibre-gl/src/data/dem_data.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/color_relief_style_layer.ts", "../../../node_modules/maplibre-gl/src/data/bucket/fill_attributes.ts", "../../../node_modules/maplibre-gl/src/data/bucket/pattern_bucket_features.ts", "../../../node_modules/maplibre-gl/node_modules/earcut/src/earcut.js", "../../../node_modules/maplibre-gl/src/render/subdivision_granularity_settings.ts", "../../../node_modules/maplibre-gl/src/render/subdivision.ts", "../../../node_modules/maplibre-gl/src/render/fill_large_mesh_arrays.ts", "../../../node_modules/maplibre-gl/src/data/bucket/fill_bucket.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/fill_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/fill_style_layer.ts", "../../../node_modules/maplibre-gl/src/data/bucket/fill_extrusion_attributes.ts", "../../../node_modules/maplibre-gl/node_modules/@mapbox/vector-tile/index.js", "../../../node_modules/maplibre-gl/src/geo/lng_lat.ts", "../../../node_modules/maplibre-gl/src/geo/projection/tile_matrix_set.ts", "../../../node_modules/maplibre-gl/src/geo/mercator_coordinate.ts", "../../../node_modules/maplibre-gl/src/geo/projection/mercator_utils.ts", "../../../node_modules/maplibre-gl/src/data/bucket/round_polygon_corners.ts", "../../../node_modules/maplibre-gl/src/data/bucket/fill_extrusion_bucket.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/fill_extrusion_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/fill_extrusion_style_layer.ts", "../../../node_modules/maplibre-gl/node_modules/@maplibre/geojson-vt/dist/geojson-vt.mjs", "../../../node_modules/maplibre-gl/src/data/bucket/line_attributes.ts", "../../../node_modules/maplibre-gl/src/data/bucket/line_attributes_ext.ts", "../../../node_modules/maplibre-gl/src/data/bucket/line_bucket.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/line_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/line_style_layer.ts", "../../../node_modules/maplibre-gl/src/data/bucket/symbol_attributes.ts", "../../../node_modules/maplibre-gl/src/source/rtl_text_plugin_worker.ts", "../../../node_modules/maplibre-gl/src/util/unicode_properties.g.ts", "../../../node_modules/maplibre-gl/src/symbol/arabic_shaping.ts", "../../../node_modules/maplibre-gl/src/symbol/transform_text.ts", "../../../node_modules/maplibre-gl/src/symbol/merge_lines.ts", "../../../node_modules/maplibre-gl/src/util/graphemes.ts", "../../../node_modules/maplibre-gl/src/util/script_detection.ts", "../../../node_modules/maplibre-gl/src/util/verticalize_punctuation.ts", "../../../node_modules/maplibre-gl/src/symbol/tagged_string.ts", "../../../node_modules/maplibre-gl/node_modules/bidi-js/dist/bidi.mjs", "../../../node_modules/maplibre-gl/src/symbol/bidi.ts", "../../../node_modules/maplibre-gl/node_modules/pbf/index.js", "../../../node_modules/maplibre-gl/src/style/parse_glyph_pbf.ts", "../../../node_modules/maplibre-gl/src/style/style_image.ts", "../../../node_modules/maplibre-gl/node_modules/potpack/index.js", "../../../node_modules/maplibre-gl/src/render/image_atlas.ts", "../../../node_modules/maplibre-gl/src/symbol/shaping.ts", "../../../node_modules/maplibre-gl/src/symbol/symbol_size.ts", "../../../node_modules/maplibre-gl/src/symbol/anchor.ts", "../../../node_modules/maplibre-gl/src/symbol/check_max_angle.ts", "../../../node_modules/maplibre-gl/src/symbol/get_anchors.ts", "../../../node_modules/maplibre-gl/src/symbol/clip_line.ts", "../../../node_modules/maplibre-gl/src/symbol/quads.ts", "../../../node_modules/maplibre-gl/src/symbol/collision_feature.ts", "../../../node_modules/maplibre-gl/node_modules/tinyqueue/index.js", "../../../node_modules/maplibre-gl/src/util/find_pole_of_inaccessibility.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/variable_text_anchor.ts", "../../../node_modules/maplibre-gl/src/symbol/symbol_layout.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/overlap_mode.ts", "../../../node_modules/maplibre-gl/src/data/bucket/symbol_bucket.ts", "../../../node_modules/maplibre-gl/src/util/resolve_tokens.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/symbol_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/format_section_override.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/symbol_style_layer.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/background_style_layer_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/background_style_layer.ts", "../../../node_modules/maplibre-gl/src/style/style_layer/custom_style_layer.ts", "../../../node_modules/maplibre-gl/src/style/create_style_layer.ts", "../../../node_modules/maplibre-gl/src/util/style.ts", "../../../node_modules/maplibre-gl/src/style/load_sprite.ts", "../../../node_modules/maplibre-gl/src/render/image_manager.ts", "../../../node_modules/maplibre-gl/src/render/pattern_atlas.ts", "../../../node_modules/maplibre-gl/src/render/font_face_manager.ts", "../../../node_modules/maplibre-gl/node_modules/@mapbox/tiny-sdf/index.js", "../../../node_modules/maplibre-gl/src/render/glyph_manager.ts", "../../../node_modules/maplibre-gl/src/style/light_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/light.ts", "../../../node_modules/maplibre-gl/src/style/sky_properties.g.ts", "../../../node_modules/maplibre-gl/src/style/sky.ts", "../../../node_modules/maplibre-gl/src/render/line_atlas.ts", "../../../node_modules/maplibre-gl/src/util/dispatcher.ts", "../../../node_modules/maplibre-gl/src/source/query_features.ts", "../../../node_modules/maplibre-gl/src/source/load_tilejson.ts", "../../../node_modules/maplibre-gl/src/geo/lng_lat_bounds.ts", "../../../node_modules/maplibre-gl/src/tile/tile_bounds.ts", "../../../node_modules/maplibre-gl/src/source/vector_tile_source.ts", "../../../node_modules/maplibre-gl/src/source/raster_tile_source.ts", "../../../node_modules/maplibre-gl/src/util/world_bounds.ts", "../../../node_modules/maplibre-gl/src/tile/tile_id.ts", "../../../node_modules/maplibre-gl/src/source/raster_dem_tile_source.ts", "../../../node_modules/maplibre-gl/src/source/geojson_source_diff.ts", "../../../node_modules/maplibre-gl/src/util/geojson_bounds.ts", "../../../node_modules/maplibre-gl/src/tile/tile_id_to_lng_lat_bounds.ts", "../../../node_modules/maplibre-gl/src/util/update_queue.ts", "../../../node_modules/maplibre-gl/src/geo/projection/crs.ts", "../../../node_modules/maplibre-gl/src/geo/projection/projection_crud.ts", "../../../node_modules/maplibre-gl/src/source/geojson_source.ts", "../../../node_modules/maplibre-gl/src/webgl/program/raster_program.ts", "../../../node_modules/maplibre-gl/src/render/mesh.ts", "../../../node_modules/maplibre-gl/src/data/pos_attributes.ts", "../../../node_modules/maplibre-gl/src/util/create_tile_mesh.ts", "../../../node_modules/maplibre-gl/src/source/image_source.ts", "../../../node_modules/maplibre-gl/src/source/video_source.ts", "../../../node_modules/maplibre-gl/src/source/canvas_source.ts", "../../../node_modules/maplibre-gl/src/source/source.ts", "../../../node_modules/maplibre-gl/src/data/bucket.ts", "../../../node_modules/maplibre-gl/node_modules/@maplibre/vt-pbf/dist/index.es.js", "../../../node_modules/maplibre-gl/src/util/dictionary_coder.ts", "../../../node_modules/maplibre-gl/src/util/vectortile_to_geojson.ts", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/vector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/fixedSizeVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/int32FlatVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/doubleFlatVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/sequence/sequenceVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/sequence/int32SequenceVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/constant/int32ConstVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/featureTable.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tileset/tilesetMetadata.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/intWrapper.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/logicalLevelTechnique.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/physicalLevelTechnique.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/fastPforShared.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/fastPforUnpack.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/fastPforDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/bigEndianDecode.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/integerDecodingUtils.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/physicalStreamType.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/dictionaryType.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/offsetType.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/lengthType.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/streamMetadataDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/vectorType.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/bitVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/unpackNullableUtils.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/decodingUtils.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/integerStreamDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/int64FlatVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/sequence/int64SequenceVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/zOrderCurve.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/geometryType.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/vertexBufferType.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/geometryVectorConverter.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/geometryVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/constGeometryVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/flatGeometryVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/gpuVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/constGpuVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/geometry/flatGpuVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/geometryDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/booleanFlatVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/floatFlatVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/constant/int64ConstVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/variableSizeVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/stringFlatVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/dictionary/stringDictionaryVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/fsstDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/fsst-dictionary/stringFsstDictionaryVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/stringDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/vector/flat/objectFlatVector.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/mapMask.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tile/mapControlValue.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/mapPropertyDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/decoding/propertyDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tileset/typeMap.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/metadata/tileset/embeddedTilesetMetadataDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/mltDecoder.js", "../../../node_modules/maplibre-gl/node_modules/@maplibre/mlt/dist/encoding/fastPforEncoder.js", "../../../node_modules/maplibre-gl/src/source/vector_tile_mlt.ts", "../../../node_modules/maplibre-gl/src/data/feature_index.ts", "../../../node_modules/maplibre-gl/src/source/rtl_text_plugin_status.ts", "../../../node_modules/maplibre-gl/src/source/rtl_text_plugin_main_thread.ts", "../../../node_modules/maplibre-gl/src/tile/tile.ts", "../../../node_modules/maplibre-gl/src/tile/tile_cache.ts", "../../../node_modules/maplibre-gl/src/source/source_state.ts", "../../../node_modules/maplibre-gl/src/util/primitives/aabb.ts", "../../../node_modules/maplibre-gl/src/util/primitives/frustum.ts", "../../../node_modules/maplibre-gl/src/geo/projection/covering_tiles.ts", "../../../node_modules/maplibre-gl/src/tile/tile_manager_raster.ts", "../../../node_modules/maplibre-gl/src/tile/tile_manager_raster_dem.ts", "../../../node_modules/maplibre-gl/src/tile/tile_manager_in_view_tiles.ts", "../../../node_modules/maplibre-gl/src/tile/tile_manager.ts", "../../../node_modules/maplibre-gl/src/symbol/path_interpolator.ts", "../../../node_modules/maplibre-gl/src/symbol/symbol_elevation.ts", "../../../node_modules/maplibre-gl/src/symbol/grid_index.ts", "../../../node_modules/maplibre-gl/src/util/fast_maths.ts", "../../../node_modules/maplibre-gl/src/symbol/projection.ts", "../../../node_modules/maplibre-gl/src/symbol/collision_index.ts", "../../../node_modules/maplibre-gl/src/symbol/placement.ts", "../../../node_modules/maplibre-gl/src/style/pauseable_placement.ts", "../../../node_modules/maplibre-gl/node_modules/kdbush/index.js", "../../../node_modules/maplibre-gl/src/symbol/cross_tile_symbol_index.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/_prelude.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/_prelude.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/background.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/background.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/background_pattern.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/background_pattern.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/circle.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/circle.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/clipping_mask.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/clipping_mask.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/heatmap.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/heatmap.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/heatmap_texture.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/heatmap_texture.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/collision_box.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/collision_box.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/collision_circle.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/collision_circle.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/color_relief.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/color_relief.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/debug.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/debug.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/depth.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_outline.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_outline.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_outline_pattern.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_outline_pattern.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_pattern.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_pattern.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_extrusion.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_extrusion.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_extrusion_pattern.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/fill_extrusion_pattern.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/hillshade_prepare.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/hillshade_prepare.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/hillshade.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/hillshade.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_gradient.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_gradient.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_pattern.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_pattern.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_sdf.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_sdf.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_gradient_sdf.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/line_gradient_sdf.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/layer_opacity.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/layer_opacity.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/raster.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/raster.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/symbol_icon.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/symbol_icon.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/symbol_sdf.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/symbol_sdf.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/symbol_text_and_icon.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/symbol_text_and_icon.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/terrain_depth.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/terrain.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/terrain.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/terrain_depth.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/terrain_height.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/terrain_height.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/_projection_mercator.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/_projection_mercator.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/_projection_globe.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/_projection_globe.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/atmosphere.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/atmosphere.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/sky.fragment.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/glsl/sky.vertex.glsl.g.ts", "../../../node_modules/maplibre-gl/src/shaders/shaders.ts", "../../../node_modules/maplibre-gl/src/geo/projection/mercator_projection.ts", "../../../node_modules/maplibre-gl/src/geo/edge_insets.ts", "../../../node_modules/maplibre-gl/src/geo/camera_state.ts", "../../../node_modules/maplibre-gl/src/geo/transform_helper.ts", "../../../node_modules/maplibre-gl/src/geo/projection/mercator_covering_tiles_details_provider.ts", "../../../node_modules/maplibre-gl/src/render/terrain_coverage.ts", "../../../node_modules/maplibre-gl/src/geo/projection/mercator_transform.ts", "../../../node_modules/maplibre-gl/src/geo/projection/camera_helper.ts", "../../../node_modules/maplibre-gl/src/geo/projection/mercator_camera_helper.ts", "../../../node_modules/maplibre-gl/src/style/projection_properties.g.ts", "../../../node_modules/maplibre-gl/src/geo/projection/vertical_perspective_projection.ts", "../../../node_modules/maplibre-gl/src/geo/projection/globe_projection.ts", "../../../node_modules/maplibre-gl/src/geo/projection/globe_utils.ts", "../../../node_modules/maplibre-gl/src/util/primitives/bounding_volume_cache.ts", "../../../node_modules/maplibre-gl/src/util/primitives/convex_volume.ts", "../../../node_modules/maplibre-gl/src/geo/projection/globe_covering_tiles_details_provider.ts", "../../../node_modules/maplibre-gl/src/geo/projection/vertical_perspective_transform.ts", "../../../node_modules/maplibre-gl/src/geo/projection/globe_transform.ts", "../../../node_modules/maplibre-gl/src/geo/projection/vertical_perspective_camera_helper.ts", "../../../node_modules/maplibre-gl/src/geo/projection/globe_camera_helper.ts", "../../../node_modules/maplibre-gl/src/geo/projection/projection_factory.ts", "../../../node_modules/maplibre-gl/src/style/style.ts", "../../../node_modules/maplibre-gl/src/data/raster_bounds_attributes.ts", "../../../node_modules/maplibre-gl/src/webgl/index_buffer.ts", "../../../node_modules/maplibre-gl/src/webgl/vertex_buffer.ts", "../../../node_modules/maplibre-gl/src/webgl/value.ts", "../../../node_modules/maplibre-gl/src/webgl/framebuffer.ts", "../../../node_modules/maplibre-gl/src/webgl/uniform_buffer.ts", "../../../node_modules/maplibre-gl/src/webgl/projection_uniform_buffer.ts", "../../../node_modules/maplibre-gl/src/webgl/frame_uniform_buffer.ts", "../../../node_modules/maplibre-gl/src/webgl/terrain_uniform_buffer.ts", "../../../node_modules/maplibre-gl/src/webgl/color_mode.ts", "../../../node_modules/maplibre-gl/src/webgl/context.ts", "../../../node_modules/maplibre-gl/src/webgl/vertex_array_object.ts", "../../../node_modules/maplibre-gl/src/webgl/program/terrain_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/pattern.ts", "../../../node_modules/maplibre-gl/src/webgl/program/fill_extrusion_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/fill_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/circle_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/debug_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/heatmap_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/hillshade_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/color_relief_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/line_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/layer_opacity_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/symbol_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/background_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/atmosphere_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/sky_program.ts", "../../../node_modules/maplibre-gl/src/webgl/program/program_uniforms.ts", "../../../node_modules/maplibre-gl/src/webgl/program_cache.ts", "../../../node_modules/maplibre-gl/src/webgl/stencil_mode.ts", "../../../node_modules/maplibre-gl/src/webgl/cull_face_mode.ts", "../../../node_modules/maplibre-gl/src/webgl/depth_mode.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_collision_debug.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_symbol.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_circle.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_heatmap.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_layer_opacity.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_line.ts", "../../../node_modules/maplibre-gl/src/render/update_pattern_positions_in_program.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_fill.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_fill_extrusion.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_hillshade.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_color_relief.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_raster.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_background.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_debug.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_terrain.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_custom.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/draw_sky.ts", "../../../node_modules/maplibre-gl/src/webgl/draw/index.ts", "../../../node_modules/maplibre-gl/src/render/frame_render_context.ts", "../../../node_modules/maplibre-gl/src/render/painter.ts", "../../../node_modules/maplibre-gl/src/util/gpu_initialization_error.ts", "../../../node_modules/maplibre-gl/src/util/throttle.ts", "../../../node_modules/maplibre-gl/src/ui/hash.ts", "../../../node_modules/maplibre-gl/src/ui/handler_inertia.ts", "../../../node_modules/maplibre-gl/src/ui/handler/map_event.ts", "../../../node_modules/maplibre-gl/src/ui/handler/box_zoom.ts", "../../../node_modules/maplibre-gl/src/ui/handler/handler_util.ts", "../../../node_modules/maplibre-gl/src/ui/handler/tap_recognizer.ts", "../../../node_modules/maplibre-gl/src/ui/handler/tap_zoom.ts", "../../../node_modules/maplibre-gl/src/ui/handler/drag_handler.ts", "../../../node_modules/maplibre-gl/src/ui/handler/drag_move_state_manager.ts", "../../../node_modules/maplibre-gl/src/ui/handler/mouse.ts", "../../../node_modules/maplibre-gl/src/ui/handler/touch_pan.ts", "../../../node_modules/maplibre-gl/src/ui/handler/two_fingers_touch.ts", "../../../node_modules/maplibre-gl/src/ui/handler/keyboard.ts", "../../../node_modules/maplibre-gl/src/ui/handler/scroll_zoom.ts", "../../../node_modules/maplibre-gl/src/ui/handler/shim/dblclick_zoom.ts", "../../../node_modules/maplibre-gl/src/ui/handler/click_zoom.ts", "../../../node_modules/maplibre-gl/src/ui/handler/tap_drag_zoom.ts", "../../../node_modules/maplibre-gl/src/ui/handler/shim/drag_pan.ts", "../../../node_modules/maplibre-gl/src/ui/handler/shim/drag_rotate.ts", "../../../node_modules/maplibre-gl/src/ui/handler/shim/two_fingers_touch.ts", "../../../node_modules/maplibre-gl/src/ui/handler/cooperative_gestures.ts", "../../../node_modules/maplibre-gl/src/ui/handler/transform-provider.ts", "../../../node_modules/maplibre-gl/src/ui/handler_manager.ts", "../../../node_modules/maplibre-gl/src/ui/elevation_hold.ts", "../../../node_modules/maplibre-gl/src/ui/camera_movement_scheduler.ts", "../../../node_modules/maplibre-gl/src/ui/camera.ts", "../../../node_modules/maplibre-gl/src/ui/control/attribution_control.ts", "../../../node_modules/maplibre-gl/src/ui/control/logo_control.ts", "../../../node_modules/maplibre-gl/src/util/task_queue.ts", "../../../node_modules/maplibre-gl/src/data/pos3d_attributes.ts", "../../../node_modules/maplibre-gl/src/tile/terrain_tile_manager.ts", "../../../node_modules/maplibre-gl/src/render/terrain.ts", "../../../node_modules/maplibre-gl/src/webgl/rtt_fingerprint.ts", "../../../node_modules/maplibre-gl/src/webgl/render_to_texture.ts", "../../../node_modules/maplibre-gl/src/ui/default_locale.ts", "../../../node_modules/maplibre-gl/src/ui/map.ts", "../../../node_modules/maplibre-gl/src/ui/control/navigation_control.ts", "../../../node_modules/maplibre-gl/src/util/geolocation_support.ts", "../../../node_modules/maplibre-gl/src/util/smart_wrap.ts", "../../../node_modules/maplibre-gl/src/ui/anchor.ts", "../../../node_modules/maplibre-gl/src/ui/marker.ts", "../../../node_modules/maplibre-gl/src/ui/control/geolocate_control.ts", "../../../node_modules/maplibre-gl/src/ui/control/scale_control.ts", "../../../node_modules/maplibre-gl/src/ui/control/fullscreen_control.ts", "../../../node_modules/maplibre-gl/src/ui/control/terrain_control.ts", "../../../node_modules/maplibre-gl/src/ui/control/globe_control.ts", "../../../node_modules/maplibre-gl/src/ui/popup.ts", "../../../node_modules/maplibre-gl/src/index.ts", "../../javascript/lib/maplibre.js", "../../components/blocks/quote_component/quote_component.js", "../../components/blocks/thumbnails_component/thumbnails_component.js", "../../components/breadcrumbs_component/breadcrumbs_component.js", "../../components/bulletin_component/bulletin_component.js", "../../../node_modules/wicg-inert/dist/inert.esm.js", "../../components/button_component/button_component.js", "../../components/card_component/card_component.js", "../../components/details_component/details_component.js", "../../components/footer_component/footer_component.js", "../../components/form/group_component/group_component.js", "../../components/header/menu_component/menu_component.js", "../../components/header_component/header_component.js", "../../components/icon_card_component/icon_card_component.js", "../../components/icon_component/icon_component.js", "../../components/link_component/link_component.js", "../../components/live/activities_component/activities_component.js", "../../components/live/bulletins_component/bulletins_component.js", "../../components/live/heading_component/heading_component.js", "../../components/live/panel_component/panel_component.js", "../../components/live/road_conditions_component/road_conditions_component.js", "../../components/live/snowfield_component/snowfield_component.js", "../../components/live/ticker_component/ticker_component.js", "../../components/live/weather_component/weather_component.js", "../../components/maps/city_component/city_component.js", "../../components/maps/station_component/station_component.js", "../../components/mda/details_component/details_component.js", "../../components/mda/forms/contact_component/contact_component.js", "../../components/mda/nav_component/nav_component.js", "../../components/mda/partners_component/partners_component.js", "../../components/notice_component/notice_component.js", "../../components/partners_component/partners_component.js", "../../components/pill_component/pill_component.js", "../../components/sections/activities_grid_component/activities_grid_component.js", "../../components/sections/agenda_component/agenda_component.js", "../../components/sections/carousel_component/carousel_component.js", "../../components/sections/features_grid_component/features_grid_component.js", "../../components/sections/grid_component/grid_component.js", "../../components/sections/hero_component/hero_component.js", "../../components/sections/lambda_component/lambda_component.js", "../../components/sections/slate_component/slate_component.js", "../../components/slate_component/slate_component.js", "../../components/switcher_component/switcher_component.js", "../../components/thumbnail_component/thumbnail_component.js", "../../components/toc_component/toc_component.js", "rails:/home/lemontdore/lemontdore/app/components/**/*_component.js", "../../components/index.js"],
  "sourcesContent": ["export default {\n  logger: typeof console !== \"undefined\" ? console : undefined,\n  WebSocket: typeof WebSocket !== \"undefined\" ? WebSocket : undefined,\n}\n", "import adapters from \"./adapters\"\n\n// The logger is disabled by default. You can enable it with:\n//\n//   ActionCable.logger.enabled = true\n//\n//   Example:\n//\n//   import * as ActionCable from '@rails/actioncable'\n//\n//   ActionCable.logger.enabled = true\n//   ActionCable.logger.log('Connection Established.')\n//\n\nexport default {\n  log(...messages) {\n    if (this.enabled) {\n      messages.push(Date.now())\n      adapters.logger.log(\"[ActionCable]\", ...messages)\n    }\n  },\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring the cable connection is in good health by validating the heartbeat pings sent from the server, and attempting\n// revival reconnections if things go astray. Internal class, not intended for direct user manipulation.\n\nconst now = () => new Date().getTime()\n\nconst secondsSince = time => (now() - time) / 1000\n\nclass ConnectionMonitor {\n  constructor(connection) {\n    this.visibilityDidChange = this.visibilityDidChange.bind(this)\n    this.connection = connection\n    this.reconnectAttempts = 0\n  }\n\n  start() {\n    if (!this.isRunning()) {\n      this.startedAt = now()\n      delete this.stoppedAt\n      this.startPolling()\n      addEventListener(\"visibilitychange\", this.visibilityDidChange)\n      logger.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`)\n    }\n  }\n\n  stop() {\n    if (this.isRunning()) {\n      this.stoppedAt = now()\n      this.stopPolling()\n      removeEventListener(\"visibilitychange\", this.visibilityDidChange)\n      logger.log(\"ConnectionMonitor stopped\")\n    }\n  }\n\n  isRunning() {\n    return this.startedAt && !this.stoppedAt\n  }\n\n  recordMessage() {\n    this.pingedAt = now()\n  }\n\n  recordConnect() {\n    this.reconnectAttempts = 0\n    delete this.disconnectedAt\n    logger.log(\"ConnectionMonitor recorded connect\")\n  }\n\n  recordDisconnect() {\n    this.disconnectedAt = now()\n    logger.log(\"ConnectionMonitor recorded disconnect\")\n  }\n\n  // Private\n\n  startPolling() {\n    this.stopPolling()\n    this.poll()\n  }\n\n  stopPolling() {\n    clearTimeout(this.pollTimeout)\n  }\n\n  poll() {\n    this.pollTimeout = setTimeout(() => {\n      this.reconnectIfStale()\n      this.poll()\n    }\n    , this.getPollInterval())\n  }\n\n  getPollInterval() {\n    const { staleThreshold, reconnectionBackoffRate } = this.constructor\n    const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10))\n    const jitterMax = this.reconnectAttempts === 0 ? 1.0 : reconnectionBackoffRate\n    const jitter = jitterMax * Math.random()\n    return staleThreshold * 1000 * backoff * (1 + jitter)\n  }\n\n  reconnectIfStale() {\n    if (this.connectionIsStale()) {\n      logger.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`)\n      this.reconnectAttempts++\n      if (this.disconnectedRecently()) {\n        logger.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`)\n      } else {\n        logger.log(\"ConnectionMonitor reopening\")\n        this.connection.reopen()\n      }\n    }\n  }\n\n  get refreshedAt() {\n    return this.pingedAt ? this.pingedAt : this.startedAt\n  }\n\n  connectionIsStale() {\n    return secondsSince(this.refreshedAt) > this.constructor.staleThreshold\n  }\n\n  disconnectedRecently() {\n    return this.disconnectedAt && (secondsSince(this.disconnectedAt) < this.constructor.staleThreshold)\n  }\n\n  visibilityDidChange() {\n    if (document.visibilityState === \"visible\") {\n      setTimeout(() => {\n        if (this.connectionIsStale() || !this.connection.isOpen()) {\n          logger.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`)\n          this.connection.reopen()\n        }\n      }\n      , 200)\n    }\n  }\n\n}\n\nConnectionMonitor.staleThreshold = 6 // Server::Connections::BEAT_INTERVAL * 2 (missed two pings)\nConnectionMonitor.reconnectionBackoffRate = 0.15\n\nexport default ConnectionMonitor\n", "export default {\n  \"message_types\": {\n    \"welcome\": \"welcome\",\n    \"disconnect\": \"disconnect\",\n    \"ping\": \"ping\",\n    \"confirmation\": \"confirm_subscription\",\n    \"rejection\": \"reject_subscription\"\n  },\n  \"disconnect_reasons\": {\n    \"unauthorized\": \"unauthorized\",\n    \"invalid_request\": \"invalid_request\",\n    \"server_restart\": \"server_restart\",\n    \"remote\": \"remote\"\n  },\n  \"default_mount_path\": \"/cable\",\n  \"protocols\": [\n    \"actioncable-v1-json\",\n    \"actioncable-unsupported\"\n  ]\n}\n", "import adapters from \"./adapters\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport INTERNAL from \"./internal\"\nimport logger from \"./logger\"\n\n// Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.\n\nconst {message_types, protocols} = INTERNAL\nconst supportedProtocols = protocols.slice(0, protocols.length - 1)\n\nconst indexOf = [].indexOf\n\nclass Connection {\n  constructor(consumer) {\n    this.open = this.open.bind(this)\n    this.consumer = consumer\n    this.subscriptions = this.consumer.subscriptions\n    this.monitor = new ConnectionMonitor(this)\n    this.disconnected = true\n  }\n\n  send(data) {\n    if (this.isOpen()) {\n      this.webSocket.send(JSON.stringify(data))\n      return true\n    } else {\n      return false\n    }\n  }\n\n  open() {\n    if (this.isActive()) {\n      logger.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`)\n      return false\n    } else {\n      const socketProtocols = [...protocols, ...this.consumer.subprotocols || []]\n      logger.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${socketProtocols}`)\n      if (this.webSocket) { this.uninstallEventHandlers() }\n      this.webSocket = new adapters.WebSocket(this.consumer.url, socketProtocols)\n      this.installEventHandlers()\n      this.monitor.start()\n      return true\n    }\n  }\n\n  close({allowReconnect} = {allowReconnect: true}) {\n    if (!allowReconnect) { this.monitor.stop() }\n    // Avoid closing websockets in a \"connecting\" state due to Safari 15.1+ bug. See: https://github.com/rails/rails/issues/43835#issuecomment-1002288478\n    if (this.isOpen()) {\n      return this.webSocket.close()\n    }\n  }\n\n  reopen() {\n    logger.log(`Reopening WebSocket, current state is ${this.getState()}`)\n    if (this.isActive()) {\n      try {\n        return this.close()\n      } catch (error) {\n        logger.log(\"Failed to reopen WebSocket\", error)\n      }\n      finally {\n        logger.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`)\n        setTimeout(this.open, this.constructor.reopenDelay)\n      }\n    } else {\n      return this.open()\n    }\n  }\n\n  getProtocol() {\n    if (this.webSocket) {\n      return this.webSocket.protocol\n    }\n  }\n\n  isOpen() {\n    return this.isState(\"open\")\n  }\n\n  isActive() {\n    return this.isState(\"open\", \"connecting\")\n  }\n\n  triedToReconnect() {\n    return this.monitor.reconnectAttempts > 0\n  }\n\n  // Private\n\n  isProtocolSupported() {\n    return indexOf.call(supportedProtocols, this.getProtocol()) >= 0\n  }\n\n  isState(...states) {\n    return indexOf.call(states, this.getState()) >= 0\n  }\n\n  getState() {\n    if (this.webSocket) {\n      for (let state in adapters.WebSocket) {\n        if (adapters.WebSocket[state] === this.webSocket.readyState) {\n          return state.toLowerCase()\n        }\n      }\n    }\n    return null\n  }\n\n  installEventHandlers() {\n    for (let eventName in this.events) {\n      const handler = this.events[eventName].bind(this)\n      this.webSocket[`on${eventName}`] = handler\n    }\n  }\n\n  uninstallEventHandlers() {\n    for (let eventName in this.events) {\n      this.webSocket[`on${eventName}`] = function() {}\n    }\n  }\n\n}\n\nConnection.reopenDelay = 500\n\nConnection.prototype.events = {\n  message(event) {\n    if (!this.isProtocolSupported()) { return }\n    const {identifier, message, reason, reconnect, type} = JSON.parse(event.data)\n    this.monitor.recordMessage()\n    switch (type) {\n      case message_types.welcome:\n        if (this.triedToReconnect()) {\n          this.reconnectAttempted = true\n        }\n        this.monitor.recordConnect()\n        return this.subscriptions.reload()\n      case message_types.disconnect:\n        logger.log(`Disconnecting. Reason: ${reason}`)\n        return this.close({allowReconnect: reconnect})\n      case message_types.ping:\n        return null\n      case message_types.confirmation:\n        this.subscriptions.confirmSubscription(identifier)\n        if (this.reconnectAttempted) {\n          this.reconnectAttempted = false\n          return this.subscriptions.notify(identifier, \"connected\", {reconnected: true})\n        } else {\n          return this.subscriptions.notify(identifier, \"connected\", {reconnected: false})\n        }\n      case message_types.rejection:\n        return this.subscriptions.reject(identifier)\n      default:\n        return this.subscriptions.notify(identifier, \"received\", message)\n    }\n  },\n\n  open() {\n    logger.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`)\n    this.disconnected = false\n    if (!this.isProtocolSupported()) {\n      logger.log(\"Protocol is unsupported. Stopping monitor and disconnecting.\")\n      return this.close({allowReconnect: false})\n    }\n  },\n\n  close(event) {\n    logger.log(\"WebSocket onclose event\")\n    if (this.disconnected) { return }\n    this.disconnected = true\n    this.monitor.recordDisconnect()\n    return this.subscriptions.notifyAll(\"disconnected\", {willAttemptReconnect: this.monitor.isRunning()})\n  },\n\n  error() {\n    logger.log(\"WebSocket onerror event\")\n  }\n}\n\nexport default Connection\n", "// A new subscription is created through the ActionCable.Subscriptions instance available on the consumer.\n// It provides a number of callbacks and a method for calling remote procedure calls on the corresponding\n// Channel instance on the server side.\n//\n// An example demonstrates the basic functionality:\n//\n//   App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\", {\n//     connected() {\n//       // Called once the subscription has been successfully completed\n//     },\n//\n//     disconnected({ willAttemptReconnect: boolean }) {\n//       // Called when the client has disconnected with the server.\n//       // The object will have an `willAttemptReconnect` property which\n//       // says whether the client has the intention of attempting\n//       // to reconnect.\n//     },\n//\n//     appear() {\n//       this.perform('appear', {appearing_on: this.appearingOn()})\n//     },\n//\n//     away() {\n//       this.perform('away')\n//     },\n//\n//     appearingOn() {\n//       $('main').data('appearing-on')\n//     }\n//   })\n//\n// The methods #appear and #away forward their intent to the remote AppearanceChannel instance on the server\n// by calling the `perform` method with the first parameter being the action (which maps to AppearanceChannel#appear/away).\n// The second parameter is a hash that'll get JSON encoded and made available on the server in the data parameter.\n//\n// This is how the server component would look:\n//\n//   class AppearanceChannel < ApplicationActionCable::Channel\n//     def subscribed\n//       current_user.appear\n//     end\n//\n//     def unsubscribed\n//       current_user.disappear\n//     end\n//\n//     def appear(data)\n//       current_user.appear on: data['appearing_on']\n//     end\n//\n//     def away\n//       current_user.away\n//     end\n//   end\n//\n// The \"AppearanceChannel\" name is automatically mapped between the client-side subscription creation and the server-side Ruby class name.\n// The AppearanceChannel#appear/away public methods are exposed automatically to client-side invocation through the perform method.\n\nconst extend = function(object, properties) {\n  if (properties != null) {\n    for (let key in properties) {\n      const value = properties[key]\n      object[key] = value\n    }\n  }\n  return object\n}\n\nexport default class Subscription {\n  constructor(consumer, params = {}, mixin) {\n    this.consumer = consumer\n    this.identifier = JSON.stringify(params)\n    extend(this, mixin)\n  }\n\n  // Perform a channel action with the optional data passed as an attribute\n  perform(action, data = {}) {\n    data.action = action\n    return this.send(data)\n  }\n\n  send(data) {\n    return this.consumer.send({command: \"message\", identifier: this.identifier, data: JSON.stringify(data)})\n  }\n\n  unsubscribe() {\n    return this.consumer.subscriptions.remove(this)\n  }\n}\n", "import logger from \"./logger\"\n\n// Responsible for ensuring channel subscribe command is confirmed, retrying until confirmation is received.\n// Internal class, not intended for direct user manipulation.\n\nclass SubscriptionGuarantor {\n  constructor(subscriptions) {\n    this.subscriptions = subscriptions\n    this.pendingSubscriptions = []\n  }\n\n  guarantee(subscription) {\n    if(this.pendingSubscriptions.indexOf(subscription) == -1){ \n      logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`)\n      this.pendingSubscriptions.push(subscription) \n    }\n    else {\n      logger.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`)\n    }\n    this.startGuaranteeing()\n  }\n\n  forget(subscription) {\n    logger.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`)\n    this.pendingSubscriptions = (this.pendingSubscriptions.filter((s) => s !== subscription))\n  }\n\n  startGuaranteeing() {\n    this.stopGuaranteeing()\n    this.retrySubscribing()\n  }\n  \n  stopGuaranteeing() {\n    clearTimeout(this.retryTimeout)\n  }\n\n  retrySubscribing() {\n    this.retryTimeout = setTimeout(() => {\n      if (this.subscriptions && typeof(this.subscriptions.subscribe) === \"function\") {\n        this.pendingSubscriptions.map((subscription) => {\n          logger.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`)\n          this.subscriptions.subscribe(subscription)\n        })\n      }\n    }\n    , 500)\n  }\n}\n\nexport default SubscriptionGuarantor", "import Subscription from \"./subscription\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\nimport logger from \"./logger\"\n\n// Collection class for creating (and internally managing) channel subscriptions.\n// The only method intended to be triggered by the user is ActionCable.Subscriptions#create,\n// and it should be called through the consumer like so:\n//\n//   App = {}\n//   App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n//   App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n\nexport default class Subscriptions {\n  constructor(consumer) {\n    this.consumer = consumer\n    this.guarantor = new SubscriptionGuarantor(this)\n    this.subscriptions = []\n  }\n\n  create(channelName, mixin) {\n    const channel = channelName\n    const params = typeof channel === \"object\" ? channel : {channel}\n    const subscription = new Subscription(this.consumer, params, mixin)\n    return this.add(subscription)\n  }\n\n  // Private\n\n  add(subscription) {\n    this.subscriptions.push(subscription)\n    this.consumer.ensureActiveConnection()\n    this.notify(subscription, \"initialized\")\n    this.subscribe(subscription)\n    return subscription\n  }\n\n  remove(subscription) {\n    this.forget(subscription)\n    if (!this.findAll(subscription.identifier).length) {\n      this.sendCommand(subscription, \"unsubscribe\")\n    }\n    return subscription\n  }\n\n  reject(identifier) {\n    return this.findAll(identifier).map((subscription) => {\n      this.forget(subscription)\n      this.notify(subscription, \"rejected\")\n      return subscription\n    })\n  }\n\n  forget(subscription) {\n    this.guarantor.forget(subscription)\n    this.subscriptions = (this.subscriptions.filter((s) => s !== subscription))\n    return subscription\n  }\n\n  findAll(identifier) {\n    return this.subscriptions.filter((s) => s.identifier === identifier)\n  }\n\n  reload() {\n    return this.subscriptions.map((subscription) =>\n      this.subscribe(subscription))\n  }\n\n  notifyAll(callbackName, ...args) {\n    return this.subscriptions.map((subscription) =>\n      this.notify(subscription, callbackName, ...args))\n  }\n\n  notify(subscription, callbackName, ...args) {\n    let subscriptions\n    if (typeof subscription === \"string\") {\n      subscriptions = this.findAll(subscription)\n    } else {\n      subscriptions = [subscription]\n    }\n\n    return subscriptions.map((subscription) =>\n      (typeof subscription[callbackName] === \"function\" ? subscription[callbackName](...args) : undefined))\n  }\n\n  subscribe(subscription) {\n    if (this.sendCommand(subscription, \"subscribe\")) {\n      this.guarantor.guarantee(subscription)\n    }\n  }\n\n  confirmSubscription(identifier) {\n    logger.log(`Subscription confirmed ${identifier}`)\n    this.findAll(identifier).map((subscription) =>\n      this.guarantor.forget(subscription))\n  }\n\n  sendCommand(subscription, command) {\n    const {identifier} = subscription\n    return this.consumer.send({command, identifier})\n  }\n}\n", "import Connection from \"./connection\"\nimport Subscriptions from \"./subscriptions\"\n\n// The ActionCable.Consumer establishes the connection to a server-side Ruby Connection object. Once established,\n// the ActionCable.ConnectionMonitor will ensure that its properly maintained through heartbeats and checking for stale updates.\n// The Consumer instance is also the gateway to establishing subscriptions to desired channels through the #createSubscription\n// method.\n//\n// The following example shows how this can be set up:\n//\n//   App = {}\n//   App.cable = ActionCable.createConsumer(\"ws://example.com/accounts/1\")\n//   App.appearance = App.cable.subscriptions.create(\"AppearanceChannel\")\n//\n// For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.\n//\n// When a consumer is created, it automatically connects with the server.\n//\n// To disconnect from the server, call\n//\n//   App.cable.disconnect()\n//\n// and to restart the connection:\n//\n//   App.cable.connect()\n//\n// Any channel subscriptions which existed prior to disconnecting will\n// automatically resubscribe.\n\nexport default class Consumer {\n  constructor(url) {\n    this._url = url\n    this.subscriptions = new Subscriptions(this)\n    this.connection = new Connection(this)\n    this.subprotocols = []\n  }\n\n  get url() {\n    return createWebSocketURL(this._url)\n  }\n\n  send(data) {\n    return this.connection.send(data)\n  }\n\n  connect() {\n    return this.connection.open()\n  }\n\n  disconnect() {\n    return this.connection.close({allowReconnect: false})\n  }\n\n  ensureActiveConnection() {\n    if (!this.connection.isActive()) {\n      return this.connection.open()\n    }\n  }\n\n  addSubProtocol(subprotocol) {\n    this.subprotocols = [...this.subprotocols, subprotocol]\n  }\n}\n\nexport function createWebSocketURL(url) {\n  if (typeof url === \"function\") {\n    url = url()\n  }\n\n  if (url && !/^wss?:/i.test(url)) {\n    const a = document.createElement(\"a\")\n    a.href = url\n    // Fix populating Location properties in IE. Otherwise, protocol will be blank.\n    a.href = a.href\n    a.protocol = a.protocol.replace(\"http\", \"ws\")\n    return a.href\n  } else {\n    return url\n  }\n}\n", "import Connection from \"./connection\"\nimport ConnectionMonitor from \"./connection_monitor\"\nimport Consumer, { createWebSocketURL } from \"./consumer\"\nimport INTERNAL from \"./internal\"\nimport Subscription from \"./subscription\"\nimport Subscriptions from \"./subscriptions\"\nimport SubscriptionGuarantor from \"./subscription_guarantor\"\nimport adapters from \"./adapters\"\nimport logger from \"./logger\"\n\nexport {\n  Connection,\n  ConnectionMonitor,\n  Consumer,\n  INTERNAL,\n  Subscription,\n  Subscriptions,\n  SubscriptionGuarantor,\n  adapters,\n  createWebSocketURL,\n  logger,\n}\n\nexport function createConsumer(url = getConfig(\"url\") || INTERNAL.default_mount_path) {\n  return new Consumer(url)\n}\n\nexport function getConfig(name) {\n  const element = document.head.querySelector(`meta[name='action-cable-${name}']`)\n  if (element) {\n    return element.getAttribute(\"content\")\n  }\n}\n", "\n;(function (name, root, factory) {\n  if (typeof exports === 'object') {\n    module.exports = factory()\n    module.exports['default'] = factory()\n  }\n  /* istanbul ignore next */\n  else if (typeof define === 'function' && define.amd) {\n    define(factory)\n  }\n  else {\n    root[name] = factory()\n  }\n}('slugify', this, function () {\n  var charMap = JSON.parse('{\"$\":\"dollar\",\"%\":\"percent\",\"&\":\"and\",\"<\":\"less\",\">\":\"greater\",\"|\":\"or\",\"\u00A2\":\"cent\",\"\u00A3\":\"pound\",\"\u00A4\":\"currency\",\"\u00A5\":\"yen\",\"\u00A9\":\"(c)\",\"\u00AA\":\"a\",\"\u00AE\":\"(r)\",\"\u00BA\":\"o\",\"\u00C0\":\"A\",\"\u00C1\":\"A\",\"\u00C2\":\"A\",\"\u00C3\":\"A\",\"\u00C4\":\"A\",\"\u00C5\":\"A\",\"\u00C6\":\"AE\",\"\u00C7\":\"C\",\"\u00C8\":\"E\",\"\u00C9\":\"E\",\"\u00CA\":\"E\",\"\u00CB\":\"E\",\"\u00CC\":\"I\",\"\u00CD\":\"I\",\"\u00CE\":\"I\",\"\u00CF\":\"I\",\"\u00D0\":\"D\",\"\u00D1\":\"N\",\"\u00D2\":\"O\",\"\u00D3\":\"O\",\"\u00D4\":\"O\",\"\u00D5\":\"O\",\"\u00D6\":\"O\",\"\u00D8\":\"O\",\"\u00D9\":\"U\",\"\u00DA\":\"U\",\"\u00DB\":\"U\",\"\u00DC\":\"U\",\"\u00DD\":\"Y\",\"\u00DE\":\"TH\",\"\u00DF\":\"ss\",\"\u00E0\":\"a\",\"\u00E1\":\"a\",\"\u00E2\":\"a\",\"\u00E3\":\"a\",\"\u00E4\":\"a\",\"\u00E5\":\"a\",\"\u00E6\":\"ae\",\"\u00E7\":\"c\",\"\u00E8\":\"e\",\"\u00E9\":\"e\",\"\u00EA\":\"e\",\"\u00EB\":\"e\",\"\u00EC\":\"i\",\"\u00ED\":\"i\",\"\u00EE\":\"i\",\"\u00EF\":\"i\",\"\u00F0\":\"d\",\"\u00F1\":\"n\",\"\u00F2\":\"o\",\"\u00F3\":\"o\",\"\u00F4\":\"o\",\"\u00F5\":\"o\",\"\u00F6\":\"o\",\"\u00F8\":\"o\",\"\u00F9\":\"u\",\"\u00FA\":\"u\",\"\u00FB\":\"u\",\"\u00FC\":\"u\",\"\u00FD\":\"y\",\"\u00FE\":\"th\",\"\u00FF\":\"y\",\"\u0100\":\"A\",\"\u0101\":\"a\",\"\u0102\":\"A\",\"\u0103\":\"a\",\"\u0104\":\"A\",\"\u0105\":\"a\",\"\u0106\":\"C\",\"\u0107\":\"c\",\"\u010C\":\"C\",\"\u010D\":\"c\",\"\u010E\":\"D\",\"\u010F\":\"d\",\"\u0110\":\"DJ\",\"\u0111\":\"dj\",\"\u0112\":\"E\",\"\u0113\":\"e\",\"\u0116\":\"E\",\"\u0117\":\"e\",\"\u0118\":\"e\",\"\u0119\":\"e\",\"\u011A\":\"E\",\"\u011B\":\"e\",\"\u011E\":\"G\",\"\u011F\":\"g\",\"\u0122\":\"G\",\"\u0123\":\"g\",\"\u0128\":\"I\",\"\u0129\":\"i\",\"\u012A\":\"i\",\"\u012B\":\"i\",\"\u012E\":\"I\",\"\u012F\":\"i\",\"\u0130\":\"I\",\"\u0131\":\"i\",\"\u0136\":\"k\",\"\u0137\":\"k\",\"\u013B\":\"L\",\"\u013C\":\"l\",\"\u013D\":\"L\",\"\u013E\":\"l\",\"\u0141\":\"L\",\"\u0142\":\"l\",\"\u0143\":\"N\",\"\u0144\":\"n\",\"\u0145\":\"N\",\"\u0146\":\"n\",\"\u0147\":\"N\",\"\u0148\":\"n\",\"\u014C\":\"O\",\"\u014D\":\"o\",\"\u0150\":\"O\",\"\u0151\":\"o\",\"\u0152\":\"OE\",\"\u0153\":\"oe\",\"\u0154\":\"R\",\"\u0155\":\"r\",\"\u0158\":\"R\",\"\u0159\":\"r\",\"\u015A\":\"S\",\"\u015B\":\"s\",\"\u015E\":\"S\",\"\u015F\":\"s\",\"\u0160\":\"S\",\"\u0161\":\"s\",\"\u0162\":\"T\",\"\u0163\":\"t\",\"\u0164\":\"T\",\"\u0165\":\"t\",\"\u0168\":\"U\",\"\u0169\":\"u\",\"\u016A\":\"u\",\"\u016B\":\"u\",\"\u016E\":\"U\",\"\u016F\":\"u\",\"\u0170\":\"U\",\"\u0171\":\"u\",\"\u0172\":\"U\",\"\u0173\":\"u\",\"\u0174\":\"W\",\"\u0175\":\"w\",\"\u0176\":\"Y\",\"\u0177\":\"y\",\"\u0178\":\"Y\",\"\u0179\":\"Z\",\"\u017A\":\"z\",\"\u017B\":\"Z\",\"\u017C\":\"z\",\"\u017D\":\"Z\",\"\u017E\":\"z\",\"\u018F\":\"E\",\"\u0192\":\"f\",\"\u01A0\":\"O\",\"\u01A1\":\"o\",\"\u01AF\":\"U\",\"\u01B0\":\"u\",\"\u01C8\":\"LJ\",\"\u01C9\":\"lj\",\"\u01CB\":\"NJ\",\"\u01CC\":\"nj\",\"\u0218\":\"S\",\"\u0219\":\"s\",\"\u021A\":\"T\",\"\u021B\":\"t\",\"\u0259\":\"e\",\"\u02DA\":\"o\",\"\u0386\":\"A\",\"\u0388\":\"E\",\"\u0389\":\"H\",\"\u038A\":\"I\",\"\u038C\":\"O\",\"\u038E\":\"Y\",\"\u038F\":\"W\",\"\u0390\":\"i\",\"\u0391\":\"A\",\"\u0392\":\"B\",\"\u0393\":\"G\",\"\u0394\":\"D\",\"\u0395\":\"E\",\"\u0396\":\"Z\",\"\u0397\":\"H\",\"\u0398\":\"8\",\"\u0399\":\"I\",\"\u039A\":\"K\",\"\u039B\":\"L\",\"\u039C\":\"M\",\"\u039D\":\"N\",\"\u039E\":\"3\",\"\u039F\":\"O\",\"\u03A0\":\"P\",\"\u03A1\":\"R\",\"\u03A3\":\"S\",\"\u03A4\":\"T\",\"\u03A5\":\"Y\",\"\u03A6\":\"F\",\"\u03A7\":\"X\",\"\u03A8\":\"PS\",\"\u03A9\":\"W\",\"\u03AA\":\"I\",\"\u03AB\":\"Y\",\"\u03AC\":\"a\",\"\u03AD\":\"e\",\"\u03AE\":\"h\",\"\u03AF\":\"i\",\"\u03B0\":\"y\",\"\u03B1\":\"a\",\"\u03B2\":\"b\",\"\u03B3\":\"g\",\"\u03B4\":\"d\",\"\u03B5\":\"e\",\"\u03B6\":\"z\",\"\u03B7\":\"h\",\"\u03B8\":\"8\",\"\u03B9\":\"i\",\"\u03BA\":\"k\",\"\u03BB\":\"l\",\"\u03BC\":\"m\",\"\u03BD\":\"n\",\"\u03BE\":\"3\",\"\u03BF\":\"o\",\"\u03C0\":\"p\",\"\u03C1\":\"r\",\"\u03C2\":\"s\",\"\u03C3\":\"s\",\"\u03C4\":\"t\",\"\u03C5\":\"y\",\"\u03C6\":\"f\",\"\u03C7\":\"x\",\"\u03C8\":\"ps\",\"\u03C9\":\"w\",\"\u03CA\":\"i\",\"\u03CB\":\"y\",\"\u03CC\":\"o\",\"\u03CD\":\"y\",\"\u03CE\":\"w\",\"\u0401\":\"Yo\",\"\u0402\":\"DJ\",\"\u0404\":\"Ye\",\"\u0406\":\"I\",\"\u0407\":\"Yi\",\"\u0408\":\"J\",\"\u0409\":\"LJ\",\"\u040A\":\"NJ\",\"\u040B\":\"C\",\"\u040F\":\"DZ\",\"\u0410\":\"A\",\"\u0411\":\"B\",\"\u0412\":\"V\",\"\u0413\":\"G\",\"\u0414\":\"D\",\"\u0415\":\"E\",\"\u0416\":\"Zh\",\"\u0417\":\"Z\",\"\u0418\":\"I\",\"\u0419\":\"J\",\"\u041A\":\"K\",\"\u041B\":\"L\",\"\u041C\":\"M\",\"\u041D\":\"N\",\"\u041E\":\"O\",\"\u041F\":\"P\",\"\u0420\":\"R\",\"\u0421\":\"S\",\"\u0422\":\"T\",\"\u0423\":\"U\",\"\u0424\":\"F\",\"\u0425\":\"H\",\"\u0426\":\"C\",\"\u0427\":\"Ch\",\"\u0428\":\"Sh\",\"\u0429\":\"Sh\",\"\u042A\":\"U\",\"\u042B\":\"Y\",\"\u042C\":\"\",\"\u042D\":\"E\",\"\u042E\":\"Yu\",\"\u042F\":\"Ya\",\"\u0430\":\"a\",\"\u0431\":\"b\",\"\u0432\":\"v\",\"\u0433\":\"g\",\"\u0434\":\"d\",\"\u0435\":\"e\",\"\u0436\":\"zh\",\"\u0437\":\"z\",\"\u0438\":\"i\",\"\u0439\":\"j\",\"\u043A\":\"k\",\"\u043B\":\"l\",\"\u043C\":\"m\",\"\u043D\":\"n\",\"\u043E\":\"o\",\"\u043F\":\"p\",\"\u0440\":\"r\",\"\u0441\":\"s\",\"\u0442\":\"t\",\"\u0443\":\"u\",\"\u0444\":\"f\",\"\u0445\":\"h\",\"\u0446\":\"c\",\"\u0447\":\"ch\",\"\u0448\":\"sh\",\"\u0449\":\"sh\",\"\u044A\":\"u\",\"\u044B\":\"y\",\"\u044C\":\"\",\"\u044D\":\"e\",\"\u044E\":\"yu\",\"\u044F\":\"ya\",\"\u0451\":\"yo\",\"\u0452\":\"dj\",\"\u0454\":\"ye\",\"\u0456\":\"i\",\"\u0457\":\"yi\",\"\u0458\":\"j\",\"\u0459\":\"lj\",\"\u045A\":\"nj\",\"\u045B\":\"c\",\"\u045D\":\"u\",\"\u045F\":\"dz\",\"\u0490\":\"G\",\"\u0491\":\"g\",\"\u0492\":\"GH\",\"\u0493\":\"gh\",\"\u049A\":\"KH\",\"\u049B\":\"kh\",\"\u04A2\":\"NG\",\"\u04A3\":\"ng\",\"\u04AE\":\"UE\",\"\u04AF\":\"ue\",\"\u04B0\":\"U\",\"\u04B1\":\"u\",\"\u04BA\":\"H\",\"\u04BB\":\"h\",\"\u04D8\":\"AE\",\"\u04D9\":\"ae\",\"\u04E8\":\"OE\",\"\u04E9\":\"oe\",\"\u0531\":\"A\",\"\u0532\":\"B\",\"\u0533\":\"G\",\"\u0534\":\"D\",\"\u0535\":\"E\",\"\u0536\":\"Z\",\"\u0537\":\"E\\'\",\"\u0538\":\"Y\\'\",\"\u0539\":\"T\\'\",\"\u053A\":\"JH\",\"\u053B\":\"I\",\"\u053C\":\"L\",\"\u053D\":\"X\",\"\u053E\":\"C\\'\",\"\u053F\":\"K\",\"\u0540\":\"H\",\"\u0541\":\"D\\'\",\"\u0542\":\"GH\",\"\u0543\":\"TW\",\"\u0544\":\"M\",\"\u0545\":\"Y\",\"\u0546\":\"N\",\"\u0547\":\"SH\",\"\u0549\":\"CH\",\"\u054A\":\"P\",\"\u054B\":\"J\",\"\u054C\":\"R\\'\",\"\u054D\":\"S\",\"\u054E\":\"V\",\"\u054F\":\"T\",\"\u0550\":\"R\",\"\u0551\":\"C\",\"\u0553\":\"P\\'\",\"\u0554\":\"Q\\'\",\"\u0555\":\"O\\'\\'\",\"\u0556\":\"F\",\"\u0587\":\"EV\",\"\u0621\":\"a\",\"\u0622\":\"aa\",\"\u0623\":\"a\",\"\u0624\":\"u\",\"\u0625\":\"i\",\"\u0626\":\"e\",\"\u0627\":\"a\",\"\u0628\":\"b\",\"\u0629\":\"h\",\"\u062A\":\"t\",\"\u062B\":\"th\",\"\u062C\":\"j\",\"\u062D\":\"h\",\"\u062E\":\"kh\",\"\u062F\":\"d\",\"\u0630\":\"th\",\"\u0631\":\"r\",\"\u0632\":\"z\",\"\u0633\":\"s\",\"\u0634\":\"sh\",\"\u0635\":\"s\",\"\u0636\":\"dh\",\"\u0637\":\"t\",\"\u0638\":\"z\",\"\u0639\":\"a\",\"\u063A\":\"gh\",\"\u0641\":\"f\",\"\u0642\":\"q\",\"\u0643\":\"k\",\"\u0644\":\"l\",\"\u0645\":\"m\",\"\u0646\":\"n\",\"\u0647\":\"h\",\"\u0648\":\"w\",\"\u0649\":\"a\",\"\u064A\":\"y\",\"\u064B\":\"an\",\"\u064C\":\"on\",\"\u064D\":\"en\",\"\u064E\":\"a\",\"\u064F\":\"u\",\"\u0650\":\"e\",\"\u0652\":\"\",\"\u0660\":\"0\",\"\u0661\":\"1\",\"\u0662\":\"2\",\"\u0663\":\"3\",\"\u0664\":\"4\",\"\u0665\":\"5\",\"\u0666\":\"6\",\"\u0667\":\"7\",\"\u0668\":\"8\",\"\u0669\":\"9\",\"\u067E\":\"p\",\"\u0686\":\"ch\",\"\u0698\":\"zh\",\"\u06A9\":\"k\",\"\u06AF\":\"g\",\"\u06CC\":\"y\",\"\u06F0\":\"0\",\"\u06F1\":\"1\",\"\u06F2\":\"2\",\"\u06F3\":\"3\",\"\u06F4\":\"4\",\"\u06F5\":\"5\",\"\u06F6\":\"6\",\"\u06F7\":\"7\",\"\u06F8\":\"8\",\"\u06F9\":\"9\",\"\u0E3F\":\"baht\",\"\u10D0\":\"a\",\"\u10D1\":\"b\",\"\u10D2\":\"g\",\"\u10D3\":\"d\",\"\u10D4\":\"e\",\"\u10D5\":\"v\",\"\u10D6\":\"z\",\"\u10D7\":\"t\",\"\u10D8\":\"i\",\"\u10D9\":\"k\",\"\u10DA\":\"l\",\"\u10DB\":\"m\",\"\u10DC\":\"n\",\"\u10DD\":\"o\",\"\u10DE\":\"p\",\"\u10DF\":\"zh\",\"\u10E0\":\"r\",\"\u10E1\":\"s\",\"\u10E2\":\"t\",\"\u10E3\":\"u\",\"\u10E4\":\"f\",\"\u10E5\":\"k\",\"\u10E6\":\"gh\",\"\u10E7\":\"q\",\"\u10E8\":\"sh\",\"\u10E9\":\"ch\",\"\u10EA\":\"ts\",\"\u10EB\":\"dz\",\"\u10EC\":\"ts\",\"\u10ED\":\"ch\",\"\u10EE\":\"kh\",\"\u10EF\":\"j\",\"\u10F0\":\"h\",\"\u1E62\":\"S\",\"\u1E63\":\"s\",\"\u1E80\":\"W\",\"\u1E81\":\"w\",\"\u1E82\":\"W\",\"\u1E83\":\"w\",\"\u1E84\":\"W\",\"\u1E85\":\"w\",\"\u1E9E\":\"SS\",\"\u1EA0\":\"A\",\"\u1EA1\":\"a\",\"\u1EA2\":\"A\",\"\u1EA3\":\"a\",\"\u1EA4\":\"A\",\"\u1EA5\":\"a\",\"\u1EA6\":\"A\",\"\u1EA7\":\"a\",\"\u1EA8\":\"A\",\"\u1EA9\":\"a\",\"\u1EAA\":\"A\",\"\u1EAB\":\"a\",\"\u1EAC\":\"A\",\"\u1EAD\":\"a\",\"\u1EAE\":\"A\",\"\u1EAF\":\"a\",\"\u1EB0\":\"A\",\"\u1EB1\":\"a\",\"\u1EB2\":\"A\",\"\u1EB3\":\"a\",\"\u1EB4\":\"A\",\"\u1EB5\":\"a\",\"\u1EB6\":\"A\",\"\u1EB7\":\"a\",\"\u1EB8\":\"E\",\"\u1EB9\":\"e\",\"\u1EBA\":\"E\",\"\u1EBB\":\"e\",\"\u1EBC\":\"E\",\"\u1EBD\":\"e\",\"\u1EBE\":\"E\",\"\u1EBF\":\"e\",\"\u1EC0\":\"E\",\"\u1EC1\":\"e\",\"\u1EC2\":\"E\",\"\u1EC3\":\"e\",\"\u1EC4\":\"E\",\"\u1EC5\":\"e\",\"\u1EC6\":\"E\",\"\u1EC7\":\"e\",\"\u1EC8\":\"I\",\"\u1EC9\":\"i\",\"\u1ECA\":\"I\",\"\u1ECB\":\"i\",\"\u1ECC\":\"O\",\"\u1ECD\":\"o\",\"\u1ECE\":\"O\",\"\u1ECF\":\"o\",\"\u1ED0\":\"O\",\"\u1ED1\":\"o\",\"\u1ED2\":\"O\",\"\u1ED3\":\"o\",\"\u1ED4\":\"O\",\"\u1ED5\":\"o\",\"\u1ED6\":\"O\",\"\u1ED7\":\"o\",\"\u1ED8\":\"O\",\"\u1ED9\":\"o\",\"\u1EDA\":\"O\",\"\u1EDB\":\"o\",\"\u1EDC\":\"O\",\"\u1EDD\":\"o\",\"\u1EDE\":\"O\",\"\u1EDF\":\"o\",\"\u1EE0\":\"O\",\"\u1EE1\":\"o\",\"\u1EE2\":\"O\",\"\u1EE3\":\"o\",\"\u1EE4\":\"U\",\"\u1EE5\":\"u\",\"\u1EE6\":\"U\",\"\u1EE7\":\"u\",\"\u1EE8\":\"U\",\"\u1EE9\":\"u\",\"\u1EEA\":\"U\",\"\u1EEB\":\"u\",\"\u1EEC\":\"U\",\"\u1EED\":\"u\",\"\u1EEE\":\"U\",\"\u1EEF\":\"u\",\"\u1EF0\":\"U\",\"\u1EF1\":\"u\",\"\u1EF2\":\"Y\",\"\u1EF3\":\"y\",\"\u1EF4\":\"Y\",\"\u1EF5\":\"y\",\"\u1EF6\":\"Y\",\"\u1EF7\":\"y\",\"\u1EF8\":\"Y\",\"\u1EF9\":\"y\",\"\u2013\":\"-\",\"\u2018\":\"\\'\",\"\u2019\":\"\\'\",\"\u201C\":\"\\\\\\\"\",\"\u201D\":\"\\\\\\\"\",\"\u201E\":\"\\\\\\\"\",\"\u2020\":\"+\",\"\u2022\":\"*\",\"\u2026\":\"...\",\"\u20A0\":\"ecu\",\"\u20A2\":\"cruzeiro\",\"\u20A3\":\"french franc\",\"\u20A4\":\"lira\",\"\u20A5\":\"mill\",\"\u20A6\":\"naira\",\"\u20A7\":\"peseta\",\"\u20A8\":\"rupee\",\"\u20A9\":\"won\",\"\u20AA\":\"new shequel\",\"\u20AB\":\"dong\",\"\u20AC\":\"euro\",\"\u20AD\":\"kip\",\"\u20AE\":\"tugrik\",\"\u20AF\":\"drachma\",\"\u20B0\":\"penny\",\"\u20B1\":\"peso\",\"\u20B2\":\"guarani\",\"\u20B3\":\"austral\",\"\u20B4\":\"hryvnia\",\"\u20B5\":\"cedi\",\"\u20B8\":\"kazakhstani tenge\",\"\u20B9\":\"indian rupee\",\"\u20BA\":\"turkish lira\",\"\u20BD\":\"russian ruble\",\"\u20BF\":\"bitcoin\",\"\u2120\":\"sm\",\"\u2122\":\"tm\",\"\u2202\":\"d\",\"\u2206\":\"delta\",\"\u2211\":\"sum\",\"\u221E\":\"infinity\",\"\u2665\":\"love\",\"\u5143\":\"yuan\",\"\u5186\":\"yen\",\"\uFDFC\":\"rial\",\"\uFEF5\":\"laa\",\"\uFEF7\":\"laa\",\"\uFEF9\":\"lai\",\"\uFEFB\":\"la\"}')\n  var locales = JSON.parse('{\"bg\":{\"\u0419\":\"Y\",\"\u0426\":\"Ts\",\"\u0429\":\"Sht\",\"\u042A\":\"A\",\"\u042C\":\"Y\",\"\u0439\":\"y\",\"\u0446\":\"ts\",\"\u0449\":\"sht\",\"\u044A\":\"a\",\"\u044C\":\"y\"},\"de\":{\"\u00C4\":\"AE\",\"\u00E4\":\"ae\",\"\u00D6\":\"OE\",\"\u00F6\":\"oe\",\"\u00DC\":\"UE\",\"\u00FC\":\"ue\",\"\u00DF\":\"ss\",\"%\":\"prozent\",\"&\":\"und\",\"|\":\"oder\",\"\u2211\":\"summe\",\"\u221E\":\"unendlich\",\"\u2665\":\"liebe\"},\"es\":{\"%\":\"por ciento\",\"&\":\"y\",\"<\":\"menor que\",\">\":\"mayor que\",\"|\":\"o\",\"\u00A2\":\"centavos\",\"\u00A3\":\"libras\",\"\u00A4\":\"moneda\",\"\u20A3\":\"francos\",\"\u2211\":\"suma\",\"\u221E\":\"infinito\",\"\u2665\":\"amor\"},\"fr\":{\"%\":\"pourcent\",\"&\":\"et\",\"<\":\"plus petit\",\">\":\"plus grand\",\"|\":\"ou\",\"\u00A2\":\"centime\",\"\u00A3\":\"livre\",\"\u00A4\":\"devise\",\"\u20A3\":\"franc\",\"\u2211\":\"somme\",\"\u221E\":\"infini\",\"\u2665\":\"amour\"},\"pt\":{\"%\":\"porcento\",\"&\":\"e\",\"<\":\"menor\",\">\":\"maior\",\"|\":\"ou\",\"\u00A2\":\"centavo\",\"\u2211\":\"soma\",\"\u00A3\":\"libra\",\"\u221E\":\"infinito\",\"\u2665\":\"amor\"},\"uk\":{\"\u0418\":\"Y\",\"\u0438\":\"y\",\"\u0419\":\"Y\",\"\u0439\":\"y\",\"\u0426\":\"Ts\",\"\u0446\":\"ts\",\"\u0425\":\"Kh\",\"\u0445\":\"kh\",\"\u0429\":\"Shch\",\"\u0449\":\"shch\",\"\u0413\":\"H\",\"\u0433\":\"h\"},\"vi\":{\"\u0110\":\"D\",\"\u0111\":\"d\"},\"da\":{\"\u00D8\":\"OE\",\"\u00F8\":\"oe\",\"\u00C5\":\"AA\",\"\u00E5\":\"aa\",\"%\":\"procent\",\"&\":\"og\",\"|\":\"eller\",\"$\":\"dollar\",\"<\":\"mindre end\",\">\":\"st\u00F8rre end\"},\"nb\":{\"&\":\"og\",\"\u00C5\":\"AA\",\"\u00C6\":\"AE\",\"\u00D8\":\"OE\",\"\u00E5\":\"aa\",\"\u00E6\":\"ae\",\"\u00F8\":\"oe\"},\"it\":{\"&\":\"e\"},\"nl\":{\"&\":\"en\"},\"sv\":{\"&\":\"och\",\"\u00C5\":\"AA\",\"\u00C4\":\"AE\",\"\u00D6\":\"OE\",\"\u00E5\":\"aa\",\"\u00E4\":\"ae\",\"\u00F6\":\"oe\"}}')\n\n  function replace (string, options) {\n    if (typeof string !== 'string') {\n      throw new Error('slugify: string argument expected')\n    }\n\n    options = (typeof options === 'string')\n      ? {replacement: options}\n      : options || {}\n\n    var locale = locales[options.locale] || {}\n\n    var replacement = options.replacement === undefined ? '-' : options.replacement\n\n    var trim = options.trim === undefined ? true : options.trim\n\n    var slug = string.normalize().split('')\n      // replace characters based on charMap\n      .reduce(function (result, ch) {\n        var appendChar = locale[ch];\n        if (appendChar === undefined) appendChar = charMap[ch];\n        if (appendChar === undefined) appendChar = ch;\n        if (appendChar === replacement) appendChar = ' ';\n        return result + appendChar\n          // remove not allowed characters\n          .replace(options.remove || /[^\\w\\s$*_+~.()'\"!\\-:@]+/g, '')\n      }, '');\n\n    if (options.strict) {\n      slug = slug.replace(/[^A-Za-z0-9\\s]/g, '');\n    }\n\n    if (trim) {\n      slug = slug.trim()\n    }\n\n    // Replace spaces with replacement character, treating multiple consecutive\n    // spaces as a single space.\n    slug = slug.replace(/\\s+/g, replacement);\n\n    if (options.lower) {\n      slug = slug.toLowerCase()\n    }\n\n    return slug\n  }\n\n  replace.extend = function (customMap) {\n    Object.assign(charMap, customMap)\n  }\n\n  return replace\n}))\n", "\"use strict\";\n\n/**\n * Adds zero to strings shorter than two characters.\n *\n * @param {number} number\n * @returns {string}\n */\nfunction pad(number) {\n  return number < 10 ? `0${number}` : number.toString();\n}\n/**\n * Returns a timestamp in the format of `hours:minutes:seconds`\n */\n\n\nfunction getTimeStamp() {\n  const date = new Date();\n  const hours = pad(date.getHours());\n  const minutes = pad(date.getMinutes());\n  const seconds = pad(date.getSeconds());\n  return `${hours}:${minutes}:${seconds}`;\n}\n\nmodule.exports = getTimeStamp;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.justErrorsLogger = exports.debugLogger = void 0;\n\n/* eslint-disable no-console */\nconst getTimeStamp = require(\"@uppy/utils/lib/getTimeStamp\"); // Swallow all logs, except errors.\n// default if logger is not set or debug: false\n\n\nconst justErrorsLogger = {\n  debug: () => {},\n  warn: () => {},\n  error: function () {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n\n    return console.error(`[Uppy] [${getTimeStamp()}]`, ...args);\n  }\n}; // Print logs to console with namespace + timestamp,\n// set by logger: Uppy.debugLogger or debug: true\n\nexports.justErrorsLogger = justErrorsLogger;\nconst debugLogger = {\n  debug: function () {\n    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n      args[_key2] = arguments[_key2];\n    }\n\n    return console.debug(`[Uppy] [${getTimeStamp()}]`, ...args);\n  },\n  warn: function () {\n    for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n      args[_key3] = arguments[_key3];\n    }\n\n    return console.warn(`[Uppy] [${getTimeStamp()}]`, ...args);\n  },\n  error: function () {\n    for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n      args[_key4] = arguments[_key4];\n    }\n\n    return console.error(`[Uppy] [${getTimeStamp()}]`, ...args);\n  }\n};\nexports.debugLogger = debugLogger;", "let urlAlphabet =\n  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'\n\nlet customAlphabet = (alphabet, defaultSize = 21) => {\n  return (size = defaultSize) => {\n    let id = ''\n    let i = size | 0\n    while (i-- > 0) {\n      id += alphabet[(Math.random() * alphabet.length) | 0]\n    }\n    return id\n  }\n}\n\nlet nanoid = (size = 21) => {\n  let id = ''\n  let i = size | 0\n  while (i-- > 0) {\n    id += urlAlphabet[(Math.random() * 64) | 0]\n  }\n  return id\n}\n\nmodule.exports = { nanoid, customAlphabet }\n", "// Adapted from https://github.com/Flet/prettier-bytes/\n// Changing 1000 bytes to 1024, so we can keep uppercase KB vs kB\n// ISC License (c) Dan Flettre https://github.com/Flet/prettier-bytes/blob/master/LICENSE\nmodule.exports = function prettierBytes (num) {\n  if (typeof num !== 'number' || isNaN(num)) {\n    throw new TypeError('Expected a number, got ' + typeof num)\n  }\n\n  var neg = num < 0\n  var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n  if (neg) {\n    num = -num\n  }\n\n  if (num < 1) {\n    return (neg ? '-' : '') + num + ' B'\n  }\n\n  var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1024)), units.length - 1)\n  num = Number(num / Math.pow(1024, exponent))\n  var unit = units[exponent]\n\n  if (num >= 10 || num % 1 === 0) {\n    // Do not show decimals when the number is two-digit, or if the number has no\n    // decimal component.\n    return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit\n  } else {\n    return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit\n  }\n}\n", "/* jshint node: true */\n'use strict';\n\n/**\n  # wildcard\n\n  Very simple wildcard matching, which is designed to provide the same\n  functionality that is found in the\n  [eve](https://github.com/adobe-webplatform/eve) eventing library.\n\n  ## Usage\n\n  It works with strings:\n\n  <<< examples/strings.js\n\n  Arrays:\n\n  <<< examples/arrays.js\n\n  Objects (matching against keys):\n\n  <<< examples/objects.js\n\n  While the library works in Node, if you are are looking for file-based\n  wildcard matching then you should have a look at:\n\n  <https://github.com/isaacs/node-glob>\n**/\n\nfunction WildcardMatcher(text, separator) {\n  this.text = text = text || '';\n  this.hasWild = ~text.indexOf('*');\n  this.separator = separator;\n  this.parts = text.split(separator);\n}\n\nWildcardMatcher.prototype.match = function(input) {\n  var matches = true;\n  var parts = this.parts;\n  var ii;\n  var partsCount = parts.length;\n  var testParts;\n\n  if (typeof input == 'string' || input instanceof String) {\n    if (!this.hasWild && this.text != input) {\n      matches = false;\n    } else {\n      testParts = (input || '').split(this.separator);\n      for (ii = 0; matches && ii < partsCount; ii++) {\n        if (parts[ii] === '*')  {\n          continue;\n        } else if (ii < testParts.length) {\n          matches = parts[ii] === testParts[ii];\n        } else {\n          matches = false;\n        }\n      }\n\n      // If matches, then return the component parts\n      matches = matches && testParts;\n    }\n  }\n  else if (typeof input.splice == 'function') {\n    matches = [];\n\n    for (ii = input.length; ii--; ) {\n      if (this.match(input[ii])) {\n        matches[matches.length] = input[ii];\n      }\n    }\n  }\n  else if (typeof input == 'object') {\n    matches = {};\n\n    for (var key in input) {\n      if (this.match(key)) {\n        matches[key] = input[key];\n      }\n    }\n  }\n\n  return matches;\n};\n\nmodule.exports = function(text, test, separator) {\n  var matcher = new WildcardMatcher(text, separator || /[\\/\\.]/);\n  if (typeof test != 'undefined') {\n    return matcher.match(test);\n  }\n\n  return matcher;\n};\n", "var wildcard = require('wildcard');\nvar reMimePartSplit = /[\\/\\+\\.]/;\n\n/**\n  # mime-match\n\n  A simple function to checker whether a target mime type matches a mime-type\n  pattern (e.g. image/jpeg matches image/jpeg OR image/*).\n\n  ## Example Usage\n\n  <<< example.js\n\n**/\nmodule.exports = function(target, pattern) {\n  function test(pattern) {\n    var result = wildcard(pattern, target, reMimePartSplit);\n\n    // ensure that we have a valid mime type (should have two parts)\n    return result && result.length >= 2;\n  }\n\n  return pattern ? test(pattern.split(';')[0]) : test;\n};\n", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.defaultOptions = exports.RestrictionError = exports.Restricter = void 0;\n\n/* eslint-disable max-classes-per-file, class-methods-use-this */\n\n/* global AggregateError */\nconst prettierBytes = require(\"@transloadit/prettier-bytes\");\n\nconst match = require(\"mime-match\");\n\nconst defaultOptions = {\n  maxFileSize: null,\n  minFileSize: null,\n  maxTotalFileSize: null,\n  maxNumberOfFiles: null,\n  minNumberOfFiles: null,\n  allowedFileTypes: null,\n  requiredMetaFields: []\n};\nexports.defaultOptions = defaultOptions;\n\nclass RestrictionError extends Error {\n  constructor() {\n    super(...arguments);\n    this.isRestriction = true;\n  }\n\n}\n\nexports.RestrictionError = RestrictionError;\n\nif (typeof AggregateError === 'undefined') {\n  // eslint-disable-next-line no-global-assign\n  // TODO: remove this \"polyfill\" in the next major.\n  globalThis.AggregateError = class AggregateError extends Error {\n    constructor(errors, message) {\n      super(message);\n      this.errors = errors;\n    }\n\n  };\n}\n\nclass Restricter {\n  constructor(getOpts, i18n) {\n    this.i18n = i18n;\n\n    this.getOpts = () => {\n      const opts = getOpts();\n\n      if (opts.restrictions.allowedFileTypes != null && !Array.isArray(opts.restrictions.allowedFileTypes)) {\n        throw new TypeError('`restrictions.allowedFileTypes` must be an array');\n      }\n\n      return opts;\n    };\n  }\n\n  validate(file, files) {\n    const {\n      maxFileSize,\n      minFileSize,\n      maxTotalFileSize,\n      maxNumberOfFiles,\n      allowedFileTypes\n    } = this.getOpts().restrictions;\n\n    if (maxNumberOfFiles) {\n      const nonGhostFiles = files.filter(f => !f.isGhost);\n\n      if (nonGhostFiles.length + 1 > maxNumberOfFiles) {\n        throw new RestrictionError(`${this.i18n('youCanOnlyUploadX', {\n          smart_count: maxNumberOfFiles\n        })}`);\n      }\n    }\n\n    if (allowedFileTypes) {\n      const isCorrectFileType = allowedFileTypes.some(type => {\n        // check if this is a mime-type\n        if (type.includes('/')) {\n          if (!file.type) return false;\n          return match(file.type.replace(/;.*?$/, ''), type);\n        } // otherwise this is likely an extension\n\n\n        if (type[0] === '.' && file.extension) {\n          return file.extension.toLowerCase() === type.slice(1).toLowerCase();\n        }\n\n        return false;\n      });\n\n      if (!isCorrectFileType) {\n        const allowedFileTypesString = allowedFileTypes.join(', ');\n        throw new RestrictionError(this.i18n('youCanOnlyUploadFileTypes', {\n          types: allowedFileTypesString\n        }));\n      }\n    } // We can't check maxTotalFileSize if the size is unknown.\n\n\n    if (maxTotalFileSize && file.size != null) {\n      const totalFilesSize = files.reduce((total, f) => total + f.size, file.size);\n\n      if (totalFilesSize > maxTotalFileSize) {\n        throw new RestrictionError(this.i18n('exceedsSize', {\n          size: prettierBytes(maxTotalFileSize),\n          file: file.name\n        }));\n      }\n    } // We can't check maxFileSize if the size is unknown.\n\n\n    if (maxFileSize && file.size != null && file.size > maxFileSize) {\n      throw new RestrictionError(this.i18n('exceedsSize', {\n        size: prettierBytes(maxFileSize),\n        file: file.name\n      }));\n    } // We can't check minFileSize if the size is unknown.\n\n\n    if (minFileSize && file.size != null && file.size < minFileSize) {\n      throw new RestrictionError(this.i18n('inferiorSize', {\n        size: prettierBytes(minFileSize)\n      }));\n    }\n  }\n\n  validateMinNumberOfFiles(files) {\n    const {\n      minNumberOfFiles\n    } = this.getOpts().restrictions;\n\n    if (Object.keys(files).length < minNumberOfFiles) {\n      throw new RestrictionError(this.i18n('youHaveToAtLeastSelectX', {\n        smart_count: minNumberOfFiles\n      }));\n    }\n  }\n\n  getMissingRequiredMetaFields(file) {\n    const error = new RestrictionError(this.i18n('missingRequiredMetaFieldOnFile', {\n      fileName: file.name\n    }));\n    const {\n      requiredMetaFields\n    } = this.getOpts().restrictions; // TODO: migrate to Object.hasOwn in the next major.\n\n    const own = Object.prototype.hasOwnProperty;\n    const missingFields = [];\n\n    for (const field of requiredMetaFields) {\n      if (!own.call(file.meta, field) || file.meta[field] === '') {\n        missingFields.push(field);\n      }\n    }\n\n    return {\n      missingFields,\n      error\n    };\n  }\n\n}\n\nexports.Restricter = Restricter;", "\"use strict\";\n\nfunction has(object, key) {\n  return Object.prototype.hasOwnProperty.call(object, key);\n}\n\nmodule.exports = has;", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst has = require(\"./hasProperty.js\");\n\nfunction insertReplacement(source, rx, replacement) {\n  const newParts = [];\n  source.forEach(chunk => {\n    // When the source contains multiple placeholders for interpolation,\n    // we should ignore chunks that are not strings, because those\n    // can be JSX objects and will be otherwise incorrectly turned into strings.\n    // Without this condition we\u2019d get this: [object Object] hello [object Object] my <button>\n    if (typeof chunk !== 'string') {\n      return newParts.push(chunk);\n    }\n\n    return rx[Symbol.split](chunk).forEach((raw, i, list) => {\n      if (raw !== '') {\n        newParts.push(raw);\n      } // Interlace with the `replacement` value\n\n\n      if (i < list.length - 1) {\n        newParts.push(replacement);\n      }\n    });\n  });\n  return newParts;\n}\n/**\n * Takes a string with placeholder variables like `%{smart_count} file selected`\n * and replaces it with values from options `{smart_count: 5}`\n *\n * @license https://github.com/airbnb/polyglot.js/blob/master/LICENSE\n * taken from https://github.com/airbnb/polyglot.js/blob/master/lib/polyglot.js#L299\n *\n * @param {string} phrase that needs interpolation, with placeholders\n * @param {object} options with values that will be used to replace placeholders\n * @returns {any[]} interpolated\n */\n\n\nfunction interpolate(phrase, options) {\n  const dollarRegex = /\\$/g;\n  const dollarBillsYall = '$$$$';\n  let interpolated = [phrase];\n  if (options == null) return interpolated;\n\n  for (const arg of Object.keys(options)) {\n    if (arg !== '_') {\n      // Ensure replacement value is escaped to prevent special $-prefixed\n      // regex replace tokens. the \"$$$$\" is needed because each \"$\" needs to\n      // be escaped with \"$\" itself, and we need two in the resulting output.\n      let replacement = options[arg];\n\n      if (typeof replacement === 'string') {\n        replacement = dollarRegex[Symbol.replace](replacement, dollarBillsYall);\n      } // We create a new `RegExp` each time instead of using a more-efficient\n      // string replace so that the same argument can be replaced multiple times\n      // in the same phrase.\n\n\n      interpolated = insertReplacement(interpolated, new RegExp(`%\\\\{${arg}\\\\}`, 'g'), replacement);\n    }\n  }\n\n  return interpolated;\n}\n/**\n * Translates strings with interpolation & pluralization support.\n * Extensible with custom dictionaries and pluralization functions.\n *\n * Borrows heavily from and inspired by Polyglot https://github.com/airbnb/polyglot.js,\n * basically a stripped-down version of it. Differences: pluralization functions are not hardcoded\n * and can be easily added among with dictionaries, nested objects are used for pluralization\n * as opposed to `||||` delimeter\n *\n * Usage example: `translator.translate('files_chosen', {smart_count: 3})`\n */\n\n\nvar _apply = /*#__PURE__*/_classPrivateFieldLooseKey(\"apply\");\n\nclass Translator {\n  /**\n   * @param {object|Array<object>} locales - locale or list of locales.\n   */\n  constructor(locales) {\n    Object.defineProperty(this, _apply, {\n      value: _apply2\n    });\n    this.locale = {\n      strings: {},\n\n      pluralize(n) {\n        if (n === 1) {\n          return 0;\n        }\n\n        return 1;\n      }\n\n    };\n\n    if (Array.isArray(locales)) {\n      locales.forEach(_classPrivateFieldLooseBase(this, _apply)[_apply], this);\n    } else {\n      _classPrivateFieldLooseBase(this, _apply)[_apply](locales);\n    }\n  }\n\n  /**\n   * Public translate method\n   *\n   * @param {string} key\n   * @param {object} options with values that will be used later to replace placeholders in string\n   * @returns {string} translated (and interpolated)\n   */\n  translate(key, options) {\n    return this.translateArray(key, options).join('');\n  }\n  /**\n   * Get a translation and return the translated and interpolated parts as an array.\n   *\n   * @param {string} key\n   * @param {object} options with values that will be used to replace placeholders\n   * @returns {Array} The translated and interpolated parts, in order.\n   */\n\n\n  translateArray(key, options) {\n    if (!has(this.locale.strings, key)) {\n      throw new Error(`missing string: ${key}`);\n    }\n\n    const string = this.locale.strings[key];\n    const hasPluralForms = typeof string === 'object';\n\n    if (hasPluralForms) {\n      if (options && typeof options.smart_count !== 'undefined') {\n        const plural = this.locale.pluralize(options.smart_count);\n        return interpolate(string[plural], options);\n      }\n\n      throw new Error('Attempted to use a string with plural forms, but no value was given for %{smart_count}');\n    }\n\n    return interpolate(string, options);\n  }\n\n}\n\nfunction _apply2(locale) {\n  if (!(locale != null && locale.strings)) {\n    return;\n  }\n\n  const prevLocale = this.locale;\n  this.locale = { ...prevLocale,\n    strings: { ...prevLocale.strings,\n      ...locale.strings\n    }\n  };\n  this.locale.pluralize = locale.pluralize || prevLocale.pluralize;\n}\n\nmodule.exports = Translator;", "/**\n* Create an event emitter with namespaces\n* @name createNamespaceEmitter\n* @example\n* var emitter = require('./index')()\n*\n* emitter.on('*', function () {\n*   console.log('all events emitted', this.event)\n* })\n*\n* emitter.on('example', function () {\n*   console.log('example event emitted')\n* })\n*/\nmodule.exports = function createNamespaceEmitter () {\n  var emitter = {}\n  var _fns = emitter._fns = {}\n\n  /**\n  * Emit an event. Optionally namespace the event. Handlers are fired in the order in which they were added with exact matches taking precedence. Separate the namespace and event with a `:`\n  * @name emit\n  * @param {String} event \u2013 the name of the event, with optional namespace\n  * @param {...*} data \u2013 up to 6 arguments that are passed to the event listener\n  * @example\n  * emitter.emit('example')\n  * emitter.emit('demo:test')\n  * emitter.emit('data', { example: true}, 'a string', 1)\n  */\n  emitter.emit = function emit (event, arg1, arg2, arg3, arg4, arg5, arg6) {\n    var toEmit = getListeners(event)\n\n    if (toEmit.length) {\n      emitAll(event, toEmit, [arg1, arg2, arg3, arg4, arg5, arg6])\n    }\n  }\n\n  /**\n  * Create en event listener.\n  * @name on\n  * @param {String} event\n  * @param {Function} fn\n  * @example\n  * emitter.on('example', function () {})\n  * emitter.on('demo', function () {})\n  */\n  emitter.on = function on (event, fn) {\n    if (!_fns[event]) {\n      _fns[event] = []\n    }\n\n    _fns[event].push(fn)\n  }\n\n  /**\n  * Create en event listener that fires once.\n  * @name once\n  * @param {String} event\n  * @param {Function} fn\n  * @example\n  * emitter.once('example', function () {})\n  * emitter.once('demo', function () {})\n  */\n  emitter.once = function once (event, fn) {\n    function one () {\n      fn.apply(this, arguments)\n      emitter.off(event, one)\n    }\n    this.on(event, one)\n  }\n\n  /**\n  * Stop listening to an event. Stop all listeners on an event by only passing the event name. Stop a single listener by passing that event handler as a callback.\n  * You must be explicit about what will be unsubscribed: `emitter.off('demo')` will unsubscribe an `emitter.on('demo')` listener,\n  * `emitter.off('demo:example')` will unsubscribe an `emitter.on('demo:example')` listener\n  * @name off\n  * @param {String} event\n  * @param {Function} [fn] \u2013 the specific handler\n  * @example\n  * emitter.off('example')\n  * emitter.off('demo', function () {})\n  */\n  emitter.off = function off (event, fn) {\n    var keep = []\n\n    if (event && fn) {\n      var fns = this._fns[event]\n      var i = 0\n      var l = fns ? fns.length : 0\n\n      for (i; i < l; i++) {\n        if (fns[i] !== fn) {\n          keep.push(fns[i])\n        }\n      }\n    }\n\n    keep.length ? this._fns[event] = keep : delete this._fns[event]\n  }\n\n  function getListeners (e) {\n    var out = _fns[e] ? _fns[e] : []\n    var idx = e.indexOf(':')\n    var args = (idx === -1) ? [e] : [e.substring(0, idx), e.substring(idx + 1)]\n\n    var keys = Object.keys(_fns)\n    var i = 0\n    var l = keys.length\n\n    for (i; i < l; i++) {\n      var key = keys[i]\n      if (key === '*') {\n        out = out.concat(_fns[key])\n      }\n\n      if (args.length === 2 && args[0] === key) {\n        out = out.concat(_fns[key])\n        break\n      }\n    }\n\n    return out\n  }\n\n  function emitAll (e, fns, args) {\n    var i = 0\n    var l = fns.length\n\n    for (i; i < l; i++) {\n      if (!fns[i]) break\n      fns[i].event = e\n      fns[i].apply(fns[i], args)\n    }\n  }\n\n  return emitter\n}\n", "/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n    nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n *   console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n  return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n *  Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n *  The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n *  Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n *   'leading': true,\n *   'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n  var lastArgs,\n      lastThis,\n      maxWait,\n      result,\n      timerId,\n      lastCallTime,\n      lastInvokeTime = 0,\n      leading = false,\n      maxing = false,\n      trailing = true;\n\n  if (typeof func != 'function') {\n    throw new TypeError(FUNC_ERROR_TEXT);\n  }\n  wait = toNumber(wait) || 0;\n  if (isObject(options)) {\n    leading = !!options.leading;\n    maxing = 'maxWait' in options;\n    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n    trailing = 'trailing' in options ? !!options.trailing : trailing;\n  }\n\n  function invokeFunc(time) {\n    var args = lastArgs,\n        thisArg = lastThis;\n\n    lastArgs = lastThis = undefined;\n    lastInvokeTime = time;\n    result = func.apply(thisArg, args);\n    return result;\n  }\n\n  function leadingEdge(time) {\n    // Reset any `maxWait` timer.\n    lastInvokeTime = time;\n    // Start the timer for the trailing edge.\n    timerId = setTimeout(timerExpired, wait);\n    // Invoke the leading edge.\n    return leading ? invokeFunc(time) : result;\n  }\n\n  function remainingWait(time) {\n    var timeSinceLastCall = time - lastCallTime,\n        timeSinceLastInvoke = time - lastInvokeTime,\n        result = wait - timeSinceLastCall;\n\n    return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n  }\n\n  function shouldInvoke(time) {\n    var timeSinceLastCall = time - lastCallTime,\n        timeSinceLastInvoke = time - lastInvokeTime;\n\n    // Either this is the first call, activity has stopped and we're at the\n    // trailing edge, the system time has gone backwards and we're treating\n    // it as the trailing edge, or we've hit the `maxWait` limit.\n    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n  }\n\n  function timerExpired() {\n    var time = now();\n    if (shouldInvoke(time)) {\n      return trailingEdge(time);\n    }\n    // Restart the timer.\n    timerId = setTimeout(timerExpired, remainingWait(time));\n  }\n\n  function trailingEdge(time) {\n    timerId = undefined;\n\n    // Only invoke if we have `lastArgs` which means `func` has been\n    // debounced at least once.\n    if (trailing && lastArgs) {\n      return invokeFunc(time);\n    }\n    lastArgs = lastThis = undefined;\n    return result;\n  }\n\n  function cancel() {\n    if (timerId !== undefined) {\n      clearTimeout(timerId);\n    }\n    lastInvokeTime = 0;\n    lastArgs = lastCallTime = lastThis = timerId = undefined;\n  }\n\n  function flush() {\n    return timerId === undefined ? result : trailingEdge(now());\n  }\n\n  function debounced() {\n    var time = now(),\n        isInvoking = shouldInvoke(time);\n\n    lastArgs = arguments;\n    lastThis = this;\n    lastCallTime = time;\n\n    if (isInvoking) {\n      if (timerId === undefined) {\n        return leadingEdge(lastCallTime);\n      }\n      if (maxing) {\n        // Handle invocations in a tight loop.\n        timerId = setTimeout(timerExpired, wait);\n        return invokeFunc(lastCallTime);\n      }\n    }\n    if (timerId === undefined) {\n      timerId = setTimeout(timerExpired, wait);\n    }\n    return result;\n  }\n  debounced.cancel = cancel;\n  debounced.flush = flush;\n  return debounced;\n}\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n *  Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n *  Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\nfunction throttle(func, wait, options) {\n  var leading = true,\n      trailing = true;\n\n  if (typeof func != 'function') {\n    throw new TypeError(FUNC_ERROR_TEXT);\n  }\n  if (isObject(options)) {\n    leading = 'leading' in options ? !!options.leading : leading;\n    trailing = 'trailing' in options ? !!options.trailing : trailing;\n  }\n  return debounce(func, wait, {\n    'leading': leading,\n    'maxWait': wait,\n    'trailing': trailing\n  });\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n  var type = typeof value;\n  return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n  return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n  return typeof value == 'symbol' ||\n    (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n  if (typeof value == 'number') {\n    return value;\n  }\n  if (isSymbol(value)) {\n    return NAN;\n  }\n  if (isObject(value)) {\n    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n    value = isObject(other) ? (other + '') : other;\n  }\n  if (typeof value != 'string') {\n    return value === 0 ? value : +value;\n  }\n  value = value.replace(reTrim, '');\n  var isBinary = reIsBinary.test(value);\n  return (isBinary || reIsOctal.test(value))\n    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n    : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = throttle;\n", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst packageJson = {\n  \"version\": \"2.1.1\"\n};\n/**\n * Default store that keeps state in a simple object.\n */\n\nvar _publish = /*#__PURE__*/_classPrivateFieldLooseKey(\"publish\");\n\nclass DefaultStore {\n  constructor() {\n    Object.defineProperty(this, _publish, {\n      value: _publish2\n    });\n    this.state = {};\n    this.callbacks = []; // TODO: use a Set instead, make it a private prop\n  }\n\n  getState() {\n    return this.state;\n  }\n\n  setState(patch) {\n    const prevState = { ...this.state\n    };\n    const nextState = { ...this.state,\n      ...patch\n    };\n    this.state = nextState;\n\n    _classPrivateFieldLooseBase(this, _publish)[_publish](prevState, nextState, patch);\n  }\n\n  subscribe(listener) {\n    this.callbacks.push(listener);\n    return () => {\n      // Remove the listener.\n      this.callbacks.splice(this.callbacks.indexOf(listener), 1);\n    };\n  }\n\n} // TODO: export the class instead in the next major.\n\n\nfunction _publish2() {\n  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n    args[_key] = arguments[_key];\n  }\n\n  this.callbacks.forEach(listener => {\n    listener(...args);\n  });\n}\n\nDefaultStore.VERSION = packageJson.version;\n\nfunction defaultStore() {\n  return new DefaultStore();\n}\n\nmodule.exports = defaultStore;", "\"use strict\";\n\nfunction getFileNameAndExtension(fullFileName) {\n  const lastDot = fullFileName.lastIndexOf('.'); // these count as no extension: \"no-dot\", \"trailing-dot.\"\n\n  if (lastDot === -1 || lastDot === fullFileName.length - 1) {\n    return {\n      name: fullFileName,\n      extension: undefined\n    };\n  }\n\n  return {\n    name: fullFileName.slice(0, lastDot),\n    extension: fullFileName.slice(lastDot + 1)\n  };\n}\n\n/**\n * Takes a full filename string and returns an object {name, extension}\n *\n * @param {string} fullFileName\n * @returns {object} {name, extension}\n */\nmodule.exports = getFileNameAndExtension;", "\"use strict\";\n\n// ___Why not add the mime-types package?\n//    It's 19.7kB gzipped, and we only need mime types for well-known extensions (for file previews).\n// ___Where to take new extensions from?\n//    https://github.com/jshttp/mime-db/blob/master/db.json\nmodule.exports = {\n  md: 'text/markdown',\n  markdown: 'text/markdown',\n  mp4: 'video/mp4',\n  mp3: 'audio/mp3',\n  svg: 'image/svg+xml',\n  jpg: 'image/jpeg',\n  png: 'image/png',\n  gif: 'image/gif',\n  heic: 'image/heic',\n  heif: 'image/heif',\n  yaml: 'text/yaml',\n  yml: 'text/yaml',\n  csv: 'text/csv',\n  tsv: 'text/tab-separated-values',\n  tab: 'text/tab-separated-values',\n  avi: 'video/x-msvideo',\n  mks: 'video/x-matroska',\n  mkv: 'video/x-matroska',\n  mov: 'video/quicktime',\n  dicom: 'application/dicom',\n  doc: 'application/msword',\n  docm: 'application/vnd.ms-word.document.macroenabled.12',\n  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n  dot: 'application/msword',\n  dotm: 'application/vnd.ms-word.template.macroenabled.12',\n  dotx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',\n  xla: 'application/vnd.ms-excel',\n  xlam: 'application/vnd.ms-excel.addin.macroenabled.12',\n  xlc: 'application/vnd.ms-excel',\n  xlf: 'application/x-xliff+xml',\n  xlm: 'application/vnd.ms-excel',\n  xls: 'application/vnd.ms-excel',\n  xlsb: 'application/vnd.ms-excel.sheet.binary.macroenabled.12',\n  xlsm: 'application/vnd.ms-excel.sheet.macroenabled.12',\n  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n  xlt: 'application/vnd.ms-excel',\n  xltm: 'application/vnd.ms-excel.template.macroenabled.12',\n  xltx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',\n  xlw: 'application/vnd.ms-excel',\n  txt: 'text/plain',\n  text: 'text/plain',\n  conf: 'text/plain',\n  log: 'text/plain',\n  pdf: 'application/pdf',\n  zip: 'application/zip',\n  '7z': 'application/x-7z-compressed',\n  rar: 'application/x-rar-compressed',\n  tar: 'application/x-tar',\n  gz: 'application/gzip',\n  dmg: 'application/x-apple-diskimage'\n};", "\"use strict\";\n\nconst getFileNameAndExtension = require(\"./getFileNameAndExtension.js\");\n\nconst mimeTypes = require(\"./mimeTypes.js\");\n\nfunction getFileType(file) {\n  var _getFileNameAndExtens;\n\n  if (file.type) return file.type;\n  const fileExtension = file.name ? (_getFileNameAndExtens = getFileNameAndExtension(file.name).extension) == null ? void 0 : _getFileNameAndExtens.toLowerCase() : null;\n\n  if (fileExtension && fileExtension in mimeTypes) {\n    // else, see if we can map extension to a mime type\n    return mimeTypes[fileExtension];\n  } // if all fails, fall back to a generic byte stream type\n\n\n  return 'application/octet-stream';\n}\n\nmodule.exports = getFileType;", "\"use strict\";\n\nfunction encodeCharacter(character) {\n  return character.charCodeAt(0).toString(32);\n}\n\nfunction encodeFilename(name) {\n  let suffix = '';\n  return name.replace(/[^A-Z0-9]/ig, character => {\n    suffix += `-${encodeCharacter(character)}`;\n    return '/';\n  }) + suffix;\n}\n/**\n * Takes a file object and turns it into fileID, by converting file.name to lowercase,\n * removing extra characters and adding type, size and lastModified\n *\n * @param {object} file\n * @returns {string} the fileID\n */\n\n\nfunction generateFileID(file) {\n  // It's tempting to do `[items].filter(Boolean).join('-')` here, but that\n  // is slower! simple string concatenation is fast\n  let id = 'uppy';\n\n  if (typeof file.name === 'string') {\n    id += `-${encodeFilename(file.name.toLowerCase())}`;\n  }\n\n  if (file.type !== undefined) {\n    id += `-${file.type}`;\n  }\n\n  if (file.meta && typeof file.meta.relativePath === 'string') {\n    id += `-${encodeFilename(file.meta.relativePath.toLowerCase())}`;\n  }\n\n  if (file.data.size !== undefined) {\n    id += `-${file.data.size}`;\n  }\n\n  if (file.data.lastModified !== undefined) {\n    id += `-${file.data.lastModified}`;\n  }\n\n  return id;\n}\n\nmodule.exports = generateFileID;", "\"use strict\";\n\nfunction supportsUploadProgress(userAgent) {\n  // Allow passing in userAgent for tests\n  if (userAgent == null && typeof navigator !== 'undefined') {\n    // eslint-disable-next-line no-param-reassign\n    userAgent = navigator.userAgent;\n  } // Assume it works because basically everything supports progress events.\n\n\n  if (!userAgent) return true;\n  const m = /Edge\\/(\\d+\\.\\d+)/.exec(userAgent);\n  if (!m) return true;\n  const edgeVersion = m[1];\n  let [major, minor] = edgeVersion.split('.');\n  major = parseInt(major, 10);\n  minor = parseInt(minor, 10); // Worked before:\n  // Edge 40.15063.0.0\n  // Microsoft EdgeHTML 15.15063\n\n  if (major < 15 || major === 15 && minor < 15063) {\n    return true;\n  } // Fixed in:\n  // Microsoft EdgeHTML 18.18218\n\n\n  if (major > 18 || major === 18 && minor >= 18218) {\n    return true;\n  } // other versions don't work.\n\n\n  return false;\n}\n\n// Edge 15.x does not fire 'progress' events on uploads.\n// See https://github.com/transloadit/uppy/issues/945\n// And https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12224510/\nmodule.exports = supportsUploadProgress;", "\"use strict\";\n\nfunction getFileName(fileType, fileDescriptor) {\n  if (fileDescriptor.name) {\n    return fileDescriptor.name;\n  }\n\n  if (fileType.split('/')[0] === 'image') {\n    return `${fileType.split('/')[0]}.${fileType.split('/')[1]}`;\n  }\n\n  return 'noname';\n}\n\nmodule.exports = getFileName;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    addBulkFilesFailed: {\n      0: 'Failed to add %{smart_count} file due to an internal error',\n      1: 'Failed to add %{smart_count} files due to internal errors'\n    },\n    youCanOnlyUploadX: {\n      0: 'You can only upload %{smart_count} file',\n      1: 'You can only upload %{smart_count} files'\n    },\n    youHaveToAtLeastSelectX: {\n      0: 'You have to select at least %{smart_count} file',\n      1: 'You have to select at least %{smart_count} files'\n    },\n    exceedsSize: '%{file} exceeds maximum allowed size of %{size}',\n    missingRequiredMetaField: 'Missing required meta fields',\n    missingRequiredMetaFieldOnFile: 'Missing required meta fields in %{fileName}',\n    inferiorSize: 'This file is smaller than the allowed size of %{size}',\n    youCanOnlyUploadFileTypes: 'You can only upload: %{types}',\n    noMoreFilesAllowed: 'Cannot add more files',\n    noDuplicates: \"Cannot add the duplicate file '%{fileName}', it already exists\",\n    companionError: 'Connection with Companion failed',\n    authAborted: 'Authentication aborted',\n    companionUnauthorizeHint: 'To unauthorize to your %{provider} account, please go to %{url}',\n    failedToUpload: 'Failed to upload %{file}',\n    noInternetConnection: 'No Internet connection',\n    connectedToInternet: 'Connected to the Internet',\n    // Strings for remote providers\n    noFilesFound: 'You have no files or folders here',\n    selectX: {\n      0: 'Select %{smart_count}',\n      1: 'Select %{smart_count}'\n    },\n    allFilesFromFolderNamed: 'All files from folder %{name}',\n    openFolderNamed: 'Open folder %{name}',\n    cancel: 'Cancel',\n    logOut: 'Log out',\n    filter: 'Filter',\n    resetFilter: 'Reset filter',\n    loading: 'Loading...',\n    authenticateWithTitle: 'Please authenticate with %{pluginName} to select files',\n    authenticateWith: 'Connect to %{pluginName}',\n    signInWithGoogle: 'Sign in with Google',\n    searchImages: 'Search for images',\n    enterTextToSearch: 'Enter text to search for images',\n    search: 'Search',\n    emptyFolderAdded: 'No files were added from empty folder',\n    folderAlreadyAdded: 'The folder \"%{folder}\" was already added',\n    folderAdded: {\n      0: 'Added %{smart_count} file from %{folder}',\n      1: 'Added %{smart_count} files from %{folder}'\n    }\n  }\n};", "\"use strict\";\n\nvar _nonSecure = require(\"nanoid/non-secure\");\n\nvar _loggers = require(\"./loggers.js\");\n\nvar _Restricter = require(\"./Restricter.js\");\n\nlet _Symbol$for, _Symbol$for2;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\n/* eslint-disable max-classes-per-file */\n\n/* global AggregateError */\nconst Translator = require(\"@uppy/utils/lib/Translator\");\n\nconst ee = require(\"namespace-emitter\");\n\nconst throttle = require(\"lodash.throttle\");\n\nconst DefaultStore = require(\"@uppy/store-default\");\n\nconst getFileType = require(\"@uppy/utils/lib/getFileType\");\n\nconst getFileNameAndExtension = require(\"@uppy/utils/lib/getFileNameAndExtension\");\n\nconst generateFileID = require(\"@uppy/utils/lib/generateFileID\");\n\nconst supportsUploadProgress = require(\"./supportsUploadProgress.js\");\n\nconst getFileName = require(\"./getFileName.js\");\n\nconst packageJson = {\n  \"version\": \"2.3.4\"\n};\n\nconst locale = require(\"./locale.js\");\n/**\n * Uppy Core module.\n * Manages plugins, state updates, acts as an event bus,\n * adds/removes files and metadata.\n */\n\n\nvar _plugins = /*#__PURE__*/_classPrivateFieldLooseKey(\"plugins\");\n\nvar _restricter = /*#__PURE__*/_classPrivateFieldLooseKey(\"restricter\");\n\nvar _storeUnsubscribe = /*#__PURE__*/_classPrivateFieldLooseKey(\"storeUnsubscribe\");\n\nvar _emitter = /*#__PURE__*/_classPrivateFieldLooseKey(\"emitter\");\n\nvar _preProcessors = /*#__PURE__*/_classPrivateFieldLooseKey(\"preProcessors\");\n\nvar _uploaders = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploaders\");\n\nvar _postProcessors = /*#__PURE__*/_classPrivateFieldLooseKey(\"postProcessors\");\n\nvar _informAndEmit = /*#__PURE__*/_classPrivateFieldLooseKey(\"informAndEmit\");\n\nvar _checkRequiredMetaFieldsOnFile = /*#__PURE__*/_classPrivateFieldLooseKey(\"checkRequiredMetaFieldsOnFile\");\n\nvar _checkRequiredMetaFields = /*#__PURE__*/_classPrivateFieldLooseKey(\"checkRequiredMetaFields\");\n\nvar _assertNewUploadAllowed = /*#__PURE__*/_classPrivateFieldLooseKey(\"assertNewUploadAllowed\");\n\nvar _checkAndCreateFileStateObject = /*#__PURE__*/_classPrivateFieldLooseKey(\"checkAndCreateFileStateObject\");\n\nvar _startIfAutoProceed = /*#__PURE__*/_classPrivateFieldLooseKey(\"startIfAutoProceed\");\n\nvar _addListeners = /*#__PURE__*/_classPrivateFieldLooseKey(\"addListeners\");\n\nvar _updateOnlineStatus = /*#__PURE__*/_classPrivateFieldLooseKey(\"updateOnlineStatus\");\n\nvar _createUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"createUpload\");\n\nvar _getUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"getUpload\");\n\nvar _removeUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"removeUpload\");\n\nvar _runUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"runUpload\");\n\n_Symbol$for = Symbol.for('uppy test: getPlugins');\n_Symbol$for2 = Symbol.for('uppy test: createUpload');\n\nclass Uppy {\n  /** @type {Record<string, BasePlugin[]>} */\n\n  /**\n   * Instantiate Uppy\n   *\n   * @param {object} opts \u2014 Uppy options\n   */\n  constructor(_opts) {\n    Object.defineProperty(this, _runUpload, {\n      value: _runUpload2\n    });\n    Object.defineProperty(this, _removeUpload, {\n      value: _removeUpload2\n    });\n    Object.defineProperty(this, _getUpload, {\n      value: _getUpload2\n    });\n    Object.defineProperty(this, _createUpload, {\n      value: _createUpload2\n    });\n    Object.defineProperty(this, _addListeners, {\n      value: _addListeners2\n    });\n    Object.defineProperty(this, _startIfAutoProceed, {\n      value: _startIfAutoProceed2\n    });\n    Object.defineProperty(this, _checkAndCreateFileStateObject, {\n      value: _checkAndCreateFileStateObject2\n    });\n    Object.defineProperty(this, _assertNewUploadAllowed, {\n      value: _assertNewUploadAllowed2\n    });\n    Object.defineProperty(this, _checkRequiredMetaFields, {\n      value: _checkRequiredMetaFields2\n    });\n    Object.defineProperty(this, _checkRequiredMetaFieldsOnFile, {\n      value: _checkRequiredMetaFieldsOnFile2\n    });\n    Object.defineProperty(this, _informAndEmit, {\n      value: _informAndEmit2\n    });\n    Object.defineProperty(this, _plugins, {\n      writable: true,\n      value: Object.create(null)\n    });\n    Object.defineProperty(this, _restricter, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _storeUnsubscribe, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _emitter, {\n      writable: true,\n      value: ee()\n    });\n    Object.defineProperty(this, _preProcessors, {\n      writable: true,\n      value: new Set()\n    });\n    Object.defineProperty(this, _uploaders, {\n      writable: true,\n      value: new Set()\n    });\n    Object.defineProperty(this, _postProcessors, {\n      writable: true,\n      value: new Set()\n    });\n    Object.defineProperty(this, _updateOnlineStatus, {\n      writable: true,\n      value: this.updateOnlineStatus.bind(this)\n    });\n    this.defaultLocale = locale;\n    const defaultOptions = {\n      id: 'uppy',\n      autoProceed: false,\n\n      /**\n       * @deprecated The method should not be used\n       */\n      allowMultipleUploads: true,\n      allowMultipleUploadBatches: true,\n      debug: false,\n      restrictions: _Restricter.defaultOptions,\n      meta: {},\n      onBeforeFileAdded: currentFile => currentFile,\n      onBeforeUpload: files => files,\n      store: DefaultStore(),\n      logger: _loggers.justErrorsLogger,\n      infoTimeout: 5000\n    }; // Merge default options with the ones set by user,\n    // making sure to merge restrictions too\n\n    this.opts = { ...defaultOptions,\n      ..._opts,\n      restrictions: { ...defaultOptions.restrictions,\n        ...(_opts && _opts.restrictions)\n      }\n    }; // Support debug: true for backwards-compatability, unless logger is set in opts\n    // opts instead of this.opts to avoid comparing objects \u2014 we set logger: justErrorsLogger in defaultOptions\n\n    if (_opts && _opts.logger && _opts.debug) {\n      this.log('You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.', 'warning');\n    } else if (_opts && _opts.debug) {\n      this.opts.logger = _loggers.debugLogger;\n    }\n\n    this.log(`Using Core v${this.constructor.VERSION}`);\n    this.i18nInit(); // ___Why throttle at 500ms?\n    //    - We must throttle at >250ms for superfocus in Dashboard to work well\n    //    (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).\n    //    [Practical Check]: if thottle is at 100ms, then if you are uploading a file,\n    //    and click 'ADD MORE FILES', - focus won't activate in Firefox.\n    //    - We must throttle at around >500ms to avoid performance lags.\n    //    [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.\n\n    this.calculateProgress = throttle(this.calculateProgress.bind(this), 500, {\n      leading: true,\n      trailing: true\n    });\n    this.store = this.opts.store;\n    this.setState({\n      plugins: {},\n      files: {},\n      currentUploads: {},\n      allowNewUpload: true,\n      capabilities: {\n        uploadProgress: supportsUploadProgress(),\n        individualCancellation: true,\n        resumableUploads: false\n      },\n      totalProgress: 0,\n      meta: { ...this.opts.meta\n      },\n      info: [],\n      recoveredState: null\n    });\n    _classPrivateFieldLooseBase(this, _restricter)[_restricter] = new _Restricter.Restricter(() => this.opts, this.i18n);\n    _classPrivateFieldLooseBase(this, _storeUnsubscribe)[_storeUnsubscribe] = this.store.subscribe((prevState, nextState, patch) => {\n      this.emit('state-update', prevState, nextState, patch);\n      this.updateAll(nextState);\n    }); // Exposing uppy object on window for debugging and testing\n\n    if (this.opts.debug && typeof window !== 'undefined') {\n      window[this.opts.id] = this;\n    }\n\n    _classPrivateFieldLooseBase(this, _addListeners)[_addListeners]();\n  }\n\n  emit(event) {\n    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      args[_key - 1] = arguments[_key];\n    }\n\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter].emit(event, ...args);\n  }\n\n  on(event, callback) {\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter].on(event, callback);\n\n    return this;\n  }\n\n  once(event, callback) {\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter].once(event, callback);\n\n    return this;\n  }\n\n  off(event, callback) {\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter].off(event, callback);\n\n    return this;\n  }\n  /**\n   * Iterate on all plugins and run `update` on them.\n   * Called each time state changes.\n   *\n   */\n\n\n  updateAll(state) {\n    this.iteratePlugins(plugin => {\n      plugin.update(state);\n    });\n  }\n  /**\n   * Updates state with a patch\n   *\n   * @param {object} patch {foo: 'bar'}\n   */\n\n\n  setState(patch) {\n    this.store.setState(patch);\n  }\n  /**\n   * Returns current state.\n   *\n   * @returns {object}\n   */\n\n\n  getState() {\n    return this.store.getState();\n  }\n  /**\n   * Back compat for when uppy.state is used instead of uppy.getState().\n   *\n   * @deprecated\n   */\n\n\n  get state() {\n    // Here, state is a non-enumerable property.\n    return this.getState();\n  }\n  /**\n   * Shorthand to set state for a specific file.\n   */\n\n\n  setFileState(fileID, state) {\n    if (!this.getState().files[fileID]) {\n      throw new Error(`Can\u2019t set state for ${fileID} (the file could have been removed)`);\n    }\n\n    this.setState({\n      files: { ...this.getState().files,\n        [fileID]: { ...this.getState().files[fileID],\n          ...state\n        }\n      }\n    });\n  }\n\n  i18nInit() {\n    const translator = new Translator([this.defaultLocale, this.opts.locale]);\n    this.i18n = translator.translate.bind(translator);\n    this.i18nArray = translator.translateArray.bind(translator);\n    this.locale = translator.locale;\n  }\n\n  setOptions(newOpts) {\n    this.opts = { ...this.opts,\n      ...newOpts,\n      restrictions: { ...this.opts.restrictions,\n        ...(newOpts && newOpts.restrictions)\n      }\n    };\n\n    if (newOpts.meta) {\n      this.setMeta(newOpts.meta);\n    }\n\n    this.i18nInit();\n\n    if (newOpts.locale) {\n      this.iteratePlugins(plugin => {\n        plugin.setOptions();\n      });\n    } // Note: this is not the preact `setState`, it's an internal function that has the same name.\n\n\n    this.setState(); // so that UI re-renders with new options\n  }\n\n  resetProgress() {\n    const defaultProgress = {\n      percentage: 0,\n      bytesUploaded: 0,\n      uploadComplete: false,\n      uploadStarted: null\n    };\n    const files = { ...this.getState().files\n    };\n    const updatedFiles = {};\n    Object.keys(files).forEach(fileID => {\n      const updatedFile = { ...files[fileID]\n      };\n      updatedFile.progress = { ...updatedFile.progress,\n        ...defaultProgress\n      };\n      updatedFiles[fileID] = updatedFile;\n    });\n    this.setState({\n      files: updatedFiles,\n      totalProgress: 0\n    });\n    this.emit('reset-progress');\n  }\n\n  addPreProcessor(fn) {\n    _classPrivateFieldLooseBase(this, _preProcessors)[_preProcessors].add(fn);\n  }\n\n  removePreProcessor(fn) {\n    return _classPrivateFieldLooseBase(this, _preProcessors)[_preProcessors].delete(fn);\n  }\n\n  addPostProcessor(fn) {\n    _classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors].add(fn);\n  }\n\n  removePostProcessor(fn) {\n    return _classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors].delete(fn);\n  }\n\n  addUploader(fn) {\n    _classPrivateFieldLooseBase(this, _uploaders)[_uploaders].add(fn);\n  }\n\n  removeUploader(fn) {\n    return _classPrivateFieldLooseBase(this, _uploaders)[_uploaders].delete(fn);\n  }\n\n  setMeta(data) {\n    const updatedMeta = { ...this.getState().meta,\n      ...data\n    };\n    const updatedFiles = { ...this.getState().files\n    };\n    Object.keys(updatedFiles).forEach(fileID => {\n      updatedFiles[fileID] = { ...updatedFiles[fileID],\n        meta: { ...updatedFiles[fileID].meta,\n          ...data\n        }\n      };\n    });\n    this.log('Adding metadata:');\n    this.log(data);\n    this.setState({\n      meta: updatedMeta,\n      files: updatedFiles\n    });\n  }\n\n  setFileMeta(fileID, data) {\n    const updatedFiles = { ...this.getState().files\n    };\n\n    if (!updatedFiles[fileID]) {\n      this.log('Was trying to set metadata for a file that has been removed: ', fileID);\n      return;\n    }\n\n    const newMeta = { ...updatedFiles[fileID].meta,\n      ...data\n    };\n    updatedFiles[fileID] = { ...updatedFiles[fileID],\n      meta: newMeta\n    };\n    this.setState({\n      files: updatedFiles\n    });\n  }\n  /**\n   * Get a file object.\n   *\n   * @param {string} fileID The ID of the file object to return.\n   */\n\n\n  getFile(fileID) {\n    return this.getState().files[fileID];\n  }\n  /**\n   * Get all files in an array.\n   */\n\n\n  getFiles() {\n    const {\n      files\n    } = this.getState();\n    return Object.values(files);\n  }\n\n  getObjectOfFilesPerState() {\n    const {\n      files: filesObject,\n      totalProgress,\n      error\n    } = this.getState();\n    const files = Object.values(filesObject);\n    const inProgressFiles = files.filter(_ref => {\n      let {\n        progress\n      } = _ref;\n      return !progress.uploadComplete && progress.uploadStarted;\n    });\n    const newFiles = files.filter(file => !file.progress.uploadStarted);\n    const startedFiles = files.filter(file => file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess);\n    const uploadStartedFiles = files.filter(file => file.progress.uploadStarted);\n    const pausedFiles = files.filter(file => file.isPaused);\n    const completeFiles = files.filter(file => file.progress.uploadComplete);\n    const erroredFiles = files.filter(file => file.error);\n    const inProgressNotPausedFiles = inProgressFiles.filter(file => !file.isPaused);\n    const processingFiles = files.filter(file => file.progress.preprocess || file.progress.postprocess);\n    return {\n      newFiles,\n      startedFiles,\n      uploadStartedFiles,\n      pausedFiles,\n      completeFiles,\n      erroredFiles,\n      inProgressFiles,\n      inProgressNotPausedFiles,\n      processingFiles,\n      isUploadStarted: uploadStartedFiles.length > 0,\n      isAllComplete: totalProgress === 100 && completeFiles.length === files.length && processingFiles.length === 0,\n      isAllErrored: !!error && erroredFiles.length === files.length,\n      isAllPaused: inProgressFiles.length !== 0 && pausedFiles.length === inProgressFiles.length,\n      isUploadInProgress: inProgressFiles.length > 0,\n      isSomeGhost: files.some(file => file.isGhost)\n    };\n  }\n  /*\n  * @constructs\n  * @param { Error } error\n  * @param { undefined } file\n  */\n\n  /*\n  * @constructs\n  * @param { RestrictionError } error\n  * @param { UppyFile | undefined } file\n  */\n\n\n  validateRestrictions(file, files) {\n    if (files === void 0) {\n      files = this.getFiles();\n    }\n\n    // TODO: directly return the Restriction error in next major version.\n    // we create RestrictionError's just to discard immediately, which doesn't make sense.\n    try {\n      _classPrivateFieldLooseBase(this, _restricter)[_restricter].validate(file, files);\n\n      return {\n        result: true\n      };\n    } catch (err) {\n      return {\n        result: false,\n        reason: err.message\n      };\n    }\n  }\n\n  checkIfFileAlreadyExists(fileID) {\n    const {\n      files\n    } = this.getState();\n\n    if (files[fileID] && !files[fileID].isGhost) {\n      return true;\n    }\n\n    return false;\n  }\n  /**\n   * Create a file state object based on user-provided `addFile()` options.\n   *\n   * Note this is extremely side-effectful and should only be done when a file state object\n   * will be added to state immediately afterward!\n   *\n   * The `files` value is passed in because it may be updated by the caller without updating the store.\n   */\n\n\n  /**\n   * Add a new file to `state.files`. This will run `onBeforeFileAdded`,\n   * try to guess file type in a clever way, check file against restrictions,\n   * and start an upload if `autoProceed === true`.\n   *\n   * @param {object} file object to add\n   * @returns {string} id for the added file\n   */\n  addFile(file) {\n    _classPrivateFieldLooseBase(this, _assertNewUploadAllowed)[_assertNewUploadAllowed](file);\n\n    const {\n      files\n    } = this.getState();\n\n    let newFile = _classPrivateFieldLooseBase(this, _checkAndCreateFileStateObject)[_checkAndCreateFileStateObject](files, file); // Users are asked to re-select recovered files without data,\n    // and to keep the progress, meta and everthing else, we only replace said data\n\n\n    if (files[newFile.id] && files[newFile.id].isGhost) {\n      newFile = { ...files[newFile.id],\n        data: file.data,\n        isGhost: false\n      };\n      this.log(`Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`);\n    }\n\n    this.setState({\n      files: { ...files,\n        [newFile.id]: newFile\n      }\n    });\n    this.emit('file-added', newFile);\n    this.emit('files-added', [newFile]);\n    this.log(`Added file: ${newFile.name}, ${newFile.id}, mime type: ${newFile.type}`);\n\n    _classPrivateFieldLooseBase(this, _startIfAutoProceed)[_startIfAutoProceed]();\n\n    return newFile.id;\n  }\n  /**\n   * Add multiple files to `state.files`. See the `addFile()` documentation.\n   *\n   * If an error occurs while adding a file, it is logged and the user is notified.\n   * This is good for UI plugins, but not for programmatic use.\n   * Programmatic users should usually still use `addFile()` on individual files.\n   */\n\n\n  addFiles(fileDescriptors) {\n    _classPrivateFieldLooseBase(this, _assertNewUploadAllowed)[_assertNewUploadAllowed](); // create a copy of the files object only once\n\n\n    const files = { ...this.getState().files\n    };\n    const newFiles = [];\n    const errors = [];\n\n    for (let i = 0; i < fileDescriptors.length; i++) {\n      try {\n        let newFile = _classPrivateFieldLooseBase(this, _checkAndCreateFileStateObject)[_checkAndCreateFileStateObject](files, fileDescriptors[i]); // Users are asked to re-select recovered files without data,\n        // and to keep the progress, meta and everthing else, we only replace said data\n\n\n        if (files[newFile.id] && files[newFile.id].isGhost) {\n          newFile = { ...files[newFile.id],\n            data: fileDescriptors[i].data,\n            isGhost: false\n          };\n          this.log(`Replaced blob in a ghost file: ${newFile.name}, ${newFile.id}`);\n        }\n\n        files[newFile.id] = newFile;\n        newFiles.push(newFile);\n      } catch (err) {\n        if (!err.isRestriction) {\n          errors.push(err);\n        }\n      }\n    }\n\n    this.setState({\n      files\n    });\n    newFiles.forEach(newFile => {\n      this.emit('file-added', newFile);\n    });\n    this.emit('files-added', newFiles);\n\n    if (newFiles.length > 5) {\n      this.log(`Added batch of ${newFiles.length} files`);\n    } else {\n      Object.keys(newFiles).forEach(fileID => {\n        this.log(`Added file: ${newFiles[fileID].name}\\n id: ${newFiles[fileID].id}\\n type: ${newFiles[fileID].type}`);\n      });\n    }\n\n    if (newFiles.length > 0) {\n      _classPrivateFieldLooseBase(this, _startIfAutoProceed)[_startIfAutoProceed]();\n    }\n\n    if (errors.length > 0) {\n      let message = 'Multiple errors occurred while adding files:\\n';\n      errors.forEach(subError => {\n        message += `\\n * ${subError.message}`;\n      });\n      this.info({\n        message: this.i18n('addBulkFilesFailed', {\n          smart_count: errors.length\n        }),\n        details: message\n      }, 'error', this.opts.infoTimeout);\n\n      if (typeof AggregateError === 'function') {\n        throw new AggregateError(errors, message);\n      } else {\n        const err = new Error(message);\n        err.errors = errors;\n        throw err;\n      }\n    }\n  }\n\n  removeFiles(fileIDs, reason) {\n    const {\n      files,\n      currentUploads\n    } = this.getState();\n    const updatedFiles = { ...files\n    };\n    const updatedUploads = { ...currentUploads\n    };\n    const removedFiles = Object.create(null);\n    fileIDs.forEach(fileID => {\n      if (files[fileID]) {\n        removedFiles[fileID] = files[fileID];\n        delete updatedFiles[fileID];\n      }\n    }); // Remove files from the `fileIDs` list in each upload.\n\n    function fileIsNotRemoved(uploadFileID) {\n      return removedFiles[uploadFileID] === undefined;\n    }\n\n    Object.keys(updatedUploads).forEach(uploadID => {\n      const newFileIDs = currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved); // Remove the upload if no files are associated with it anymore.\n\n      if (newFileIDs.length === 0) {\n        delete updatedUploads[uploadID];\n        return;\n      }\n\n      const {\n        capabilities\n      } = this.getState();\n\n      if (newFileIDs.length !== currentUploads[uploadID].fileIDs.length && !capabilities.individualCancellation) {\n        throw new Error('individualCancellation is disabled');\n      }\n\n      updatedUploads[uploadID] = { ...currentUploads[uploadID],\n        fileIDs: newFileIDs\n      };\n    });\n    const stateUpdate = {\n      currentUploads: updatedUploads,\n      files: updatedFiles\n    }; // If all files were removed - allow new uploads,\n    // and clear recoveredState\n\n    if (Object.keys(updatedFiles).length === 0) {\n      stateUpdate.allowNewUpload = true;\n      stateUpdate.error = null;\n      stateUpdate.recoveredState = null;\n    }\n\n    this.setState(stateUpdate);\n    this.calculateTotalProgress();\n    const removedFileIDs = Object.keys(removedFiles);\n    removedFileIDs.forEach(fileID => {\n      this.emit('file-removed', removedFiles[fileID], reason);\n    });\n\n    if (removedFileIDs.length > 5) {\n      this.log(`Removed ${removedFileIDs.length} files`);\n    } else {\n      this.log(`Removed files: ${removedFileIDs.join(', ')}`);\n    }\n  }\n\n  removeFile(fileID, reason) {\n    if (reason === void 0) {\n      reason = null;\n    }\n\n    this.removeFiles([fileID], reason);\n  }\n\n  pauseResume(fileID) {\n    if (!this.getState().capabilities.resumableUploads || this.getFile(fileID).uploadComplete) {\n      return undefined;\n    }\n\n    const wasPaused = this.getFile(fileID).isPaused || false;\n    const isPaused = !wasPaused;\n    this.setFileState(fileID, {\n      isPaused\n    });\n    this.emit('upload-pause', fileID, isPaused);\n    return isPaused;\n  }\n\n  pauseAll() {\n    const updatedFiles = { ...this.getState().files\n    };\n    const inProgressUpdatedFiles = Object.keys(updatedFiles).filter(file => {\n      return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;\n    });\n    inProgressUpdatedFiles.forEach(file => {\n      const updatedFile = { ...updatedFiles[file],\n        isPaused: true\n      };\n      updatedFiles[file] = updatedFile;\n    });\n    this.setState({\n      files: updatedFiles\n    });\n    this.emit('pause-all');\n  }\n\n  resumeAll() {\n    const updatedFiles = { ...this.getState().files\n    };\n    const inProgressUpdatedFiles = Object.keys(updatedFiles).filter(file => {\n      return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;\n    });\n    inProgressUpdatedFiles.forEach(file => {\n      const updatedFile = { ...updatedFiles[file],\n        isPaused: false,\n        error: null\n      };\n      updatedFiles[file] = updatedFile;\n    });\n    this.setState({\n      files: updatedFiles\n    });\n    this.emit('resume-all');\n  }\n\n  retryAll() {\n    const updatedFiles = { ...this.getState().files\n    };\n    const filesToRetry = Object.keys(updatedFiles).filter(file => {\n      return updatedFiles[file].error;\n    });\n    filesToRetry.forEach(file => {\n      const updatedFile = { ...updatedFiles[file],\n        isPaused: false,\n        error: null\n      };\n      updatedFiles[file] = updatedFile;\n    });\n    this.setState({\n      files: updatedFiles,\n      error: null\n    });\n    this.emit('retry-all', filesToRetry);\n\n    if (filesToRetry.length === 0) {\n      return Promise.resolve({\n        successful: [],\n        failed: []\n      });\n    }\n\n    const uploadID = _classPrivateFieldLooseBase(this, _createUpload)[_createUpload](filesToRetry, {\n      forceAllowNewUpload: true // create new upload even if allowNewUpload: false\n\n    });\n\n    return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);\n  }\n\n  cancelAll(_temp) {\n    let {\n      reason = 'user'\n    } = _temp === void 0 ? {} : _temp;\n    this.emit('cancel-all', {\n      reason\n    }); // Only remove existing uploads if user is canceling\n\n    if (reason === 'user') {\n      const {\n        files\n      } = this.getState();\n      const fileIDs = Object.keys(files);\n\n      if (fileIDs.length) {\n        this.removeFiles(fileIDs, 'cancel-all');\n      }\n\n      this.setState({\n        totalProgress: 0,\n        error: null,\n        recoveredState: null\n      });\n    }\n  }\n\n  retryUpload(fileID) {\n    this.setFileState(fileID, {\n      error: null,\n      isPaused: false\n    });\n    this.emit('upload-retry', fileID);\n\n    const uploadID = _classPrivateFieldLooseBase(this, _createUpload)[_createUpload]([fileID], {\n      forceAllowNewUpload: true // create new upload even if allowNewUpload: false\n\n    });\n\n    return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);\n  } // todo remove in next major. what is the point of the reset method when we have cancelAll or vice versa?\n\n\n  reset() {\n    this.cancelAll(...arguments);\n  }\n\n  logout() {\n    this.iteratePlugins(plugin => {\n      if (plugin.provider && plugin.provider.logout) {\n        plugin.provider.logout();\n      }\n    });\n  }\n\n  calculateProgress(file, data) {\n    if (file == null || !this.getFile(file.id)) {\n      this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`);\n      return;\n    } // bytesTotal may be null or zero; in that case we can't divide by it\n\n\n    const canHavePercentage = Number.isFinite(data.bytesTotal) && data.bytesTotal > 0;\n    this.setFileState(file.id, {\n      progress: { ...this.getFile(file.id).progress,\n        bytesUploaded: data.bytesUploaded,\n        bytesTotal: data.bytesTotal,\n        percentage: canHavePercentage ? Math.round(data.bytesUploaded / data.bytesTotal * 100) : 0\n      }\n    });\n    this.calculateTotalProgress();\n  }\n\n  calculateTotalProgress() {\n    // calculate total progress, using the number of files currently uploading,\n    // multiplied by 100 and the summ of individual progress of each file\n    const files = this.getFiles();\n    const inProgress = files.filter(file => {\n      return file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess;\n    });\n\n    if (inProgress.length === 0) {\n      this.emit('progress', 0);\n      this.setState({\n        totalProgress: 0\n      });\n      return;\n    }\n\n    const sizedFiles = inProgress.filter(file => file.progress.bytesTotal != null);\n    const unsizedFiles = inProgress.filter(file => file.progress.bytesTotal == null);\n\n    if (sizedFiles.length === 0) {\n      const progressMax = inProgress.length * 100;\n      const currentProgress = unsizedFiles.reduce((acc, file) => {\n        return acc + file.progress.percentage;\n      }, 0);\n      const totalProgress = Math.round(currentProgress / progressMax * 100);\n      this.setState({\n        totalProgress\n      });\n      return;\n    }\n\n    let totalSize = sizedFiles.reduce((acc, file) => {\n      return acc + file.progress.bytesTotal;\n    }, 0);\n    const averageSize = totalSize / sizedFiles.length;\n    totalSize += averageSize * unsizedFiles.length;\n    let uploadedSize = 0;\n    sizedFiles.forEach(file => {\n      uploadedSize += file.progress.bytesUploaded;\n    });\n    unsizedFiles.forEach(file => {\n      uploadedSize += averageSize * (file.progress.percentage || 0) / 100;\n    });\n    let totalProgress = totalSize === 0 ? 0 : Math.round(uploadedSize / totalSize * 100); // hot fix, because:\n    // uploadedSize ended up larger than totalSize, resulting in 1325% total\n\n    if (totalProgress > 100) {\n      totalProgress = 100;\n    }\n\n    this.setState({\n      totalProgress\n    });\n    this.emit('progress', totalProgress);\n  }\n  /**\n   * Registers listeners for all global actions, like:\n   * `error`, `file-removed`, `upload-progress`\n   */\n\n\n  updateOnlineStatus() {\n    const online = typeof window.navigator.onLine !== 'undefined' ? window.navigator.onLine : true;\n\n    if (!online) {\n      this.emit('is-offline');\n      this.info(this.i18n('noInternetConnection'), 'error', 0);\n      this.wasOffline = true;\n    } else {\n      this.emit('is-online');\n\n      if (this.wasOffline) {\n        this.emit('back-online');\n        this.info(this.i18n('connectedToInternet'), 'success', 3000);\n        this.wasOffline = false;\n      }\n    }\n  }\n\n  getID() {\n    return this.opts.id;\n  }\n  /**\n   * Registers a plugin with Core.\n   *\n   * @param {object} Plugin object\n   * @param {object} [opts] object with options to be passed to Plugin\n   * @returns {object} self for chaining\n   */\n  // eslint-disable-next-line no-shadow\n\n\n  use(Plugin, opts) {\n    if (typeof Plugin !== 'function') {\n      const msg = `Expected a plugin class, but got ${Plugin === null ? 'null' : typeof Plugin}.` + ' Please verify that the plugin was imported and spelled correctly.';\n      throw new TypeError(msg);\n    } // Instantiate\n\n\n    const plugin = new Plugin(this, opts);\n    const pluginId = plugin.id;\n\n    if (!pluginId) {\n      throw new Error('Your plugin must have an id');\n    }\n\n    if (!plugin.type) {\n      throw new Error('Your plugin must have a type');\n    }\n\n    const existsPluginAlready = this.getPlugin(pluginId);\n\n    if (existsPluginAlready) {\n      const msg = `Already found a plugin named '${existsPluginAlready.id}'. ` + `Tried to use: '${pluginId}'.\\n` + 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.';\n      throw new Error(msg);\n    }\n\n    if (Plugin.VERSION) {\n      this.log(`Using ${pluginId} v${Plugin.VERSION}`);\n    }\n\n    if (plugin.type in _classPrivateFieldLooseBase(this, _plugins)[_plugins]) {\n      _classPrivateFieldLooseBase(this, _plugins)[_plugins][plugin.type].push(plugin);\n    } else {\n      _classPrivateFieldLooseBase(this, _plugins)[_plugins][plugin.type] = [plugin];\n    }\n\n    plugin.install();\n    return this;\n  }\n  /**\n   * Find one Plugin by name.\n   *\n   * @param {string} id plugin id\n   * @returns {BasePlugin|undefined}\n   */\n\n\n  getPlugin(id) {\n    for (const plugins of Object.values(_classPrivateFieldLooseBase(this, _plugins)[_plugins])) {\n      const foundPlugin = plugins.find(plugin => plugin.id === id);\n      if (foundPlugin != null) return foundPlugin;\n    }\n\n    return undefined;\n  }\n\n  [_Symbol$for](type) {\n    return _classPrivateFieldLooseBase(this, _plugins)[_plugins][type];\n  }\n  /**\n   * Iterate through all `use`d plugins.\n   *\n   * @param {Function} method that will be run on each plugin\n   */\n\n\n  iteratePlugins(method) {\n    Object.values(_classPrivateFieldLooseBase(this, _plugins)[_plugins]).flat(1).forEach(method);\n  }\n  /**\n   * Uninstall and remove a plugin.\n   *\n   * @param {object} instance The plugin instance to remove.\n   */\n\n\n  removePlugin(instance) {\n    this.log(`Removing plugin ${instance.id}`);\n    this.emit('plugin-remove', instance);\n\n    if (instance.uninstall) {\n      instance.uninstall();\n    }\n\n    const list = _classPrivateFieldLooseBase(this, _plugins)[_plugins][instance.type]; // list.indexOf failed here, because Vue3 converted the plugin instance\n    // to a Proxy object, which failed the strict comparison test:\n    // obj !== objProxy\n\n\n    const index = list.findIndex(item => item.id === instance.id);\n\n    if (index !== -1) {\n      list.splice(index, 1);\n    }\n\n    const state = this.getState();\n    const updatedState = {\n      plugins: { ...state.plugins,\n        [instance.id]: undefined\n      }\n    };\n    this.setState(updatedState);\n  }\n  /**\n   * Uninstall all plugins and close down this Uppy instance.\n   */\n\n\n  close(_temp2) {\n    let {\n      reason\n    } = _temp2 === void 0 ? {} : _temp2;\n    this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`);\n    this.cancelAll({\n      reason\n    });\n\n    _classPrivateFieldLooseBase(this, _storeUnsubscribe)[_storeUnsubscribe]();\n\n    this.iteratePlugins(plugin => {\n      this.removePlugin(plugin);\n    });\n\n    if (typeof window !== 'undefined' && window.removeEventListener) {\n      window.removeEventListener('online', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);\n      window.removeEventListener('offline', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);\n    }\n  }\n\n  hideInfo() {\n    const {\n      info\n    } = this.getState();\n    this.setState({\n      info: info.slice(1)\n    });\n    this.emit('info-hidden');\n  }\n  /**\n   * Set info message in `state.info`, so that UI plugins like `Informer`\n   * can display the message.\n   *\n   * @param {string | object} message Message to be displayed by the informer\n   * @param {string} [type]\n   * @param {number} [duration]\n   */\n\n\n  info(message, type, duration) {\n    if (type === void 0) {\n      type = 'info';\n    }\n\n    if (duration === void 0) {\n      duration = 3000;\n    }\n\n    const isComplexMessage = typeof message === 'object';\n    this.setState({\n      info: [...this.getState().info, {\n        type,\n        message: isComplexMessage ? message.message : message,\n        details: isComplexMessage ? message.details : null\n      }]\n    });\n    setTimeout(() => this.hideInfo(), duration);\n    this.emit('info-visible');\n  }\n  /**\n   * Passes messages to a function, provided in `opts.logger`.\n   * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.\n   *\n   * @param {string|object} message to log\n   * @param {string} [type] optional `error` or `warning`\n   */\n\n\n  log(message, type) {\n    const {\n      logger\n    } = this.opts;\n\n    switch (type) {\n      case 'error':\n        logger.error(message);\n        break;\n\n      case 'warning':\n        logger.warn(message);\n        break;\n\n      default:\n        logger.debug(message);\n        break;\n    }\n  }\n  /**\n   * Restore an upload by its ID.\n   */\n\n\n  restore(uploadID) {\n    this.log(`Core: attempting to restore upload \"${uploadID}\"`);\n\n    if (!this.getState().currentUploads[uploadID]) {\n      _classPrivateFieldLooseBase(this, _removeUpload)[_removeUpload](uploadID);\n\n      return Promise.reject(new Error('Nonexistent upload'));\n    }\n\n    return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);\n  }\n  /**\n   * Create an upload for a bunch of files.\n   *\n   * @param {Array<string>} fileIDs File IDs to include in this upload.\n   * @returns {string} ID of this upload.\n   */\n\n\n  [_Symbol$for2]() {\n    return _classPrivateFieldLooseBase(this, _createUpload)[_createUpload](...arguments);\n  }\n\n  /**\n   * Add data to an upload's result object.\n   *\n   * @param {string} uploadID The ID of the upload.\n   * @param {object} data Data properties to add to the result object.\n   */\n  addResultData(uploadID, data) {\n    if (!_classPrivateFieldLooseBase(this, _getUpload)[_getUpload](uploadID)) {\n      this.log(`Not setting result for an upload that has been removed: ${uploadID}`);\n      return;\n    }\n\n    const {\n      currentUploads\n    } = this.getState();\n    const currentUpload = { ...currentUploads[uploadID],\n      result: { ...currentUploads[uploadID].result,\n        ...data\n      }\n    };\n    this.setState({\n      currentUploads: { ...currentUploads,\n        [uploadID]: currentUpload\n      }\n    });\n  }\n  /**\n   * Remove an upload, eg. if it has been canceled or completed.\n   *\n   * @param {string} uploadID The ID of the upload.\n   */\n\n\n  /**\n   * Start an upload for all the files that are not currently being uploaded.\n   *\n   * @returns {Promise}\n   */\n  upload() {\n    var _classPrivateFieldLoo;\n\n    if (!((_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _plugins)[_plugins].uploader) != null && _classPrivateFieldLoo.length)) {\n      this.log('No uploader type plugins are used', 'warning');\n    }\n\n    let {\n      files\n    } = this.getState();\n    const onBeforeUploadResult = this.opts.onBeforeUpload(files);\n\n    if (onBeforeUploadResult === false) {\n      return Promise.reject(new Error('Not starting the upload because onBeforeUpload returned false'));\n    }\n\n    if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {\n      files = onBeforeUploadResult; // Updating files in state, because uploader plugins receive file IDs,\n      // and then fetch the actual file object from state\n\n      this.setState({\n        files\n      });\n    }\n\n    return Promise.resolve().then(() => _classPrivateFieldLooseBase(this, _restricter)[_restricter].validateMinNumberOfFiles(files)).catch(err => {\n      _classPrivateFieldLooseBase(this, _informAndEmit)[_informAndEmit](err);\n\n      throw err;\n    }).then(() => {\n      if (!_classPrivateFieldLooseBase(this, _checkRequiredMetaFields)[_checkRequiredMetaFields](files)) {\n        throw new _Restricter.RestrictionError(this.i18n('missingRequiredMetaField'));\n      }\n    }).catch(err => {\n      // Doing this in a separate catch because we already emited and logged\n      // all the errors in `checkRequiredMetaFields` so we only throw a generic\n      // missing fields error here.\n      throw err;\n    }).then(() => {\n      const {\n        currentUploads\n      } = this.getState(); // get a list of files that are currently assigned to uploads\n\n      const currentlyUploadingFiles = Object.values(currentUploads).flatMap(curr => curr.fileIDs);\n      const waitingFileIDs = [];\n      Object.keys(files).forEach(fileID => {\n        const file = this.getFile(fileID); // if the file hasn't started uploading and hasn't already been assigned to an upload..\n\n        if (!file.progress.uploadStarted && currentlyUploadingFiles.indexOf(fileID) === -1) {\n          waitingFileIDs.push(file.id);\n        }\n      });\n\n      const uploadID = _classPrivateFieldLooseBase(this, _createUpload)[_createUpload](waitingFileIDs);\n\n      return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);\n    }).catch(err => {\n      this.emit('error', err);\n      this.log(err, 'error');\n      throw err;\n    });\n  }\n\n}\n\nfunction _informAndEmit2(error, file) {\n  const {\n    message,\n    details = ''\n  } = error;\n\n  if (error.isRestriction) {\n    this.emit('restriction-failed', file, error);\n  } else {\n    this.emit('error', error);\n  }\n\n  this.info({\n    message,\n    details\n  }, 'error', this.opts.infoTimeout);\n  this.log(`${message} ${details}`.trim(), 'error');\n}\n\nfunction _checkRequiredMetaFieldsOnFile2(file) {\n  const {\n    missingFields,\n    error\n  } = _classPrivateFieldLooseBase(this, _restricter)[_restricter].getMissingRequiredMetaFields(file);\n\n  if (missingFields.length > 0) {\n    this.setFileState(file.id, {\n      missingRequiredMetaFields: missingFields\n    });\n    this.log(error.message);\n    this.emit('restriction-failed', file, error);\n    return false;\n  }\n\n  return true;\n}\n\nfunction _checkRequiredMetaFields2(files) {\n  let success = true;\n\n  for (const file of Object.values(files)) {\n    if (!_classPrivateFieldLooseBase(this, _checkRequiredMetaFieldsOnFile)[_checkRequiredMetaFieldsOnFile](file)) {\n      success = false;\n    }\n  }\n\n  return success;\n}\n\nfunction _assertNewUploadAllowed2(file) {\n  const {\n    allowNewUpload\n  } = this.getState();\n\n  if (allowNewUpload === false) {\n    const error = new _Restricter.RestrictionError(this.i18n('noMoreFilesAllowed'));\n\n    _classPrivateFieldLooseBase(this, _informAndEmit)[_informAndEmit](error, file);\n\n    throw error;\n  }\n}\n\nfunction _checkAndCreateFileStateObject2(files, fileDescriptor) {\n  const fileType = getFileType(fileDescriptor);\n  const fileName = getFileName(fileType, fileDescriptor);\n  const fileExtension = getFileNameAndExtension(fileName).extension;\n  const isRemote = Boolean(fileDescriptor.isRemote);\n  const fileID = generateFileID({ ...fileDescriptor,\n    type: fileType\n  });\n\n  if (this.checkIfFileAlreadyExists(fileID)) {\n    const error = new _Restricter.RestrictionError(this.i18n('noDuplicates', {\n      fileName\n    }));\n\n    _classPrivateFieldLooseBase(this, _informAndEmit)[_informAndEmit](error, fileDescriptor);\n\n    throw error;\n  }\n\n  const meta = fileDescriptor.meta || {};\n  meta.name = fileName;\n  meta.type = fileType; // `null` means the size is unknown.\n\n  const size = Number.isFinite(fileDescriptor.data.size) ? fileDescriptor.data.size : null;\n  let newFile = {\n    source: fileDescriptor.source || '',\n    id: fileID,\n    name: fileName,\n    extension: fileExtension || '',\n    meta: { ...this.getState().meta,\n      ...meta\n    },\n    type: fileType,\n    data: fileDescriptor.data,\n    progress: {\n      percentage: 0,\n      bytesUploaded: 0,\n      bytesTotal: size,\n      uploadComplete: false,\n      uploadStarted: null\n    },\n    size,\n    isRemote,\n    remote: fileDescriptor.remote || '',\n    preview: fileDescriptor.preview\n  };\n  const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(newFile, files);\n\n  if (onBeforeFileAddedResult === false) {\n    // Don\u2019t show UI info for this error, as it should be done by the developer\n    const error = new _Restricter.RestrictionError('Cannot add the file because onBeforeFileAdded returned false.');\n    this.emit('restriction-failed', fileDescriptor, error);\n    throw error;\n  } else if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult !== null) {\n    newFile = onBeforeFileAddedResult;\n  }\n\n  try {\n    const filesArray = Object.keys(files).map(i => files[i]);\n\n    _classPrivateFieldLooseBase(this, _restricter)[_restricter].validate(newFile, filesArray);\n  } catch (err) {\n    _classPrivateFieldLooseBase(this, _informAndEmit)[_informAndEmit](err, newFile);\n\n    throw err;\n  }\n\n  return newFile;\n}\n\nfunction _startIfAutoProceed2() {\n  if (this.opts.autoProceed && !this.scheduledAutoProceed) {\n    this.scheduledAutoProceed = setTimeout(() => {\n      this.scheduledAutoProceed = null;\n      this.upload().catch(err => {\n        if (!err.isRestriction) {\n          this.log(err.stack || err.message || err);\n        }\n      });\n    }, 4);\n  }\n}\n\nfunction _addListeners2() {\n  /**\n   * @param {Error} error\n   * @param {object} [file]\n   * @param {object} [response]\n   */\n  const errorHandler = (error, file, response) => {\n    let errorMsg = error.message || 'Unknown error';\n\n    if (error.details) {\n      errorMsg += ` ${error.details}`;\n    }\n\n    this.setState({\n      error: errorMsg\n    });\n\n    if (file != null && file.id in this.getState().files) {\n      this.setFileState(file.id, {\n        error: errorMsg,\n        response\n      });\n    }\n  };\n\n  this.on('error', errorHandler);\n  this.on('upload-error', (file, error, response) => {\n    errorHandler(error, file, response);\n\n    if (typeof error === 'object' && error.message) {\n      const newError = new Error(error.message);\n      newError.details = error.message;\n\n      if (error.details) {\n        newError.details += ` ${error.details}`;\n      }\n\n      newError.message = this.i18n('failedToUpload', {\n        file: file == null ? void 0 : file.name\n      });\n\n      _classPrivateFieldLooseBase(this, _informAndEmit)[_informAndEmit](newError);\n    } else {\n      _classPrivateFieldLooseBase(this, _informAndEmit)[_informAndEmit](error);\n    }\n  });\n  this.on('upload', () => {\n    this.setState({\n      error: null\n    });\n  });\n  this.on('upload-started', file => {\n    if (file == null || !this.getFile(file.id)) {\n      this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`);\n      return;\n    }\n\n    this.setFileState(file.id, {\n      progress: {\n        uploadStarted: Date.now(),\n        uploadComplete: false,\n        percentage: 0,\n        bytesUploaded: 0,\n        bytesTotal: file.size\n      }\n    });\n  });\n  this.on('upload-progress', this.calculateProgress);\n  this.on('upload-success', (file, uploadResp) => {\n    if (file == null || !this.getFile(file.id)) {\n      this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`);\n      return;\n    }\n\n    const currentProgress = this.getFile(file.id).progress;\n    this.setFileState(file.id, {\n      progress: { ...currentProgress,\n        postprocess: _classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors].size > 0 ? {\n          mode: 'indeterminate'\n        } : null,\n        uploadComplete: true,\n        percentage: 100,\n        bytesUploaded: currentProgress.bytesTotal\n      },\n      response: uploadResp,\n      uploadURL: uploadResp.uploadURL,\n      isPaused: false\n    }); // Remote providers sometimes don't tell us the file size,\n    // but we can know how many bytes we uploaded once the upload is complete.\n\n    if (file.size == null) {\n      this.setFileState(file.id, {\n        size: uploadResp.bytesUploaded || currentProgress.bytesTotal\n      });\n    }\n\n    this.calculateTotalProgress();\n  });\n  this.on('preprocess-progress', (file, progress) => {\n    if (file == null || !this.getFile(file.id)) {\n      this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`);\n      return;\n    }\n\n    this.setFileState(file.id, {\n      progress: { ...this.getFile(file.id).progress,\n        preprocess: progress\n      }\n    });\n  });\n  this.on('preprocess-complete', file => {\n    if (file == null || !this.getFile(file.id)) {\n      this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`);\n      return;\n    }\n\n    const files = { ...this.getState().files\n    };\n    files[file.id] = { ...files[file.id],\n      progress: { ...files[file.id].progress\n      }\n    };\n    delete files[file.id].progress.preprocess;\n    this.setState({\n      files\n    });\n  });\n  this.on('postprocess-progress', (file, progress) => {\n    if (file == null || !this.getFile(file.id)) {\n      this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`);\n      return;\n    }\n\n    this.setFileState(file.id, {\n      progress: { ...this.getState().files[file.id].progress,\n        postprocess: progress\n      }\n    });\n  });\n  this.on('postprocess-complete', file => {\n    if (file == null || !this.getFile(file.id)) {\n      this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`);\n      return;\n    }\n\n    const files = { ...this.getState().files\n    };\n    files[file.id] = { ...files[file.id],\n      progress: { ...files[file.id].progress\n      }\n    };\n    delete files[file.id].progress.postprocess;\n    this.setState({\n      files\n    });\n  });\n  this.on('restored', () => {\n    // Files may have changed--ensure progress is still accurate.\n    this.calculateTotalProgress();\n  });\n  this.on('dashboard:file-edit-complete', file => {\n    if (file) {\n      _classPrivateFieldLooseBase(this, _checkRequiredMetaFieldsOnFile)[_checkRequiredMetaFieldsOnFile](file);\n    }\n  }); // show informer if offline\n\n  if (typeof window !== 'undefined' && window.addEventListener) {\n    window.addEventListener('online', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);\n    window.addEventListener('offline', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);\n    setTimeout(_classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus], 3000);\n  }\n}\n\nfunction _createUpload2(fileIDs, opts) {\n  if (opts === void 0) {\n    opts = {};\n  }\n\n  // uppy.retryAll sets this to true \u2014 when retrying we want to ignore `allowNewUpload: false`\n  const {\n    forceAllowNewUpload = false\n  } = opts;\n  const {\n    allowNewUpload,\n    currentUploads\n  } = this.getState();\n\n  if (!allowNewUpload && !forceAllowNewUpload) {\n    throw new Error('Cannot create a new upload: already uploading.');\n  }\n\n  const uploadID = (0, _nonSecure.nanoid)();\n  this.emit('upload', {\n    id: uploadID,\n    fileIDs\n  });\n  this.setState({\n    allowNewUpload: this.opts.allowMultipleUploadBatches !== false && this.opts.allowMultipleUploads !== false,\n    currentUploads: { ...currentUploads,\n      [uploadID]: {\n        fileIDs,\n        step: 0,\n        result: {}\n      }\n    }\n  });\n  return uploadID;\n}\n\nfunction _getUpload2(uploadID) {\n  const {\n    currentUploads\n  } = this.getState();\n  return currentUploads[uploadID];\n}\n\nfunction _removeUpload2(uploadID) {\n  const currentUploads = { ...this.getState().currentUploads\n  };\n  delete currentUploads[uploadID];\n  this.setState({\n    currentUploads\n  });\n}\n\nasync function _runUpload2(uploadID) {\n  let {\n    currentUploads\n  } = this.getState();\n  let currentUpload = currentUploads[uploadID];\n  const restoreStep = currentUpload.step || 0;\n  const steps = [..._classPrivateFieldLooseBase(this, _preProcessors)[_preProcessors], ..._classPrivateFieldLooseBase(this, _uploaders)[_uploaders], ..._classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors]];\n\n  try {\n    for (let step = restoreStep; step < steps.length; step++) {\n      if (!currentUpload) {\n        break;\n      }\n\n      const fn = steps[step];\n      const updatedUpload = { ...currentUpload,\n        step\n      };\n      this.setState({\n        currentUploads: { ...currentUploads,\n          [uploadID]: updatedUpload\n        }\n      }); // TODO give this the `updatedUpload` object as its only parameter maybe?\n      // Otherwise when more metadata may be added to the upload this would keep getting more parameters\n\n      await fn(updatedUpload.fileIDs, uploadID); // Update currentUpload value in case it was modified asynchronously.\n\n      currentUploads = this.getState().currentUploads;\n      currentUpload = currentUploads[uploadID];\n    }\n  } catch (err) {\n    _classPrivateFieldLooseBase(this, _removeUpload)[_removeUpload](uploadID);\n\n    throw err;\n  } // Set result data.\n\n\n  if (currentUpload) {\n    // Mark postprocessing step as complete if necessary; this addresses a case where we might get\n    // stuck in the postprocessing UI while the upload is fully complete.\n    // If the postprocessing steps do not do any work, they may not emit postprocessing events at\n    // all, and never mark the postprocessing as complete. This is fine on its own but we\n    // introduced code in the @uppy/core upload-success handler to prepare postprocessing progress\n    // state if any postprocessors are registered. That is to avoid a \"flash of completed state\"\n    // before the postprocessing plugins can emit events.\n    //\n    // So, just in case an upload with postprocessing plugins *has* completed *without* emitting\n    // postprocessing completion, we do it instead.\n    currentUpload.fileIDs.forEach(fileID => {\n      const file = this.getFile(fileID);\n\n      if (file && file.progress.postprocess) {\n        this.emit('postprocess-complete', file);\n      }\n    });\n    const files = currentUpload.fileIDs.map(fileID => this.getFile(fileID));\n    const successful = files.filter(file => !file.error);\n    const failed = files.filter(file => file.error);\n    await this.addResultData(uploadID, {\n      successful,\n      failed,\n      uploadID\n    }); // Update currentUpload value in case it was modified asynchronously.\n\n    currentUploads = this.getState().currentUploads;\n    currentUpload = currentUploads[uploadID];\n  } // Emit completion events.\n  // This is in a separate function so that the `currentUploads` variable\n  // always refers to the latest state. In the handler right above it refers\n  // to an outdated object without the `.result` property.\n\n\n  let result;\n\n  if (currentUpload) {\n    result = currentUpload.result;\n    this.emit('complete', result);\n\n    _classPrivateFieldLooseBase(this, _removeUpload)[_removeUpload](uploadID);\n  }\n\n  if (result == null) {\n    this.log(`Not setting result for an upload that has been removed: ${uploadID}`);\n  }\n\n  return result;\n}\n\nUppy.VERSION = packageJson.version;\nmodule.exports = Uppy;", "/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n", "import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {import('./index').ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tif (node && node.parentNode) node.parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n", "import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n", "import { slice } from './util';\nimport options from './options';\nimport { NULL, UNDEFINED } from './constants';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array<import('.').ComponentChildren>} [children] The children of the\n * virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != NULL) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === UNDEFINED) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, NULL);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {import('./internal').VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: NULL,\n\t\t_parent: NULL,\n\t\t_depth: 0,\n\t\t_dom: NULL,\n\t\t_component: NULL,\n\t\tconstructor: UNDEFINED,\n\t\t_original: original == NULL ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == NULL && options.vnode != NULL) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: NULL };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != NULL && vnode.constructor === UNDEFINED;\n", "import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE, NULL } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != NULL && this._nextState != this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == NULL) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](https://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == NULL) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: NULL;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != NULL && sibling._dom != NULL) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : NULL;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tif (component._parentDom && component._dirty) {\n\t\tlet oldVNode = component._vnode,\n\t\t\toldDom = oldVNode._dom,\n\t\t\tcommitQueue = [],\n\t\t\trefQueue = [],\n\t\t\tnewVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.namespaceURI,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : NULL,\n\t\t\tcommitQueue,\n\t\t\toldDom == NULL ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\t\toldVNode._dom = oldVNode._parent = null;\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != NULL && vnode._component != NULL) {\n\t\tvnode._dom = vnode._component.base = NULL;\n\t\tvnode._children.some(child => {\n\t\t\tif (child != NULL && child._dom != NULL) {\n\t\t\t\treturn (vnode._dom = vnode._component.base = child._dom);\n\t\t\t}\n\t\t});\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array<import('./internal').Component>}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce != options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {import('./internal').Component} a\n * @param {import('./internal').Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\ttry {\n\t\tlet c,\n\t\t\tl = 1;\n\n\t\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t\t// process() calls from getting scheduled while `queue` is still being consumed.\n\t\twhile (rerenderQueue.length) {\n\t\t\t// Keep the rerender queue sorted by (depth, insertion order). The queue\n\t\t\t// will initially be sorted on the first iteration only if it has more than 1 item.\n\t\t\t//\n\t\t\t// New items can be added to the queue e.g. when rerendering a provider, so we want to\n\t\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t\t// single pass\n\t\t\tif (rerenderQueue.length > l) {\n\t\t\t\trerenderQueue.sort(depthSort);\n\t\t\t}\n\n\t\t\tc = rerenderQueue.shift();\n\t\t\tl = rerenderQueue.length;\n\n\t\t\trenderComponent(c);\n\t\t}\n\t} finally {\n\t\trerenderQueue.length = process._rerenderCount = 0;\n\t}\n}\n\nprocess._rerenderCount = 0;\n", "import { IS_NON_DIMENSIONAL, NULL, SVG_NAMESPACE } from '../constants';\nimport options from '../options';\n\n// Per-instance unique key for event clock stamps. Each Preact copy on the page\n// gets its own random suffix so that `_dispatched` / `_attached` properties on\n// shared event objects and handler functions cannot collide across instances.\n// ~1 in 60M collision odds - if you have that many praect versions on the page,\n// you deserve some weird bugs.\n// In 11 we can replace this with a\n// Symbol\nlet _id = Math.random().toString(8),\n\tEVENT_DISPATCHED = '__d' + _id,\n\tEVENT_ATTACHED = '__a' + _id;\n\nfunction setStyle(style, key, value) {\n\tif (key[0] == '-') {\n\t\tstyle.setProperty(key, value == NULL ? '' : value);\n\t} else if (value == NULL) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\nconst CAPTURE_REGEX = /(PointerCapture)$|Capture$/i;\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {string} namespace Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, namespace) {\n\tlet useCapture;\n\n\to: if (name == 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] != oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] == 'o' && name[1] == 'n') {\n\t\tuseCapture = name != (name = name.replace(CAPTURE_REGEX, '$1'));\n\t\tconst lowerCaseName = name.toLowerCase();\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (lowerCaseName in dom || name == 'onFocusOut' || name == 'onFocusIn')\n\t\t\tname = lowerCaseName.slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue[EVENT_ATTACHED] = eventClock;\n\t\t\t\tdom.addEventListener(\n\t\t\t\t\tname,\n\t\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\t\tuseCapture\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue[EVENT_ATTACHED] = oldValue[EVENT_ATTACHED];\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (namespace == SVG_NAMESPACE) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname != 'popover' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == NULL ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != NULL && (value !== false || name[4] == '-')) {\n\t\t\tdom.setAttribute(name, name == 'popover' && value == true ? '' : value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {import('../internal').PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e[EVENT_DISPATCHED] == NULL) {\n\t\t\t\te[EVENT_DISPATCHED] = eventClock++;\n\n\t\t\t\t// When `e[EVENT_DISPATCHED]` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e[EVENT_DISPATCHED] < eventHandler[EVENT_ATTACHED]) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n", "import { enqueueRender } from './component';\nimport { NULL } from './constants';\n\nexport let i = 0;\n\nexport function createContext(defaultValue) {\n\tfunction Context(props) {\n\t\tif (!this.getChildContext) {\n\t\t\t/** @type {Set<import('./internal').Component> | null} */\n\t\t\tlet subs = new Set();\n\t\t\tlet ctx = {};\n\t\t\tctx[Context._id] = this;\n\n\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\tthis.componentWillUnmount = () => {\n\t\t\t\tsubs = NULL;\n\t\t\t};\n\n\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t// @ts-expect-error even\n\t\t\t\tif (this.props.value != _props.value) {\n\t\t\t\t\tsubs.forEach(c => {\n\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.sub = c => {\n\t\t\t\tsubs.add(c);\n\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\tif (subs) {\n\t\t\t\t\t\tsubs.delete(c);\n\t\t\t\t\t}\n\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\n\t\treturn props.children;\n\t}\n\n\tContext._id = '__cC' + i++;\n\tContext._defaultValue = defaultValue;\n\n\t/** @type {import('./internal').FunctionComponent} */\n\tContext.Consumer = (props, contextValue) => {\n\t\treturn props.children(contextValue);\n\t};\n\n\t// we could also get rid of _contextRef entirely\n\tContext.Provider =\n\t\tContext._contextRef =\n\t\tContext.Consumer.contextType =\n\t\t\tContext;\n\n\treturn Context;\n}\n", "import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport {\n\tEMPTY_OBJ,\n\tEMPTY_ARR,\n\tINSERT_VNODE,\n\tMATCHED,\n\tUNDEFINED,\n\tNULL\n} from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\toldDom = constructNewChildrenArray(\n\t\tnewParentVNode,\n\t\trenderResult,\n\t\toldChildren,\n\t\toldDom,\n\t\tnewChildrenLength\n\t);\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (childVNode == NULL) continue;\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\toldVNode =\n\t\t\t(childVNode._index != -1 && oldChildren[childVNode._index]) || EMPTY_OBJ;\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tlet result = diff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, NULL, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == NULL && newDom != NULL) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tif (childVNode._flags & INSERT_VNODE) {\n\t\t\toldDom = insert(childVNode, oldDom, parentDom);\n\n\t\t\t// When a matched VNode is physically moved via INSERT_VNODE, its old\n\t\t\t// _dom pointer becomes a stale positional reference. Clear it so that\n\t\t\t// getDomSibling (called from nested diffs) won't return this stale\n\t\t\t// reference and mis-place subsequent DOM nodes. See #5065.\n\t\t\tif (oldVNode._dom) {\n\t\t\t\toldVNode._dom = NULL;\n\t\t\t}\n\t\t} else if (typeof childVNode.type == 'function' && result !== UNDEFINED) {\n\t\t\toldDom = result;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(\n\tnewParentVNode,\n\trenderResult,\n\toldChildren,\n\toldDom,\n\tnewChildrenLength\n) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = new Array(newChildrenLength);\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == NULL ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tnewParentVNode._children[i] = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t// If this newVNode is being reused (e.g. <div>{reuse}{reuse}</div>) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tNULL,\n\t\t\t\tchildVNode,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (childVNode.constructor === UNDEFINED && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t//   const reuse = <div />\n\t\t\t//   <div>{reuse}<span />{reuse}</div>\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : NULL,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tnewParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tconst matchingIndex = (childVNode._index = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t));\n\n\t\toldVNode = NULL;\n\t\tif (matchingIndex != -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original == null\n\t\tconst isMounting = oldVNode == NULL || oldVNode._original == NULL;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\t// When the array of children is growing we need to decrease the skew\n\t\t\t\t// as we are adding a new element to the array.\n\t\t\t\t// Example:\n\t\t\t\t// [1, 2, 3] --> [0, 1, 2, 3]\n\t\t\t\t// oldChildren   newChildren\n\t\t\t\t//\n\t\t\t\t// The new element is at index 0, so our skew is 0,\n\t\t\t\t// we need to decrease the skew as we are adding a new element.\n\t\t\t\t// The decrease will cause us to compare the element at position 1\n\t\t\t\t// with value 1 with the element at position 0 with value 0.\n\t\t\t\t//\n\t\t\t\t// A linear concept is applied when the array is shrinking,\n\t\t\t\t// if the length is unchanged we can assume that no skew\n\t\t\t\t// changes are needed.\n\t\t\t\tif (newChildrenLength > oldChildrenLength) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else if (newChildrenLength < oldChildrenLength) {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex != skewedIndex) {\n\t\t\t// When we move elements around i.e. [0, 1, 2] --> [1, 0, 2]\n\t\t\t// --> we diff 1, we find it at position 1 while our skewed index is 0 and our skew is 0\n\t\t\t//     we set the skew to 1 as we found an offset.\n\t\t\t// --> we diff 0, we find it at position 0 while our skewed index is at 2 and our skew is 1\n\t\t\t//     this makes us increase the skew again.\n\t\t\t// --> we diff 2, we find it at position 2 while our skewed index is at 4 and our skew is 2\n\t\t\t//\n\t\t\t// this becomes an optimization question where currently we see a 1 element offset as an insertion\n\t\t\t// or deletion i.e. we optimize for [0, 1, 2] --> [9, 0, 1, 2]\n\t\t\t// while a more than 1 offset we see as a swap.\n\t\t\t// We could probably build heuristics for having an optimized course of action here as well, but\n\t\t\t// might go at the cost of some bytes.\n\t\t\t//\n\t\t\t// If we wanted to optimize for i.e. only swaps we'd just do the last two code-branches and have\n\t\t\t// only the first item be a re-scouting and all the others fall in their skewed counter-part.\n\t\t\t// We could also further optimize for swaps\n\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\tskew--;\n\t\t\t} else if (matchingIndex == skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else {\n\t\t\t\tif (matchingIndex > skewedIndex) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\n\t\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t\t// match the new skew index (i + new skew)\n\t\t\t\t// In the former two branches we know that it matches after skewing\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != NULL && (oldVNode._flags & MATCHED) == 0) {\n\t\t\t\tif (oldVNode._dom == oldDom) {\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tif (oldDom && parentVNode.type && !oldDom.parentNode) {\n\t\t\toldDom = getDomSibling(parentVNode);\n\t\t}\n\t\toldDom = parentDom.insertBefore(parentVNode._dom, oldDom || NULL);\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != NULL && oldDom.nodeType == 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == NULL || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet oldVNode = oldChildren[skewedIndex];\n\tconst matched = oldVNode != NULL && (oldVNode._flags & MATCHED) == 0;\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\t//\n\t// If there is an unkeyed functional VNode, that isn't a built-in like our Fragment,\n\t// we should not search as we risk re-using state of an unrelated VNode. (reverted for now)\n\tlet shouldSearch =\n\t\t// (typeof type != 'function' || type === Fragment || key) &&\n\t\tremainingOldChildren > (matched ? 1 : 0);\n\n\tif (\n\t\t(oldVNode === NULL && key == null) ||\n\t\t(matched && key == oldVNode.key && type == oldVNode.type)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\tlet x = skewedIndex - 1;\n\t\tlet y = skewedIndex + 1;\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tconst childIndex = x >= 0 ? x-- : y++;\n\t\t\toldVNode = oldChildren[childIndex];\n\t\t\tif (\n\t\t\t\toldVNode != NULL &&\n\t\t\t\t(oldVNode._flags & MATCHED) == 0 &&\n\t\t\t\tkey == oldVNode.key &&\n\t\t\t\ttype == oldVNode.type\n\t\t\t) {\n\t\t\t\treturn childIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n", "import {\n\tEMPTY_ARR,\n\tEMPTY_OBJ,\n\tMATH_NAMESPACE,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tNULL,\n\tRESET_MODE,\n\tSVG_NAMESPACE,\n\tUNDEFINED,\n\tXHTML_NAMESPACE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * @template {any} T\n * @typedef {import('../internal').Ref<T>} Ref<T>\n */\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== UNDEFINED) return NULL;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\tlet oldCommitQueueLength = commitQueue.length;\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\t\t\tconst isClassComponent = newType.prototype && newType.prototype.render;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif (isClassComponent) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (isClassComponent && c._nextState == NULL) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (isClassComponent && newType.getDerivedStateFromProps != NULL) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tc.componentWillMount != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidMount != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tnewVNode._original == oldVNode._original ||\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != NULL &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original != oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.some(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tEMPTY_ARR.push.apply(c._renderCallbacks, c._stateCallbacks);\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Skip over the retained subtree without traversing it; the\n\t\t\t\t\t// `result` branch in diffChildren picks this up as the next\n\t\t\t\t\t// oldDom.\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != NULL) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidUpdate != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif (isClassComponent) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tEMPTY_ARR.push.apply(c._renderCallbacks, c._stateCallbacks);\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != NULL) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != NULL) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet renderResult =\n\t\t\t\ttmp != NULL && tmp.type === Fragment && tmp.key == NULL\n\t\t\t\t\t? cloneNode(tmp.props.children)\n\t\t\t\t\t: tmp;\n\n\t\t\toldDom = diffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnamespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = NULL;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// We remove any componentDidMount, ...\n\t\t\t// that have been invalidated by us\n\t\t\t// intercepting the error.\n\t\t\tcommitQueue.length = oldCommitQueueLength;\n\t\t\tnewVNode._original = NULL;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != NULL) {\n\t\t\t\tif (e.then) {\n\t\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t\t: MODE_SUSPENDED;\n\n\t\t\t\t\twhile (oldDom && oldDom.nodeType == 8 && oldDom.nextSibling) {\n\t\t\t\t\t\toldDom = oldDom.nextSibling;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t\t} else if (excessDomChildren != NULL) {\n\t\t\t\t\tfor (let i = excessDomChildren.length; i--; ) {\n\t\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t}\n\n\t\t\tif (newVNode._children == NULL) {\n\t\t\t\tnewVNode._children = oldVNode._children || [];\n\t\t\t}\n\n\t\t\tif (!e.then) markAsForce(newVNode);\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == NULL &&\n\t\tnewVNode._original == oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\toldDom = newVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n\n\treturn newVNode._flags & MODE_SUSPENDED ? undefined : oldDom;\n}\n\nfunction markAsForce(vnode) {\n\tif (vnode) {\n\t\tif (vnode._component) vnode._component._force = true;\n\t\tif (vnode._children) vnode._children.some(markAsForce);\n\t}\n}\n\n/**\n * @param {Array<Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\nfunction cloneNode(node) {\n\tif (typeof node != 'object' || node == NULL || node._depth > 0) {\n\t\treturn node;\n\t}\n\n\tif (isArray(node)) {\n\t\treturn node.map(cloneNode);\n\t}\n\n\tif (node.constructor !== UNDEFINED) return null;\n\n\treturn assign({}, node);\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array<PreactElement>} excessDomChildren\n * @param {Array<Component>} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props || EMPTY_OBJ;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting namespaces when descending through the tree.\n\tif (nodeType == 'svg') namespace = SVG_NAMESPACE;\n\telse if (nodeType == 'math') namespace = MATH_NAMESPACE;\n\telse if (!namespace) namespace = XHTML_NAMESPACE;\n\n\tif (excessDomChildren != NULL) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value == !!nodeType &&\n\t\t\t\t(nodeType ? value.localName == nodeType : value.nodeType == 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == NULL) {\n\t\tif (nodeType == NULL) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tdom = document.createElementNS(\n\t\t\tnamespace,\n\t\t\tnodeType,\n\t\t\tnewProps.is && newProps\n\t\t);\n\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tif (isHydrating) {\n\t\t\tif (options._hydrationMismatch)\n\t\t\t\toptions._hydrationMismatch(newVNode, excessDomChildren);\n\t\t\tisHydrating = false;\n\t\t}\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = NULL;\n\t}\n\n\tif (nodeType == NULL) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data != newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren =\n\t\t\tnodeType == 'textarea' && newProps.defaultValue != NULL\n\t\t\t\t? NULL\n\t\t\t\t: excessDomChildren && slice.call(dom.childNodes);\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != NULL) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (\n\t\t\t\ti != 'children' &&\n\t\t\t\t!(i in newProps) &&\n\t\t\t\t!(i == 'value' && 'defaultValue' in newProps) &&\n\t\t\t\t!(i == 'checked' && 'defaultChecked' in newProps)\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, NULL, value, namespace);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html != oldHtml.__html && newHtml.__html != dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnewVNode.type == 'template' ? dom.content : dom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnodeType == 'foreignObject' ? XHTML_NAMESPACE : namespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating || nodeType == 'textarea') {\n\t\t\ti = 'value';\n\t\t\tif (nodeType == 'progress' && inputValue == NULL) {\n\t\t\t\tdom.removeAttribute('value');\n\t\t\t} else if (\n\t\t\t\tinputValue != UNDEFINED &&\n\t\t\t\t// #2756 For the <progress>-element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType == 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix <select> value not being updated.\n\t\t\t\t\t// To avoid a stale select value we need to set the option.value\n\t\t\t\t\t// again, which triggers IE11 to re-evaluate the select value\n\t\t\t\t\t(nodeType == 'option' && inputValue != oldProps[i]))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, inputValue, oldProps[i], namespace);\n\t\t\t}\n\n\t\t\ti = 'checked';\n\t\t\tif (checked != UNDEFINED && checked != dom[i]) {\n\t\t\t\tsetProperty(dom, i, checked, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {Ref<any> & { _unmount?: unknown }} ref\n * @param {any} value\n * @param {VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') {\n\t\t\tlet hasRefUnmount = typeof ref._unmount == 'function';\n\t\t\tif (hasRefUnmount) {\n\t\t\t\t// @ts-ignore TS doesn't like moving narrowing checks into variables\n\t\t\t\tref._unmount();\n\t\t\t}\n\n\t\t\tif (!hasRefUnmount || value != NULL) {\n\t\t\t\t// Store the cleanup function on the function\n\t\t\t\t// instance object itself to avoid shape\n\t\t\t\t// transitioning vnode\n\t\t\t\tref._unmount = ref(value);\n\t\t\t}\n\t\t} else ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {VNode} vnode The virtual node to unmount\n * @param {VNode} parentVNode The parent of the VNode that initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current == vnode._dom) {\n\t\t\tapplyRef(r, NULL, parentVNode);\n\t\t}\n\t}\n\n\tif ((r = vnode._component) != NULL) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = r._globalContext = NULL;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) {\n\t\t\t\tunmount(\n\t\t\t\t\tr[i],\n\t\t\t\t\tparentVNode,\n\t\t\t\t\tskipRemove || typeof vnode.type != 'function'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!skipRemove) {\n\t\tremoveNode(vnode._dom);\n\t}\n\n\tvnode._component = vnode._parent = vnode._dom = UNDEFINED;\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n", "import { EMPTY_OBJ, NULL } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\nimport { slice } from './util';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\t// https://github.com/preactjs/preact/issues/3794\n\tif (parentDom == document) {\n\t\tparentDom = document.documentElement;\n\t}\n\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode == 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? NULL\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = ((!isHydrating && replaceNode) || parentDom)._children =\n\t\tcreateElement(Fragment, NULL, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [],\n\t\trefQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.namespaceURI,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t\t? NULL\n\t\t\t\t: parentDom.firstChild\n\t\t\t\t\t? slice.call(parentDom.childNodes)\n\t\t\t\t\t: NULL,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t\t? oldVNode._dom\n\t\t\t\t: parentDom.firstChild,\n\t\tisHydrating,\n\t\trefQueue\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode, refQueue);\n\n\t// The live children are tracked on _children after diffing.\n\tvnode.props.children = NULL;\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n", "import { assign, slice } from './util';\nimport { createVNode } from './create-element';\nimport { NULL, UNDEFINED } from './constants';\n\n/**\n * Clones the given VNode, optionally adding attributes/props and replacing its\n * children.\n * @param {import('./internal').VNode} vnode The virtual DOM element to clone\n * @param {object} props Attributes/props to add when cloning\n * @param {Array<import('./internal').ComponentChildren>} rest Any additional arguments will be used\n * as replacement children.\n * @returns {import('./internal').VNode}\n */\nexport function cloneElement(vnode, props, children) {\n\tlet normalizedProps = assign({}, vnode.props),\n\t\tkey,\n\t\tref,\n\t\ti;\n\n\tlet defaultProps;\n\n\tif (vnode.type && vnode.type.defaultProps) {\n\t\tdefaultProps = vnode.type.defaultProps;\n\t}\n\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse if (props[i] === UNDEFINED && defaultProps != UNDEFINED) {\n\t\t\tnormalizedProps[i] = defaultProps[i];\n\t\t} else {\n\t\t\tnormalizedProps[i] = props[i];\n\t\t}\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\treturn createVNode(\n\t\tvnode.type,\n\t\tnormalizedProps,\n\t\tkey || vnode.key,\n\t\tref || vnode.ref,\n\t\tNULL\n\t);\n}\n", "import { NULL } from '../constants';\n\n/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw the error that was caught (except\n * for unmounting when this parameter is the highest parent that was being\n * unmounted)\n * @param {import('../internal').VNode} [oldVNode]\n * @param {import('../internal').ErrorInfo} [errorInfo]\n */\nexport function _catchError(error, vnode, oldVNode, errorInfo) {\n\t/** @type {import('../internal').Component} */\n\tlet component,\n\t\t/** @type {import('../internal').ComponentType} */\n\t\tctor,\n\t\t/** @type {boolean} */\n\t\thandled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != NULL) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != NULL) {\n\t\t\t\t\tcomponent.componentDidCatch(error, errorInfo || {});\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n", "\"use strict\";\n\nfunction isDOMElement(obj) {\n  return (obj == null ? void 0 : obj.nodeType) === Node.ELEMENT_NODE;\n}\n\n/**\n * Check if an object is a DOM element. Duck-typing based on `nodeType`.\n *\n * @param {*} obj\n */\nmodule.exports = isDOMElement;", "\"use strict\";\n\nconst isDOMElement = require(\"./isDOMElement.js\");\n/**\n * Find a DOM element.\n *\n * @param {Node|string} element\n * @returns {Node|null}\n */\n\n\nfunction findDOMElement(element, context) {\n  if (context === void 0) {\n    context = document;\n  }\n\n  if (typeof element === 'string') {\n    return context.querySelector(element);\n  }\n\n  if (isDOMElement(element)) {\n    return element;\n  }\n\n  return null;\n}\n\nmodule.exports = findDOMElement;", "\"use strict\";\n\n/**\n * Get the declared text direction for an element.\n *\n * @param {Node} element\n * @returns {string|undefined}\n */\nfunction getTextDirection(element) {\n  var _element;\n\n  // There is another way to determine text direction using getComputedStyle(), as done here:\n  // https://github.com/pencil-js/text-direction/blob/2a235ce95089b3185acec3b51313cbba921b3811/text-direction.js\n  //\n  // We do not use that approach because we are interested specifically in the _declared_ text direction.\n  // If no text direction is declared, we have to provide our own explicit text direction so our\n  // bidirectional CSS style sheets work.\n  while (element && !element.dir) {\n    // eslint-disable-next-line no-param-reassign\n    element = element.parentNode;\n  }\n\n  return (_element = element) == null ? void 0 : _element.dir;\n}\n\nmodule.exports = getTextDirection;", "\"use strict\";\n\n/**\n * Core plugin logic that all plugins share.\n *\n * BasePlugin does not contain DOM rendering so it can be used for plugins\n * without a user interface.\n *\n * See `Plugin` for the extended version with Preact rendering for interfaces.\n */\nconst Translator = require(\"@uppy/utils/lib/Translator\");\n\nclass BasePlugin {\n  constructor(uppy, opts) {\n    if (opts === void 0) {\n      opts = {};\n    }\n\n    this.uppy = uppy;\n    this.opts = opts;\n  }\n\n  getPluginState() {\n    const {\n      plugins\n    } = this.uppy.getState();\n    return plugins[this.id] || {};\n  }\n\n  setPluginState(update) {\n    const {\n      plugins\n    } = this.uppy.getState();\n    this.uppy.setState({\n      plugins: { ...plugins,\n        [this.id]: { ...plugins[this.id],\n          ...update\n        }\n      }\n    });\n  }\n\n  setOptions(newOpts) {\n    this.opts = { ...this.opts,\n      ...newOpts\n    };\n    this.setPluginState(); // so that UI re-renders with new options\n\n    this.i18nInit();\n  }\n\n  i18nInit() {\n    const translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale]);\n    this.i18n = translator.translate.bind(translator);\n    this.i18nArray = translator.translateArray.bind(translator);\n    this.setPluginState(); // so that UI re-renders and we see the updated locale\n  }\n  /**\n   * Extendable methods\n   * ==================\n   * These methods are here to serve as an overview of the extendable methods as well as\n   * making them not conditional in use, such as `if (this.afterUpdate)`.\n   */\n  // eslint-disable-next-line class-methods-use-this\n\n\n  addTarget() {\n    throw new Error('Extend the addTarget method to add your plugin to another plugin\\'s target');\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  install() {} // eslint-disable-next-line class-methods-use-this\n\n\n  uninstall() {}\n  /**\n   * Called when plugin is mounted, whether in DOM or into another plugin.\n   * Needed because sometimes plugins are mounted separately/after `install`,\n   * so this.el and this.parent might not be available in `install`.\n   * This is the case with @uppy/react plugins, for example.\n   */\n\n\n  render() {\n    throw new Error('Extend the render method to add your plugin to a DOM element');\n  } // TODO: remove in the next major version. It's not feasible to\n  // try to use plugins with other frameworks.\n  // eslint-disable-next-line class-methods-use-this\n\n\n  update() {} // Called after every state update, after everything's mounted. Debounced.\n  // eslint-disable-next-line class-methods-use-this\n\n\n  afterUpdate() {}\n\n}\n\nmodule.exports = BasePlugin;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst findDOMElement = require(\"@uppy/utils/lib/findDOMElement\");\n\nconst getTextDirection = require(\"@uppy/utils/lib/getTextDirection\");\n\nconst BasePlugin = require(\"./BasePlugin.js\");\n/**\n * Defer a frequent call to the microtask queue.\n *\n * @param {() => T} fn\n * @returns {Promise<T>}\n */\n\n\nfunction debounce(fn) {\n  let calling = null;\n  let latestArgs = null;\n  return function () {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n\n    latestArgs = args;\n\n    if (!calling) {\n      calling = Promise.resolve().then(() => {\n        calling = null; // At this point `args` may be different from the most\n        // recent state, if multiple calls happened since this task\n        // was queued. So we use the `latestArgs`, which definitely\n        // is the most recent call.\n\n        return fn(...latestArgs);\n      });\n    }\n\n    return calling;\n  };\n}\n/**\n * UIPlugin is the extended version of BasePlugin to incorporate rendering with Preact.\n * Use this for plugins that need a user interface.\n *\n * For plugins without an user interface, see BasePlugin.\n */\n\n\nvar _updateUI = /*#__PURE__*/_classPrivateFieldLooseKey(\"updateUI\");\n\nclass UIPlugin extends BasePlugin {\n  constructor() {\n    super(...arguments);\n    Object.defineProperty(this, _updateUI, {\n      writable: true,\n      value: void 0\n    });\n  }\n\n  /**\n   * Check if supplied `target` is a DOM element or an `object`.\n   * If it\u2019s an object \u2014 target is a plugin, and we search `plugins`\n   * for a plugin with same name and return its target.\n   */\n  mount(target, plugin) {\n    const callerPluginName = plugin.id;\n    const targetElement = findDOMElement(target);\n\n    if (targetElement) {\n      this.isTargetDOMEl = true; // When target is <body> with a single <div> element,\n      // Preact thinks it\u2019s the Uppy root element in there when doing a diff,\n      // and destroys it. So we are creating a fragment (could be empty div)\n\n      const uppyRootElement = document.createElement('div');\n      uppyRootElement.classList.add('uppy-Root'); // API for plugins that require a synchronous rerender.\n\n      _classPrivateFieldLooseBase(this, _updateUI)[_updateUI] = debounce(state => {\n        // plugin could be removed, but this.rerender is debounced below,\n        // so it could still be called even after uppy.removePlugin or uppy.close\n        // hence the check\n        if (!this.uppy.getPlugin(this.id)) return;\n        (0, _preact.render)(this.render(state), uppyRootElement);\n        this.afterUpdate();\n      });\n      this.uppy.log(`Installing ${callerPluginName} to a DOM element '${target}'`);\n\n      if (this.opts.replaceTargetContent) {\n        // Doing render(h(null), targetElement), which should have been\n        // a better way, since because the component might need to do additional cleanup when it is removed,\n        // stopped working \u2014 Preact just adds null into target, not replacing\n        targetElement.innerHTML = '';\n      }\n\n      (0, _preact.render)(this.render(this.uppy.getState()), uppyRootElement);\n      this.el = uppyRootElement;\n      targetElement.appendChild(uppyRootElement); // Set the text direction if the page has not defined one.\n\n      uppyRootElement.dir = this.opts.direction || getTextDirection(uppyRootElement) || 'ltr';\n      this.onMount();\n      return this.el;\n    }\n\n    let targetPlugin;\n\n    if (typeof target === 'object' && target instanceof UIPlugin) {\n      // Targeting a plugin *instance*\n      targetPlugin = target;\n    } else if (typeof target === 'function') {\n      // Targeting a plugin type\n      const Target = target; // Find the target plugin instance.\n\n      this.uppy.iteratePlugins(p => {\n        if (p instanceof Target) {\n          targetPlugin = p;\n        }\n      });\n    }\n\n    if (targetPlugin) {\n      this.uppy.log(`Installing ${callerPluginName} to ${targetPlugin.id}`);\n      this.parent = targetPlugin;\n      this.el = targetPlugin.addTarget(plugin);\n      this.onMount();\n      return this.el;\n    }\n\n    this.uppy.log(`Not installing ${callerPluginName}`);\n    let message = `Invalid target option given to ${callerPluginName}.`;\n\n    if (typeof target === 'function') {\n      message += ' The given target is not a Plugin class. ' + 'Please check that you\\'re not specifying a React Component instead of a plugin. ' + 'If you are using @uppy/* packages directly, make sure you have only 1 version of @uppy/core installed: ' + 'run `npm ls @uppy/core` on the command line and verify that all the versions match and are deduped correctly.';\n    } else {\n      message += 'If you meant to target an HTML element, please make sure that the element exists. ' + 'Check that the <script> tag initializing Uppy is right before the closing </body> tag at the end of the page. ' + '(see https://github.com/transloadit/uppy/issues/1042)\\n\\n' + 'If you meant to target a plugin, please confirm that your `import` statements or `require` calls are correct.';\n    }\n\n    throw new Error(message);\n  }\n\n  update(state) {\n    if (this.el != null) {\n      var _classPrivateFieldLoo, _classPrivateFieldLoo2;\n\n      (_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _updateUI))[_updateUI]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2, state);\n    }\n  }\n\n  unmount() {\n    if (this.isTargetDOMEl) {\n      var _this$el;\n\n      (_this$el = this.el) == null ? void 0 : _this$el.remove();\n    }\n\n    this.onUnmount();\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  onMount() {} // eslint-disable-next-line class-methods-use-this\n\n\n  onUnmount() {}\n\n}\n\nmodule.exports = UIPlugin;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.Uppy = exports.UIPlugin = exports.BasePlugin = void 0;\nObject.defineProperty(exports, \"debugLogger\", {\n  enumerable: true,\n  get: function () {\n    return _loggers.debugLogger;\n  }\n});\n\nvar _loggers = require(\"./loggers.js\");\n\nmodule.exports = require('./Uppy.js');\n\nconst _0 = require(\"./UIPlugin.js\");\n\nexports.UIPlugin = _0;\n\nconst _1 = require(\"./BasePlugin.js\");\n\nexports.BasePlugin = _1;\n\n// TODO: remove all the following in the next major\n\n/* eslint-disable import/first */\nconst Uppy = require(\"./Uppy.js\");\n\nexports.Uppy = Uppy;\n\nconst UIPlugin = require(\"./UIPlugin.js\");\n\nconst BasePlugin = require(\"./BasePlugin.js\");\n\n// Backward compatibility: we want those to keep being accessible as static\n// properties of `Uppy` to avoid a breaking change.\nUppy.Uppy = Uppy;\nUppy.UIPlugin = UIPlugin;\nUppy.BasePlugin = BasePlugin;\nUppy.debugLogger = _loggers.debugLogger;", "\"use strict\";\n\nclass NetworkError extends Error {\n  constructor(error, xhr) {\n    if (xhr === void 0) {\n      xhr = null;\n    }\n\n    super(`This looks like a network error, the endpoint might be blocked by an internet provider or a firewall.`);\n    this.cause = error;\n    this.isNetworkError = true;\n    this.request = xhr;\n  }\n\n}\n\nmodule.exports = NetworkError;", "\"use strict\";\n\nconst NetworkError = require(\"./NetworkError.js\");\n/**\n * Wrapper around window.fetch that throws a NetworkError when appropriate\n */\n\n\nfunction fetchWithNetworkError() {\n  return fetch(...arguments).catch(err => {\n    if (err.name === 'AbortError') {\n      throw err;\n    } else {\n      throw new NetworkError(err);\n    }\n  });\n}\n\nmodule.exports = fetchWithNetworkError;", "\"use strict\";\n\nconst hasProperty = require(\"./hasProperty.js\");\n\nclass ErrorWithCause extends Error {\n  constructor(message, options) {\n    if (options === void 0) {\n      options = {};\n    }\n\n    super(message);\n    this.cause = options.cause;\n\n    if (this.cause && hasProperty(this.cause, 'isNetworkError')) {\n      this.isNetworkError = this.cause.isNetworkError;\n    }\n  }\n\n}\n\nmodule.exports = ErrorWithCause;", "'use strict';\n\nclass AuthError extends Error {\n  constructor() {\n    super('Authorization required');\n    this.name = 'AuthError';\n    this.isAuthError = true;\n  }\n\n}\n\nmodule.exports = AuthError;", "'use strict';\n\nlet _Symbol$for;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst fetchWithNetworkError = require(\"@uppy/utils/lib/fetchWithNetworkError\");\n\nconst ErrorWithCause = require(\"@uppy/utils/lib/ErrorWithCause\");\n\nconst AuthError = require(\"./AuthError.js\");\n\nconst packageJson = {\n  \"version\": \"2.2.2\"\n}; // Remove the trailing slash so we can always safely append /xyz.\n\nfunction stripSlash(url) {\n  return url.replace(/\\/$/, '');\n}\n\nasync function handleJSONResponse(res) {\n  if (res.status === 401) {\n    throw new AuthError();\n  }\n\n  const jsonPromise = res.json();\n\n  if (res.status < 200 || res.status > 300) {\n    let errMsg = `Failed request with status: ${res.status}. ${res.statusText}`;\n\n    try {\n      const errData = await jsonPromise;\n      errMsg = errData.message ? `${errMsg} message: ${errData.message}` : errMsg;\n      errMsg = errData.requestId ? `${errMsg} request-Id: ${errData.requestId}` : errMsg;\n    } finally {\n      // eslint-disable-next-line no-unsafe-finally\n      throw new Error(errMsg);\n    }\n  }\n\n  return jsonPromise;\n}\n\nvar _companionHeaders = /*#__PURE__*/_classPrivateFieldLooseKey(\"companionHeaders\");\n\nvar _getPostResponseFunc = /*#__PURE__*/_classPrivateFieldLooseKey(\"getPostResponseFunc\");\n\nvar _getUrl = /*#__PURE__*/_classPrivateFieldLooseKey(\"getUrl\");\n\nvar _errorHandler = /*#__PURE__*/_classPrivateFieldLooseKey(\"errorHandler\");\n\n_Symbol$for = Symbol.for('uppy test: getCompanionHeaders');\n\nclass RequestClient {\n  constructor(uppy, opts) {\n    Object.defineProperty(this, _errorHandler, {\n      value: _errorHandler2\n    });\n    Object.defineProperty(this, _getUrl, {\n      value: _getUrl2\n    });\n    Object.defineProperty(this, _companionHeaders, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _getPostResponseFunc, {\n      writable: true,\n      value: skip => response => skip ? response : this.onReceiveResponse(response)\n    });\n    this.uppy = uppy;\n    this.opts = opts;\n    this.onReceiveResponse = this.onReceiveResponse.bind(this);\n    this.allowedHeaders = ['accept', 'content-type', 'uppy-auth-token'];\n    this.preflightDone = false;\n    _classPrivateFieldLooseBase(this, _companionHeaders)[_companionHeaders] = opts == null ? void 0 : opts.companionHeaders;\n  }\n\n  setCompanionHeaders(headers) {\n    _classPrivateFieldLooseBase(this, _companionHeaders)[_companionHeaders] = headers;\n  }\n\n  [_Symbol$for]() {\n    return _classPrivateFieldLooseBase(this, _companionHeaders)[_companionHeaders];\n  }\n\n  get hostname() {\n    const {\n      companion\n    } = this.uppy.getState();\n    const host = this.opts.companionUrl;\n    return stripSlash(companion && companion[host] ? companion[host] : host);\n  }\n\n  headers() {\n    return Promise.resolve({ ...RequestClient.defaultHeaders,\n      ..._classPrivateFieldLooseBase(this, _companionHeaders)[_companionHeaders]\n    });\n  }\n\n  onReceiveResponse(response) {\n    const state = this.uppy.getState();\n    const companion = state.companion || {};\n    const host = this.opts.companionUrl;\n    const {\n      headers\n    } = response; // Store the self-identified domain name for the Companion instance we just hit.\n\n    if (headers.has('i-am') && headers.get('i-am') !== companion[host]) {\n      this.uppy.setState({\n        companion: { ...companion,\n          [host]: headers.get('i-am')\n        }\n      });\n    }\n\n    return response;\n  }\n\n  preflight(path) {\n    if (this.preflightDone) {\n      return Promise.resolve(this.allowedHeaders.slice());\n    }\n\n    return fetch(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {\n      method: 'OPTIONS'\n    }).then(response => {\n      if (response.headers.has('access-control-allow-headers')) {\n        this.allowedHeaders = response.headers.get('access-control-allow-headers').split(',').map(headerName => headerName.trim().toLowerCase());\n      }\n\n      this.preflightDone = true;\n      return this.allowedHeaders.slice();\n    }).catch(err => {\n      this.uppy.log(`[CompanionClient] unable to make preflight request ${err}`, 'warning');\n      this.preflightDone = true;\n      return this.allowedHeaders.slice();\n    });\n  }\n\n  preflightAndHeaders(path) {\n    return Promise.all([this.preflight(path), this.headers()]).then(_ref => {\n      let [allowedHeaders, headers] = _ref;\n      // filter to keep only allowed Headers\n      Object.keys(headers).forEach(header => {\n        if (!allowedHeaders.includes(header.toLowerCase())) {\n          this.uppy.log(`[CompanionClient] excluding disallowed header ${header}`);\n          delete headers[header]; // eslint-disable-line no-param-reassign\n        }\n      });\n      return headers;\n    });\n  }\n\n  get(path, skipPostResponse) {\n    const method = 'get';\n    return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {\n      method,\n      headers,\n      credentials: this.opts.companionCookiesRule || 'same-origin'\n    })).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));\n  }\n\n  post(path, data, skipPostResponse) {\n    const method = 'post';\n    return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {\n      method,\n      headers,\n      credentials: this.opts.companionCookiesRule || 'same-origin',\n      body: JSON.stringify(data)\n    })).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));\n  }\n\n  delete(path, data, skipPostResponse) {\n    const method = 'delete';\n    return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(`${this.hostname}/${path}`, {\n      method,\n      headers,\n      credentials: this.opts.companionCookiesRule || 'same-origin',\n      body: data ? JSON.stringify(data) : null\n    })).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));\n  }\n\n}\n\nfunction _getUrl2(url) {\n  if (/^(https?:|)\\/\\//.test(url)) {\n    return url;\n  }\n\n  return `${this.hostname}/${url}`;\n}\n\nfunction _errorHandler2(method, path) {\n  return err => {\n    var _err;\n\n    if (!((_err = err) != null && _err.isAuthError)) {\n      // eslint-disable-next-line no-param-reassign\n      err = new ErrorWithCause(`Could not ${method} ${_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path)}`, {\n        cause: err\n      });\n    }\n\n    return Promise.reject(err);\n  };\n}\n\nRequestClient.VERSION = packageJson.version;\nRequestClient.defaultHeaders = {\n  Accept: 'application/json',\n  'Content-Type': 'application/json',\n  'Uppy-Versions': `@uppy/companion-client=${RequestClient.VERSION}`\n};\nmodule.exports = RequestClient;", "'use strict';\n/**\n * This module serves as an Async wrapper for LocalStorage\n */\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.getItem = getItem;\nexports.removeItem = removeItem;\nexports.setItem = setItem;\n\nfunction setItem(key, value) {\n  return new Promise(resolve => {\n    localStorage.setItem(key, value);\n    resolve();\n  });\n}\n\nfunction getItem(key) {\n  return Promise.resolve(localStorage.getItem(key));\n}\n\nfunction removeItem(key) {\n  return new Promise(resolve => {\n    localStorage.removeItem(key);\n    resolve();\n  });\n}", "'use strict';\n\nvar tokenStorage = require(\"./tokenStorage.js\");\n\nconst RequestClient = require(\"./RequestClient.js\");\n\nconst getName = id => {\n  return id.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');\n};\n\nclass Provider extends RequestClient {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.provider = opts.provider;\n    this.id = this.provider;\n    this.name = this.opts.name || getName(this.id);\n    this.pluginId = this.opts.pluginId;\n    this.tokenKey = `companion-${this.pluginId}-auth-token`;\n    this.companionKeysParams = this.opts.companionKeysParams;\n    this.preAuthToken = null;\n  }\n\n  headers() {\n    return Promise.all([super.headers(), this.getAuthToken()]).then(_ref => {\n      let [headers, token] = _ref;\n      const authHeaders = {};\n\n      if (token) {\n        authHeaders['uppy-auth-token'] = token;\n      }\n\n      if (this.companionKeysParams) {\n        authHeaders['uppy-credentials-params'] = btoa(JSON.stringify({\n          params: this.companionKeysParams\n        }));\n      }\n\n      return { ...headers,\n        ...authHeaders\n      };\n    });\n  }\n\n  onReceiveResponse(response) {\n    response = super.onReceiveResponse(response); // eslint-disable-line no-param-reassign\n\n    const plugin = this.uppy.getPlugin(this.pluginId);\n    const oldAuthenticated = plugin.getPluginState().authenticated;\n    const authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400;\n    plugin.setPluginState({\n      authenticated\n    });\n    return response;\n  }\n\n  setAuthToken(token) {\n    return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token);\n  }\n\n  getAuthToken() {\n    return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey);\n  }\n  /**\n   * Ensure we have a preauth token if necessary. Attempts to fetch one if we don't,\n   * or rejects if loading one fails.\n   */\n\n\n  async ensurePreAuth() {\n    if (this.companionKeysParams && !this.preAuthToken) {\n      await this.fetchPreAuthToken();\n\n      if (!this.preAuthToken) {\n        throw new Error('Could not load authentication data required for third-party login. Please try again later.');\n      }\n    }\n  }\n\n  authUrl(queries) {\n    if (queries === void 0) {\n      queries = {};\n    }\n\n    const params = new URLSearchParams(queries);\n\n    if (this.preAuthToken) {\n      params.set('uppyPreAuthToken', this.preAuthToken);\n    }\n\n    return `${this.hostname}/${this.id}/connect?${params}`;\n  }\n\n  fileUrl(id) {\n    return `${this.hostname}/${this.id}/get/${id}`;\n  }\n\n  async fetchPreAuthToken() {\n    if (!this.companionKeysParams) {\n      return;\n    }\n\n    try {\n      const res = await this.post(`${this.id}/preauth/`, {\n        params: this.companionKeysParams\n      });\n      this.preAuthToken = res.token;\n    } catch (err) {\n      this.uppy.log(`[CompanionClient] unable to fetch preAuthToken ${err}`, 'warning');\n    }\n  }\n\n  list(directory) {\n    return this.get(`${this.id}/list/${directory || ''}`);\n  }\n\n  logout() {\n    return this.get(`${this.id}/logout`).then(response => Promise.all([response, this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey)])).then(_ref2 => {\n      let [response] = _ref2;\n      return response;\n    });\n  }\n\n  static initPlugin(plugin, opts, defaultOpts) {\n    /* eslint-disable no-param-reassign */\n    plugin.type = 'acquirer';\n    plugin.files = [];\n\n    if (defaultOpts) {\n      plugin.opts = { ...defaultOpts,\n        ...opts\n      };\n    }\n\n    if (opts.serverUrl || opts.serverPattern) {\n      throw new Error('`serverUrl` and `serverPattern` have been renamed to `companionUrl` and `companionAllowedHosts` respectively in the 0.30.5 release. Please consult the docs (for example, https://uppy.io/docs/instagram/ for the Instagram plugin) and use the updated options.`');\n    }\n\n    if (opts.companionAllowedHosts) {\n      const pattern = opts.companionAllowedHosts; // validate companionAllowedHosts param\n\n      if (typeof pattern !== 'string' && !Array.isArray(pattern) && !(pattern instanceof RegExp)) {\n        throw new TypeError(`${plugin.id}: the option \"companionAllowedHosts\" must be one of string, Array, RegExp`);\n      }\n\n      plugin.opts.companionAllowedHosts = pattern;\n    } else if (/^(?!https?:\\/\\/).*$/i.test(opts.companionUrl)) {\n      // does not start with https://\n      plugin.opts.companionAllowedHosts = `https://${opts.companionUrl.replace(/^\\/\\//, '')}`;\n    } else {\n      plugin.opts.companionAllowedHosts = new URL(opts.companionUrl).origin;\n    }\n\n    plugin.storage = plugin.opts.storage || tokenStorage;\n    /* eslint-enable no-param-reassign */\n  }\n\n}\n\nmodule.exports = Provider;", "'use strict';\n\nconst RequestClient = require(\"./RequestClient.js\");\n\nconst getName = id => {\n  return id.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');\n};\n\nclass SearchProvider extends RequestClient {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.provider = opts.provider;\n    this.id = this.provider;\n    this.name = this.opts.name || getName(this.id);\n    this.pluginId = this.opts.pluginId;\n  }\n\n  fileUrl(id) {\n    return `${this.hostname}/search/${this.id}/get/${id}`;\n  }\n\n  search(text, queries) {\n    return this.get(`search/${this.id}/list?q=${encodeURIComponent(text)}${queries ? `&${queries}` : ''}`);\n  }\n\n}\n\nmodule.exports = SearchProvider;", "\"use strict\";\n\nlet _Symbol$for, _Symbol$for2;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst ee = require(\"namespace-emitter\");\n\nvar _queued = /*#__PURE__*/_classPrivateFieldLooseKey(\"queued\");\n\nvar _emitter = /*#__PURE__*/_classPrivateFieldLooseKey(\"emitter\");\n\nvar _isOpen = /*#__PURE__*/_classPrivateFieldLooseKey(\"isOpen\");\n\nvar _socket = /*#__PURE__*/_classPrivateFieldLooseKey(\"socket\");\n\nvar _handleMessage = /*#__PURE__*/_classPrivateFieldLooseKey(\"handleMessage\");\n\n_Symbol$for = Symbol.for('uppy test: getSocket');\n_Symbol$for2 = Symbol.for('uppy test: getQueued');\n\nclass UppySocket {\n  constructor(opts) {\n    Object.defineProperty(this, _queued, {\n      writable: true,\n      value: []\n    });\n    Object.defineProperty(this, _emitter, {\n      writable: true,\n      value: ee()\n    });\n    Object.defineProperty(this, _isOpen, {\n      writable: true,\n      value: false\n    });\n    Object.defineProperty(this, _socket, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _handleMessage, {\n      writable: true,\n      value: e => {\n        try {\n          const message = JSON.parse(e.data);\n          this.emit(message.action, message.payload);\n        } catch (err) {\n          // TODO: use a more robust error handler.\n          console.log(err); // eslint-disable-line no-console\n        }\n      }\n    });\n    this.opts = opts;\n\n    if (!opts || opts.autoOpen !== false) {\n      this.open();\n    }\n  }\n\n  get isOpen() {\n    return _classPrivateFieldLooseBase(this, _isOpen)[_isOpen];\n  }\n\n  [_Symbol$for]() {\n    return _classPrivateFieldLooseBase(this, _socket)[_socket];\n  }\n\n  [_Symbol$for2]() {\n    return _classPrivateFieldLooseBase(this, _queued)[_queued];\n  }\n\n  open() {\n    _classPrivateFieldLooseBase(this, _socket)[_socket] = new WebSocket(this.opts.target);\n\n    _classPrivateFieldLooseBase(this, _socket)[_socket].onopen = () => {\n      _classPrivateFieldLooseBase(this, _isOpen)[_isOpen] = true;\n\n      while (_classPrivateFieldLooseBase(this, _queued)[_queued].length > 0 && _classPrivateFieldLooseBase(this, _isOpen)[_isOpen]) {\n        const first = _classPrivateFieldLooseBase(this, _queued)[_queued].shift();\n\n        this.send(first.action, first.payload);\n      }\n    };\n\n    _classPrivateFieldLooseBase(this, _socket)[_socket].onclose = () => {\n      _classPrivateFieldLooseBase(this, _isOpen)[_isOpen] = false;\n    };\n\n    _classPrivateFieldLooseBase(this, _socket)[_socket].onmessage = _classPrivateFieldLooseBase(this, _handleMessage)[_handleMessage];\n  }\n\n  close() {\n    var _classPrivateFieldLoo;\n\n    (_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _socket)[_socket]) == null ? void 0 : _classPrivateFieldLoo.close();\n  }\n\n  send(action, payload) {\n    // attach uuid\n    if (!_classPrivateFieldLooseBase(this, _isOpen)[_isOpen]) {\n      _classPrivateFieldLooseBase(this, _queued)[_queued].push({\n        action,\n        payload\n      });\n\n      return;\n    }\n\n    _classPrivateFieldLooseBase(this, _socket)[_socket].send(JSON.stringify({\n      action,\n      payload\n    }));\n  }\n\n  on(action, handler) {\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter].on(action, handler);\n  }\n\n  emit(action, payload) {\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter].emit(action, payload);\n  }\n\n  once(action, handler) {\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter].once(action, handler);\n  }\n\n}\n\nmodule.exports = UppySocket;", "'use strict';\n/**\n * Manages communications with Companion\n */\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.Socket = exports.SearchProvider = exports.RequestClient = exports.Provider = void 0;\n\nconst _0 = require(\"./RequestClient.js\");\n\nexports.RequestClient = _0;\n\nconst _1 = require(\"./Provider.js\");\n\nexports.Provider = _1;\n\nconst _2 = require(\"./SearchProvider.js\");\n\nexports.SearchProvider = _2;\n\nconst _3 = require(\"./Socket.js\");\n\nexports.Socket = _3;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction GoogleIcon() {\n  return (0, _preact.h)(\"svg\", {\n    width: \"26\",\n    height: \"26\",\n    viewBox: \"0 0 26 26\",\n    xmlns: \"http://www.w3.org/2000/svg\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"none\",\n    \"fill-rule\": \"evenodd\"\n  }, (0, _preact.h)(\"circle\", {\n    fill: \"#FFF\",\n    cx: \"13\",\n    cy: \"13\",\n    r: \"13\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M21.64 13.205c0-.639-.057-1.252-.164-1.841H13v3.481h4.844a4.14 4.14 0 01-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z\",\n    fill: \"#4285F4\",\n    \"fill-rule\": \"nonzero\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M13 22c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H4.957v2.332A8.997 8.997 0 0013 22z\",\n    fill: \"#34A853\",\n    \"fill-rule\": \"nonzero\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M7.964 14.71A5.41 5.41 0 017.682 13c0-.593.102-1.17.282-1.71V8.958H4.957A8.996 8.996 0 004 13c0 1.452.348 2.827.957 4.042l3.007-2.332z\",\n    fill: \"#FBBC05\",\n    \"fill-rule\": \"nonzero\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M13 7.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C17.463 4.891 15.426 4 13 4a8.997 8.997 0 00-8.043 4.958l3.007 2.332C8.672 9.163 10.656 7.58 13 7.58z\",\n    fill: \"#EA4335\",\n    \"fill-rule\": \"nonzero\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M4 4h18v18H4z\"\n  })));\n}\n\nfunction AuthView(props) {\n  const {\n    pluginName,\n    pluginIcon,\n    i18nArray,\n    handleAuth\n  } = props; // In order to comply with Google's brand we need to create a different button\n  // for the Google Drive plugin\n\n  const isGoogleDrive = pluginName === 'Google Drive';\n  const pluginNameComponent = (0, _preact.h)(\"span\", {\n    className: \"uppy-Provider-authTitleName\"\n  }, pluginName, (0, _preact.h)(\"br\", null));\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Provider-auth\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Provider-authIcon\"\n  }, pluginIcon()), (0, _preact.h)(\"div\", {\n    className: \"uppy-Provider-authTitle\"\n  }, i18nArray('authenticateWithTitle', {\n    pluginName: pluginNameComponent\n  })), isGoogleDrive ? (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: \"uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn uppy-Provider-btn-google\",\n    onClick: handleAuth,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(GoogleIcon, null), i18nArray('signInWithGoogle')) : (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: \"uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn\",\n    onClick: handleAuth,\n    \"data-uppy-super-focusable\": true\n  }, i18nArray('authenticateWith', {\n    pluginName\n  })));\n}\n\nmodule.exports = AuthView;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    i18n,\n    logout,\n    username\n  } = _ref;\n  return [(0, _preact.h)(\"span\", {\n    className: \"uppy-ProviderBrowser-user\",\n    key: \"username\"\n  }, username), (0, _preact.h)(\"button\", {\n    type: \"button\",\n    onClick: logout,\n    className: \"uppy-u-reset uppy-ProviderBrowser-userLogout\",\n    key: \"logout\"\n  }, i18n('logOut'))];\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst Breadcrumb = props => {\n  const {\n    getFolder,\n    title,\n    isLast\n  } = props;\n  return (0, _preact.h)(_preact.Fragment, null, (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: \"uppy-u-reset\",\n    onClick: getFolder\n  }, title), !isLast ? ' / ' : '');\n};\n\nmodule.exports = props => {\n  const {\n    getFolder,\n    title,\n    breadcrumbsIcon,\n    directories\n  } = props;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Provider-breadcrumbs\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Provider-breadcrumbsIcon\"\n  }, breadcrumbsIcon), directories.map((directory, i) => (0, _preact.h)(Breadcrumb, {\n    key: directory.id,\n    getFolder: () => getFolder(directory.id),\n    title: i === 0 ? title : directory.title,\n    isLast: i + 1 === directories.length\n  })));\n};", "\"use strict\";\n\nconst User = require(\"./User.js\");\n\nconst Breadcrumbs = require(\"../Breadcrumbs.js\");\n\nmodule.exports = props => {\n  const components = [];\n\n  if (props.showBreadcrumbs) {\n    components.push(Breadcrumbs({\n      getFolder: props.getFolder,\n      directories: props.directories,\n      breadcrumbsIcon: props.pluginIcon && props.pluginIcon(),\n      title: props.title\n    }));\n  }\n\n  components.push(User({\n    logout: props.logout,\n    username: props.username,\n    i18n: props.i18n\n  }));\n  return components;\n};", "/*!\n\tCopyright (c) 2018 Jed Watson.\n\tLicensed under the MIT License (MIT), see\n\thttp://jedwatson.github.io/classnames\n*/\n/* global define */\n\n(function () {\n\t'use strict';\n\n\tvar hasOwn = {}.hasOwnProperty;\n\n\tfunction classNames () {\n\t\tvar classes = '';\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (arg) {\n\t\t\t\tclasses = appendClass(classes, parseValue(arg));\n\t\t\t}\n\t\t}\n\n\t\treturn classes;\n\t}\n\n\tfunction parseValue (arg) {\n\t\tif (typeof arg === 'string' || typeof arg === 'number') {\n\t\t\treturn arg;\n\t\t}\n\n\t\tif (typeof arg !== 'object') {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (Array.isArray(arg)) {\n\t\t\treturn classNames.apply(null, arg);\n\t\t}\n\n\t\tif (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {\n\t\t\treturn arg.toString();\n\t\t}\n\n\t\tvar classes = '';\n\n\t\tfor (var key in arg) {\n\t\t\tif (hasOwn.call(arg, key) && arg[key]) {\n\t\t\t\tclasses = appendClass(classes, key);\n\t\t\t}\n\t\t}\n\n\t\treturn classes;\n\t}\n\n\tfunction appendClass (value, newClass) {\n\t\tif (!newClass) {\n\t\t\treturn value;\n\t\t}\n\t\n\t\tif (value) {\n\t\t\treturn value + ' ' + newClass;\n\t\t}\n\t\n\t\treturn value + newClass;\n\t}\n\n\tif (typeof module !== 'undefined' && module.exports) {\n\t\tclassNames.default = classNames;\n\t\tmodule.exports = classNames;\n\t} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {\n\t\t// register as 'classnames', consistent with npm package name\n\t\tdefine('classnames', [], function () {\n\t\t\treturn classNames;\n\t\t});\n\t} else {\n\t\twindow.classNames = classNames;\n\t}\n}());\n", "\"use strict\";\n\nconst getFileNameAndExtension = require(\"./getFileNameAndExtension.js\");\n\nfunction remoteFileObjToLocal(file) {\n  return { ...file,\n    type: file.mimeType,\n    extension: file.name ? getFileNameAndExtension(file.name).extension : null\n  };\n}\n\nmodule.exports = remoteFileObjToLocal;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nclass Filter extends _preact.Component {\n  constructor(props) {\n    super(props);\n    this.preventEnterPress = this.preventEnterPress.bind(this);\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  preventEnterPress(ev) {\n    if (ev.keyCode === 13) {\n      ev.stopPropagation();\n      ev.preventDefault();\n    }\n  }\n\n  render() {\n    const {\n      i18n,\n      filterInput,\n      filterQuery\n    } = this.props;\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-ProviderBrowser-filter\"\n    }, (0, _preact.h)(\"input\", {\n      className: \"uppy-u-reset uppy-ProviderBrowser-filterInput\",\n      type: \"text\",\n      placeholder: i18n('filter'),\n      \"aria-label\": i18n('filter'),\n      onKeyUp: this.preventEnterPress,\n      onKeyDown: this.preventEnterPress,\n      onKeyPress: this.preventEnterPress,\n      onInput: e => filterQuery(e),\n      value: filterInput\n    }), (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon uppy-ProviderBrowser-filterIcon\",\n      width: \"12\",\n      height: \"12\",\n      viewBox: \"0 0 12 12\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M8.638 7.99l3.172 3.172a.492.492 0 1 1-.697.697L7.91 8.656a4.977 4.977 0 0 1-2.983.983C2.206 9.639 0 7.481 0 4.819 0 2.158 2.206 0 4.927 0c2.721 0 4.927 2.158 4.927 4.82a4.74 4.74 0 0 1-1.216 3.17zm-3.71.685c2.176 0 3.94-1.726 3.94-3.856 0-2.129-1.764-3.855-3.94-3.855C2.75.964.984 2.69.984 4.819c0 2.13 1.765 3.856 3.942 3.856z\"\n    })), filterInput && (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-ProviderBrowser-filterClose\",\n      type: \"button\",\n      \"aria-label\": i18n('resetFilter'),\n      title: i18n('resetFilter'),\n      onClick: filterQuery\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon\",\n      viewBox: \"0 0 19 19\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M17.318 17.232L9.94 9.854 9.586 9.5l-.354.354-7.378 7.378h.707l-.62-.62v.706L9.318 9.94l.354-.354-.354-.354L1.94 1.854v.707l.62-.62h-.706l7.378 7.378.354.354.354-.354 7.378-7.378h-.707l.622.62v-.706L9.854 9.232l-.354.354.354.354 7.378 7.378.708-.707-7.38-7.378v.708l7.38-7.38.353-.353-.353-.353-.622-.622-.353-.353-.354.352-7.378 7.38h.708L2.56 1.23 2.208.88l-.353.353-.622.62-.353.355.352.353 7.38 7.38v-.708l-7.38 7.38-.353.353.352.353.622.622.353.353.354-.353 7.38-7.38h-.708l7.38 7.38z\"\n    }))));\n  }\n\n}\n\nmodule.exports = Filter;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    cancel,\n    done,\n    i18n,\n    selected\n  } = _ref;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-ProviderBrowser-footer\"\n  }, (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-c-btn-primary\",\n    onClick: done,\n    type: \"button\"\n  }, i18n('selectX', {\n    smart_count: selected\n  })), (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-c-btn-link\",\n    onClick: cancel,\n    type: \"button\"\n  }, i18n('cancel')));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction FileIcon() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: 11,\n    height: 14.5,\n    viewBox: \"0 0 44 58\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M27.437.517a1 1 0 0 0-.094.03H4.25C2.037.548.217 2.368.217 4.58v48.405c0 2.212 1.82 4.03 4.03 4.03H39.03c2.21 0 4.03-1.818 4.03-4.03V15.61a1 1 0 0 0-.03-.28 1 1 0 0 0 0-.093 1 1 0 0 0-.03-.032 1 1 0 0 0 0-.03 1 1 0 0 0-.032-.063 1 1 0 0 0-.03-.063 1 1 0 0 0-.032 0 1 1 0 0 0-.03-.063 1 1 0 0 0-.032-.03 1 1 0 0 0-.03-.063 1 1 0 0 0-.063-.062l-14.593-14a1 1 0 0 0-.062-.062A1 1 0 0 0 28 .708a1 1 0 0 0-.374-.157 1 1 0 0 0-.156 0 1 1 0 0 0-.03-.03l-.003-.003zM4.25 2.547h22.218v9.97c0 2.21 1.82 4.03 4.03 4.03h10.564v36.438a2.02 2.02 0 0 1-2.032 2.032H4.25c-1.13 0-2.032-.9-2.032-2.032V4.58c0-1.13.902-2.032 2.03-2.032zm24.218 1.345l10.375 9.937.75.718H30.5c-1.13 0-2.032-.9-2.032-2.03V3.89z\"\n  }));\n}\n\nfunction FolderIcon() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    style: {\n      minWidth: 16,\n      marginRight: 3\n    },\n    viewBox: \"0 0 276.157 276.157\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M273.08 101.378c-3.3-4.65-8.86-7.32-15.254-7.32h-24.34V67.59c0-10.2-8.3-18.5-18.5-18.5h-85.322c-3.63 0-9.295-2.875-11.436-5.805l-6.386-8.735c-4.982-6.814-15.104-11.954-23.546-11.954H58.73c-9.292 0-18.638 6.608-21.737 15.372l-2.033 5.752c-.958 2.71-4.72 5.37-7.596 5.37H18.5C8.3 49.09 0 57.39 0 67.59v167.07c0 .886.16 1.73.443 2.52.152 3.306 1.18 6.424 3.053 9.064 3.3 4.652 8.86 7.32 15.255 7.32h188.487c11.395 0 23.27-8.425 27.035-19.18l40.677-116.188c2.11-6.035 1.43-12.164-1.87-16.816zM18.5 64.088h8.864c9.295 0 18.64-6.607 21.738-15.37l2.032-5.75c.96-2.712 4.722-5.373 7.597-5.373h29.565c3.63 0 9.295 2.876 11.437 5.806l6.386 8.735c4.982 6.815 15.104 11.954 23.546 11.954h85.322c1.898 0 3.5 1.602 3.5 3.5v26.47H69.34c-11.395 0-23.27 8.423-27.035 19.178L15 191.23V67.59c0-1.898 1.603-3.5 3.5-3.5zm242.29 49.15l-40.676 116.188c-1.674 4.78-7.812 9.135-12.877 9.135H18.75c-1.447 0-2.576-.372-3.02-.997-.442-.625-.422-1.814.057-3.18l40.677-116.19c1.674-4.78 7.812-9.134 12.877-9.134h188.487c1.448 0 2.577.372 3.02.997.443.625.423 1.814-.056 3.18z\"\n  }));\n}\n\nfunction VideoIcon() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    style: {\n      width: 16,\n      marginRight: 4\n    },\n    viewBox: \"0 0 58 58\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M36.537 28.156l-11-7a1.005 1.005 0 0 0-1.02-.033C24.2 21.3 24 21.635 24 22v14a1 1 0 0 0 1.537.844l11-7a1.002 1.002 0 0 0 0-1.688zM26 34.18V23.82L34.137 29 26 34.18z\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M57 6H1a1 1 0 0 0-1 1v44a1 1 0 0 0 1 1h56a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1zM10 28H2v-9h8v9zm-8 2h8v9H2v-9zm10 10V8h34v42H12V40zm44-12h-8v-9h8v9zm-8 2h8v9h-8v-9zm8-22v9h-8V8h8zM2 8h8v9H2V8zm0 42v-9h8v9H2zm54 0h-8v-9h8v9z\"\n  }));\n}\n\nmodule.exports = props => {\n  const {\n    itemIconString\n  } = props;\n  if (itemIconString === null) return undefined;\n\n  switch (itemIconString) {\n    case 'file':\n      return (0, _preact.h)(FileIcon, null);\n\n    case 'folder':\n      return (0, _preact.h)(FolderIcon, null);\n\n    case 'video':\n      return (0, _preact.h)(VideoIcon, null);\n\n    default:\n      {\n        const {\n          alt\n        } = props;\n        return (0, _preact.h)(\"img\", {\n          src: itemIconString,\n          alt: alt\n        });\n      }\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction GridListItem(props) {\n  const {\n    className,\n    isDisabled,\n    restrictionReason,\n    isChecked,\n    title,\n    itemIconEl,\n    showTitles,\n    toggleCheckbox,\n    recordShiftKeyPress,\n    id,\n    children\n  } = props;\n  return (0, _preact.h)(\"li\", {\n    className: className,\n    title: isDisabled ? restrictionReason : null\n  }, (0, _preact.h)(\"input\", {\n    type: \"checkbox\",\n    className: `uppy-u-reset uppy-ProviderBrowserItem-checkbox ${isChecked ? 'uppy-ProviderBrowserItem-checkbox--is-checked' : ''} uppy-ProviderBrowserItem-checkbox--grid`,\n    onChange: toggleCheckbox,\n    onKeyDown: recordShiftKeyPress,\n    name: \"listitem\",\n    id: id,\n    checked: isChecked,\n    disabled: isDisabled,\n    \"data-uppy-super-focusable\": true\n  }), (0, _preact.h)(\"label\", {\n    htmlFor: id,\n    \"aria-label\": title,\n    className: \"uppy-u-reset uppy-ProviderBrowserItem-inner\"\n  }, (0, _preact.h)(\"span\", {\n    className: \"uppy-ProviderBrowserItem-inner-relative\"\n  }, itemIconEl, showTitles && title, children)));\n}\n\nmodule.exports = GridListItem;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\n// if folder:\n//   + checkbox (selects all files from folder)\n//   + folder name (opens folder)\n// if file:\n//   + checkbox (selects file)\n//   + file name (selects file)\nfunction ListItem(props) {\n  const {\n    className,\n    isDisabled,\n    restrictionReason,\n    isCheckboxDisabled,\n    isChecked,\n    toggleCheckbox,\n    recordShiftKeyPress,\n    type,\n    id,\n    itemIconEl,\n    title,\n    handleFolderClick,\n    showTitles,\n    i18n\n  } = props;\n  return (0, _preact.h)(\"li\", {\n    className: className,\n    title: isDisabled ? restrictionReason : null\n  }, !isCheckboxDisabled ? (0, _preact.h)(\"input\", {\n    type: \"checkbox\",\n    className: `uppy-u-reset uppy-ProviderBrowserItem-checkbox ${isChecked ? 'uppy-ProviderBrowserItem-checkbox--is-checked' : ''}`,\n    onChange: toggleCheckbox,\n    onKeyDown: recordShiftKeyPress // for the <label/>\n    ,\n    name: \"listitem\",\n    id: id,\n    checked: isChecked,\n    \"aria-label\": type === 'file' ? null : i18n('allFilesFromFolderNamed', {\n      name: title\n    }),\n    disabled: isDisabled,\n    \"data-uppy-super-focusable\": true\n  }) : null, type === 'file' ? // label for a checkbox\n  (0, _preact.h)(\"label\", {\n    htmlFor: id,\n    className: \"uppy-u-reset uppy-ProviderBrowserItem-inner\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-ProviderBrowserItem-iconWrap\"\n  }, itemIconEl), showTitles && title) : // button to open a folder\n  (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: \"uppy-u-reset uppy-ProviderBrowserItem-inner\",\n    onClick: handleFolderClick,\n    \"aria-label\": i18n('openFolderNamed', {\n      name: title\n    })\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-ProviderBrowserItem-iconWrap\"\n  }, itemIconEl), showTitles && (0, _preact.h)(\"span\", null, title)));\n}\n\nmodule.exports = ListItem;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nconst classNames = require(\"classnames\");\n\nconst ItemIcon = require(\"./components/ItemIcon.js\");\n\nconst GridListItem = require(\"./components/GridLi.js\");\n\nconst ListItem = require(\"./components/ListLi.js\");\n\nmodule.exports = props => {\n  const {\n    author,\n    getItemIcon,\n    isChecked,\n    isDisabled,\n    viewType\n  } = props;\n  const itemIconString = getItemIcon();\n  const className = classNames('uppy-ProviderBrowserItem', {\n    'uppy-ProviderBrowserItem--selected': isChecked\n  }, {\n    'uppy-ProviderBrowserItem--disabled': isDisabled\n  }, {\n    'uppy-ProviderBrowserItem--noPreview': itemIconString === 'video'\n  });\n  const itemIconEl = (0, _preact.h)(ItemIcon, {\n    itemIconString: itemIconString\n  });\n\n  switch (viewType) {\n    case 'grid':\n      return (0, _preact.h)(GridListItem // eslint-disable-next-line react/jsx-props-no-spreading\n      , _extends({}, props, {\n        className: className,\n        itemIconEl: itemIconEl\n      }));\n\n    case 'list':\n      return (// eslint-disable-next-line react/jsx-props-no-spreading\n        (0, _preact.h)(ListItem, _extends({}, props, {\n          className: className,\n          itemIconEl: itemIconEl\n        }))\n      );\n\n    case 'unsplash':\n      return (// eslint-disable-next-line react/jsx-props-no-spreading\n        (0, _preact.h)(GridListItem, _extends({}, props, {\n          className: className,\n          itemIconEl: itemIconEl\n        }), (0, _preact.h)(\"a\", {\n          href: `${author.url}?utm_source=Companion&utm_medium=referral`,\n          target: \"_blank\",\n          rel: \"noopener noreferrer\",\n          className: \"uppy-ProviderBrowserItem-author\"\n        }, author.name))\n      );\n\n    default:\n      throw new Error(`There is no such type ${viewType}`);\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst classNames = require(\"classnames\");\n\nconst remoteFileObjToLocal = require(\"@uppy/utils/lib/remoteFileObjToLocal\");\n\nconst Filter = require(\"./Filter.js\");\n\nconst FooterActions = require(\"./FooterActions.js\");\n\nconst Item = require(\"./Item/index.js\");\n\nconst VIRTUAL_SHARED_DIR = 'shared-with-me';\n\nfunction Browser(props) {\n  const {\n    currentSelection,\n    folders,\n    files,\n    uppyFiles,\n    viewType,\n    headerComponent,\n    showBreadcrumbs,\n    isChecked,\n    toggleCheckbox,\n    recordShiftKeyPress,\n    handleScroll,\n    showTitles,\n    i18n,\n    validateRestrictions,\n    showFilter,\n    filterQuery,\n    filterInput,\n    getNextFolder,\n    cancel,\n    done,\n    columns\n  } = props;\n  const selected = currentSelection.length;\n  return (0, _preact.h)(\"div\", {\n    className: classNames('uppy-ProviderBrowser', `uppy-ProviderBrowser-viewType--${viewType}`)\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-ProviderBrowser-header\"\n  }, (0, _preact.h)(\"div\", {\n    className: classNames('uppy-ProviderBrowser-headerBar', !showBreadcrumbs && 'uppy-ProviderBrowser-headerBar--simple')\n  }, headerComponent)), showFilter && (0, _preact.h)(Filter, {\n    i18n: i18n,\n    filterQuery: filterQuery,\n    filterInput: filterInput\n  }), (() => {\n    if (!folders.length && !files.length) {\n      return (0, _preact.h)(\"div\", {\n        className: \"uppy-Provider-empty\"\n      }, i18n('noFilesFound'));\n    }\n\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-ProviderBrowser-body\"\n    }, (0, _preact.h)(\"ul\", {\n      className: \"uppy-ProviderBrowser-list\",\n      onScroll: handleScroll,\n      role: \"listbox\" // making <ul> not focusable for firefox\n      ,\n      tabIndex: \"-1\"\n    }, folders.map(folder => {\n      var _isChecked;\n\n      return Item({\n        columns,\n        showTitles,\n        viewType,\n        i18n,\n        id: folder.id,\n        title: folder.name,\n        getItemIcon: () => folder.icon,\n        isChecked: isChecked(folder),\n        toggleCheckbox: event => toggleCheckbox(event, folder),\n        recordShiftKeyPress,\n        type: 'folder',\n        isDisabled: (_isChecked = isChecked(folder)) == null ? void 0 : _isChecked.loading,\n        isCheckboxDisabled: folder.id === VIRTUAL_SHARED_DIR,\n        handleFolderClick: () => getNextFolder(folder)\n      });\n    }), files.map(file => {\n      const validated = validateRestrictions(remoteFileObjToLocal(file), [...uppyFiles, ...currentSelection]);\n      return Item({\n        id: file.id,\n        title: file.name,\n        author: file.author,\n        getItemIcon: () => file.icon,\n        isChecked: isChecked(file),\n        toggleCheckbox: event => toggleCheckbox(event, file),\n        recordShiftKeyPress,\n        columns,\n        showTitles,\n        viewType,\n        i18n,\n        type: 'file',\n        isDisabled: !validated.result && !isChecked(file),\n        restrictionReason: validated.reason\n      });\n    })));\n  })(), selected > 0 && (0, _preact.h)(FooterActions, {\n    selected: selected,\n    done: done,\n    cancel: cancel,\n    i18n: i18n\n  }));\n}\n\nmodule.exports = Browser;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    i18n\n  } = _ref;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Provider-loading\"\n  }, (0, _preact.h)(\"span\", null, i18n('loading')));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nclass CloseWrapper extends _preact.Component {\n  componentWillUnmount() {\n    const {\n      onUnmount\n    } = this.props;\n    onUnmount();\n  }\n\n  render() {\n    const {\n      children\n    } = this.props;\n    return (0, _preact.toChildArray)(children)[0];\n  }\n\n}\n\nmodule.exports = CloseWrapper;", "\"use strict\";\n\nfunction isPreviewSupported(fileType) {\n  if (!fileType) return false; // list of images that browsers can preview\n\n  return /^[^/]+\\/(jpe?g|gif|png|svg|svg\\+xml|bmp|webp|avif)$/.test(fileType);\n}\n\nmodule.exports = isPreviewSupported;", "\"use strict\";\n\nconst remoteFileObjToLocal = require(\"@uppy/utils/lib/remoteFileObjToLocal\");\n\nclass SharedHandler {\n  constructor(plugin) {\n    this.plugin = plugin;\n    this.filterItems = this.filterItems.bind(this);\n    this.toggleCheckbox = this.toggleCheckbox.bind(this);\n    this.recordShiftKeyPress = this.recordShiftKeyPress.bind(this);\n    this.isChecked = this.isChecked.bind(this);\n    this.loaderWrapper = this.loaderWrapper.bind(this);\n  }\n\n  filterItems(items) {\n    const state = this.plugin.getPluginState();\n\n    if (!state.filterInput || state.filterInput === '') {\n      return items;\n    }\n\n    return items.filter(folder => {\n      return folder.name.toLowerCase().indexOf(state.filterInput.toLowerCase()) !== -1;\n    });\n  }\n\n  recordShiftKeyPress(e) {\n    this.isShiftKeyPressed = e.shiftKey;\n  }\n  /**\n   * Toggles file/folder checkbox to on/off state while updating files list.\n   *\n   * Note that some extra complexity comes from supporting shift+click to\n   * toggle multiple checkboxes at once, which is done by getting all files\n   * in between last checked file and current one.\n   */\n\n\n  toggleCheckbox(e, file) {\n    e.stopPropagation();\n    e.preventDefault();\n    e.currentTarget.focus();\n    const {\n      folders,\n      files\n    } = this.plugin.getPluginState();\n    const items = this.filterItems(folders.concat(files)); // Shift-clicking selects a single consecutive list of items\n    // starting at the previous click and deselects everything else.\n\n    if (this.lastCheckbox && this.isShiftKeyPressed) {\n      const prevIndex = items.indexOf(this.lastCheckbox);\n      const currentIndex = items.indexOf(file);\n      const currentSelection = prevIndex < currentIndex ? items.slice(prevIndex, currentIndex + 1) : items.slice(currentIndex, prevIndex + 1);\n      const reducedCurrentSelection = []; // Check restrictions on each file in currentSelection,\n      // reduce it to only contain files that pass restrictions\n\n      for (const item of currentSelection) {\n        const {\n          uppy\n        } = this.plugin;\n        const validatedRestrictions = uppy.validateRestrictions(remoteFileObjToLocal(item), [...uppy.getFiles(), ...reducedCurrentSelection]);\n\n        if (validatedRestrictions.result) {\n          reducedCurrentSelection.push(item);\n        } else {\n          uppy.info({\n            message: validatedRestrictions.reason\n          }, 'error', uppy.opts.infoTimeout);\n        }\n      }\n\n      this.plugin.setPluginState({\n        currentSelection: reducedCurrentSelection\n      });\n      return;\n    }\n\n    this.lastCheckbox = file;\n    const {\n      currentSelection\n    } = this.plugin.getPluginState();\n\n    if (this.isChecked(file)) {\n      this.plugin.setPluginState({\n        currentSelection: currentSelection.filter(item => item.id !== file.id)\n      });\n    } else {\n      this.plugin.setPluginState({\n        currentSelection: currentSelection.concat([file])\n      });\n    }\n  }\n\n  isChecked(file) {\n    const {\n      currentSelection\n    } = this.plugin.getPluginState(); // comparing id instead of the file object, because the reference to the object\n    // changes when we switch folders, and the file list is updated\n\n    return currentSelection.some(item => item.id === file.id);\n  }\n\n  loaderWrapper(promise, then, catch_) {\n    promise.then(result => {\n      this.plugin.setPluginState({\n        loading: false\n      });\n      then(result);\n    }).catch(err => {\n      this.plugin.setPluginState({\n        loading: false\n      });\n      catch_(err);\n    });\n    this.plugin.setPluginState({\n      loading: true\n    });\n  }\n\n}\n\nmodule.exports = SharedHandler;", "\"use strict\";\n\nconst getFileType = require(\"@uppy/utils/lib/getFileType\");\n\nconst isPreviewSupported = require(\"@uppy/utils/lib/isPreviewSupported\");\n\nconst generateFileID = require(\"@uppy/utils/lib/generateFileID\"); // TODO: now that we have a shared `View` class,\n// `SharedHandler` could be cleaned up and moved into here\n\n\nconst SharedHandler = require(\"./SharedHandler.js\");\n\nclass View {\n  constructor(plugin, opts) {\n    this.plugin = plugin;\n    this.provider = opts.provider;\n    this.sharedHandler = new SharedHandler(plugin);\n    this.isHandlingScroll = false;\n    this.preFirstRender = this.preFirstRender.bind(this);\n    this.handleError = this.handleError.bind(this);\n    this.addFile = this.addFile.bind(this);\n    this.clearSelection = this.clearSelection.bind(this);\n    this.cancelPicking = this.cancelPicking.bind(this);\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  providerFileToId(file) {\n    return generateFileID({\n      data: file,\n      name: file.name || file.id,\n      type: file.mimetype\n    });\n  }\n\n  preFirstRender() {\n    this.plugin.setPluginState({\n      didFirstRender: true\n    });\n    this.plugin.onFirstRender();\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  shouldHandleScroll(event) {\n    const {\n      scrollHeight,\n      scrollTop,\n      offsetHeight\n    } = event.target;\n    const scrollPosition = scrollHeight - (scrollTop + offsetHeight);\n    return scrollPosition < 50 && !this.isHandlingScroll;\n  }\n\n  clearSelection() {\n    this.plugin.setPluginState({\n      currentSelection: []\n    });\n  }\n\n  cancelPicking() {\n    this.clearSelection();\n    const dashboard = this.plugin.uppy.getPlugin('Dashboard');\n\n    if (dashboard) {\n      dashboard.hideAllPanels();\n    }\n  }\n\n  handleError(error) {\n    const {\n      uppy\n    } = this.plugin;\n    const message = uppy.i18n('companionError');\n    uppy.log(error.toString());\n\n    if (error.isAuthError) {\n      return;\n    }\n\n    uppy.info({\n      message,\n      details: error.toString()\n    }, 'error', 5000);\n  }\n\n  addFile(file) {\n    const tagFile = {\n      id: this.providerFileToId(file),\n      source: this.plugin.id,\n      data: file,\n      name: file.name || file.id,\n      type: file.mimeType,\n      isRemote: true,\n      meta: {},\n      body: {\n        fileId: file.id\n      },\n      remote: {\n        companionUrl: this.plugin.opts.companionUrl,\n        url: `${this.provider.fileUrl(file.requestPath)}`,\n        body: {\n          fileId: file.id\n        },\n        providerOptions: this.provider.opts,\n        providerName: this.provider.name\n      }\n    };\n    const fileType = getFileType(tagFile); // TODO Should we just always use the thumbnail URL if it exists?\n\n    if (fileType && isPreviewSupported(fileType)) {\n      tagFile.preview = file.thumbnail;\n    }\n\n    if (file.author) {\n      if (file.author.name != null) tagFile.meta.authorName = String(file.author.name);\n      if (file.author.url) tagFile.meta.authorUrl = file.author.url;\n    }\n\n    this.plugin.uppy.log('Adding remote file');\n\n    try {\n      this.plugin.uppy.addFile(tagFile);\n      return true;\n    } catch (err) {\n      if (!err.isRestriction) {\n        this.plugin.uppy.log(err);\n      }\n\n      return false;\n    }\n  }\n\n}\n\nmodule.exports = View;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst AuthView = require(\"./AuthView.js\");\n\nconst Header = require(\"./Header.js\");\n\nconst Browser = require(\"../Browser.js\");\n\nconst LoaderView = require(\"../Loader.js\");\n\nconst CloseWrapper = require(\"../CloseWrapper.js\");\n\nconst View = require(\"../View.js\");\n\nconst packageJson = {\n  \"version\": \"2.1.3\"\n};\n\nfunction getOrigin() {\n  // eslint-disable-next-line no-restricted-globals\n  return location.origin;\n}\n\nfunction getRegex(value) {\n  if (typeof value === 'string') {\n    return new RegExp(`^${value}$`);\n  }\n\n  if (value instanceof RegExp) {\n    return value;\n  }\n\n  return undefined;\n}\n\nfunction isOriginAllowed(origin, allowedOrigin) {\n  const patterns = Array.isArray(allowedOrigin) ? allowedOrigin.map(getRegex) : [getRegex(allowedOrigin)];\n  return patterns.some(pattern => (pattern == null ? void 0 : pattern.test(origin)) || (pattern == null ? void 0 : pattern.test(`${origin}/`))); // allowing for trailing '/'\n}\n/**\n * Class to easily generate generic views for Provider plugins\n */\n\n\nvar _updateFilesAndFolders = /*#__PURE__*/_classPrivateFieldLooseKey(\"updateFilesAndFolders\");\n\nclass ProviderView extends View {\n  /**\n   * @param {object} plugin instance of the plugin\n   * @param {object} opts\n   */\n  constructor(plugin, opts) {\n    super(plugin, opts); // set default options\n\n    Object.defineProperty(this, _updateFilesAndFolders, {\n      value: _updateFilesAndFolders2\n    });\n    const defaultOptions = {\n      viewType: 'list',\n      showTitles: true,\n      showFilter: true,\n      showBreadcrumbs: true\n    }; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    }; // Logic\n\n    this.filterQuery = this.filterQuery.bind(this);\n    this.getFolder = this.getFolder.bind(this);\n    this.getNextFolder = this.getNextFolder.bind(this);\n    this.logout = this.logout.bind(this);\n    this.handleAuth = this.handleAuth.bind(this);\n    this.handleScroll = this.handleScroll.bind(this);\n    this.listAllFiles = this.listAllFiles.bind(this);\n    this.donePicking = this.donePicking.bind(this); // Visual\n\n    this.render = this.render.bind(this); // Set default state for the plugin\n\n    this.plugin.setPluginState({\n      authenticated: false,\n      files: [],\n      folders: [],\n      directories: [],\n      filterInput: '',\n      isSearchVisible: false,\n      currentSelection: []\n    });\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  tearDown() {// Nothing.\n  }\n\n  /**\n   * Based on folder ID, fetch a new folder and update it to state\n   *\n   * @param  {string} id Folder id\n   * @returns {Promise}   Folders/files in folder\n   */\n  getFolder(id, name) {\n    return this.sharedHandler.loaderWrapper(this.provider.list(id), res => {\n      const folders = [];\n      const files = [];\n      let updatedDirectories;\n      const state = this.plugin.getPluginState();\n      const index = state.directories.findIndex(dir => id === dir.id);\n\n      if (index !== -1) {\n        updatedDirectories = state.directories.slice(0, index + 1);\n      } else {\n        updatedDirectories = state.directories.concat([{\n          id,\n          title: name\n        }]);\n      }\n\n      this.username = res.username || this.username;\n\n      _classPrivateFieldLooseBase(this, _updateFilesAndFolders)[_updateFilesAndFolders](res, files, folders);\n\n      this.plugin.setPluginState({\n        directories: updatedDirectories\n      });\n    }, this.handleError);\n  }\n  /**\n   * Fetches new folder\n   *\n   * @param  {object} folder\n   */\n\n\n  getNextFolder(folder) {\n    this.getFolder(folder.requestPath, folder.name);\n    this.lastCheckbox = undefined;\n  }\n  /**\n   * Removes session token on client side.\n   */\n\n\n  logout() {\n    this.provider.logout().then(res => {\n      if (res.ok) {\n        if (!res.revoked) {\n          const message = this.plugin.uppy.i18n('companionUnauthorizeHint', {\n            provider: this.plugin.title,\n            url: res.manual_revoke_url\n          });\n          this.plugin.uppy.info(message, 'info', 7000);\n        }\n\n        const newState = {\n          authenticated: false,\n          files: [],\n          folders: [],\n          directories: []\n        };\n        this.plugin.setPluginState(newState);\n      }\n    }).catch(this.handleError);\n  }\n\n  filterQuery(e) {\n    const state = this.plugin.getPluginState();\n    this.plugin.setPluginState({ ...state,\n      filterInput: e ? e.target.value : ''\n    });\n  }\n  /**\n   * Adds all files found inside of specified folder.\n   *\n   * Uses separated state while folder contents are being fetched and\n   * mantains list of selected folders, which are separated from files.\n   */\n\n\n  addFolder(folder) {\n    const folderId = this.providerFileToId(folder);\n    const folders = { ...this.plugin.getPluginState().selectedFolders\n    };\n\n    if (folderId in folders && folders[folderId].loading) {\n      return;\n    }\n\n    folders[folderId] = {\n      loading: true,\n      files: []\n    };\n    this.plugin.setPluginState({\n      selectedFolders: { ...folders\n      }\n    }); // eslint-disable-next-line consistent-return\n\n    return this.listAllFiles(folder.requestPath).then(files => {\n      let count = 0; // If the same folder is added again, we don't want to send\n      // X amount of duplicate file notifications, we want to say\n      // the folder was already added. This checks if all files are duplicate,\n      // if that's the case, we don't add the files.\n\n      files.forEach(file => {\n        const id = this.providerFileToId(file);\n\n        if (!this.plugin.uppy.checkIfFileAlreadyExists(id)) {\n          count++;\n        }\n      });\n\n      if (count > 0) {\n        files.forEach(file => this.addFile(file));\n      }\n\n      const ids = files.map(this.providerFileToId);\n      folders[folderId] = {\n        loading: false,\n        files: ids\n      };\n      this.plugin.setPluginState({\n        selectedFolders: folders\n      });\n      let message;\n\n      if (count === 0) {\n        message = this.plugin.uppy.i18n('folderAlreadyAdded', {\n          folder: folder.name\n        });\n      } else if (files.length) {\n        message = this.plugin.uppy.i18n('folderAdded', {\n          smart_count: count,\n          folder: folder.name\n        });\n      } else {\n        message = this.plugin.uppy.i18n('emptyFolderAdded');\n      }\n\n      this.plugin.uppy.info(message);\n    }).catch(e => {\n      const selectedFolders = { ...this.plugin.getPluginState().selectedFolders\n      };\n      delete selectedFolders[folderId];\n      this.plugin.setPluginState({\n        selectedFolders\n      });\n      this.handleError(e);\n    });\n  }\n\n  async handleAuth() {\n    await this.provider.ensurePreAuth();\n    const authState = btoa(JSON.stringify({\n      origin: getOrigin()\n    }));\n    const clientVersion = `@uppy/provider-views=${ProviderView.VERSION}`;\n    const link = this.provider.authUrl({\n      state: authState,\n      uppyVersions: clientVersion\n    });\n    const authWindow = window.open(link, '_blank');\n\n    const handleToken = e => {\n      if (e.source !== authWindow) {\n        this.plugin.uppy.log('rejecting event from unknown source');\n        return;\n      }\n\n      if (!isOriginAllowed(e.origin, this.plugin.opts.companionAllowedHosts) || e.source !== authWindow) {\n        this.plugin.uppy.log(`rejecting event from ${e.origin} vs allowed pattern ${this.plugin.opts.companionAllowedHosts}`);\n      } // Check if it's a string before doing the JSON.parse to maintain support\n      // for older Companion versions that used object references\n\n\n      const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data;\n\n      if (data.error) {\n        this.plugin.uppy.log('auth aborted', 'warning');\n        const {\n          uppy\n        } = this.plugin;\n        const message = uppy.i18n('authAborted');\n        uppy.info({\n          message\n        }, 'warning', 5000);\n        return;\n      }\n\n      if (!data.token) {\n        this.plugin.uppy.log('did not receive token from auth window', 'error');\n        return;\n      }\n\n      authWindow.close();\n      window.removeEventListener('message', handleToken);\n      this.provider.setAuthToken(data.token);\n      this.preFirstRender();\n    };\n\n    window.addEventListener('message', handleToken);\n  }\n\n  async handleScroll(event) {\n    const path = this.nextPagePath || null;\n\n    if (this.shouldHandleScroll(event) && path) {\n      this.isHandlingScroll = true;\n\n      try {\n        const response = await this.provider.list(path);\n        const {\n          files,\n          folders\n        } = this.plugin.getPluginState();\n\n        _classPrivateFieldLooseBase(this, _updateFilesAndFolders)[_updateFilesAndFolders](response, files, folders);\n      } catch (error) {\n        this.handleError(error);\n      } finally {\n        this.isHandlingScroll = false;\n      }\n    }\n  }\n\n  async listAllFiles(path, files) {\n    if (files === void 0) {\n      files = null;\n    }\n\n    files = files || []; // eslint-disable-line no-param-reassign\n\n    const res = await this.provider.list(path);\n    res.items.forEach(item => {\n      if (!item.isFolder) {\n        files.push(item);\n      } else {\n        this.addFolder(item);\n      }\n    });\n    const moreFiles = res.nextPagePath;\n\n    if (moreFiles) {\n      return this.listAllFiles(moreFiles, files);\n    }\n\n    return files;\n  }\n\n  donePicking() {\n    const {\n      currentSelection\n    } = this.plugin.getPluginState();\n    const promises = currentSelection.map(file => {\n      if (file.isFolder) {\n        return this.addFolder(file);\n      }\n\n      return this.addFile(file);\n    });\n    this.sharedHandler.loaderWrapper(Promise.all(promises), () => {\n      this.clearSelection();\n    }, () => {});\n  }\n\n  render(state, viewOptions) {\n    var _this = this;\n\n    if (viewOptions === void 0) {\n      viewOptions = {};\n    }\n\n    const {\n      authenticated,\n      didFirstRender\n    } = this.plugin.getPluginState();\n\n    if (!didFirstRender) {\n      this.preFirstRender();\n    }\n\n    const targetViewOptions = { ...this.opts,\n      ...viewOptions\n    };\n    const {\n      files,\n      folders,\n      filterInput,\n      loading,\n      currentSelection\n    } = this.plugin.getPluginState();\n    const {\n      isChecked,\n      toggleCheckbox,\n      recordShiftKeyPress,\n      filterItems\n    } = this.sharedHandler;\n    const hasInput = filterInput !== '';\n    const headerProps = {\n      showBreadcrumbs: targetViewOptions.showBreadcrumbs,\n      getFolder: this.getFolder,\n      directories: this.plugin.getPluginState().directories,\n      pluginIcon: this.plugin.icon,\n      title: this.plugin.title,\n      logout: this.logout,\n      username: this.username,\n      i18n: this.plugin.uppy.i18n\n    };\n    const browserProps = {\n      isChecked,\n      toggleCheckbox,\n      recordShiftKeyPress,\n      currentSelection,\n      files: hasInput ? filterItems(files) : files,\n      folders: hasInput ? filterItems(folders) : folders,\n      username: this.username,\n      getNextFolder: this.getNextFolder,\n      getFolder: this.getFolder,\n      filterItems: this.sharedHandler.filterItems,\n      filterQuery: this.filterQuery,\n      logout: this.logout,\n      handleScroll: this.handleScroll,\n      listAllFiles: this.listAllFiles,\n      done: this.donePicking,\n      cancel: this.cancelPicking,\n      headerComponent: Header(headerProps),\n      title: this.plugin.title,\n      viewType: targetViewOptions.viewType,\n      showTitles: targetViewOptions.showTitles,\n      showFilter: targetViewOptions.showFilter,\n      showBreadcrumbs: targetViewOptions.showBreadcrumbs,\n      pluginIcon: this.plugin.icon,\n      i18n: this.plugin.uppy.i18n,\n      uppyFiles: this.plugin.uppy.getFiles(),\n      validateRestrictions: function () {\n        return _this.plugin.uppy.validateRestrictions(...arguments);\n      }\n    };\n\n    if (loading) {\n      return (0, _preact.h)(CloseWrapper, {\n        onUnmount: this.clearSelection\n      }, (0, _preact.h)(LoaderView, {\n        i18n: this.plugin.uppy.i18n\n      }));\n    }\n\n    if (!authenticated) {\n      return (0, _preact.h)(CloseWrapper, {\n        onUnmount: this.clearSelection\n      }, (0, _preact.h)(AuthView, {\n        pluginName: this.plugin.title,\n        pluginIcon: this.plugin.icon,\n        handleAuth: this.handleAuth,\n        i18n: this.plugin.uppy.i18n,\n        i18nArray: this.plugin.uppy.i18nArray\n      }));\n    }\n\n    return (0, _preact.h)(CloseWrapper, {\n      onUnmount: this.clearSelection\n    }, (0, _preact.h)(Browser, browserProps));\n  }\n\n}\n\nfunction _updateFilesAndFolders2(res, files, folders) {\n  this.nextPagePath = res.nextPagePath;\n  res.items.forEach(item => {\n    if (item.isFolder) {\n      folders.push(item);\n    } else {\n      files.push(item);\n    }\n  });\n  this.plugin.setPluginState({\n    folders,\n    files\n  });\n}\n\nProviderView.VERSION = packageJson.version;\nmodule.exports = ProviderView;", "\"use strict\";\n\nmodule.exports = require(\"./ProviderView.js\");", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    i18n,\n    search\n  } = _ref;\n  let input;\n\n  const validateAndSearch = () => {\n    if (input.value) {\n      search(input.value);\n    }\n  };\n\n  const handleKeyPress = ev => {\n    if (ev.keyCode === 13) {\n      validateAndSearch();\n    }\n  };\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-SearchProvider\"\n  }, (0, _preact.h)(\"input\", {\n    className: \"uppy-u-reset uppy-c-textInput uppy-SearchProvider-input\",\n    type: \"search\",\n    \"aria-label\": i18n('enterTextToSearch'),\n    placeholder: i18n('enterTextToSearch'),\n    onKeyUp: handleKeyPress,\n    ref: input_ => {\n      input = input_;\n    },\n    \"data-uppy-super-focusable\": true\n  }), (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-SearchProvider-searchButton\",\n    type: \"button\",\n    onClick: validateAndSearch\n  }, i18n('searchImages')));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst SUBMIT_KEY = 13;\n\nmodule.exports = props => {\n  const {\n    searchTerm,\n    i18n,\n    search\n  } = props;\n\n  const handleKeyPress = ev => {\n    if (ev.keyCode === SUBMIT_KEY) {\n      ev.stopPropagation();\n      ev.preventDefault();\n      search(ev.target.value);\n    }\n  };\n\n  return (0, _preact.h)(\"div\", {\n    class: \"uppy-ProviderBrowser-search\"\n  }, (0, _preact.h)(\"input\", {\n    class: \"uppy-u-reset uppy-ProviderBrowser-searchInput\",\n    type: \"text\",\n    placeholder: i18n('search'),\n    \"aria-label\": i18n('search'),\n    value: searchTerm,\n    onKeyUp: handleKeyPress,\n    \"data-uppy-super-focusable\": true\n  }), (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    class: \"uppy-c-icon uppy-ProviderBrowser-searchIcon\",\n    width: \"12\",\n    height: \"12\",\n    viewBox: \"0 0 12 12\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M8.638 7.99l3.172 3.172a.492.492 0 1 1-.697.697L7.91 8.656a4.977 4.977 0 0 1-2.983.983C2.206 9.639 0 7.481 0 4.819 0 2.158 2.206 0 4.927 0c2.721 0 4.927 2.158 4.927 4.82a4.74 4.74 0 0 1-1.216 3.17zm-3.71.685c2.176 0 3.94-1.726 3.94-3.856 0-2.129-1.764-3.855-3.94-3.855C2.75.964.984 2.69.984 4.819c0 2.13 1.765 3.856 3.942 3.856z\"\n  })));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst SearchInput = require(\"./InputView.js\");\n\nconst Browser = require(\"../Browser.js\");\n\nconst LoaderView = require(\"../Loader.js\");\n\nconst Header = require(\"./Header.js\");\n\nconst CloseWrapper = require(\"../CloseWrapper.js\");\n\nconst View = require(\"../View.js\");\n\nconst packageJson = {\n  \"version\": \"2.1.3\"\n};\n/**\n * Class to easily generate generic views for Provider plugins\n */\n\nvar _updateFilesAndInputMode = /*#__PURE__*/_classPrivateFieldLooseKey(\"updateFilesAndInputMode\");\n\nclass SearchProviderView extends View {\n  /**\n   * @param {object} plugin instance of the plugin\n   * @param {object} opts\n   */\n  constructor(plugin, opts) {\n    super(plugin, opts); // set default options\n\n    Object.defineProperty(this, _updateFilesAndInputMode, {\n      value: _updateFilesAndInputMode2\n    });\n    const defaultOptions = {\n      viewType: 'grid',\n      showTitles: false,\n      showFilter: false,\n      showBreadcrumbs: false\n    }; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    }; // Logic\n\n    this.search = this.search.bind(this);\n    this.triggerSearchInput = this.triggerSearchInput.bind(this);\n    this.addFile = this.addFile.bind(this);\n    this.handleScroll = this.handleScroll.bind(this);\n    this.donePicking = this.donePicking.bind(this); // Visual\n\n    this.render = this.render.bind(this); // Set default state for the plugin\n\n    this.plugin.setPluginState({\n      isInputMode: true,\n      files: [],\n      folders: [],\n      directories: [],\n      filterInput: '',\n      currentSelection: [],\n      searchTerm: null\n    });\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  tearDown() {// Nothing.\n  }\n\n  clearSelection() {\n    this.plugin.setPluginState({\n      currentSelection: [],\n      isInputMode: true,\n      files: [],\n      searchTerm: null\n    });\n  }\n\n  search(query) {\n    const {\n      searchTerm\n    } = this.plugin.getPluginState();\n\n    if (query && query === searchTerm) {\n      // no need to search again as this is the same as the previous search\n      return undefined;\n    }\n\n    return this.sharedHandler.loaderWrapper(this.provider.search(query), res => {\n      _classPrivateFieldLooseBase(this, _updateFilesAndInputMode)[_updateFilesAndInputMode](res, []);\n    }, this.handleError);\n  }\n\n  triggerSearchInput() {\n    this.plugin.setPluginState({\n      isInputMode: true\n    });\n  }\n\n  async handleScroll(event) {\n    const query = this.nextPageQuery || null;\n\n    if (this.shouldHandleScroll(event) && query) {\n      this.isHandlingScroll = true;\n\n      try {\n        const {\n          files,\n          searchTerm\n        } = this.plugin.getPluginState();\n        const response = await this.provider.search(searchTerm, query);\n\n        _classPrivateFieldLooseBase(this, _updateFilesAndInputMode)[_updateFilesAndInputMode](response, files);\n      } catch (error) {\n        this.handleError(error);\n      } finally {\n        this.isHandlingScroll = false;\n      }\n    }\n  }\n\n  donePicking() {\n    const {\n      currentSelection\n    } = this.plugin.getPluginState();\n    const promises = currentSelection.map(file => this.addFile(file));\n    this.sharedHandler.loaderWrapper(Promise.all(promises), () => {\n      this.clearSelection();\n    }, () => {});\n  }\n\n  render(state, viewOptions) {\n    var _this = this;\n\n    if (viewOptions === void 0) {\n      viewOptions = {};\n    }\n\n    const {\n      didFirstRender,\n      isInputMode,\n      searchTerm\n    } = this.plugin.getPluginState();\n\n    if (!didFirstRender) {\n      this.preFirstRender();\n    }\n\n    const targetViewOptions = { ...this.opts,\n      ...viewOptions\n    };\n    const {\n      files,\n      folders,\n      filterInput,\n      loading,\n      currentSelection\n    } = this.plugin.getPluginState();\n    const {\n      isChecked,\n      toggleCheckbox,\n      filterItems\n    } = this.sharedHandler;\n    const hasInput = filterInput !== '';\n    const browserProps = {\n      isChecked,\n      toggleCheckbox,\n      currentSelection,\n      files: hasInput ? filterItems(files) : files,\n      folders: hasInput ? filterItems(folders) : folders,\n      handleScroll: this.handleScroll,\n      done: this.donePicking,\n      cancel: this.cancelPicking,\n      headerComponent: Header({\n        search: this.search,\n        i18n: this.plugin.uppy.i18n,\n        searchTerm\n      }),\n      title: this.plugin.title,\n      viewType: targetViewOptions.viewType,\n      showTitles: targetViewOptions.showTitles,\n      showFilter: targetViewOptions.showFilter,\n      showBreadcrumbs: targetViewOptions.showBreadcrumbs,\n      pluginIcon: this.plugin.icon,\n      i18n: this.plugin.uppy.i18n,\n      uppyFiles: this.plugin.uppy.getFiles(),\n      validateRestrictions: function () {\n        return _this.plugin.uppy.validateRestrictions(...arguments);\n      }\n    };\n\n    if (loading) {\n      return (0, _preact.h)(CloseWrapper, {\n        onUnmount: this.clearSelection\n      }, (0, _preact.h)(LoaderView, {\n        i18n: this.plugin.uppy.i18n\n      }));\n    }\n\n    if (isInputMode) {\n      return (0, _preact.h)(CloseWrapper, {\n        onUnmount: this.clearSelection\n      }, (0, _preact.h)(SearchInput, {\n        search: this.search,\n        i18n: this.plugin.uppy.i18n\n      }));\n    }\n\n    return (0, _preact.h)(CloseWrapper, {\n      onUnmount: this.clearSelection\n    }, (0, _preact.h)(Browser, browserProps));\n  }\n\n}\n\nfunction _updateFilesAndInputMode2(res, files) {\n  this.nextPageQuery = res.nextPageQuery;\n  res.items.forEach(item => {\n    files.push(item);\n  });\n  this.plugin.setPluginState({\n    isInputMode: false,\n    files,\n    searchTerm: res.searchedFor\n  });\n}\n\nSearchProviderView.VERSION = packageJson.version;\nmodule.exports = SearchProviderView;", "\"use strict\";\n\nmodule.exports = require(\"./SearchProviderView.js\");", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.SearchProviderViews = exports.ProviderViews = void 0;\n\nconst _0 = require(\"./ProviderView/index.js\");\n\nexports.ProviderViews = _0;\n\nconst _1 = require(\"./SearchProviderView/index.js\");\n\nexports.SearchProviderViews = _1;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.STATE_UPDATE = exports.ReduxStore = void 0;\nexports.middleware = middleware;\nexports.reducer = reducer;\n\nvar _nonSecure = require(\"nanoid/non-secure\");\n\nlet _Symbol$for;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst packageJson = {\n  \"version\": \"2.1.1\"\n}; // Redux action name.\n\nconst STATE_UPDATE = 'uppy/STATE_UPDATE'; // Pluck Uppy state from the Redux store in the default location.\n\nexports.STATE_UPDATE = STATE_UPDATE;\n\nconst defaultSelector = id => state => state.uppy[id];\n\nfunction getPatch(prev, next) {\n  const nextKeys = Object.keys(next);\n  const patch = {};\n  nextKeys.forEach(k => {\n    if (prev[k] !== next[k]) patch[k] = next[k];\n  });\n  return patch;\n}\n/**\n * Redux store.\n *\n * @param {object} opts.store - The Redux store to use.\n * @param {string} opts.id - This store instance's ID. Defaults to a random string.\n *    If you need to access Uppy state through Redux, eg. to render custom UI, set this to something constant.\n * @param {Function} opts.selector - Function, `(state) => uppyState`, to pluck state from the Redux store.\n *    Defaults to retrieving `state.uppy[opts.id]`. Override if you placed Uppy state elsewhere in the Redux store.\n */\n\n\nvar _id = /*#__PURE__*/_classPrivateFieldLooseKey(\"id\");\n\nvar _selector = /*#__PURE__*/_classPrivateFieldLooseKey(\"selector\");\n\nvar _store = /*#__PURE__*/_classPrivateFieldLooseKey(\"store\");\n\n_Symbol$for = Symbol.for('uppy test: get id');\n\nclass ReduxStore {\n  constructor(opts) {\n    Object.defineProperty(this, _id, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _selector, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _store, {\n      writable: true,\n      value: void 0\n    });\n    _classPrivateFieldLooseBase(this, _store)[_store] = opts.store;\n    _classPrivateFieldLooseBase(this, _id)[_id] = opts.id || (0, _nonSecure.nanoid)();\n    _classPrivateFieldLooseBase(this, _selector)[_selector] = opts.selector || defaultSelector(_classPrivateFieldLooseBase(this, _id)[_id]); // Calling `setState` to dispatch an action to the Redux store.\n    // The intent is to make sure that the reducer has run once.\n\n    this.setState({});\n  }\n\n  setState(patch) {\n    _classPrivateFieldLooseBase(this, _store)[_store].dispatch({\n      type: STATE_UPDATE,\n      id: _classPrivateFieldLooseBase(this, _id)[_id],\n      payload: patch\n    });\n  }\n\n  getState() {\n    return _classPrivateFieldLooseBase(this, _selector)[_selector](_classPrivateFieldLooseBase(this, _store)[_store].getState());\n  }\n\n  subscribe(cb) {\n    let prevState = this.getState();\n    return _classPrivateFieldLooseBase(this, _store)[_store].subscribe(() => {\n      const nextState = this.getState();\n\n      if (prevState !== nextState) {\n        const patch = getPatch(prevState, nextState);\n        cb(prevState, nextState, patch);\n        prevState = nextState;\n      }\n    });\n  }\n\n  [_Symbol$for]() {\n    return _classPrivateFieldLooseBase(this, _id)[_id];\n  }\n\n}\n\nexports.ReduxStore = ReduxStore;\nReduxStore.VERSION = packageJson.version;\n\nfunction reducer(state, action) {\n  if (state === void 0) {\n    state = {};\n  }\n\n  if (action.type === STATE_UPDATE) {\n    const newState = { ...state[action.id],\n      ...action.payload\n    };\n    return { ...state,\n      [action.id]: newState\n    };\n  }\n\n  return state;\n}\n\nfunction middleware() {\n  // Do nothing, at the moment.\n  return () => next => action => {\n    next(action);\n  };\n}\n\nmodule.exports = ReduxStore; // Backward compatibility: we want these to keep being available as static\n// properties of `ReduxStore` to avoid a breaking change.\n// TODO: remove these in the next semver-major.\n\nReduxStore.ReduxStore = ReduxStore;\nReduxStore.STATE_UPDATE = STATE_UPDATE;\nReduxStore.reducer = reducer;\nReduxStore.middleware = middleware;", "\"use strict\";\n\n/**\n * Converts list into array\n */\nmodule.exports = Array.from;", "\"use strict\";\n\nmodule.exports = ['a[href]:not([tabindex^=\"-\"]):not([inert]):not([aria-hidden])', 'area[href]:not([tabindex^=\"-\"]):not([inert]):not([aria-hidden])', 'input:not([disabled]):not([inert]):not([aria-hidden])', 'select:not([disabled]):not([inert]):not([aria-hidden])', 'textarea:not([disabled]):not([inert]):not([aria-hidden])', 'button:not([disabled]):not([inert]):not([aria-hidden])', 'iframe:not([tabindex^=\"-\"]):not([inert]):not([aria-hidden])', 'object:not([tabindex^=\"-\"]):not([inert]):not([aria-hidden])', 'embed:not([tabindex^=\"-\"]):not([inert]):not([aria-hidden])', '[contenteditable]:not([tabindex^=\"-\"]):not([inert]):not([aria-hidden])', '[tabindex]:not([tabindex^=\"-\"]):not([inert]):not([aria-hidden])'];", "\"use strict\";\n\nfunction getActiveOverlayEl(dashboardEl, activeOverlayType) {\n  if (activeOverlayType) {\n    const overlayEl = dashboardEl.querySelector(`[data-uppy-paneltype=\"${activeOverlayType}\"]`); // if an overlay is already mounted\n\n    if (overlayEl) return overlayEl;\n  }\n\n  return dashboardEl;\n}\n\n/**\n * @returns {HTMLElement} - either dashboard element, or the overlay that's most on top\n */\nmodule.exports = getActiveOverlayEl;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.forInline = forInline;\nexports.forModal = trapFocus;\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n\nconst FOCUSABLE_ELEMENTS = require(\"@uppy/utils/lib/FOCUSABLE_ELEMENTS\");\n\nconst getActiveOverlayEl = require(\"./getActiveOverlayEl.js\");\n\nfunction focusOnFirstNode(event, nodes) {\n  const node = nodes[0];\n\n  if (node) {\n    node.focus();\n    event.preventDefault();\n  }\n}\n\nfunction focusOnLastNode(event, nodes) {\n  const node = nodes[nodes.length - 1];\n\n  if (node) {\n    node.focus();\n    event.preventDefault();\n  }\n} // ___Why not just use (focusedItemIndex === -1)?\n//    Firefox thinks <ul> is focusable, but we don't have <ul>s in our FOCUSABLE_ELEMENTS. Which means that if we tab into\n//    the <ul>, code will think that we are not in the active overlay, and we should focusOnFirstNode() of the currently\n//    active overlay!\n//    [Practical check] if we use (focusedItemIndex === -1), instagram provider in firefox will never get focus on its pics\n//    in the <ul>.\n\n\nfunction isFocusInOverlay(activeOverlayEl) {\n  return activeOverlayEl.contains(document.activeElement);\n}\n\nfunction trapFocus(event, activeOverlayType, dashboardEl) {\n  const activeOverlayEl = getActiveOverlayEl(dashboardEl, activeOverlayType);\n  const focusableNodes = toArray(activeOverlayEl.querySelectorAll(FOCUSABLE_ELEMENTS));\n  const focusedItemIndex = focusableNodes.indexOf(document.activeElement); // If we pressed tab, and focus is not yet within the current overlay - focus on\n  // the first element within the current overlay.\n  // This is a safety measure (for when user returns from another tab e.g.), most\n  // plugins will try to focus on some important element as it loads.\n\n  if (!isFocusInOverlay(activeOverlayEl)) {\n    focusOnFirstNode(event, focusableNodes); // If we pressed shift + tab, and we're on the first element of a modal\n  } else if (event.shiftKey && focusedItemIndex === 0) {\n    focusOnLastNode(event, focusableNodes); // If we pressed tab, and we're on the last element of the modal\n  } else if (!event.shiftKey && focusedItemIndex === focusableNodes.length - 1) {\n    focusOnFirstNode(event, focusableNodes);\n  }\n} // Traps focus inside of the currently open overlay (e.g. Dashboard, or e.g. Instagram),\n// never lets focus disappear from the modal.\n\n\n// Traps focus inside of the currently open overlay, unless overlay is null - then let the user tab away.\nfunction forInline(event, activeOverlayType, dashboardEl) {\n  // ___When we're in the bare 'Drop files here, paste, browse or import from' screen\n  if (activeOverlayType === null) {// Do nothing and let the browser handle it, user can tab away from Uppy to other elements on the page\n    // ___When there is some overlay with 'Done' button\n  } else {\n    // Trap the focus inside this overlay!\n    // User can close the overlay (click 'Done') if they want to travel away from Uppy.\n    trapFocus(event, activeOverlayType, dashboardEl);\n  }\n}", "\"use strict\";\n\nfunction getSpeed(fileProgress) {\n  if (!fileProgress.bytesUploaded) return 0;\n  const timeElapsed = Date.now() - fileProgress.uploadStarted;\n  const uploadSpeed = fileProgress.bytesUploaded / (timeElapsed / 1000);\n  return uploadSpeed;\n}\n\nmodule.exports = getSpeed;", "\"use strict\";\n\nfunction getBytesRemaining(fileProgress) {\n  return fileProgress.bytesTotal - fileProgress.bytesUploaded;\n}\n\nmodule.exports = getBytesRemaining;", "\"use strict\";\n\nmodule.exports = {\n  STATE_ERROR: 'error',\n  STATE_WAITING: 'waiting',\n  STATE_PREPROCESSING: 'preprocessing',\n  STATE_UPLOADING: 'uploading',\n  STATE_POSTPROCESSING: 'postprocessing',\n  STATE_COMPLETE: 'complete'\n};", "\"use strict\";\n\nfunction secondsToTime(rawSeconds) {\n  const hours = Math.floor(rawSeconds / 3600) % 24;\n  const minutes = Math.floor(rawSeconds / 60) % 60;\n  const seconds = Math.floor(rawSeconds % 60);\n  return {\n    hours,\n    minutes,\n    seconds\n  };\n}\n\nmodule.exports = secondsToTime;", "\"use strict\";\n\nconst secondsToTime = require(\"./secondsToTime.js\");\n\nfunction prettyETA(seconds) {\n  const time = secondsToTime(seconds); // Only display hours and minutes if they are greater than 0 but always\n  // display minutes if hours is being displayed\n  // Display a leading zero if the there is a preceding unit: 1m 05s, but 5s\n\n  const hoursStr = time.hours === 0 ? '' : `${time.hours}h`;\n  const minutesStr = time.minutes === 0 ? '' : `${time.hours === 0 ? time.minutes : ` ${time.minutes.toString(10).padStart(2, '0')}`}m`;\n  const secondsStr = time.hours !== 0 ? '' : `${time.minutes === 0 ? time.seconds : ` ${time.seconds.toString(10).padStart(2, '0')}`}s`;\n  return `${hoursStr}${minutesStr}${secondsStr}`;\n}\n\nmodule.exports = prettyETA;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.CancelBtn = CancelBtn;\nexports.DoneBtn = DoneBtn;\nexports.LoadingSpinner = LoadingSpinner;\nexports.PauseResumeButton = PauseResumeButton;\nexports.ProgressBarComplete = ProgressBarComplete;\nexports.ProgressBarError = ProgressBarError;\nexports.ProgressBarProcessing = ProgressBarProcessing;\nexports.ProgressBarUploading = ProgressBarUploading;\nexports.ProgressDetails = ProgressDetails;\nexports.RetryBtn = RetryBtn;\nexports.UploadBtn = UploadBtn;\n\nvar _preact = require(\"preact\");\n\nconst classNames = require(\"classnames\");\n\nconst throttle = require(\"lodash.throttle\");\n\nconst prettierBytes = require(\"@transloadit/prettier-bytes\");\n\nconst prettyETA = require(\"@uppy/utils/lib/prettyETA\");\n\nconst statusBarStates = require(\"./StatusBarStates.js\");\n\nconst DOT = `\\u00B7`;\n\nconst renderDot = () => ` ${DOT} `;\n\nfunction UploadBtn(props) {\n  const {\n    newFiles,\n    isUploadStarted,\n    recoveredState,\n    i18n,\n    uploadState,\n    isSomeGhost,\n    startUpload\n  } = props;\n  const uploadBtnClassNames = classNames('uppy-u-reset', 'uppy-c-btn', 'uppy-StatusBar-actionBtn', 'uppy-StatusBar-actionBtn--upload', {\n    'uppy-c-btn-primary': uploadState === statusBarStates.STATE_WAITING\n  }, {\n    'uppy-StatusBar-actionBtn--disabled': isSomeGhost\n  });\n  const uploadBtnText = newFiles && isUploadStarted && !recoveredState ? i18n('uploadXNewFiles', {\n    smart_count: newFiles\n  }) : i18n('uploadXFiles', {\n    smart_count: newFiles\n  });\n  return (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: uploadBtnClassNames,\n    \"aria-label\": i18n('uploadXFiles', {\n      smart_count: newFiles\n    }),\n    onClick: startUpload,\n    disabled: isSomeGhost,\n    \"data-uppy-super-focusable\": true\n  }, uploadBtnText);\n}\n\nfunction RetryBtn(props) {\n  const {\n    i18n,\n    uppy\n  } = props;\n  return (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: \"uppy-u-reset uppy-c-btn uppy-StatusBar-actionBtn uppy-StatusBar-actionBtn--retry\",\n    \"aria-label\": i18n('retryUpload'),\n    onClick: () => uppy.retryAll(),\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"8\",\n    height: \"10\",\n    viewBox: \"0 0 8 10\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M4 2.408a2.75 2.75 0 1 0 2.75 2.75.626.626 0 0 1 1.25.018v.023a4 4 0 1 1-4-4.041V.25a.25.25 0 0 1 .389-.208l2.299 1.533a.25.25 0 0 1 0 .416l-2.3 1.533A.25.25 0 0 1 4 3.316v-.908z\"\n  })), i18n('retry'));\n}\n\nfunction CancelBtn(props) {\n  const {\n    i18n,\n    uppy\n  } = props;\n  return (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: \"uppy-u-reset uppy-StatusBar-actionCircleBtn\",\n    title: i18n('cancel'),\n    \"aria-label\": i18n('cancel'),\n    onClick: () => uppy.cancelAll(),\n    \"data-cy\": \"cancel\",\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"16\",\n    height: \"16\",\n    viewBox: \"0 0 16 16\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"none\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"circle\", {\n    fill: \"#888\",\n    cx: \"8\",\n    cy: \"8\",\n    r: \"8\"\n  }), (0, _preact.h)(\"path\", {\n    fill: \"#FFF\",\n    d: \"M9.283 8l2.567 2.567-1.283 1.283L8 9.283 5.433 11.85 4.15 10.567 6.717 8 4.15 5.433 5.433 4.15 8 6.717l2.567-2.567 1.283 1.283z\"\n  }))));\n}\n\nfunction PauseResumeButton(props) {\n  const {\n    isAllPaused,\n    i18n,\n    isAllComplete,\n    resumableUploads,\n    uppy\n  } = props;\n  const title = isAllPaused ? i18n('resume') : i18n('pause');\n\n  function togglePauseResume() {\n    if (isAllComplete) return null;\n\n    if (!resumableUploads) {\n      return uppy.cancelAll();\n    }\n\n    if (isAllPaused) {\n      return uppy.resumeAll();\n    }\n\n    return uppy.pauseAll();\n  }\n\n  return (0, _preact.h)(\"button\", {\n    title: title,\n    \"aria-label\": title,\n    className: \"uppy-u-reset uppy-StatusBar-actionCircleBtn\",\n    type: \"button\",\n    onClick: togglePauseResume,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"16\",\n    height: \"16\",\n    viewBox: \"0 0 16 16\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"none\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"circle\", {\n    fill: \"#888\",\n    cx: \"8\",\n    cy: \"8\",\n    r: \"8\"\n  }), (0, _preact.h)(\"path\", {\n    fill: \"#FFF\",\n    d: isAllPaused ? 'M6 4.25L11.5 8 6 11.75z' : 'M5 4.5h2v7H5v-7zm4 0h2v7H9v-7z'\n  }))));\n}\n\nfunction DoneBtn(props) {\n  const {\n    i18n,\n    doneButtonHandler\n  } = props;\n  return (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: \"uppy-u-reset uppy-c-btn uppy-StatusBar-actionBtn uppy-StatusBar-actionBtn--done\",\n    onClick: doneButtonHandler,\n    \"data-uppy-super-focusable\": true\n  }, i18n('done'));\n}\n\nfunction LoadingSpinner() {\n  return (0, _preact.h)(\"svg\", {\n    className: \"uppy-StatusBar-spinner\",\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"14\",\n    height: \"14\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M13.983 6.547c-.12-2.509-1.64-4.893-3.939-5.936-2.48-1.127-5.488-.656-7.556 1.094C.524 3.367-.398 6.048.162 8.562c.556 2.495 2.46 4.52 4.94 5.183 2.932.784 5.61-.602 7.256-3.015-1.493 1.993-3.745 3.309-6.298 2.868-2.514-.434-4.578-2.349-5.153-4.84a6.226 6.226 0 0 1 2.98-6.778C6.34.586 9.74 1.1 11.373 3.493c.407.596.693 1.282.842 1.988.127.598.073 1.197.161 1.794.078.525.543 1.257 1.15.864.525-.341.49-1.05.456-1.592-.007-.15.02.3 0 0\",\n    fillRule: \"evenodd\"\n  }));\n}\n\nfunction ProgressBarProcessing(props) {\n  const {\n    progress\n  } = props;\n  const {\n    value,\n    mode,\n    message\n  } = progress;\n  const roundedValue = Math.round(value * 100);\n  const dot = `\\u00B7`;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-content\"\n  }, (0, _preact.h)(LoadingSpinner, null), mode === 'determinate' ? `${roundedValue}% ${dot} ` : '', message);\n}\n\nfunction ProgressDetails(props) {\n  const {\n    numUploads,\n    complete,\n    totalUploadedSize,\n    totalSize,\n    totalETA,\n    i18n\n  } = props;\n  const ifShowFilesUploadedOfTotal = numUploads > 1;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-statusSecondary\"\n  }, ifShowFilesUploadedOfTotal && i18n('filesUploadedOfTotal', {\n    complete,\n    smart_count: numUploads\n  }), (0, _preact.h)(\"span\", {\n    className: \"uppy-StatusBar-additionalInfo\"\n  }, ifShowFilesUploadedOfTotal && renderDot(), i18n('dataUploadedOfTotal', {\n    complete: prettierBytes(totalUploadedSize),\n    total: prettierBytes(totalSize)\n  }), renderDot(), i18n('xTimeLeft', {\n    time: prettyETA(totalETA)\n  })));\n}\n\nfunction FileUploadCount(props) {\n  const {\n    i18n,\n    complete,\n    numUploads\n  } = props;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-statusSecondary\"\n  }, i18n('filesUploadedOfTotal', {\n    complete,\n    smart_count: numUploads\n  }));\n}\n\nfunction UploadNewlyAddedFiles(props) {\n  const {\n    i18n,\n    newFiles,\n    startUpload\n  } = props;\n  const uploadBtnClassNames = classNames('uppy-u-reset', 'uppy-c-btn', 'uppy-StatusBar-actionBtn', 'uppy-StatusBar-actionBtn--uploadNewlyAdded');\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-statusSecondary\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-statusSecondaryHint\"\n  }, i18n('xMoreFilesAdded', {\n    smart_count: newFiles\n  })), (0, _preact.h)(\"button\", {\n    type: \"button\",\n    className: uploadBtnClassNames,\n    \"aria-label\": i18n('uploadXFiles', {\n      smart_count: newFiles\n    }),\n    onClick: startUpload\n  }, i18n('upload')));\n}\n\nconst ThrottledProgressDetails = throttle(ProgressDetails, 500, {\n  leading: true,\n  trailing: true\n});\n\nfunction ProgressBarUploading(props) {\n  const {\n    i18n,\n    supportsUploadProgress,\n    totalProgress,\n    showProgressDetails,\n    isUploadStarted,\n    isAllComplete,\n    isAllPaused,\n    newFiles,\n    numUploads,\n    complete,\n    totalUploadedSize,\n    totalSize,\n    totalETA,\n    startUpload\n  } = props;\n  const showUploadNewlyAddedFiles = newFiles && isUploadStarted;\n\n  if (!isUploadStarted || isAllComplete) {\n    return null;\n  }\n\n  const title = isAllPaused ? i18n('paused') : i18n('uploading');\n\n  function renderProgressDetails() {\n    if (!isAllPaused && !showUploadNewlyAddedFiles && showProgressDetails) {\n      if (supportsUploadProgress) {\n        return (0, _preact.h)(ThrottledProgressDetails, {\n          numUploads: numUploads,\n          complete: complete,\n          totalUploadedSize: totalUploadedSize,\n          totalSize: totalSize,\n          totalETA: totalETA,\n          i18n: i18n\n        });\n      }\n\n      return (0, _preact.h)(FileUploadCount, {\n        i18n: i18n,\n        complete: complete,\n        numUploads: numUploads\n      });\n    }\n\n    return null;\n  }\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-content\",\n    \"aria-label\": title,\n    title: title\n  }, !isAllPaused ? (0, _preact.h)(LoadingSpinner, null) : null, (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-status\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-statusPrimary\"\n  }, supportsUploadProgress ? `${title}: ${totalProgress}%` : title), renderProgressDetails(), showUploadNewlyAddedFiles ? (0, _preact.h)(UploadNewlyAddedFiles, {\n    i18n: i18n,\n    newFiles: newFiles,\n    startUpload: startUpload\n  }) : null));\n}\n\nfunction ProgressBarComplete(props) {\n  const {\n    i18n\n  } = props;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-content\",\n    role: \"status\",\n    title: i18n('complete')\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-status\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-statusPrimary\"\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-StatusBar-statusIndicator uppy-c-icon\",\n    width: \"15\",\n    height: \"11\",\n    viewBox: \"0 0 15 11\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M.414 5.843L1.627 4.63l3.472 3.472L13.202 0l1.212 1.213L5.1 10.528z\"\n  })), i18n('complete'))));\n}\n\nfunction ProgressBarError(props) {\n  const {\n    error,\n    i18n,\n    complete,\n    numUploads\n  } = props;\n\n  function displayErrorAlert() {\n    const errorMessage = `${i18n('uploadFailed')} \\n\\n ${error}`; // eslint-disable-next-line no-alert\n\n    alert(errorMessage); // TODO: move to custom alert implementation\n  }\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-content\",\n    title: i18n('uploadFailed')\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-StatusBar-statusIndicator uppy-c-icon\",\n    width: \"11\",\n    height: \"11\",\n    viewBox: \"0 0 11 11\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M4.278 5.5L0 1.222 1.222 0 5.5 4.278 9.778 0 11 1.222 6.722 5.5 11 9.778 9.778 11 5.5 6.722 1.222 11 0 9.778z\"\n  })), (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-status\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-statusPrimary\"\n  }, i18n('uploadFailed'), (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-StatusBar-details\",\n    \"aria-label\": i18n('showErrorDetails'),\n    \"data-microtip-position\": \"top-right\",\n    \"data-microtip-size\": \"medium\",\n    onClick: displayErrorAlert,\n    type: \"button\"\n  }, \"?\")), (0, _preact.h)(FileUploadCount, {\n    i18n: i18n,\n    complete: complete,\n    numUploads: numUploads\n  })));\n}", "\"use strict\";\n\nfunction calculateProcessingProgress(files) {\n  const values = [];\n  let mode;\n  let message;\n\n  for (const {\n    progress\n  } of Object.values(files)) {\n    const {\n      preprocess,\n      postprocess\n    } = progress; // In the future we should probably do this differently. For now we'll take the\n    // mode and message from the first file\u2026\n\n    if (message == null && (preprocess || postprocess)) {\n      ({\n        mode,\n        message\n      } = preprocess || postprocess);\n    }\n\n    if ((preprocess == null ? void 0 : preprocess.mode) === 'determinate') values.push(preprocess.value);\n    if ((postprocess == null ? void 0 : postprocess.mode) === 'determinate') values.push(postprocess.value);\n  }\n\n  const value = values.reduce((total, progressValue) => {\n    return total + progressValue / values.length;\n  }, 0);\n  return {\n    mode,\n    message,\n    value\n  };\n}\n\nmodule.exports = calculateProcessingProgress;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _Components = require(\"./Components.js\");\n\n// TODO: rename this file to StatusBarUI>jsx on the next major.\nconst classNames = require(\"classnames\");\n\nconst statusBarStates = require(\"./StatusBarStates.js\");\n\nconst calculateProcessingProgress = require(\"./calculateProcessingProgress.js\");\n\nconst {\n  STATE_ERROR,\n  STATE_WAITING,\n  STATE_PREPROCESSING,\n  STATE_UPLOADING,\n  STATE_POSTPROCESSING,\n  STATE_COMPLETE\n} = statusBarStates; // TODO: rename the function to StatusBarUI on the next major.\n\nfunction StatusBar(props) {\n  const {\n    newFiles,\n    allowNewUpload,\n    isUploadInProgress,\n    isAllPaused,\n    resumableUploads,\n    error,\n    hideUploadButton,\n    hidePauseResumeButton,\n    hideCancelButton,\n    hideRetryButton,\n    recoveredState,\n    uploadState,\n    totalProgress,\n    files,\n    supportsUploadProgress,\n    hideAfterFinish,\n    isSomeGhost,\n    doneButtonHandler,\n    isUploadStarted,\n    i18n,\n    startUpload,\n    uppy,\n    isAllComplete,\n    showProgressDetails,\n    numUploads,\n    complete,\n    totalSize,\n    totalETA,\n    totalUploadedSize\n  } = props;\n\n  function getProgressValue() {\n    switch (uploadState) {\n      case STATE_POSTPROCESSING:\n      case STATE_PREPROCESSING:\n        {\n          const progress = calculateProcessingProgress(files);\n\n          if (progress.mode === 'determinate') {\n            return progress.value * 100;\n          }\n\n          return totalProgress;\n        }\n\n      case STATE_ERROR:\n        {\n          return null;\n        }\n\n      case STATE_UPLOADING:\n        {\n          if (!supportsUploadProgress) {\n            return null;\n          }\n\n          return totalProgress;\n        }\n\n      default:\n        return totalProgress;\n    }\n  }\n\n  function getIsIndeterminate() {\n    switch (uploadState) {\n      case STATE_POSTPROCESSING:\n      case STATE_PREPROCESSING:\n        {\n          const {\n            mode\n          } = calculateProcessingProgress(files);\n          return mode === 'indeterminate';\n        }\n\n      case STATE_UPLOADING:\n        {\n          if (!supportsUploadProgress) {\n            return true;\n          }\n\n          return false;\n        }\n\n      default:\n        return false;\n    }\n  }\n\n  function getIsHidden() {\n    if (recoveredState) {\n      return false;\n    }\n\n    switch (uploadState) {\n      case STATE_WAITING:\n        return hideUploadButton || newFiles === 0;\n\n      case STATE_COMPLETE:\n        return hideAfterFinish;\n\n      default:\n        return false;\n    }\n  }\n\n  const progressValue = getProgressValue();\n  const isHidden = getIsHidden();\n  const width = progressValue != null ? progressValue : 100;\n  const showUploadBtn = !error && newFiles && !isUploadInProgress && !isAllPaused && allowNewUpload && !hideUploadButton;\n  const showCancelBtn = !hideCancelButton && uploadState !== STATE_WAITING && uploadState !== STATE_COMPLETE;\n  const showPauseResumeBtn = resumableUploads && !hidePauseResumeButton && uploadState === STATE_UPLOADING;\n  const showRetryBtn = error && !isAllComplete && !hideRetryButton;\n  const showDoneBtn = doneButtonHandler && uploadState === STATE_COMPLETE;\n  const progressClassNames = classNames('uppy-StatusBar-progress', {\n    'is-indeterminate': getIsIndeterminate()\n  });\n  const statusBarClassNames = classNames('uppy-StatusBar', `is-${uploadState}`, {\n    'has-ghosts': isSomeGhost\n  });\n  return (0, _preact.h)(\"div\", {\n    className: statusBarClassNames,\n    \"aria-hidden\": isHidden\n  }, (0, _preact.h)(\"div\", {\n    className: progressClassNames,\n    style: {\n      width: `${width}%`\n    },\n    role: \"progressbar\",\n    \"aria-label\": `${width}%`,\n    \"aria-valuetext\": `${width}%`,\n    \"aria-valuemin\": \"0\",\n    \"aria-valuemax\": \"100\",\n    \"aria-valuenow\": progressValue\n  }), (() => {\n    switch (uploadState) {\n      case STATE_PREPROCESSING:\n      case STATE_POSTPROCESSING:\n        return (0, _preact.h)(_Components.ProgressBarProcessing, {\n          progress: calculateProcessingProgress(files)\n        });\n\n      case STATE_COMPLETE:\n        return (0, _preact.h)(_Components.ProgressBarComplete, {\n          i18n: i18n\n        });\n\n      case STATE_ERROR:\n        return (0, _preact.h)(_Components.ProgressBarError, {\n          error: error,\n          i18n: i18n,\n          numUploads: numUploads,\n          complete: complete\n        });\n\n      case STATE_UPLOADING:\n        return (0, _preact.h)(_Components.ProgressBarUploading, {\n          i18n: i18n,\n          supportsUploadProgress: supportsUploadProgress,\n          totalProgress: totalProgress,\n          showProgressDetails: showProgressDetails,\n          isUploadStarted: isUploadStarted,\n          isAllComplete: isAllComplete,\n          isAllPaused: isAllPaused,\n          newFiles: newFiles,\n          numUploads: numUploads,\n          complete: complete,\n          totalUploadedSize: totalUploadedSize,\n          totalSize: totalSize,\n          totalETA: totalETA,\n          startUpload: startUpload\n        });\n\n      default:\n        return null;\n    }\n  })(), (0, _preact.h)(\"div\", {\n    className: \"uppy-StatusBar-actions\"\n  }, recoveredState || showUploadBtn ? (0, _preact.h)(_Components.UploadBtn, {\n    newFiles: newFiles,\n    isUploadStarted: isUploadStarted,\n    recoveredState: recoveredState,\n    i18n: i18n,\n    isSomeGhost: isSomeGhost,\n    startUpload: startUpload,\n    uploadState: uploadState\n  }) : null, showRetryBtn ? (0, _preact.h)(_Components.RetryBtn, {\n    i18n: i18n,\n    uppy: uppy\n  }) : null, showPauseResumeBtn ? (0, _preact.h)(_Components.PauseResumeButton, {\n    isAllPaused: isAllPaused,\n    i18n: i18n,\n    isAllComplete: isAllComplete,\n    resumableUploads: resumableUploads,\n    uppy: uppy\n  }) : null, showCancelBtn ? (0, _preact.h)(_Components.CancelBtn, {\n    i18n: i18n,\n    uppy: uppy\n  }) : null, showDoneBtn ? (0, _preact.h)(_Components.DoneBtn, {\n    i18n: i18n,\n    doneButtonHandler: doneButtonHandler\n  }) : null));\n}\n\nmodule.exports = StatusBar;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // Shown in the status bar while files are being uploaded.\n    uploading: 'Uploading',\n    // Shown in the status bar once all files have been uploaded.\n    complete: 'Complete',\n    // Shown in the status bar if an upload failed.\n    uploadFailed: 'Upload failed',\n    // Shown in the status bar while the upload is paused.\n    paused: 'Paused',\n    // Used as the label for the button that retries an upload.\n    retry: 'Retry',\n    // Used as the label for the button that cancels an upload.\n    cancel: 'Cancel',\n    // Used as the label for the button that pauses an upload.\n    pause: 'Pause',\n    // Used as the label for the button that resumes an upload.\n    resume: 'Resume',\n    // Used as the label for the button that resets the upload state after an upload\n    done: 'Done',\n    // When `showProgressDetails` is set, shows the number of files that have been fully uploaded so far.\n    filesUploadedOfTotal: {\n      0: '%{complete} of %{smart_count} file uploaded',\n      1: '%{complete} of %{smart_count} files uploaded'\n    },\n    // When `showProgressDetails` is set, shows the amount of bytes that have been uploaded so far.\n    dataUploadedOfTotal: '%{complete} of %{total}',\n    // When `showProgressDetails` is set, shows an estimation of how long the upload will take to complete.\n    xTimeLeft: '%{time} left',\n    // Used as the label for the button that starts an upload.\n    uploadXFiles: {\n      0: 'Upload %{smart_count} file',\n      1: 'Upload %{smart_count} files'\n    },\n    // Used as the label for the button that starts an upload, if another upload has been started in the past\n    // and new files were added later.\n    uploadXNewFiles: {\n      0: 'Upload +%{smart_count} file',\n      1: 'Upload +%{smart_count} files'\n    },\n    upload: 'Upload',\n    retryUpload: 'Retry upload',\n    xMoreFilesAdded: {\n      0: '%{smart_count} more file added',\n      1: '%{smart_count} more files added'\n    },\n    showErrorDetails: 'Show error details'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\n// TODO: rename this file to StatusBar.jsx on the next major.\nconst getSpeed = require(\"@uppy/utils/lib/getSpeed\");\n\nconst getBytesRemaining = require(\"@uppy/utils/lib/getBytesRemaining\");\n\nconst getTextDirection = require(\"@uppy/utils/lib/getTextDirection\");\n\nconst statusBarStates = require(\"./StatusBarStates.js\");\n\nconst StatusBarUI = require(\"./StatusBar.js\");\n\nconst packageJson = {\n  \"version\": \"2.2.2\"\n};\n\nconst locale = require(\"./locale.js\");\n\nfunction getTotalSpeed(files) {\n  let totalSpeed = 0;\n  files.forEach(file => {\n    totalSpeed += getSpeed(file.progress);\n  });\n  return totalSpeed;\n}\n\nfunction getTotalETA(files) {\n  const totalSpeed = getTotalSpeed(files);\n\n  if (totalSpeed === 0) {\n    return 0;\n  }\n\n  const totalBytesRemaining = files.reduce((total, file) => {\n    return total + getBytesRemaining(file.progress);\n  }, 0);\n  return Math.round(totalBytesRemaining / totalSpeed * 10) / 10;\n}\n\nfunction getUploadingState(error, isAllComplete, recoveredState, files) {\n  if (error && !isAllComplete) {\n    return statusBarStates.STATE_ERROR;\n  }\n\n  if (isAllComplete) {\n    return statusBarStates.STATE_COMPLETE;\n  }\n\n  if (recoveredState) {\n    return statusBarStates.STATE_WAITING;\n  }\n\n  let state = statusBarStates.STATE_WAITING;\n  const fileIDs = Object.keys(files);\n\n  for (let i = 0; i < fileIDs.length; i++) {\n    const {\n      progress\n    } = files[fileIDs[i]]; // If ANY files are being uploaded right now, show the uploading state.\n\n    if (progress.uploadStarted && !progress.uploadComplete) {\n      return statusBarStates.STATE_UPLOADING;\n    } // If files are being preprocessed AND postprocessed at this time, we show the\n    // preprocess state. If any files are being uploaded we show uploading.\n\n\n    if (progress.preprocess && state !== statusBarStates.STATE_UPLOADING) {\n      state = statusBarStates.STATE_PREPROCESSING;\n    } // If NO files are being preprocessed or uploaded right now, but some files are\n    // being postprocessed, show the postprocess state.\n\n\n    if (progress.postprocess && state !== statusBarStates.STATE_UPLOADING && state !== statusBarStates.STATE_PREPROCESSING) {\n      state = statusBarStates.STATE_POSTPROCESSING;\n    }\n  }\n\n  return state;\n}\n/**\n * StatusBar: renders a status bar with upload/pause/resume/cancel/retry buttons,\n * progress percentage and time remaining.\n */\n\n\nclass StatusBar extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n\n    this.startUpload = () => {\n      const {\n        recoveredState\n      } = this.uppy.getState();\n\n      if (recoveredState) {\n        this.uppy.emit('restore-confirmed');\n        return undefined;\n      }\n\n      return this.uppy.upload().catch(() => {// Error logged in Core\n      });\n    };\n\n    this.id = this.opts.id || 'StatusBar';\n    this.title = 'StatusBar';\n    this.type = 'progressindicator';\n    this.defaultLocale = locale; // set default options\n\n    const defaultOptions = {\n      target: 'body',\n      hideUploadButton: false,\n      hideRetryButton: false,\n      hidePauseResumeButton: false,\n      hideCancelButton: false,\n      showProgressDetails: false,\n      hideAfterFinish: true,\n      doneButtonHandler: null\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.i18nInit();\n    this.render = this.render.bind(this);\n    this.install = this.install.bind(this);\n  }\n\n  render(state) {\n    const {\n      capabilities,\n      files,\n      allowNewUpload,\n      totalProgress,\n      error,\n      recoveredState\n    } = state;\n    const {\n      newFiles,\n      startedFiles,\n      completeFiles,\n      inProgressNotPausedFiles,\n      isUploadStarted,\n      isAllComplete,\n      isAllErrored,\n      isAllPaused,\n      isUploadInProgress,\n      isSomeGhost\n    } = this.uppy.getObjectOfFilesPerState(); // If some state was recovered, we want to show Upload button/counter\n    // for all the files, because in this case it\u2019s not an Upload button,\n    // but \u201CConfirm Restore Button\u201D\n\n    const newFilesOrRecovered = recoveredState ? Object.values(files) : newFiles;\n    const totalETA = getTotalETA(inProgressNotPausedFiles);\n    const resumableUploads = !!capabilities.resumableUploads;\n    const supportsUploadProgress = capabilities.uploadProgress !== false;\n    let totalSize = 0;\n    let totalUploadedSize = 0;\n    startedFiles.forEach(file => {\n      totalSize += file.progress.bytesTotal || 0;\n      totalUploadedSize += file.progress.bytesUploaded || 0;\n    });\n    return StatusBarUI({\n      error,\n      uploadState: getUploadingState(error, isAllComplete, recoveredState, state.files || {}),\n      allowNewUpload,\n      totalProgress,\n      totalSize,\n      totalUploadedSize,\n      isAllComplete: false,\n      isAllPaused,\n      isAllErrored,\n      isUploadStarted,\n      isUploadInProgress,\n      isSomeGhost,\n      recoveredState,\n      complete: completeFiles.length,\n      newFiles: newFilesOrRecovered.length,\n      numUploads: startedFiles.length,\n      totalETA,\n      files,\n      i18n: this.i18n,\n      uppy: this.uppy,\n      startUpload: this.startUpload,\n      doneButtonHandler: this.opts.doneButtonHandler,\n      resumableUploads,\n      supportsUploadProgress,\n      showProgressDetails: this.opts.showProgressDetails,\n      hideUploadButton: this.opts.hideUploadButton,\n      hideRetryButton: this.opts.hideRetryButton,\n      hidePauseResumeButton: this.opts.hidePauseResumeButton,\n      hideCancelButton: this.opts.hideCancelButton,\n      hideAfterFinish: this.opts.hideAfterFinish,\n      isTargetDOMEl: this.isTargetDOMEl\n    });\n  }\n\n  onMount() {\n    // Set the text direction if the page has not defined one.\n    const element = this.el;\n    const direction = getTextDirection(element);\n\n    if (!direction) {\n      element.dir = 'ltr';\n    }\n  }\n\n  install() {\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.unmount();\n  }\n\n}\n\nStatusBar.VERSION = packageJson.version;\nmodule.exports = StatusBar;", "\"use strict\";\n\nmodule.exports = require(\"./_StatusBar.js\");", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst TRANSITION_MS = 300;\n\nclass FadeIn extends _preact.Component {\n  constructor() {\n    super(...arguments);\n    this.ref = (0, _preact.createRef)();\n  }\n\n  componentWillEnter(callback) {\n    this.ref.current.style.opacity = '1';\n    this.ref.current.style.transform = 'none';\n    setTimeout(callback, TRANSITION_MS);\n  }\n\n  componentWillLeave(callback) {\n    this.ref.current.style.opacity = '0';\n    this.ref.current.style.transform = 'translateY(350%)';\n    setTimeout(callback, TRANSITION_MS);\n  }\n\n  render() {\n    const {\n      children\n    } = this.props;\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-Informer-animated\",\n      ref: this.ref\n    }, children);\n  }\n\n}\n\nmodule.exports = FadeIn;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\n/* eslint-disable */\n\n/**\n * @source https://github.com/developit/preact-transition-group\n */\nfunction assign(obj, props) {\n  return Object.assign(obj, props);\n}\n\nfunction getKey(vnode, fallback) {\n  var _vnode$key;\n\n  return (_vnode$key = vnode == null ? void 0 : vnode.key) != null ? _vnode$key : fallback;\n}\n\nfunction linkRef(component, name) {\n  const cache = component._ptgLinkedRefs || (component._ptgLinkedRefs = {});\n  return cache[name] || (cache[name] = c => {\n    component.refs[name] = c;\n  });\n}\n\nfunction getChildMapping(children) {\n  const out = {};\n\n  for (let i = 0; i < children.length; i++) {\n    if (children[i] != null) {\n      const key = getKey(children[i], i.toString(36));\n      out[key] = children[i];\n    }\n  }\n\n  return out;\n}\n\nfunction mergeChildMappings(prev, next) {\n  prev = prev || {};\n  next = next || {};\n\n  const getValueForKey = key => next.hasOwnProperty(key) ? next[key] : prev[key]; // For each key of `next`, the list of keys to insert before that key in\n  // the combined list\n\n\n  const nextKeysPending = {};\n  let pendingKeys = [];\n\n  for (const prevKey in prev) {\n    if (next.hasOwnProperty(prevKey)) {\n      if (pendingKeys.length) {\n        nextKeysPending[prevKey] = pendingKeys;\n        pendingKeys = [];\n      }\n    } else {\n      pendingKeys.push(prevKey);\n    }\n  }\n\n  const childMapping = {};\n\n  for (const nextKey in next) {\n    if (nextKeysPending.hasOwnProperty(nextKey)) {\n      for (let i = 0; i < nextKeysPending[nextKey].length; i++) {\n        const pendingNextKey = nextKeysPending[nextKey][i];\n        childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);\n      }\n    }\n\n    childMapping[nextKey] = getValueForKey(nextKey);\n  } // Finally, add the keys which didn't appear before any key in `next`\n\n\n  for (let i = 0; i < pendingKeys.length; i++) {\n    childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);\n  }\n\n  return childMapping;\n}\n\nconst identity = i => i;\n\nclass TransitionGroup extends _preact.Component {\n  constructor(props, context) {\n    super(props, context);\n    this.refs = {};\n    this.state = {\n      children: getChildMapping((0, _preact.toChildArray)((0, _preact.toChildArray)(this.props.children)) || [])\n    };\n    this.performAppear = this.performAppear.bind(this);\n    this.performEnter = this.performEnter.bind(this);\n    this.performLeave = this.performLeave.bind(this);\n  }\n\n  componentWillMount() {\n    this.currentlyTransitioningKeys = {};\n    this.keysToAbortLeave = [];\n    this.keysToEnter = [];\n    this.keysToLeave = [];\n  }\n\n  componentDidMount() {\n    const initialChildMapping = this.state.children;\n\n    for (const key in initialChildMapping) {\n      if (initialChildMapping[key]) {\n        // this.performAppear(getKey(initialChildMapping[key], key));\n        this.performAppear(key);\n      }\n    }\n  }\n\n  componentWillReceiveProps(nextProps) {\n    const nextChildMapping = getChildMapping((0, _preact.toChildArray)(nextProps.children) || []);\n    const prevChildMapping = this.state.children;\n    this.setState(prevState => ({\n      children: mergeChildMappings(prevState.children, nextChildMapping)\n    }));\n    let key;\n\n    for (key in nextChildMapping) {\n      if (nextChildMapping.hasOwnProperty(key)) {\n        const hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key); // We should re-enter the component and abort its leave function\n\n        if (nextChildMapping[key] && hasPrev && this.currentlyTransitioningKeys[key]) {\n          this.keysToEnter.push(key);\n          this.keysToAbortLeave.push(key);\n        } else if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) {\n          this.keysToEnter.push(key);\n        }\n      }\n    }\n\n    for (key in prevChildMapping) {\n      if (prevChildMapping.hasOwnProperty(key)) {\n        const hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key);\n\n        if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) {\n          this.keysToLeave.push(key);\n        }\n      }\n    }\n  }\n\n  componentDidUpdate() {\n    const {\n      keysToEnter\n    } = this;\n    this.keysToEnter = [];\n    keysToEnter.forEach(this.performEnter);\n    const {\n      keysToLeave\n    } = this;\n    this.keysToLeave = [];\n    keysToLeave.forEach(this.performLeave);\n  }\n\n  _finishAbort(key) {\n    const idx = this.keysToAbortLeave.indexOf(key);\n\n    if (idx !== -1) {\n      this.keysToAbortLeave.splice(idx, 1);\n    }\n  }\n\n  performAppear(key) {\n    this.currentlyTransitioningKeys[key] = true;\n    const component = this.refs[key];\n\n    if (component.componentWillAppear) {\n      component.componentWillAppear(this._handleDoneAppearing.bind(this, key));\n    } else {\n      this._handleDoneAppearing(key);\n    }\n  }\n\n  _handleDoneAppearing(key) {\n    const component = this.refs[key];\n\n    if (component.componentDidAppear) {\n      component.componentDidAppear();\n    }\n\n    delete this.currentlyTransitioningKeys[key];\n\n    this._finishAbort(key);\n\n    const currentChildMapping = getChildMapping((0, _preact.toChildArray)(this.props.children) || []);\n\n    if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {\n      // This was removed before it had fully appeared. Remove it.\n      this.performLeave(key);\n    }\n  }\n\n  performEnter(key) {\n    this.currentlyTransitioningKeys[key] = true;\n    const component = this.refs[key];\n\n    if (component.componentWillEnter) {\n      component.componentWillEnter(this._handleDoneEntering.bind(this, key));\n    } else {\n      this._handleDoneEntering(key);\n    }\n  }\n\n  _handleDoneEntering(key) {\n    const component = this.refs[key];\n\n    if (component.componentDidEnter) {\n      component.componentDidEnter();\n    }\n\n    delete this.currentlyTransitioningKeys[key];\n\n    this._finishAbort(key);\n\n    const currentChildMapping = getChildMapping((0, _preact.toChildArray)(this.props.children) || []);\n\n    if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {\n      // This was removed before it had fully entered. Remove it.\n      this.performLeave(key);\n    }\n  }\n\n  performLeave(key) {\n    // If we should immediately abort this leave function,\n    // don't run the leave transition at all.\n    const idx = this.keysToAbortLeave.indexOf(key);\n\n    if (idx !== -1) {\n      return;\n    }\n\n    this.currentlyTransitioningKeys[key] = true;\n    const component = this.refs[key];\n\n    if (component.componentWillLeave) {\n      component.componentWillLeave(this._handleDoneLeaving.bind(this, key));\n    } else {\n      // Note that this is somewhat dangerous b/c it calls setState()\n      // again, effectively mutating the component before all the work\n      // is done.\n      this._handleDoneLeaving(key);\n    }\n  }\n\n  _handleDoneLeaving(key) {\n    // If we should immediately abort the leave,\n    // then skip this altogether\n    const idx = this.keysToAbortLeave.indexOf(key);\n\n    if (idx !== -1) {\n      return;\n    }\n\n    const component = this.refs[key];\n\n    if (component.componentDidLeave) {\n      component.componentDidLeave();\n    }\n\n    delete this.currentlyTransitioningKeys[key];\n    const currentChildMapping = getChildMapping((0, _preact.toChildArray)(this.props.children) || []);\n\n    if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {\n      // This entered again before it fully left. Add it again.\n      this.performEnter(key);\n    } else {\n      const children = assign({}, this.state.children);\n      delete children[key];\n      this.setState({\n        children\n      });\n    }\n  }\n\n  render(_ref, _ref2) {\n    let {\n      childFactory,\n      transitionLeave,\n      transitionName,\n      transitionAppear,\n      transitionEnter,\n      transitionLeaveTimeout,\n      transitionEnterTimeout,\n      transitionAppearTimeout,\n      component,\n      ...props\n    } = _ref;\n    let {\n      children\n    } = _ref2;\n    // TODO: we could get rid of the need for the wrapper node\n    // by cloning a single child\n    const childrenToRender = [];\n\n    for (const key in children) {\n      if (children.hasOwnProperty(key)) {\n        const child = children[key];\n\n        if (child) {\n          const ref = linkRef(this, key),\n                el = (0, _preact.cloneElement)(childFactory(child), {\n            ref,\n            key\n          });\n          childrenToRender.push(el);\n        }\n      }\n    }\n\n    return (0, _preact.h)(component, props, childrenToRender);\n  }\n\n}\n\nTransitionGroup.defaultProps = {\n  component: 'span',\n  childFactory: identity\n};\nmodule.exports = TransitionGroup;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\n/* eslint-disable jsx-a11y/no-noninteractive-element-interactions  */\n\n/* eslint-disable jsx-a11y/click-events-have-key-events */\nconst FadeIn = require(\"./FadeIn.js\");\n\nconst TransitionGroup = require(\"./TransitionGroup.js\");\n\nconst packageJson = {\n  \"version\": \"2.1.1\"\n};\n/**\n * Informer\n * Shows rad message bubbles\n * used like this: `uppy.info('hello world', 'info', 5000)`\n * or for errors: `uppy.info('Error uploading img.jpg', 'error', 5000)`\n *\n */\n\nclass Informer extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n\n    this.render = state => {\n      return (0, _preact.h)(\"div\", {\n        className: \"uppy uppy-Informer\"\n      }, (0, _preact.h)(TransitionGroup, null, state.info.map(info => (0, _preact.h)(FadeIn, {\n        key: info.message\n      }, (0, _preact.h)(\"p\", {\n        role: \"alert\"\n      }, info.message, ' ', info.details && (0, _preact.h)(\"span\", {\n        \"aria-label\": info.details,\n        \"data-microtip-position\": \"top-left\",\n        \"data-microtip-size\": \"medium\",\n        role: \"tooltip\" // eslint-disable-next-line no-alert\n        ,\n        onClick: () => alert(`${info.message} \\n\\n ${info.details}`)\n      }, \"?\"))))));\n    };\n\n    this.type = 'progressindicator';\n    this.id = this.opts.id || 'Informer';\n    this.title = 'Informer'; // set default options\n\n    const defaultOptions = {}; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n  }\n\n  install() {\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n}\n\nInformer.VERSION = packageJson.version;\nmodule.exports = Informer;", "\"use strict\";\n\nmodule.exports = require(\"./Informer.js\");", "!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?t(exports):\"function\"==typeof define&&define.amd?define(\"exifr\",[\"exports\"],t):t((e=\"undefined\"!=typeof globalThis?globalThis:e||self).exifr={})}(this,(function(e){\"use strict\";function t(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}var s=\"undefined\"!=typeof self?self:global;const i=\"undefined\"!=typeof navigator,n=i&&\"undefined\"==typeof HTMLImageElement,r=!(\"undefined\"==typeof global||\"undefined\"==typeof process||!process.versions||!process.versions.node),a=s.Buffer,h=!!a,f=e=>void 0!==e;function l(e){return void 0===e||(e instanceof Map?0===e.size:0===Object.values(e).filter(f).length)}function o(e){let t=new Error(e);throw delete t.stack,t}function u(e){let t=function(e){let t=0;return e.ifd0.enabled&&(t+=1024),e.exif.enabled&&(t+=2048),e.makerNote&&(t+=2048),e.userComment&&(t+=1024),e.gps.enabled&&(t+=512),e.interop.enabled&&(t+=100),e.ifd1.enabled&&(t+=1024),t+2048}(e);return e.jfif.enabled&&(t+=50),e.xmp.enabled&&(t+=2e4),e.iptc.enabled&&(t+=14e3),e.icc.enabled&&(t+=6e3),t}const d=e=>String.fromCharCode.apply(null,e),c=\"undefined\"!=typeof TextDecoder?new TextDecoder(\"utf-8\"):void 0;class p{static from(e,t){return e instanceof this&&e.le===t?e:new p(e,void 0,void 0,t)}constructor(e,t=0,s,i){if(\"boolean\"==typeof i&&(this.le=i),Array.isArray(e)&&(e=new Uint8Array(e)),0===e)this.byteOffset=0,this.byteLength=0;else if(e instanceof ArrayBuffer){void 0===s&&(s=e.byteLength-t);let i=new DataView(e,t,s);this._swapDataView(i)}else if(e instanceof Uint8Array||e instanceof DataView||e instanceof p){void 0===s&&(s=e.byteLength-t),(t+=e.byteOffset)+s>e.byteOffset+e.byteLength&&o(\"Creating view outside of available memory in ArrayBuffer\");let i=new DataView(e.buffer,t,s);this._swapDataView(i)}else if(\"number\"==typeof e){let t=new DataView(new ArrayBuffer(e));this._swapDataView(t)}else o(\"Invalid input argument for BufferView: \"+e)}_swapArrayBuffer(e){this._swapDataView(new DataView(e))}_swapBuffer(e){this._swapDataView(new DataView(e.buffer,e.byteOffset,e.byteLength))}_swapDataView(e){this.dataView=e,this.buffer=e.buffer,this.byteOffset=e.byteOffset,this.byteLength=e.byteLength}_lengthToEnd(e){return this.byteLength-e}set(e,t,s=p){return e instanceof DataView||e instanceof p?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Uint8Array||o(\"BufferView.set(): Invalid data argument.\"),this.toUint8().set(e,t),new s(this,t,e.byteLength)}subarray(e,t){return t=t||this._lengthToEnd(e),new p(this,e,t)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(e,t){return new Uint8Array(this.buffer,this.byteOffset+e,t)}getString(e=0,t=this.byteLength){let s=this.getUint8Array(e,t);return i=s,c?c.decode(i):h?Buffer.from(i).toString(\"utf8\"):decodeURIComponent(escape(d(i)));var i}getLatin1String(e=0,t=this.byteLength){let s=this.getUint8Array(e,t);return d(s)}getUnicodeString(e=0,t=this.byteLength){const s=[];for(let i=0;i<t&&e+i<this.byteLength;i+=2)s.push(this.getUint16(e+i));return d(s)}getInt8(e){return this.dataView.getInt8(e)}getUint8(e){return this.dataView.getUint8(e)}getInt16(e,t=this.le){return this.dataView.getInt16(e,t)}getInt32(e,t=this.le){return this.dataView.getInt32(e,t)}getUint16(e,t=this.le){return this.dataView.getUint16(e,t)}getUint32(e,t=this.le){return this.dataView.getUint32(e,t)}getFloat32(e,t=this.le){return this.dataView.getFloat32(e,t)}getFloat64(e,t=this.le){return this.dataView.getFloat64(e,t)}getFloat(e,t=this.le){return this.dataView.getFloat32(e,t)}getDouble(e,t=this.le){return this.dataView.getFloat64(e,t)}getUintBytes(e,t,s){switch(t){case 1:return this.getUint8(e,s);case 2:return this.getUint16(e,s);case 4:return this.getUint32(e,s);case 8:return this.getUint64&&this.getUint64(e,s)}}getUint(e,t,s){switch(t){case 8:return this.getUint8(e,s);case 16:return this.getUint16(e,s);case 32:return this.getUint32(e,s);case 64:return this.getUint64&&this.getUint64(e,s)}}toString(e){return this.dataView.toString(e,this.constructor.name)}ensureChunk(){}}function g(e,t){o(`${e} '${t}' was not loaded, try using full build of exifr.`)}class m extends Map{constructor(e){super(),this.kind=e}get(e,t){return this.has(e)||g(this.kind,e),t&&(e in t||function(e,t){o(`Unknown ${e} '${t}'.`)}(this.kind,e),t[e].enabled||g(this.kind,e)),super.get(e)}keyList(){return Array.from(this.keys())}}var y=new m(\"file parser\"),b=new m(\"segment parser\"),w=new m(\"file reader\");let k=s.fetch;const O=\"Invalid input argument\";function v(e,t){return(s=e).startsWith(\"data:\")||s.length>1e4?A(e,t,\"base64\"):r&&e.includes(\"://\")?S(e,t,\"url\",U):r?A(e,t,\"fs\"):i?S(e,t,\"url\",U):void o(O);var s}async function S(e,t,s,i){return w.has(s)?A(e,t,s):i?async function(e,t){let s=await t(e);return new p(s)}(e,i):void o(`Parser ${s} is not loaded`)}async function A(e,t,s){let i=new(w.get(s))(e,t);return await i.read(),i}const U=e=>k(e).then((e=>e.arrayBuffer())),x=e=>new Promise(((t,s)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=s,i.readAsArrayBuffer(e)}));class C extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}}function B(e,t,s){let i=new C;for(let[e,t]of s)i.set(e,t);if(Array.isArray(t))for(let s of t)e.set(s,i);else e.set(t,i);return i}function V(e,t,s){let i,n=e.get(t);for(i of s)n.set(i[0],i[1])}const I=new Map,L=new Map,T=new Map,P=37500,z=37510,F=33723,j=34675,E=34665,_=34853,D=40965,M=[\"chunked\",\"firstChunkSize\",\"firstChunkSizeNode\",\"firstChunkSizeBrowser\",\"chunkSize\",\"chunkLimit\"],N=[\"jfif\",\"xmp\",\"icc\",\"iptc\",\"ihdr\"],R=[\"tiff\",...N],$=[\"ifd0\",\"ifd1\",\"exif\",\"gps\",\"interop\"],K=[...R,...$],W=[\"makerNote\",\"userComment\"],X=[\"translateKeys\",\"translateValues\",\"reviveValues\",\"multiSegment\"],H=[...X,\"sanitize\",\"mergeOutput\",\"silentErrors\"];class Y{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}}class G extends Y{get needed(){return this.enabled||this.deps.size>0}constructor(e,s,i,n){if(super(),t(this,\"enabled\",!1),t(this,\"skip\",new Set),t(this,\"pick\",new Set),t(this,\"deps\",new Set),t(this,\"translateKeys\",!1),t(this,\"translateValues\",!1),t(this,\"reviveValues\",!1),this.key=e,this.enabled=s,this.parse=this.enabled,this.applyInheritables(n),this.canBeFiltered=$.includes(e),this.canBeFiltered&&(this.dict=I.get(e)),void 0!==i)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(\"object\"==typeof i){if(this.enabled=!0,this.parse=!1!==i.parse,this.canBeFiltered){let{pick:e,skip:t}=i;e&&e.length>0&&this.translateTagSet(e,this.pick),t&&t.length>0&&this.translateTagSet(t,this.skip)}this.applyInheritables(i)}else!0===i||!1===i?this.parse=this.enabled=i:o(`Invalid options argument: ${i}`)}applyInheritables(e){let t,s;for(t of X)s=e[t],void 0!==s&&(this[t]=s)}translateTagSet(e,t){if(this.dict){let s,i,{tagKeys:n,tagValues:r}=this.dict;for(s of e)\"string\"==typeof s?(i=r.indexOf(s),-1===i&&(i=n.indexOf(Number(s))),-1!==i&&t.add(Number(n[i]))):t.add(s)}else for(let s of e)t.add(s)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,te(this.pick,this.deps)):this.enabled&&this.pick.size>0&&te(this.pick,this.deps)}}var J={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},q=new Map;class Q extends Y{static useCached(e){let t=q.get(e);return void 0!==t||(t=new this(e),q.set(e,t)),t}constructor(e){super(),!0===e?this.setupFromTrue():void 0===e?this.setupFromUndefined():Array.isArray(e)?this.setupFromArray(e):\"object\"==typeof e?this.setupFromObject(e):o(`Invalid options argument ${e}`),void 0===this.firstChunkSize&&(this.firstChunkSize=i?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let e;for(e of M)this[e]=J[e];for(e of H)this[e]=J[e];for(e of W)this[e]=J[e];for(e of K)this[e]=new G(e,J[e],void 0,this)}setupFromTrue(){let e;for(e of M)this[e]=J[e];for(e of H)this[e]=J[e];for(e of W)this[e]=!0;for(e of K)this[e]=new G(e,!0,void 0,this)}setupFromArray(e){let t;for(t of M)this[t]=J[t];for(t of H)this[t]=J[t];for(t of W)this[t]=J[t];for(t of K)this[t]=new G(t,!1,void 0,this);this.setupGlobalFilters(e,void 0,$)}setupFromObject(e){let t;for(t of($.ifd0=$.ifd0||$.image,$.ifd1=$.ifd1||$.thumbnail,Object.assign(this,e),M))this[t]=ee(e[t],J[t]);for(t of H)this[t]=ee(e[t],J[t]);for(t of W)this[t]=ee(e[t],J[t]);for(t of R)this[t]=new G(t,J[t],e[t],this);for(t of $)this[t]=new G(t,J[t],e[t],this.tiff);this.setupGlobalFilters(e.pick,e.skip,$,K),!0===e.tiff?this.batchEnableWithBool($,!0):!1===e.tiff?this.batchEnableWithUserValue($,e):Array.isArray(e.tiff)?this.setupGlobalFilters(e.tiff,void 0,$):\"object\"==typeof e.tiff&&this.setupGlobalFilters(e.tiff.pick,e.tiff.skip,$)}batchEnableWithBool(e,t){for(let s of e)this[s].enabled=t}batchEnableWithUserValue(e,t){for(let s of e){let e=t[s];this[s].enabled=!1!==e&&void 0!==e}}setupGlobalFilters(e,t,s,i=s){if(e&&e.length){for(let e of i)this[e].enabled=!1;let t=Z(e,s);for(let[e,s]of t)te(this[e].pick,s),this[e].enabled=!0}else if(t&&t.length){let e=Z(t,s);for(let[t,s]of e)te(this[t].skip,s)}}filterNestedSegmentTags(){let{ifd0:e,exif:t,xmp:s,iptc:i,icc:n}=this;this.makerNote?t.deps.add(P):t.skip.add(P),this.userComment?t.deps.add(z):t.skip.add(z),s.enabled||e.skip.add(700),i.enabled||e.skip.add(F),n.enabled||e.skip.add(j)}traverseTiffDependencyTree(){let{ifd0:e,exif:t,gps:s,interop:i}=this;i.needed&&(t.deps.add(D),e.deps.add(D)),t.needed&&e.deps.add(E),s.needed&&e.deps.add(_),this.tiff.enabled=$.some((e=>!0===this[e].enabled))||this.makerNote||this.userComment;for(let e of $)this[e].finalizeFilters()}get onlyTiff(){return!N.map((e=>this[e].enabled)).some((e=>!0===e))&&this.tiff.enabled}checkLoadedPlugins(){for(let e of R)this[e].enabled&&!b.has(e)&&g(\"segment parser\",e)}}function Z(e,t){let s,i,n,r,a=[];for(n of t){for(r of(s=I.get(n),i=[],s))(e.includes(r[0])||e.includes(r[1]))&&i.push(r[0]);i.length&&a.push([n,i])}return a}function ee(e,t){return void 0!==e?e:void 0!==t?t:void 0}function te(e,t){for(let s of t)e.add(s)}t(Q,\"default\",J);class se{constructor(e){t(this,\"parsers\",{}),t(this,\"output\",{}),t(this,\"errors\",[]),t(this,\"pushToErrors\",(e=>this.errors.push(e))),this.options=Q.useCached(e)}async read(e){this.file=await function(e,t){return\"string\"==typeof e?v(e,t):i&&!n&&e instanceof HTMLImageElement?v(e.src,t):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new p(e):i&&e instanceof Blob?S(e,t,\"blob\",x):void o(O)}(e,this.options)}setup(){if(this.fileParser)return;let{file:e}=this,t=e.getUint16(0);for(let[s,i]of y)if(i.canHandle(e,t))return this.fileParser=new i(this.options,this.file,this.parsers),e[s]=!0;this.file.close&&this.file.close(),o(\"Unknown file format\")}async parse(){let{output:e,errors:t}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),t.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&t.length>0&&(e.errors=t),l(s=e)?void 0:s;var s}async executeParsers(){let{output:e}=this;await this.fileParser.parse();let t=Object.values(this.parsers).map((async t=>{let s=await t.parse();t.assignToOutput(e,s)}));this.options.silentErrors&&(t=t.map((e=>e.catch(this.pushToErrors)))),await Promise.all(t)}async extractThumbnail(){this.setup();let{options:e,file:t}=this,s=b.get(\"tiff\",e);var i;if(t.tiff?i={start:0,type:\"tiff\"}:t.jpeg&&(i=await this.fileParser.getOrFindSegment(\"tiff\")),void 0===i)return;let n=await this.fileParser.ensureSegmentChunk(i),r=this.parsers.tiff=new s(n,e,t),a=await r.extractThumbnail();return t.close&&t.close(),a}}async function ie(e,t){let s=new se(t);return await s.read(e),s.parse()}var ne=Object.freeze({__proto__:null,parse:ie,Exifr:se,fileParsers:y,segmentParsers:b,fileReaders:w,tagKeys:I,tagValues:L,tagRevivers:T,createDictionary:B,extendDictionary:V,fetchUrlAsArrayBuffer:U,readBlobAsArrayBuffer:x,chunkedProps:M,otherSegments:N,segments:R,tiffBlocks:$,segmentsAndBlocks:K,tiffExtractables:W,inheritables:X,allFormatters:H,Options:Q});class re{static findPosition(e,t){let s=e.getUint16(t+2)+2,i=\"function\"==typeof this.headerLength?this.headerLength(e,t,s):this.headerLength,n=t+i,r=s-i;return{offset:t,length:s,headerLength:i,start:n,size:r,end:n+r}}static parse(e,t={}){return new this(e,new Q({[this.type]:t}),e).parse()}normalizeInput(e){return e instanceof p?e:new p(e)}constructor(e,s={},i){t(this,\"errors\",[]),t(this,\"raw\",new Map),t(this,\"handleError\",(e=>{if(!this.options.silentErrors)throw e;this.errors.push(e.message)})),this.chunk=this.normalizeInput(e),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=s,this.localOptions=s[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(e,t){let s=T.get(t),i=L.get(t),n=I.get(t),r=this.options[t],a=r.reviveValues&&!!s,h=r.translateValues&&!!i,f=r.translateKeys&&!!n,l={};for(let[t,r]of e)a&&s.has(t)?r=s.get(t)(r):h&&i.has(t)&&(r=this.translateValue(r,i.get(t))),f&&n.has(t)&&(t=n.get(t)||t),l[t]=r;return l}translateValue(e,t){return t[e]||t.DEFAULT||e}assignToOutput(e,t){this.assignObjectToOutput(e,this.constructor.type,t)}assignObjectToOutput(e,t,s){if(this.globalOptions.mergeOutput)return Object.assign(e,s);e[t]?Object.assign(e[t],s):e[t]=s}}t(re,\"headerLength\",4),t(re,\"type\",void 0),t(re,\"multiSegment\",!1),t(re,\"canHandle\",(()=>!1));function ae(e){return 192===e||194===e||196===e||219===e||221===e||218===e||254===e}function he(e){return e>=224&&e<=239}function fe(e,t,s){for(let[i,n]of b)if(n.canHandle(e,t,s))return i}class le extends class{constructor(e,s,i){t(this,\"errors\",[]),t(this,\"ensureSegmentChunk\",(async e=>{let t=e.start,s=e.size||65536;if(this.file.chunked)if(this.file.available(t,s))e.chunk=this.file.subarray(t,s);else try{e.chunk=await this.file.readChunk(t,s)}catch(t){o(`Couldn't read segment: ${JSON.stringify(e)}. ${t.message}`)}else this.file.byteLength>t+s?e.chunk=this.file.subarray(t,s):void 0===e.size?e.chunk=this.file.subarray(t):o(\"Segment unreachable: \"+JSON.stringify(e));return e.chunk})),this.extendOptions&&this.extendOptions(e),this.options=e,this.file=s,this.parsers=i}injectSegment(e,t){this.options[e].enabled&&this.createParser(e,t)}createParser(e,t){let s=new(b.get(e))(t,this.options,this.file);return this.parsers[e]=s}createParsers(e){for(let t of e){let{type:e,chunk:s}=t,i=this.options[e];if(i&&i.enabled){let t=this.parsers[e];t&&t.append||t||this.createParser(e,s)}}}async readSegments(e){let t=e.map(this.ensureSegmentChunk);await Promise.all(t)}}{constructor(...e){super(...e),t(this,\"appSegments\",[]),t(this,\"jpegSegments\",[]),t(this,\"unknownSegments\",[])}static canHandle(e,t){return 65496===t}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(e){!0===e?(this.findAll=!0,this.wanted=new Set(b.keyList())):(e=void 0===e?b.keyList().filter((e=>this.options[e].enabled)):e.filter((e=>this.options[e].enabled&&b.has(e))),this.findAll=!1,this.remaining=new Set(e),this.wanted=new Set(e)),this.unfinishedMultiSegment=!1}async findAppSegments(e=0,t){this.setupSegmentFinderArgs(t);let{file:s,findAll:i,wanted:n,remaining:r}=this;if(!i&&this.file.chunked&&(i=Array.from(n).some((e=>{let t=b.get(e),s=this.options[e];return t.multiSegment&&s.multiSegment})),i&&await this.file.readWhole()),e=this.findAppSegmentsInRange(e,s.byteLength),!this.options.onlyTiff&&s.chunked){let t=!1;for(;r.size>0&&!t&&(s.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:i}=s,n=this.appSegments.some((e=>!this.file.available(e.offset||e.start,e.length||e.size)));if(t=e>i&&!n?!await s.readNextChunk(e):!await s.readNextChunk(i),void 0===(e=this.findAppSegmentsInRange(e,s.byteLength)))return}}}findAppSegmentsInRange(e,t){t-=2;let s,i,n,r,a,h,{file:f,findAll:l,wanted:o,remaining:u,options:d}=this;for(;e<t;e++)if(255===f.getUint8(e))if(s=f.getUint8(e+1),he(s)){if(i=f.getUint16(e+2),n=fe(f,e,i),n&&o.has(n)&&(r=b.get(n),a=r.findPosition(f,e),h=d[n],a.type=n,this.appSegments.push(a),!l&&(r.multiSegment&&h.multiSegment?(this.unfinishedMultiSegment=a.chunkNumber<a.chunkCount,this.unfinishedMultiSegment||u.delete(n)):u.delete(n),0===u.size)))break;d.recordUnknownSegments&&(a=re.findPosition(f,e),a.marker=s,this.unknownSegments.push(a)),e+=i+1}else if(ae(s)){if(i=f.getUint16(e+2),218===s&&!1!==d.stopAfterSos)return;d.recordJpegSegments&&this.jpegSegments.push({offset:e,length:i,marker:s}),e+=i+1}return e}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let e=function(e,t){let s,i,n,r=new Map;for(let a=0;a<e.length;a++)s=e[a],i=s[t],r.has(i)?n=r.get(i):r.set(i,n=[]),n.push(s);return Array.from(r)}(this.appSegments,\"type\");this.mergedAppSegments=e.map((([e,t])=>{let s=b.get(e,this.options);if(s.handleMultiSegments){return{type:e,chunk:s.handleMultiSegments(t)}}return t[0]}))}getSegment(e){return this.appSegments.find((t=>t.type===e))}async getOrFindSegment(e){let t=this.getSegment(e);return void 0===t&&(await this.findAppSegments(0,[e]),t=this.getSegment(e)),t}}t(le,\"type\",\"jpeg\"),y.set(\"jpeg\",le);const oe=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4];class ue extends re{parseHeader(){var e=this.chunk.getUint16();18761===e?this.le=!0:19789===e&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(e,t,s=new Map){let{pick:i,skip:n}=this.options[t];i=new Set(i);let r=i.size>0,a=0===n.size,h=this.chunk.getUint16(e);e+=2;for(let f=0;f<h;f++){let h=this.chunk.getUint16(e);if(r){if(i.has(h)&&(s.set(h,this.parseTag(e,h,t)),i.delete(h),0===i.size))break}else!a&&n.has(h)||s.set(h,this.parseTag(e,h,t));e+=12}return s}parseTag(e,t,s){let{chunk:i}=this,n=i.getUint16(e+2),r=i.getUint32(e+4),a=oe[n];if(a*r<=4?e+=8:e=i.getUint32(e+8),(n<1||n>13)&&o(`Invalid TIFF value type. block: ${s.toUpperCase()}, tag: ${t.toString(16)}, type: ${n}, offset ${e}`),e>i.byteLength&&o(`Invalid TIFF value offset. block: ${s.toUpperCase()}, tag: ${t.toString(16)}, type: ${n}, offset ${e} is outside of chunk size ${i.byteLength}`),1===n)return i.getUint8Array(e,r);if(2===n)return\"\"===(h=function(e){for(;e.endsWith(\"\\0\");)e=e.slice(0,-1);return e}(h=i.getString(e,r)).trim())?void 0:h;var h;if(7===n)return i.getUint8Array(e,r);if(1===r)return this.parseTagValue(n,e);{let t=new(function(e){switch(e){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}}(n))(r),s=a;for(let i=0;i<r;i++)t[i]=this.parseTagValue(n,e),e+=s;return t}}parseTagValue(e,t){let{chunk:s}=this;switch(e){case 1:return s.getUint8(t);case 3:return s.getUint16(t);case 4:return s.getUint32(t);case 5:return s.getUint32(t)/s.getUint32(t+4);case 6:return s.getInt8(t);case 8:return s.getInt16(t);case 9:return s.getInt32(t);case 10:return s.getInt32(t)/s.getInt32(t+4);case 11:return s.getFloat(t);case 12:return s.getDouble(t);case 13:return s.getUint32(t);default:o(`Invalid tiff type ${e}`)}}}class de extends ue{static canHandle(e,t){return 225===e.getUint8(t+1)&&1165519206===e.getUint32(t+4)&&0===e.getUint16(t+8)}async parse(){this.parseHeader();let{options:e}=this;return e.ifd0.enabled&&await this.parseIfd0Block(),e.exif.enabled&&await this.safeParse(\"parseExifBlock\"),e.gps.enabled&&await this.safeParse(\"parseGpsBlock\"),e.interop.enabled&&await this.safeParse(\"parseInteropBlock\"),e.ifd1.enabled&&await this.safeParse(\"parseThumbnailBlock\"),this.createOutput()}safeParse(e){let t=this[e]();return void 0!==t.catch&&(t=t.catch(this.handleError)),t}findIfd0Offset(){void 0===this.ifd0Offset&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(void 0===this.ifd1Offset){this.findIfd0Offset();let e=this.chunk.getUint16(this.ifd0Offset),t=this.ifd0Offset+2+12*e;this.ifd1Offset=this.chunk.getUint32(t)}}parseBlock(e,t){let s=new Map;return this[t]=s,this.parseTags(e,t,s),s}async parseIfd0Block(){if(this.ifd0)return;let{file:e}=this;this.findIfd0Offset(),this.ifd0Offset<8&&o(\"Malformed EXIF data\"),!e.chunked&&this.ifd0Offset>e.byteLength&&o(`IFD0 offset points to outside of file.\\nthis.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${e.byteLength}`),e.tiff&&await e.ensureChunk(this.ifd0Offset,u(this.options));let t=this.parseBlock(this.ifd0Offset,\"ifd0\");return 0!==t.size?(this.exifOffset=t.get(E),this.interopOffset=t.get(D),this.gpsOffset=t.get(_),this.xmp=t.get(700),this.iptc=t.get(F),this.icc=t.get(j),this.options.sanitize&&(t.delete(E),t.delete(D),t.delete(_),t.delete(700),t.delete(F),t.delete(j)),t):void 0}async parseExifBlock(){if(this.exif)return;if(this.ifd0||await this.parseIfd0Block(),void 0===this.exifOffset)return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,u(this.options));let e=this.parseBlock(this.exifOffset,\"exif\");return this.interopOffset||(this.interopOffset=e.get(D)),this.makerNote=e.get(P),this.userComment=e.get(z),this.options.sanitize&&(e.delete(D),e.delete(P),e.delete(z)),this.unpack(e,41728),this.unpack(e,41729),e}unpack(e,t){let s=e.get(t);s&&1===s.length&&e.set(t,s[0])}async parseGpsBlock(){if(this.gps)return;if(this.ifd0||await this.parseIfd0Block(),void 0===this.gpsOffset)return;let e=this.parseBlock(this.gpsOffset,\"gps\");return e&&e.has(2)&&e.has(4)&&(e.set(\"latitude\",ce(...e.get(2),e.get(1))),e.set(\"longitude\",ce(...e.get(4),e.get(3)))),e}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),void 0!==this.interopOffset||this.exif||await this.parseExifBlock(),void 0!==this.interopOffset))return this.parseBlock(this.interopOffset,\"interop\")}async parseThumbnailBlock(e=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||e))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,\"ifd1\"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),void 0===this.ifd1)return;let e=this.ifd1.get(513),t=this.ifd1.get(514);return this.chunk.getUint8Array(e,t)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let e,t,s,i={};for(t of $)if(e=this[t],!l(e))if(s=this.canTranslate?this.translateBlock(e,t):Object.fromEntries(e),this.options.mergeOutput){if(\"ifd1\"===t)continue;Object.assign(i,s)}else i[t]=s;return this.makerNote&&(i.makerNote=this.makerNote),this.userComment&&(i.userComment=this.userComment),i}assignToOutput(e,t){if(this.globalOptions.mergeOutput)Object.assign(e,t);else for(let[s,i]of Object.entries(t))this.assignObjectToOutput(e,s,i)}}function ce(e,t,s,i){var n=e+t/60+s/3600;return\"S\"!==i&&\"W\"!==i||(n*=-1),n}t(de,\"type\",\"tiff\"),t(de,\"headerLength\",10),b.set(\"tiff\",de);var pe=Object.freeze({__proto__:null,default:ne,Exifr:se,fileParsers:y,segmentParsers:b,fileReaders:w,tagKeys:I,tagValues:L,tagRevivers:T,createDictionary:B,extendDictionary:V,fetchUrlAsArrayBuffer:U,readBlobAsArrayBuffer:x,chunkedProps:M,otherSegments:N,segments:R,tiffBlocks:$,segmentsAndBlocks:K,tiffExtractables:W,inheritables:X,allFormatters:H,Options:Q,parse:ie});const ge={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},me=Object.assign({},ge,{firstChunkSize:4e4,gps:[1,2,3,4]});const ye=Object.assign({},ge,{tiff:!1,ifd1:!0,mergeOutput:!1});const be=Object.assign({},ge,{firstChunkSize:4e4,ifd0:[274]});async function we(e){let t=new se(be);await t.read(e);let s=await t.parse();if(s&&s.ifd0)return s.ifd0[274]}const ke=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}});if(e.rotateCanvas=!0,e.rotateCss=!0,\"object\"==typeof navigator){let t=navigator.userAgent;if(t.includes(\"iPad\")||t.includes(\"iPhone\")){let s=t.match(/OS (\\d+)_(\\d+)/);if(s){let[,t,i]=s,n=Number(t)+.1*Number(i);e.rotateCanvas=n<13.4,e.rotateCss=!1}}else if(t.includes(\"OS X 10\")){let[,s]=t.match(/OS X 10[_.](\\d+)/);e.rotateCanvas=e.rotateCss=Number(s)<15}if(t.includes(\"Chrome/\")){let[,s]=t.match(/Chrome\\/(\\d+)/);e.rotateCanvas=e.rotateCss=Number(s)<81}else if(t.includes(\"Firefox/\")){let[,s]=t.match(/Firefox\\/(\\d+)/);e.rotateCanvas=e.rotateCss=Number(s)<77}}class Oe extends p{constructor(...e){super(...e),t(this,\"ranges\",new ve),0!==this.byteLength&&this.ranges.add(0,this.byteLength)}_tryExtend(e,t,s){if(0===e&&0===this.byteLength&&s){let e=new DataView(s.buffer||s,s.byteOffset,s.byteLength);this._swapDataView(e)}else{let s=e+t;if(s>this.byteLength){let{dataView:e}=this._extend(s);this._swapDataView(e)}}}_extend(e){let t;t=h?a.allocUnsafe(e):new Uint8Array(e);let s=new DataView(t.buffer,t.byteOffset,t.byteLength);return t.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:t,dataView:s}}subarray(e,t,s=!1){return t=t||this._lengthToEnd(e),s&&this._tryExtend(e,t),this.ranges.add(e,t),super.subarray(e,t)}set(e,t,s=!1){s&&this._tryExtend(t,e.byteLength,e);let i=super.set(e,t);return this.ranges.add(t,i.byteLength),i}async ensureChunk(e,t){this.chunked&&(this.ranges.available(e,t)||await this.readChunk(e,t))}available(e,t){return this.ranges.available(e,t)}}class ve{constructor(){t(this,\"list\",[])}get length(){return this.list.length}add(e,t,s=0){let i=e+t,n=this.list.filter((t=>Se(e,t.offset,i)||Se(e,t.end,i)));if(n.length>0){e=Math.min(e,...n.map((e=>e.offset))),i=Math.max(i,...n.map((e=>e.end))),t=i-e;let s=n.shift();s.offset=e,s.length=t,s.end=i,this.list=this.list.filter((e=>!n.includes(e)))}else this.list.push({offset:e,length:t,end:i})}available(e,t){let s=e+t;return this.list.some((t=>t.offset<=e&&s<=t.end))}}function Se(e,t,s){return e<=t&&t<=s}class Ae extends Oe{constructor(e,s){super(0),t(this,\"chunksRead\",0),this.input=e,this.options=s}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(e=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let t=this.options.chunkSize,s=await this.readChunk(e,t);return!!s&&s.byteLength===t}async readChunk(e,t){if(this.chunksRead++,0!==(t=this.safeWrapAddress(e,t)))return this._readChunk(e,t)}safeWrapAddress(e,t){return void 0!==this.size&&e+t>this.size?Math.max(0,this.size-e):t}get nextChunkOffset(){if(0!==this.ranges.list.length)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return void 0!==this.size&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}}w.set(\"blob\",class extends Ae{async readWhole(){this.chunked=!1;let e=await x(this.input);this._swapArrayBuffer(e)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(e,t){let s=t?e+t:void 0,i=this.input.slice(e,s),n=await x(i);return this.set(n,e,!0)}}),e.Exifr=se,e.Options=Q,e.allFormatters=H,e.chunkedProps=M,e.createDictionary=B,e.default=pe,e.extendDictionary=V,e.fetchUrlAsArrayBuffer=U,e.fileParsers=y,e.fileReaders=w,e.gps=async function(e){let t=new se(me);await t.read(e);let s=await t.parse();if(s&&s.gps){let{latitude:e,longitude:t}=s.gps;return{latitude:e,longitude:t}}},e.gpsOnlyOptions=me,e.inheritables=X,e.orientation=we,e.orientationOnlyOptions=be,e.otherSegments=N,e.parse=ie,e.readBlobAsArrayBuffer=x,e.rotation=async function(t){let s=await we(t);return Object.assign({canvas:e.rotateCanvas,css:e.rotateCss},ke[s])},e.rotations=ke,e.segmentParsers=b,e.segments=R,e.segmentsAndBlocks=K,e.tagKeys=I,e.tagRevivers=T,e.tagValues=L,e.thumbnail=async function(e){let t=new se(ye);await t.read(e);let s=await t.extractThumbnail();return s&&h?a.from(s):s},e.thumbnailOnlyOptions=ye,e.thumbnailUrl=async function(e){let t=await this.thumbnail(e);if(void 0!==t){let e=new Blob([t]);return URL.createObjectURL(e)}},e.tiffBlocks=$,e.tiffExtractables=W,Object.defineProperty(e,\"__esModule\",{value:!0})}));\n", "\"use strict\";\n\nconst DATA_URL_PATTERN = /^data:([^/]+\\/[^,;]+(?:[^,]*?))(;base64)?,([\\s\\S]*)$/;\n\nfunction dataURItoBlob(dataURI, opts, toFile) {\n  var _ref, _opts$mimeType;\n\n  // get the base64 data\n  const dataURIData = DATA_URL_PATTERN.exec(dataURI); // user may provide mime type, if not get it from data URI\n\n  const mimeType = (_ref = (_opts$mimeType = opts.mimeType) != null ? _opts$mimeType : dataURIData == null ? void 0 : dataURIData[1]) != null ? _ref : 'plain/text';\n  let data;\n\n  if (dataURIData[2] != null) {\n    const binary = atob(decodeURIComponent(dataURIData[3]));\n    const bytes = new Uint8Array(binary.length);\n\n    for (let i = 0; i < binary.length; i++) {\n      bytes[i] = binary.charCodeAt(i);\n    }\n\n    data = [bytes];\n  } else {\n    data = [decodeURIComponent(dataURIData[3])];\n  } // Convert to a File?\n\n\n  if (toFile) {\n    return new File(data, opts.name || '', {\n      type: mimeType\n    });\n  }\n\n  return new Blob(data, {\n    type: mimeType\n  });\n}\n\nmodule.exports = dataURItoBlob;", "\"use strict\";\n\nfunction isObjectURL(url) {\n  return url.startsWith('blob:');\n}\n\n/**\n * Check if a URL string is an object URL from `URL.createObjectURL`.\n *\n * @param {string} url\n * @returns {boolean}\n */\nmodule.exports = isObjectURL;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    generatingThumbnails: 'Generating thumbnails...'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _miniUmd = require(\"exifr/dist/mini.umd.js\");\n\nconst dataURItoBlob = require(\"@uppy/utils/lib/dataURItoBlob\");\n\nconst isObjectURL = require(\"@uppy/utils/lib/isObjectURL\");\n\nconst isPreviewSupported = require(\"@uppy/utils/lib/isPreviewSupported\");\n\nconst locale = require(\"./locale.js\");\n\nconst packageJson = {\n  \"version\": \"2.2.2\"\n};\n/**\n * Save a <canvas> element's content to a Blob object.\n *\n * @param {HTMLCanvasElement} canvas\n * @returns {Promise}\n */\n\nfunction canvasToBlob(canvas, type, quality) {\n  try {\n    canvas.getContext('2d').getImageData(0, 0, 1, 1);\n  } catch (err) {\n    if (err.code === 18) {\n      return Promise.reject(new Error('cannot read image, probably an svg with external resources'));\n    }\n  }\n\n  if (canvas.toBlob) {\n    return new Promise(resolve => {\n      canvas.toBlob(resolve, type, quality);\n    }).then(blob => {\n      if (blob === null) {\n        throw new Error('cannot read image, probably an svg with external resources');\n      }\n\n      return blob;\n    });\n  }\n\n  return Promise.resolve().then(() => {\n    return dataURItoBlob(canvas.toDataURL(type, quality), {});\n  }).then(blob => {\n    if (blob === null) {\n      throw new Error('could not extract blob, probably an old browser');\n    }\n\n    return blob;\n  });\n}\n\nfunction rotateImage(image, translate) {\n  let w = image.width;\n  let h = image.height;\n\n  if (translate.deg === 90 || translate.deg === 270) {\n    w = image.height;\n    h = image.width;\n  }\n\n  const canvas = document.createElement('canvas');\n  canvas.width = w;\n  canvas.height = h;\n  const context = canvas.getContext('2d');\n  context.translate(w / 2, h / 2);\n\n  if (translate.canvas) {\n    context.rotate(translate.rad);\n    context.scale(translate.scaleX, translate.scaleY);\n  }\n\n  context.drawImage(image, -image.width / 2, -image.height / 2, image.width, image.height);\n  return canvas;\n}\n/**\n * Make sure the image doesn\u2019t exceed browser/device canvas limits.\n * For ios with 256 RAM and ie\n */\n\n\nfunction protect(image) {\n  // https://stackoverflow.com/questions/6081483/maximum-size-of-a-canvas-element\n  const ratio = image.width / image.height;\n  const maxSquare = 5000000; // ios max canvas square\n\n  const maxSize = 4096; // ie max canvas dimensions\n\n  let maxW = Math.floor(Math.sqrt(maxSquare * ratio));\n  let maxH = Math.floor(maxSquare / Math.sqrt(maxSquare * ratio));\n\n  if (maxW > maxSize) {\n    maxW = maxSize;\n    maxH = Math.round(maxW / ratio);\n  }\n\n  if (maxH > maxSize) {\n    maxH = maxSize;\n    maxW = Math.round(ratio * maxH);\n  }\n\n  if (image.width > maxW) {\n    const canvas = document.createElement('canvas');\n    canvas.width = maxW;\n    canvas.height = maxH;\n    canvas.getContext('2d').drawImage(image, 0, 0, maxW, maxH);\n    return canvas;\n  }\n\n  return image;\n}\n/**\n * The Thumbnail Generator plugin\n */\n\n\nclass ThumbnailGenerator extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n\n    this.onFileAdded = file => {\n      if (!file.preview && file.data && isPreviewSupported(file.type) && !file.isRemote) {\n        this.addToQueue(file.id);\n      }\n    };\n\n    this.onCancelRequest = file => {\n      const index = this.queue.indexOf(file.id);\n\n      if (index !== -1) {\n        this.queue.splice(index, 1);\n      }\n    };\n\n    this.onFileRemoved = file => {\n      const index = this.queue.indexOf(file.id);\n\n      if (index !== -1) {\n        this.queue.splice(index, 1);\n      } // Clean up object URLs.\n\n\n      if (file.preview && isObjectURL(file.preview)) {\n        URL.revokeObjectURL(file.preview);\n      }\n    };\n\n    this.onRestored = () => {\n      const restoredFiles = this.uppy.getFiles().filter(file => file.isRestored);\n      restoredFiles.forEach(file => {\n        // Only add blob URLs; they are likely invalid after being restored.\n        if (!file.preview || isObjectURL(file.preview)) {\n          this.addToQueue(file.id);\n        }\n      });\n    };\n\n    this.onAllFilesRemoved = () => {\n      this.queue = [];\n    };\n\n    this.waitUntilAllProcessed = fileIDs => {\n      fileIDs.forEach(fileID => {\n        const file = this.uppy.getFile(fileID);\n        this.uppy.emit('preprocess-progress', file, {\n          mode: 'indeterminate',\n          message: this.i18n('generatingThumbnails')\n        });\n      });\n\n      const emitPreprocessCompleteForAll = () => {\n        fileIDs.forEach(fileID => {\n          const file = this.uppy.getFile(fileID);\n          this.uppy.emit('preprocess-complete', file);\n        });\n      };\n\n      return new Promise(resolve => {\n        if (this.queueProcessing) {\n          this.uppy.once('thumbnail:all-generated', () => {\n            emitPreprocessCompleteForAll();\n            resolve();\n          });\n        } else {\n          emitPreprocessCompleteForAll();\n          resolve();\n        }\n      });\n    };\n\n    this.type = 'modifier';\n    this.id = this.opts.id || 'ThumbnailGenerator';\n    this.title = 'Thumbnail Generator';\n    this.queue = [];\n    this.queueProcessing = false;\n    this.defaultThumbnailDimension = 200;\n    this.thumbnailType = this.opts.thumbnailType || 'image/jpeg';\n    this.defaultLocale = locale;\n    const defaultOptions = {\n      thumbnailWidth: null,\n      thumbnailHeight: null,\n      waitForThumbnailsBeforeUpload: false,\n      lazy: false\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.i18nInit();\n\n    if (this.opts.lazy && this.opts.waitForThumbnailsBeforeUpload) {\n      throw new Error('ThumbnailGenerator: The `lazy` and `waitForThumbnailsBeforeUpload` options are mutually exclusive. Please ensure at most one of them is set to `true`.');\n    }\n  }\n  /**\n   * Create a thumbnail for the given Uppy file object.\n   *\n   * @param {{data: Blob}} file\n   * @param {number} targetWidth\n   * @param {number} targetHeight\n   * @returns {Promise}\n   */\n\n\n  createThumbnail(file, targetWidth, targetHeight) {\n    const originalUrl = URL.createObjectURL(file.data);\n    const onload = new Promise((resolve, reject) => {\n      const image = new Image();\n      image.src = originalUrl;\n      image.addEventListener('load', () => {\n        URL.revokeObjectURL(originalUrl);\n        resolve(image);\n      });\n      image.addEventListener('error', event => {\n        URL.revokeObjectURL(originalUrl);\n        reject(event.error || new Error('Could not create thumbnail'));\n      });\n    });\n    const orientationPromise = (0, _miniUmd.rotation)(file.data).catch(() => 1);\n    return Promise.all([onload, orientationPromise]).then(_ref => {\n      let [image, orientation] = _ref;\n      const dimensions = this.getProportionalDimensions(image, targetWidth, targetHeight, orientation.deg);\n      const rotatedImage = this.rotateImage(image, orientation);\n      const resizedImage = this.resizeImage(rotatedImage, dimensions.width, dimensions.height);\n      return this.canvasToBlob(resizedImage, this.thumbnailType, 80);\n    }).then(blob => {\n      return URL.createObjectURL(blob);\n    });\n  }\n  /**\n   * Get the new calculated dimensions for the given image and a target width\n   * or height. If both width and height are given, only width is taken into\n   * account. If neither width nor height are given, the default dimension\n   * is used.\n   */\n\n\n  getProportionalDimensions(img, width, height, rotation) {\n    // eslint-disable-line no-shadow\n    let aspect = img.width / img.height;\n\n    if (rotation === 90 || rotation === 270) {\n      aspect = img.height / img.width;\n    }\n\n    if (width != null) {\n      return {\n        width,\n        height: Math.round(width / aspect)\n      };\n    }\n\n    if (height != null) {\n      return {\n        width: Math.round(height * aspect),\n        height\n      };\n    }\n\n    return {\n      width: this.defaultThumbnailDimension,\n      height: Math.round(this.defaultThumbnailDimension / aspect)\n    };\n  }\n  /**\n   * Resize an image to the target `width` and `height`.\n   *\n   * Returns a Canvas with the resized image on it.\n   */\n\n\n  resizeImage(image, targetWidth, targetHeight) {\n    // Resizing in steps refactored to use a solution from\n    // https://blog.uploadcare.com/image-resize-in-browsers-is-broken-e38eed08df01\n    let img = this.protect(image);\n    let steps = Math.ceil(Math.log2(img.width / targetWidth));\n\n    if (steps < 1) {\n      steps = 1;\n    }\n\n    let sW = targetWidth * 2 ** (steps - 1);\n    let sH = targetHeight * 2 ** (steps - 1);\n    const x = 2;\n\n    while (steps--) {\n      const canvas = document.createElement('canvas');\n      canvas.width = sW;\n      canvas.height = sH;\n      canvas.getContext('2d').drawImage(img, 0, 0, sW, sH);\n      img = canvas;\n      sW = Math.round(sW / x);\n      sH = Math.round(sH / x);\n    }\n\n    return img;\n  }\n  /**\n   * Set the preview URL for a file.\n   */\n\n\n  setPreviewURL(fileID, preview) {\n    this.uppy.setFileState(fileID, {\n      preview\n    });\n  }\n\n  addToQueue(item) {\n    this.queue.push(item);\n\n    if (this.queueProcessing === false) {\n      this.processQueue();\n    }\n  }\n\n  processQueue() {\n    this.queueProcessing = true;\n\n    if (this.queue.length > 0) {\n      const current = this.uppy.getFile(this.queue.shift());\n\n      if (!current) {\n        this.uppy.log('[ThumbnailGenerator] file was removed before a thumbnail could be generated, but not removed from the queue. This is probably a bug', 'error');\n        return Promise.resolve();\n      }\n\n      return this.requestThumbnail(current).catch(() => {}) // eslint-disable-line node/handle-callback-err\n      .then(() => this.processQueue());\n    }\n\n    this.queueProcessing = false;\n    this.uppy.log('[ThumbnailGenerator] Emptied thumbnail queue');\n    this.uppy.emit('thumbnail:all-generated');\n    return Promise.resolve();\n  }\n\n  requestThumbnail(file) {\n    if (isPreviewSupported(file.type) && !file.isRemote) {\n      return this.createThumbnail(file, this.opts.thumbnailWidth, this.opts.thumbnailHeight).then(preview => {\n        this.setPreviewURL(file.id, preview);\n        this.uppy.log(`[ThumbnailGenerator] Generated thumbnail for ${file.id}`);\n        this.uppy.emit('thumbnail:generated', this.uppy.getFile(file.id), preview);\n      }).catch(err => {\n        this.uppy.log(`[ThumbnailGenerator] Failed thumbnail for ${file.id}:`, 'warning');\n        this.uppy.log(err, 'warning');\n        this.uppy.emit('thumbnail:error', this.uppy.getFile(file.id), err);\n      });\n    }\n\n    return Promise.resolve();\n  }\n\n  install() {\n    this.uppy.on('file-removed', this.onFileRemoved);\n    this.uppy.on('cancel-all', this.onAllFilesRemoved);\n\n    if (this.opts.lazy) {\n      this.uppy.on('thumbnail:request', this.onFileAdded);\n      this.uppy.on('thumbnail:cancel', this.onCancelRequest);\n    } else {\n      this.uppy.on('file-added', this.onFileAdded);\n      this.uppy.on('restored', this.onRestored);\n    }\n\n    if (this.opts.waitForThumbnailsBeforeUpload) {\n      this.uppy.addPreProcessor(this.waitUntilAllProcessed);\n    }\n  }\n\n  uninstall() {\n    this.uppy.off('file-removed', this.onFileRemoved);\n    this.uppy.off('cancel-all', this.onAllFilesRemoved);\n\n    if (this.opts.lazy) {\n      this.uppy.off('thumbnail:request', this.onFileAdded);\n      this.uppy.off('thumbnail:cancel', this.onCancelRequest);\n    } else {\n      this.uppy.off('file-added', this.onFileAdded);\n      this.uppy.off('restored', this.onRestored);\n    }\n\n    if (this.opts.waitForThumbnailsBeforeUpload) {\n      this.uppy.removePreProcessor(this.waitUntilAllProcessed);\n    }\n  }\n\n}\n\nThumbnailGenerator.VERSION = packageJson.version;\nmodule.exports = ThumbnailGenerator; // TODO: remove these methods from the prototype in the next major.\n\nThumbnailGenerator.prototype.canvasToBlob = canvasToBlob;\nThumbnailGenerator.prototype.protect = protect;\nThumbnailGenerator.prototype.rotateImage = rotateImage;", "\"use strict\";\n\nconst isDOMElement = require(\"./isDOMElement.js\");\n/**\n * Find one or more DOM elements.\n *\n * @param {string|Node} element\n * @returns {Node[]|null}\n */\n\n\nfunction findAllDOMElements(element) {\n  if (typeof element === 'string') {\n    const elements = document.querySelectorAll(element);\n    return elements.length === 0 ? null : Array.from(elements);\n  }\n\n  if (typeof element === 'object' && isDOMElement(element)) {\n    return [element];\n  }\n\n  return null;\n}\n\nmodule.exports = findAllDOMElements;", "\"use strict\";\n\nfunction getFilesAndDirectoriesFromDirectory(directoryReader, oldEntries, logDropError, _ref) {\n  let {\n    onSuccess\n  } = _ref;\n  directoryReader.readEntries(entries => {\n    const newEntries = [...oldEntries, ...entries]; // According to the FileSystem API spec, getFilesAndDirectoriesFromDirectory()\n    // must be called until it calls the onSuccess with an empty array.\n\n    if (entries.length) {\n      queueMicrotask(() => {\n        getFilesAndDirectoriesFromDirectory(directoryReader, newEntries, logDropError, {\n          onSuccess\n        });\n      }); // Done iterating this particular directory\n    } else {\n      onSuccess(newEntries);\n    }\n  }, // Make sure we resolve on error anyway, it's fine if only one directory couldn't be parsed!\n  error => {\n    logDropError(error);\n    onSuccess(oldEntries);\n  });\n}\n\n/**\n * Recursive function, calls the original callback() when the directory is entirely parsed.\n *\n * @param {FileSystemDirectoryReader} directoryReader\n * @param {Array} oldEntries\n * @param {Function} logDropError\n * @param {Function} callback - called with ([ all files and directories in that directoryReader ])\n */\nmodule.exports = getFilesAndDirectoriesFromDirectory;", "\"use strict\";\n\nconst getFilesAndDirectoriesFromDirectory = require(\"./getFilesAndDirectoriesFromDirectory.js\");\n/**\n * Interop between deprecated webkitGetAsEntry and standard getAsFileSystemHandle.\n */\n\n\nfunction getAsFileSystemHandleFromEntry(entry, logDropError) {\n  if (entry == null) return entry;\n  return {\n    // eslint-disable-next-line no-nested-ternary\n    kind: entry.isFile ? 'file' : entry.isDirectory ? 'directory' : undefined,\n    name: entry.name,\n\n    getFile() {\n      return new Promise((resolve, reject) => entry.file(resolve, reject));\n    },\n\n    async *values() {\n      // If the file is a directory.\n      const directoryReader = entry.createReader();\n      const entries = await new Promise(resolve => {\n        getFilesAndDirectoriesFromDirectory(directoryReader, [], logDropError, {\n          onSuccess: dirEntries => resolve(dirEntries.map(file => getAsFileSystemHandleFromEntry(file, logDropError)))\n        });\n      });\n      yield* entries;\n    }\n\n  };\n}\n\nasync function* createPromiseToAddFileOrParseDirectory(entry, relativePath) {\n  // For each dropped item, - make sure it's a file/directory, and start deepening in!\n  if (entry.kind === 'file') {\n    const file = await entry.getFile();\n\n    if (file !== null) {\n      file.relativePath = relativePath ? `${relativePath}/${entry.name}` : null;\n      yield file;\n    }\n  } else if (entry.kind === 'directory') {\n    for await (const handle of entry.values()) {\n      yield* createPromiseToAddFileOrParseDirectory(handle, `${relativePath}/${entry.name}`);\n    }\n  }\n}\n\nasync function* getFilesFromDataTransfer(dataTransfer, logDropError) {\n  const entries = await Promise.all(Array.from(dataTransfer.items, async item => {\n    var _await$item$getAsFile;\n\n    const lastResortFile = item.getAsFile(); // Chromium bug, see https://github.com/transloadit/uppy/issues/3505.\n\n    const entry = (_await$item$getAsFile = await (item.getAsFileSystemHandle == null ? void 0 : item.getAsFileSystemHandle())) != null ? _await$item$getAsFile : getAsFileSystemHandleFromEntry(item.webkitGetAsEntry(), logDropError);\n    return {\n      lastResortFile,\n      entry\n    };\n  }));\n\n  for (const {\n    lastResortFile,\n    entry\n  } of entries) {\n    // :entry can be null when we drop the url e.g.\n    if (entry != null) {\n      try {\n        yield* createPromiseToAddFileOrParseDirectory(entry, '');\n      } catch (err) {\n        if (lastResortFile) {\n          yield lastResortFile;\n        } else {\n          logDropError(err);\n        }\n      }\n    }\n  }\n}\n\nmodule.exports = getFilesFromDataTransfer;", "\"use strict\";\n\nconst toArray = require(\"../../toArray.js\"); // .files fallback, should be implemented in any browser\n\n\nfunction fallbackApi(dataTransfer) {\n  const files = toArray(dataTransfer.files);\n  return Promise.resolve(files);\n}\n\nmodule.exports = fallbackApi;", "\"use strict\";\n\nconst webkitGetAsEntryApi = require(\"./utils/webkitGetAsEntryApi/index.js\");\n\nconst fallbackApi = require(\"./utils/fallbackApi.js\");\n/**\n * Returns a promise that resolves to the array of dropped files (if a folder is\n * dropped, and browser supports folder parsing - promise resolves to the flat\n * array of all files in all directories).\n * Each file has .relativePath prop appended to it (e.g. \"/docs/Prague/ticket_from_prague_to_ufa.pdf\")\n * if browser supports it. Otherwise it's undefined.\n *\n * @param {DataTransfer} dataTransfer\n * @param {Function} logDropError - a function that's called every time some\n * folder or some file error out (e.g. because of the folder name being too long\n * on Windows). Notice that resulting promise will always be resolved anyway.\n *\n * @returns {Promise} - Array<File>\n */\n\n\nasync function getDroppedFiles(dataTransfer, _temp) {\n  let {\n    logDropError = () => {}\n  } = _temp === void 0 ? {} : _temp;\n\n  // Get all files from all subdirs. Works (at least) in Chrome, Mozilla, and Safari\n  try {\n    const accumulator = [];\n\n    for await (const file of webkitGetAsEntryApi(dataTransfer, logDropError)) {\n      accumulator.push(file);\n    }\n\n    return accumulator; // Otherwise just return all first-order files\n  } catch {\n    return fallbackApi(dataTransfer);\n  }\n}\n\nmodule.exports = getDroppedFiles;", "'use strict';\n\nvar safeIsNaN = Number.isNaN ||\n    function ponyfill(value) {\n        return typeof value === 'number' && value !== value;\n    };\nfunction isEqual(first, second) {\n    if (first === second) {\n        return true;\n    }\n    if (safeIsNaN(first) && safeIsNaN(second)) {\n        return true;\n    }\n    return false;\n}\nfunction areInputsEqual(newInputs, lastInputs) {\n    if (newInputs.length !== lastInputs.length) {\n        return false;\n    }\n    for (var i = 0; i < newInputs.length; i++) {\n        if (!isEqual(newInputs[i], lastInputs[i])) {\n            return false;\n        }\n    }\n    return true;\n}\n\nfunction memoizeOne(resultFn, isEqual) {\n    if (isEqual === void 0) { isEqual = areInputsEqual; }\n    var lastThis;\n    var lastArgs = [];\n    var lastResult;\n    var calledOnce = false;\n    function memoized() {\n        var newArgs = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            newArgs[_i] = arguments[_i];\n        }\n        if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {\n            return lastResult;\n        }\n        lastResult = resultFn.apply(this, newArgs);\n        calledOnce = true;\n        lastThis = this;\n        lastArgs = newArgs;\n        return lastResult;\n    }\n    return memoized;\n}\n\nmodule.exports = memoizeOne;\n", "/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n    nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n *   console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n  return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n *  Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n *  The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n *  Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n *   'leading': true,\n *   'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n  var lastArgs,\n      lastThis,\n      maxWait,\n      result,\n      timerId,\n      lastCallTime,\n      lastInvokeTime = 0,\n      leading = false,\n      maxing = false,\n      trailing = true;\n\n  if (typeof func != 'function') {\n    throw new TypeError(FUNC_ERROR_TEXT);\n  }\n  wait = toNumber(wait) || 0;\n  if (isObject(options)) {\n    leading = !!options.leading;\n    maxing = 'maxWait' in options;\n    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n    trailing = 'trailing' in options ? !!options.trailing : trailing;\n  }\n\n  function invokeFunc(time) {\n    var args = lastArgs,\n        thisArg = lastThis;\n\n    lastArgs = lastThis = undefined;\n    lastInvokeTime = time;\n    result = func.apply(thisArg, args);\n    return result;\n  }\n\n  function leadingEdge(time) {\n    // Reset any `maxWait` timer.\n    lastInvokeTime = time;\n    // Start the timer for the trailing edge.\n    timerId = setTimeout(timerExpired, wait);\n    // Invoke the leading edge.\n    return leading ? invokeFunc(time) : result;\n  }\n\n  function remainingWait(time) {\n    var timeSinceLastCall = time - lastCallTime,\n        timeSinceLastInvoke = time - lastInvokeTime,\n        result = wait - timeSinceLastCall;\n\n    return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n  }\n\n  function shouldInvoke(time) {\n    var timeSinceLastCall = time - lastCallTime,\n        timeSinceLastInvoke = time - lastInvokeTime;\n\n    // Either this is the first call, activity has stopped and we're at the\n    // trailing edge, the system time has gone backwards and we're treating\n    // it as the trailing edge, or we've hit the `maxWait` limit.\n    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n  }\n\n  function timerExpired() {\n    var time = now();\n    if (shouldInvoke(time)) {\n      return trailingEdge(time);\n    }\n    // Restart the timer.\n    timerId = setTimeout(timerExpired, remainingWait(time));\n  }\n\n  function trailingEdge(time) {\n    timerId = undefined;\n\n    // Only invoke if we have `lastArgs` which means `func` has been\n    // debounced at least once.\n    if (trailing && lastArgs) {\n      return invokeFunc(time);\n    }\n    lastArgs = lastThis = undefined;\n    return result;\n  }\n\n  function cancel() {\n    if (timerId !== undefined) {\n      clearTimeout(timerId);\n    }\n    lastInvokeTime = 0;\n    lastArgs = lastCallTime = lastThis = timerId = undefined;\n  }\n\n  function flush() {\n    return timerId === undefined ? result : trailingEdge(now());\n  }\n\n  function debounced() {\n    var time = now(),\n        isInvoking = shouldInvoke(time);\n\n    lastArgs = arguments;\n    lastThis = this;\n    lastCallTime = time;\n\n    if (isInvoking) {\n      if (timerId === undefined) {\n        return leadingEdge(lastCallTime);\n      }\n      if (maxing) {\n        // Handle invocations in a tight loop.\n        timerId = setTimeout(timerExpired, wait);\n        return invokeFunc(lastCallTime);\n      }\n    }\n    if (timerId === undefined) {\n      timerId = setTimeout(timerExpired, wait);\n    }\n    return result;\n  }\n  debounced.cancel = cancel;\n  debounced.flush = flush;\n  return debounced;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n  var type = typeof value;\n  return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n  return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n  return typeof value == 'symbol' ||\n    (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n  if (typeof value == 'number') {\n    return value;\n  }\n  if (isSymbol(value)) {\n    return NAN;\n  }\n  if (isObject(value)) {\n    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n    value = isObject(other) ? (other + '') : other;\n  }\n  if (typeof value != 'string') {\n    return value === 0 ? value : +value;\n  }\n  value = value.replace(reTrim, '');\n  var isBinary = reIsBinary.test(value);\n  return (isBinary || reIsOctal.test(value))\n    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n    : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = debounce;\n", "\"use strict\";\n\nconst debounce = require(\"lodash.debounce\");\n\nconst FOCUSABLE_ELEMENTS = require(\"@uppy/utils/lib/FOCUSABLE_ELEMENTS\");\n\nconst getActiveOverlayEl = require(\"./getActiveOverlayEl.js\");\n/*\n  Focuses on some element in the currently topmost overlay.\n\n  1. If there are some [data-uppy-super-focusable] elements rendered already - focuses\n     on the first superfocusable element, and leaves focus up to the control of\n     a user (until currently focused element disappears from the screen [which\n     can happen when overlay changes, or, e.g., when we click on a folder in googledrive]).\n  2. If there are no [data-uppy-super-focusable] elements yet (or ever) - focuses\n     on the first focusable element, but switches focus if superfocusable elements appear on next render.\n*/\n\n\nfunction createSuperFocus() {\n  let lastFocusWasOnSuperFocusableEl = false;\n\n  const superFocus = (dashboardEl, activeOverlayType) => {\n    const overlayEl = getActiveOverlayEl(dashboardEl, activeOverlayType);\n    const isFocusInOverlay = overlayEl.contains(document.activeElement); // If focus is already in the topmost overlay, AND on last update we focused on the superfocusable\n    // element - then leave focus up to the user.\n    // [Practical check] without this line, typing in the search input in googledrive overlay won't work.\n\n    if (isFocusInOverlay && lastFocusWasOnSuperFocusableEl) return;\n    const superFocusableEl = overlayEl.querySelector('[data-uppy-super-focusable]'); // If we are already in the topmost overlay, AND there are no super focusable elements yet, - leave focus up to the user.\n    // [Practical check] without this line, if you are in an empty folder in google drive, and something's uploading in the\n    // bg, - focus will be jumping to Done all the time.\n\n    if (isFocusInOverlay && !superFocusableEl) return;\n\n    if (superFocusableEl) {\n      superFocusableEl.focus({\n        preventScroll: true\n      });\n      lastFocusWasOnSuperFocusableEl = true;\n    } else {\n      const firstEl = overlayEl.querySelector(FOCUSABLE_ELEMENTS);\n      firstEl == null ? void 0 : firstEl.focus({\n        preventScroll: true\n      });\n      lastFocusWasOnSuperFocusableEl = false;\n    }\n  }; // ___Why do we need to debounce?\n  //    1. To deal with animations: overlay changes via animations, which results in the DOM updating AFTER plugin.update()\n  //       already executed.\n  //    [Practical check] without debounce, if we open the Url overlay, and click 'Done', Dashboard won't get focused again.\n  //    [Practical check] if we delay 250ms instead of 260ms - IE11 won't get focused in same situation.\n  //    2. Performance: there can be many state update()s in a second, and this function is called every time.\n\n\n  return debounce(superFocus, 260);\n}\n\nmodule.exports = createSuperFocus;", "\"use strict\";\n\nfunction isDragDropSupported() {\n  const div = document.body;\n\n  if (!('draggable' in div) || !('ondragstart' in div && 'ondrop' in div)) {\n    return false;\n  }\n\n  if (!('FormData' in window)) {\n    return false;\n  }\n\n  if (!('FileReader' in window)) {\n    return false;\n  }\n\n  return true;\n}\n\n/**\n * Checks if the browser supports Drag & Drop (not supported on mobile devices, for example).\n *\n * @returns {boolean}\n */\nmodule.exports = isDragDropSupported;", "module.exports = function isShallowEqual (a, b) {\n  if (a === b) return true\n  for (var i in a) if (!(i in b)) return false\n  for (var i in b) if (a[i] !== b[i]) return false\n  return true\n}\n", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction iconImage() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"25\",\n    height: \"25\",\n    viewBox: \"0 0 25 25\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"#686DE0\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M5 7v10h15V7H5zm0-1h15a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1z\",\n    fillRule: \"nonzero\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M6.35 17.172l4.994-5.026a.5.5 0 0 1 .707 0l2.16 2.16 3.505-3.505a.5.5 0 0 1 .707 0l2.336 2.31-.707.72-1.983-1.97-3.505 3.505a.5.5 0 0 1-.707 0l-2.16-2.159-3.938 3.939-1.409.026z\",\n    fillRule: \"nonzero\"\n  }), (0, _preact.h)(\"circle\", {\n    cx: \"7.5\",\n    cy: \"9.5\",\n    r: \"1.5\"\n  })));\n}\n\nfunction iconAudio() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"25\",\n    height: \"25\",\n    viewBox: \"0 0 25 25\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M9.5 18.64c0 1.14-1.145 2-2.5 2s-2.5-.86-2.5-2c0-1.14 1.145-2 2.5-2 .557 0 1.079.145 1.5.396V7.25a.5.5 0 0 1 .379-.485l9-2.25A.5.5 0 0 1 18.5 5v11.64c0 1.14-1.145 2-2.5 2s-2.5-.86-2.5-2c0-1.14 1.145-2 2.5-2 .557 0 1.079.145 1.5.396V8.67l-8 2v7.97zm8-11v-2l-8 2v2l8-2zM7 19.64c.855 0 1.5-.484 1.5-1s-.645-1-1.5-1-1.5.484-1.5 1 .645 1 1.5 1zm9-2c.855 0 1.5-.484 1.5-1s-.645-1-1.5-1-1.5.484-1.5 1 .645 1 1.5 1z\",\n    fill: \"#049BCF\",\n    fillRule: \"nonzero\"\n  }));\n}\n\nfunction iconVideo() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"25\",\n    height: \"25\",\n    viewBox: \"0 0 25 25\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M16 11.834l4.486-2.691A1 1 0 0 1 22 10v6a1 1 0 0 1-1.514.857L16 14.167V17a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v2.834zM15 9H5v8h10V9zm1 4l5 3v-6l-5 3z\",\n    fill: \"#19AF67\",\n    fillRule: \"nonzero\"\n  }));\n}\n\nfunction iconPDF() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"25\",\n    height: \"25\",\n    viewBox: \"0 0 25 25\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M9.766 8.295c-.691-1.843-.539-3.401.747-3.726 1.643-.414 2.505.938 2.39 3.299-.039.79-.194 1.662-.537 3.148.324.49.66.967 1.055 1.51.17.231.382.488.629.757 1.866-.128 3.653.114 4.918.655 1.487.635 2.192 1.685 1.614 2.84-.566 1.133-1.839 1.084-3.416.249-1.141-.604-2.457-1.634-3.51-2.707a13.467 13.467 0 0 0-2.238.426c-1.392 4.051-4.534 6.453-5.707 4.572-.986-1.58 1.38-4.206 4.914-5.375.097-.322.185-.656.264-1.001.08-.353.306-1.31.407-1.737-.678-1.059-1.2-2.031-1.53-2.91zm2.098 4.87c-.033.144-.068.287-.104.427l.033-.01-.012.038a14.065 14.065 0 0 1 1.02-.197l-.032-.033.052-.004a7.902 7.902 0 0 1-.208-.271c-.197-.27-.38-.526-.555-.775l-.006.028-.002-.003c-.076.323-.148.632-.186.8zm5.77 2.978c1.143.605 1.832.632 2.054.187.26-.519-.087-1.034-1.113-1.473-.911-.39-2.175-.608-3.55-.608.845.766 1.787 1.459 2.609 1.894zM6.559 18.789c.14.223.693.16 1.425-.413.827-.648 1.61-1.747 2.208-3.206-2.563 1.064-4.102 2.867-3.633 3.62zm5.345-10.97c.088-1.793-.351-2.48-1.146-2.28-.473.119-.564 1.05-.056 2.405.213.566.52 1.188.908 1.859.18-.858.268-1.453.294-1.984z\",\n    fill: \"#E2514A\",\n    fillRule: \"nonzero\"\n  }));\n}\n\nfunction iconArchive() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"25\",\n    height: \"25\",\n    viewBox: \"0 0 25 25\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M10.45 2.05h1.05a.5.5 0 0 1 .5.5v.024a.5.5 0 0 1-.5.5h-1.05a.5.5 0 0 1-.5-.5V2.55a.5.5 0 0 1 .5-.5zm2.05 1.024h1.05a.5.5 0 0 1 .5.5V3.6a.5.5 0 0 1-.5.5H12.5a.5.5 0 0 1-.5-.5v-.025a.5.5 0 0 1 .5-.5v-.001zM10.45 0h1.05a.5.5 0 0 1 .5.5v.025a.5.5 0 0 1-.5.5h-1.05a.5.5 0 0 1-.5-.5V.5a.5.5 0 0 1 .5-.5zm2.05 1.025h1.05a.5.5 0 0 1 .5.5v.024a.5.5 0 0 1-.5.5H12.5a.5.5 0 0 1-.5-.5v-.024a.5.5 0 0 1 .5-.5zm-2.05 3.074h1.05a.5.5 0 0 1 .5.5v.025a.5.5 0 0 1-.5.5h-1.05a.5.5 0 0 1-.5-.5v-.025a.5.5 0 0 1 .5-.5zm2.05 1.025h1.05a.5.5 0 0 1 .5.5v.024a.5.5 0 0 1-.5.5H12.5a.5.5 0 0 1-.5-.5v-.024a.5.5 0 0 1 .5-.5zm-2.05 1.024h1.05a.5.5 0 0 1 .5.5v.025a.5.5 0 0 1-.5.5h-1.05a.5.5 0 0 1-.5-.5v-.025a.5.5 0 0 1 .5-.5zm2.05 1.025h1.05a.5.5 0 0 1 .5.5v.025a.5.5 0 0 1-.5.5H12.5a.5.5 0 0 1-.5-.5v-.025a.5.5 0 0 1 .5-.5zm-2.05 1.025h1.05a.5.5 0 0 1 .5.5v.025a.5.5 0 0 1-.5.5h-1.05a.5.5 0 0 1-.5-.5v-.025a.5.5 0 0 1 .5-.5zm2.05 1.025h1.05a.5.5 0 0 1 .5.5v.024a.5.5 0 0 1-.5.5H12.5a.5.5 0 0 1-.5-.5v-.024a.5.5 0 0 1 .5-.5zm-1.656 3.074l-.82 5.946c.52.302 1.174.458 1.976.458.803 0 1.455-.156 1.975-.458l-.82-5.946h-2.311zm0-1.025h2.312c.512 0 .946.378 1.015.885l.82 5.946c.056.412-.142.817-.501 1.026-.686.398-1.515.597-2.49.597-.974 0-1.804-.199-2.49-.597a1.025 1.025 0 0 1-.5-1.026l.819-5.946c.07-.507.503-.885 1.015-.885zm.545 6.6a.5.5 0 0 1-.397-.561l.143-.999a.5.5 0 0 1 .495-.429h.74a.5.5 0 0 1 .495.43l.143.998a.5.5 0 0 1-.397.561c-.404.08-.819.08-1.222 0z\",\n    fill: \"#00C469\",\n    fillRule: \"nonzero\"\n  }));\n}\n\nfunction iconFile() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"25\",\n    height: \"25\",\n    viewBox: \"0 0 25 25\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"#A7AFB7\",\n    fillRule: \"nonzero\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M5.5 22a.5.5 0 0 1-.5-.5v-18a.5.5 0 0 1 .5-.5h10.719a.5.5 0 0 1 .367.16l3.281 3.556a.5.5 0 0 1 .133.339V21.5a.5.5 0 0 1-.5.5h-14zm.5-1h13V7.25L16 4H6v17z\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M15 4v3a1 1 0 0 0 1 1h3V7h-3V4h-1z\"\n  })));\n}\n\nfunction iconText() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"25\",\n    height: \"25\",\n    viewBox: \"0 0 25 25\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M4.5 7h13a.5.5 0 1 1 0 1h-13a.5.5 0 0 1 0-1zm0 3h15a.5.5 0 1 1 0 1h-15a.5.5 0 1 1 0-1zm0 3h15a.5.5 0 1 1 0 1h-15a.5.5 0 1 1 0-1zm0 3h10a.5.5 0 1 1 0 1h-10a.5.5 0 1 1 0-1z\",\n    fill: \"#5A5E69\",\n    fillRule: \"nonzero\"\n  }));\n}\n\nfunction getIconByMime(fileType) {\n  const defaultChoice = {\n    color: '#838999',\n    icon: iconFile()\n  };\n  if (!fileType) return defaultChoice;\n  const fileTypeGeneral = fileType.split('/')[0];\n  const fileTypeSpecific = fileType.split('/')[1]; // Text\n\n  if (fileTypeGeneral === 'text') {\n    return {\n      color: '#5a5e69',\n      icon: iconText()\n    };\n  } // Image\n\n\n  if (fileTypeGeneral === 'image') {\n    return {\n      color: '#686de0',\n      icon: iconImage()\n    };\n  } // Audio\n\n\n  if (fileTypeGeneral === 'audio') {\n    return {\n      color: '#068dbb',\n      icon: iconAudio()\n    };\n  } // Video\n\n\n  if (fileTypeGeneral === 'video') {\n    return {\n      color: '#19af67',\n      icon: iconVideo()\n    };\n  } // PDF\n\n\n  if (fileTypeGeneral === 'application' && fileTypeSpecific === 'pdf') {\n    return {\n      color: '#e25149',\n      icon: iconPDF()\n    };\n  } // Archive\n\n\n  const archiveTypes = ['zip', 'x-7z-compressed', 'x-rar-compressed', 'x-tar', 'x-gzip', 'x-apple-diskimage'];\n\n  if (fileTypeGeneral === 'application' && archiveTypes.indexOf(fileTypeSpecific) !== -1) {\n    return {\n      color: '#00C469',\n      icon: iconArchive()\n    };\n  }\n\n  return defaultChoice;\n}\n\nmodule.exports = getIconByMime;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst getFileTypeIcon = require(\"../utils/getFileTypeIcon.js\");\n\nfunction FilePreview(props) {\n  const {\n    file\n  } = props;\n\n  if (file.preview) {\n    return (0, _preact.h)(\"img\", {\n      className: \"uppy-Dashboard-Item-previewImg\",\n      alt: file.name,\n      src: file.preview\n    });\n  }\n\n  const {\n    color,\n    icon\n  } = getFileTypeIcon(file.type);\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-previewIconWrap\"\n  }, (0, _preact.h)(\"span\", {\n    className: \"uppy-Dashboard-Item-previewIcon\",\n    style: {\n      color\n    }\n  }, icon), (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-Dashboard-Item-previewIconBg\",\n    width: \"58\",\n    height: \"76\",\n    viewBox: \"0 0 58 76\"\n  }, (0, _preact.h)(\"rect\", {\n    fill: \"#FFF\",\n    width: \"58\",\n    height: \"76\",\n    rx: \"3\",\n    fillRule: \"evenodd\"\n  })));\n}\n\nmodule.exports = FilePreview;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst metaFieldIdToName = (metaFieldId, metaFields) => {\n  const field = metaFields.filter(f => f.id === metaFieldId);\n  return field[0].name;\n};\n\nfunction renderMissingMetaFieldsError(props) {\n  const {\n    file,\n    toggleFileCard,\n    i18n,\n    metaFields\n  } = props;\n  const {\n    missingRequiredMetaFields\n  } = file;\n\n  if (!(missingRequiredMetaFields != null && missingRequiredMetaFields.length)) {\n    return null;\n  }\n\n  const metaFieldsString = missingRequiredMetaFields.map(missingMetaField => metaFieldIdToName(missingMetaField, metaFields)).join(', ');\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-errorMessage\"\n  }, i18n('missingRequiredMetaFields', {\n    smart_count: missingRequiredMetaFields.length,\n    fields: metaFieldsString\n  }), ' ', (0, _preact.h)(\"button\", {\n    type: \"button\",\n    class: \"uppy-u-reset uppy-Dashboard-Item-errorMessageBtn\",\n    onClick: () => toggleFileCard(true, file.id)\n  }, i18n('editFile')));\n}\n\nmodule.exports = renderMissingMetaFieldsError;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst FilePreview = require(\"../../FilePreview.js\");\n\nconst MetaErrorMessage = require(\"../MetaErrorMessage.js\");\n\nconst getFileTypeIcon = require(\"../../../utils/getFileTypeIcon.js\");\n\nfunction FilePreviewAndLink(props) {\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-previewInnerWrap\",\n    style: {\n      backgroundColor: getFileTypeIcon(props.file.type).color\n    }\n  }, props.showLinkToFileUploadResult && props.file.uploadURL && (0, _preact.h)(\"a\", {\n    className: \"uppy-Dashboard-Item-previewLink\",\n    href: props.file.uploadURL,\n    rel: \"noreferrer noopener\",\n    target: \"_blank\",\n    \"aria-label\": props.file.meta.name\n  }, (0, _preact.h)(\"span\", {\n    hidden: true\n  }, props.file.meta.name)), (0, _preact.h)(FilePreview, {\n    file: props.file\n  }), (0, _preact.h)(MetaErrorMessage, {\n    file: props.file,\n    i18n: props.i18n,\n    toggleFileCard: props.toggleFileCard,\n    metaFields: props.metaFields\n  }));\n}\n\nmodule.exports = FilePreviewAndLink;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction onPauseResumeCancelRetry(props) {\n  if (props.isUploaded) return;\n\n  if (props.error && !props.hideRetryButton) {\n    props.uppy.retryUpload(props.file.id);\n    return;\n  }\n\n  if (props.resumableUploads && !props.hidePauseResumeButton) {\n    props.uppy.pauseResume(props.file.id);\n  } else if (props.individualCancellation && !props.hideCancelButton) {\n    props.uppy.removeFile(props.file.id);\n  }\n}\n\nfunction progressIndicatorTitle(props) {\n  if (props.isUploaded) {\n    return props.i18n('uploadComplete');\n  }\n\n  if (props.error) {\n    return props.i18n('retryUpload');\n  }\n\n  if (props.resumableUploads) {\n    if (props.file.isPaused) {\n      return props.i18n('resumeUpload');\n    }\n\n    return props.i18n('pauseUpload');\n  }\n\n  if (props.individualCancellation) {\n    return props.i18n('cancelUpload');\n  }\n\n  return '';\n}\n\nfunction ProgressIndicatorButton(props) {\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-progress\"\n  }, (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-Dashboard-Item-progressIndicator\",\n    type: \"button\",\n    \"aria-label\": progressIndicatorTitle(props),\n    title: progressIndicatorTitle(props),\n    onClick: () => onPauseResumeCancelRetry(props)\n  }, props.children));\n}\n\nfunction ProgressCircleContainer(_ref) {\n  let {\n    children\n  } = _ref;\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"70\",\n    height: \"70\",\n    viewBox: \"0 0 36 36\",\n    className: \"uppy-c-icon uppy-Dashboard-Item-progressIcon--circle\"\n  }, children);\n}\n\nfunction ProgressCircle(_ref2) {\n  let {\n    progress\n  } = _ref2;\n  // circle length equals 2 * PI * R\n  const circleLength = 2 * Math.PI * 15;\n  return (0, _preact.h)(\"g\", null, (0, _preact.h)(\"circle\", {\n    className: \"uppy-Dashboard-Item-progressIcon--bg\",\n    r: \"15\",\n    cx: \"18\",\n    cy: \"18\",\n    \"stroke-width\": \"2\",\n    fill: \"none\"\n  }), (0, _preact.h)(\"circle\", {\n    className: \"uppy-Dashboard-Item-progressIcon--progress\",\n    r: \"15\",\n    cx: \"18\",\n    cy: \"18\",\n    transform: \"rotate(-90, 18, 18)\",\n    fill: \"none\",\n    \"stroke-width\": \"2\",\n    \"stroke-dasharray\": circleLength,\n    \"stroke-dashoffset\": circleLength - circleLength / 100 * progress\n  }));\n}\n\nfunction FileProgress(props) {\n  // Nothing if upload has not started\n  if (!props.file.progress.uploadStarted) {\n    return null;\n  } // Green checkmark when complete\n\n\n  if (props.isUploaded) {\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-Item-progress\"\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-Item-progressIndicator\"\n    }, (0, _preact.h)(ProgressCircleContainer, null, (0, _preact.h)(\"circle\", {\n      r: \"15\",\n      cx: \"18\",\n      cy: \"18\",\n      fill: \"#1bb240\"\n    }), (0, _preact.h)(\"polygon\", {\n      className: \"uppy-Dashboard-Item-progressIcon--check\",\n      transform: \"translate(2, 3)\",\n      points: \"14 22.5 7 15.2457065 8.99985857 13.1732815 14 18.3547104 22.9729883 9 25 11.1005634\"\n    }))));\n  }\n\n  if (props.recoveredState) {\n    return undefined;\n  } // Retry button for error\n\n\n  if (props.error && !props.hideRetryButton) {\n    return (// eslint-disable-next-line react/jsx-props-no-spreading\n      (0, _preact.h)(ProgressIndicatorButton, props, (0, _preact.h)(\"svg\", {\n        \"aria-hidden\": \"true\",\n        focusable: \"false\",\n        className: \"uppy-c-icon uppy-Dashboard-Item-progressIcon--retry\",\n        width: \"28\",\n        height: \"31\",\n        viewBox: \"0 0 16 19\"\n      }, (0, _preact.h)(\"path\", {\n        d: \"M16 11a8 8 0 1 1-8-8v2a6 6 0 1 0 6 6h2z\"\n      }), (0, _preact.h)(\"path\", {\n        d: \"M7.9 3H10v2H7.9z\"\n      }), (0, _preact.h)(\"path\", {\n        d: \"M8.536.5l3.535 3.536-1.414 1.414L7.12 1.914z\"\n      }), (0, _preact.h)(\"path\", {\n        d: \"M10.657 2.621l1.414 1.415L8.536 7.57 7.12 6.157z\"\n      })))\n    );\n  } // Pause/resume button for resumable uploads\n\n\n  if (props.resumableUploads && !props.hidePauseResumeButton) {\n    return (// eslint-disable-next-line react/jsx-props-no-spreading\n      (0, _preact.h)(ProgressIndicatorButton, props, (0, _preact.h)(ProgressCircleContainer, null, (0, _preact.h)(ProgressCircle, {\n        progress: props.file.progress.percentage\n      }), props.file.isPaused ? (0, _preact.h)(\"polygon\", {\n        className: \"uppy-Dashboard-Item-progressIcon--play\",\n        transform: \"translate(3, 3)\",\n        points: \"12 20 12 10 20 15\"\n      }) : (0, _preact.h)(\"g\", {\n        className: \"uppy-Dashboard-Item-progressIcon--pause\",\n        transform: \"translate(14.5, 13)\"\n      }, (0, _preact.h)(\"rect\", {\n        x: \"0\",\n        y: \"0\",\n        width: \"2\",\n        height: \"10\",\n        rx: \"0\"\n      }), (0, _preact.h)(\"rect\", {\n        x: \"5\",\n        y: \"0\",\n        width: \"2\",\n        height: \"10\",\n        rx: \"0\"\n      }))))\n    );\n  } // Cancel button for non-resumable uploads if individualCancellation is supported (not bundled)\n\n\n  if (!props.resumableUploads && props.individualCancellation && !props.hideCancelButton) {\n    return (// eslint-disable-next-line react/jsx-props-no-spreading\n      (0, _preact.h)(ProgressIndicatorButton, props, (0, _preact.h)(ProgressCircleContainer, null, (0, _preact.h)(ProgressCircle, {\n        progress: props.file.progress.percentage\n      }), (0, _preact.h)(\"polygon\", {\n        className: \"cancel\",\n        transform: \"translate(2, 2)\",\n        points: \"19.8856516 11.0625 16 14.9481516 12.1019737 11.0625 11.0625 12.1143484 14.9481516 16 11.0625 19.8980263 12.1019737 20.9375 16 17.0518484 19.8856516 20.9375 20.9375 19.8980263 17.0518484 16 20.9375 12\"\n      })))\n    );\n  } // Just progress when buttons are disabled\n\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-progress\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-progressIndicator\"\n  }, (0, _preact.h)(ProgressCircleContainer, null, (0, _preact.h)(ProgressCircle, {\n    progress: props.file.progress.percentage\n  }))));\n}\n\nmodule.exports = FileProgress;", "\"use strict\";\n\n/**\n * Truncates a string to the given number of chars (maxLength) by inserting '...' in the middle of that string.\n * Partially taken from https://stackoverflow.com/a/5723274/3192470.\n *\n * @param {string} string - string to be truncated\n * @param {number} maxLength - maximum size of the resulting string\n * @returns {string}\n */\nconst separator = '...';\n\nfunction truncateString(string, maxLength) {\n  // Return the empty string if maxLength is zero\n  if (maxLength === 0) return ''; // Return original string if it's already shorter than maxLength\n\n  if (string.length <= maxLength) return string; // Return truncated substring appended of the ellipsis char if string can't be meaningfully truncated\n\n  if (maxLength <= separator.length + 1) return `${string.slice(0, maxLength - 1)}\u2026`;\n  const charsToShow = maxLength - separator.length;\n  const frontChars = Math.ceil(charsToShow / 2);\n  const backChars = Math.floor(charsToShow / 2);\n  return string.slice(0, frontChars) + separator + string.slice(-backChars);\n}\n\nmodule.exports = truncateString;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst prettierBytes = require(\"@transloadit/prettier-bytes\");\n\nconst truncateString = require(\"@uppy/utils/lib/truncateString\");\n\nconst MetaErrorMessage = require(\"../MetaErrorMessage.js\");\n\nconst renderFileName = props => {\n  const {\n    author,\n    name\n  } = props.file.meta;\n\n  function getMaxNameLength() {\n    if (props.containerWidth <= 352) {\n      return 35;\n    }\n\n    if (props.containerWidth <= 576) {\n      return 60;\n    } // When `author` is present, we want to make sure\n    // the file name fits on one line so we can place\n    // the author on the second line.\n\n\n    return author ? 20 : 30;\n  }\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-name\",\n    title: name\n  }, truncateString(name, getMaxNameLength()));\n};\n\nconst renderAuthor = props => {\n  const {\n    author\n  } = props.file.meta;\n  const {\n    providerName\n  } = props.file.remote;\n  const dot = `\\u00B7`;\n\n  if (!author) {\n    return null;\n  }\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-author\"\n  }, (0, _preact.h)(\"a\", {\n    href: `${author.url}?utm_source=Companion&utm_medium=referral`,\n    target: \"_blank\",\n    rel: \"noopener noreferrer\"\n  }, truncateString(author.name, 13)), providerName ? (0, _preact.h)(_preact.Fragment, null, ` ${dot} `, providerName, ` ${dot} `) : null);\n};\n\nconst renderFileSize = props => props.file.size && (0, _preact.h)(\"div\", {\n  className: \"uppy-Dashboard-Item-statusSize\"\n}, prettierBytes(props.file.size));\n\nconst ReSelectButton = props => props.file.isGhost && (0, _preact.h)(\"span\", null, ' \\u2022 ', (0, _preact.h)(\"button\", {\n  className: \"uppy-u-reset uppy-c-btn uppy-Dashboard-Item-reSelect\",\n  type: \"button\",\n  onClick: props.toggleAddFilesPanel\n}, props.i18n('reSelect')));\n\nconst ErrorButton = _ref => {\n  let {\n    file,\n    onClick\n  } = _ref;\n\n  if (file.error) {\n    return (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-Dashboard-Item-errorDetails\",\n      \"aria-label\": file.error,\n      \"data-microtip-position\": \"bottom\",\n      \"data-microtip-size\": \"medium\",\n      onClick: onClick,\n      type: \"button\"\n    }, \"?\");\n  }\n\n  return null;\n};\n\nfunction FileInfo(props) {\n  const {\n    file\n  } = props;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-fileInfo\",\n    \"data-uppy-file-source\": file.source\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-fileName\"\n  }, renderFileName(props), (0, _preact.h)(ErrorButton, {\n    file: props.file // eslint-disable-next-line no-alert\n    ,\n    onClick: () => alert(props.file.error) // TODO: move to a custom alert implementation\n\n  })), (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-status\"\n  }, renderAuthor(props), renderFileSize(props), ReSelectButton(props)), (0, _preact.h)(MetaErrorMessage, {\n    file: props.file,\n    i18n: props.i18n,\n    toggleFileCard: props.toggleFileCard,\n    metaFields: props.metaFields\n  }));\n}\n\nmodule.exports = FileInfo;", "\"use strict\";\n\nfunction copyToClipboard(textToCopy, fallbackString) {\n  // TODO: make `fallbackString` an optional parameter instead.\n  fallbackString || (fallbackString = 'Copy the URL below'); // eslint-disable-line no-param-reassign\n\n  return new Promise(resolve => {\n    const textArea = document.createElement('textarea');\n    textArea.setAttribute('style', {\n      position: 'fixed',\n      top: 0,\n      left: 0,\n      width: '2em',\n      height: '2em',\n      padding: 0,\n      border: 'none',\n      outline: 'none',\n      boxShadow: 'none',\n      background: 'transparent'\n    });\n    textArea.value = textToCopy;\n    document.body.appendChild(textArea);\n    textArea.select();\n\n    const magicCopyFailed = () => {\n      document.body.removeChild(textArea); // eslint-disable-next-line no-alert\n\n      window.prompt(fallbackString, textToCopy);\n      resolve();\n    };\n\n    try {\n      const successful = document.execCommand('copy');\n\n      if (!successful) {\n        return magicCopyFailed('copy command unavailable');\n      }\n\n      document.body.removeChild(textArea);\n      return resolve();\n    } catch (err) {\n      document.body.removeChild(textArea);\n      return magicCopyFailed(err);\n    }\n  });\n}\n\n/**\n * Copies text to clipboard by creating an almost invisible textarea,\n * adding text there, then running execCommand('copy').\n * Falls back to prompt() when the easy way fails (hello, Safari!)\n * From http://stackoverflow.com/a/30810322\n *\n * @param {string} textToCopy\n * @param {string} fallbackString\n * @returns {Promise}\n */\nmodule.exports = copyToClipboard;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst copyToClipboard = require(\"../../../utils/copyToClipboard.js\");\n\nfunction EditButton(_ref) {\n  let {\n    file,\n    uploadInProgressOrComplete,\n    metaFields,\n    canEditFile,\n    i18n,\n    onClick\n  } = _ref;\n\n  if (!uploadInProgressOrComplete && metaFields && metaFields.length > 0 || !uploadInProgressOrComplete && canEditFile(file)) {\n    return (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-Dashboard-Item-action uppy-Dashboard-Item-action--edit\",\n      type: \"button\",\n      \"aria-label\": i18n('editFileWithFilename', {\n        file: file.meta.name\n      }),\n      title: i18n('editFileWithFilename', {\n        file: file.meta.name\n      }),\n      onClick: () => onClick()\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon\",\n      width: \"14\",\n      height: \"14\",\n      viewBox: \"0 0 14 14\"\n    }, (0, _preact.h)(\"g\", {\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M1.5 10.793h2.793A1 1 0 0 0 5 10.5L11.5 4a1 1 0 0 0 0-1.414L9.707.793a1 1 0 0 0-1.414 0l-6.5 6.5A1 1 0 0 0 1.5 8v2.793zm1-1V8L9 1.5l1.793 1.793-6.5 6.5H2.5z\",\n      fillRule: \"nonzero\"\n    }), (0, _preact.h)(\"rect\", {\n      x: \"1\",\n      y: \"12.293\",\n      width: \"11\",\n      height: \"1\",\n      rx: \".5\"\n    }), (0, _preact.h)(\"path\", {\n      fillRule: \"nonzero\",\n      d: \"M6.793 2.5L9.5 5.207l.707-.707L7.5 1.793z\"\n    }))));\n  }\n\n  return null;\n}\n\nfunction RemoveButton(_ref2) {\n  let {\n    i18n,\n    onClick,\n    file\n  } = _ref2;\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-Dashboard-Item-action uppy-Dashboard-Item-action--remove\",\n    type: \"button\",\n    \"aria-label\": i18n('removeFile', {\n      file: file.meta.name\n    }),\n    title: i18n('removeFile', {\n      file: file.meta.name\n    }),\n    onClick: () => onClick()\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"18\",\n    height: \"18\",\n    viewBox: \"0 0 18 18\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M9 0C4.034 0 0 4.034 0 9s4.034 9 9 9 9-4.034 9-9-4.034-9-9-9z\"\n  }), (0, _preact.h)(\"path\", {\n    fill: \"#FFF\",\n    d: \"M13 12.222l-.778.778L9 9.778 5.778 13 5 12.222 8.222 9 5 5.778 5.778 5 9 8.222 12.222 5l.778.778L9.778 9z\"\n  })));\n}\n\nconst copyLinkToClipboard = (event, props) => {\n  copyToClipboard(props.file.uploadURL, props.i18n('copyLinkToClipboardFallback')).then(() => {\n    props.uppy.log('Link copied to clipboard.');\n    props.uppy.info(props.i18n('copyLinkToClipboardSuccess'), 'info', 3000);\n  }).catch(props.uppy.log) // avoid losing focus\n  .then(() => event.target.focus({\n    preventScroll: true\n  }));\n};\n\nfunction CopyLinkButton(props) {\n  const {\n    i18n\n  } = props;\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-Dashboard-Item-action uppy-Dashboard-Item-action--copyLink\",\n    type: \"button\",\n    \"aria-label\": i18n('copyLink'),\n    title: i18n('copyLink'),\n    onClick: event => copyLinkToClipboard(event, props)\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"14\",\n    height: \"14\",\n    viewBox: \"0 0 14 12\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M7.94 7.703a2.613 2.613 0 0 1-.626 2.681l-.852.851a2.597 2.597 0 0 1-1.849.766A2.616 2.616 0 0 1 2.764 7.54l.852-.852a2.596 2.596 0 0 1 2.69-.625L5.267 7.099a1.44 1.44 0 0 0-.833.407l-.852.851a1.458 1.458 0 0 0 1.03 2.486c.39 0 .755-.152 1.03-.426l.852-.852c.231-.231.363-.522.406-.824l1.04-1.038zm4.295-5.937A2.596 2.596 0 0 0 10.387 1c-.698 0-1.355.272-1.849.766l-.852.851a2.614 2.614 0 0 0-.624 2.688l1.036-1.036c.041-.304.173-.6.407-.833l.852-.852c.275-.275.64-.426 1.03-.426a1.458 1.458 0 0 1 1.03 2.486l-.852.851a1.442 1.442 0 0 1-.824.406l-1.04 1.04a2.596 2.596 0 0 0 2.683-.628l.851-.85a2.616 2.616 0 0 0 0-3.697zm-6.88 6.883a.577.577 0 0 0 .82 0l3.474-3.474a.579.579 0 1 0-.819-.82L5.355 7.83a.579.579 0 0 0 0 .819z\"\n  })));\n}\n\nfunction Buttons(props) {\n  const {\n    uppy,\n    file,\n    uploadInProgressOrComplete,\n    canEditFile,\n    metaFields,\n    showLinkToFileUploadResult,\n    showRemoveButton,\n    i18n,\n    toggleFileCard,\n    openFileEditor\n  } = props;\n\n  const editAction = () => {\n    if (metaFields && metaFields.length > 0) {\n      toggleFileCard(true, file.id);\n    } else {\n      openFileEditor(file);\n    }\n  };\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-Item-actionWrapper\"\n  }, (0, _preact.h)(EditButton, {\n    i18n: i18n,\n    file: file,\n    uploadInProgressOrComplete: uploadInProgressOrComplete,\n    canEditFile: canEditFile,\n    metaFields: metaFields,\n    onClick: editAction\n  }), showLinkToFileUploadResult && file.uploadURL ? (0, _preact.h)(CopyLinkButton, {\n    file: file,\n    uppy: uppy,\n    i18n: i18n\n  }) : null, showRemoveButton ? (0, _preact.h)(RemoveButton, {\n    i18n: i18n,\n    file: file,\n    uppy: uppy,\n    onClick: () => props.uppy.removeFile(file.id, 'removed-by-user')\n  }) : null);\n}\n\nmodule.exports = Buttons;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst classNames = require(\"classnames\");\n\nconst shallowEqual = require(\"is-shallow-equal\");\n\nconst FilePreviewAndLink = require(\"./FilePreviewAndLink/index.js\");\n\nconst FileProgress = require(\"./FileProgress/index.js\");\n\nconst FileInfo = require(\"./FileInfo/index.js\");\n\nconst Buttons = require(\"./Buttons/index.js\");\n\nclass FileItem extends _preact.Component {\n  componentDidMount() {\n    const {\n      file\n    } = this.props;\n\n    if (!file.preview) {\n      this.props.handleRequestThumbnail(file);\n    }\n  }\n\n  shouldComponentUpdate(nextProps) {\n    return !shallowEqual(this.props, nextProps);\n  } // VirtualList mounts FileItems again and they emit `thumbnail:request`\n  // Otherwise thumbnails are broken or missing after Golden Retriever restores files\n\n\n  componentDidUpdate() {\n    const {\n      file\n    } = this.props;\n\n    if (!file.preview) {\n      this.props.handleRequestThumbnail(file);\n    }\n  }\n\n  componentWillUnmount() {\n    const {\n      file\n    } = this.props;\n\n    if (!file.preview) {\n      this.props.handleCancelThumbnail(file);\n    }\n  }\n\n  render() {\n    const {\n      file\n    } = this.props;\n    const isProcessing = file.progress.preprocess || file.progress.postprocess;\n    const isUploaded = file.progress.uploadComplete && !isProcessing && !file.error;\n    const uploadInProgressOrComplete = file.progress.uploadStarted || isProcessing;\n    const uploadInProgress = file.progress.uploadStarted && !file.progress.uploadComplete || isProcessing;\n    const error = file.error || false; // File that Golden Retriever was able to partly restore (only meta, not blob),\n    // users still need to re-add it, so it\u2019s a ghost\n\n    const {\n      isGhost\n    } = file;\n    let showRemoveButton = this.props.individualCancellation ? !isUploaded : !uploadInProgress && !isUploaded;\n\n    if (isUploaded && this.props.showRemoveButtonAfterComplete) {\n      showRemoveButton = true;\n    }\n\n    const dashboardItemClass = classNames({\n      'uppy-Dashboard-Item': true,\n      'is-inprogress': uploadInProgress && !this.props.recoveredState,\n      'is-processing': isProcessing,\n      'is-complete': isUploaded,\n      'is-error': !!error,\n      'is-resumable': this.props.resumableUploads,\n      'is-noIndividualCancellation': !this.props.individualCancellation,\n      'is-ghost': isGhost\n    });\n    return (0, _preact.h)(\"div\", {\n      className: dashboardItemClass,\n      id: `uppy_${file.id}`,\n      role: this.props.role\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-Item-preview\"\n    }, (0, _preact.h)(FilePreviewAndLink, {\n      file: file,\n      showLinkToFileUploadResult: this.props.showLinkToFileUploadResult,\n      i18n: this.props.i18n,\n      toggleFileCard: this.props.toggleFileCard,\n      metaFields: this.props.metaFields\n    }), (0, _preact.h)(FileProgress, {\n      uppy: this.props.uppy,\n      file: file,\n      error: error,\n      isUploaded: isUploaded,\n      hideRetryButton: this.props.hideRetryButton,\n      hideCancelButton: this.props.hideCancelButton,\n      hidePauseResumeButton: this.props.hidePauseResumeButton,\n      recoveredState: this.props.recoveredState,\n      showRemoveButtonAfterComplete: this.props.showRemoveButtonAfterComplete,\n      resumableUploads: this.props.resumableUploads,\n      individualCancellation: this.props.individualCancellation,\n      i18n: this.props.i18n\n    })), (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-Item-fileInfoAndButtons\"\n    }, (0, _preact.h)(FileInfo, {\n      file: file,\n      id: this.props.id,\n      acquirers: this.props.acquirers,\n      containerWidth: this.props.containerWidth,\n      i18n: this.props.i18n,\n      toggleAddFilesPanel: this.props.toggleAddFilesPanel,\n      toggleFileCard: this.props.toggleFileCard,\n      metaFields: this.props.metaFields\n    }), (0, _preact.h)(Buttons, {\n      file: file,\n      metaFields: this.props.metaFields,\n      showLinkToFileUploadResult: this.props.showLinkToFileUploadResult,\n      showRemoveButton: showRemoveButton,\n      canEditFile: this.props.canEditFile,\n      uploadInProgressOrComplete: uploadInProgressOrComplete,\n      toggleFileCard: this.props.toggleFileCard,\n      openFileEditor: this.props.openFileEditor,\n      uppy: this.props.uppy,\n      i18n: this.props.i18n\n    })));\n  }\n\n}\n\nmodule.exports = FileItem;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nconst STYLE_INNER = {\n  position: 'relative',\n  // Disabled for our use case: the wrapper elements around FileList already deal with overflow,\n  // and this additional property would hide things that we want to show.\n  //\n  // overflow: 'hidden',\n  width: '100%',\n  minHeight: '100%'\n};\nconst STYLE_CONTENT = {\n  position: 'absolute',\n  top: 0,\n  left: 0,\n  // Because the `top` value gets set to some offset, this `height` being 100% would make the scrollbar\n  // stretch far beyond the content. For our use case, the content div actually can get its height from\n  // the elements inside it, so we don't need to specify a `height` property at all.\n  //\n  // height: '100%',\n  width: '100%',\n  overflow: 'visible'\n};\n\nclass VirtualList extends _preact.Component {\n  constructor(props) {\n    super(props); // The currently focused node, used to retain focus when the visible rows change.\n    // To avoid update loops, this should not cause state updates, so it's kept as a plain property.\n\n    this.handleScroll = () => {\n      this.setState({\n        offset: this.base.scrollTop\n      });\n    };\n\n    this.handleResize = () => {\n      this.resize();\n    };\n\n    this.focusElement = null;\n    this.state = {\n      offset: 0,\n      height: 0\n    };\n  }\n\n  componentDidMount() {\n    this.resize();\n    window.addEventListener('resize', this.handleResize);\n  } // TODO: refactor to stable lifecycle method\n  // eslint-disable-next-line\n\n\n  componentWillUpdate() {\n    if (this.base.contains(document.activeElement)) {\n      this.focusElement = document.activeElement;\n    }\n  }\n\n  componentDidUpdate() {\n    // Maintain focus when rows are added and removed.\n    if (this.focusElement && this.focusElement.parentNode && document.activeElement !== this.focusElement) {\n      this.focusElement.focus();\n    }\n\n    this.focusElement = null;\n    this.resize();\n  }\n\n  componentWillUnmount() {\n    window.removeEventListener('resize', this.handleResize);\n  }\n\n  resize() {\n    const {\n      height\n    } = this.state;\n\n    if (height !== this.base.offsetHeight) {\n      this.setState({\n        height: this.base.offsetHeight\n      });\n    }\n  }\n\n  render(_ref) {\n    let {\n      data,\n      rowHeight,\n      renderRow,\n      overscanCount = 10,\n      ...props\n    } = _ref;\n    const {\n      offset,\n      height\n    } = this.state; // first visible row index\n\n    let start = Math.floor(offset / rowHeight); // actual number of visible rows (without overscan)\n\n    let visibleRowCount = Math.floor(height / rowHeight); // Overscan: render blocks of rows modulo an overscan row count\n    // This dramatically reduces DOM writes during scrolling\n\n    if (overscanCount) {\n      start = Math.max(0, start - start % overscanCount);\n      visibleRowCount += overscanCount;\n    } // last visible + overscan row index + padding to allow keyboard focus to travel past the visible area\n\n\n    const end = start + visibleRowCount + 4; // data slice currently in viewport plus overscan items\n\n    const selection = data.slice(start, end);\n    const styleInner = { ...STYLE_INNER,\n      height: data.length * rowHeight\n    };\n    const styleContent = { ...STYLE_CONTENT,\n      top: start * rowHeight\n    }; // The `role=\"presentation\"` attributes ensure that these wrapper elements are not treated as list\n    // items by accessibility and outline tools.\n\n    return (// eslint-disable-next-line react/jsx-props-no-spreading\n      (0, _preact.h)(\"div\", _extends({\n        onScroll: this.handleScroll\n      }, props), (0, _preact.h)(\"div\", {\n        role: \"presentation\",\n        style: styleInner\n      }, (0, _preact.h)(\"div\", {\n        role: \"presentation\",\n        style: styleContent\n      }, selection.map(renderRow))))\n    );\n  }\n\n}\n\nmodule.exports = VirtualList;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nconst classNames = require(\"classnames\");\n\nconst FileItem = require(\"./FileItem/index.js\");\n\nconst VirtualList = require(\"./VirtualList.js\");\n\nfunction chunks(list, size) {\n  const chunked = [];\n  let currentChunk = [];\n  list.forEach(item => {\n    if (currentChunk.length < size) {\n      currentChunk.push(item);\n    } else {\n      chunked.push(currentChunk);\n      currentChunk = [item];\n    }\n  });\n  if (currentChunk.length) chunked.push(currentChunk);\n  return chunked;\n}\n\nmodule.exports = props => {\n  const noFiles = props.totalFileCount === 0;\n  const dashboardFilesClass = classNames('uppy-Dashboard-files', {\n    'uppy-Dashboard-files--noFiles': noFiles\n  }); // It's not great that this is hardcoded!\n  // It's ESPECIALLY not great that this is checking against `itemsPerRow`!\n\n  const rowHeight = props.itemsPerRow === 1 // Mobile\n  ? 71 // 190px height + 2 * 5px margin\n  : 200;\n  const fileProps = {\n    // FIXME This is confusing, it's actually the Dashboard's plugin ID\n    id: props.id,\n    error: props.error,\n    // TODO move this to context\n    i18n: props.i18n,\n    uppy: props.uppy,\n    // features\n    acquirers: props.acquirers,\n    resumableUploads: props.resumableUploads,\n    individualCancellation: props.individualCancellation,\n    // visual options\n    hideRetryButton: props.hideRetryButton,\n    hidePauseResumeButton: props.hidePauseResumeButton,\n    hideCancelButton: props.hideCancelButton,\n    showLinkToFileUploadResult: props.showLinkToFileUploadResult,\n    showRemoveButtonAfterComplete: props.showRemoveButtonAfterComplete,\n    isWide: props.isWide,\n    metaFields: props.metaFields,\n    recoveredState: props.recoveredState,\n    // callbacks\n    toggleFileCard: props.toggleFileCard,\n    handleRequestThumbnail: props.handleRequestThumbnail,\n    handleCancelThumbnail: props.handleCancelThumbnail\n  };\n\n  const sortByGhostComesFirst = (file1, file2) => {\n    return props.files[file2].isGhost - props.files[file1].isGhost;\n  }; // Sort files by file.isGhost, ghost files first, only if recoveredState is present\n\n\n  const files = Object.keys(props.files);\n  if (props.recoveredState) files.sort(sortByGhostComesFirst);\n  const rows = chunks(files, props.itemsPerRow);\n\n  const renderRow = row => // The `role=\"presentation` attribute ensures that the list items are properly\n  // associated with the `VirtualList` element.\n  // We use the first file ID as the key\u2014this should not change across scroll rerenders\n  (0, _preact.h)(\"div\", {\n    role: \"presentation\",\n    key: row[0]\n  }, row.map(fileID => (0, _preact.h)(FileItem, _extends({\n    key: fileID,\n    uppy: props.uppy\n  }, fileProps, {\n    // eslint-disable-line react/jsx-props-no-spreading\n    role: \"listitem\",\n    openFileEditor: props.openFileEditor,\n    canEditFile: props.canEditFile,\n    toggleAddFilesPanel: props.toggleAddFilesPanel,\n    file: props.files[fileID]\n  }))));\n\n  return (0, _preact.h)(VirtualList, {\n    class: dashboardFilesClass,\n    role: \"list\",\n    data: rows,\n    renderRow: renderRow,\n    rowHeight: rowHeight\n  });\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nlet _Symbol$for;\n\n_Symbol$for = Symbol.for('uppy test: disable unused locale key warning');\n\nclass AddFiles extends _preact.Component {\n  constructor() {\n    super(...arguments);\n\n    this.triggerFileInputClick = () => {\n      this.fileInput.click();\n    };\n\n    this.triggerFolderInputClick = () => {\n      this.folderInput.click();\n    };\n\n    this.onFileInputChange = event => {\n      this.props.handleInputChange(event); // We clear the input after a file is selected, because otherwise\n      // change event is not fired in Chrome and Safari when a file\n      // with the same name is selected.\n      // ___Why not use value=\"\" on <input/> instead?\n      //    Because if we use that method of clearing the input,\n      //    Chrome will not trigger change if we drop the same file twice (Issue #768).\n\n      event.target.value = null; // eslint-disable-line no-param-reassign\n    };\n\n    this.renderHiddenInput = (isFolder, refCallback) => {\n      return (0, _preact.h)(\"input\", {\n        className: \"uppy-Dashboard-input\",\n        hidden: true,\n        \"aria-hidden\": \"true\",\n        tabIndex: -1,\n        webkitdirectory: isFolder,\n        type: \"file\",\n        name: \"files[]\",\n        multiple: this.props.maxNumberOfFiles !== 1,\n        onChange: this.onFileInputChange,\n        accept: this.props.allowedFileTypes,\n        ref: refCallback\n      });\n    };\n\n    this.renderMyDeviceAcquirer = () => {\n      return (0, _preact.h)(\"div\", {\n        className: \"uppy-DashboardTab\",\n        role: \"presentation\",\n        \"data-uppy-acquirer-id\": \"MyDevice\"\n      }, (0, _preact.h)(\"button\", {\n        type: \"button\",\n        className: \"uppy-u-reset uppy-c-btn uppy-DashboardTab-btn\",\n        role: \"tab\",\n        tabIndex: 0,\n        \"data-uppy-super-focusable\": true,\n        onClick: this.triggerFileInputClick\n      }, (0, _preact.h)(\"svg\", {\n        \"aria-hidden\": \"true\",\n        focusable: \"false\",\n        width: \"32\",\n        height: \"32\",\n        viewBox: \"0 0 32 32\"\n      }, (0, _preact.h)(\"g\", {\n        fill: \"none\",\n        fillRule: \"evenodd\"\n      }, (0, _preact.h)(\"rect\", {\n        className: \"uppy-ProviderIconBg\",\n        width: \"32\",\n        height: \"32\",\n        rx: \"16\",\n        fill: \"#2275D7\"\n      }), (0, _preact.h)(\"path\", {\n        d: \"M21.973 21.152H9.863l-1.108-5.087h14.464l-1.246 5.087zM9.935 11.37h3.958l.886 1.444a.673.673 0 0 0 .585.316h6.506v1.37H9.935v-3.13zm14.898 3.44a.793.793 0 0 0-.616-.31h-.978v-2.126c0-.379-.275-.613-.653-.613H15.75l-.886-1.445a.673.673 0 0 0-.585-.316H9.232c-.378 0-.667.209-.667.587V14.5h-.782a.793.793 0 0 0-.61.303.795.795 0 0 0-.155.663l1.45 6.633c.078.36.396.618.764.618h13.354c.36 0 .674-.246.76-.595l1.631-6.636a.795.795 0 0 0-.144-.675z\",\n        fill: \"#FFF\"\n      }))), (0, _preact.h)(\"div\", {\n        className: \"uppy-DashboardTab-name\"\n      }, this.props.i18n('myDevice'))));\n    };\n\n    this.renderBrowseButton = (text, onClickFn) => {\n      const numberOfAcquirers = this.props.acquirers.length;\n      return (0, _preact.h)(\"button\", {\n        type: \"button\",\n        className: \"uppy-u-reset uppy-Dashboard-browse\",\n        onClick: onClickFn,\n        \"data-uppy-super-focusable\": numberOfAcquirers === 0\n      }, text);\n    };\n\n    this.renderDropPasteBrowseTagline = () => {\n      const numberOfAcquirers = this.props.acquirers.length;\n      const browseFiles = this.renderBrowseButton(this.props.i18n('browseFiles'), this.triggerFileInputClick);\n      const browseFolders = this.renderBrowseButton(this.props.i18n('browseFolders'), this.triggerFolderInputClick); // in order to keep the i18n CamelCase and options lower (as are defaults) we will want to transform a lower\n      // to Camel\n\n      const lowerFMSelectionType = this.props.fileManagerSelectionType;\n      const camelFMSelectionType = lowerFMSelectionType.charAt(0).toUpperCase() + lowerFMSelectionType.slice(1);\n      return (0, _preact.h)(\"div\", {\n        class: \"uppy-Dashboard-AddFiles-title\"\n      }, // eslint-disable-next-line no-nested-ternary\n      this.props.disableLocalFiles ? this.props.i18n('importFiles') : numberOfAcquirers > 0 ? this.props.i18nArray(`dropPasteImport${camelFMSelectionType}`, {\n        browseFiles,\n        browseFolders,\n        browse: browseFiles\n      }) : this.props.i18nArray(`dropPaste${camelFMSelectionType}`, {\n        browseFiles,\n        browseFolders,\n        browse: browseFiles\n      }));\n    };\n\n    this.renderAcquirer = acquirer => {\n      return (0, _preact.h)(\"div\", {\n        className: \"uppy-DashboardTab\",\n        role: \"presentation\",\n        \"data-uppy-acquirer-id\": acquirer.id\n      }, (0, _preact.h)(\"button\", {\n        type: \"button\",\n        className: \"uppy-u-reset uppy-c-btn uppy-DashboardTab-btn\",\n        role: \"tab\",\n        tabIndex: 0,\n        \"data-cy\": acquirer.id,\n        \"aria-controls\": `uppy-DashboardContent-panel--${acquirer.id}`,\n        \"aria-selected\": this.props.activePickerPanel.id === acquirer.id,\n        \"data-uppy-super-focusable\": true,\n        onClick: () => this.props.showPanel(acquirer.id)\n      }, acquirer.icon(), (0, _preact.h)(\"div\", {\n        className: \"uppy-DashboardTab-name\"\n      }, acquirer.name)));\n    };\n\n    this.renderAcquirers = (acquirers, disableLocalFiles) => {\n      // Group last two buttons, so we don\u2019t end up with\n      // just one button on a new line\n      const acquirersWithoutLastTwo = [...acquirers];\n      const lastTwoAcquirers = acquirersWithoutLastTwo.splice(acquirers.length - 2, acquirers.length);\n      return (0, _preact.h)(\"div\", {\n        className: \"uppy-Dashboard-AddFiles-list\",\n        role: \"tablist\"\n      }, !disableLocalFiles && this.renderMyDeviceAcquirer(), acquirersWithoutLastTwo.map(acquirer => this.renderAcquirer(acquirer)), (0, _preact.h)(\"span\", {\n        role: \"presentation\",\n        style: {\n          'white-space': 'nowrap'\n        }\n      }, lastTwoAcquirers.map(acquirer => this.renderAcquirer(acquirer))));\n    };\n  }\n\n  [_Symbol$for]() {\n    // Those are actually used in `renderDropPasteBrowseTagline` method.\n    this.props.i18nArray('dropPasteBoth');\n    this.props.i18nArray('dropPasteFiles');\n    this.props.i18nArray('dropPasteFolders');\n    this.props.i18nArray('dropPasteImportBoth');\n    this.props.i18nArray('dropPasteImportFiles');\n    this.props.i18nArray('dropPasteImportFolders');\n  }\n\n  renderPoweredByUppy() {\n    const {\n      i18nArray\n    } = this.props;\n    const uppyBranding = (0, _preact.h)(\"span\", null, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon uppy-Dashboard-poweredByIcon\",\n      width: \"11\",\n      height: \"11\",\n      viewBox: \"0 0 11 11\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M7.365 10.5l-.01-4.045h2.612L5.5.806l-4.467 5.65h2.604l.01 4.044h3.718z\",\n      fillRule: \"evenodd\"\n    })), (0, _preact.h)(\"span\", {\n      className: \"uppy-Dashboard-poweredByUppy\"\n    }, \"Uppy\"));\n    const linkText = i18nArray('poweredBy', {\n      uppy: uppyBranding\n    });\n    return (0, _preact.h)(\"a\", {\n      tabIndex: \"-1\",\n      href: \"https://uppy.io\",\n      rel: \"noreferrer noopener\",\n      target: \"_blank\",\n      className: \"uppy-Dashboard-poweredBy\"\n    }, linkText);\n  }\n\n  render() {\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-AddFiles\"\n    }, this.renderHiddenInput(false, ref => {\n      this.fileInput = ref;\n    }), this.renderHiddenInput(true, ref => {\n      this.folderInput = ref;\n    }), this.renderDropPasteBrowseTagline(), this.props.acquirers.length > 0 && this.renderAcquirers(this.props.acquirers, this.props.disableLocalFiles), (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-AddFiles-info\"\n    }, this.props.note && (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-note\"\n    }, this.props.note), this.props.proudlyDisplayPoweredByUppy && this.renderPoweredByUppy(this.props)));\n  }\n\n}\n\nmodule.exports = AddFiles;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst classNames = require(\"classnames\");\n\nconst AddFiles = require(\"./AddFiles.js\");\n\nconst AddFilesPanel = props => {\n  return (0, _preact.h)(\"div\", {\n    className: classNames('uppy-Dashboard-AddFilesPanel', props.className),\n    \"data-uppy-panelType\": \"AddFiles\",\n    \"aria-hidden\": props.showAddFilesPanel\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-bar\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-title\",\n    role: \"heading\",\n    \"aria-level\": \"1\"\n  }, props.i18n('addingMoreFiles')), (0, _preact.h)(\"button\", {\n    className: \"uppy-DashboardContent-back\",\n    type: \"button\",\n    onClick: () => props.toggleAddFilesPanel(false)\n  }, props.i18n('back'))), (0, _preact.h)(AddFiles, props));\n};\n\nmodule.exports = AddFilesPanel;", "\"use strict\";\n\n// ignore drop/paste events if they are not in input or textarea \u2014\n// otherwise when Url plugin adds drop/paste listeners to this.el,\n// draging UI elements or pasting anything into any field triggers those events \u2014\n// Url treats them as URLs that need to be imported\nfunction ignoreEvent(ev) {\n  const {\n    tagName\n  } = ev.target;\n\n  if (tagName === 'INPUT' || tagName === 'TEXTAREA') {\n    ev.stopPropagation();\n    return;\n  }\n\n  ev.preventDefault();\n  ev.stopPropagation();\n}\n\nmodule.exports = ignoreEvent;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst classNames = require(\"classnames\");\n\nconst ignoreEvent = require(\"../utils/ignoreEvent.js\");\n\nfunction PickerPanelContent(_ref) {\n  let {\n    activePickerPanel,\n    className,\n    hideAllPanels,\n    i18n,\n    state,\n    uppy\n  } = _ref;\n  return (0, _preact.h)(\"div\", {\n    className: classNames('uppy-DashboardContent-panel', className),\n    role: \"tabpanel\",\n    \"data-uppy-panelType\": \"PickerPanel\",\n    id: `uppy-DashboardContent-panel--${activePickerPanel.id}`,\n    onDragOver: ignoreEvent,\n    onDragLeave: ignoreEvent,\n    onDrop: ignoreEvent,\n    onPaste: ignoreEvent\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-bar\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-title\",\n    role: \"heading\",\n    \"aria-level\": \"1\"\n  }, i18n('importFrom', {\n    name: activePickerPanel.name\n  })), (0, _preact.h)(\"button\", {\n    className: \"uppy-DashboardContent-back\",\n    type: \"button\",\n    onClick: hideAllPanels\n  }, i18n('cancel'))), (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-panelBody\"\n  }, uppy.getPlugin(activePickerPanel.id).render(state)));\n}\n\nmodule.exports = PickerPanelContent;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst classNames = require(\"classnames\");\n\nfunction EditorPanel(props) {\n  const file = props.files[props.fileCardFor];\n  return (0, _preact.h)(\"div\", {\n    className: classNames('uppy-DashboardContent-panel', props.className),\n    role: \"tabpanel\",\n    \"data-uppy-panelType\": \"FileEditor\",\n    id: \"uppy-DashboardContent-panel--editor\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-bar\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-title\",\n    role: \"heading\",\n    \"aria-level\": \"1\"\n  }, props.i18nArray('editing', {\n    file: (0, _preact.h)(\"span\", {\n      className: \"uppy-DashboardContent-titleFile\"\n    }, file.meta ? file.meta.name : file.name)\n  })), (0, _preact.h)(\"button\", {\n    className: \"uppy-DashboardContent-back\",\n    type: \"button\",\n    onClick: props.hideAllPanels\n  }, props.i18n('cancel')), (0, _preact.h)(\"button\", {\n    className: \"uppy-DashboardContent-save\",\n    type: \"button\",\n    onClick: props.saveFileEditor\n  }, props.i18n('save'))), (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-panelBody\"\n  }, props.editors.map(target => {\n    return props.uppy.getPlugin(target.id).render(props.state);\n  })));\n}\n\nmodule.exports = EditorPanel;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst uploadStates = {\n  STATE_ERROR: 'error',\n  STATE_WAITING: 'waiting',\n  STATE_PREPROCESSING: 'preprocessing',\n  STATE_UPLOADING: 'uploading',\n  STATE_POSTPROCESSING: 'postprocessing',\n  STATE_COMPLETE: 'complete',\n  STATE_PAUSED: 'paused'\n};\n\nfunction getUploadingState(isAllErrored, isAllComplete, isAllPaused, files) {\n  if (files === void 0) {\n    files = {};\n  }\n\n  if (isAllErrored) {\n    return uploadStates.STATE_ERROR;\n  }\n\n  if (isAllComplete) {\n    return uploadStates.STATE_COMPLETE;\n  }\n\n  if (isAllPaused) {\n    return uploadStates.STATE_PAUSED;\n  }\n\n  let state = uploadStates.STATE_WAITING;\n  const fileIDs = Object.keys(files);\n\n  for (let i = 0; i < fileIDs.length; i++) {\n    const {\n      progress\n    } = files[fileIDs[i]]; // If ANY files are being uploaded right now, show the uploading state.\n\n    if (progress.uploadStarted && !progress.uploadComplete) {\n      return uploadStates.STATE_UPLOADING;\n    } // If files are being preprocessed AND postprocessed at this time, we show the\n    // preprocess state. If any files are being uploaded we show uploading.\n\n\n    if (progress.preprocess && state !== uploadStates.STATE_UPLOADING) {\n      state = uploadStates.STATE_PREPROCESSING;\n    } // If NO files are being preprocessed or uploaded right now, but some files are\n    // being postprocessed, show the postprocess state.\n\n\n    if (progress.postprocess && state !== uploadStates.STATE_UPLOADING && state !== uploadStates.STATE_PREPROCESSING) {\n      state = uploadStates.STATE_POSTPROCESSING;\n    }\n  }\n\n  return state;\n}\n\nfunction UploadStatus(_ref) {\n  let {\n    files,\n    i18n,\n    isAllComplete,\n    isAllErrored,\n    isAllPaused,\n    inProgressNotPausedFiles,\n    newFiles,\n    processingFiles\n  } = _ref;\n  const uploadingState = getUploadingState(isAllErrored, isAllComplete, isAllPaused, files);\n\n  switch (uploadingState) {\n    case 'uploading':\n      return i18n('uploadingXFiles', {\n        smart_count: inProgressNotPausedFiles.length\n      });\n\n    case 'preprocessing':\n    case 'postprocessing':\n      return i18n('processingXFiles', {\n        smart_count: processingFiles.length\n      });\n\n    case 'paused':\n      return i18n('uploadPaused');\n\n    case 'waiting':\n      return i18n('xFilesSelected', {\n        smart_count: newFiles.length\n      });\n\n    case 'complete':\n      return i18n('uploadComplete');\n\n    default:\n  }\n}\n\nfunction PanelTopBar(props) {\n  const {\n    i18n,\n    isAllComplete,\n    hideCancelButton,\n    maxNumberOfFiles,\n    toggleAddFilesPanel,\n    uppy\n  } = props;\n  let {\n    allowNewUpload\n  } = props; // TODO maybe this should be done in ../Dashboard.jsx, then just pass that down as `allowNewUpload`\n\n  if (allowNewUpload && maxNumberOfFiles) {\n    // eslint-disable-next-line react/destructuring-assignment\n    allowNewUpload = props.totalFileCount < props.maxNumberOfFiles;\n  }\n\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-bar\"\n  }, !isAllComplete && !hideCancelButton ? (0, _preact.h)(\"button\", {\n    className: \"uppy-DashboardContent-back\",\n    type: \"button\",\n    onClick: () => uppy.cancelAll()\n  }, i18n('cancel')) : (0, _preact.h)(\"div\", null), (0, _preact.h)(\"div\", {\n    className: \"uppy-DashboardContent-title\",\n    role: \"heading\",\n    \"aria-level\": \"1\"\n  }, (0, _preact.h)(UploadStatus, props)), allowNewUpload ? (0, _preact.h)(\"button\", {\n    className: \"uppy-DashboardContent-addMore\",\n    type: \"button\",\n    \"aria-label\": i18n('addMoreFiles'),\n    title: i18n('addMoreFiles'),\n    onClick: () => toggleAddFilesPanel(true)\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"15\",\n    height: \"15\",\n    viewBox: \"0 0 15 15\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M8 6.5h6a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5H8v6a.5.5 0 0 1-.5.5H7a.5.5 0 0 1-.5-.5V8h-6a.5.5 0 0 1-.5-.5V7a.5.5 0 0 1 .5-.5h6v-6A.5.5 0 0 1 7 0h.5a.5.5 0 0 1 .5.5v6z\"\n  })), (0, _preact.h)(\"span\", {\n    className: \"uppy-DashboardContent-addMoreCaption\"\n  }, i18n('addMore'))) : (0, _preact.h)(\"div\", null));\n}\n\nmodule.exports = PanelTopBar;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _nonSecure = require(\"nanoid/non-secure\");\n\nconst classNames = require(\"classnames\");\n\nconst getFileTypeIcon = require(\"../../utils/getFileTypeIcon.js\");\n\nconst ignoreEvent = require(\"../../utils/ignoreEvent.js\");\n\nconst FilePreview = require(\"../FilePreview.js\");\n\nclass FileCard extends _preact.Component {\n  constructor(props) {\n    super(props);\n    this.form = document.createElement('form');\n\n    this.updateMeta = (newVal, name) => {\n      this.setState(_ref => {\n        let {\n          formState\n        } = _ref;\n        return {\n          formState: { ...formState,\n            [name]: newVal\n          }\n        };\n      });\n    };\n\n    this.handleSave = e => {\n      e.preventDefault();\n      const fileID = this.props.fileCardFor;\n      this.props.saveFileCard(this.state.formState, fileID);\n    };\n\n    this.handleCancel = () => {\n      const file = this.props.files[this.props.fileCardFor];\n      this.props.uppy.emit('file-editor:cancel', file);\n      this.props.toggleFileCard(false);\n    };\n\n    this.saveOnEnter = ev => {\n      if (ev.keyCode === 13) {\n        ev.stopPropagation();\n        ev.preventDefault();\n        const file = this.props.files[this.props.fileCardFor];\n        this.props.saveFileCard(this.state.formState, file.id);\n      }\n    };\n\n    this.renderMetaFields = () => {\n      const metaFields = this.getMetaFields() || [];\n      const fieldCSSClasses = {\n        text: 'uppy-u-reset uppy-c-textInput uppy-Dashboard-FileCard-input'\n      };\n      return metaFields.map(field => {\n        const id = `uppy-Dashboard-FileCard-input-${field.id}`;\n        const required = this.props.requiredMetaFields.includes(field.id);\n        return (0, _preact.h)(\"fieldset\", {\n          key: field.id,\n          className: \"uppy-Dashboard-FileCard-fieldset\"\n        }, (0, _preact.h)(\"label\", {\n          className: \"uppy-Dashboard-FileCard-label\",\n          htmlFor: id\n        }, field.name), field.render !== undefined ? field.render({\n          value: this.state.formState[field.id],\n          onChange: newVal => this.updateMeta(newVal, field.id),\n          fieldCSSClasses,\n          required,\n          form: this.form.id\n        }, _preact.h) : (0, _preact.h)(\"input\", {\n          className: fieldCSSClasses.text,\n          id: id,\n          form: this.form.id,\n          type: field.type || 'text',\n          required: required,\n          value: this.state.formState[field.id],\n          placeholder: field.placeholder // If `form` attribute is not supported, we need to capture pressing Enter to avoid bubbling in case Uppy is\n          // embedded inside a <form>.\n          ,\n          onKeyUp: 'form' in HTMLInputElement.prototype ? undefined : this.saveOnEnter,\n          onKeyDown: 'form' in HTMLInputElement.prototype ? undefined : this.saveOnEnter,\n          onKeyPress: 'form' in HTMLInputElement.prototype ? undefined : this.saveOnEnter,\n          onInput: ev => this.updateMeta(ev.target.value, field.id),\n          \"data-uppy-super-focusable\": true\n        }));\n      });\n    };\n\n    const _file = this.props.files[this.props.fileCardFor];\n\n    const _metaFields = this.getMetaFields() || [];\n\n    const storedMetaData = {};\n\n    _metaFields.forEach(field => {\n      storedMetaData[field.id] = _file.meta[field.id] || '';\n    });\n\n    this.state = {\n      formState: storedMetaData\n    };\n    this.form.id = (0, _nonSecure.nanoid)();\n  } // TODO(aduh95): move this to `UNSAFE_componentWillMount` when updating to Preact X+.\n\n\n  componentWillMount() {\n    // eslint-disable-line react/no-deprecated\n    this.form.addEventListener('submit', this.handleSave);\n    document.body.appendChild(this.form);\n  }\n\n  componentWillUnmount() {\n    this.form.removeEventListener('submit', this.handleSave);\n    document.body.removeChild(this.form);\n  }\n\n  getMetaFields() {\n    return typeof this.props.metaFields === 'function' ? this.props.metaFields(this.props.files[this.props.fileCardFor]) : this.props.metaFields;\n  }\n\n  render() {\n    const file = this.props.files[this.props.fileCardFor];\n    const showEditButton = this.props.canEditFile(file);\n    return (0, _preact.h)(\"div\", {\n      className: classNames('uppy-Dashboard-FileCard', this.props.className),\n      \"data-uppy-panelType\": \"FileCard\",\n      onDragOver: ignoreEvent,\n      onDragLeave: ignoreEvent,\n      onDrop: ignoreEvent,\n      onPaste: ignoreEvent\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-DashboardContent-bar\"\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-DashboardContent-title\",\n      role: \"heading\",\n      \"aria-level\": \"1\"\n    }, this.props.i18nArray('editing', {\n      file: (0, _preact.h)(\"span\", {\n        className: \"uppy-DashboardContent-titleFile\"\n      }, file.meta ? file.meta.name : file.name)\n    })), (0, _preact.h)(\"button\", {\n      className: \"uppy-DashboardContent-back\",\n      type: \"button\",\n      form: this.form.id,\n      title: this.props.i18n('finishEditingFile'),\n      onClick: this.handleCancel\n    }, this.props.i18n('cancel'))), (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-FileCard-inner\"\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-FileCard-preview\",\n      style: {\n        backgroundColor: getFileTypeIcon(file.type).color\n      }\n    }, (0, _preact.h)(FilePreview, {\n      file: file\n    }), showEditButton && (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn uppy-Dashboard-FileCard-edit\",\n      onClick: event => {\n        // When opening the image editor we want to save any meta fields changes.\n        // Otherwise it's confusing for the user to click save in the editor,\n        // but the changes here are discarded. This bypasses validation,\n        // but we are okay with that.\n        this.handleSave(event);\n        this.props.openFileEditor(file);\n      },\n      form: this.form.id\n    }, this.props.i18n('editFile'))), (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-FileCard-info\"\n    }, this.renderMetaFields()), (0, _preact.h)(\"div\", {\n      className: \"uppy-Dashboard-FileCard-actions\"\n    }, (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Dashboard-FileCard-actionsBtn\" // If `form` attribute is supported, we want a submit button to trigger the form validation.\n      // Otherwise, fallback to a classic button with a onClick event handler.\n      ,\n      type: 'form' in HTMLButtonElement.prototype ? 'submit' : 'button',\n      onClick: 'form' in HTMLButtonElement.prototype ? undefined : this.handleSave,\n      form: this.form.id\n    }, this.props.i18n('saveChanges')), (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-c-btn uppy-c-btn-link uppy-Dashboard-FileCard-actionsBtn\",\n      type: \"button\",\n      onClick: this.handleCancel,\n      form: this.form.id\n    }, this.props.i18n('cancel')))));\n  }\n\n}\n\nmodule.exports = FileCard;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst classNames = require(\"classnames\");\n\nconst transitionName = 'uppy-transition-slideDownUp';\nconst duration = 250;\n/**\n * Vertical slide transition.\n *\n * This can take a _single_ child component, which _must_ accept a `className` prop.\n *\n * Currently this is specific to the `uppy-transition-slideDownUp` transition,\n * but it should be simple to extend this for any type of single-element\n * transition by setting the CSS name and duration as props.\n */\n\nclass Slide extends _preact.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      cachedChildren: null,\n      className: ''\n    };\n  } // TODO: refactor to stable lifecycle method\n  // eslint-disable-next-line\n\n\n  componentWillUpdate(nextProps) {\n    const {\n      cachedChildren\n    } = this.state;\n    const child = (0, _preact.toChildArray)(nextProps.children)[0];\n    if (cachedChildren === child) return null;\n    const patch = {\n      cachedChildren: child\n    }; // Enter transition\n\n    if (child && !cachedChildren) {\n      patch.className = `${transitionName}-enter`;\n      cancelAnimationFrame(this.animationFrame);\n      clearTimeout(this.leaveTimeout);\n      this.leaveTimeout = undefined;\n      this.animationFrame = requestAnimationFrame(() => {\n        // Force it to render before we add the active class\n        // this.base.getBoundingClientRect()\n        this.setState({\n          className: `${transitionName}-enter ${transitionName}-enter-active`\n        });\n        this.enterTimeout = setTimeout(() => {\n          this.setState({\n            className: ''\n          });\n        }, duration);\n      });\n    } // Leave transition\n\n\n    if (cachedChildren && !child && this.leaveTimeout === undefined) {\n      patch.cachedChildren = cachedChildren;\n      patch.className = `${transitionName}-leave`;\n      cancelAnimationFrame(this.animationFrame);\n      clearTimeout(this.enterTimeout);\n      this.enterTimeout = undefined;\n      this.animationFrame = requestAnimationFrame(() => {\n        this.setState({\n          className: `${transitionName}-leave ${transitionName}-leave-active`\n        });\n        this.leaveTimeout = setTimeout(() => {\n          this.setState({\n            cachedChildren: null,\n            className: ''\n          });\n        }, duration);\n      });\n    } // eslint-disable-next-line\n\n\n    this.setState(patch);\n  }\n\n  render() {\n    const {\n      cachedChildren,\n      className\n    } = this.state;\n\n    if (!cachedChildren) {\n      return null;\n    }\n\n    return (0, _preact.cloneElement)(cachedChildren, {\n      className: classNames(className, cachedChildren.props.className)\n    });\n  }\n\n}\n\nmodule.exports = Slide;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nconst classNames = require(\"classnames\");\n\nconst isDragDropSupported = require(\"@uppy/utils/lib/isDragDropSupported\");\n\nconst FileList = require(\"./FileList.js\");\n\nconst AddFiles = require(\"./AddFiles.js\");\n\nconst AddFilesPanel = require(\"./AddFilesPanel.js\");\n\nconst PickerPanelContent = require(\"./PickerPanelContent.js\");\n\nconst EditorPanel = require(\"./EditorPanel.js\");\n\nconst PanelTopBar = require(\"./PickerPanelTopBar.js\");\n\nconst FileCard = require(\"./FileCard/index.js\");\n\nconst Slide = require(\"./Slide.js\"); // http://dev.edenspiekermann.com/2016/02/11/introducing-accessible-modal-dialog\n// https://github.com/ghosh/micromodal\n\n\nconst WIDTH_XL = 900;\nconst WIDTH_LG = 700;\nconst WIDTH_MD = 576;\nconst HEIGHT_MD = 400;\n\nfunction Dashboard(props) {\n  const noFiles = props.totalFileCount === 0;\n  const isSizeMD = props.containerWidth > WIDTH_MD;\n  const dashboardClassName = classNames({\n    'uppy-Dashboard': true,\n    'uppy-Dashboard--isDisabled': props.disabled,\n    'uppy-Dashboard--animateOpenClose': props.animateOpenClose,\n    'uppy-Dashboard--isClosing': props.isClosing,\n    'uppy-Dashboard--isDraggingOver': props.isDraggingOver,\n    'uppy-Dashboard--modal': !props.inline,\n    'uppy-size--md': props.containerWidth > WIDTH_MD,\n    'uppy-size--lg': props.containerWidth > WIDTH_LG,\n    'uppy-size--xl': props.containerWidth > WIDTH_XL,\n    'uppy-size--height-md': props.containerHeight > HEIGHT_MD,\n    'uppy-Dashboard--isAddFilesPanelVisible': props.showAddFilesPanel,\n    'uppy-Dashboard--isInnerWrapVisible': props.areInsidesReadyToBeVisible\n  }); // Important: keep these in sync with the percent width values in `src/components/FileItem/index.scss`.\n\n  let itemsPerRow = 1; // mobile\n\n  if (props.containerWidth > WIDTH_XL) {\n    itemsPerRow = 5;\n  } else if (props.containerWidth > WIDTH_LG) {\n    itemsPerRow = 4;\n  } else if (props.containerWidth > WIDTH_MD) {\n    itemsPerRow = 3;\n  }\n\n  const showFileList = props.showSelectedFiles && !noFiles;\n  const numberOfFilesForRecovery = props.recoveredState ? Object.keys(props.recoveredState.files).length : null;\n  const numberOfGhosts = props.files ? Object.keys(props.files).filter(fileID => props.files[fileID].isGhost).length : null;\n\n  const renderRestoredText = () => {\n    if (numberOfGhosts > 0) {\n      return props.i18n('recoveredXFiles', {\n        smart_count: numberOfGhosts\n      });\n    }\n\n    return props.i18n('recoveredAllFiles');\n  };\n\n  const dashboard = (0, _preact.h)(\"div\", {\n    className: dashboardClassName,\n    \"data-uppy-theme\": props.theme,\n    \"data-uppy-num-acquirers\": props.acquirers.length,\n    \"data-uppy-drag-drop-supported\": !props.disableLocalFiles && isDragDropSupported(),\n    \"aria-hidden\": props.inline ? 'false' : props.isHidden,\n    \"aria-disabled\": props.disabled,\n    \"aria-label\": !props.inline ? props.i18n('dashboardWindowTitle') : props.i18n('dashboardTitle'),\n    onPaste: props.handlePaste,\n    onDragOver: props.handleDragOver,\n    onDragLeave: props.handleDragLeave,\n    onDrop: props.handleDrop\n  }, (0, _preact.h)(\"div\", {\n    \"aria-hidden\": \"true\",\n    className: \"uppy-Dashboard-overlay\",\n    tabIndex: -1,\n    onClick: props.handleClickOutside\n  }), (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-inner\",\n    \"aria-modal\": !props.inline && 'true',\n    role: !props.inline && 'dialog',\n    style: {\n      width: props.inline && props.width ? props.width : '',\n      height: props.inline && props.height ? props.height : ''\n    }\n  }, !props.inline ? (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-Dashboard-close\",\n    type: \"button\",\n    \"aria-label\": props.i18n('closeModal'),\n    title: props.i18n('closeModal'),\n    onClick: props.closeModal\n  }, (0, _preact.h)(\"span\", {\n    \"aria-hidden\": \"true\"\n  }, \"\\xD7\")) : null, (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-innerWrap\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-dropFilesHereHint\"\n  }, props.i18n('dropHint')), showFileList && (0, _preact.h)(PanelTopBar, props), numberOfFilesForRecovery && (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-serviceMsg\"\n  }, (0, _preact.h)(\"svg\", {\n    className: \"uppy-Dashboard-serviceMsg-icon\",\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"21\",\n    height: \"16\",\n    viewBox: \"0 0 24 19\"\n  }, (0, _preact.h)(\"g\", {\n    transform: \"translate(0 -1)\",\n    fill: \"none\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M12.857 1.43l10.234 17.056A1 1 0 0122.234 20H1.766a1 1 0 01-.857-1.514L11.143 1.429a1 1 0 011.714 0z\",\n    fill: \"#FFD300\"\n  }), (0, _preact.h)(\"path\", {\n    fill: \"#000\",\n    d: \"M11 6h2l-.3 8h-1.4z\"\n  }), (0, _preact.h)(\"circle\", {\n    fill: \"#000\",\n    cx: \"12\",\n    cy: \"17\",\n    r: \"1\"\n  }))), (0, _preact.h)(\"strong\", {\n    className: \"uppy-Dashboard-serviceMsg-title\"\n  }, props.i18n('sessionRestored')), (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-serviceMsg-text\"\n  }, renderRestoredText())), showFileList ? (0, _preact.h)(FileList // eslint-disable-next-line react/jsx-props-no-spreading\n  , _extends({}, props, {\n    itemsPerRow: itemsPerRow\n  })) : // eslint-disable-next-line react/jsx-props-no-spreading\n  (0, _preact.h)(AddFiles, _extends({}, props, {\n    isSizeMD: isSizeMD\n  })), (0, _preact.h)(Slide, null, props.showAddFilesPanel ? (0, _preact.h)(AddFilesPanel, _extends({\n    key: \"AddFiles\"\n  }, props, {\n    isSizeMD: isSizeMD\n  })) : null), (0, _preact.h)(Slide, null, props.fileCardFor ? (0, _preact.h)(FileCard, _extends({\n    key: \"FileCard\"\n  }, props)) : null), (0, _preact.h)(Slide, null, props.activePickerPanel ? (0, _preact.h)(PickerPanelContent, _extends({\n    key: \"Picker\"\n  }, props)) : null), (0, _preact.h)(Slide, null, props.showFileEditor ? (0, _preact.h)(EditorPanel, _extends({\n    key: \"Editor\"\n  }, props)) : null), (0, _preact.h)(\"div\", {\n    className: \"uppy-Dashboard-progressindicators\"\n  }, props.progressindicators.map(target => {\n    return props.uppy.getPlugin(target.id).render(props.state);\n  })))));\n  return dashboard;\n}\n\nmodule.exports = Dashboard;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // When `inline: false`, used as the screen reader label for the button that closes the modal.\n    closeModal: 'Close Modal',\n    // Used as the screen reader label for the plus (+) button that shows the \u201CAdd more files\u201D screen\n    addMoreFiles: 'Add more files',\n    addingMoreFiles: 'Adding more files',\n    // Used as the header for import panels, e.g., \u201CImport from Google Drive\u201D.\n    importFrom: 'Import from %{name}',\n    // When `inline: false`, used as the screen reader label for the dashboard modal.\n    dashboardWindowTitle: 'Uppy Dashboard Window (Press escape to close)',\n    // When `inline: true`, used as the screen reader label for the dashboard area.\n    dashboardTitle: 'Uppy Dashboard',\n    // Shown in the Informer when a link to a file was copied to the clipboard.\n    copyLinkToClipboardSuccess: 'Link copied to clipboard.',\n    // Used when a link cannot be copied automatically \u2014 the user has to select the text from the\n    // input element below this string.\n    copyLinkToClipboardFallback: 'Copy the URL below',\n    // Used as the hover title and screen reader label for buttons that copy a file link.\n    copyLink: 'Copy link',\n    back: 'Back',\n    // Used as the screen reader label for buttons that remove a file.\n    removeFile: 'Remove file',\n    // Used as the screen reader label for buttons that open the metadata editor panel for a file.\n    editFile: 'Edit file',\n    // Shown in the panel header for the metadata editor. Rendered as \u201CEditing image.png\u201D.\n    editing: 'Editing %{file}',\n    // Used as the screen reader label for the button that saves metadata edits and returns to the\n    // file list view.\n    finishEditingFile: 'Finish editing file',\n    saveChanges: 'Save changes',\n    // Used as the label for the tab button that opens the system file selection dialog.\n    myDevice: 'My Device',\n    dropHint: 'Drop your files here',\n    // Used as the hover text and screen reader label for file progress indicators when\n    // they have been fully uploaded.\n    uploadComplete: 'Upload complete',\n    uploadPaused: 'Upload paused',\n    // Used as the hover text and screen reader label for the buttons to resume paused uploads.\n    resumeUpload: 'Resume upload',\n    // Used as the hover text and screen reader label for the buttons to pause uploads.\n    pauseUpload: 'Pause upload',\n    // Used as the hover text and screen reader label for the buttons to retry failed uploads.\n    retryUpload: 'Retry upload',\n    // Used as the hover text and screen reader label for the buttons to cancel uploads.\n    cancelUpload: 'Cancel upload',\n    // Used in a title, how many files are currently selected\n    xFilesSelected: {\n      0: '%{smart_count} file selected',\n      1: '%{smart_count} files selected'\n    },\n    uploadingXFiles: {\n      0: 'Uploading %{smart_count} file',\n      1: 'Uploading %{smart_count} files'\n    },\n    processingXFiles: {\n      0: 'Processing %{smart_count} file',\n      1: 'Processing %{smart_count} files'\n    },\n    // The \"powered by Uppy\" link at the bottom of the Dashboard.\n    poweredBy: 'Powered by %{uppy}',\n    addMore: 'Add more',\n    editFileWithFilename: 'Edit file %{file}',\n    save: 'Save',\n    cancel: 'Cancel',\n    dropPasteFiles: 'Drop files here or %{browseFiles}',\n    dropPasteFolders: 'Drop files here or %{browseFolders}',\n    dropPasteBoth: 'Drop files here, %{browseFiles} or %{browseFolders}',\n    dropPasteImportFiles: 'Drop files here, %{browseFiles} or import from:',\n    dropPasteImportFolders: 'Drop files here, %{browseFolders} or import from:',\n    dropPasteImportBoth: 'Drop files here, %{browseFiles}, %{browseFolders} or import from:',\n    importFiles: 'Import files from:',\n    browseFiles: 'browse files',\n    browseFolders: 'browse folders',\n    recoveredXFiles: {\n      0: 'We could not fully recover 1 file. Please re-select it and resume the upload.',\n      1: 'We could not fully recover %{smart_count} files. Please re-select them and resume the upload.'\n    },\n    recoveredAllFiles: 'We restored all files. You can now resume the upload.',\n    sessionRestored: 'Session restored',\n    reSelect: 'Re-select',\n    missingRequiredMetaFields: {\n      0: 'Missing required meta field: %{fields}.',\n      1: 'Missing required meta fields: %{fields}.'\n    }\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nvar _nonSecure = require(\"nanoid/non-secure\");\n\nvar trapFocus = require(\"./utils/trapFocus.js\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst StatusBar = require(\"@uppy/status-bar\");\n\nconst Informer = require(\"@uppy/informer\");\n\nconst ThumbnailGenerator = require(\"@uppy/thumbnail-generator\");\n\nconst findAllDOMElements = require(\"@uppy/utils/lib/findAllDOMElements\");\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n\nconst getDroppedFiles = require(\"@uppy/utils/lib/getDroppedFiles\");\n\nconst memoizeOne = require(\"memoize-one\");\n\nconst FOCUSABLE_ELEMENTS = require(\"@uppy/utils/lib/FOCUSABLE_ELEMENTS.js\");\n\nconst createSuperFocus = require(\"./utils/createSuperFocus.js\");\n\nconst DashboardUI = require(\"./components/Dashboard.js\");\n\nconst packageJson = {\n  \"version\": \"2.4.3\"\n};\n\nconst locale = require(\"./locale.js\");\n\nconst memoize = memoizeOne.default || memoizeOne;\nconst TAB_KEY = 9;\nconst ESC_KEY = 27;\n\nfunction createPromise() {\n  const o = {};\n  o.promise = new Promise((resolve, reject) => {\n    o.resolve = resolve;\n    o.reject = reject;\n  });\n  return o;\n}\n\nfunction defaultPickerIcon() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"30\",\n    height: \"30\",\n    viewBox: \"0 0 30 30\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M15 30c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15C6.716 0 0 6.716 0 15c0 8.284 6.716 15 15 15zm4.258-12.676v6.846h-8.426v-6.846H5.204l9.82-12.364 9.82 12.364H19.26z\"\n  }));\n}\n/**\n * Dashboard UI with previews, metadata editing, tabs for various services and more\n */\n\n\nvar _openFileEditorWhenFilesAdded = /*#__PURE__*/_classPrivateFieldLooseKey(\"openFileEditorWhenFilesAdded\");\n\nvar _attachRenderFunctionToTarget = /*#__PURE__*/_classPrivateFieldLooseKey(\"attachRenderFunctionToTarget\");\n\nvar _isTargetSupported = /*#__PURE__*/_classPrivateFieldLooseKey(\"isTargetSupported\");\n\nvar _getAcquirers = /*#__PURE__*/_classPrivateFieldLooseKey(\"getAcquirers\");\n\nvar _getProgressIndicators = /*#__PURE__*/_classPrivateFieldLooseKey(\"getProgressIndicators\");\n\nvar _getEditors = /*#__PURE__*/_classPrivateFieldLooseKey(\"getEditors\");\n\nclass Dashboard extends _core.UIPlugin {\n  constructor(uppy, _opts) {\n    var _this;\n\n    super(uppy, _opts);\n    _this = this;\n\n    this.removeTarget = plugin => {\n      const pluginState = this.getPluginState(); // filter out the one we want to remove\n\n      const newTargets = pluginState.targets.filter(target => target.id !== plugin.id);\n      this.setPluginState({\n        targets: newTargets\n      });\n    };\n\n    this.addTarget = plugin => {\n      const callerPluginId = plugin.id || plugin.constructor.name;\n      const callerPluginName = plugin.title || callerPluginId;\n      const callerPluginType = plugin.type;\n\n      if (callerPluginType !== 'acquirer' && callerPluginType !== 'progressindicator' && callerPluginType !== 'editor') {\n        const msg = 'Dashboard: can only be targeted by plugins of types: acquirer, progressindicator, editor';\n        this.uppy.log(msg, 'error');\n        return undefined;\n      }\n\n      const target = {\n        id: callerPluginId,\n        name: callerPluginName,\n        type: callerPluginType\n      };\n      const state = this.getPluginState();\n      const newTargets = state.targets.slice();\n      newTargets.push(target);\n      this.setPluginState({\n        targets: newTargets\n      });\n      return this.el;\n    };\n\n    this.hideAllPanels = () => {\n      const state = this.getPluginState();\n      const update = {\n        activePickerPanel: false,\n        showAddFilesPanel: false,\n        activeOverlayType: null,\n        fileCardFor: null,\n        showFileEditor: false\n      };\n\n      if (state.activePickerPanel === update.activePickerPanel && state.showAddFilesPanel === update.showAddFilesPanel && state.showFileEditor === update.showFileEditor && state.activeOverlayType === update.activeOverlayType) {\n        // avoid doing a state update if nothing changed\n        return;\n      }\n\n      this.setPluginState(update);\n    };\n\n    this.showPanel = id => {\n      const {\n        targets\n      } = this.getPluginState();\n      const activePickerPanel = targets.filter(target => {\n        return target.type === 'acquirer' && target.id === id;\n      })[0];\n      this.setPluginState({\n        activePickerPanel,\n        activeOverlayType: 'PickerPanel'\n      });\n    };\n\n    this.canEditFile = file => {\n      const {\n        targets\n      } = this.getPluginState();\n\n      const editors = _classPrivateFieldLooseBase(this, _getEditors)[_getEditors](targets);\n\n      return editors.some(target => this.uppy.getPlugin(target.id).canEditFile(file));\n    };\n\n    this.openFileEditor = file => {\n      const {\n        targets\n      } = this.getPluginState();\n\n      const editors = _classPrivateFieldLooseBase(this, _getEditors)[_getEditors](targets);\n\n      this.setPluginState({\n        showFileEditor: true,\n        fileCardFor: file.id || null,\n        activeOverlayType: 'FileEditor'\n      });\n      editors.forEach(editor => {\n        this.uppy.getPlugin(editor.id).selectFile(file);\n      });\n    };\n\n    this.saveFileEditor = () => {\n      const {\n        targets\n      } = this.getPluginState();\n\n      const editors = _classPrivateFieldLooseBase(this, _getEditors)[_getEditors](targets);\n\n      editors.forEach(editor => {\n        this.uppy.getPlugin(editor.id).save();\n      });\n      this.hideAllPanels();\n    };\n\n    this.openModal = () => {\n      const {\n        promise,\n        resolve\n      } = createPromise(); // save scroll position\n\n      this.savedScrollPosition = window.pageYOffset; // save active element, so we can restore focus when modal is closed\n\n      this.savedActiveElement = document.activeElement;\n\n      if (this.opts.disablePageScrollWhenModalOpen) {\n        document.body.classList.add('uppy-Dashboard-isFixed');\n      }\n\n      if (this.opts.animateOpenClose && this.getPluginState().isClosing) {\n        const handler = () => {\n          this.setPluginState({\n            isHidden: false\n          });\n          this.el.removeEventListener('animationend', handler, false);\n          resolve();\n        };\n\n        this.el.addEventListener('animationend', handler, false);\n      } else {\n        this.setPluginState({\n          isHidden: false\n        });\n        resolve();\n      }\n\n      if (this.opts.browserBackButtonClose) {\n        this.updateBrowserHistory();\n      } // handle ESC and TAB keys in modal dialog\n\n\n      document.addEventListener('keydown', this.handleKeyDownInModal);\n      this.uppy.emit('dashboard:modal-open');\n      return promise;\n    };\n\n    this.closeModal = function (opts) {\n      if (opts === void 0) {\n        opts = {};\n      }\n\n      const {\n        // Whether the modal is being closed by the user (`true`) or by other means (e.g. browser back button)\n        manualClose = true\n      } = opts;\n\n      const {\n        isHidden,\n        isClosing\n      } = _this.getPluginState();\n\n      if (isHidden || isClosing) {\n        // short-circuit if animation is ongoing\n        return undefined;\n      }\n\n      const {\n        promise,\n        resolve\n      } = createPromise();\n\n      if (_this.opts.disablePageScrollWhenModalOpen) {\n        document.body.classList.remove('uppy-Dashboard-isFixed');\n      }\n\n      if (_this.opts.animateOpenClose) {\n        _this.setPluginState({\n          isClosing: true\n        });\n\n        const handler = () => {\n          _this.setPluginState({\n            isHidden: true,\n            isClosing: false\n          });\n\n          _this.superFocus.cancel();\n\n          _this.savedActiveElement.focus();\n\n          _this.el.removeEventListener('animationend', handler, false);\n\n          resolve();\n        };\n\n        _this.el.addEventListener('animationend', handler, false);\n      } else {\n        _this.setPluginState({\n          isHidden: true\n        });\n\n        _this.superFocus.cancel();\n\n        _this.savedActiveElement.focus();\n\n        resolve();\n      } // handle ESC and TAB keys in modal dialog\n\n\n      document.removeEventListener('keydown', _this.handleKeyDownInModal);\n\n      if (manualClose) {\n        if (_this.opts.browserBackButtonClose) {\n          var _history$state;\n\n          // Make sure that the latest entry in the history state is our modal name\n          // eslint-disable-next-line no-restricted-globals\n          if ((_history$state = history.state) != null && _history$state[_this.modalName]) {\n            // Go back in history to clear out the entry we created (ultimately closing the modal)\n            // eslint-disable-next-line no-restricted-globals\n            history.back();\n          }\n        }\n      }\n\n      _this.uppy.emit('dashboard:modal-closed');\n\n      return promise;\n    };\n\n    this.isModalOpen = () => {\n      return !this.getPluginState().isHidden || false;\n    };\n\n    this.requestCloseModal = () => {\n      if (this.opts.onRequestCloseModal) {\n        return this.opts.onRequestCloseModal();\n      }\n\n      return this.closeModal();\n    };\n\n    this.setDarkModeCapability = isDarkModeOn => {\n      const {\n        capabilities\n      } = this.uppy.getState();\n      this.uppy.setState({\n        capabilities: { ...capabilities,\n          darkMode: isDarkModeOn\n        }\n      });\n    };\n\n    this.handleSystemDarkModeChange = event => {\n      const isDarkModeOnNow = event.matches;\n      this.uppy.log(`[Dashboard] Dark mode is ${isDarkModeOnNow ? 'on' : 'off'}`);\n      this.setDarkModeCapability(isDarkModeOnNow);\n    };\n\n    this.toggleFileCard = (show, fileID) => {\n      const file = this.uppy.getFile(fileID);\n\n      if (show) {\n        this.uppy.emit('dashboard:file-edit-start', file);\n      } else {\n        this.uppy.emit('dashboard:file-edit-complete', file);\n      }\n\n      this.setPluginState({\n        fileCardFor: show ? fileID : null,\n        activeOverlayType: show ? 'FileCard' : null\n      });\n    };\n\n    this.toggleAddFilesPanel = show => {\n      this.setPluginState({\n        showAddFilesPanel: show,\n        activeOverlayType: show ? 'AddFiles' : null\n      });\n    };\n\n    this.addFiles = files => {\n      const descriptors = files.map(file => ({\n        source: this.id,\n        name: file.name,\n        type: file.type,\n        data: file,\n        meta: {\n          // path of the file relative to the ancestor directory the user selected.\n          // e.g. 'docs/Old Prague/airbnb.pdf'\n          relativePath: file.relativePath || file.webkitRelativePath || null\n        }\n      }));\n\n      try {\n        this.uppy.addFiles(descriptors);\n      } catch (err) {\n        this.uppy.log(err);\n      }\n    };\n\n    this.startListeningToResize = () => {\n      // Watch for Dashboard container (`.uppy-Dashboard-inner`) resize\n      // and update containerWidth/containerHeight in plugin state accordingly.\n      // Emits first event on initialization.\n      this.resizeObserver = new ResizeObserver(entries => {\n        const uppyDashboardInnerEl = entries[0];\n        const {\n          width,\n          height\n        } = uppyDashboardInnerEl.contentRect;\n        this.uppy.log(`[Dashboard] resized: ${width} / ${height}`, 'debug');\n        this.setPluginState({\n          containerWidth: width,\n          containerHeight: height,\n          areInsidesReadyToBeVisible: true\n        });\n      });\n      this.resizeObserver.observe(this.el.querySelector('.uppy-Dashboard-inner')); // If ResizeObserver fails to emit an event telling us what size to use - default to the mobile view\n\n      this.makeDashboardInsidesVisibleAnywayTimeout = setTimeout(() => {\n        const pluginState = this.getPluginState();\n        const isModalAndClosed = !this.opts.inline && pluginState.isHidden;\n\n        if ( // if ResizeObserver hasn't yet fired,\n        !pluginState.areInsidesReadyToBeVisible // and it's not due to the modal being closed\n        && !isModalAndClosed) {\n          this.uppy.log(\"[Dashboard] resize event didn't fire on time: defaulted to mobile layout\", 'debug');\n          this.setPluginState({\n            areInsidesReadyToBeVisible: true\n          });\n        }\n      }, 1000);\n    };\n\n    this.stopListeningToResize = () => {\n      this.resizeObserver.disconnect();\n      clearTimeout(this.makeDashboardInsidesVisibleAnywayTimeout);\n    };\n\n    this.recordIfFocusedOnUppyRecently = event => {\n      if (this.el.contains(event.target)) {\n        this.ifFocusedOnUppyRecently = true;\n      } else {\n        this.ifFocusedOnUppyRecently = false; // ___Why run this.superFocus.cancel here when it already runs in superFocusOnEachUpdate?\n        //    Because superFocus is debounced, when we move from Uppy to some other element on the page,\n        //    previously run superFocus sometimes hits and moves focus back to Uppy.\n\n        this.superFocus.cancel();\n      }\n    };\n\n    this.disableAllFocusableElements = disable => {\n      const focusableNodes = toArray(this.el.querySelectorAll(FOCUSABLE_ELEMENTS));\n\n      if (disable) {\n        focusableNodes.forEach(node => {\n          // save previous tabindex in a data-attribute, to restore when enabling\n          const currentTabIndex = node.getAttribute('tabindex');\n\n          if (currentTabIndex) {\n            node.dataset.inertTabindex = currentTabIndex; // eslint-disable-line no-param-reassign\n          }\n\n          node.setAttribute('tabindex', '-1');\n        });\n      } else {\n        focusableNodes.forEach(node => {\n          if ('inertTabindex' in node.dataset) {\n            node.setAttribute('tabindex', node.dataset.inertTabindex);\n          } else {\n            node.removeAttribute('tabindex');\n          }\n        });\n      }\n\n      this.dashboardIsDisabled = disable;\n    };\n\n    this.updateBrowserHistory = () => {\n      var _history$state2;\n\n      // Ensure history state does not already contain our modal name to avoid double-pushing\n      // eslint-disable-next-line no-restricted-globals\n      if (!((_history$state2 = history.state) != null && _history$state2[this.modalName])) {\n        // Push to history so that the page is not lost on browser back button press\n        // eslint-disable-next-line no-restricted-globals\n        history.pushState({ // eslint-disable-next-line no-restricted-globals\n          ...history.state,\n          [this.modalName]: true\n        }, '');\n      } // Listen for back button presses\n\n\n      window.addEventListener('popstate', this.handlePopState, false);\n    };\n\n    this.handlePopState = event => {\n      var _event$state;\n\n      // Close the modal if the history state no longer contains our modal name\n      if (this.isModalOpen() && (!event.state || !event.state[this.modalName])) {\n        this.closeModal({\n          manualClose: false\n        });\n      } // When the browser back button is pressed and uppy is now the latest entry\n      // in the history but the modal is closed, fix the history by removing the\n      // uppy history entry.\n      // This occurs when another entry is added into the history state while the\n      // modal is open, and then the modal gets manually closed.\n      // Solves PR #575 (https://github.com/transloadit/uppy/pull/575)\n\n\n      if (!this.isModalOpen() && (_event$state = event.state) != null && _event$state[this.modalName]) {\n        // eslint-disable-next-line no-restricted-globals\n        history.back();\n      }\n    };\n\n    this.handleKeyDownInModal = event => {\n      // close modal on esc key press\n      if (event.keyCode === ESC_KEY) this.requestCloseModal(event); // trap focus on tab key press\n\n      if (event.keyCode === TAB_KEY) trapFocus.forModal(event, this.getPluginState().activeOverlayType, this.el);\n    };\n\n    this.handleClickOutside = () => {\n      if (this.opts.closeModalOnClickOutside) this.requestCloseModal();\n    };\n\n    this.handlePaste = event => {\n      // Let any acquirer plugin (Url/Webcam/etc.) handle pastes to the root\n      this.uppy.iteratePlugins(plugin => {\n        if (plugin.type === 'acquirer') {\n          // Every Plugin with .type acquirer can define handleRootPaste(event)\n          plugin.handleRootPaste == null ? void 0 : plugin.handleRootPaste(event);\n        }\n      }); // Add all dropped files\n\n      const files = toArray(event.clipboardData.files);\n\n      if (files.length > 0) {\n        this.uppy.log('[Dashboard] Files pasted');\n        this.addFiles(files);\n      }\n    };\n\n    this.handleInputChange = event => {\n      event.preventDefault();\n      const files = toArray(event.target.files);\n\n      if (files.length > 0) {\n        this.uppy.log('[Dashboard] Files selected through input');\n        this.addFiles(files);\n      }\n    };\n\n    this.handleDragOver = event => {\n      var _this$opts$onDragOver, _this$opts;\n\n      event.preventDefault();\n      event.stopPropagation(); // Check if some plugin can handle the datatransfer without files \u2014\n      // for instance, the Url plugin can import a url\n\n      const canSomePluginHandleRootDrop = () => {\n        let somePluginCanHandleRootDrop = true;\n        this.uppy.iteratePlugins(plugin => {\n          if (plugin.canHandleRootDrop != null && plugin.canHandleRootDrop(event)) {\n            somePluginCanHandleRootDrop = true;\n          }\n        });\n        return somePluginCanHandleRootDrop;\n      }; // Check if the \"type\" of the datatransfer object includes files\n\n\n      const doesEventHaveFiles = () => {\n        const {\n          types\n        } = event.dataTransfer;\n        return types.some(type => type === 'Files');\n      }; // Deny drop, if no plugins can handle datatransfer, there are no files,\n      // or when opts.disabled is set, or new uploads are not allowed\n\n\n      const somePluginCanHandleRootDrop = canSomePluginHandleRootDrop(event);\n      const hasFiles = doesEventHaveFiles(event);\n\n      if (!somePluginCanHandleRootDrop && !hasFiles || this.opts.disabled // opts.disableLocalFiles should only be taken into account if no plugins\n      // can handle the datatransfer\n      || this.opts.disableLocalFiles && (hasFiles || !somePluginCanHandleRootDrop) || !this.uppy.getState().allowNewUpload) {\n        event.dataTransfer.dropEffect = 'none'; // eslint-disable-line no-param-reassign\n\n        clearTimeout(this.removeDragOverClassTimeout);\n        return;\n      } // Add a small (+) icon on drop\n      // (and prevent browsers from interpreting this as files being _moved_ into the\n      // browser, https://github.com/transloadit/uppy/issues/1978).\n\n\n      event.dataTransfer.dropEffect = 'copy'; // eslint-disable-line no-param-reassign\n\n      clearTimeout(this.removeDragOverClassTimeout);\n      this.setPluginState({\n        isDraggingOver: true\n      });\n      (_this$opts$onDragOver = (_this$opts = this.opts).onDragOver) == null ? void 0 : _this$opts$onDragOver.call(_this$opts, event);\n    };\n\n    this.handleDragLeave = event => {\n      var _this$opts$onDragLeav, _this$opts2;\n\n      event.preventDefault();\n      event.stopPropagation();\n      clearTimeout(this.removeDragOverClassTimeout); // Timeout against flickering, this solution is taken from drag-drop library.\n      // Solution with 'pointer-events: none' didn't work across browsers.\n\n      this.removeDragOverClassTimeout = setTimeout(() => {\n        this.setPluginState({\n          isDraggingOver: false\n        });\n      }, 50);\n      (_this$opts$onDragLeav = (_this$opts2 = this.opts).onDragLeave) == null ? void 0 : _this$opts$onDragLeav.call(_this$opts2, event);\n    };\n\n    this.handleDrop = async event => {\n      var _this$opts$onDrop, _this$opts3;\n\n      event.preventDefault();\n      event.stopPropagation();\n      clearTimeout(this.removeDragOverClassTimeout);\n      this.setPluginState({\n        isDraggingOver: false\n      }); // Let any acquirer plugin (Url/Webcam/etc.) handle drops to the root\n\n      this.uppy.iteratePlugins(plugin => {\n        if (plugin.type === 'acquirer') {\n          // Every Plugin with .type acquirer can define handleRootDrop(event)\n          plugin.handleRootDrop == null ? void 0 : plugin.handleRootDrop(event);\n        }\n      }); // Add all dropped files\n\n      let executedDropErrorOnce = false;\n\n      const logDropError = error => {\n        this.uppy.log(error, 'error'); // In practice all drop errors are most likely the same,\n        // so let's just show one to avoid overwhelming the user\n\n        if (!executedDropErrorOnce) {\n          this.uppy.info(error.message, 'error');\n          executedDropErrorOnce = true;\n        }\n      }; // Add all dropped files\n\n\n      const files = await getDroppedFiles(event.dataTransfer, {\n        logDropError\n      });\n\n      if (files.length > 0) {\n        this.uppy.log('[Dashboard] Files dropped');\n        this.addFiles(files);\n      }\n\n      (_this$opts$onDrop = (_this$opts3 = this.opts).onDrop) == null ? void 0 : _this$opts$onDrop.call(_this$opts3, event);\n    };\n\n    this.handleRequestThumbnail = file => {\n      if (!this.opts.waitForThumbnailsBeforeUpload) {\n        this.uppy.emit('thumbnail:request', file);\n      }\n    };\n\n    this.handleCancelThumbnail = file => {\n      if (!this.opts.waitForThumbnailsBeforeUpload) {\n        this.uppy.emit('thumbnail:cancel', file);\n      }\n    };\n\n    this.handleKeyDownInInline = event => {\n      // Trap focus on tab key press.\n      if (event.keyCode === TAB_KEY) trapFocus.forInline(event, this.getPluginState().activeOverlayType, this.el);\n    };\n\n    this.handlePasteOnBody = event => {\n      const isFocusInOverlay = this.el.contains(document.activeElement);\n\n      if (isFocusInOverlay) {\n        this.handlePaste(event);\n      }\n    };\n\n    this.handleComplete = _ref => {\n      let {\n        failed\n      } = _ref;\n\n      if (this.opts.closeAfterFinish && failed.length === 0) {\n        // All uploads are done\n        this.requestCloseModal();\n      }\n    };\n\n    this.handleCancelRestore = () => {\n      this.uppy.emit('restore-canceled');\n    };\n\n    Object.defineProperty(this, _openFileEditorWhenFilesAdded, {\n      writable: true,\n      value: files => {\n        const firstFile = files[0];\n\n        if (this.canEditFile(firstFile)) {\n          this.openFileEditor(firstFile);\n        }\n      }\n    });\n\n    this.initEvents = () => {\n      // Modal open button\n      if (this.opts.trigger && !this.opts.inline) {\n        const showModalTrigger = findAllDOMElements(this.opts.trigger);\n\n        if (showModalTrigger) {\n          showModalTrigger.forEach(trigger => trigger.addEventListener('click', this.openModal));\n        } else {\n          this.uppy.log('Dashboard modal trigger not found. Make sure `trigger` is set in Dashboard options, unless you are planning to call `dashboard.openModal()` method yourself', 'warning');\n        }\n      }\n\n      this.startListeningToResize();\n      document.addEventListener('paste', this.handlePasteOnBody);\n      this.uppy.on('plugin-remove', this.removeTarget);\n      this.uppy.on('file-added', this.hideAllPanels);\n      this.uppy.on('dashboard:modal-closed', this.hideAllPanels);\n      this.uppy.on('file-editor:complete', this.hideAllPanels);\n      this.uppy.on('complete', this.handleComplete); // ___Why fire on capture?\n      //    Because this.ifFocusedOnUppyRecently needs to change before onUpdate() fires.\n\n      document.addEventListener('focus', this.recordIfFocusedOnUppyRecently, true);\n      document.addEventListener('click', this.recordIfFocusedOnUppyRecently, true);\n\n      if (this.opts.inline) {\n        this.el.addEventListener('keydown', this.handleKeyDownInInline);\n      }\n\n      if (this.opts.autoOpenFileEditor) {\n        this.uppy.on('files-added', _classPrivateFieldLooseBase(this, _openFileEditorWhenFilesAdded)[_openFileEditorWhenFilesAdded]);\n      }\n    };\n\n    this.removeEvents = () => {\n      const showModalTrigger = findAllDOMElements(this.opts.trigger);\n\n      if (!this.opts.inline && showModalTrigger) {\n        showModalTrigger.forEach(trigger => trigger.removeEventListener('click', this.openModal));\n      }\n\n      this.stopListeningToResize();\n      document.removeEventListener('paste', this.handlePasteOnBody);\n      window.removeEventListener('popstate', this.handlePopState, false);\n      this.uppy.off('plugin-remove', this.removeTarget);\n      this.uppy.off('file-added', this.hideAllPanels);\n      this.uppy.off('dashboard:modal-closed', this.hideAllPanels);\n      this.uppy.off('file-editor:complete', this.hideAllPanels);\n      this.uppy.off('complete', this.handleComplete);\n      document.removeEventListener('focus', this.recordIfFocusedOnUppyRecently);\n      document.removeEventListener('click', this.recordIfFocusedOnUppyRecently);\n\n      if (this.opts.inline) {\n        this.el.removeEventListener('keydown', this.handleKeyDownInInline);\n      }\n\n      if (this.opts.autoOpenFileEditor) {\n        this.uppy.off('files-added', _classPrivateFieldLooseBase(this, _openFileEditorWhenFilesAdded)[_openFileEditorWhenFilesAdded]);\n      }\n    };\n\n    this.superFocusOnEachUpdate = () => {\n      const isFocusInUppy = this.el.contains(document.activeElement); // When focus is lost on the page (== focus is on body for most browsers, or focus is null for IE11)\n\n      const isFocusNowhere = document.activeElement === document.body || document.activeElement === null;\n      const isInformerHidden = this.uppy.getState().info.length === 0;\n      const isModal = !this.opts.inline;\n\n      if ( // If update is connected to showing the Informer - let the screen reader calmly read it.\n      isInformerHidden && ( // If we are in a modal - always superfocus without concern for other elements\n      // on the page (user is unlikely to want to interact with the rest of the page)\n      isModal // If we are already inside of Uppy, or\n      || isFocusInUppy // If we are not focused on anything BUT we have already, at least once, focused on uppy\n      //   1. We focus when isFocusNowhere, because when the element we were focused\n      //      on disappears (e.g. an overlay), - focus gets lost. If user is typing\n      //      something somewhere else on the page, - focus won't be 'nowhere'.\n      //   2. We only focus when focus is nowhere AND this.ifFocusedOnUppyRecently,\n      //      to avoid focus jumps if we do something else on the page.\n      //   [Practical check] Without '&& this.ifFocusedOnUppyRecently', in Safari, in inline mode,\n      //                     when file is uploading, - navigate via tab to the checkbox,\n      //                     try to press space multiple times. Focus will jump to Uppy.\n      || isFocusNowhere && this.ifFocusedOnUppyRecently)) {\n        this.superFocus(this.el, this.getPluginState().activeOverlayType);\n      } else {\n        this.superFocus.cancel();\n      }\n    };\n\n    this.afterUpdate = () => {\n      if (this.opts.disabled && !this.dashboardIsDisabled) {\n        this.disableAllFocusableElements(true);\n        return;\n      }\n\n      if (!this.opts.disabled && this.dashboardIsDisabled) {\n        this.disableAllFocusableElements(false);\n      }\n\n      this.superFocusOnEachUpdate();\n    };\n\n    this.saveFileCard = (meta, fileID) => {\n      this.uppy.setFileMeta(fileID, meta);\n      this.toggleFileCard(false, fileID);\n    };\n\n    Object.defineProperty(this, _attachRenderFunctionToTarget, {\n      writable: true,\n      value: target => {\n        const plugin = this.uppy.getPlugin(target.id);\n        return { ...target,\n          icon: plugin.icon || this.opts.defaultPickerIcon,\n          render: plugin.render\n        };\n      }\n    });\n    Object.defineProperty(this, _isTargetSupported, {\n      writable: true,\n      value: target => {\n        const plugin = this.uppy.getPlugin(target.id); // If the plugin does not provide a `supported` check, assume the plugin works everywhere.\n\n        if (typeof plugin.isSupported !== 'function') {\n          return true;\n        }\n\n        return plugin.isSupported();\n      }\n    });\n    Object.defineProperty(this, _getAcquirers, {\n      writable: true,\n      value: memoize(targets => {\n        return targets.filter(target => target.type === 'acquirer' && _classPrivateFieldLooseBase(this, _isTargetSupported)[_isTargetSupported](target)).map(_classPrivateFieldLooseBase(this, _attachRenderFunctionToTarget)[_attachRenderFunctionToTarget]);\n      })\n    });\n    Object.defineProperty(this, _getProgressIndicators, {\n      writable: true,\n      value: memoize(targets => {\n        return targets.filter(target => target.type === 'progressindicator').map(_classPrivateFieldLooseBase(this, _attachRenderFunctionToTarget)[_attachRenderFunctionToTarget]);\n      })\n    });\n    Object.defineProperty(this, _getEditors, {\n      writable: true,\n      value: memoize(targets => {\n        return targets.filter(target => target.type === 'editor').map(_classPrivateFieldLooseBase(this, _attachRenderFunctionToTarget)[_attachRenderFunctionToTarget]);\n      })\n    });\n\n    this.render = state => {\n      const pluginState = this.getPluginState();\n      const {\n        files,\n        capabilities,\n        allowNewUpload\n      } = state;\n      const {\n        newFiles,\n        uploadStartedFiles,\n        completeFiles,\n        erroredFiles,\n        inProgressFiles,\n        inProgressNotPausedFiles,\n        processingFiles,\n        isUploadStarted,\n        isAllComplete,\n        isAllErrored,\n        isAllPaused\n      } = this.uppy.getObjectOfFilesPerState();\n\n      const acquirers = _classPrivateFieldLooseBase(this, _getAcquirers)[_getAcquirers](pluginState.targets);\n\n      const progressindicators = _classPrivateFieldLooseBase(this, _getProgressIndicators)[_getProgressIndicators](pluginState.targets);\n\n      const editors = _classPrivateFieldLooseBase(this, _getEditors)[_getEditors](pluginState.targets);\n\n      let theme;\n\n      if (this.opts.theme === 'auto') {\n        theme = capabilities.darkMode ? 'dark' : 'light';\n      } else {\n        theme = this.opts.theme;\n      }\n\n      if (['files', 'folders', 'both'].indexOf(this.opts.fileManagerSelectionType) < 0) {\n        this.opts.fileManagerSelectionType = 'files'; // eslint-disable-next-line no-console\n\n        console.warn(`Unsupported option for \"fileManagerSelectionType\". Using default of \"${this.opts.fileManagerSelectionType}\".`);\n      }\n\n      return DashboardUI({\n        state,\n        isHidden: pluginState.isHidden,\n        files,\n        newFiles,\n        uploadStartedFiles,\n        completeFiles,\n        erroredFiles,\n        inProgressFiles,\n        inProgressNotPausedFiles,\n        processingFiles,\n        isUploadStarted,\n        isAllComplete,\n        isAllErrored,\n        isAllPaused,\n        totalFileCount: Object.keys(files).length,\n        totalProgress: state.totalProgress,\n        allowNewUpload,\n        acquirers,\n        theme,\n        disabled: this.opts.disabled,\n        disableLocalFiles: this.opts.disableLocalFiles,\n        direction: this.opts.direction,\n        activePickerPanel: pluginState.activePickerPanel,\n        showFileEditor: pluginState.showFileEditor,\n        saveFileEditor: this.saveFileEditor,\n        disableAllFocusableElements: this.disableAllFocusableElements,\n        animateOpenClose: this.opts.animateOpenClose,\n        isClosing: pluginState.isClosing,\n        progressindicators,\n        editors,\n        autoProceed: this.uppy.opts.autoProceed,\n        id: this.id,\n        closeModal: this.requestCloseModal,\n        handleClickOutside: this.handleClickOutside,\n        handleInputChange: this.handleInputChange,\n        handlePaste: this.handlePaste,\n        inline: this.opts.inline,\n        showPanel: this.showPanel,\n        hideAllPanels: this.hideAllPanels,\n        i18n: this.i18n,\n        i18nArray: this.i18nArray,\n        uppy: this.uppy,\n        note: this.opts.note,\n        recoveredState: state.recoveredState,\n        metaFields: pluginState.metaFields,\n        resumableUploads: capabilities.resumableUploads || false,\n        individualCancellation: capabilities.individualCancellation,\n        isMobileDevice: capabilities.isMobileDevice,\n        fileCardFor: pluginState.fileCardFor,\n        toggleFileCard: this.toggleFileCard,\n        toggleAddFilesPanel: this.toggleAddFilesPanel,\n        showAddFilesPanel: pluginState.showAddFilesPanel,\n        saveFileCard: this.saveFileCard,\n        openFileEditor: this.openFileEditor,\n        canEditFile: this.canEditFile,\n        width: this.opts.width,\n        height: this.opts.height,\n        showLinkToFileUploadResult: this.opts.showLinkToFileUploadResult,\n        fileManagerSelectionType: this.opts.fileManagerSelectionType,\n        proudlyDisplayPoweredByUppy: this.opts.proudlyDisplayPoweredByUppy,\n        hideCancelButton: this.opts.hideCancelButton,\n        hideRetryButton: this.opts.hideRetryButton,\n        hidePauseResumeButton: this.opts.hidePauseResumeButton,\n        showRemoveButtonAfterComplete: this.opts.showRemoveButtonAfterComplete,\n        containerWidth: pluginState.containerWidth,\n        containerHeight: pluginState.containerHeight,\n        areInsidesReadyToBeVisible: pluginState.areInsidesReadyToBeVisible,\n        isTargetDOMEl: this.isTargetDOMEl,\n        parentElement: this.el,\n        allowedFileTypes: this.uppy.opts.restrictions.allowedFileTypes,\n        maxNumberOfFiles: this.uppy.opts.restrictions.maxNumberOfFiles,\n        requiredMetaFields: this.uppy.opts.restrictions.requiredMetaFields,\n        showSelectedFiles: this.opts.showSelectedFiles,\n        handleCancelRestore: this.handleCancelRestore,\n        handleRequestThumbnail: this.handleRequestThumbnail,\n        handleCancelThumbnail: this.handleCancelThumbnail,\n        // drag props\n        isDraggingOver: pluginState.isDraggingOver,\n        handleDragOver: this.handleDragOver,\n        handleDragLeave: this.handleDragLeave,\n        handleDrop: this.handleDrop\n      });\n    };\n\n    this.discoverProviderPlugins = () => {\n      this.uppy.iteratePlugins(plugin => {\n        if (plugin && !plugin.target && plugin.opts && plugin.opts.target === this.constructor) {\n          this.addTarget(plugin);\n        }\n      });\n    };\n\n    this.install = () => {\n      // Set default state for Dashboard\n      this.setPluginState({\n        isHidden: true,\n        fileCardFor: null,\n        activeOverlayType: null,\n        showAddFilesPanel: false,\n        activePickerPanel: false,\n        showFileEditor: false,\n        metaFields: this.opts.metaFields,\n        targets: [],\n        // We'll make them visible once .containerWidth is determined\n        areInsidesReadyToBeVisible: false,\n        isDraggingOver: false\n      });\n      const {\n        inline,\n        closeAfterFinish\n      } = this.opts;\n\n      if (inline && closeAfterFinish) {\n        throw new Error('[Dashboard] `closeAfterFinish: true` cannot be used on an inline Dashboard, because an inline Dashboard cannot be closed at all. Either set `inline: false`, or disable the `closeAfterFinish` option.');\n      }\n\n      const {\n        allowMultipleUploads,\n        allowMultipleUploadBatches\n      } = this.uppy.opts;\n\n      if ((allowMultipleUploads || allowMultipleUploadBatches) && closeAfterFinish) {\n        this.uppy.log('[Dashboard] When using `closeAfterFinish`, we recommended setting the `allowMultipleUploadBatches` option to `false` in the Uppy constructor. See https://uppy.io/docs/uppy/#allowMultipleUploads-true', 'warning');\n      }\n\n      const {\n        target\n      } = this.opts;\n\n      if (target) {\n        this.mount(target, this);\n      }\n\n      const plugins = this.opts.plugins || [];\n      plugins.forEach(pluginID => {\n        const plugin = this.uppy.getPlugin(pluginID);\n\n        if (plugin) {\n          plugin.mount(this, plugin);\n        }\n      });\n\n      if (!this.opts.disableStatusBar) {\n        this.uppy.use(StatusBar, {\n          id: `${this.id}:StatusBar`,\n          target: this,\n          hideUploadButton: this.opts.hideUploadButton,\n          hideRetryButton: this.opts.hideRetryButton,\n          hidePauseResumeButton: this.opts.hidePauseResumeButton,\n          hideCancelButton: this.opts.hideCancelButton,\n          showProgressDetails: this.opts.showProgressDetails,\n          hideAfterFinish: this.opts.hideProgressAfterFinish,\n          locale: this.opts.locale,\n          doneButtonHandler: this.opts.doneButtonHandler\n        });\n      }\n\n      if (!this.opts.disableInformer) {\n        this.uppy.use(Informer, {\n          id: `${this.id}:Informer`,\n          target: this\n        });\n      }\n\n      if (!this.opts.disableThumbnailGenerator) {\n        this.uppy.use(ThumbnailGenerator, {\n          id: `${this.id}:ThumbnailGenerator`,\n          thumbnailWidth: this.opts.thumbnailWidth,\n          thumbnailHeight: this.opts.thumbnailHeight,\n          thumbnailType: this.opts.thumbnailType,\n          waitForThumbnailsBeforeUpload: this.opts.waitForThumbnailsBeforeUpload,\n          // If we don't block on thumbnails, we can lazily generate them\n          lazy: !this.opts.waitForThumbnailsBeforeUpload\n        });\n      } // Dark Mode / theme\n\n\n      this.darkModeMediaQuery = typeof window !== 'undefined' && window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;\n      const isDarkModeOnFromTheStart = this.darkModeMediaQuery ? this.darkModeMediaQuery.matches : false;\n      this.uppy.log(`[Dashboard] Dark mode is ${isDarkModeOnFromTheStart ? 'on' : 'off'}`);\n      this.setDarkModeCapability(isDarkModeOnFromTheStart);\n\n      if (this.opts.theme === 'auto') {\n        this.darkModeMediaQuery.addListener(this.handleSystemDarkModeChange);\n      }\n\n      this.discoverProviderPlugins();\n      this.initEvents();\n    };\n\n    this.uninstall = () => {\n      if (!this.opts.disableInformer) {\n        const informer = this.uppy.getPlugin(`${this.id}:Informer`); // Checking if this plugin exists, in case it was removed by uppy-core\n        // before the Dashboard was.\n\n        if (informer) this.uppy.removePlugin(informer);\n      }\n\n      if (!this.opts.disableStatusBar) {\n        const statusBar = this.uppy.getPlugin(`${this.id}:StatusBar`);\n        if (statusBar) this.uppy.removePlugin(statusBar);\n      }\n\n      if (!this.opts.disableThumbnailGenerator) {\n        const thumbnail = this.uppy.getPlugin(`${this.id}:ThumbnailGenerator`);\n        if (thumbnail) this.uppy.removePlugin(thumbnail);\n      }\n\n      const plugins = this.opts.plugins || [];\n      plugins.forEach(pluginID => {\n        const plugin = this.uppy.getPlugin(pluginID);\n        if (plugin) plugin.unmount();\n      });\n\n      if (this.opts.theme === 'auto') {\n        this.darkModeMediaQuery.removeListener(this.handleSystemDarkModeChange);\n      }\n\n      this.unmount();\n      this.removeEvents();\n    };\n\n    this.id = this.opts.id || 'Dashboard';\n    this.title = 'Dashboard';\n    this.type = 'orchestrator';\n    this.modalName = `uppy-Dashboard-${(0, _nonSecure.nanoid)()}`;\n    this.defaultLocale = locale; // set default options\n\n    const defaultOptions = {\n      target: 'body',\n      metaFields: [],\n      trigger: null,\n      inline: false,\n      width: 750,\n      height: 550,\n      thumbnailWidth: 280,\n      thumbnailType: 'image/jpeg',\n      waitForThumbnailsBeforeUpload: false,\n      defaultPickerIcon,\n      showLinkToFileUploadResult: false,\n      showProgressDetails: false,\n      hideUploadButton: false,\n      hideCancelButton: false,\n      hideRetryButton: false,\n      hidePauseResumeButton: false,\n      hideProgressAfterFinish: false,\n      doneButtonHandler: () => {\n        this.uppy.reset();\n        this.requestCloseModal();\n      },\n      note: null,\n      closeModalOnClickOutside: false,\n      closeAfterFinish: false,\n      disableStatusBar: false,\n      disableInformer: false,\n      disableThumbnailGenerator: false,\n      disablePageScrollWhenModalOpen: true,\n      animateOpenClose: true,\n      fileManagerSelectionType: 'files',\n      proudlyDisplayPoweredByUppy: true,\n      onRequestCloseModal: () => this.closeModal(),\n      showSelectedFiles: true,\n      showRemoveButtonAfterComplete: false,\n      browserBackButtonClose: false,\n      theme: 'light',\n      autoOpenFileEditor: false,\n      disabled: false,\n      disableLocalFiles: false\n    }; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ..._opts\n    };\n    this.i18nInit();\n    this.superFocus = createSuperFocus();\n    this.ifFocusedOnUppyRecently = false; // Timeouts\n\n    this.makeDashboardInsidesVisibleAnywayTimeout = null;\n    this.removeDragOverClassTimeout = null;\n  }\n\n}\n\nDashboard.VERSION = packageJson.version;\nmodule.exports = Dashboard;", "\"use strict\";\n\nmodule.exports = require(\"./Dashboard.js\");", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // Text to show on the droppable area.\n    // `%{browse}` is replaced with a link that opens the system file selection dialog.\n    dropHereOr: 'Drop here or %{browse}',\n    // Used as the label for the link that opens the system file selection dialog.\n    browse: 'browse'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _preact = require(\"preact\");\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n\nconst isDragDropSupported = require(\"@uppy/utils/lib/isDragDropSupported\");\n\nconst getDroppedFiles = require(\"@uppy/utils/lib/getDroppedFiles\");\n\nconst packageJson = {\n  \"version\": \"2.1.2\"\n};\n\nconst locale = require(\"./locale.js\");\n/**\n * Drag & Drop plugin\n *\n */\n\n\nclass DragDrop extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n\n    this.handleDrop = async event => {\n      var _this$opts$onDrop, _this$opts;\n\n      event.preventDefault();\n      event.stopPropagation();\n      clearTimeout(this.removeDragOverClassTimeout); // Remove dragover class\n\n      this.setPluginState({\n        isDraggingOver: false\n      });\n\n      const logDropError = error => {\n        this.uppy.log(error, 'error');\n      }; // Add all dropped files\n\n\n      const files = await getDroppedFiles(event.dataTransfer, {\n        logDropError\n      });\n\n      if (files.length > 0) {\n        this.uppy.log('[DragDrop] Files dropped');\n        this.addFiles(files);\n      }\n\n      (_this$opts$onDrop = (_this$opts = this.opts).onDrop) == null ? void 0 : _this$opts$onDrop.call(_this$opts, event);\n    };\n\n    this.type = 'acquirer';\n    this.id = this.opts.id || 'DragDrop';\n    this.title = 'Drag & Drop';\n    this.defaultLocale = locale; // Default options\n\n    const defaultOpts = {\n      target: null,\n      inputName: 'files[]',\n      width: '100%',\n      height: '100%',\n      note: null\n    }; // Merge default options with the ones set by user\n\n    this.opts = { ...defaultOpts,\n      ...opts\n    };\n    this.i18nInit(); // Check for browser dragDrop support\n\n    this.isDragDropSupported = isDragDropSupported();\n    this.removeDragOverClassTimeout = null; // Bind `this` to class methods\n\n    this.onInputChange = this.onInputChange.bind(this);\n    this.handleDragOver = this.handleDragOver.bind(this);\n    this.handleDragLeave = this.handleDragLeave.bind(this);\n    this.handleDrop = this.handleDrop.bind(this);\n    this.addFiles = this.addFiles.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  addFiles(files) {\n    const descriptors = files.map(file => ({\n      source: this.id,\n      name: file.name,\n      type: file.type,\n      data: file,\n      meta: {\n        // path of the file relative to the ancestor directory the user selected.\n        // e.g. 'docs/Old Prague/airbnb.pdf'\n        relativePath: file.relativePath || null\n      }\n    }));\n\n    try {\n      this.uppy.addFiles(descriptors);\n    } catch (err) {\n      this.uppy.log(err);\n    }\n  }\n\n  onInputChange(event) {\n    const files = toArray(event.target.files);\n\n    if (files.length > 0) {\n      this.uppy.log('[DragDrop] Files selected through input');\n      this.addFiles(files);\n    } // We clear the input after a file is selected, because otherwise\n    // change event is not fired in Chrome and Safari when a file\n    // with the same name is selected.\n    // ___Why not use value=\"\" on <input/> instead?\n    //    Because if we use that method of clearing the input,\n    //    Chrome will not trigger change if we drop the same file twice (Issue #768).\n    // eslint-disable-next-line no-param-reassign\n\n\n    event.target.value = null;\n  }\n\n  handleDragOver(event) {\n    var _this$opts$onDragOver, _this$opts2;\n\n    event.preventDefault();\n    event.stopPropagation(); // Check if the \"type\" of the datatransfer object includes files. If not, deny drop.\n\n    const {\n      types\n    } = event.dataTransfer;\n    const hasFiles = types.some(type => type === 'Files');\n    const {\n      allowNewUpload\n    } = this.uppy.getState();\n\n    if (!hasFiles || !allowNewUpload) {\n      // eslint-disable-next-line no-param-reassign\n      event.dataTransfer.dropEffect = 'none';\n      clearTimeout(this.removeDragOverClassTimeout);\n      return;\n    } // Add a small (+) icon on drop\n    // (and prevent browsers from interpreting this as files being _moved_ into the browser\n    // https://github.com/transloadit/uppy/issues/1978)\n    //\n    // eslint-disable-next-line no-param-reassign\n\n\n    event.dataTransfer.dropEffect = 'copy';\n    clearTimeout(this.removeDragOverClassTimeout);\n    this.setPluginState({\n      isDraggingOver: true\n    });\n    (_this$opts$onDragOver = (_this$opts2 = this.opts).onDragOver) == null ? void 0 : _this$opts$onDragOver.call(_this$opts2, event);\n  }\n\n  handleDragLeave(event) {\n    var _this$opts$onDragLeav, _this$opts3;\n\n    event.preventDefault();\n    event.stopPropagation();\n    clearTimeout(this.removeDragOverClassTimeout); // Timeout against flickering, this solution is taken from drag-drop library.\n    // Solution with 'pointer-events: none' didn't work across browsers.\n\n    this.removeDragOverClassTimeout = setTimeout(() => {\n      this.setPluginState({\n        isDraggingOver: false\n      });\n    }, 50);\n    (_this$opts$onDragLeav = (_this$opts3 = this.opts).onDragLeave) == null ? void 0 : _this$opts$onDragLeav.call(_this$opts3, event);\n  }\n\n  renderHiddenFileInput() {\n    const {\n      restrictions\n    } = this.uppy.opts;\n    return (0, _preact.h)(\"input\", {\n      className: \"uppy-DragDrop-input\",\n      type: \"file\",\n      hidden: true,\n      ref: ref => {\n        this.fileInputRef = ref;\n      },\n      name: this.opts.inputName,\n      multiple: restrictions.maxNumberOfFiles !== 1,\n      accept: restrictions.allowedFileTypes,\n      onChange: this.onInputChange\n    });\n  }\n\n  static renderArrowSvg() {\n    return (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon uppy-DragDrop-arrow\",\n      width: \"16\",\n      height: \"16\",\n      viewBox: \"0 0 16 16\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M11 10V0H5v10H2l6 6 6-6h-3zm0 0\",\n      fillRule: \"evenodd\"\n    }));\n  }\n\n  renderLabel() {\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-DragDrop-label\"\n    }, this.i18nArray('dropHereOr', {\n      browse: (0, _preact.h)(\"span\", {\n        className: \"uppy-DragDrop-browse\"\n      }, this.i18n('browse'))\n    }));\n  }\n\n  renderNote() {\n    return (0, _preact.h)(\"span\", {\n      className: \"uppy-DragDrop-note\"\n    }, this.opts.note);\n  }\n\n  render() {\n    const dragDropClass = `uppy-u-reset\n      uppy-DragDrop-container\n      ${this.isDragDropSupported ? 'uppy-DragDrop--isDragDropSupported' : ''}\n      ${this.getPluginState().isDraggingOver ? 'uppy-DragDrop--isDraggingOver' : ''}\n    `;\n    const dragDropStyle = {\n      width: this.opts.width,\n      height: this.opts.height\n    };\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: dragDropClass,\n      style: dragDropStyle,\n      onClick: () => this.fileInputRef.click(),\n      onDragOver: this.handleDragOver,\n      onDragLeave: this.handleDragLeave,\n      onDrop: this.handleDrop\n    }, this.renderHiddenFileInput(), (0, _preact.h)(\"div\", {\n      className: \"uppy-DragDrop-inner\"\n    }, DragDrop.renderArrowSvg(), this.renderLabel(), this.renderNote()));\n  }\n\n  install() {\n    const {\n      target\n    } = this.opts;\n    this.setPluginState({\n      isDraggingOver: false\n    });\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.unmount();\n  }\n\n}\n\nDragDrop.VERSION = packageJson.version;\nmodule.exports = DragDrop;", "\"use strict\";\n\nmodule.exports = require(\"./DragDrop.js\");", "\"use strict\";\n\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst getDroppedFiles = require(\"@uppy/utils/lib/getDroppedFiles\");\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n\nconst packageJson = {\n  \"version\": \"1.1.4\"\n};\n\nfunction isFileTransfer(event) {\n  var _event$dataTransfer$t, _event$dataTransfer$t2;\n\n  return (_event$dataTransfer$t = (_event$dataTransfer$t2 = event.dataTransfer.types) == null ? void 0 : _event$dataTransfer$t2.some(type => type === 'Files')) != null ? _event$dataTransfer$t : false;\n}\n/**\n * Drop Target plugin\n *\n */\n\n\nclass DropTarget extends BasePlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n\n    this.addFiles = files => {\n      const descriptors = files.map(file => ({\n        source: this.id,\n        name: file.name,\n        type: file.type,\n        data: file,\n        meta: {\n          // path of the file relative to the ancestor directory the user selected.\n          // e.g. 'docs/Old Prague/airbnb.pdf'\n          relativePath: file.relativePath || null\n        }\n      }));\n\n      try {\n        this.uppy.addFiles(descriptors);\n      } catch (err) {\n        this.uppy.log(err);\n      }\n    };\n\n    this.isFileTransfer = isFileTransfer;\n\n    this.handleDrop = async event => {\n      var _this$opts$onDrop, _this$opts;\n\n      if (!this.isFileTransfer(event)) {\n        return;\n      }\n\n      event.preventDefault();\n      event.stopPropagation();\n      clearTimeout(this.removeDragOverClassTimeout); // Remove dragover class\n\n      event.currentTarget.classList.remove('uppy-is-drag-over');\n      this.setPluginState({\n        isDraggingOver: false\n      }); // Let any acquirer plugin (Url/Webcam/etc.) handle drops to the root\n\n      this.uppy.iteratePlugins(plugin => {\n        if (plugin.type === 'acquirer') {\n          // Every Plugin with .type acquirer can define handleRootDrop(event)\n          plugin.handleRootDrop == null ? void 0 : plugin.handleRootDrop(event);\n        }\n      }); // Add all dropped files, handle errors\n\n      let executedDropErrorOnce = false;\n\n      const logDropError = error => {\n        this.uppy.log(error, 'error'); // In practice all drop errors are most likely the same,\n        // so let's just show one to avoid overwhelming the user\n\n        if (!executedDropErrorOnce) {\n          this.uppy.info(error.message, 'error');\n          executedDropErrorOnce = true;\n        }\n      };\n\n      const files = await getDroppedFiles(event.dataTransfer, {\n        logDropError\n      });\n\n      if (files.length > 0) {\n        this.uppy.log('[DropTarget] Files were dropped');\n        this.addFiles(files);\n      }\n\n      (_this$opts$onDrop = (_this$opts = this.opts).onDrop) == null ? void 0 : _this$opts$onDrop.call(_this$opts, event);\n    };\n\n    this.handleDragOver = event => {\n      var _this$opts$onDragOver, _this$opts2;\n\n      if (!this.isFileTransfer(event)) {\n        return;\n      }\n\n      event.preventDefault();\n      event.stopPropagation(); // Add a small (+) icon on drop\n      // (and prevent browsers from interpreting this as files being _moved_ into the browser,\n      // https://github.com/transloadit/uppy/issues/1978)\n\n      event.dataTransfer.dropEffect = 'copy'; // eslint-disable-line no-param-reassign\n\n      clearTimeout(this.removeDragOverClassTimeout);\n      event.currentTarget.classList.add('uppy-is-drag-over');\n      this.setPluginState({\n        isDraggingOver: true\n      });\n      (_this$opts$onDragOver = (_this$opts2 = this.opts).onDragOver) == null ? void 0 : _this$opts$onDragOver.call(_this$opts2, event);\n    };\n\n    this.handleDragLeave = event => {\n      var _this$opts$onDragLeav, _this$opts3;\n\n      if (!this.isFileTransfer(event)) {\n        return;\n      }\n\n      event.preventDefault();\n      event.stopPropagation();\n      const {\n        currentTarget\n      } = event;\n      clearTimeout(this.removeDragOverClassTimeout); // Timeout against flickering, this solution is taken from drag-drop library.\n      // Solution with 'pointer-events: none' didn't work across browsers.\n\n      this.removeDragOverClassTimeout = setTimeout(() => {\n        currentTarget.classList.remove('uppy-is-drag-over');\n        this.setPluginState({\n          isDraggingOver: false\n        });\n      }, 50);\n      (_this$opts$onDragLeav = (_this$opts3 = this.opts).onDragLeave) == null ? void 0 : _this$opts$onDragLeav.call(_this$opts3, event);\n    };\n\n    this.addListeners = () => {\n      const {\n        target\n      } = this.opts;\n\n      if (target instanceof Element) {\n        this.nodes = [target];\n      } else if (typeof target === 'string') {\n        this.nodes = toArray(document.querySelectorAll(target));\n      }\n\n      if (!this.nodes && !this.nodes.length > 0) {\n        throw new Error(`\"${target}\" does not match any HTML elements`);\n      }\n\n      this.nodes.forEach(node => {\n        node.addEventListener('dragover', this.handleDragOver, false);\n        node.addEventListener('dragleave', this.handleDragLeave, false);\n        node.addEventListener('drop', this.handleDrop, false);\n      });\n    };\n\n    this.removeListeners = () => {\n      if (this.nodes) {\n        this.nodes.forEach(node => {\n          node.removeEventListener('dragover', this.handleDragOver, false);\n          node.removeEventListener('dragleave', this.handleDragLeave, false);\n          node.removeEventListener('drop', this.handleDrop, false);\n        });\n      }\n    };\n\n    this.type = 'acquirer';\n    this.id = this.opts.id || 'DropTarget';\n    this.title = 'Drop Target'; // Default options\n\n    const defaultOpts = {\n      target: null\n    }; // Merge default options with the ones set by user\n\n    this.opts = { ...defaultOpts,\n      ...opts\n    };\n    this.removeDragOverClassTimeout = null;\n  }\n\n  install() {\n    this.setPluginState({\n      isDraggingOver: false\n    });\n    this.addListeners();\n  }\n\n  uninstall() {\n    this.removeListeners();\n  }\n\n}\n\nDropTarget.VERSION = packageJson.version;\nmodule.exports = DropTarget;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // The same key is used for the same purpose by @uppy/robodog's `form()` API, but our\n    // locale pack scripts can't access it in Robodog. If it is updated here, it should\n    // also be updated there!\n    chooseFiles: 'Choose files'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _preact = require(\"preact\");\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n\nconst packageJson = {\n  \"version\": \"2.1.2\"\n};\n\nconst locale = require(\"./locale.js\");\n\nclass FileInput extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'FileInput';\n    this.title = 'File Input';\n    this.type = 'acquirer';\n    this.defaultLocale = locale; // Default options\n\n    const defaultOptions = {\n      target: null,\n      pretty: true,\n      inputName: 'files[]'\n    }; // Merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.i18nInit();\n    this.render = this.render.bind(this);\n    this.handleInputChange = this.handleInputChange.bind(this);\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  addFiles(files) {\n    const descriptors = files.map(file => ({\n      source: this.id,\n      name: file.name,\n      type: file.type,\n      data: file\n    }));\n\n    try {\n      this.uppy.addFiles(descriptors);\n    } catch (err) {\n      this.uppy.log(err);\n    }\n  }\n\n  handleInputChange(event) {\n    this.uppy.log('[FileInput] Something selected through input...');\n    const files = toArray(event.target.files);\n    this.addFiles(files); // We clear the input after a file is selected, because otherwise\n    // change event is not fired in Chrome and Safari when a file\n    // with the same name is selected.\n    // ___Why not use value=\"\" on <input/> instead?\n    //    Because if we use that method of clearing the input,\n    //    Chrome will not trigger change if we drop the same file twice (Issue #768).\n\n    event.target.value = null; // eslint-disable-line no-param-reassign\n  }\n\n  handleClick() {\n    this.input.click();\n  }\n\n  render() {\n    /* http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/ */\n    const hiddenInputStyle = {\n      width: '0.1px',\n      height: '0.1px',\n      opacity: 0,\n      overflow: 'hidden',\n      position: 'absolute',\n      zIndex: -1\n    };\n    const {\n      restrictions\n    } = this.uppy.opts;\n    const accept = restrictions.allowedFileTypes ? restrictions.allowedFileTypes.join(',') : null;\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-FileInput-container\"\n    }, (0, _preact.h)(\"input\", {\n      className: \"uppy-FileInput-input\",\n      style: this.opts.pretty && hiddenInputStyle,\n      type: \"file\",\n      name: this.opts.inputName,\n      onChange: this.handleInputChange,\n      multiple: restrictions.maxNumberOfFiles !== 1,\n      accept: accept,\n      ref: input => {\n        this.input = input;\n      }\n    }), this.opts.pretty && (0, _preact.h)(\"button\", {\n      className: \"uppy-FileInput-btn\",\n      type: \"button\",\n      onClick: this.handleClick\n    }, this.i18n('chooseFiles')));\n  }\n\n  install() {\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.unmount();\n  }\n\n}\n\nFileInput.VERSION = packageJson.version;\nmodule.exports = FileInput;", "\"use strict\";\n\nmodule.exports = require(\"./FileInput.js\");", "/*!\n * Cropper.js v1.5.7\n * https://fengyuanchen.github.io/cropperjs\n *\n * Copyright 2015-present Chen Fengyuan\n * Released under the MIT license\n *\n * Date: 2020-05-23T05:23:00.081Z\n */\n\n(function (global, factory) {\n  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n  typeof define === 'function' && define.amd ? define(factory) :\n  (global = global || self, global.Cropper = factory());\n}(this, (function () { 'use strict';\n\n  function _typeof(obj) {\n    \"@babel/helpers - typeof\";\n\n    if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n      _typeof = function (obj) {\n        return typeof obj;\n      };\n    } else {\n      _typeof = function (obj) {\n        return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n      };\n    }\n\n    return _typeof(obj);\n  }\n\n  function _classCallCheck(instance, Constructor) {\n    if (!(instance instanceof Constructor)) {\n      throw new TypeError(\"Cannot call a class as a function\");\n    }\n  }\n\n  function _defineProperties(target, props) {\n    for (var i = 0; i < props.length; i++) {\n      var descriptor = props[i];\n      descriptor.enumerable = descriptor.enumerable || false;\n      descriptor.configurable = true;\n      if (\"value\" in descriptor) descriptor.writable = true;\n      Object.defineProperty(target, descriptor.key, descriptor);\n    }\n  }\n\n  function _createClass(Constructor, protoProps, staticProps) {\n    if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n    if (staticProps) _defineProperties(Constructor, staticProps);\n    return Constructor;\n  }\n\n  function _defineProperty(obj, key, value) {\n    if (key in obj) {\n      Object.defineProperty(obj, key, {\n        value: value,\n        enumerable: true,\n        configurable: true,\n        writable: true\n      });\n    } else {\n      obj[key] = value;\n    }\n\n    return obj;\n  }\n\n  function ownKeys(object, enumerableOnly) {\n    var keys = Object.keys(object);\n\n    if (Object.getOwnPropertySymbols) {\n      var symbols = Object.getOwnPropertySymbols(object);\n      if (enumerableOnly) symbols = symbols.filter(function (sym) {\n        return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n      });\n      keys.push.apply(keys, symbols);\n    }\n\n    return keys;\n  }\n\n  function _objectSpread2(target) {\n    for (var i = 1; i < arguments.length; i++) {\n      var source = arguments[i] != null ? arguments[i] : {};\n\n      if (i % 2) {\n        ownKeys(Object(source), true).forEach(function (key) {\n          _defineProperty(target, key, source[key]);\n        });\n      } else if (Object.getOwnPropertyDescriptors) {\n        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n      } else {\n        ownKeys(Object(source)).forEach(function (key) {\n          Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n        });\n      }\n    }\n\n    return target;\n  }\n\n  function _toConsumableArray(arr) {\n    return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n  }\n\n  function _arrayWithoutHoles(arr) {\n    if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n  }\n\n  function _iterableToArray(iter) {\n    if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n  }\n\n  function _unsupportedIterableToArray(o, minLen) {\n    if (!o) return;\n    if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n    var n = Object.prototype.toString.call(o).slice(8, -1);\n    if (n === \"Object\" && o.constructor) n = o.constructor.name;\n    if (n === \"Map\" || n === \"Set\") return Array.from(o);\n    if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n  }\n\n  function _arrayLikeToArray(arr, len) {\n    if (len == null || len > arr.length) len = arr.length;\n\n    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n    return arr2;\n  }\n\n  function _nonIterableSpread() {\n    throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n  }\n\n  var IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n  var WINDOW = IS_BROWSER ? window : {};\n  var IS_TOUCH_DEVICE = IS_BROWSER && WINDOW.document.documentElement ? 'ontouchstart' in WINDOW.document.documentElement : false;\n  var HAS_POINTER_EVENT = IS_BROWSER ? 'PointerEvent' in WINDOW : false;\n  var NAMESPACE = 'cropper'; // Actions\n\n  var ACTION_ALL = 'all';\n  var ACTION_CROP = 'crop';\n  var ACTION_MOVE = 'move';\n  var ACTION_ZOOM = 'zoom';\n  var ACTION_EAST = 'e';\n  var ACTION_WEST = 'w';\n  var ACTION_SOUTH = 's';\n  var ACTION_NORTH = 'n';\n  var ACTION_NORTH_EAST = 'ne';\n  var ACTION_NORTH_WEST = 'nw';\n  var ACTION_SOUTH_EAST = 'se';\n  var ACTION_SOUTH_WEST = 'sw'; // Classes\n\n  var CLASS_CROP = \"\".concat(NAMESPACE, \"-crop\");\n  var CLASS_DISABLED = \"\".concat(NAMESPACE, \"-disabled\");\n  var CLASS_HIDDEN = \"\".concat(NAMESPACE, \"-hidden\");\n  var CLASS_HIDE = \"\".concat(NAMESPACE, \"-hide\");\n  var CLASS_INVISIBLE = \"\".concat(NAMESPACE, \"-invisible\");\n  var CLASS_MODAL = \"\".concat(NAMESPACE, \"-modal\");\n  var CLASS_MOVE = \"\".concat(NAMESPACE, \"-move\"); // Data keys\n\n  var DATA_ACTION = \"\".concat(NAMESPACE, \"Action\");\n  var DATA_PREVIEW = \"\".concat(NAMESPACE, \"Preview\"); // Drag modes\n\n  var DRAG_MODE_CROP = 'crop';\n  var DRAG_MODE_MOVE = 'move';\n  var DRAG_MODE_NONE = 'none'; // Events\n\n  var EVENT_CROP = 'crop';\n  var EVENT_CROP_END = 'cropend';\n  var EVENT_CROP_MOVE = 'cropmove';\n  var EVENT_CROP_START = 'cropstart';\n  var EVENT_DBLCLICK = 'dblclick';\n  var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? 'touchstart' : 'mousedown';\n  var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? 'touchmove' : 'mousemove';\n  var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? 'touchend touchcancel' : 'mouseup';\n  var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? 'pointerdown' : EVENT_TOUCH_START;\n  var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? 'pointermove' : EVENT_TOUCH_MOVE;\n  var EVENT_POINTER_UP = HAS_POINTER_EVENT ? 'pointerup pointercancel' : EVENT_TOUCH_END;\n  var EVENT_READY = 'ready';\n  var EVENT_RESIZE = 'resize';\n  var EVENT_WHEEL = 'wheel';\n  var EVENT_ZOOM = 'zoom'; // Mime types\n\n  var MIME_TYPE_JPEG = 'image/jpeg'; // RegExps\n\n  var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/;\n  var REGEXP_DATA_URL = /^data:/;\n  var REGEXP_DATA_URL_JPEG = /^data:image\\/jpeg;base64,/;\n  var REGEXP_TAG_NAME = /^img|canvas$/i; // Misc\n\n  var DEFAULTS = {\n    // Define the view mode of the cropper\n    viewMode: 0,\n    // 0, 1, 2, 3\n    // Define the dragging mode of the cropper\n    dragMode: DRAG_MODE_CROP,\n    // 'crop', 'move' or 'none'\n    // Define the initial aspect ratio of the crop box\n    initialAspectRatio: NaN,\n    // Define the aspect ratio of the crop box\n    aspectRatio: NaN,\n    // An object with the previous cropping result data\n    data: null,\n    // A selector for adding extra containers to preview\n    preview: '',\n    // Re-render the cropper when resize the window\n    responsive: true,\n    // Restore the cropped area after resize the window\n    restore: true,\n    // Check if the current image is a cross-origin image\n    checkCrossOrigin: true,\n    // Check the current image's Exif Orientation information\n    checkOrientation: true,\n    // Show the black modal\n    modal: true,\n    // Show the dashed lines for guiding\n    guides: true,\n    // Show the center indicator for guiding\n    center: true,\n    // Show the white modal to highlight the crop box\n    highlight: true,\n    // Show the grid background\n    background: true,\n    // Enable to crop the image automatically when initialize\n    autoCrop: true,\n    // Define the percentage of automatic cropping area when initializes\n    autoCropArea: 0.8,\n    // Enable to move the image\n    movable: true,\n    // Enable to rotate the image\n    rotatable: true,\n    // Enable to scale the image\n    scalable: true,\n    // Enable to zoom the image\n    zoomable: true,\n    // Enable to zoom the image by dragging touch\n    zoomOnTouch: true,\n    // Enable to zoom the image by wheeling mouse\n    zoomOnWheel: true,\n    // Define zoom ratio when zoom the image by wheeling mouse\n    wheelZoomRatio: 0.1,\n    // Enable to move the crop box\n    cropBoxMovable: true,\n    // Enable to resize the crop box\n    cropBoxResizable: true,\n    // Toggle drag mode between \"crop\" and \"move\" when click twice on the cropper\n    toggleDragModeOnDblclick: true,\n    // Size limitation\n    minCanvasWidth: 0,\n    minCanvasHeight: 0,\n    minCropBoxWidth: 0,\n    minCropBoxHeight: 0,\n    minContainerWidth: 200,\n    minContainerHeight: 100,\n    // Shortcuts of events\n    ready: null,\n    cropstart: null,\n    cropmove: null,\n    cropend: null,\n    crop: null,\n    zoom: null\n  };\n\n  var TEMPLATE = '<div class=\"cropper-container\" touch-action=\"none\">' + '<div class=\"cropper-wrap-box\">' + '<div class=\"cropper-canvas\"></div>' + '</div>' + '<div class=\"cropper-drag-box\"></div>' + '<div class=\"cropper-crop-box\">' + '<span class=\"cropper-view-box\"></span>' + '<span class=\"cropper-dashed dashed-h\"></span>' + '<span class=\"cropper-dashed dashed-v\"></span>' + '<span class=\"cropper-center\"></span>' + '<span class=\"cropper-face\"></span>' + '<span class=\"cropper-line line-e\" data-cropper-action=\"e\"></span>' + '<span class=\"cropper-line line-n\" data-cropper-action=\"n\"></span>' + '<span class=\"cropper-line line-w\" data-cropper-action=\"w\"></span>' + '<span class=\"cropper-line line-s\" data-cropper-action=\"s\"></span>' + '<span class=\"cropper-point point-e\" data-cropper-action=\"e\"></span>' + '<span class=\"cropper-point point-n\" data-cropper-action=\"n\"></span>' + '<span class=\"cropper-point point-w\" data-cropper-action=\"w\"></span>' + '<span class=\"cropper-point point-s\" data-cropper-action=\"s\"></span>' + '<span class=\"cropper-point point-ne\" data-cropper-action=\"ne\"></span>' + '<span class=\"cropper-point point-nw\" data-cropper-action=\"nw\"></span>' + '<span class=\"cropper-point point-sw\" data-cropper-action=\"sw\"></span>' + '<span class=\"cropper-point point-se\" data-cropper-action=\"se\"></span>' + '</div>' + '</div>';\n\n  /**\n   * Check if the given value is not a number.\n   */\n\n  var isNaN = Number.isNaN || WINDOW.isNaN;\n  /**\n   * Check if the given value is a number.\n   * @param {*} value - The value to check.\n   * @returns {boolean} Returns `true` if the given value is a number, else `false`.\n   */\n\n  function isNumber(value) {\n    return typeof value === 'number' && !isNaN(value);\n  }\n  /**\n   * Check if the given value is a positive number.\n   * @param {*} value - The value to check.\n   * @returns {boolean} Returns `true` if the given value is a positive number, else `false`.\n   */\n\n  var isPositiveNumber = function isPositiveNumber(value) {\n    return value > 0 && value < Infinity;\n  };\n  /**\n   * Check if the given value is undefined.\n   * @param {*} value - The value to check.\n   * @returns {boolean} Returns `true` if the given value is undefined, else `false`.\n   */\n\n  function isUndefined(value) {\n    return typeof value === 'undefined';\n  }\n  /**\n   * Check if the given value is an object.\n   * @param {*} value - The value to check.\n   * @returns {boolean} Returns `true` if the given value is an object, else `false`.\n   */\n\n  function isObject(value) {\n    return _typeof(value) === 'object' && value !== null;\n  }\n  var hasOwnProperty = Object.prototype.hasOwnProperty;\n  /**\n   * Check if the given value is a plain object.\n   * @param {*} value - The value to check.\n   * @returns {boolean} Returns `true` if the given value is a plain object, else `false`.\n   */\n\n  function isPlainObject(value) {\n    if (!isObject(value)) {\n      return false;\n    }\n\n    try {\n      var _constructor = value.constructor;\n      var prototype = _constructor.prototype;\n      return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');\n    } catch (error) {\n      return false;\n    }\n  }\n  /**\n   * Check if the given value is a function.\n   * @param {*} value - The value to check.\n   * @returns {boolean} Returns `true` if the given value is a function, else `false`.\n   */\n\n  function isFunction(value) {\n    return typeof value === 'function';\n  }\n  var slice = Array.prototype.slice;\n  /**\n   * Convert array-like or iterable object to an array.\n   * @param {*} value - The value to convert.\n   * @returns {Array} Returns a new array.\n   */\n\n  function toArray(value) {\n    return Array.from ? Array.from(value) : slice.call(value);\n  }\n  /**\n   * Iterate the given data.\n   * @param {*} data - The data to iterate.\n   * @param {Function} callback - The process function for each element.\n   * @returns {*} The original data.\n   */\n\n  function forEach(data, callback) {\n    if (data && isFunction(callback)) {\n      if (Array.isArray(data) || isNumber(data.length)\n      /* array-like */\n      ) {\n          toArray(data).forEach(function (value, key) {\n            callback.call(data, value, key, data);\n          });\n        } else if (isObject(data)) {\n        Object.keys(data).forEach(function (key) {\n          callback.call(data, data[key], key, data);\n        });\n      }\n    }\n\n    return data;\n  }\n  /**\n   * Extend the given object.\n   * @param {*} target - The target object to extend.\n   * @param {*} args - The rest objects for merging to the target object.\n   * @returns {Object} The extended object.\n   */\n\n  var assign = Object.assign || function assign(target) {\n    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      args[_key - 1] = arguments[_key];\n    }\n\n    if (isObject(target) && args.length > 0) {\n      args.forEach(function (arg) {\n        if (isObject(arg)) {\n          Object.keys(arg).forEach(function (key) {\n            target[key] = arg[key];\n          });\n        }\n      });\n    }\n\n    return target;\n  };\n  var REGEXP_DECIMALS = /\\.\\d*(?:0|9){12}\\d*$/;\n  /**\n   * Normalize decimal number.\n   * Check out {@link https://0.30000000000000004.com/}\n   * @param {number} value - The value to normalize.\n   * @param {number} [times=100000000000] - The times for normalizing.\n   * @returns {number} Returns the normalized number.\n   */\n\n  function normalizeDecimalNumber(value) {\n    var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;\n    return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;\n  }\n  var REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/;\n  /**\n   * Apply styles to the given element.\n   * @param {Element} element - The target element.\n   * @param {Object} styles - The styles for applying.\n   */\n\n  function setStyle(element, styles) {\n    var style = element.style;\n    forEach(styles, function (value, property) {\n      if (REGEXP_SUFFIX.test(property) && isNumber(value)) {\n        value = \"\".concat(value, \"px\");\n      }\n\n      style[property] = value;\n    });\n  }\n  /**\n   * Check if the given element has a special class.\n   * @param {Element} element - The element to check.\n   * @param {string} value - The class to search.\n   * @returns {boolean} Returns `true` if the special class was found.\n   */\n\n  function hasClass(element, value) {\n    return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1;\n  }\n  /**\n   * Add classes to the given element.\n   * @param {Element} element - The target element.\n   * @param {string} value - The classes to be added.\n   */\n\n  function addClass(element, value) {\n    if (!value) {\n      return;\n    }\n\n    if (isNumber(element.length)) {\n      forEach(element, function (elem) {\n        addClass(elem, value);\n      });\n      return;\n    }\n\n    if (element.classList) {\n      element.classList.add(value);\n      return;\n    }\n\n    var className = element.className.trim();\n\n    if (!className) {\n      element.className = value;\n    } else if (className.indexOf(value) < 0) {\n      element.className = \"\".concat(className, \" \").concat(value);\n    }\n  }\n  /**\n   * Remove classes from the given element.\n   * @param {Element} element - The target element.\n   * @param {string} value - The classes to be removed.\n   */\n\n  function removeClass(element, value) {\n    if (!value) {\n      return;\n    }\n\n    if (isNumber(element.length)) {\n      forEach(element, function (elem) {\n        removeClass(elem, value);\n      });\n      return;\n    }\n\n    if (element.classList) {\n      element.classList.remove(value);\n      return;\n    }\n\n    if (element.className.indexOf(value) >= 0) {\n      element.className = element.className.replace(value, '');\n    }\n  }\n  /**\n   * Add or remove classes from the given element.\n   * @param {Element} element - The target element.\n   * @param {string} value - The classes to be toggled.\n   * @param {boolean} added - Add only.\n   */\n\n  function toggleClass(element, value, added) {\n    if (!value) {\n      return;\n    }\n\n    if (isNumber(element.length)) {\n      forEach(element, function (elem) {\n        toggleClass(elem, value, added);\n      });\n      return;\n    } // IE10-11 doesn't support the second parameter of `classList.toggle`\n\n\n    if (added) {\n      addClass(element, value);\n    } else {\n      removeClass(element, value);\n    }\n  }\n  var REGEXP_CAMEL_CASE = /([a-z\\d])([A-Z])/g;\n  /**\n   * Transform the given string from camelCase to kebab-case\n   * @param {string} value - The value to transform.\n   * @returns {string} The transformed value.\n   */\n\n  function toParamCase(value) {\n    return value.replace(REGEXP_CAMEL_CASE, '$1-$2').toLowerCase();\n  }\n  /**\n   * Get data from the given element.\n   * @param {Element} element - The target element.\n   * @param {string} name - The data key to get.\n   * @returns {string} The data value.\n   */\n\n  function getData(element, name) {\n    if (isObject(element[name])) {\n      return element[name];\n    }\n\n    if (element.dataset) {\n      return element.dataset[name];\n    }\n\n    return element.getAttribute(\"data-\".concat(toParamCase(name)));\n  }\n  /**\n   * Set data to the given element.\n   * @param {Element} element - The target element.\n   * @param {string} name - The data key to set.\n   * @param {string} data - The data value.\n   */\n\n  function setData(element, name, data) {\n    if (isObject(data)) {\n      element[name] = data;\n    } else if (element.dataset) {\n      element.dataset[name] = data;\n    } else {\n      element.setAttribute(\"data-\".concat(toParamCase(name)), data);\n    }\n  }\n  /**\n   * Remove data from the given element.\n   * @param {Element} element - The target element.\n   * @param {string} name - The data key to remove.\n   */\n\n  function removeData(element, name) {\n    if (isObject(element[name])) {\n      try {\n        delete element[name];\n      } catch (error) {\n        element[name] = undefined;\n      }\n    } else if (element.dataset) {\n      // #128 Safari not allows to delete dataset property\n      try {\n        delete element.dataset[name];\n      } catch (error) {\n        element.dataset[name] = undefined;\n      }\n    } else {\n      element.removeAttribute(\"data-\".concat(toParamCase(name)));\n    }\n  }\n  var REGEXP_SPACES = /\\s\\s*/;\n\n  var onceSupported = function () {\n    var supported = false;\n\n    if (IS_BROWSER) {\n      var once = false;\n\n      var listener = function listener() {};\n\n      var options = Object.defineProperty({}, 'once', {\n        get: function get() {\n          supported = true;\n          return once;\n        },\n\n        /**\n         * This setter can fix a `TypeError` in strict mode\n         * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only}\n         * @param {boolean} value - The value to set\n         */\n        set: function set(value) {\n          once = value;\n        }\n      });\n      WINDOW.addEventListener('test', listener, options);\n      WINDOW.removeEventListener('test', listener, options);\n    }\n\n    return supported;\n  }();\n  /**\n   * Remove event listener from the target element.\n   * @param {Element} element - The event target.\n   * @param {string} type - The event type(s).\n   * @param {Function} listener - The event listener.\n   * @param {Object} options - The event options.\n   */\n\n\n  function removeListener(element, type, listener) {\n    var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n    var handler = listener;\n    type.trim().split(REGEXP_SPACES).forEach(function (event) {\n      if (!onceSupported) {\n        var listeners = element.listeners;\n\n        if (listeners && listeners[event] && listeners[event][listener]) {\n          handler = listeners[event][listener];\n          delete listeners[event][listener];\n\n          if (Object.keys(listeners[event]).length === 0) {\n            delete listeners[event];\n          }\n\n          if (Object.keys(listeners).length === 0) {\n            delete element.listeners;\n          }\n        }\n      }\n\n      element.removeEventListener(event, handler, options);\n    });\n  }\n  /**\n   * Add event listener to the target element.\n   * @param {Element} element - The event target.\n   * @param {string} type - The event type(s).\n   * @param {Function} listener - The event listener.\n   * @param {Object} options - The event options.\n   */\n\n  function addListener(element, type, listener) {\n    var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n    var _handler = listener;\n    type.trim().split(REGEXP_SPACES).forEach(function (event) {\n      if (options.once && !onceSupported) {\n        var _element$listeners = element.listeners,\n            listeners = _element$listeners === void 0 ? {} : _element$listeners;\n\n        _handler = function handler() {\n          delete listeners[event][listener];\n          element.removeEventListener(event, _handler, options);\n\n          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n            args[_key2] = arguments[_key2];\n          }\n\n          listener.apply(element, args);\n        };\n\n        if (!listeners[event]) {\n          listeners[event] = {};\n        }\n\n        if (listeners[event][listener]) {\n          element.removeEventListener(event, listeners[event][listener], options);\n        }\n\n        listeners[event][listener] = _handler;\n        element.listeners = listeners;\n      }\n\n      element.addEventListener(event, _handler, options);\n    });\n  }\n  /**\n   * Dispatch event on the target element.\n   * @param {Element} element - The event target.\n   * @param {string} type - The event type(s).\n   * @param {Object} data - The additional event data.\n   * @returns {boolean} Indicate if the event is default prevented or not.\n   */\n\n  function dispatchEvent(element, type, data) {\n    var event; // Event and CustomEvent on IE9-11 are global objects, not constructors\n\n    if (isFunction(Event) && isFunction(CustomEvent)) {\n      event = new CustomEvent(type, {\n        detail: data,\n        bubbles: true,\n        cancelable: true\n      });\n    } else {\n      event = document.createEvent('CustomEvent');\n      event.initCustomEvent(type, true, true, data);\n    }\n\n    return element.dispatchEvent(event);\n  }\n  /**\n   * Get the offset base on the document.\n   * @param {Element} element - The target element.\n   * @returns {Object} The offset data.\n   */\n\n  function getOffset(element) {\n    var box = element.getBoundingClientRect();\n    return {\n      left: box.left + (window.pageXOffset - document.documentElement.clientLeft),\n      top: box.top + (window.pageYOffset - document.documentElement.clientTop)\n    };\n  }\n  var location = WINDOW.location;\n  var REGEXP_ORIGINS = /^(\\w+:)\\/\\/([^:/?#]*):?(\\d*)/i;\n  /**\n   * Check if the given URL is a cross origin URL.\n   * @param {string} url - The target URL.\n   * @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.\n   */\n\n  function isCrossOriginURL(url) {\n    var parts = url.match(REGEXP_ORIGINS);\n    return parts !== null && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);\n  }\n  /**\n   * Add timestamp to the given URL.\n   * @param {string} url - The target URL.\n   * @returns {string} The result URL.\n   */\n\n  function addTimestamp(url) {\n    var timestamp = \"timestamp=\".concat(new Date().getTime());\n    return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;\n  }\n  /**\n   * Get transforms base on the given object.\n   * @param {Object} obj - The target object.\n   * @returns {string} A string contains transform values.\n   */\n\n  function getTransforms(_ref) {\n    var rotate = _ref.rotate,\n        scaleX = _ref.scaleX,\n        scaleY = _ref.scaleY,\n        translateX = _ref.translateX,\n        translateY = _ref.translateY;\n    var values = [];\n\n    if (isNumber(translateX) && translateX !== 0) {\n      values.push(\"translateX(\".concat(translateX, \"px)\"));\n    }\n\n    if (isNumber(translateY) && translateY !== 0) {\n      values.push(\"translateY(\".concat(translateY, \"px)\"));\n    } // Rotate should come first before scale to match orientation transform\n\n\n    if (isNumber(rotate) && rotate !== 0) {\n      values.push(\"rotate(\".concat(rotate, \"deg)\"));\n    }\n\n    if (isNumber(scaleX) && scaleX !== 1) {\n      values.push(\"scaleX(\".concat(scaleX, \")\"));\n    }\n\n    if (isNumber(scaleY) && scaleY !== 1) {\n      values.push(\"scaleY(\".concat(scaleY, \")\"));\n    }\n\n    var transform = values.length ? values.join(' ') : 'none';\n    return {\n      WebkitTransform: transform,\n      msTransform: transform,\n      transform: transform\n    };\n  }\n  /**\n   * Get the max ratio of a group of pointers.\n   * @param {string} pointers - The target pointers.\n   * @returns {number} The result ratio.\n   */\n\n  function getMaxZoomRatio(pointers) {\n    var pointers2 = _objectSpread2({}, pointers);\n\n    var ratios = [];\n    forEach(pointers, function (pointer, pointerId) {\n      delete pointers2[pointerId];\n      forEach(pointers2, function (pointer2) {\n        var x1 = Math.abs(pointer.startX - pointer2.startX);\n        var y1 = Math.abs(pointer.startY - pointer2.startY);\n        var x2 = Math.abs(pointer.endX - pointer2.endX);\n        var y2 = Math.abs(pointer.endY - pointer2.endY);\n        var z1 = Math.sqrt(x1 * x1 + y1 * y1);\n        var z2 = Math.sqrt(x2 * x2 + y2 * y2);\n        var ratio = (z2 - z1) / z1;\n        ratios.push(ratio);\n      });\n    });\n    ratios.sort(function (a, b) {\n      return Math.abs(a) < Math.abs(b);\n    });\n    return ratios[0];\n  }\n  /**\n   * Get a pointer from an event object.\n   * @param {Object} event - The target event object.\n   * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not.\n   * @returns {Object} The result pointer contains start and/or end point coordinates.\n   */\n\n  function getPointer(_ref2, endOnly) {\n    var pageX = _ref2.pageX,\n        pageY = _ref2.pageY;\n    var end = {\n      endX: pageX,\n      endY: pageY\n    };\n    return endOnly ? end : _objectSpread2({\n      startX: pageX,\n      startY: pageY\n    }, end);\n  }\n  /**\n   * Get the center point coordinate of a group of pointers.\n   * @param {Object} pointers - The target pointers.\n   * @returns {Object} The center point coordinate.\n   */\n\n  function getPointersCenter(pointers) {\n    var pageX = 0;\n    var pageY = 0;\n    var count = 0;\n    forEach(pointers, function (_ref3) {\n      var startX = _ref3.startX,\n          startY = _ref3.startY;\n      pageX += startX;\n      pageY += startY;\n      count += 1;\n    });\n    pageX /= count;\n    pageY /= count;\n    return {\n      pageX: pageX,\n      pageY: pageY\n    };\n  }\n  /**\n   * Get the max sizes in a rectangle under the given aspect ratio.\n   * @param {Object} data - The original sizes.\n   * @param {string} [type='contain'] - The adjust type.\n   * @returns {Object} The result sizes.\n   */\n\n  function getAdjustedSizes(_ref4) // or 'cover'\n  {\n    var aspectRatio = _ref4.aspectRatio,\n        height = _ref4.height,\n        width = _ref4.width;\n    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain';\n    var isValidWidth = isPositiveNumber(width);\n    var isValidHeight = isPositiveNumber(height);\n\n    if (isValidWidth && isValidHeight) {\n      var adjustedWidth = height * aspectRatio;\n\n      if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {\n        height = width / aspectRatio;\n      } else {\n        width = height * aspectRatio;\n      }\n    } else if (isValidWidth) {\n      height = width / aspectRatio;\n    } else if (isValidHeight) {\n      width = height * aspectRatio;\n    }\n\n    return {\n      width: width,\n      height: height\n    };\n  }\n  /**\n   * Get the new sizes of a rectangle after rotated.\n   * @param {Object} data - The original sizes.\n   * @returns {Object} The result sizes.\n   */\n\n  function getRotatedSizes(_ref5) {\n    var width = _ref5.width,\n        height = _ref5.height,\n        degree = _ref5.degree;\n    degree = Math.abs(degree) % 180;\n\n    if (degree === 90) {\n      return {\n        width: height,\n        height: width\n      };\n    }\n\n    var arc = degree % 90 * Math.PI / 180;\n    var sinArc = Math.sin(arc);\n    var cosArc = Math.cos(arc);\n    var newWidth = width * cosArc + height * sinArc;\n    var newHeight = width * sinArc + height * cosArc;\n    return degree > 90 ? {\n      width: newHeight,\n      height: newWidth\n    } : {\n      width: newWidth,\n      height: newHeight\n    };\n  }\n  /**\n   * Get a canvas which drew the given image.\n   * @param {HTMLImageElement} image - The image for drawing.\n   * @param {Object} imageData - The image data.\n   * @param {Object} canvasData - The canvas data.\n   * @param {Object} options - The options.\n   * @returns {HTMLCanvasElement} The result canvas.\n   */\n\n  function getSourceCanvas(image, _ref6, _ref7, _ref8) {\n    var imageAspectRatio = _ref6.aspectRatio,\n        imageNaturalWidth = _ref6.naturalWidth,\n        imageNaturalHeight = _ref6.naturalHeight,\n        _ref6$rotate = _ref6.rotate,\n        rotate = _ref6$rotate === void 0 ? 0 : _ref6$rotate,\n        _ref6$scaleX = _ref6.scaleX,\n        scaleX = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX,\n        _ref6$scaleY = _ref6.scaleY,\n        scaleY = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY;\n    var aspectRatio = _ref7.aspectRatio,\n        naturalWidth = _ref7.naturalWidth,\n        naturalHeight = _ref7.naturalHeight;\n    var _ref8$fillColor = _ref8.fillColor,\n        fillColor = _ref8$fillColor === void 0 ? 'transparent' : _ref8$fillColor,\n        _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled,\n        imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE,\n        _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality,\n        imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? 'low' : _ref8$imageSmoothingQ,\n        _ref8$maxWidth = _ref8.maxWidth,\n        maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth,\n        _ref8$maxHeight = _ref8.maxHeight,\n        maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight,\n        _ref8$minWidth = _ref8.minWidth,\n        minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth,\n        _ref8$minHeight = _ref8.minHeight,\n        minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight;\n    var canvas = document.createElement('canvas');\n    var context = canvas.getContext('2d');\n    var maxSizes = getAdjustedSizes({\n      aspectRatio: aspectRatio,\n      width: maxWidth,\n      height: maxHeight\n    });\n    var minSizes = getAdjustedSizes({\n      aspectRatio: aspectRatio,\n      width: minWidth,\n      height: minHeight\n    }, 'cover');\n    var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth));\n    var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight)); // Note: should always use image's natural sizes for drawing as\n    // imageData.naturalWidth === canvasData.naturalHeight when rotate % 180 === 90\n\n    var destMaxSizes = getAdjustedSizes({\n      aspectRatio: imageAspectRatio,\n      width: maxWidth,\n      height: maxHeight\n    });\n    var destMinSizes = getAdjustedSizes({\n      aspectRatio: imageAspectRatio,\n      width: minWidth,\n      height: minHeight\n    }, 'cover');\n    var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth));\n    var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight));\n    var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight];\n    canvas.width = normalizeDecimalNumber(width);\n    canvas.height = normalizeDecimalNumber(height);\n    context.fillStyle = fillColor;\n    context.fillRect(0, 0, width, height);\n    context.save();\n    context.translate(width / 2, height / 2);\n    context.rotate(rotate * Math.PI / 180);\n    context.scale(scaleX, scaleY);\n    context.imageSmoothingEnabled = imageSmoothingEnabled;\n    context.imageSmoothingQuality = imageSmoothingQuality;\n    context.drawImage.apply(context, [image].concat(_toConsumableArray(params.map(function (param) {\n      return Math.floor(normalizeDecimalNumber(param));\n    }))));\n    context.restore();\n    return canvas;\n  }\n  var fromCharCode = String.fromCharCode;\n  /**\n   * Get string from char code in data view.\n   * @param {DataView} dataView - The data view for read.\n   * @param {number} start - The start index.\n   * @param {number} length - The read length.\n   * @returns {string} The read result.\n   */\n\n  function getStringFromCharCode(dataView, start, length) {\n    var str = '';\n    length += start;\n\n    for (var i = start; i < length; i += 1) {\n      str += fromCharCode(dataView.getUint8(i));\n    }\n\n    return str;\n  }\n  var REGEXP_DATA_URL_HEAD = /^data:.*,/;\n  /**\n   * Transform Data URL to array buffer.\n   * @param {string} dataURL - The Data URL to transform.\n   * @returns {ArrayBuffer} The result array buffer.\n   */\n\n  function dataURLToArrayBuffer(dataURL) {\n    var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');\n    var binary = atob(base64);\n    var arrayBuffer = new ArrayBuffer(binary.length);\n    var uint8 = new Uint8Array(arrayBuffer);\n    forEach(uint8, function (value, i) {\n      uint8[i] = binary.charCodeAt(i);\n    });\n    return arrayBuffer;\n  }\n  /**\n   * Transform array buffer to Data URL.\n   * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.\n   * @param {string} mimeType - The mime type of the Data URL.\n   * @returns {string} The result Data URL.\n   */\n\n  function arrayBufferToDataURL(arrayBuffer, mimeType) {\n    var chunks = []; // Chunk Typed Array for better performance (#435)\n\n    var chunkSize = 8192;\n    var uint8 = new Uint8Array(arrayBuffer);\n\n    while (uint8.length > 0) {\n      // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9\n      // eslint-disable-next-line prefer-spread\n      chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));\n      uint8 = uint8.subarray(chunkSize);\n    }\n\n    return \"data:\".concat(mimeType, \";base64,\").concat(btoa(chunks.join('')));\n  }\n  /**\n   * Get orientation value from given array buffer.\n   * @param {ArrayBuffer} arrayBuffer - The array buffer to read.\n   * @returns {number} The read orientation value.\n   */\n\n  function resetAndGetOrientation(arrayBuffer) {\n    var dataView = new DataView(arrayBuffer);\n    var orientation; // Ignores range error when the image does not have correct Exif information\n\n    try {\n      var littleEndian;\n      var app1Start;\n      var ifdStart; // Only handle JPEG image (start by 0xFFD8)\n\n      if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {\n        var length = dataView.byteLength;\n        var offset = 2;\n\n        while (offset + 1 < length) {\n          if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {\n            app1Start = offset;\n            break;\n          }\n\n          offset += 1;\n        }\n      }\n\n      if (app1Start) {\n        var exifIDCode = app1Start + 4;\n        var tiffOffset = app1Start + 10;\n\n        if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {\n          var endianness = dataView.getUint16(tiffOffset);\n          littleEndian = endianness === 0x4949;\n\n          if (littleEndian || endianness === 0x4D4D\n          /* bigEndian */\n          ) {\n              if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {\n                var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);\n\n                if (firstIFDOffset >= 0x00000008) {\n                  ifdStart = tiffOffset + firstIFDOffset;\n                }\n              }\n            }\n        }\n      }\n\n      if (ifdStart) {\n        var _length = dataView.getUint16(ifdStart, littleEndian);\n\n        var _offset;\n\n        var i;\n\n        for (i = 0; i < _length; i += 1) {\n          _offset = ifdStart + i * 12 + 2;\n\n          if (dataView.getUint16(_offset, littleEndian) === 0x0112\n          /* Orientation */\n          ) {\n              // 8 is the offset of the current tag's value\n              _offset += 8; // Get the original orientation value\n\n              orientation = dataView.getUint16(_offset, littleEndian); // Override the orientation with its default value\n\n              dataView.setUint16(_offset, 1, littleEndian);\n              break;\n            }\n        }\n      }\n    } catch (error) {\n      orientation = 1;\n    }\n\n    return orientation;\n  }\n  /**\n   * Parse Exif Orientation value.\n   * @param {number} orientation - The orientation to parse.\n   * @returns {Object} The parsed result.\n   */\n\n  function parseOrientation(orientation) {\n    var rotate = 0;\n    var scaleX = 1;\n    var scaleY = 1;\n\n    switch (orientation) {\n      // Flip horizontal\n      case 2:\n        scaleX = -1;\n        break;\n      // Rotate left 180\u00B0\n\n      case 3:\n        rotate = -180;\n        break;\n      // Flip vertical\n\n      case 4:\n        scaleY = -1;\n        break;\n      // Flip vertical and rotate right 90\u00B0\n\n      case 5:\n        rotate = 90;\n        scaleY = -1;\n        break;\n      // Rotate right 90\u00B0\n\n      case 6:\n        rotate = 90;\n        break;\n      // Flip horizontal and rotate right 90\u00B0\n\n      case 7:\n        rotate = 90;\n        scaleX = -1;\n        break;\n      // Rotate left 90\u00B0\n\n      case 8:\n        rotate = -90;\n        break;\n    }\n\n    return {\n      rotate: rotate,\n      scaleX: scaleX,\n      scaleY: scaleY\n    };\n  }\n\n  var render = {\n    render: function render() {\n      this.initContainer();\n      this.initCanvas();\n      this.initCropBox();\n      this.renderCanvas();\n\n      if (this.cropped) {\n        this.renderCropBox();\n      }\n    },\n    initContainer: function initContainer() {\n      var element = this.element,\n          options = this.options,\n          container = this.container,\n          cropper = this.cropper;\n      addClass(cropper, CLASS_HIDDEN);\n      removeClass(element, CLASS_HIDDEN);\n      var containerData = {\n        width: Math.max(container.offsetWidth, Number(options.minContainerWidth) || 200),\n        height: Math.max(container.offsetHeight, Number(options.minContainerHeight) || 100)\n      };\n      this.containerData = containerData;\n      setStyle(cropper, {\n        width: containerData.width,\n        height: containerData.height\n      });\n      addClass(element, CLASS_HIDDEN);\n      removeClass(cropper, CLASS_HIDDEN);\n    },\n    // Canvas (image wrapper)\n    initCanvas: function initCanvas() {\n      var containerData = this.containerData,\n          imageData = this.imageData;\n      var viewMode = this.options.viewMode;\n      var rotated = Math.abs(imageData.rotate) % 180 === 90;\n      var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth;\n      var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight;\n      var aspectRatio = naturalWidth / naturalHeight;\n      var canvasWidth = containerData.width;\n      var canvasHeight = containerData.height;\n\n      if (containerData.height * aspectRatio > containerData.width) {\n        if (viewMode === 3) {\n          canvasWidth = containerData.height * aspectRatio;\n        } else {\n          canvasHeight = containerData.width / aspectRatio;\n        }\n      } else if (viewMode === 3) {\n        canvasHeight = containerData.width / aspectRatio;\n      } else {\n        canvasWidth = containerData.height * aspectRatio;\n      }\n\n      var canvasData = {\n        aspectRatio: aspectRatio,\n        naturalWidth: naturalWidth,\n        naturalHeight: naturalHeight,\n        width: canvasWidth,\n        height: canvasHeight\n      };\n      canvasData.left = (containerData.width - canvasWidth) / 2;\n      canvasData.top = (containerData.height - canvasHeight) / 2;\n      canvasData.oldLeft = canvasData.left;\n      canvasData.oldTop = canvasData.top;\n      this.canvasData = canvasData;\n      this.limited = viewMode === 1 || viewMode === 2;\n      this.limitCanvas(true, true);\n      this.initialImageData = assign({}, imageData);\n      this.initialCanvasData = assign({}, canvasData);\n    },\n    limitCanvas: function limitCanvas(sizeLimited, positionLimited) {\n      var options = this.options,\n          containerData = this.containerData,\n          canvasData = this.canvasData,\n          cropBoxData = this.cropBoxData;\n      var viewMode = options.viewMode;\n      var aspectRatio = canvasData.aspectRatio;\n      var cropped = this.cropped && cropBoxData;\n\n      if (sizeLimited) {\n        var minCanvasWidth = Number(options.minCanvasWidth) || 0;\n        var minCanvasHeight = Number(options.minCanvasHeight) || 0;\n\n        if (viewMode > 1) {\n          minCanvasWidth = Math.max(minCanvasWidth, containerData.width);\n          minCanvasHeight = Math.max(minCanvasHeight, containerData.height);\n\n          if (viewMode === 3) {\n            if (minCanvasHeight * aspectRatio > minCanvasWidth) {\n              minCanvasWidth = minCanvasHeight * aspectRatio;\n            } else {\n              minCanvasHeight = minCanvasWidth / aspectRatio;\n            }\n          }\n        } else if (viewMode > 0) {\n          if (minCanvasWidth) {\n            minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0);\n          } else if (minCanvasHeight) {\n            minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0);\n          } else if (cropped) {\n            minCanvasWidth = cropBoxData.width;\n            minCanvasHeight = cropBoxData.height;\n\n            if (minCanvasHeight * aspectRatio > minCanvasWidth) {\n              minCanvasWidth = minCanvasHeight * aspectRatio;\n            } else {\n              minCanvasHeight = minCanvasWidth / aspectRatio;\n            }\n          }\n        }\n\n        var _getAdjustedSizes = getAdjustedSizes({\n          aspectRatio: aspectRatio,\n          width: minCanvasWidth,\n          height: minCanvasHeight\n        });\n\n        minCanvasWidth = _getAdjustedSizes.width;\n        minCanvasHeight = _getAdjustedSizes.height;\n        canvasData.minWidth = minCanvasWidth;\n        canvasData.minHeight = minCanvasHeight;\n        canvasData.maxWidth = Infinity;\n        canvasData.maxHeight = Infinity;\n      }\n\n      if (positionLimited) {\n        if (viewMode > (cropped ? 0 : 1)) {\n          var newCanvasLeft = containerData.width - canvasData.width;\n          var newCanvasTop = containerData.height - canvasData.height;\n          canvasData.minLeft = Math.min(0, newCanvasLeft);\n          canvasData.minTop = Math.min(0, newCanvasTop);\n          canvasData.maxLeft = Math.max(0, newCanvasLeft);\n          canvasData.maxTop = Math.max(0, newCanvasTop);\n\n          if (cropped && this.limited) {\n            canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width));\n            canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height));\n            canvasData.maxLeft = cropBoxData.left;\n            canvasData.maxTop = cropBoxData.top;\n\n            if (viewMode === 2) {\n              if (canvasData.width >= containerData.width) {\n                canvasData.minLeft = Math.min(0, newCanvasLeft);\n                canvasData.maxLeft = Math.max(0, newCanvasLeft);\n              }\n\n              if (canvasData.height >= containerData.height) {\n                canvasData.minTop = Math.min(0, newCanvasTop);\n                canvasData.maxTop = Math.max(0, newCanvasTop);\n              }\n            }\n          }\n        } else {\n          canvasData.minLeft = -canvasData.width;\n          canvasData.minTop = -canvasData.height;\n          canvasData.maxLeft = containerData.width;\n          canvasData.maxTop = containerData.height;\n        }\n      }\n    },\n    renderCanvas: function renderCanvas(changed, transformed) {\n      var canvasData = this.canvasData,\n          imageData = this.imageData;\n\n      if (transformed) {\n        var _getRotatedSizes = getRotatedSizes({\n          width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1),\n          height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1),\n          degree: imageData.rotate || 0\n        }),\n            naturalWidth = _getRotatedSizes.width,\n            naturalHeight = _getRotatedSizes.height;\n\n        var width = canvasData.width * (naturalWidth / canvasData.naturalWidth);\n        var height = canvasData.height * (naturalHeight / canvasData.naturalHeight);\n        canvasData.left -= (width - canvasData.width) / 2;\n        canvasData.top -= (height - canvasData.height) / 2;\n        canvasData.width = width;\n        canvasData.height = height;\n        canvasData.aspectRatio = naturalWidth / naturalHeight;\n        canvasData.naturalWidth = naturalWidth;\n        canvasData.naturalHeight = naturalHeight;\n        this.limitCanvas(true, false);\n      }\n\n      if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) {\n        canvasData.left = canvasData.oldLeft;\n      }\n\n      if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) {\n        canvasData.top = canvasData.oldTop;\n      }\n\n      canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);\n      canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);\n      this.limitCanvas(false, true);\n      canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft);\n      canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop);\n      canvasData.oldLeft = canvasData.left;\n      canvasData.oldTop = canvasData.top;\n      setStyle(this.canvas, assign({\n        width: canvasData.width,\n        height: canvasData.height\n      }, getTransforms({\n        translateX: canvasData.left,\n        translateY: canvasData.top\n      })));\n      this.renderImage(changed);\n\n      if (this.cropped && this.limited) {\n        this.limitCropBox(true, true);\n      }\n    },\n    renderImage: function renderImage(changed) {\n      var canvasData = this.canvasData,\n          imageData = this.imageData;\n      var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth);\n      var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight);\n      assign(imageData, {\n        width: width,\n        height: height,\n        left: (canvasData.width - width) / 2,\n        top: (canvasData.height - height) / 2\n      });\n      setStyle(this.image, assign({\n        width: imageData.width,\n        height: imageData.height\n      }, getTransforms(assign({\n        translateX: imageData.left,\n        translateY: imageData.top\n      }, imageData))));\n\n      if (changed) {\n        this.output();\n      }\n    },\n    initCropBox: function initCropBox() {\n      var options = this.options,\n          canvasData = this.canvasData;\n      var aspectRatio = options.aspectRatio || options.initialAspectRatio;\n      var autoCropArea = Number(options.autoCropArea) || 0.8;\n      var cropBoxData = {\n        width: canvasData.width,\n        height: canvasData.height\n      };\n\n      if (aspectRatio) {\n        if (canvasData.height * aspectRatio > canvasData.width) {\n          cropBoxData.height = cropBoxData.width / aspectRatio;\n        } else {\n          cropBoxData.width = cropBoxData.height * aspectRatio;\n        }\n      }\n\n      this.cropBoxData = cropBoxData;\n      this.limitCropBox(true, true); // Initialize auto crop area\n\n      cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);\n      cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); // The width/height of auto crop area must large than \"minWidth/Height\"\n\n      cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea);\n      cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea);\n      cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2;\n      cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2;\n      cropBoxData.oldLeft = cropBoxData.left;\n      cropBoxData.oldTop = cropBoxData.top;\n      this.initialCropBoxData = assign({}, cropBoxData);\n    },\n    limitCropBox: function limitCropBox(sizeLimited, positionLimited) {\n      var options = this.options,\n          containerData = this.containerData,\n          canvasData = this.canvasData,\n          cropBoxData = this.cropBoxData,\n          limited = this.limited;\n      var aspectRatio = options.aspectRatio;\n\n      if (sizeLimited) {\n        var minCropBoxWidth = Number(options.minCropBoxWidth) || 0;\n        var minCropBoxHeight = Number(options.minCropBoxHeight) || 0;\n        var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width;\n        var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height; // The min/maxCropBoxWidth/Height must be less than container's width/height\n\n        minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width);\n        minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height);\n\n        if (aspectRatio) {\n          if (minCropBoxWidth && minCropBoxHeight) {\n            if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {\n              minCropBoxHeight = minCropBoxWidth / aspectRatio;\n            } else {\n              minCropBoxWidth = minCropBoxHeight * aspectRatio;\n            }\n          } else if (minCropBoxWidth) {\n            minCropBoxHeight = minCropBoxWidth / aspectRatio;\n          } else if (minCropBoxHeight) {\n            minCropBoxWidth = minCropBoxHeight * aspectRatio;\n          }\n\n          if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {\n            maxCropBoxHeight = maxCropBoxWidth / aspectRatio;\n          } else {\n            maxCropBoxWidth = maxCropBoxHeight * aspectRatio;\n          }\n        } // The minWidth/Height must be less than maxWidth/Height\n\n\n        cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth);\n        cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight);\n        cropBoxData.maxWidth = maxCropBoxWidth;\n        cropBoxData.maxHeight = maxCropBoxHeight;\n      }\n\n      if (positionLimited) {\n        if (limited) {\n          cropBoxData.minLeft = Math.max(0, canvasData.left);\n          cropBoxData.minTop = Math.max(0, canvasData.top);\n          cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width;\n          cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height;\n        } else {\n          cropBoxData.minLeft = 0;\n          cropBoxData.minTop = 0;\n          cropBoxData.maxLeft = containerData.width - cropBoxData.width;\n          cropBoxData.maxTop = containerData.height - cropBoxData.height;\n        }\n      }\n    },\n    renderCropBox: function renderCropBox() {\n      var options = this.options,\n          containerData = this.containerData,\n          cropBoxData = this.cropBoxData;\n\n      if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) {\n        cropBoxData.left = cropBoxData.oldLeft;\n      }\n\n      if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) {\n        cropBoxData.top = cropBoxData.oldTop;\n      }\n\n      cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);\n      cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);\n      this.limitCropBox(false, true);\n      cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft);\n      cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop);\n      cropBoxData.oldLeft = cropBoxData.left;\n      cropBoxData.oldTop = cropBoxData.top;\n\n      if (options.movable && options.cropBoxMovable) {\n        // Turn to move the canvas when the crop box is equal to the container\n        setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL);\n      }\n\n      setStyle(this.cropBox, assign({\n        width: cropBoxData.width,\n        height: cropBoxData.height\n      }, getTransforms({\n        translateX: cropBoxData.left,\n        translateY: cropBoxData.top\n      })));\n\n      if (this.cropped && this.limited) {\n        this.limitCanvas(true, true);\n      }\n\n      if (!this.disabled) {\n        this.output();\n      }\n    },\n    output: function output() {\n      this.preview();\n      dispatchEvent(this.element, EVENT_CROP, this.getData());\n    }\n  };\n\n  var preview = {\n    initPreview: function initPreview() {\n      var element = this.element,\n          crossOrigin = this.crossOrigin;\n      var preview = this.options.preview;\n      var url = crossOrigin ? this.crossOriginUrl : this.url;\n      var alt = element.alt || 'The image to preview';\n      var image = document.createElement('img');\n\n      if (crossOrigin) {\n        image.crossOrigin = crossOrigin;\n      }\n\n      image.src = url;\n      image.alt = alt;\n      this.viewBox.appendChild(image);\n      this.viewBoxImage = image;\n\n      if (!preview) {\n        return;\n      }\n\n      var previews = preview;\n\n      if (typeof preview === 'string') {\n        previews = element.ownerDocument.querySelectorAll(preview);\n      } else if (preview.querySelector) {\n        previews = [preview];\n      }\n\n      this.previews = previews;\n      forEach(previews, function (el) {\n        var img = document.createElement('img'); // Save the original size for recover\n\n        setData(el, DATA_PREVIEW, {\n          width: el.offsetWidth,\n          height: el.offsetHeight,\n          html: el.innerHTML\n        });\n\n        if (crossOrigin) {\n          img.crossOrigin = crossOrigin;\n        }\n\n        img.src = url;\n        img.alt = alt;\n        /**\n         * Override img element styles\n         * Add `display:block` to avoid margin top issue\n         * Add `height:auto` to override `height` attribute on IE8\n         * (Occur only when margin-top <= -height)\n         */\n\n        img.style.cssText = 'display:block;' + 'width:100%;' + 'height:auto;' + 'min-width:0!important;' + 'min-height:0!important;' + 'max-width:none!important;' + 'max-height:none!important;' + 'image-orientation:0deg!important;\"';\n        el.innerHTML = '';\n        el.appendChild(img);\n      });\n    },\n    resetPreview: function resetPreview() {\n      forEach(this.previews, function (element) {\n        var data = getData(element, DATA_PREVIEW);\n        setStyle(element, {\n          width: data.width,\n          height: data.height\n        });\n        element.innerHTML = data.html;\n        removeData(element, DATA_PREVIEW);\n      });\n    },\n    preview: function preview() {\n      var imageData = this.imageData,\n          canvasData = this.canvasData,\n          cropBoxData = this.cropBoxData;\n      var cropBoxWidth = cropBoxData.width,\n          cropBoxHeight = cropBoxData.height;\n      var width = imageData.width,\n          height = imageData.height;\n      var left = cropBoxData.left - canvasData.left - imageData.left;\n      var top = cropBoxData.top - canvasData.top - imageData.top;\n\n      if (!this.cropped || this.disabled) {\n        return;\n      }\n\n      setStyle(this.viewBoxImage, assign({\n        width: width,\n        height: height\n      }, getTransforms(assign({\n        translateX: -left,\n        translateY: -top\n      }, imageData))));\n      forEach(this.previews, function (element) {\n        var data = getData(element, DATA_PREVIEW);\n        var originalWidth = data.width;\n        var originalHeight = data.height;\n        var newWidth = originalWidth;\n        var newHeight = originalHeight;\n        var ratio = 1;\n\n        if (cropBoxWidth) {\n          ratio = originalWidth / cropBoxWidth;\n          newHeight = cropBoxHeight * ratio;\n        }\n\n        if (cropBoxHeight && newHeight > originalHeight) {\n          ratio = originalHeight / cropBoxHeight;\n          newWidth = cropBoxWidth * ratio;\n          newHeight = originalHeight;\n        }\n\n        setStyle(element, {\n          width: newWidth,\n          height: newHeight\n        });\n        setStyle(element.getElementsByTagName('img')[0], assign({\n          width: width * ratio,\n          height: height * ratio\n        }, getTransforms(assign({\n          translateX: -left * ratio,\n          translateY: -top * ratio\n        }, imageData))));\n      });\n    }\n  };\n\n  var events = {\n    bind: function bind() {\n      var element = this.element,\n          options = this.options,\n          cropper = this.cropper;\n\n      if (isFunction(options.cropstart)) {\n        addListener(element, EVENT_CROP_START, options.cropstart);\n      }\n\n      if (isFunction(options.cropmove)) {\n        addListener(element, EVENT_CROP_MOVE, options.cropmove);\n      }\n\n      if (isFunction(options.cropend)) {\n        addListener(element, EVENT_CROP_END, options.cropend);\n      }\n\n      if (isFunction(options.crop)) {\n        addListener(element, EVENT_CROP, options.crop);\n      }\n\n      if (isFunction(options.zoom)) {\n        addListener(element, EVENT_ZOOM, options.zoom);\n      }\n\n      addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this));\n\n      if (options.zoomable && options.zoomOnWheel) {\n        addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), {\n          passive: false,\n          capture: true\n        });\n      }\n\n      if (options.toggleDragModeOnDblclick) {\n        addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this));\n      }\n\n      addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this));\n      addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this));\n\n      if (options.responsive) {\n        addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this));\n      }\n    },\n    unbind: function unbind() {\n      var element = this.element,\n          options = this.options,\n          cropper = this.cropper;\n\n      if (isFunction(options.cropstart)) {\n        removeListener(element, EVENT_CROP_START, options.cropstart);\n      }\n\n      if (isFunction(options.cropmove)) {\n        removeListener(element, EVENT_CROP_MOVE, options.cropmove);\n      }\n\n      if (isFunction(options.cropend)) {\n        removeListener(element, EVENT_CROP_END, options.cropend);\n      }\n\n      if (isFunction(options.crop)) {\n        removeListener(element, EVENT_CROP, options.crop);\n      }\n\n      if (isFunction(options.zoom)) {\n        removeListener(element, EVENT_ZOOM, options.zoom);\n      }\n\n      removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart);\n\n      if (options.zoomable && options.zoomOnWheel) {\n        removeListener(cropper, EVENT_WHEEL, this.onWheel, {\n          passive: false,\n          capture: true\n        });\n      }\n\n      if (options.toggleDragModeOnDblclick) {\n        removeListener(cropper, EVENT_DBLCLICK, this.onDblclick);\n      }\n\n      removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove);\n      removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd);\n\n      if (options.responsive) {\n        removeListener(window, EVENT_RESIZE, this.onResize);\n      }\n    }\n  };\n\n  var handlers = {\n    resize: function resize() {\n      if (this.disabled) {\n        return;\n      }\n\n      var options = this.options,\n          container = this.container,\n          containerData = this.containerData;\n      var ratio = container.offsetWidth / containerData.width; // Resize when width changed or height changed\n\n      if (ratio !== 1 || container.offsetHeight !== containerData.height) {\n        var canvasData;\n        var cropBoxData;\n\n        if (options.restore) {\n          canvasData = this.getCanvasData();\n          cropBoxData = this.getCropBoxData();\n        }\n\n        this.render();\n\n        if (options.restore) {\n          this.setCanvasData(forEach(canvasData, function (n, i) {\n            canvasData[i] = n * ratio;\n          }));\n          this.setCropBoxData(forEach(cropBoxData, function (n, i) {\n            cropBoxData[i] = n * ratio;\n          }));\n        }\n      }\n    },\n    dblclick: function dblclick() {\n      if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) {\n        return;\n      }\n\n      this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP);\n    },\n    wheel: function wheel(event) {\n      var _this = this;\n\n      var ratio = Number(this.options.wheelZoomRatio) || 0.1;\n      var delta = 1;\n\n      if (this.disabled) {\n        return;\n      }\n\n      event.preventDefault(); // Limit wheel speed to prevent zoom too fast (#21)\n\n      if (this.wheeling) {\n        return;\n      }\n\n      this.wheeling = true;\n      setTimeout(function () {\n        _this.wheeling = false;\n      }, 50);\n\n      if (event.deltaY) {\n        delta = event.deltaY > 0 ? 1 : -1;\n      } else if (event.wheelDelta) {\n        delta = -event.wheelDelta / 120;\n      } else if (event.detail) {\n        delta = event.detail > 0 ? 1 : -1;\n      }\n\n      this.zoom(-delta * ratio, event);\n    },\n    cropStart: function cropStart(event) {\n      var buttons = event.buttons,\n          button = event.button;\n\n      if (this.disabled // Handle mouse event and pointer event and ignore touch event\n      || (event.type === 'mousedown' || event.type === 'pointerdown' && event.pointerType === 'mouse') && ( // No primary button (Usually the left button)\n      isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0 // Open context menu\n      || event.ctrlKey)) {\n        return;\n      }\n\n      var options = this.options,\n          pointers = this.pointers;\n      var action;\n\n      if (event.changedTouches) {\n        // Handle touch event\n        forEach(event.changedTouches, function (touch) {\n          pointers[touch.identifier] = getPointer(touch);\n        });\n      } else {\n        // Handle mouse event and pointer event\n        pointers[event.pointerId || 0] = getPointer(event);\n      }\n\n      if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {\n        action = ACTION_ZOOM;\n      } else {\n        action = getData(event.target, DATA_ACTION);\n      }\n\n      if (!REGEXP_ACTIONS.test(action)) {\n        return;\n      }\n\n      if (dispatchEvent(this.element, EVENT_CROP_START, {\n        originalEvent: event,\n        action: action\n      }) === false) {\n        return;\n      } // This line is required for preventing page zooming in iOS browsers\n\n\n      event.preventDefault();\n      this.action = action;\n      this.cropping = false;\n\n      if (action === ACTION_CROP) {\n        this.cropping = true;\n        addClass(this.dragBox, CLASS_MODAL);\n      }\n    },\n    cropMove: function cropMove(event) {\n      var action = this.action;\n\n      if (this.disabled || !action) {\n        return;\n      }\n\n      var pointers = this.pointers;\n      event.preventDefault();\n\n      if (dispatchEvent(this.element, EVENT_CROP_MOVE, {\n        originalEvent: event,\n        action: action\n      }) === false) {\n        return;\n      }\n\n      if (event.changedTouches) {\n        forEach(event.changedTouches, function (touch) {\n          // The first parameter should not be undefined (#432)\n          assign(pointers[touch.identifier] || {}, getPointer(touch, true));\n        });\n      } else {\n        assign(pointers[event.pointerId || 0] || {}, getPointer(event, true));\n      }\n\n      this.change(event);\n    },\n    cropEnd: function cropEnd(event) {\n      if (this.disabled) {\n        return;\n      }\n\n      var action = this.action,\n          pointers = this.pointers;\n\n      if (event.changedTouches) {\n        forEach(event.changedTouches, function (touch) {\n          delete pointers[touch.identifier];\n        });\n      } else {\n        delete pointers[event.pointerId || 0];\n      }\n\n      if (!action) {\n        return;\n      }\n\n      event.preventDefault();\n\n      if (!Object.keys(pointers).length) {\n        this.action = '';\n      }\n\n      if (this.cropping) {\n        this.cropping = false;\n        toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal);\n      }\n\n      dispatchEvent(this.element, EVENT_CROP_END, {\n        originalEvent: event,\n        action: action\n      });\n    }\n  };\n\n  var change = {\n    change: function change(event) {\n      var options = this.options,\n          canvasData = this.canvasData,\n          containerData = this.containerData,\n          cropBoxData = this.cropBoxData,\n          pointers = this.pointers;\n      var action = this.action;\n      var aspectRatio = options.aspectRatio;\n      var left = cropBoxData.left,\n          top = cropBoxData.top,\n          width = cropBoxData.width,\n          height = cropBoxData.height;\n      var right = left + width;\n      var bottom = top + height;\n      var minLeft = 0;\n      var minTop = 0;\n      var maxWidth = containerData.width;\n      var maxHeight = containerData.height;\n      var renderable = true;\n      var offset; // Locking aspect ratio in \"free mode\" by holding shift key\n\n      if (!aspectRatio && event.shiftKey) {\n        aspectRatio = width && height ? width / height : 1;\n      }\n\n      if (this.limited) {\n        minLeft = cropBoxData.minLeft;\n        minTop = cropBoxData.minTop;\n        maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width);\n        maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height);\n      }\n\n      var pointer = pointers[Object.keys(pointers)[0]];\n      var range = {\n        x: pointer.endX - pointer.startX,\n        y: pointer.endY - pointer.startY\n      };\n\n      var check = function check(side) {\n        switch (side) {\n          case ACTION_EAST:\n            if (right + range.x > maxWidth) {\n              range.x = maxWidth - right;\n            }\n\n            break;\n\n          case ACTION_WEST:\n            if (left + range.x < minLeft) {\n              range.x = minLeft - left;\n            }\n\n            break;\n\n          case ACTION_NORTH:\n            if (top + range.y < minTop) {\n              range.y = minTop - top;\n            }\n\n            break;\n\n          case ACTION_SOUTH:\n            if (bottom + range.y > maxHeight) {\n              range.y = maxHeight - bottom;\n            }\n\n            break;\n        }\n      };\n\n      switch (action) {\n        // Move crop box\n        case ACTION_ALL:\n          left += range.x;\n          top += range.y;\n          break;\n        // Resize crop box\n\n        case ACTION_EAST:\n          if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) {\n            renderable = false;\n            break;\n          }\n\n          check(ACTION_EAST);\n          width += range.x;\n\n          if (width < 0) {\n            action = ACTION_WEST;\n            width = -width;\n            left -= width;\n          }\n\n          if (aspectRatio) {\n            height = width / aspectRatio;\n            top += (cropBoxData.height - height) / 2;\n          }\n\n          break;\n\n        case ACTION_NORTH:\n          if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) {\n            renderable = false;\n            break;\n          }\n\n          check(ACTION_NORTH);\n          height -= range.y;\n          top += range.y;\n\n          if (height < 0) {\n            action = ACTION_SOUTH;\n            height = -height;\n            top -= height;\n          }\n\n          if (aspectRatio) {\n            width = height * aspectRatio;\n            left += (cropBoxData.width - width) / 2;\n          }\n\n          break;\n\n        case ACTION_WEST:\n          if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) {\n            renderable = false;\n            break;\n          }\n\n          check(ACTION_WEST);\n          width -= range.x;\n          left += range.x;\n\n          if (width < 0) {\n            action = ACTION_EAST;\n            width = -width;\n            left -= width;\n          }\n\n          if (aspectRatio) {\n            height = width / aspectRatio;\n            top += (cropBoxData.height - height) / 2;\n          }\n\n          break;\n\n        case ACTION_SOUTH:\n          if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) {\n            renderable = false;\n            break;\n          }\n\n          check(ACTION_SOUTH);\n          height += range.y;\n\n          if (height < 0) {\n            action = ACTION_NORTH;\n            height = -height;\n            top -= height;\n          }\n\n          if (aspectRatio) {\n            width = height * aspectRatio;\n            left += (cropBoxData.width - width) / 2;\n          }\n\n          break;\n\n        case ACTION_NORTH_EAST:\n          if (aspectRatio) {\n            if (range.y <= 0 && (top <= minTop || right >= maxWidth)) {\n              renderable = false;\n              break;\n            }\n\n            check(ACTION_NORTH);\n            height -= range.y;\n            top += range.y;\n            width = height * aspectRatio;\n          } else {\n            check(ACTION_NORTH);\n            check(ACTION_EAST);\n\n            if (range.x >= 0) {\n              if (right < maxWidth) {\n                width += range.x;\n              } else if (range.y <= 0 && top <= minTop) {\n                renderable = false;\n              }\n            } else {\n              width += range.x;\n            }\n\n            if (range.y <= 0) {\n              if (top > minTop) {\n                height -= range.y;\n                top += range.y;\n              }\n            } else {\n              height -= range.y;\n              top += range.y;\n            }\n          }\n\n          if (width < 0 && height < 0) {\n            action = ACTION_SOUTH_WEST;\n            height = -height;\n            width = -width;\n            top -= height;\n            left -= width;\n          } else if (width < 0) {\n            action = ACTION_NORTH_WEST;\n            width = -width;\n            left -= width;\n          } else if (height < 0) {\n            action = ACTION_SOUTH_EAST;\n            height = -height;\n            top -= height;\n          }\n\n          break;\n\n        case ACTION_NORTH_WEST:\n          if (aspectRatio) {\n            if (range.y <= 0 && (top <= minTop || left <= minLeft)) {\n              renderable = false;\n              break;\n            }\n\n            check(ACTION_NORTH);\n            height -= range.y;\n            top += range.y;\n            width = height * aspectRatio;\n            left += cropBoxData.width - width;\n          } else {\n            check(ACTION_NORTH);\n            check(ACTION_WEST);\n\n            if (range.x <= 0) {\n              if (left > minLeft) {\n                width -= range.x;\n                left += range.x;\n              } else if (range.y <= 0 && top <= minTop) {\n                renderable = false;\n              }\n            } else {\n              width -= range.x;\n              left += range.x;\n            }\n\n            if (range.y <= 0) {\n              if (top > minTop) {\n                height -= range.y;\n                top += range.y;\n              }\n            } else {\n              height -= range.y;\n              top += range.y;\n            }\n          }\n\n          if (width < 0 && height < 0) {\n            action = ACTION_SOUTH_EAST;\n            height = -height;\n            width = -width;\n            top -= height;\n            left -= width;\n          } else if (width < 0) {\n            action = ACTION_NORTH_EAST;\n            width = -width;\n            left -= width;\n          } else if (height < 0) {\n            action = ACTION_SOUTH_WEST;\n            height = -height;\n            top -= height;\n          }\n\n          break;\n\n        case ACTION_SOUTH_WEST:\n          if (aspectRatio) {\n            if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) {\n              renderable = false;\n              break;\n            }\n\n            check(ACTION_WEST);\n            width -= range.x;\n            left += range.x;\n            height = width / aspectRatio;\n          } else {\n            check(ACTION_SOUTH);\n            check(ACTION_WEST);\n\n            if (range.x <= 0) {\n              if (left > minLeft) {\n                width -= range.x;\n                left += range.x;\n              } else if (range.y >= 0 && bottom >= maxHeight) {\n                renderable = false;\n              }\n            } else {\n              width -= range.x;\n              left += range.x;\n            }\n\n            if (range.y >= 0) {\n              if (bottom < maxHeight) {\n                height += range.y;\n              }\n            } else {\n              height += range.y;\n            }\n          }\n\n          if (width < 0 && height < 0) {\n            action = ACTION_NORTH_EAST;\n            height = -height;\n            width = -width;\n            top -= height;\n            left -= width;\n          } else if (width < 0) {\n            action = ACTION_SOUTH_EAST;\n            width = -width;\n            left -= width;\n          } else if (height < 0) {\n            action = ACTION_NORTH_WEST;\n            height = -height;\n            top -= height;\n          }\n\n          break;\n\n        case ACTION_SOUTH_EAST:\n          if (aspectRatio) {\n            if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) {\n              renderable = false;\n              break;\n            }\n\n            check(ACTION_EAST);\n            width += range.x;\n            height = width / aspectRatio;\n          } else {\n            check(ACTION_SOUTH);\n            check(ACTION_EAST);\n\n            if (range.x >= 0) {\n              if (right < maxWidth) {\n                width += range.x;\n              } else if (range.y >= 0 && bottom >= maxHeight) {\n                renderable = false;\n              }\n            } else {\n              width += range.x;\n            }\n\n            if (range.y >= 0) {\n              if (bottom < maxHeight) {\n                height += range.y;\n              }\n            } else {\n              height += range.y;\n            }\n          }\n\n          if (width < 0 && height < 0) {\n            action = ACTION_NORTH_WEST;\n            height = -height;\n            width = -width;\n            top -= height;\n            left -= width;\n          } else if (width < 0) {\n            action = ACTION_SOUTH_WEST;\n            width = -width;\n            left -= width;\n          } else if (height < 0) {\n            action = ACTION_NORTH_EAST;\n            height = -height;\n            top -= height;\n          }\n\n          break;\n        // Move canvas\n\n        case ACTION_MOVE:\n          this.move(range.x, range.y);\n          renderable = false;\n          break;\n        // Zoom canvas\n\n        case ACTION_ZOOM:\n          this.zoom(getMaxZoomRatio(pointers), event);\n          renderable = false;\n          break;\n        // Create crop box\n\n        case ACTION_CROP:\n          if (!range.x || !range.y) {\n            renderable = false;\n            break;\n          }\n\n          offset = getOffset(this.cropper);\n          left = pointer.startX - offset.left;\n          top = pointer.startY - offset.top;\n          width = cropBoxData.minWidth;\n          height = cropBoxData.minHeight;\n\n          if (range.x > 0) {\n            action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST;\n          } else if (range.x < 0) {\n            left -= width;\n            action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST;\n          }\n\n          if (range.y < 0) {\n            top -= height;\n          } // Show the crop box if is hidden\n\n\n          if (!this.cropped) {\n            removeClass(this.cropBox, CLASS_HIDDEN);\n            this.cropped = true;\n\n            if (this.limited) {\n              this.limitCropBox(true, true);\n            }\n          }\n\n          break;\n      }\n\n      if (renderable) {\n        cropBoxData.width = width;\n        cropBoxData.height = height;\n        cropBoxData.left = left;\n        cropBoxData.top = top;\n        this.action = action;\n        this.renderCropBox();\n      } // Override\n\n\n      forEach(pointers, function (p) {\n        p.startX = p.endX;\n        p.startY = p.endY;\n      });\n    }\n  };\n\n  var methods = {\n    // Show the crop box manually\n    crop: function crop() {\n      if (this.ready && !this.cropped && !this.disabled) {\n        this.cropped = true;\n        this.limitCropBox(true, true);\n\n        if (this.options.modal) {\n          addClass(this.dragBox, CLASS_MODAL);\n        }\n\n        removeClass(this.cropBox, CLASS_HIDDEN);\n        this.setCropBoxData(this.initialCropBoxData);\n      }\n\n      return this;\n    },\n    // Reset the image and crop box to their initial states\n    reset: function reset() {\n      if (this.ready && !this.disabled) {\n        this.imageData = assign({}, this.initialImageData);\n        this.canvasData = assign({}, this.initialCanvasData);\n        this.cropBoxData = assign({}, this.initialCropBoxData);\n        this.renderCanvas();\n\n        if (this.cropped) {\n          this.renderCropBox();\n        }\n      }\n\n      return this;\n    },\n    // Clear the crop box\n    clear: function clear() {\n      if (this.cropped && !this.disabled) {\n        assign(this.cropBoxData, {\n          left: 0,\n          top: 0,\n          width: 0,\n          height: 0\n        });\n        this.cropped = false;\n        this.renderCropBox();\n        this.limitCanvas(true, true); // Render canvas after crop box rendered\n\n        this.renderCanvas();\n        removeClass(this.dragBox, CLASS_MODAL);\n        addClass(this.cropBox, CLASS_HIDDEN);\n      }\n\n      return this;\n    },\n\n    /**\n     * Replace the image's src and rebuild the cropper\n     * @param {string} url - The new URL.\n     * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one.\n     * @returns {Cropper} this\n     */\n    replace: function replace(url) {\n      var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n      if (!this.disabled && url) {\n        if (this.isImg) {\n          this.element.src = url;\n        }\n\n        if (hasSameSize) {\n          this.url = url;\n          this.image.src = url;\n\n          if (this.ready) {\n            this.viewBoxImage.src = url;\n            forEach(this.previews, function (element) {\n              element.getElementsByTagName('img')[0].src = url;\n            });\n          }\n        } else {\n          if (this.isImg) {\n            this.replaced = true;\n          }\n\n          this.options.data = null;\n          this.uncreate();\n          this.load(url);\n        }\n      }\n\n      return this;\n    },\n    // Enable (unfreeze) the cropper\n    enable: function enable() {\n      if (this.ready && this.disabled) {\n        this.disabled = false;\n        removeClass(this.cropper, CLASS_DISABLED);\n      }\n\n      return this;\n    },\n    // Disable (freeze) the cropper\n    disable: function disable() {\n      if (this.ready && !this.disabled) {\n        this.disabled = true;\n        addClass(this.cropper, CLASS_DISABLED);\n      }\n\n      return this;\n    },\n\n    /**\n     * Destroy the cropper and remove the instance from the image\n     * @returns {Cropper} this\n     */\n    destroy: function destroy() {\n      var element = this.element;\n\n      if (!element[NAMESPACE]) {\n        return this;\n      }\n\n      element[NAMESPACE] = undefined;\n\n      if (this.isImg && this.replaced) {\n        element.src = this.originalUrl;\n      }\n\n      this.uncreate();\n      return this;\n    },\n\n    /**\n     * Move the canvas with relative offsets\n     * @param {number} offsetX - The relative offset distance on the x-axis.\n     * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis.\n     * @returns {Cropper} this\n     */\n    move: function move(offsetX) {\n      var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX;\n      var _this$canvasData = this.canvasData,\n          left = _this$canvasData.left,\n          top = _this$canvasData.top;\n      return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY));\n    },\n\n    /**\n     * Move the canvas to an absolute point\n     * @param {number} x - The x-axis coordinate.\n     * @param {number} [y=x] - The y-axis coordinate.\n     * @returns {Cropper} this\n     */\n    moveTo: function moveTo(x) {\n      var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;\n      var canvasData = this.canvasData;\n      var changed = false;\n      x = Number(x);\n      y = Number(y);\n\n      if (this.ready && !this.disabled && this.options.movable) {\n        if (isNumber(x)) {\n          canvasData.left = x;\n          changed = true;\n        }\n\n        if (isNumber(y)) {\n          canvasData.top = y;\n          changed = true;\n        }\n\n        if (changed) {\n          this.renderCanvas(true);\n        }\n      }\n\n      return this;\n    },\n\n    /**\n     * Zoom the canvas with a relative ratio\n     * @param {number} ratio - The target ratio.\n     * @param {Event} _originalEvent - The original event if any.\n     * @returns {Cropper} this\n     */\n    zoom: function zoom(ratio, _originalEvent) {\n      var canvasData = this.canvasData;\n      ratio = Number(ratio);\n\n      if (ratio < 0) {\n        ratio = 1 / (1 - ratio);\n      } else {\n        ratio = 1 + ratio;\n      }\n\n      return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent);\n    },\n\n    /**\n     * Zoom the canvas to an absolute ratio\n     * @param {number} ratio - The target ratio.\n     * @param {Object} pivot - The zoom pivot point coordinate.\n     * @param {Event} _originalEvent - The original event if any.\n     * @returns {Cropper} this\n     */\n    zoomTo: function zoomTo(ratio, pivot, _originalEvent) {\n      var options = this.options,\n          canvasData = this.canvasData;\n      var width = canvasData.width,\n          height = canvasData.height,\n          naturalWidth = canvasData.naturalWidth,\n          naturalHeight = canvasData.naturalHeight;\n      ratio = Number(ratio);\n\n      if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) {\n        var newWidth = naturalWidth * ratio;\n        var newHeight = naturalHeight * ratio;\n\n        if (dispatchEvent(this.element, EVENT_ZOOM, {\n          ratio: ratio,\n          oldRatio: width / naturalWidth,\n          originalEvent: _originalEvent\n        }) === false) {\n          return this;\n        }\n\n        if (_originalEvent) {\n          var pointers = this.pointers;\n          var offset = getOffset(this.cropper);\n          var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : {\n            pageX: _originalEvent.pageX,\n            pageY: _originalEvent.pageY\n          }; // Zoom from the triggering point of the event\n\n          canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width);\n          canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height);\n        } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) {\n          canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width);\n          canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height);\n        } else {\n          // Zoom from the center of the canvas\n          canvasData.left -= (newWidth - width) / 2;\n          canvasData.top -= (newHeight - height) / 2;\n        }\n\n        canvasData.width = newWidth;\n        canvasData.height = newHeight;\n        this.renderCanvas(true);\n      }\n\n      return this;\n    },\n\n    /**\n     * Rotate the canvas with a relative degree\n     * @param {number} degree - The rotate degree.\n     * @returns {Cropper} this\n     */\n    rotate: function rotate(degree) {\n      return this.rotateTo((this.imageData.rotate || 0) + Number(degree));\n    },\n\n    /**\n     * Rotate the canvas to an absolute degree\n     * @param {number} degree - The rotate degree.\n     * @returns {Cropper} this\n     */\n    rotateTo: function rotateTo(degree) {\n      degree = Number(degree);\n\n      if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) {\n        this.imageData.rotate = degree % 360;\n        this.renderCanvas(true, true);\n      }\n\n      return this;\n    },\n\n    /**\n     * Scale the image on the x-axis.\n     * @param {number} scaleX - The scale ratio on the x-axis.\n     * @returns {Cropper} this\n     */\n    scaleX: function scaleX(_scaleX) {\n      var scaleY = this.imageData.scaleY;\n      return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1);\n    },\n\n    /**\n     * Scale the image on the y-axis.\n     * @param {number} scaleY - The scale ratio on the y-axis.\n     * @returns {Cropper} this\n     */\n    scaleY: function scaleY(_scaleY) {\n      var scaleX = this.imageData.scaleX;\n      return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY);\n    },\n\n    /**\n     * Scale the image\n     * @param {number} scaleX - The scale ratio on the x-axis.\n     * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis.\n     * @returns {Cropper} this\n     */\n    scale: function scale(scaleX) {\n      var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;\n      var imageData = this.imageData;\n      var transformed = false;\n      scaleX = Number(scaleX);\n      scaleY = Number(scaleY);\n\n      if (this.ready && !this.disabled && this.options.scalable) {\n        if (isNumber(scaleX)) {\n          imageData.scaleX = scaleX;\n          transformed = true;\n        }\n\n        if (isNumber(scaleY)) {\n          imageData.scaleY = scaleY;\n          transformed = true;\n        }\n\n        if (transformed) {\n          this.renderCanvas(true, true);\n        }\n      }\n\n      return this;\n    },\n\n    /**\n     * Get the cropped area position and size data (base on the original image)\n     * @param {boolean} [rounded=false] - Indicate if round the data values or not.\n     * @returns {Object} The result cropped data.\n     */\n    getData: function getData() {\n      var rounded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n      var options = this.options,\n          imageData = this.imageData,\n          canvasData = this.canvasData,\n          cropBoxData = this.cropBoxData;\n      var data;\n\n      if (this.ready && this.cropped) {\n        data = {\n          x: cropBoxData.left - canvasData.left,\n          y: cropBoxData.top - canvasData.top,\n          width: cropBoxData.width,\n          height: cropBoxData.height\n        };\n        var ratio = imageData.width / imageData.naturalWidth;\n        forEach(data, function (n, i) {\n          data[i] = n / ratio;\n        });\n\n        if (rounded) {\n          // In case rounding off leads to extra 1px in right or bottom border\n          // we should round the top-left corner and the dimension (#343).\n          var bottom = Math.round(data.y + data.height);\n          var right = Math.round(data.x + data.width);\n          data.x = Math.round(data.x);\n          data.y = Math.round(data.y);\n          data.width = right - data.x;\n          data.height = bottom - data.y;\n        }\n      } else {\n        data = {\n          x: 0,\n          y: 0,\n          width: 0,\n          height: 0\n        };\n      }\n\n      if (options.rotatable) {\n        data.rotate = imageData.rotate || 0;\n      }\n\n      if (options.scalable) {\n        data.scaleX = imageData.scaleX || 1;\n        data.scaleY = imageData.scaleY || 1;\n      }\n\n      return data;\n    },\n\n    /**\n     * Set the cropped area position and size with new data\n     * @param {Object} data - The new data.\n     * @returns {Cropper} this\n     */\n    setData: function setData(data) {\n      var options = this.options,\n          imageData = this.imageData,\n          canvasData = this.canvasData;\n      var cropBoxData = {};\n\n      if (this.ready && !this.disabled && isPlainObject(data)) {\n        var transformed = false;\n\n        if (options.rotatable) {\n          if (isNumber(data.rotate) && data.rotate !== imageData.rotate) {\n            imageData.rotate = data.rotate;\n            transformed = true;\n          }\n        }\n\n        if (options.scalable) {\n          if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) {\n            imageData.scaleX = data.scaleX;\n            transformed = true;\n          }\n\n          if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) {\n            imageData.scaleY = data.scaleY;\n            transformed = true;\n          }\n        }\n\n        if (transformed) {\n          this.renderCanvas(true, true);\n        }\n\n        var ratio = imageData.width / imageData.naturalWidth;\n\n        if (isNumber(data.x)) {\n          cropBoxData.left = data.x * ratio + canvasData.left;\n        }\n\n        if (isNumber(data.y)) {\n          cropBoxData.top = data.y * ratio + canvasData.top;\n        }\n\n        if (isNumber(data.width)) {\n          cropBoxData.width = data.width * ratio;\n        }\n\n        if (isNumber(data.height)) {\n          cropBoxData.height = data.height * ratio;\n        }\n\n        this.setCropBoxData(cropBoxData);\n      }\n\n      return this;\n    },\n\n    /**\n     * Get the container size data.\n     * @returns {Object} The result container data.\n     */\n    getContainerData: function getContainerData() {\n      return this.ready ? assign({}, this.containerData) : {};\n    },\n\n    /**\n     * Get the image position and size data.\n     * @returns {Object} The result image data.\n     */\n    getImageData: function getImageData() {\n      return this.sized ? assign({}, this.imageData) : {};\n    },\n\n    /**\n     * Get the canvas position and size data.\n     * @returns {Object} The result canvas data.\n     */\n    getCanvasData: function getCanvasData() {\n      var canvasData = this.canvasData;\n      var data = {};\n\n      if (this.ready) {\n        forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) {\n          data[n] = canvasData[n];\n        });\n      }\n\n      return data;\n    },\n\n    /**\n     * Set the canvas position and size with new data.\n     * @param {Object} data - The new canvas data.\n     * @returns {Cropper} this\n     */\n    setCanvasData: function setCanvasData(data) {\n      var canvasData = this.canvasData;\n      var aspectRatio = canvasData.aspectRatio;\n\n      if (this.ready && !this.disabled && isPlainObject(data)) {\n        if (isNumber(data.left)) {\n          canvasData.left = data.left;\n        }\n\n        if (isNumber(data.top)) {\n          canvasData.top = data.top;\n        }\n\n        if (isNumber(data.width)) {\n          canvasData.width = data.width;\n          canvasData.height = data.width / aspectRatio;\n        } else if (isNumber(data.height)) {\n          canvasData.height = data.height;\n          canvasData.width = data.height * aspectRatio;\n        }\n\n        this.renderCanvas(true);\n      }\n\n      return this;\n    },\n\n    /**\n     * Get the crop box position and size data.\n     * @returns {Object} The result crop box data.\n     */\n    getCropBoxData: function getCropBoxData() {\n      var cropBoxData = this.cropBoxData;\n      var data;\n\n      if (this.ready && this.cropped) {\n        data = {\n          left: cropBoxData.left,\n          top: cropBoxData.top,\n          width: cropBoxData.width,\n          height: cropBoxData.height\n        };\n      }\n\n      return data || {};\n    },\n\n    /**\n     * Set the crop box position and size with new data.\n     * @param {Object} data - The new crop box data.\n     * @returns {Cropper} this\n     */\n    setCropBoxData: function setCropBoxData(data) {\n      var cropBoxData = this.cropBoxData;\n      var aspectRatio = this.options.aspectRatio;\n      var widthChanged;\n      var heightChanged;\n\n      if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) {\n        if (isNumber(data.left)) {\n          cropBoxData.left = data.left;\n        }\n\n        if (isNumber(data.top)) {\n          cropBoxData.top = data.top;\n        }\n\n        if (isNumber(data.width) && data.width !== cropBoxData.width) {\n          widthChanged = true;\n          cropBoxData.width = data.width;\n        }\n\n        if (isNumber(data.height) && data.height !== cropBoxData.height) {\n          heightChanged = true;\n          cropBoxData.height = data.height;\n        }\n\n        if (aspectRatio) {\n          if (widthChanged) {\n            cropBoxData.height = cropBoxData.width / aspectRatio;\n          } else if (heightChanged) {\n            cropBoxData.width = cropBoxData.height * aspectRatio;\n          }\n        }\n\n        this.renderCropBox();\n      }\n\n      return this;\n    },\n\n    /**\n     * Get a canvas drawn the cropped image.\n     * @param {Object} [options={}] - The config options.\n     * @returns {HTMLCanvasElement} - The result canvas.\n     */\n    getCroppedCanvas: function getCroppedCanvas() {\n      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n      if (!this.ready || !window.HTMLCanvasElement) {\n        return null;\n      }\n\n      var canvasData = this.canvasData;\n      var source = getSourceCanvas(this.image, this.imageData, canvasData, options); // Returns the source canvas if it is not cropped.\n\n      if (!this.cropped) {\n        return source;\n      }\n\n      var _this$getData = this.getData(),\n          initialX = _this$getData.x,\n          initialY = _this$getData.y,\n          initialWidth = _this$getData.width,\n          initialHeight = _this$getData.height;\n\n      var ratio = source.width / Math.floor(canvasData.naturalWidth);\n\n      if (ratio !== 1) {\n        initialX *= ratio;\n        initialY *= ratio;\n        initialWidth *= ratio;\n        initialHeight *= ratio;\n      }\n\n      var aspectRatio = initialWidth / initialHeight;\n      var maxSizes = getAdjustedSizes({\n        aspectRatio: aspectRatio,\n        width: options.maxWidth || Infinity,\n        height: options.maxHeight || Infinity\n      });\n      var minSizes = getAdjustedSizes({\n        aspectRatio: aspectRatio,\n        width: options.minWidth || 0,\n        height: options.minHeight || 0\n      }, 'cover');\n\n      var _getAdjustedSizes = getAdjustedSizes({\n        aspectRatio: aspectRatio,\n        width: options.width || (ratio !== 1 ? source.width : initialWidth),\n        height: options.height || (ratio !== 1 ? source.height : initialHeight)\n      }),\n          width = _getAdjustedSizes.width,\n          height = _getAdjustedSizes.height;\n\n      width = Math.min(maxSizes.width, Math.max(minSizes.width, width));\n      height = Math.min(maxSizes.height, Math.max(minSizes.height, height));\n      var canvas = document.createElement('canvas');\n      var context = canvas.getContext('2d');\n      canvas.width = normalizeDecimalNumber(width);\n      canvas.height = normalizeDecimalNumber(height);\n      context.fillStyle = options.fillColor || 'transparent';\n      context.fillRect(0, 0, width, height);\n      var _options$imageSmoothi = options.imageSmoothingEnabled,\n          imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi,\n          imageSmoothingQuality = options.imageSmoothingQuality;\n      context.imageSmoothingEnabled = imageSmoothingEnabled;\n\n      if (imageSmoothingQuality) {\n        context.imageSmoothingQuality = imageSmoothingQuality;\n      } // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage\n\n\n      var sourceWidth = source.width;\n      var sourceHeight = source.height; // Source canvas parameters\n\n      var srcX = initialX;\n      var srcY = initialY;\n      var srcWidth;\n      var srcHeight; // Destination canvas parameters\n\n      var dstX;\n      var dstY;\n      var dstWidth;\n      var dstHeight;\n\n      if (srcX <= -initialWidth || srcX > sourceWidth) {\n        srcX = 0;\n        srcWidth = 0;\n        dstX = 0;\n        dstWidth = 0;\n      } else if (srcX <= 0) {\n        dstX = -srcX;\n        srcX = 0;\n        srcWidth = Math.min(sourceWidth, initialWidth + srcX);\n        dstWidth = srcWidth;\n      } else if (srcX <= sourceWidth) {\n        dstX = 0;\n        srcWidth = Math.min(initialWidth, sourceWidth - srcX);\n        dstWidth = srcWidth;\n      }\n\n      if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) {\n        srcY = 0;\n        srcHeight = 0;\n        dstY = 0;\n        dstHeight = 0;\n      } else if (srcY <= 0) {\n        dstY = -srcY;\n        srcY = 0;\n        srcHeight = Math.min(sourceHeight, initialHeight + srcY);\n        dstHeight = srcHeight;\n      } else if (srcY <= sourceHeight) {\n        dstY = 0;\n        srcHeight = Math.min(initialHeight, sourceHeight - srcY);\n        dstHeight = srcHeight;\n      }\n\n      var params = [srcX, srcY, srcWidth, srcHeight]; // Avoid \"IndexSizeError\"\n\n      if (dstWidth > 0 && dstHeight > 0) {\n        var scale = width / initialWidth;\n        params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale);\n      } // All the numerical parameters should be integer for `drawImage`\n      // https://github.com/fengyuanchen/cropper/issues/476\n\n\n      context.drawImage.apply(context, [source].concat(_toConsumableArray(params.map(function (param) {\n        return Math.floor(normalizeDecimalNumber(param));\n      }))));\n      return canvas;\n    },\n\n    /**\n     * Change the aspect ratio of the crop box.\n     * @param {number} aspectRatio - The new aspect ratio.\n     * @returns {Cropper} this\n     */\n    setAspectRatio: function setAspectRatio(aspectRatio) {\n      var options = this.options;\n\n      if (!this.disabled && !isUndefined(aspectRatio)) {\n        // 0 -> NaN\n        options.aspectRatio = Math.max(0, aspectRatio) || NaN;\n\n        if (this.ready) {\n          this.initCropBox();\n\n          if (this.cropped) {\n            this.renderCropBox();\n          }\n        }\n      }\n\n      return this;\n    },\n\n    /**\n     * Change the drag mode.\n     * @param {string} mode - The new drag mode.\n     * @returns {Cropper} this\n     */\n    setDragMode: function setDragMode(mode) {\n      var options = this.options,\n          dragBox = this.dragBox,\n          face = this.face;\n\n      if (this.ready && !this.disabled) {\n        var croppable = mode === DRAG_MODE_CROP;\n        var movable = options.movable && mode === DRAG_MODE_MOVE;\n        mode = croppable || movable ? mode : DRAG_MODE_NONE;\n        options.dragMode = mode;\n        setData(dragBox, DATA_ACTION, mode);\n        toggleClass(dragBox, CLASS_CROP, croppable);\n        toggleClass(dragBox, CLASS_MOVE, movable);\n\n        if (!options.cropBoxMovable) {\n          // Sync drag mode to crop box when it is not movable\n          setData(face, DATA_ACTION, mode);\n          toggleClass(face, CLASS_CROP, croppable);\n          toggleClass(face, CLASS_MOVE, movable);\n        }\n      }\n\n      return this;\n    }\n  };\n\n  var AnotherCropper = WINDOW.Cropper;\n\n  var Cropper = /*#__PURE__*/function () {\n    /**\n     * Create a new Cropper.\n     * @param {Element} element - The target element for cropping.\n     * @param {Object} [options={}] - The configuration options.\n     */\n    function Cropper(element) {\n      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n      _classCallCheck(this, Cropper);\n\n      if (!element || !REGEXP_TAG_NAME.test(element.tagName)) {\n        throw new Error('The first argument is required and must be an <img> or <canvas> element.');\n      }\n\n      this.element = element;\n      this.options = assign({}, DEFAULTS, isPlainObject(options) && options);\n      this.cropped = false;\n      this.disabled = false;\n      this.pointers = {};\n      this.ready = false;\n      this.reloading = false;\n      this.replaced = false;\n      this.sized = false;\n      this.sizing = false;\n      this.init();\n    }\n\n    _createClass(Cropper, [{\n      key: \"init\",\n      value: function init() {\n        var element = this.element;\n        var tagName = element.tagName.toLowerCase();\n        var url;\n\n        if (element[NAMESPACE]) {\n          return;\n        }\n\n        element[NAMESPACE] = this;\n\n        if (tagName === 'img') {\n          this.isImg = true; // e.g.: \"img/picture.jpg\"\n\n          url = element.getAttribute('src') || '';\n          this.originalUrl = url; // Stop when it's a blank image\n\n          if (!url) {\n            return;\n          } // e.g.: \"https://example.com/img/picture.jpg\"\n\n\n          url = element.src;\n        } else if (tagName === 'canvas' && window.HTMLCanvasElement) {\n          url = element.toDataURL();\n        }\n\n        this.load(url);\n      }\n    }, {\n      key: \"load\",\n      value: function load(url) {\n        var _this = this;\n\n        if (!url) {\n          return;\n        }\n\n        this.url = url;\n        this.imageData = {};\n        var element = this.element,\n            options = this.options;\n\n        if (!options.rotatable && !options.scalable) {\n          options.checkOrientation = false;\n        } // Only IE10+ supports Typed Arrays\n\n\n        if (!options.checkOrientation || !window.ArrayBuffer) {\n          this.clone();\n          return;\n        } // Detect the mime type of the image directly if it is a Data URL\n\n\n        if (REGEXP_DATA_URL.test(url)) {\n          // Read ArrayBuffer from Data URL of JPEG images directly for better performance\n          if (REGEXP_DATA_URL_JPEG.test(url)) {\n            this.read(dataURLToArrayBuffer(url));\n          } else {\n            // Only a JPEG image may contains Exif Orientation information,\n            // the rest types of Data URLs are not necessary to check orientation at all.\n            this.clone();\n          }\n\n          return;\n        } // 1. Detect the mime type of the image by a XMLHttpRequest.\n        // 2. Load the image as ArrayBuffer for reading orientation if its a JPEG image.\n\n\n        var xhr = new XMLHttpRequest();\n        var clone = this.clone.bind(this);\n        this.reloading = true;\n        this.xhr = xhr; // 1. Cross origin requests are only supported for protocol schemes:\n        // http, https, data, chrome, chrome-extension.\n        // 2. Access to XMLHttpRequest from a Data URL will be blocked by CORS policy\n        // in some browsers as IE11 and Safari.\n\n        xhr.onabort = clone;\n        xhr.onerror = clone;\n        xhr.ontimeout = clone;\n\n        xhr.onprogress = function () {\n          // Abort the request directly if it not a JPEG image for better performance\n          if (xhr.getResponseHeader('content-type') !== MIME_TYPE_JPEG) {\n            xhr.abort();\n          }\n        };\n\n        xhr.onload = function () {\n          _this.read(xhr.response);\n        };\n\n        xhr.onloadend = function () {\n          _this.reloading = false;\n          _this.xhr = null;\n        }; // Bust cache when there is a \"crossOrigin\" property to avoid browser cache error\n\n\n        if (options.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) {\n          url = addTimestamp(url);\n        }\n\n        xhr.open('GET', url);\n        xhr.responseType = 'arraybuffer';\n        xhr.withCredentials = element.crossOrigin === 'use-credentials';\n        xhr.send();\n      }\n    }, {\n      key: \"read\",\n      value: function read(arrayBuffer) {\n        var options = this.options,\n            imageData = this.imageData; // Reset the orientation value to its default value 1\n        // as some iOS browsers will render image with its orientation\n\n        var orientation = resetAndGetOrientation(arrayBuffer);\n        var rotate = 0;\n        var scaleX = 1;\n        var scaleY = 1;\n\n        if (orientation > 1) {\n          // Generate a new URL which has the default orientation value\n          this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG);\n\n          var _parseOrientation = parseOrientation(orientation);\n\n          rotate = _parseOrientation.rotate;\n          scaleX = _parseOrientation.scaleX;\n          scaleY = _parseOrientation.scaleY;\n        }\n\n        if (options.rotatable) {\n          imageData.rotate = rotate;\n        }\n\n        if (options.scalable) {\n          imageData.scaleX = scaleX;\n          imageData.scaleY = scaleY;\n        }\n\n        this.clone();\n      }\n    }, {\n      key: \"clone\",\n      value: function clone() {\n        var element = this.element,\n            url = this.url;\n        var crossOrigin = element.crossOrigin;\n        var crossOriginUrl = url;\n\n        if (this.options.checkCrossOrigin && isCrossOriginURL(url)) {\n          if (!crossOrigin) {\n            crossOrigin = 'anonymous';\n          } // Bust cache when there is not a \"crossOrigin\" property (#519)\n\n\n          crossOriginUrl = addTimestamp(url);\n        }\n\n        this.crossOrigin = crossOrigin;\n        this.crossOriginUrl = crossOriginUrl;\n        var image = document.createElement('img');\n\n        if (crossOrigin) {\n          image.crossOrigin = crossOrigin;\n        }\n\n        image.src = crossOriginUrl || url;\n        image.alt = element.alt || 'The image to crop';\n        this.image = image;\n        image.onload = this.start.bind(this);\n        image.onerror = this.stop.bind(this);\n        addClass(image, CLASS_HIDE);\n        element.parentNode.insertBefore(image, element.nextSibling);\n      }\n    }, {\n      key: \"start\",\n      value: function start() {\n        var _this2 = this;\n\n        var image = this.image;\n        image.onload = null;\n        image.onerror = null;\n        this.sizing = true; // Match all browsers that use WebKit as the layout engine in iOS devices,\n        // such as Safari for iOS, Chrome for iOS, and in-app browsers.\n\n        var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent);\n\n        var done = function done(naturalWidth, naturalHeight) {\n          assign(_this2.imageData, {\n            naturalWidth: naturalWidth,\n            naturalHeight: naturalHeight,\n            aspectRatio: naturalWidth / naturalHeight\n          });\n          _this2.sizing = false;\n          _this2.sized = true;\n\n          _this2.build();\n        }; // Most modern browsers (excepts iOS WebKit)\n\n\n        if (image.naturalWidth && !isIOSWebKit) {\n          done(image.naturalWidth, image.naturalHeight);\n          return;\n        }\n\n        var sizingImage = document.createElement('img');\n        var body = document.body || document.documentElement;\n        this.sizingImage = sizingImage;\n\n        sizingImage.onload = function () {\n          done(sizingImage.width, sizingImage.height);\n\n          if (!isIOSWebKit) {\n            body.removeChild(sizingImage);\n          }\n        };\n\n        sizingImage.src = image.src; // iOS WebKit will convert the image automatically\n        // with its orientation once append it into DOM (#279)\n\n        if (!isIOSWebKit) {\n          sizingImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';\n          body.appendChild(sizingImage);\n        }\n      }\n    }, {\n      key: \"stop\",\n      value: function stop() {\n        var image = this.image;\n        image.onload = null;\n        image.onerror = null;\n        image.parentNode.removeChild(image);\n        this.image = null;\n      }\n    }, {\n      key: \"build\",\n      value: function build() {\n        if (!this.sized || this.ready) {\n          return;\n        }\n\n        var element = this.element,\n            options = this.options,\n            image = this.image; // Create cropper elements\n\n        var container = element.parentNode;\n        var template = document.createElement('div');\n        template.innerHTML = TEMPLATE;\n        var cropper = template.querySelector(\".\".concat(NAMESPACE, \"-container\"));\n        var canvas = cropper.querySelector(\".\".concat(NAMESPACE, \"-canvas\"));\n        var dragBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-drag-box\"));\n        var cropBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-crop-box\"));\n        var face = cropBox.querySelector(\".\".concat(NAMESPACE, \"-face\"));\n        this.container = container;\n        this.cropper = cropper;\n        this.canvas = canvas;\n        this.dragBox = dragBox;\n        this.cropBox = cropBox;\n        this.viewBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-view-box\"));\n        this.face = face;\n        canvas.appendChild(image); // Hide the original image\n\n        addClass(element, CLASS_HIDDEN); // Inserts the cropper after to the current image\n\n        container.insertBefore(cropper, element.nextSibling); // Show the image if is hidden\n\n        if (!this.isImg) {\n          removeClass(image, CLASS_HIDE);\n        }\n\n        this.initPreview();\n        this.bind();\n        options.initialAspectRatio = Math.max(0, options.initialAspectRatio) || NaN;\n        options.aspectRatio = Math.max(0, options.aspectRatio) || NaN;\n        options.viewMode = Math.max(0, Math.min(3, Math.round(options.viewMode))) || 0;\n        addClass(cropBox, CLASS_HIDDEN);\n\n        if (!options.guides) {\n          addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-dashed\")), CLASS_HIDDEN);\n        }\n\n        if (!options.center) {\n          addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-center\")), CLASS_HIDDEN);\n        }\n\n        if (options.background) {\n          addClass(cropper, \"\".concat(NAMESPACE, \"-bg\"));\n        }\n\n        if (!options.highlight) {\n          addClass(face, CLASS_INVISIBLE);\n        }\n\n        if (options.cropBoxMovable) {\n          addClass(face, CLASS_MOVE);\n          setData(face, DATA_ACTION, ACTION_ALL);\n        }\n\n        if (!options.cropBoxResizable) {\n          addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-line\")), CLASS_HIDDEN);\n          addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-point\")), CLASS_HIDDEN);\n        }\n\n        this.render();\n        this.ready = true;\n        this.setDragMode(options.dragMode);\n\n        if (options.autoCrop) {\n          this.crop();\n        }\n\n        this.setData(options.data);\n\n        if (isFunction(options.ready)) {\n          addListener(element, EVENT_READY, options.ready, {\n            once: true\n          });\n        }\n\n        dispatchEvent(element, EVENT_READY);\n      }\n    }, {\n      key: \"unbuild\",\n      value: function unbuild() {\n        if (!this.ready) {\n          return;\n        }\n\n        this.ready = false;\n        this.unbind();\n        this.resetPreview();\n        this.cropper.parentNode.removeChild(this.cropper);\n        removeClass(this.element, CLASS_HIDDEN);\n      }\n    }, {\n      key: \"uncreate\",\n      value: function uncreate() {\n        if (this.ready) {\n          this.unbuild();\n          this.ready = false;\n          this.cropped = false;\n        } else if (this.sizing) {\n          this.sizingImage.onload = null;\n          this.sizing = false;\n          this.sized = false;\n        } else if (this.reloading) {\n          this.xhr.onabort = null;\n          this.xhr.abort();\n        } else if (this.image) {\n          this.stop();\n        }\n      }\n      /**\n       * Get the no conflict cropper class.\n       * @returns {Cropper} The cropper class.\n       */\n\n    }], [{\n      key: \"noConflict\",\n      value: function noConflict() {\n        window.Cropper = AnotherCropper;\n        return Cropper;\n      }\n      /**\n       * Change the default options.\n       * @param {Object} options - The new default options.\n       */\n\n    }, {\n      key: \"setDefaults\",\n      value: function setDefaults(options) {\n        assign(DEFAULTS, isPlainObject(options) && options);\n      }\n    }]);\n\n    return Cropper;\n  }();\n\n  assign(Cropper.prototype, render, preview, events, handlers, change, methods);\n\n  return Cropper;\n\n})));\n", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst Cropper = require(\"cropperjs\").default || require(\"cropperjs\");\n\nclass Editor extends _preact.Component {\n  constructor(props) {\n    super(props);\n\n    this.granularRotateOnChange = ev => {\n      const {\n        rotationAngle,\n        rotationDelta\n      } = this.state;\n      const pendingRotationDelta = Number(ev.target.value) - rotationDelta;\n      cancelAnimationFrame(this.granularRotateOnInputNextFrame);\n\n      if (pendingRotationDelta !== 0) {\n        const pendingRotationAngle = rotationAngle + pendingRotationDelta;\n        this.granularRotateOnInputNextFrame = requestAnimationFrame(() => {\n          this.cropper.rotateTo(pendingRotationAngle);\n        });\n      }\n    };\n\n    this.state = {\n      rotationAngle: 0,\n      rotationDelta: 0\n    };\n  }\n\n  componentDidMount() {\n    const {\n      opts,\n      storeCropperInstance\n    } = this.props;\n    this.cropper = new Cropper(this.imgElement, opts.cropperOptions);\n    storeCropperInstance(this.cropper);\n\n    if (opts.actions.granularRotate) {\n      this.imgElement.addEventListener('crop', ev => {\n        const rotationAngle = ev.detail.rotate;\n        this.setState({\n          rotationAngle,\n          // 405 == 360 + 45\n          rotationDelta: (rotationAngle + 405) % 90 - 45\n        });\n      });\n    }\n  }\n\n  componentWillUnmount() {\n    this.cropper.destroy();\n  }\n\n  renderGranularRotate() {\n    const {\n      i18n\n    } = this.props;\n    const {\n      rotationDelta,\n      rotationAngle\n    } = this.state;\n    return (// eslint-disable-next-line jsx-a11y/label-has-associated-control\n      (0, _preact.h)(\"label\", {\n        \"data-microtip-position\": \"top\",\n        role: \"tooltip\",\n        \"aria-label\": `${rotationAngle}\u00BA`,\n        className: \"uppy-ImageCropper-rangeWrapper uppy-u-reset\"\n      }, (0, _preact.h)(\"input\", {\n        className: \"uppy-ImageCropper-range uppy-u-reset\",\n        type: \"range\",\n        onInput: this.granularRotateOnChange,\n        onChange: this.granularRotateOnChange,\n        value: rotationDelta,\n        min: \"-45\",\n        max: \"44\",\n        \"aria-label\": i18n('rotate')\n      }))\n    );\n  }\n\n  renderRevert() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      \"aria-label\": i18n('revert'),\n      \"data-microtip-position\": \"top\",\n      onClick: () => {\n        this.cropper.reset();\n        this.cropper.setAspectRatio(0);\n      }\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0z\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z\"\n    })));\n  }\n\n  renderRotate() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      onClick: () => this.cropper.rotate(-90),\n      \"aria-label\": i18n('rotate'),\n      \"data-microtip-position\": \"top\"\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0V0zm0 0h24v24H0V0z\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M14 10a2 2 0 012 2v7a2 2 0 01-2 2H6a2 2 0 01-2-2v-7a2 2 0 012-2h8zm0 1.75H6a.25.25 0 00-.243.193L5.75 12v7a.25.25 0 00.193.243L6 19.25h8a.25.25 0 00.243-.193L14.25 19v-7a.25.25 0 00-.193-.243L14 11.75zM12 .76V4c2.3 0 4.61.88 6.36 2.64a8.95 8.95 0 012.634 6.025L21 13a1 1 0 01-1.993.117L19 13h-.003a6.979 6.979 0 00-2.047-4.95 6.97 6.97 0 00-4.652-2.044L12 6v3.24L7.76 5 12 .76z\"\n    })));\n  }\n\n  renderFlip() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      \"aria-label\": i18n('flipHorizontal'),\n      \"data-microtip-position\": \"top\",\n      onClick: () => this.cropper.scaleX(-this.cropper.getData().scaleX || -1)\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0z\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z\"\n    })));\n  }\n\n  renderZoomIn() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      \"aria-label\": i18n('zoomIn'),\n      \"data-microtip-position\": \"top\",\n      onClick: () => this.cropper.zoom(0.1)\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\",\n      width: \"24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0V0z\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M12 10h-2v2H9v-2H7V9h2V7h1v2h2v1z\"\n    })));\n  }\n\n  renderZoomOut() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      \"aria-label\": i18n('zoomOut'),\n      \"data-microtip-position\": \"top\",\n      onClick: () => this.cropper.zoom(-0.1)\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0V0z\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zM7 9h5v1H7z\"\n    })));\n  }\n\n  renderCropSquare() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      \"aria-label\": i18n('aspectRatioSquare'),\n      \"data-microtip-position\": \"top\",\n      onClick: () => this.cropper.setAspectRatio(1)\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0z\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z\"\n    })));\n  }\n\n  renderCropWidescreen() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      \"aria-label\": i18n('aspectRatioLandscape'),\n      \"data-microtip-position\": \"top\",\n      onClick: () => this.cropper.setAspectRatio(16 / 9)\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M 19,4.9999992 V 17.000001 H 4.9999998 V 6.9999992 H 19 m 0,-2 H 4.9999998 c -1.0999999,0 -1.9999999,0.9000001 -1.9999999,2 V 17.000001 c 0,1.1 0.9,2 1.9999999,2 H 19 c 1.1,0 2,-0.9 2,-2 V 6.9999992 c 0,-1.0999999 -0.9,-2 -2,-2 z\"\n    }), (0, _preact.h)(\"path\", {\n      fill: \"none\",\n      d: \"M0 0h24v24H0z\"\n    })));\n  }\n\n  renderCropWidescreenVertical() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"button\", {\n      type: \"button\",\n      className: \"uppy-u-reset uppy-c-btn\",\n      \"aria-label\": i18n('aspectRatioPortrait'),\n      \"data-microtip-position\": \"top\",\n      onClick: () => this.cropper.setAspectRatio(9 / 16)\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      className: \"uppy-c-icon\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M 19.000001,19 H 6.999999 V 5 h 10.000002 v 14 m 2,0 V 5 c 0,-1.0999999 -0.9,-1.9999999 -2,-1.9999999 H 6.999999 c -1.1,0 -2,0.9 -2,1.9999999 v 14 c 0,1.1 0.9,2 2,2 h 10.000002 c 1.1,0 2,-0.9 2,-2 z\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0z\",\n      fill: \"none\"\n    })));\n  }\n\n  render() {\n    const {\n      currentImage,\n      opts\n    } = this.props;\n    const {\n      actions\n    } = opts;\n    const imageURL = URL.createObjectURL(currentImage.data);\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-ImageCropper\"\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-ImageCropper-container\"\n    }, (0, _preact.h)(\"img\", {\n      className: \"uppy-ImageCropper-image\",\n      alt: currentImage.name,\n      src: imageURL,\n      ref: ref => {\n        this.imgElement = ref;\n      }\n    })), (0, _preact.h)(\"div\", {\n      className: \"uppy-ImageCropper-controls\"\n    }, actions.revert && this.renderRevert(), actions.rotate && this.renderRotate(), actions.granularRotate && this.renderGranularRotate(), actions.flip && this.renderFlip(), actions.zoomIn && this.renderZoomIn(), actions.zoomOut && this.renderZoomOut(), actions.cropSquare && this.renderCropSquare(), actions.cropWidescreen && this.renderCropWidescreen(), actions.cropWidescreenVertical && this.renderCropWidescreenVertical()));\n  }\n\n}\n\nmodule.exports = Editor;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    revert: 'Revert',\n    rotate: 'Rotate',\n    zoomIn: 'Zoom in',\n    zoomOut: 'Zoom out',\n    flipHorizontal: 'Flip horizontal',\n    aspectRatioSquare: 'Crop square',\n    aspectRatioLandscape: 'Crop landscape (16:9)',\n    aspectRatioPortrait: 'Crop portrait (9:16)'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _preact = require(\"preact\");\n\nconst Editor = require(\"./Editor.js\");\n\nconst packageJson = {\n  \"version\": \"1.4.2\"\n};\n\nconst locale = require(\"./locale.js\");\n\nclass ImageEditor extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n\n    this.save = () => {\n      const saveBlobCallback = blob => {\n        const {\n          currentImage\n        } = this.getPluginState();\n        this.uppy.setFileState(currentImage.id, {\n          data: blob,\n          size: blob.size,\n          preview: null\n        });\n        const updatedFile = this.uppy.getFile(currentImage.id);\n        this.uppy.emit('thumbnail:request', updatedFile);\n        this.setPluginState({\n          currentImage: updatedFile\n        });\n        this.uppy.emit('file-editor:complete', updatedFile);\n      };\n\n      const {\n        currentImage\n      } = this.getPluginState();\n      this.cropper.getCroppedCanvas(this.opts.cropperOptions.croppedCanvasOptions).toBlob(saveBlobCallback, currentImage.type, this.opts.quality);\n    };\n\n    this.storeCropperInstance = cropper => {\n      this.cropper = cropper;\n    };\n\n    this.selectFile = file => {\n      this.uppy.emit('file-editor:start', file);\n      this.setPluginState({\n        currentImage: file\n      });\n    };\n\n    this.id = this.opts.id || 'ImageEditor';\n    this.title = 'Image Editor';\n    this.type = 'editor';\n    this.defaultLocale = locale;\n    const defaultCropperOptions = {\n      viewMode: 1,\n      background: false,\n      autoCropArea: 1,\n      responsive: true,\n      croppedCanvasOptions: {}\n    };\n    const defaultActions = {\n      revert: true,\n      rotate: true,\n      granularRotate: true,\n      flip: true,\n      zoomIn: true,\n      zoomOut: true,\n      cropSquare: true,\n      cropWidescreen: true,\n      cropWidescreenVertical: true\n    };\n    const defaultOptions = {\n      quality: 0.8\n    };\n    this.opts = { ...defaultOptions,\n      ...opts,\n      actions: { ...defaultActions,\n        ...opts.actions\n      },\n      cropperOptions: { ...defaultCropperOptions,\n        ...opts.cropperOptions\n      }\n    };\n    this.i18nInit();\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  canEditFile(file) {\n    if (!file.type || file.isRemote) {\n      return false;\n    }\n\n    const fileTypeSpecific = file.type.split('/')[1];\n\n    if (/^(jpe?g|gif|png|bmp|webp)$/.test(fileTypeSpecific)) {\n      return true;\n    }\n\n    return false;\n  }\n\n  install() {\n    this.setPluginState({\n      currentImage: null\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    const {\n      currentImage\n    } = this.getPluginState();\n\n    if (currentImage) {\n      const file = this.uppy.getFile(currentImage.id);\n      this.uppy.emit('file-editor:cancel', file);\n    }\n\n    this.unmount();\n  }\n\n  render() {\n    const {\n      currentImage\n    } = this.getPluginState();\n\n    if (currentImage === null || currentImage.isRemote) {\n      return null;\n    }\n\n    return (0, _preact.h)(Editor, {\n      currentImage: currentImage,\n      storeCropperInstance: this.storeCropperInstance,\n      save: this.save,\n      opts: this.opts,\n      i18n: this.i18n\n    });\n  }\n\n}\n\nImageEditor.VERSION = packageJson.version;\nmodule.exports = ImageEditor;", "\"use strict\";\n\nmodule.exports = require(\"./ImageEditor.js\");", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nconst packageJson = {\n  \"version\": \"2.1.2\"\n};\n/**\n * Progress bar\n *\n */\n\nclass ProgressBar extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'ProgressBar';\n    this.title = 'Progress Bar';\n    this.type = 'progressindicator'; // set default options\n\n    const defaultOptions = {\n      target: 'body',\n      fixed: false,\n      hideAfterFinish: true\n    }; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.render = this.render.bind(this);\n  }\n\n  render(state) {\n    const progress = state.totalProgress || 0; // before starting and after finish should be hidden if specified in the options\n\n    const isHidden = (progress === 0 || progress === 100) && this.opts.hideAfterFinish;\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy uppy-ProgressBar\",\n      style: {\n        position: this.opts.fixed ? 'fixed' : 'initial'\n      },\n      \"aria-hidden\": isHidden\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-ProgressBar-inner\",\n      style: {\n        width: `${progress}%`\n      }\n    }), (0, _preact.h)(\"div\", {\n      className: \"uppy-ProgressBar-percentage\"\n    }, progress));\n  }\n\n  install() {\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.unmount();\n  }\n\n}\n\nProgressBar.VERSION = packageJson.version;\nmodule.exports = ProgressBar;", "\"use strict\";\n\nmodule.exports = require(\"./ProgressBar.js\");", "\"use strict\";\n\nconst mimeToExtensions = {\n  'audio/mp3': 'mp3',\n  'audio/mp4': 'mp4',\n  'audio/ogg': 'ogg',\n  'audio/webm': 'webm',\n  'image/gif': 'gif',\n  'image/heic': 'heic',\n  'image/heif': 'heif',\n  'image/jpeg': 'jpg',\n  'image/png': 'png',\n  'image/svg+xml': 'svg',\n  'video/mp4': 'mp4',\n  'video/ogg': 'ogv',\n  'video/quicktime': 'mov',\n  'video/webm': 'webm',\n  'video/x-matroska': 'mkv',\n  'video/x-msvideo': 'avi'\n};\n\nfunction getFileTypeExtension(mimeType) {\n  // Remove the ; bit in 'video/x-matroska;codecs=avc1'\n  // eslint-disable-next-line no-param-reassign\n  [mimeType] = mimeType.split(';', 1);\n  return mimeToExtensions[mimeType] || null;\n}\n\nmodule.exports = getFileTypeExtension;", "\"use strict\";\n\nfunction supportsMediaRecorder() {\n  var _MediaRecorder$protot;\n\n  /* eslint-disable compat/compat */\n  return typeof MediaRecorder === 'function' && typeof ((_MediaRecorder$protot = MediaRecorder.prototype) == null ? void 0 : _MediaRecorder$protot.start) === 'function';\n  /* eslint-enable compat/compat */\n}\n\nmodule.exports = supportsMediaRecorder;", "import { options as _options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n\n/** @type {import('./internal').Component} */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array<import('./internal').Component>} */\nlet afterPaintEffects = [];\n\n// Cast to use internal Options type\nconst options = /** @type {import('./internal').Options} */ (_options);\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\nlet oldRoot = options._root;\n\n// We take the minimum timeout for requestAnimationFrame to ensure that\n// the callback is invoked after the next frame. 35ms is based on a 30hz\n// refresh rate, which is the minimum rate for a smooth user experience.\nconst RAF_TIMEOUT = 35;\nlet prevRaf;\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._root = (vnode, parentDom) => {\n\tif (vnode && parentDom._children && parentDom._children._mask) {\n\t\tvnode._mask = parentDom._children._mask;\n\t}\n\n\tif (oldRoot) oldRoot(vnode, parentDom);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\tif (previousComponent === currentComponent) {\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentComponent._renderCallbacks = [];\n\t\t\thooks._list.some(hookItem => {\n\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t}\n\t\t\t\thookItem._pendingArgs = hookItem._nextValue = undefined;\n\t\t\t});\n\t\t} else {\n\t\t\thooks._pendingEffects.some(invokeCleanup);\n\t\t\thooks._pendingEffects.some(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentIndex = 0;\n\t\t}\n\t}\n\tpreviousComponent = currentComponent;\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tif (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c));\n\t\tc.__hooks._list.some(hookItem => {\n\t\t\tif (hookItem._pendingArgs) {\n\t\t\t\thookItem._args = hookItem._pendingArgs;\n\t\t\t\thookItem._pendingArgs = undefined;\n\t\t\t}\n\t\t});\n\t}\n\tpreviousComponent = currentComponent = null;\n};\n\n// TODO: Improve typing of commitQueue parameter\n/** @type {(vnode: import('./internal').VNode, commitQueue: any) => void} */\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.some(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tlet hasErrored;\n\t\tc.__hooks._list.some(s => {\n\t\t\ttry {\n\t\t\t\tinvokeCleanup(s);\n\t\t\t} catch (e) {\n\t\t\t\thasErrored = e;\n\t\t\t}\n\t\t});\n\t\tc.__hooks = undefined;\n\t\tif (hasErrored) options._catchError(hasErrored, c._vnode);\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\n\treturn hooks._list[index];\n}\n\n/**\n * @template {unknown} S\n * @param {import('./index').Dispatch<import('./index').StateUpdater<S>>} [initialState]\n * @returns {[S, (state: S) => void]}\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @template {unknown} S\n * @template {unknown} A\n * @param {import('./index').Reducer<S, A>} reducer\n * @param {import('./index').Dispatch<import('./index').StateUpdater<S>>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ S, (state: S) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst currentValue = hookState._nextValue\n\t\t\t\t\t? hookState._nextValue[0]\n\t\t\t\t\t: hookState._value[0];\n\t\t\t\tconst nextValue = hookState._reducer(currentValue, action);\n\n\t\t\t\tif (currentValue !== nextValue) {\n\t\t\t\t\thookState._nextValue = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\n\t\tif (!currentComponent._hasScuFromHooks) {\n\t\t\tcurrentComponent._hasScuFromHooks = true;\n\t\t\tlet prevScu = currentComponent.shouldComponentUpdate;\n\t\t\tconst prevCWU = currentComponent.componentWillUpdate;\n\n\t\t\t// If we're dealing with a forced update `shouldComponentUpdate` will\n\t\t\t// not be called. But we use that to update the hook values, so we\n\t\t\t// need to call it.\n\t\t\tcurrentComponent.componentWillUpdate = function (p, s, c) {\n\t\t\t\tif (this._force) {\n\t\t\t\t\tlet tmp = prevScu;\n\t\t\t\t\t// Clear to avoid other sCU hooks from being called\n\t\t\t\t\tprevScu = undefined;\n\t\t\t\t\tupdateHookState(p, s, c);\n\t\t\t\t\tprevScu = tmp;\n\t\t\t\t}\n\n\t\t\t\tif (prevCWU) prevCWU.call(this, p, s, c);\n\t\t\t};\n\n\t\t\t// This SCU has the purpose of bailing out after repeated updates\n\t\t\t// to stateful hooks.\n\t\t\t// we store the next value in _nextValue[0] and keep doing that for all\n\t\t\t// state setters, if we have next states and\n\t\t\t// all next states within a component end up being equal to their original state\n\t\t\t// we are safe to bail out for this specific component.\n\t\t\t/**\n\t\t\t *\n\t\t\t * @type {import('./internal').Component[\"shouldComponentUpdate\"]}\n\t\t\t */\n\t\t\t// @ts-ignore - We don't use TS to downtranspile\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction updateHookState(p, s, c) {\n\t\t\t\tif (!hookState._component.__hooks) return true;\n\n\t\t\t\t// We check whether we have components with a nextValue set that\n\t\t\t\t// have values that aren't equal to one another this pushes\n\t\t\t\t// us to update further down the tree\n\t\t\t\tlet updatedHook = false;\n\t\t\t\tlet shouldUpdate = hookState._component.props !== p;\n\t\t\t\thookState._component.__hooks._list.some(hookItem => {\n\t\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\t\tupdatedHook = true;\n\t\t\t\t\t\tconst currentValue = hookItem._value[0];\n\t\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t\t\thookItem._nextValue = undefined;\n\t\t\t\t\t\tif (currentValue !== hookItem._value[0]) shouldUpdate = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (prevScu) {\n\t\t\t\t\tconst result = prevScu.call(this, p, s, c);\n\t\t\t\t\treturn updatedHook ? result || shouldUpdate : result;\n\t\t\t\t}\n\n\t\t\t\treturn !updatedHook || shouldUpdate;\n\t\t\t}\n\n\t\t\tcurrentComponent.shouldComponentUpdate = updateHookState;\n\t\t}\n\t}\n\n\treturn hookState._nextValue || hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\n/** @type {(initialValue: unknown) => unknown} */\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') {\n\t\t\t\tconst result = ref(createHandle());\n\t\t\t\treturn () => {\n\t\t\t\t\tref(null);\n\t\t\t\t\tif (result && typeof result == 'function') result();\n\t\t\t\t};\n\t\t\t} else if (ref) {\n\t\t\t\tref.current = createHandle();\n\t\t\t\treturn () => (ref.current = null);\n\t\t\t}\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @template {unknown} T\n * @param {() => T} factory\n * @param {unknown[]} args\n * @returns {T}\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState<T>} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {unknown[]} args\n * @returns {() => void}\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {<T>(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(\n\t\t\tformatter ? formatter(value) : /** @type {any}*/ (value)\n\t\t);\n\t}\n}\n\n/**\n * @param {(error: unknown, errorInfo: import('preact').ErrorInfo) => void} cb\n * @returns {[unknown, () => void]}\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = (err, errorInfo) => {\n\t\t\tif (state._value) state._value(err, errorInfo);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/** @type {() => string} */\nexport function useId() {\n\t/** @type {import('./internal').IdHookState} */\n\tconst state = getHookState(currentIndex++, 11);\n\tif (!state._value) {\n\t\t// Grab either the root node or the nearest async boundary node.\n\t\t/** @type {import('./internal').VNode} */\n\t\tlet root = currentComponent._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\tlet mask = root._mask || (root._mask = [0, 0]);\n\t\tstate._value = 'P' + mask[0] + '-' + mask[1]++;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tlet component;\n\twhile ((component = afterPaintEffects.shift())) {\n\t\tconst hooks = component.__hooks;\n\t\tif (!component._parentDom || !hooks) continue;\n\t\ttry {\n\t\t\thooks._pendingEffects.some(invokeCleanup);\n\t\t\thooks._pendingEffects.some(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t} catch (e) {\n\t\t\thooks._pendingEffects = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t}\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n * @returns {void}\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').HookState} hook\n * @returns {void}\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tlet cleanup = hook._cleanup;\n\tif (typeof cleanup == 'function') {\n\t\thook._cleanup = undefined;\n\t\tcleanup();\n\t}\n\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n * @returns {void}\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {unknown[]} oldArgs\n * @param {unknown[]} newArgs\n * @returns {boolean}\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\n/**\n * @template Arg\n * @param {Arg} arg\n * @param {(arg: Arg) => any} f\n * @returns {any}\n */\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction RecordButton(_ref) {\n  let {\n    recording,\n    onStartRecording,\n    onStopRecording,\n    i18n\n  } = _ref;\n\n  if (recording) {\n    return (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-c-btn uppy-Audio-button\",\n      type: \"button\",\n      title: i18n('stopAudioRecording'),\n      \"aria-label\": i18n('stopAudioRecording'),\n      onClick: onStopRecording,\n      \"data-uppy-super-focusable\": true\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon\",\n      width: \"100\",\n      height: \"100\",\n      viewBox: \"0 0 100 100\"\n    }, (0, _preact.h)(\"rect\", {\n      x: \"15\",\n      y: \"15\",\n      width: \"70\",\n      height: \"70\"\n    })));\n  }\n\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-Audio-button\",\n    type: \"button\",\n    title: i18n('startAudioRecording'),\n    \"aria-label\": i18n('startAudioRecording'),\n    onClick: onStartRecording,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"14px\",\n    height: \"20px\",\n    viewBox: \"0 0 14 20\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M7 14c2.21 0 4-1.71 4-3.818V3.818C11 1.71 9.21 0 7 0S3 1.71 3 3.818v6.364C3 12.29 4.79 14 7 14zm6.364-7h-.637a.643.643 0 0 0-.636.65V9.6c0 3.039-2.565 5.477-5.6 5.175-2.645-.264-4.582-2.692-4.582-5.407V7.65c0-.36-.285-.65-.636-.65H.636A.643.643 0 0 0 0 7.65v1.631c0 3.642 2.544 6.888 6.045 7.382v1.387H3.818a.643.643 0 0 0-.636.65v.65c0 .36.285.65.636.65h6.364c.351 0 .636-.29.636-.65v-.65c0-.36-.285-.65-.636-.65H7.955v-1.372C11.363 16.2 14 13.212 14 9.6V7.65c0-.36-.285-.65-.636-.65z\",\n    fill: \"#FFF\",\n    \"fill-rule\": \"nonzero\"\n  })));\n}\n\nmodule.exports = RecordButton;", "\"use strict\";\n\nfunction formatSeconds(seconds) {\n  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, 0)}`;\n}\n\n/**\n * Takes an Integer value of seconds (e.g. 83) and converts it into a human-readable formatted string (e.g. '1:23').\n *\n * @param {Integer} seconds\n * @returns {string} the formatted seconds (e.g. '1:23' for 1 minute and 23 seconds)\n *\n */\nmodule.exports = formatSeconds;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst formatSeconds = require(\"./formatSeconds.js\");\n\nfunction RecordingLength(_ref) {\n  let {\n    recordingLengthSeconds,\n    i18n\n  } = _ref;\n  const formattedRecordingLengthSeconds = formatSeconds(recordingLengthSeconds);\n  return (0, _preact.h)(\"span\", {\n    \"aria-label\": i18n('recordingLength', {\n      recording_length: formattedRecordingLengthSeconds\n    })\n  }, formattedRecordingLengthSeconds);\n}\n\nmodule.exports = RecordingLength;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    currentDeviceId,\n    audioSources,\n    onChangeSource\n  } = _ref;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-videoSource\"\n  }, (0, _preact.h)(\"select\", {\n    className: \"uppy-u-reset uppy-Audio-audioSource-select\",\n    onChange: event => {\n      onChangeSource(event.target.value);\n    }\n  }, audioSources.map(audioSource => (0, _preact.h)(\"option\", {\n    key: audioSource.deviceId,\n    value: audioSource.deviceId,\n    selected: audioSource.deviceId === currentDeviceId\n  }, audioSource.label))));\n};", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nfunction isFunction(v) {\n  return typeof v === 'function';\n}\n\nfunction result(v) {\n  return isFunction(v) ? v() : v;\n}\n/* Audio Oscilloscope\n  https://github.com/miguelmota/audio-oscilloscope\n*/\n\n\nvar _draw = /*#__PURE__*/_classPrivateFieldLooseKey(\"draw\");\n\nclass AudioOscilloscope {\n  constructor(canvas, options) {\n    if (options === void 0) {\n      options = {};\n    }\n\n    Object.defineProperty(this, _draw, {\n      writable: true,\n      value: () => this.draw()\n    });\n    const canvasOptions = options.canvas || {};\n    const canvasContextOptions = options.canvasContext || {};\n    this.analyser = null;\n    this.bufferLength = 0;\n    this.dataArray = [];\n    this.canvas = canvas;\n    this.width = result(canvasOptions.width) || this.canvas.width;\n    this.height = result(canvasOptions.height) || this.canvas.height;\n    this.canvas.width = this.width;\n    this.canvas.height = this.height;\n    this.canvasContext = this.canvas.getContext('2d');\n    this.canvasContext.fillStyle = result(canvasContextOptions.fillStyle) || 'rgb(255, 255, 255)';\n    this.canvasContext.strokeStyle = result(canvasContextOptions.strokeStyle) || 'rgb(0, 0, 0)';\n    this.canvasContext.lineWidth = result(canvasContextOptions.lineWidth) || 1;\n    this.onDrawFrame = isFunction(options.onDrawFrame) ? options.onDrawFrame : () => {};\n  }\n\n  addSource(streamSource) {\n    this.streamSource = streamSource;\n    this.audioContext = this.streamSource.context;\n    this.analyser = this.audioContext.createAnalyser();\n    this.analyser.fftSize = 2048;\n    this.bufferLength = this.analyser.frequencyBinCount;\n    this.source = this.audioContext.createBufferSource();\n    this.dataArray = new Uint8Array(this.bufferLength);\n    this.analyser.getByteTimeDomainData(this.dataArray);\n    this.streamSource.connect(this.analyser);\n  }\n\n  draw() {\n    const {\n      analyser,\n      dataArray,\n      bufferLength\n    } = this;\n    const ctx = this.canvasContext;\n    const w = this.width;\n    const h = this.height;\n\n    if (analyser) {\n      analyser.getByteTimeDomainData(dataArray);\n    }\n\n    ctx.fillRect(0, 0, w, h);\n    ctx.beginPath();\n    const sliceWidth = w * 1.0 / bufferLength;\n    let x = 0;\n\n    if (!bufferLength) {\n      ctx.moveTo(0, this.height / 2);\n    }\n\n    for (let i = 0; i < bufferLength; i++) {\n      const v = dataArray[i] / 128.0;\n      const y = v * (h / 2);\n\n      if (i === 0) {\n        ctx.moveTo(x, y);\n      } else {\n        ctx.lineTo(x, y);\n      }\n\n      x += sliceWidth;\n    }\n\n    ctx.lineTo(w, h / 2);\n    ctx.stroke();\n    this.onDrawFrame(this);\n    requestAnimationFrame(_classPrivateFieldLooseBase(this, _draw)[_draw]);\n  }\n\n}\n\nmodule.exports = AudioOscilloscope;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction SubmitButton(_ref) {\n  let {\n    onSubmit,\n    i18n\n  } = _ref;\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-Audio-button uppy-Audio-button--submit\",\n    type: \"button\",\n    title: i18n('submitRecordedFile'),\n    \"aria-label\": i18n('submitRecordedFile'),\n    onClick: onSubmit,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    width: \"12\",\n    height: \"9\",\n    viewBox: \"0 0 12 9\",\n    xmlns: \"http://www.w3.org/2000/svg\",\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\"\n  }, (0, _preact.h)(\"path\", {\n    fill: \"#fff\",\n    fillRule: \"nonzero\",\n    d: \"M10.66 0L12 1.31 4.136 9 0 4.956l1.34-1.31L4.136 6.38z\"\n  })));\n}\n\nmodule.exports = SubmitButton;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction DiscardButton(_ref) {\n  let {\n    onDiscard,\n    i18n\n  } = _ref;\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-Audio-button\",\n    type: \"button\",\n    title: i18n('discardRecordedFile'),\n    \"aria-label\": i18n('discardRecordedFile'),\n    onClick: onDiscard,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    width: \"13\",\n    height: \"13\",\n    viewBox: \"0 0 13 13\",\n    xmlns: \"http://www.w3.org/2000/svg\",\n    \"aria-hidden\": \"true\",\n    className: \"uppy-c-icon\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"#FFF\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M.496 11.367L11.103.76l1.414 1.414L1.911 12.781z\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M11.104 12.782L.497 2.175 1.911.76l10.607 10.606z\"\n  }))));\n}\n\nmodule.exports = DiscardButton;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _hooks = require(\"preact/hooks\");\n\n/* eslint-disable jsx-a11y/media-has-caption */\nconst RecordButton = require(\"./RecordButton.js\");\n\nconst RecordingLength = require(\"./RecordingLength.js\");\n\nconst AudioSourceSelect = require(\"./AudioSourceSelect.js\");\n\nconst AudioOscilloscope = require(\"./audio-oscilloscope/index.js\");\n\nconst SubmitButton = require(\"./SubmitButton.js\");\n\nconst DiscardButton = require(\"./DiscardButton.js\");\n\nfunction RecordingScreen(props) {\n  const {\n    stream,\n    recordedAudio,\n    onStop,\n    recording,\n    supportsRecording,\n    audioSources,\n    showAudioSourceDropdown,\n    onSubmit,\n    i18n,\n    onStartRecording,\n    onStopRecording,\n    onDiscardRecordedAudio,\n    recordingLengthSeconds\n  } = props;\n  const canvasEl = (0, _hooks.useRef)(null);\n  const oscilloscope = (0, _hooks.useRef)(null); // componentDidMount / componentDidUnmount\n\n  (0, _hooks.useEffect)(() => {\n    return () => {\n      oscilloscope.current = null;\n      onStop();\n    };\n  }, [onStop]); // componentDidUpdate\n\n  (0, _hooks.useEffect)(() => {\n    if (!recordedAudio) {\n      oscilloscope.current = new AudioOscilloscope(canvasEl.current, {\n        canvas: {\n          width: 600,\n          height: 600\n        },\n        canvasContext: {\n          lineWidth: 2,\n          fillStyle: 'rgb(0,0,0)',\n          strokeStyle: 'green'\n        }\n      });\n      oscilloscope.current.draw();\n\n      if (stream) {\n        const audioContext = new AudioContext();\n        const source = audioContext.createMediaStreamSource(stream);\n        oscilloscope.current.addSource(source);\n      }\n    }\n  }, [recordedAudio, stream]);\n  const hasRecordedAudio = recordedAudio != null;\n  const shouldShowRecordButton = !hasRecordedAudio && supportsRecording;\n  const shouldShowAudioSourceDropdown = showAudioSourceDropdown && !hasRecordedAudio && audioSources && audioSources.length > 1;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-container\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-audioContainer\"\n  }, hasRecordedAudio ? (0, _preact.h)(\"audio\", {\n    className: \"uppy-Audio-player\",\n    controls: true,\n    src: recordedAudio\n  }) : (0, _preact.h)(\"canvas\", {\n    ref: canvasEl,\n    className: \"uppy-Audio-canvas\"\n  })), (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-footer\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-audioSourceContainer\"\n  }, shouldShowAudioSourceDropdown ? AudioSourceSelect(props) : null), (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-buttonContainer\"\n  }, shouldShowRecordButton && (0, _preact.h)(RecordButton, {\n    recording: recording,\n    onStartRecording: onStartRecording,\n    onStopRecording: onStopRecording,\n    i18n: i18n\n  }), hasRecordedAudio && (0, _preact.h)(SubmitButton, {\n    onSubmit: onSubmit,\n    i18n: i18n\n  }), hasRecordedAudio && (0, _preact.h)(DiscardButton, {\n    onDiscard: onDiscardRecordedAudio,\n    i18n: i18n\n  })), (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-recordingLength\"\n  }, !hasRecordedAudio && (0, _preact.h)(RecordingLength, {\n    recordingLengthSeconds: recordingLengthSeconds,\n    i18n: i18n\n  }))));\n}\n\nmodule.exports = RecordingScreen;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = props => {\n  const {\n    icon,\n    hasAudio,\n    i18n\n  } = props;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-permissons\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Audio-permissonsIcon\"\n  }, icon()), (0, _preact.h)(\"h1\", {\n    className: \"uppy-Audio-title\"\n  }, hasAudio ? i18n('allowAudioAccessTitle') : i18n('noAudioTitle')), (0, _preact.h)(\"p\", null, hasAudio ? i18n('allowAudioAccessDescription') : i18n('noAudioDescription')));\n};", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameAudio: 'Audio',\n    // Used as the label for the button that starts an audio recording.\n    // This is not visibly rendered but is picked up by screen readers.\n    startAudioRecording: 'Begin audio recording',\n    // Used as the label for the button that stops an audio recording.\n    // This is not visibly rendered but is picked up by screen readers.\n    stopAudioRecording: 'Stop audio recording',\n    // Title on the \u201Callow access\u201D screen\n    allowAudioAccessTitle: 'Please allow access to your microphone',\n    // Description on the \u201Callow access\u201D screen\n    allowAudioAccessDescription: 'In order to record audio, please allow microphone access for this site.',\n    // Title on the \u201Cdevice not available\u201D screen\n    noAudioTitle: 'Microphone Not Available',\n    // Description on the \u201Cdevice not available\u201D screen\n    noAudioDescription: 'In order to record audio, please connect a microphone or another audio input device',\n    // Message about file size will be shown in an Informer bubble\n    recordingStoppedMaxSize: 'Recording stopped because the file size is about to exceed the limit',\n    // Used as the label for the counter that shows recording length (`1:25`).\n    // This is not visibly rendered but is picked up by screen readers.\n    recordingLength: 'Recording length %{recording_length}',\n    // Used as the label for the submit checkmark button.\n    // This is not visibly rendered but is picked up by screen readers.\n    submitRecordedFile: 'Submit recorded file',\n    // Used as the label for the discard cross button.\n    // This is not visibly rendered but is picked up by screen readers.\n    discardRecordedFile: 'Discard recorded file'\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst getFileTypeExtension = require(\"@uppy/utils/lib/getFileTypeExtension\");\n\nconst supportsMediaRecorder = require(\"./supportsMediaRecorder.js\");\n\nconst RecordingScreen = require(\"./RecordingScreen.js\");\n\nconst PermissionsScreen = require(\"./PermissionsScreen.js\");\n\nconst locale = require(\"./locale.js\");\n\nconst packageJson = {\n  \"version\": \"0.3.3\"\n};\n/**\n * Audio recording plugin\n */\n\nvar _stream = /*#__PURE__*/_classPrivateFieldLooseKey(\"stream\");\n\nvar _audioActive = /*#__PURE__*/_classPrivateFieldLooseKey(\"audioActive\");\n\nvar _recordingChunks = /*#__PURE__*/_classPrivateFieldLooseKey(\"recordingChunks\");\n\nvar _recorder = /*#__PURE__*/_classPrivateFieldLooseKey(\"recorder\");\n\nvar _capturedMediaFile = /*#__PURE__*/_classPrivateFieldLooseKey(\"capturedMediaFile\");\n\nvar _mediaDevices = /*#__PURE__*/_classPrivateFieldLooseKey(\"mediaDevices\");\n\nvar _supportsUserMedia = /*#__PURE__*/_classPrivateFieldLooseKey(\"supportsUserMedia\");\n\nvar _hasAudioCheck = /*#__PURE__*/_classPrivateFieldLooseKey(\"hasAudioCheck\");\n\nvar _start = /*#__PURE__*/_classPrivateFieldLooseKey(\"start\");\n\nvar _startRecording = /*#__PURE__*/_classPrivateFieldLooseKey(\"startRecording\");\n\nvar _stopRecording = /*#__PURE__*/_classPrivateFieldLooseKey(\"stopRecording\");\n\nvar _discardRecordedAudio = /*#__PURE__*/_classPrivateFieldLooseKey(\"discardRecordedAudio\");\n\nvar _submit = /*#__PURE__*/_classPrivateFieldLooseKey(\"submit\");\n\nvar _stop = /*#__PURE__*/_classPrivateFieldLooseKey(\"stop\");\n\nvar _getAudio = /*#__PURE__*/_classPrivateFieldLooseKey(\"getAudio\");\n\nvar _changeSource = /*#__PURE__*/_classPrivateFieldLooseKey(\"changeSource\");\n\nvar _updateSources = /*#__PURE__*/_classPrivateFieldLooseKey(\"updateSources\");\n\nclass Audio extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    var _this;\n\n    super(uppy, opts);\n    _this = this;\n    Object.defineProperty(this, _getAudio, {\n      value: _getAudio2\n    });\n    Object.defineProperty(this, _hasAudioCheck, {\n      value: _hasAudioCheck2\n    });\n    Object.defineProperty(this, _stream, {\n      writable: true,\n      value: null\n    });\n    Object.defineProperty(this, _audioActive, {\n      writable: true,\n      value: false\n    });\n    Object.defineProperty(this, _recordingChunks, {\n      writable: true,\n      value: null\n    });\n    Object.defineProperty(this, _recorder, {\n      writable: true,\n      value: null\n    });\n    Object.defineProperty(this, _capturedMediaFile, {\n      writable: true,\n      value: null\n    });\n    Object.defineProperty(this, _mediaDevices, {\n      writable: true,\n      value: null\n    });\n    Object.defineProperty(this, _supportsUserMedia, {\n      writable: true,\n      value: null\n    });\n    Object.defineProperty(this, _start, {\n      writable: true,\n      value: function (options) {\n        if (options === void 0) {\n          options = null;\n        }\n\n        if (!_classPrivateFieldLooseBase(_this, _supportsUserMedia)[_supportsUserMedia]) {\n          return Promise.reject(new Error('Microphone access not supported'));\n        }\n\n        _classPrivateFieldLooseBase(_this, _audioActive)[_audioActive] = true;\n\n        _classPrivateFieldLooseBase(_this, _hasAudioCheck)[_hasAudioCheck]().then(hasAudio => {\n          _this.setPluginState({\n            hasAudio\n          }); // ask user for access to their camera\n\n\n          return _classPrivateFieldLooseBase(_this, _mediaDevices)[_mediaDevices].getUserMedia({\n            audio: true\n          }).then(stream => {\n            _classPrivateFieldLooseBase(_this, _stream)[_stream] = stream;\n            let currentDeviceId = null;\n            const tracks = stream.getAudioTracks();\n\n            if (!options || !options.deviceId) {\n              currentDeviceId = tracks[0].getSettings().deviceId;\n            } else {\n              tracks.forEach(track => {\n                if (track.getSettings().deviceId === options.deviceId) {\n                  currentDeviceId = track.getSettings().deviceId;\n                }\n              });\n            } // Update the sources now, so we can access the names.\n\n\n            _classPrivateFieldLooseBase(_this, _updateSources)[_updateSources]();\n\n            _this.setPluginState({\n              currentDeviceId,\n              audioReady: true\n            });\n          }).catch(err => {\n            _this.setPluginState({\n              audioReady: false,\n              cameraError: err\n            });\n\n            _this.uppy.info(err.message, 'error');\n          });\n        });\n      }\n    });\n    Object.defineProperty(this, _startRecording, {\n      writable: true,\n      value: () => {\n        // only used if supportsMediaRecorder() returned true\n        // eslint-disable-next-line compat/compat\n        _classPrivateFieldLooseBase(this, _recorder)[_recorder] = new MediaRecorder(_classPrivateFieldLooseBase(this, _stream)[_stream]);\n        _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks] = [];\n        let stoppingBecauseOfMaxSize = false;\n\n        _classPrivateFieldLooseBase(this, _recorder)[_recorder].addEventListener('dataavailable', event => {\n          _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks].push(event.data);\n\n          const {\n            restrictions\n          } = this.uppy.opts;\n\n          if (_classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks].length > 1 && restrictions.maxFileSize != null && !stoppingBecauseOfMaxSize) {\n            const totalSize = _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks].reduce((acc, chunk) => acc + chunk.size, 0); // Exclude the initial chunk from the average size calculation because it is likely to be a very small outlier\n\n\n            const averageChunkSize = (totalSize - _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks][0].size) / (_classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks].length - 1);\n            const expectedEndChunkSize = averageChunkSize * 3;\n            const maxSize = Math.max(0, restrictions.maxFileSize - expectedEndChunkSize);\n\n            if (totalSize > maxSize) {\n              stoppingBecauseOfMaxSize = true;\n              this.uppy.info(this.i18n('recordingStoppedMaxSize'), 'warning', 4000);\n\n              _classPrivateFieldLooseBase(this, _stopRecording)[_stopRecording]();\n            }\n          }\n        }); // use a \"time slice\" of 500ms: ondataavailable will be called each 500ms\n        // smaller time slices mean we can more accurately check the max file size restriction\n\n\n        _classPrivateFieldLooseBase(this, _recorder)[_recorder].start(500); // Start the recordingLengthTimer if we are showing the recording length.\n\n\n        this.recordingLengthTimer = setInterval(() => {\n          const currentRecordingLength = this.getPluginState().recordingLengthSeconds;\n          this.setPluginState({\n            recordingLengthSeconds: currentRecordingLength + 1\n          });\n        }, 1000);\n        this.setPluginState({\n          isRecording: true\n        });\n      }\n    });\n    Object.defineProperty(this, _stopRecording, {\n      writable: true,\n      value: () => {\n        const stopped = new Promise(resolve => {\n          _classPrivateFieldLooseBase(this, _recorder)[_recorder].addEventListener('stop', () => {\n            resolve();\n          });\n\n          _classPrivateFieldLooseBase(this, _recorder)[_recorder].stop();\n\n          clearInterval(this.recordingLengthTimer);\n          this.setPluginState({\n            recordingLengthSeconds: 0\n          });\n        });\n        return stopped.then(() => {\n          this.setPluginState({\n            isRecording: false\n          });\n          return _classPrivateFieldLooseBase(this, _getAudio)[_getAudio]();\n        }).then(file => {\n          try {\n            _classPrivateFieldLooseBase(this, _capturedMediaFile)[_capturedMediaFile] = file; // create object url for capture result preview\n\n            this.setPluginState({\n              recordedAudio: URL.createObjectURL(file.data)\n            });\n          } catch (err) {\n            // Logging the error, exept restrictions, which is handled in Core\n            if (!err.isRestriction) {\n              this.uppy.log(err);\n            }\n          }\n        }).then(() => {\n          _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks] = null;\n          _classPrivateFieldLooseBase(this, _recorder)[_recorder] = null;\n        }, error => {\n          _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks] = null;\n          _classPrivateFieldLooseBase(this, _recorder)[_recorder] = null;\n          throw error;\n        });\n      }\n    });\n    Object.defineProperty(this, _discardRecordedAudio, {\n      writable: true,\n      value: () => {\n        this.setPluginState({\n          recordedAudio: null\n        });\n        _classPrivateFieldLooseBase(this, _capturedMediaFile)[_capturedMediaFile] = null;\n      }\n    });\n    Object.defineProperty(this, _submit, {\n      writable: true,\n      value: () => {\n        try {\n          if (_classPrivateFieldLooseBase(this, _capturedMediaFile)[_capturedMediaFile]) {\n            this.uppy.addFile(_classPrivateFieldLooseBase(this, _capturedMediaFile)[_capturedMediaFile]);\n          }\n        } catch (err) {\n          // Logging the error, exept restrictions, which is handled in Core\n          if (!err.isRestriction) {\n            this.uppy.log(err, 'error');\n          }\n        }\n      }\n    });\n    Object.defineProperty(this, _stop, {\n      writable: true,\n      value: async () => {\n        if (_classPrivateFieldLooseBase(this, _stream)[_stream]) {\n          const audioTracks = _classPrivateFieldLooseBase(this, _stream)[_stream].getAudioTracks();\n\n          audioTracks.forEach(track => track.stop());\n        }\n\n        if (_classPrivateFieldLooseBase(this, _recorder)[_recorder]) {\n          await new Promise(resolve => {\n            _classPrivateFieldLooseBase(this, _recorder)[_recorder].addEventListener('stop', resolve, {\n              once: true\n            });\n\n            _classPrivateFieldLooseBase(this, _recorder)[_recorder].stop();\n\n            clearInterval(this.recordingLengthTimer);\n          });\n        }\n\n        _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks] = null;\n        _classPrivateFieldLooseBase(this, _recorder)[_recorder] = null;\n        _classPrivateFieldLooseBase(this, _audioActive)[_audioActive] = false;\n        _classPrivateFieldLooseBase(this, _stream)[_stream] = null;\n        this.setPluginState({\n          recordedAudio: null,\n          isRecording: false,\n          recordingLengthSeconds: 0\n        });\n      }\n    });\n    Object.defineProperty(this, _changeSource, {\n      writable: true,\n      value: deviceId => {\n        _classPrivateFieldLooseBase(this, _stop)[_stop]();\n\n        _classPrivateFieldLooseBase(this, _start)[_start]({\n          deviceId\n        });\n      }\n    });\n    Object.defineProperty(this, _updateSources, {\n      writable: true,\n      value: () => {\n        _classPrivateFieldLooseBase(this, _mediaDevices)[_mediaDevices].enumerateDevices().then(devices => {\n          this.setPluginState({\n            audioSources: devices.filter(device => device.kind === 'audioinput')\n          });\n        });\n      }\n    });\n    _classPrivateFieldLooseBase(this, _mediaDevices)[_mediaDevices] = navigator.mediaDevices;\n    _classPrivateFieldLooseBase(this, _supportsUserMedia)[_supportsUserMedia] = _classPrivateFieldLooseBase(this, _mediaDevices)[_mediaDevices] != null;\n    this.id = this.opts.id || 'Audio';\n    this.type = 'acquirer';\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32px\",\n      height: \"32px\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      \"fill-rule\": \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      fill: \"#9B59B6\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M16 20c-2.21 0-4-1.71-4-3.818V9.818C12 7.71 13.79 6 16 6s4 1.71 4 3.818v6.364C20 18.29 18.21 20 16 20zm-6.364-7h.637c.351 0 .636.29.636.65v1.95c0 3.039 2.565 5.477 5.6 5.175 2.645-.264 4.582-2.692 4.582-5.407V13.65c0-.36.285-.65.636-.65h.637c.351 0 .636.29.636.65v1.631c0 3.642-2.544 6.888-6.045 7.382v1.387h2.227c.351 0 .636.29.636.65v.65c0 .36-.285.65-.636.65h-6.364a.643.643 0 0 1-.636-.65v-.65c0-.36.285-.65.636-.65h2.227v-1.372C11.637 22.2 9 19.212 9 15.6v-1.95c0-.36.285-.65.636-.65z\",\n      fill: \"#FFF\",\n      \"fill-rule\": \"nonzero\"\n    })));\n\n    this.defaultLocale = locale;\n    this.opts = { ...opts\n    };\n    this.i18nInit();\n    this.title = this.i18n('pluginNameAudio');\n    this.setPluginState({\n      hasAudio: false,\n      audioReady: false,\n      cameraError: null,\n      recordingLengthSeconds: 0,\n      audioSources: [],\n      currentDeviceId: null\n    });\n  }\n\n  render() {\n    if (!_classPrivateFieldLooseBase(this, _audioActive)[_audioActive]) {\n      _classPrivateFieldLooseBase(this, _start)[_start]();\n    }\n\n    const audioState = this.getPluginState();\n\n    if (!audioState.audioReady || !audioState.hasAudio) {\n      return (0, _preact.h)(PermissionsScreen, {\n        icon: this.icon,\n        i18n: this.i18n,\n        hasAudio: audioState.hasAudio\n      });\n    }\n\n    return (0, _preact.h)(RecordingScreen // eslint-disable-next-line react/jsx-props-no-spreading\n    , _extends({}, audioState, {\n      audioActive: _classPrivateFieldLooseBase(this, _audioActive)[_audioActive],\n      onChangeSource: _classPrivateFieldLooseBase(this, _changeSource)[_changeSource],\n      onStartRecording: _classPrivateFieldLooseBase(this, _startRecording)[_startRecording],\n      onStopRecording: _classPrivateFieldLooseBase(this, _stopRecording)[_stopRecording],\n      onDiscardRecordedAudio: _classPrivateFieldLooseBase(this, _discardRecordedAudio)[_discardRecordedAudio],\n      onSubmit: _classPrivateFieldLooseBase(this, _submit)[_submit],\n      onStop: _classPrivateFieldLooseBase(this, _stop)[_stop],\n      i18n: this.i18n,\n      showAudioSourceDropdown: this.opts.showAudioSourceDropdown,\n      supportsRecording: supportsMediaRecorder(),\n      recording: audioState.isRecording,\n      stream: _classPrivateFieldLooseBase(this, _stream)[_stream]\n    }));\n  }\n\n  install() {\n    this.setPluginState({\n      audioReady: false,\n      recordingLengthSeconds: 0\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n\n    if (_classPrivateFieldLooseBase(this, _mediaDevices)[_mediaDevices]) {\n      _classPrivateFieldLooseBase(this, _updateSources)[_updateSources]();\n\n      _classPrivateFieldLooseBase(this, _mediaDevices)[_mediaDevices].ondevicechange = () => {\n        _classPrivateFieldLooseBase(this, _updateSources)[_updateSources]();\n\n        if (_classPrivateFieldLooseBase(this, _stream)[_stream]) {\n          let restartStream = true;\n          const {\n            audioSources,\n            currentDeviceId\n          } = this.getPluginState();\n          audioSources.forEach(audioSource => {\n            if (currentDeviceId === audioSource.deviceId) {\n              restartStream = false;\n            }\n          });\n\n          if (restartStream) {\n            _classPrivateFieldLooseBase(this, _stop)[_stop]();\n\n            _classPrivateFieldLooseBase(this, _start)[_start]();\n          }\n        }\n      };\n    }\n  }\n\n  uninstall() {\n    if (_classPrivateFieldLooseBase(this, _stream)[_stream]) {\n      _classPrivateFieldLooseBase(this, _stop)[_stop]();\n    }\n\n    this.unmount();\n  }\n\n}\n\nfunction _hasAudioCheck2() {\n  if (!_classPrivateFieldLooseBase(this, _mediaDevices)[_mediaDevices]) {\n    return Promise.resolve(false);\n  }\n\n  return _classPrivateFieldLooseBase(this, _mediaDevices)[_mediaDevices].enumerateDevices().then(devices => {\n    return devices.some(device => device.kind === 'audioinput');\n  });\n}\n\nfunction _getAudio2() {\n  // Sometimes in iOS Safari, Blobs (especially the first Blob in the recordingChunks Array)\n  // have empty 'type' attributes (e.g. '') so we need to find a Blob that has a defined 'type'\n  // attribute in order to determine the correct MIME type.\n  const mimeType = _classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks].find(blob => {\n    var _blob$type;\n\n    return ((_blob$type = blob.type) == null ? void 0 : _blob$type.length) > 0;\n  }).type;\n\n  const fileExtension = getFileTypeExtension(mimeType);\n\n  if (!fileExtension) {\n    return Promise.reject(new Error(`Could not retrieve recording: Unsupported media type \"${mimeType}\"`));\n  }\n\n  const name = `audio-${Date.now()}.${fileExtension}`;\n  const blob = new Blob(_classPrivateFieldLooseBase(this, _recordingChunks)[_recordingChunks], {\n    type: mimeType\n  });\n  const file = {\n    source: this.id,\n    name,\n    data: new Blob([blob], {\n      type: mimeType\n    }),\n    type: mimeType\n  };\n  return Promise.resolve(file);\n}\n\nAudio.VERSION = packageJson.version;\nmodule.exports = Audio;", "\"use strict\";\n\nmodule.exports = require(\"./Audio.js\");", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameBox: 'Box'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nvar _preact = require(\"preact\");\n\nconst locale = require(\"./locale.js\");\n\nconst packageJson = {\n  \"version\": \"1.0.8\"\n};\n\nclass Box extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'Box';\n\n    _companionClient.Provider.initPlugin(this, opts);\n\n    this.title = this.opts.title || 'Box';\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      fill: \"#0061D5\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\"\n    }), (0, _preact.h)(\"g\", {\n      fill: \"#fff\",\n      fillRule: \"nonzero\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"m16.4 13.5c-1.6 0-3 0.9-3.7 2.2-0.7-1.3-2.1-2.2-3.7-2.2-1 0-1.8 0.3-2.5 0.8v-3.6c-0.1-0.3-0.5-0.7-1-0.7s-0.8 0.4-0.8 0.8v7c0 2.3 1.9 4.2 4.2 4.2 1.6 0 3-0.9 3.7-2.2 0.7 1.3 2.1 2.2 3.7 2.2 2.3 0 4.2-1.9 4.2-4.2 0.1-2.4-1.8-4.3-4.1-4.3m-7.5 6.8c-1.4 0-2.5-1.1-2.5-2.5s1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5-1.1 2.5-2.5 2.5m7.5 0c-1.4 0-2.5-1.1-2.5-2.5s1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5-1.1 2.5-2.5 2.5\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"m27.2 20.6l-2.3-2.8 2.3-2.8c0.3-0.4 0.2-0.9-0.2-1.2s-1-0.2-1.3 0.2l-2 2.4-2-2.4c-0.3-0.4-0.9-0.4-1.3-0.2-0.4 0.3-0.5 0.8-0.2 1.2l2.3 2.8-2.3 2.8c-0.3 0.4-0.2 0.9 0.2 1.2s1 0.2 1.3-0.2l2-2.4 2 2.4c0.3 0.4 0.9 0.4 1.3 0.2 0.4-0.3 0.4-0.8 0.2-1.2\"\n    }))));\n\n    this.provider = new _companionClient.Provider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionKeysParams: this.opts.companionKeysParams,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'box',\n      pluginId: this.id\n    });\n    this.defaultLocale = locale;\n    this.i18nInit();\n    this.title = this.i18n('pluginNameBox');\n    this.onFirstRender = this.onFirstRender.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  install() {\n    this.view = new _providerViews.ProviderViews(this, {\n      provider: this.provider\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.view.tearDown();\n    this.unmount();\n  }\n\n  onFirstRender() {\n    return this.view.getFolder();\n  }\n\n  render(state) {\n    return this.view.render(state);\n  }\n\n}\n\nBox.VERSION = packageJson.version;\nmodule.exports = Box;", "\"use strict\";\n\nmodule.exports = require(\"./Box.js\");", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameDropbox: 'Dropbox'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nvar _preact = require(\"preact\");\n\nconst packageJson = {\n  \"version\": \"2.0.8\"\n};\n\nconst locale = require(\"./locale.js\");\n\nclass Dropbox extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'Dropbox';\n\n    _companionClient.Provider.initPlugin(this, opts);\n\n    this.title = this.opts.title || 'Dropbox';\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      fill: \"#0D2481\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M11 8l5 3.185-5 3.186-5-3.186L11 8zm10 0l5 3.185-5 3.186-5-3.186L21 8zM6 17.556l5-3.185 5 3.185-5 3.186-5-3.186zm15-3.185l5 3.185-5 3.186-5-3.186 5-3.185zm-10 7.432l5-3.185 5 3.185-5 3.186-5-3.186z\",\n      fill: \"#FFF\",\n      fillRule: \"nonzero\"\n    })));\n\n    this.provider = new _companionClient.Provider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionKeysParams: this.opts.companionKeysParams,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'dropbox',\n      pluginId: this.id\n    });\n    this.defaultLocale = locale;\n    this.i18nInit();\n    this.title = this.i18n('pluginNameDropbox');\n    this.onFirstRender = this.onFirstRender.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  install() {\n    this.view = new _providerViews.ProviderViews(this, {\n      provider: this.provider\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.view.tearDown();\n    this.unmount();\n  }\n\n  onFirstRender() {\n    return Promise.all([this.provider.fetchPreAuthToken(), this.view.getFolder()]);\n  }\n\n  render(state) {\n    return this.view.render(state);\n  }\n\n}\n\nDropbox.VERSION = packageJson.version;\nmodule.exports = Dropbox;", "\"use strict\";\n\nmodule.exports = require(\"./Dropbox.js\");", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameFacebook: 'Facebook'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nvar _preact = require(\"preact\");\n\nconst packageJson = {\n  \"version\": \"2.0.8\"\n};\n\nconst locale = require(\"./locale.js\");\n\nclass Facebook extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'Facebook';\n\n    _companionClient.Provider.initPlugin(this, opts);\n\n    this.title = this.opts.title || 'Facebook';\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\",\n      fill: \"#3C5A99\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M17.842 26v-8.667h2.653l.398-3.377h-3.051v-2.157c0-.978.248-1.644 1.527-1.644H21V7.132A19.914 19.914 0 0 0 18.623 7c-2.352 0-3.963 1.574-3.963 4.465v2.49H12v3.378h2.66V26h3.182z\",\n      fill: \"#FFF\",\n      fillRule: \"nonzero\"\n    })));\n\n    this.provider = new _companionClient.Provider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionKeysParams: this.opts.companionKeysParams,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'facebook',\n      pluginId: this.id\n    });\n    this.defaultLocale = locale;\n    this.i18nInit();\n    this.title = this.i18n('pluginNameFacebook');\n    this.onFirstRender = this.onFirstRender.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  install() {\n    this.view = new _providerViews.ProviderViews(this, {\n      provider: this.provider\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.view.tearDown();\n    this.unmount();\n  }\n\n  onFirstRender() {\n    return Promise.all([this.provider.fetchPreAuthToken(), this.view.getFolder()]);\n  }\n\n  render(state) {\n    const viewOptions = {};\n\n    if (this.getPluginState().files.length && !this.getPluginState().folders.length) {\n      viewOptions.viewType = 'grid';\n      viewOptions.showFilter = false;\n      viewOptions.showTitles = false;\n    }\n\n    return this.view.render(state, viewOptions);\n  }\n\n}\n\nFacebook.VERSION = packageJson.version;\nmodule.exports = Facebook;", "\"use strict\";\n\nmodule.exports = require(\"./Facebook.js\");", "\"use strict\";\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nclass DriveProviderViews extends _providerViews.ProviderViews {\n  toggleCheckbox(e, file) {\n    e.stopPropagation();\n    e.preventDefault(); // Shared Drives aren't selectable; for all else, defer to the base ProviderView.\n\n    if (!file.custom.isSharedDrive) {\n      super.toggleCheckbox(e, file);\n    }\n  }\n\n}\n\nmodule.exports = DriveProviderViews;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameGoogleDrive: 'Google Drive'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _preact = require(\"preact\");\n\nconst packageJson = {\n  \"version\": \"2.1.2\"\n};\n\nconst DriveProviderViews = require(\"./DriveProviderViews.js\");\n\nconst locale = require(\"./locale.js\");\n\nclass GoogleDrive extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'GoogleDrive';\n    this.title = this.opts.title || 'Google Drive';\n\n    _companionClient.Provider.initPlugin(this, opts);\n\n    this.title = this.opts.title || 'Google Drive';\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      fill: \"#4285F4\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M25.216 17.736L19.043 7h-6.086l6.175 10.736h6.084zm-11.275.896L10.9 24h11.723l3.04-5.368H13.942zm-1.789-10.29l-5.816 10.29L9.38 24l5.905-10.29-3.132-5.369z\",\n      fill: \"#FFF\"\n    })));\n\n    this.provider = new _companionClient.Provider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionKeysParams: this.opts.companionKeysParams,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'drive',\n      pluginId: this.id\n    });\n    this.defaultLocale = locale;\n    this.i18nInit();\n    this.title = this.i18n('pluginNameGoogleDrive');\n    this.onFirstRender = this.onFirstRender.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  install() {\n    this.view = new DriveProviderViews(this, {\n      provider: this.provider\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.view.tearDown();\n    this.unmount();\n  }\n\n  onFirstRender() {\n    return Promise.all([this.provider.fetchPreAuthToken(), this.view.getFolder('root', '/')]);\n  }\n\n  render(state) {\n    return this.view.render(state);\n  }\n\n}\n\nGoogleDrive.VERSION = packageJson.version;\nmodule.exports = GoogleDrive;", "\"use strict\";\n\nmodule.exports = require(\"./GoogleDrive.js\");", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameInstagram: 'Instagram'\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nconst packageJson = {\n  \"version\": \"2.1.2\"\n};\n\nconst locale = require(\"./locale.js\");\n\nclass Instagram extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'Instagram';\n\n    _companionClient.Provider.initPlugin(this, opts);\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      fill: \"#E1306C\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M16 8.622c2.403 0 2.688.009 3.637.052.877.04 1.354.187 1.67.31.392.144.745.374 1.036.673.299.29.529.644.673 1.035.123.317.27.794.31 1.671.043.95.052 1.234.052 3.637s-.009 2.688-.052 3.637c-.04.877-.187 1.354-.31 1.671a2.98 2.98 0 0 1-1.708 1.708c-.317.123-.794.27-1.671.31-.95.043-1.234.053-3.637.053s-2.688-.01-3.637-.053c-.877-.04-1.354-.187-1.671-.31a2.788 2.788 0 0 1-1.035-.673 2.788 2.788 0 0 1-.673-1.035c-.123-.317-.27-.794-.31-1.671-.043-.949-.052-1.234-.052-3.637s.009-2.688.052-3.637c.04-.877.187-1.354.31-1.67.144-.392.374-.745.673-1.036.29-.299.644-.529 1.035-.673.317-.123.794-.27 1.671-.31.95-.043 1.234-.052 3.637-.052zM16 7c-2.444 0-2.75.01-3.71.054-.959.044-1.613.196-2.185.419-.6.225-1.145.58-1.594 1.038-.458.45-.813.993-1.039 1.594-.222.572-.374 1.226-.418 2.184C7.01 13.25 7 13.556 7 16s.01 2.75.054 3.71c.044.959.196 1.613.419 2.185.226.6.58 1.145 1.038 1.594.45.458.993.813 1.594 1.038.572.223 1.227.375 2.184.419.96.044 1.267.054 3.711.054s2.75-.01 3.71-.054c.959-.044 1.613-.196 2.185-.419a4.602 4.602 0 0 0 2.632-2.632c.223-.572.375-1.226.419-2.184.044-.96.054-1.267.054-3.711s-.01-2.75-.054-3.71c-.044-.959-.196-1.613-.419-2.185A4.412 4.412 0 0 0 23.49 8.51a4.412 4.412 0 0 0-1.594-1.039c-.572-.222-1.226-.374-2.184-.418C18.75 7.01 18.444 7 16 7zm0 4.5a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9zm0 7.421a2.921 2.921 0 1 1 0-5.842 2.921 2.921 0 0 1 0 5.842zm4.875-6.671a1.125 1.125 0 1 1 0-2.25 1.125 1.125 0 0 1 0 2.25z\",\n      fill: \"#FFF\"\n    })));\n\n    this.defaultLocale = locale;\n    this.i18nInit();\n    this.title = this.i18n('pluginNameInstagram');\n    this.provider = new _companionClient.Provider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionKeysParams: this.opts.companionKeysParams,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'instagram',\n      pluginId: this.id\n    });\n    this.onFirstRender = this.onFirstRender.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  install() {\n    this.view = new _providerViews.ProviderViews(this, {\n      provider: this.provider,\n      viewType: 'grid',\n      showTitles: false,\n      showFilter: false,\n      showBreadcrumbs: false\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.view.tearDown();\n    this.unmount();\n  }\n\n  onFirstRender() {\n    return Promise.all([this.provider.fetchPreAuthToken(), this.view.getFolder('recent')]);\n  }\n\n  render(state) {\n    return this.view.render(state);\n  }\n\n}\n\nInstagram.VERSION = packageJson.version;\nmodule.exports = Instagram;", "\"use strict\";\n\nmodule.exports = require(\"./Instagram.js\");", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameOneDrive: 'OneDrive'\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nconst packageJson = {\n  \"version\": \"2.1.2\"\n};\n\nconst locale = require(\"./locale.js\");\n\nclass OneDrive extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'OneDrive';\n\n    _companionClient.Provider.initPlugin(this, opts);\n\n    this.title = this.opts.title || 'OneDrive';\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\",\n      fill: \"#0262C0\"\n    }), (0, _preact.h)(\"g\", {\n      fill: \"#FFF\",\n      fillRule: \"nonzero\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M24.157 22s1.492-.205 1.79-1.655a2.624 2.624 0 0 0 .03-.878c-.22-1.64-1.988-2.01-1.988-2.01s.307-1.765-1.312-2.69c-1.62-.925-3.1 0-3.1 0S18.711 13 16.366 13c-3.016 0-3.519 3.448-3.519 3.448S10 16.618 10 19.14c0 2.523 2.597 2.86 2.597 2.86h11.56z\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M9.421 19.246c0-2.197 1.606-3.159 2.871-3.472.44-1.477 1.654-3.439 4.135-3.439H16.445c1.721 0 2.79.823 3.368 1.476a3.99 3.99 0 0 1 1.147-.171h.01l.03.002C21.017 13.5 20.691 10 16.757 10c-2.69 0-3.639 2.345-3.639 2.345s-1.95-1.482-3.955.567c-1.028 1.052-.79 2.669-.79 2.669S6 15.824 6 18.412C6 20.757 8.452 21 8.452 21h1.372a3.77 3.77 0 0 1-.403-1.754z\"\n    }))));\n\n    this.provider = new _companionClient.Provider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'onedrive',\n      pluginId: this.id\n    });\n    this.defaultLocale = locale;\n    this.i18nInit();\n    this.title = this.i18n('pluginNameOneDrive');\n    this.onFirstRender = this.onFirstRender.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  install() {\n    this.view = new _providerViews.ProviderViews(this, {\n      provider: this.provider\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.view.tearDown();\n    this.unmount();\n  }\n\n  onFirstRender() {\n    return Promise.all([this.provider.fetchPreAuthToken(), this.view.getFolder()]);\n  }\n\n  render(state) {\n    return this.view.render(state);\n  }\n\n}\n\nOneDrive.VERSION = packageJson.version;\nmodule.exports = OneDrive;", "\"use strict\";\n\nmodule.exports = require(\"./OneDrive.js\");", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nconst packageJson = {\n  \"version\": \"2.1.1\"\n};\n/**\n * Unsplash\n *\n */\n\nclass Unsplash extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'Unsplash';\n    this.title = this.opts.title || 'Unsplash';\n\n    _companionClient.Provider.initPlugin(this, opts, {});\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      viewBox: \"0 0 32 32\",\n      height: \"32\",\n      width: \"32\",\n      \"aria-hidden\": \"true\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M46.575 10.883v-9h12v9zm12 5h10v18h-32v-18h10v9h12z\",\n      fill: \"#fff\"\n    }), (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M13 12.5V8h6v4.5zm6 2.5h5v9H8v-9h5v4.5h6z\",\n      fill: \"#fff\"\n    }));\n\n    if (!this.opts.companionUrl) {\n      throw new Error('Companion hostname is required, please consult https://uppy.io/docs/companion');\n    }\n\n    this.hostname = this.opts.companionUrl;\n    this.provider = new _companionClient.SearchProvider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'unsplash',\n      pluginId: this.id\n    });\n  }\n\n  install() {\n    this.view = new _providerViews.SearchProviderViews(this, {\n      provider: this.provider,\n      viewType: 'unsplash'\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  onFirstRender() {// do nothing\n  }\n\n  render(state) {\n    return this.view.render(state);\n  }\n\n  uninstall() {\n    this.unmount();\n  }\n\n}\n\nUnsplash.VERSION = packageJson.version;\nmodule.exports = Unsplash;", "\"use strict\";\n\nmodule.exports = require(\"./Unsplash.js\");", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nclass UrlUI extends _preact.Component {\n  constructor(props) {\n    super(props);\n    this.handleKeyPress = this.handleKeyPress.bind(this);\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  componentDidMount() {\n    this.input.value = '';\n  }\n\n  handleKeyPress(ev) {\n    const {\n      addFile\n    } = this.props;\n\n    if (ev.keyCode === 13) {\n      addFile(this.input.value);\n    }\n  }\n\n  handleClick() {\n    const {\n      addFile\n    } = this.props;\n    addFile(this.input.value);\n  }\n\n  render() {\n    const {\n      i18n\n    } = this.props;\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy-Url\"\n    }, (0, _preact.h)(\"input\", {\n      className: \"uppy-u-reset uppy-c-textInput uppy-Url-input\",\n      type: \"text\",\n      \"aria-label\": i18n('enterUrlToImport'),\n      placeholder: i18n('enterUrlToImport'),\n      onKeyUp: this.handleKeyPress,\n      ref: input => {\n        this.input = input;\n      },\n      \"data-uppy-super-focusable\": true\n    }), (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Url-importButton\",\n      type: \"button\",\n      onClick: this.handleClick\n    }, i18n('import')));\n  }\n\n}\n\nmodule.exports = UrlUI;", "\"use strict\";\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n/*\n  SITUATION\n\n    1. Cross-browser dataTransfer.items\n\n      paste in chrome [Copy Image]:\n      0: {kind: \"file\", type: \"image/png\"}\n      1: {kind: \"string\", type: \"text/html\"}\n      paste in safari [Copy Image]:\n      0: {kind: \"file\", type: \"image/png\"}\n      1: {kind: \"string\", type: \"text/html\"}\n      2: {kind: \"string\", type: \"text/plain\"}\n      3: {kind: \"string\", type: \"text/uri-list\"}\n      paste in firefox [Copy Image]:\n      0: {kind: \"file\", type: \"image/png\"}\n      1: {kind: \"string\", type: \"text/html\"}\n\n      paste in chrome [Copy Image Address]:\n      0: {kind: \"string\", type: \"text/plain\"}\n      paste in safari [Copy Image Address]:\n      0: {kind: \"string\", type: \"text/plain\"}\n      1: {kind: \"string\", type: \"text/uri-list\"}\n      paste in firefox [Copy Image Address]:\n      0: {kind: \"string\", type: \"text/plain\"}\n\n      drop in chrome [from browser]:\n      0: {kind: \"string\", type: \"text/uri-list\"}\n      1: {kind: \"string\", type: \"text/html\"}\n      drop in safari [from browser]:\n      0: {kind: \"string\", type: \"text/uri-list\"}\n      1: {kind: \"string\", type: \"text/html\"}\n      2: {kind: \"file\", type: \"image/png\"}\n      drop in firefox [from browser]:\n      0: {kind: \"string\", type: \"text/uri-list\"}\n      1: {kind: \"string\", type: \"text/x-moz-url\"}\n      2: {kind: \"string\", type: \"text/plain\"}\n\n    2. We can determine if it's a 'copypaste' or a 'drop', but we can't discern between [Copy Image] and [Copy Image Address]\n\n  CONCLUSION\n\n    1. 'paste' ([Copy Image] or [Copy Image Address], we can't discern between these two)\n      Don't do anything if there is 'file' item. .handlePaste in the DashboardPlugin will deal with all 'file' items.\n      If there are no 'file' items - handle 'text/plain' items.\n\n    2. 'drop'\n      Take 'text/uri-list' items. Safari has an additional item of .kind === 'file', and you may worry about the item being\n      duplicated (first by DashboardPlugin, and then by UrlPlugin, now), but don't. Directory handling code won't pay\n      attention to this particular item of kind 'file'.\n*/\n\n/**\n * Finds all links dropped/pasted from one browser window to another.\n *\n * @param {object} dataTransfer - DataTransfer instance, e.g. e.clipboardData, or e.dataTransfer\n * @param {string} isDropOrPaste - either 'drop' or 'paste'\n * @param {Function} callback - (urlString) => {}\n */\n\n\nfunction forEachDroppedOrPastedUrl(dataTransfer, isDropOrPaste, callback) {\n  const items = toArray(dataTransfer.items);\n  let urlItems;\n\n  switch (isDropOrPaste) {\n    case 'paste':\n      {\n        const atLeastOneFileIsDragged = items.some(item => item.kind === 'file');\n\n        if (atLeastOneFileIsDragged) {\n          return;\n        }\n\n        urlItems = items.filter(item => item.kind === 'string' && item.type === 'text/plain');\n        break;\n      }\n\n    case 'drop':\n      {\n        urlItems = items.filter(item => item.kind === 'string' && item.type === 'text/uri-list');\n        break;\n      }\n\n    default:\n      {\n        throw new Error(`isDropOrPaste must be either 'drop' or 'paste', but it's ${isDropOrPaste}`);\n      }\n  }\n\n  urlItems.forEach(item => {\n    item.getAsString(urlString => callback(urlString));\n  });\n}\n\nmodule.exports = forEachDroppedOrPastedUrl;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // Label for the \"Import\" button.\n    import: 'Import',\n    // Placeholder text for the URL input.\n    enterUrlToImport: 'Enter URL to import a file',\n    // Error message shown if Companion could not load a URL.\n    failedToFetch: 'Companion failed to fetch this URL, please make sure it\u2019s correct',\n    // Error message shown if the input does not look like a URL.\n    enterCorrectUrl: 'Incorrect URL: Please make sure you are entering a direct link to a file'\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n\nconst UrlUI = require(\"./UrlUI.js\");\n\nconst forEachDroppedOrPastedUrl = require(\"./utils/forEachDroppedOrPastedUrl.js\");\n\nconst packageJson = {\n  \"version\": \"2.2.1\"\n};\n\nconst locale = require(\"./locale.js\");\n\nfunction UrlIcon() {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"32\",\n    height: \"32\",\n    viewBox: \"0 0 32 32\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"none\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"rect\", {\n    className: \"uppy-ProviderIconBg\",\n    fill: \"#FF753E\",\n    width: \"32\",\n    height: \"32\",\n    rx: \"16\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M22.788 15.389l-2.199 2.19a3.184 3.184 0 0 1-.513.437c-.806.584-1.686.876-2.638.876a4.378 4.378 0 0 1-3.519-1.752c-.22-.292-.146-.802.147-1.021.293-.22.806-.146 1.026.146.953 1.313 2.785 1.532 4.105.583a.571.571 0 0 0 .293-.292l2.199-2.189c1.1-1.167 1.1-2.992-.073-4.086a2.976 2.976 0 0 0-4.105 0l-1.246 1.24a.71.71 0 0 1-1.026 0 .703.703 0 0 1 0-1.022l1.246-1.24a4.305 4.305 0 0 1 6.083 0c1.833 1.605 1.906 4.451.22 6.13zm-7.183 5.035l-1.246 1.24a2.976 2.976 0 0 1-4.105 0c-1.172-1.094-1.172-2.991-.073-4.086l2.2-2.19.292-.291c.66-.438 1.393-.657 2.2-.584.805.146 1.465.51 1.905 1.168.22.292.733.365 1.026.146.293-.22.367-.73.147-1.022-.733-.949-1.76-1.532-2.859-1.678-1.1-.22-2.272.073-3.225.802l-.44.438-2.199 2.19c-1.686 1.75-1.612 4.524.074 6.202.88.803 1.979 1.241 3.078 1.241 1.1 0 2.199-.438 3.079-1.24l1.246-1.241a.703.703 0 0 0 0-1.022c-.294-.292-.807-.365-1.1-.073z\",\n    fill: \"#FFF\",\n    fillRule: \"nonzero\"\n  })));\n}\n\nfunction addProtocolToURL(url) {\n  const protocolRegex = /^[a-z0-9]+:\\/\\//;\n  const defaultProtocol = 'http://';\n\n  if (protocolRegex.test(url)) {\n    return url;\n  }\n\n  return defaultProtocol + url;\n}\n\nfunction canHandleRootDrop(e) {\n  const items = toArray(e.dataTransfer.items);\n  const urls = items.filter(item => item.kind === 'string' && item.type === 'text/uri-list');\n  return urls.length > 0;\n}\n\nfunction checkIfCorrectURL(url) {\n  if (!url) return false;\n  const protocol = url.match(/^([a-z0-9]+):\\/\\//)[1];\n\n  if (protocol !== 'http' && protocol !== 'https') {\n    return false;\n  }\n\n  return true;\n}\n\nfunction getFileNameFromUrl(url) {\n  const {\n    pathname\n  } = new URL(url);\n  return pathname.substring(pathname.lastIndexOf('/') + 1);\n}\n/**\n * Url\n *\n */\n\n\nclass Url extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'Url';\n    this.title = this.opts.title || 'Link';\n    this.type = 'acquirer';\n\n    this.icon = () => (0, _preact.h)(UrlIcon, null); // Set default options and locale\n\n\n    this.defaultLocale = locale;\n    const defaultOptions = {};\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.i18nInit();\n    this.hostname = this.opts.companionUrl;\n\n    if (!this.hostname) {\n      throw new Error('Companion hostname is required, please consult https://uppy.io/docs/companion');\n    } // Bind all event handlers for referencability\n\n\n    this.getMeta = this.getMeta.bind(this);\n    this.addFile = this.addFile.bind(this);\n    this.handleRootDrop = this.handleRootDrop.bind(this);\n    this.handleRootPaste = this.handleRootPaste.bind(this);\n    this.client = new _companionClient.RequestClient(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionCookiesRule: this.opts.companionCookiesRule\n    });\n  }\n\n  getMeta(url) {\n    return this.client.post('url/meta', {\n      url\n    }).then(res => {\n      if (res.error) {\n        this.uppy.log('[URL] Error:');\n        this.uppy.log(res.error);\n        throw new Error('Failed to fetch the file');\n      }\n\n      return res;\n    });\n  }\n\n  async addFile(protocollessUrl, optionalMeta) {\n    if (optionalMeta === void 0) {\n      optionalMeta = undefined;\n    }\n\n    const url = this.addProtocolToURL(protocollessUrl);\n\n    if (!this.checkIfCorrectURL(url)) {\n      this.uppy.log(`[URL] Incorrect URL entered: ${url}`);\n      this.uppy.info(this.i18n('enterCorrectUrl'), 'error', 4000);\n      return undefined;\n    }\n\n    try {\n      const meta = await this.getMeta(url);\n      const tagFile = {\n        meta: optionalMeta,\n        source: this.id,\n        name: this.getFileNameFromUrl(url),\n        type: meta.type,\n        data: {\n          size: meta.size\n        },\n        isRemote: true,\n        body: {\n          url\n        },\n        remote: {\n          companionUrl: this.opts.companionUrl,\n          url: `${this.hostname}/url/get`,\n          body: {\n            fileId: url,\n            url\n          },\n          providerOptions: this.client.opts\n        }\n      };\n      this.uppy.log('[Url] Adding remote file');\n\n      try {\n        return this.uppy.addFile(tagFile);\n      } catch (err) {\n        if (!err.isRestriction) {\n          this.uppy.log(err);\n        }\n\n        return err;\n      }\n    } catch (err) {\n      this.uppy.log(err);\n      this.uppy.info({\n        message: this.i18n('failedToFetch'),\n        details: err\n      }, 'error', 4000);\n      return err;\n    }\n  }\n\n  handleRootDrop(e) {\n    forEachDroppedOrPastedUrl(e.dataTransfer, 'drop', url => {\n      this.uppy.log(`[URL] Adding file from dropped url: ${url}`);\n      this.addFile(url);\n    });\n  }\n\n  handleRootPaste(e) {\n    forEachDroppedOrPastedUrl(e.clipboardData, 'paste', url => {\n      this.uppy.log(`[URL] Adding file from pasted url: ${url}`);\n      this.addFile(url);\n    });\n  }\n\n  render() {\n    return (0, _preact.h)(UrlUI, {\n      i18n: this.i18n,\n      addFile: this.addFile\n    });\n  }\n\n  install() {\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.unmount();\n  }\n\n}\n\nUrl.VERSION = packageJson.version;\nmodule.exports = Url; // TODO: remove from prototype in the next major.\n\nUrl.prototype.addProtocolToURL = addProtocolToURL;\nUrl.prototype.canHandleRootDrop = canHandleRootDrop;\nUrl.prototype.checkIfCorrectURL = checkIfCorrectURL;\nUrl.prototype.getFileNameFromUrl = getFileNameFromUrl;", "\"use strict\";\n\nmodule.exports = require(\"./Url.js\");", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameZoom: 'Zoom'\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _providerViews = require(\"@uppy/provider-views\");\n\nconst packageJson = {\n  \"version\": \"1.1.2\"\n};\n\nconst locale = require(\"./locale.js\");\n\nclass Zoom extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.id = this.opts.id || 'Zoom';\n\n    _companionClient.Provider.initPlugin(this, opts);\n\n    this.title = this.opts.title || 'Zoom';\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\",\n      fill: \"#0E71EB\"\n    }), (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"path\", {\n      fill: \"#fff\",\n      d: \"M29,31H14c-1.657,0-3-1.343-3-3V17h15c1.657,0,3,1.343,3,3V31z\",\n      style: {\n        transform: 'translate(-5px, -5px) scale(0.9)'\n      }\n    }), (0, _preact.h)(\"polygon\", {\n      fill: \"#fff\",\n      points: \"37,31 31,27 31,21 37,17\",\n      style: {\n        transform: 'translate(-5px, -5px) scale(0.9)'\n      }\n    })));\n\n    this.provider = new _companionClient.Provider(uppy, {\n      companionUrl: this.opts.companionUrl,\n      companionHeaders: this.opts.companionHeaders,\n      companionKeysParams: this.opts.companionKeysParams,\n      companionCookiesRule: this.opts.companionCookiesRule,\n      provider: 'zoom',\n      pluginId: this.id\n    });\n    this.defaultLocale = locale;\n    this.i18nInit();\n    this.title = this.i18n('pluginNameZoom');\n    this.onFirstRender = this.onFirstRender.bind(this);\n    this.render = this.render.bind(this);\n  }\n\n  install() {\n    this.view = new _providerViews.ProviderViews(this, {\n      provider: this.provider\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n  }\n\n  uninstall() {\n    this.view.tearDown();\n    this.unmount();\n  }\n\n  onFirstRender() {\n    return Promise.all([this.provider.fetchPreAuthToken(), this.view.getFolder()]);\n  }\n\n  render(state) {\n    return this.view.render(state);\n  }\n\n}\n\nZoom.VERSION = packageJson.version;\nmodule.exports = Zoom;", "\"use strict\";\n\nmodule.exports = require(\"./Zoom.js\");", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst Dashboard = require(\"@uppy/dashboard\");\n\nconst Dropbox = require(\"@uppy/dropbox\");\n\nconst GoogleDrive = require(\"@uppy/google-drive\");\n\nconst Instagram = require(\"@uppy/instagram\");\n\nconst Facebook = require(\"@uppy/facebook\");\n\nconst OneDrive = require(\"@uppy/onedrive\");\n\nconst Box = require(\"@uppy/box\");\n\nconst Unsplash = require(\"@uppy/unsplash\");\n\nconst Url = require(\"@uppy/url\");\n\nconst Zoom = require(\"@uppy/zoom\");\n\nconst packageJson = {\n  \"version\": \"0.1.2\"\n};\nconst availablePlugins = [Box, Dropbox, Facebook, GoogleDrive, Instagram, OneDrive, Unsplash, Url, Zoom];\n\nvar _installedPlugins = /*#__PURE__*/_classPrivateFieldLooseKey(\"installedPlugins\");\n\nclass RemoteSources extends _core.BasePlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    Object.defineProperty(this, _installedPlugins, {\n      writable: true,\n      value: new Set()\n    });\n    this.id = this.opts.id || 'RemoteSources';\n    this.type = 'acquirer';\n    const defaultOptions = {\n      sources: ['Box', 'Dropbox', 'Facebook', 'GoogleDrive', 'Instagram', 'OneDrive', 'Unsplash', 'Url'],\n      target: Dashboard\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n\n    if (this.opts.companionUrl == null) {\n      throw new Error('Please specify companionUrl for RemoteSources to work, see https://uppy.io/docs/remote-sources#companionUrl');\n    }\n  }\n\n  setOptions(newOpts) {\n    this.uninstall();\n    super.setOptions(newOpts);\n    this.install();\n  }\n\n  install() {\n    this.opts.sources.forEach(pluginId => {\n      const optsForRemoteSourcePlugin = { ...this.opts,\n        sources: undefined\n      };\n      const plugin = availablePlugins.find(p => p.name === pluginId);\n\n      if (plugin == null) {\n        const pluginNames = availablePlugins.map(p => p.name);\n        const formatter = new Intl.ListFormat('en', {\n          style: 'long',\n          type: 'disjunction'\n        });\n        throw new Error(`Invalid plugin: \"${pluginId}\" is not one of: ${formatter.format(pluginNames)}.`);\n      }\n\n      this.uppy.use(plugin, optsForRemoteSourcePlugin); // `plugin` is a class, but we want to track the instance object\n      // so we have to do `getPlugin` here.\n\n      _classPrivateFieldLooseBase(this, _installedPlugins)[_installedPlugins].add(this.uppy.getPlugin(pluginId));\n    });\n  }\n\n  uninstall() {\n    for (const plugin of _classPrivateFieldLooseBase(this, _installedPlugins)[_installedPlugins]) {\n      this.uppy.removePlugin(plugin);\n    }\n\n    _classPrivateFieldLooseBase(this, _installedPlugins)[_installedPlugins].clear();\n  }\n\n}\n\nRemoteSources.VERSION = packageJson.version;\nmodule.exports = RemoteSources;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = () => {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"32\",\n    height: \"32\",\n    viewBox: \"0 0 32 32\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"none\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"rect\", {\n    className: \"uppy-ProviderIconBg\",\n    fill: \"#2C3E50\",\n    width: \"32\",\n    height: \"32\",\n    rx: \"16\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M24.182 9H7.818C6.81 9 6 9.742 6 10.667v10c0 .916.81 1.666 1.818 1.666h4.546V24h7.272v-1.667h4.546c1 0 1.809-.75 1.809-1.666l.009-10C26 9.742 25.182 9 24.182 9zM24 21H8V11h16v10z\",\n    fill: \"#FFF\",\n    fillRule: \"nonzero\"\n  }), (0, _preact.h)(\"circle\", {\n    fill: \"#FFF\",\n    cx: \"16\",\n    cy: \"16\",\n    r: \"2\"\n  })));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction RecordButton(_ref) {\n  let {\n    recording,\n    onStartRecording,\n    onStopRecording,\n    i18n\n  } = _ref;\n\n  if (recording) {\n    return (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-c-btn uppy-ScreenCapture-button uppy-ScreenCapture-button--video uppy-ScreenCapture-button--stop-rec\",\n      type: \"button\",\n      title: i18n('stopCapturing'),\n      \"aria-label\": i18n('stopCapturing'),\n      onClick: onStopRecording,\n      \"data-uppy-super-focusable\": true\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon\",\n      width: \"100\",\n      height: \"100\",\n      viewBox: \"0 0 100 100\"\n    }, (0, _preact.h)(\"rect\", {\n      x: \"15\",\n      y: \"15\",\n      width: \"70\",\n      height: \"70\"\n    })));\n  }\n\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-ScreenCapture-button uppy-ScreenCapture-button--video\",\n    type: \"button\",\n    title: i18n('startCapturing'),\n    \"aria-label\": i18n('startCapturing'),\n    onClick: onStartRecording,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"100\",\n    height: \"100\",\n    viewBox: \"0 0 100 100\"\n  }, (0, _preact.h)(\"circle\", {\n    cx: \"50\",\n    cy: \"50\",\n    r: \"40\"\n  })));\n}\n\n/**\n * Control screen capture recording. Will show record or stop button.\n */\nmodule.exports = RecordButton;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction SubmitButton(_ref) {\n  let {\n    recording,\n    recordedVideo,\n    onSubmit,\n    i18n\n  } = _ref;\n\n  if (recordedVideo && !recording) {\n    return (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-c-btn uppy-ScreenCapture-button uppy-ScreenCapture-button--submit\",\n      type: \"button\",\n      title: i18n('submitRecordedFile'),\n      \"aria-label\": i18n('submitRecordedFile'),\n      onClick: onSubmit,\n      \"data-uppy-super-focusable\": true\n    }, (0, _preact.h)(\"svg\", {\n      width: \"12\",\n      height: \"9\",\n      viewBox: \"0 0 12 9\",\n      xmlns: \"http://www.w3.org/2000/svg\",\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon\"\n    }, (0, _preact.h)(\"path\", {\n      fill: \"#fff\",\n      fillRule: \"nonzero\",\n      d: \"M10.66 0L12 1.31 4.136 9 0 4.956l1.34-1.31L4.136 6.38z\"\n    })));\n  }\n\n  return null;\n}\n\n/**\n * Submit recorded video to uppy. Enabled when file is available\n */\nmodule.exports = SubmitButton;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\n// TODO: rename this class to StopWatch in the next major.\nclass Stopwatch extends _preact.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      elapsedTime: 0\n    };\n    this.wrapperStyle = {\n      width: '100%',\n      height: '100%',\n      display: 'flex'\n    };\n    this.overlayStyle = {\n      position: 'absolute',\n      width: '100%',\n      height: '100%',\n      background: 'black',\n      opacity: 0.7\n    };\n    this.infoContainerStyle = {\n      marginLeft: 'auto',\n      marginRight: 'auto',\n      marginTop: 'auto',\n      marginBottom: 'auto',\n      zIndex: 1,\n      color: 'white'\n    };\n    this.infotextStyle = {\n      marginLeft: 'auto',\n      marginRight: 'auto',\n      marginBottom: '1rem',\n      fontSize: '1.5rem'\n    };\n    this.timeStyle = {\n      display: 'block',\n      fontWeight: 'bold',\n      marginLeft: 'auto',\n      marginRight: 'auto',\n      fontSize: '3rem',\n      fontFamily: 'Courier New'\n    };\n  }\n\n  startTimer() {\n    this.timerTick();\n    this.timerRunning = true;\n  }\n\n  resetTimer() {\n    clearTimeout(this.timer);\n    this.setState({\n      elapsedTime: 0\n    });\n    this.timerRunning = false;\n  }\n\n  timerTick() {\n    this.timer = setTimeout(() => {\n      this.setState(state => ({\n        elapsedTime: state.elapsedTime + 1\n      }));\n      this.timerTick();\n    }, 1000);\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  fmtMSS(s) {\n    // eslint-disable-next-line no-return-assign, no-param-reassign\n    return (s - (s %= 60)) / 60 + (s > 9 ? ':' : ':0') + s;\n  }\n\n  render() {\n    const {\n      recording,\n      i18n\n    } = { ...this.props\n    };\n    const {\n      elapsedTime\n    } = this.state; // second to minutes and seconds\n\n    const minAndSec = this.fmtMSS(elapsedTime);\n\n    if (recording && !this.timerRunning) {\n      this.startTimer();\n    }\n\n    if (!recording && this.timerRunning) {\n      this.resetTimer();\n    }\n\n    if (recording) {\n      return (0, _preact.h)(\"div\", {\n        style: this.wrapperStyle\n      }, (0, _preact.h)(\"div\", {\n        style: this.overlayStyle\n      }), (0, _preact.h)(\"div\", {\n        style: this.infoContainerStyle\n      }, (0, _preact.h)(\"div\", {\n        style: this.infotextStyle\n      }, i18n('recording')), (0, _preact.h)(\"div\", {\n        style: this.timeStyle\n      }, minAndSec)));\n    }\n\n    return null;\n  }\n\n}\n\nmodule.exports = Stopwatch;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    streamActive,\n    i18n\n  } = _ref;\n\n  if (streamActive) {\n    return (0, _preact.h)(\"div\", {\n      title: i18n('streamActive'),\n      \"aria-label\": i18n('streamActive'),\n      className: \"uppy-ScreenCapture-icon--stream uppy-ScreenCapture-icon--streamActive\"\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"24\",\n      height: \"24\",\n      viewBox: \"0 0 24 24\"\n    }, (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0z\",\n      opacity: \".1\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M0 0h24v24H0z\",\n      fill: \"none\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm18-7H5v1.63c3.96 1.28 7.09 4.41 8.37 8.37H19V7zM1 10v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z\"\n    })));\n  }\n\n  return (0, _preact.h)(\"div\", {\n    title: i18n('streamPassive'),\n    \"aria-label\": i18n('streamPassive'),\n    className: \"uppy-ScreenCapture-icon--stream\"\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    width: \"24\",\n    height: \"24\",\n    viewBox: \"0 0 24 24\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M0 0h24v24H0z\",\n    opacity: \".1\",\n    fill: \"none\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M0 0h24v24H0z\",\n    fill: \"none\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M21 3H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11z\"\n  })));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nconst RecordButton = require(\"./RecordButton.js\");\n\nconst SubmitButton = require(\"./SubmitButton.js\");\n\nconst StopWatch = require(\"./StopWatch.js\");\n\nconst StreamStatus = require(\"./StreamStatus.js\");\n\nclass RecorderScreen extends _preact.Component {\n  componentWillUnmount() {\n    const {\n      onStop\n    } = this.props;\n    onStop();\n  }\n\n  render() {\n    const {\n      recording,\n      stream: videoStream,\n      recordedVideo\n    } = this.props;\n    const videoProps = {\n      playsinline: true\n    }; // show stream\n\n    if (recording || !recordedVideo && !recording) {\n      videoProps.muted = true;\n      videoProps.autoplay = true;\n      videoProps.srcObject = videoStream;\n    } // show preview\n\n\n    if (recordedVideo && !recording) {\n      videoProps.muted = false;\n      videoProps.controls = true;\n      videoProps.src = recordedVideo; // reset srcObject in dom. If not resetted, stream sticks in element\n\n      if (this.videoElement) {\n        this.videoElement.srcObject = undefined;\n      }\n    }\n\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy uppy-ScreenCapture-container\"\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-ScreenCapture-videoContainer\"\n    }, (0, _preact.h)(StreamStatus, this.props), (0, _preact.h)(\"video\", _extends({\n      ref: videoElement => {\n        this.videoElement = videoElement;\n      },\n      className: \"uppy-ScreenCapture-video\"\n    }, videoProps)), (0, _preact.h)(StopWatch, this.props)), (0, _preact.h)(\"div\", {\n      className: \"uppy-ScreenCapture-buttonContainer\"\n    }, (0, _preact.h)(RecordButton, this.props), (0, _preact.h)(SubmitButton, this.props)));\n  }\n\n}\n\nmodule.exports = RecorderScreen;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    startCapturing: 'Begin screen capturing',\n    stopCapturing: 'Stop screen capturing',\n    submitRecordedFile: 'Submit recorded file',\n    streamActive: 'Stream active',\n    streamPassive: 'Stream passive',\n    micDisabled: 'Microphone access denied by user',\n    recording: 'Recording'\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nconst getFileTypeExtension = require(\"@uppy/utils/lib/getFileTypeExtension\");\n\nconst ScreenRecIcon = require(\"./ScreenRecIcon.js\");\n\nconst CaptureScreen = require(\"./CaptureScreen.js\");\n\nconst packageJson = {\n  \"version\": \"2.1.2\"\n};\n\nconst locale = require(\"./locale.js\"); // Check if screen capturing is supported.\n// mediaDevices is supprted on mobile Safari, getDisplayMedia is not\n\n\nfunction isScreenRecordingSupported() {\n  var _navigator$mediaDevic;\n\n  return window.MediaRecorder && ((_navigator$mediaDevic = navigator.mediaDevices) == null ? void 0 : _navigator$mediaDevic.getDisplayMedia); // eslint-disable-line compat/compat\n} // Adapted from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia\n\n\nfunction getMediaDevices() {\n  return window.MediaRecorder && navigator.mediaDevices; // eslint-disable-line compat/compat\n}\n/**\n * Screen capture\n */\n\n\nclass ScreenCapture extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.mediaDevices = getMediaDevices(); // eslint-disable-next-line no-restricted-globals\n\n    this.protocol = location.protocol === 'https:' ? 'https' : 'http';\n    this.id = this.opts.id || 'ScreenCapture';\n    this.title = this.opts.title || 'Screencast';\n    this.type = 'acquirer';\n    this.icon = ScreenRecIcon;\n    this.defaultLocale = locale; // set default options\n    // https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints\n\n    const defaultOptions = {\n      // https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#Properties_of_shared_screen_tracks\n      displayMediaConstraints: {\n        video: {\n          width: 1280,\n          height: 720,\n          frameRate: {\n            ideal: 3,\n            max: 5\n          },\n          cursor: 'motion',\n          displaySurface: 'monitor'\n        }\n      },\n      // https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints/audio\n      userMediaConstraints: {\n        audio: true\n      },\n      preferredVideoMimeType: 'video/webm'\n    }; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    }; // i18n\n\n    this.i18nInit(); // uppy plugin class related\n\n    this.install = this.install.bind(this);\n    this.setPluginState = this.setPluginState.bind(this);\n    this.render = this.render.bind(this); // screen capturer related\n\n    this.start = this.start.bind(this);\n    this.stop = this.stop.bind(this);\n    this.startRecording = this.startRecording.bind(this);\n    this.stopRecording = this.stopRecording.bind(this);\n    this.submit = this.submit.bind(this);\n    this.streamInterrupted = this.streamInactivated.bind(this); // initialize\n\n    this.captureActive = false;\n    this.capturedMediaFile = null;\n  }\n\n  install() {\n    if (!isScreenRecordingSupported()) {\n      this.uppy.log('Screen recorder access is not supported', 'error');\n      return null;\n    }\n\n    this.setPluginState({\n      streamActive: false,\n      audioStreamActive: false\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n\n    return undefined;\n  }\n\n  uninstall() {\n    if (this.videoStream) {\n      this.stop();\n    }\n\n    this.unmount();\n  }\n\n  start() {\n    if (!this.mediaDevices) {\n      return Promise.reject(new Error('Screen recorder access not supported'));\n    }\n\n    this.captureActive = true;\n    this.selectAudioStreamSource();\n    return this.selectVideoStreamSource().then(res => {\n      // something happened in start -> return\n      if (res === false) {\n        // Close the Dashboard panel if plugin is installed\n        // into Dashboard (could be other parent UI plugin)\n        if (this.parent && this.parent.hideAllPanels) {\n          this.parent.hideAllPanels();\n          this.captureActive = false;\n        }\n      }\n    });\n  }\n\n  selectVideoStreamSource() {\n    // if active stream available, return it\n    if (this.videoStream) {\n      return new Promise(resolve => resolve(this.videoStream));\n    } // ask user to select source to record and get mediastream from that\n    // eslint-disable-next-line compat/compat\n\n\n    return this.mediaDevices.getDisplayMedia(this.opts.displayMediaConstraints).then(videoStream => {\n      this.videoStream = videoStream; // add event listener to stop recording if stream is interrupted\n\n      this.videoStream.addEventListener('inactive', () => {\n        this.streamInactivated();\n      });\n      this.setPluginState({\n        streamActive: true\n      });\n      return videoStream;\n    }).catch(err => {\n      this.setPluginState({\n        screenRecError: err\n      });\n      this.userDenied = true;\n      setTimeout(() => {\n        this.userDenied = false;\n      }, 1000);\n      return false;\n    });\n  }\n\n  selectAudioStreamSource() {\n    // if active stream available, return it\n    if (this.audioStream) {\n      return new Promise(resolve => resolve(this.audioStream));\n    } // ask user to select source to record and get mediastream from that\n    // eslint-disable-next-line compat/compat\n\n\n    return this.mediaDevices.getUserMedia(this.opts.userMediaConstraints).then(audioStream => {\n      this.audioStream = audioStream;\n      this.setPluginState({\n        audioStreamActive: true\n      });\n      return audioStream;\n    }).catch(err => {\n      if (err.name === 'NotAllowedError') {\n        this.uppy.info(this.i18n('micDisabled'), 'error', 5000);\n      }\n\n      return false;\n    });\n  }\n\n  startRecording() {\n    const options = {};\n    this.capturedMediaFile = null;\n    this.recordingChunks = [];\n    const {\n      preferredVideoMimeType\n    } = this.opts;\n    this.selectVideoStreamSource().then(videoStream => {\n      // Attempt to use the passed preferredVideoMimeType (if any) during recording.\n      // If the browser doesn't support it, we'll fall back to the browser default instead\n      if (preferredVideoMimeType && MediaRecorder.isTypeSupported(preferredVideoMimeType) && getFileTypeExtension(preferredVideoMimeType)) {\n        options.mimeType = preferredVideoMimeType;\n      } // prepare tracks\n\n\n      const tracks = [videoStream.getVideoTracks()[0]]; // merge audio if exits\n\n      if (this.audioStream) {\n        tracks.push(this.audioStream.getAudioTracks()[0]);\n      } // create new stream from video and audio\n      // eslint-disable-next-line compat/compat\n\n\n      this.outputStream = new MediaStream(tracks); // initialize mediarecorder\n      // eslint-disable-next-line compat/compat\n\n      this.recorder = new MediaRecorder(this.outputStream, options); // push data to buffer when data available\n\n      this.recorder.addEventListener('dataavailable', event => {\n        this.recordingChunks.push(event.data);\n      }); // start recording\n\n      this.recorder.start(); // set plugin state to recording\n\n      this.setPluginState({\n        recording: true\n      });\n    }).catch(err => {\n      this.uppy.log(err, 'error');\n    });\n  }\n\n  streamInactivated() {\n    // get screen recorder state\n    const {\n      recordedVideo,\n      recording\n    } = { ...this.getPluginState()\n    };\n\n    if (!recordedVideo && !recording) {\n      // Close the Dashboard panel if plugin is installed\n      // into Dashboard (could be other parent UI plugin)\n      if (this.parent && this.parent.hideAllPanels) {\n        this.parent.hideAllPanels();\n      }\n    } else if (recording) {\n      // stop recorder if it is active\n      this.uppy.log('Capture stream inactive \u2014 stop recording');\n      this.stopRecording();\n    }\n\n    this.videoStream = null;\n    this.audioStream = null;\n    this.setPluginState({\n      streamActive: false,\n      audioStreamActive: false\n    });\n  }\n\n  stopRecording() {\n    const stopped = new Promise(resolve => {\n      this.recorder.addEventListener('stop', () => {\n        resolve();\n      });\n      this.recorder.stop();\n    });\n    return stopped.then(() => {\n      // recording stopped\n      this.setPluginState({\n        recording: false\n      }); // get video file after recorder stopped\n\n      return this.getVideo();\n    }).then(file => {\n      // store media file\n      this.capturedMediaFile = file; // create object url for capture result preview\n\n      this.setPluginState({\n        // eslint-disable-next-line compat/compat\n        recordedVideo: URL.createObjectURL(file.data)\n      });\n    }).then(() => {\n      this.recordingChunks = null;\n      this.recorder = null;\n    }, error => {\n      this.recordingChunks = null;\n      this.recorder = null;\n      throw error;\n    });\n  }\n\n  submit() {\n    try {\n      // add recorded file to uppy\n      if (this.capturedMediaFile) {\n        this.uppy.addFile(this.capturedMediaFile);\n      }\n    } catch (err) {\n      // Logging the error, exept restrictions, which is handled in Core\n      if (!err.isRestriction) {\n        this.uppy.log(err, 'error');\n      }\n    }\n  }\n\n  stop() {\n    // flush video stream\n    if (this.videoStream) {\n      this.videoStream.getVideoTracks().forEach(track => {\n        track.stop();\n      });\n      this.videoStream.getAudioTracks().forEach(track => {\n        track.stop();\n      });\n      this.videoStream = null;\n    } // flush audio stream\n\n\n    if (this.audioStream) {\n      this.audioStream.getAudioTracks().forEach(track => {\n        track.stop();\n      });\n      this.audioStream.getVideoTracks().forEach(track => {\n        track.stop();\n      });\n      this.audioStream = null;\n    } // flush output stream\n\n\n    if (this.outputStream) {\n      this.outputStream.getAudioTracks().forEach(track => {\n        track.stop();\n      });\n      this.outputStream.getVideoTracks().forEach(track => {\n        track.stop();\n      });\n      this.outputStream = null;\n    } // remove preview video\n\n\n    this.setPluginState({\n      recordedVideo: null\n    });\n    this.captureActive = false;\n  }\n\n  getVideo() {\n    const mimeType = this.recordingChunks[0].type;\n    const fileExtension = getFileTypeExtension(mimeType);\n\n    if (!fileExtension) {\n      return Promise.reject(new Error(`Could not retrieve recording: Unsupported media type \"${mimeType}\"`));\n    }\n\n    const name = `screencap-${Date.now()}.${fileExtension}`;\n    const blob = new Blob(this.recordingChunks, {\n      type: mimeType\n    });\n    const file = {\n      source: this.id,\n      name,\n      data: new Blob([blob], {\n        type: mimeType\n      }),\n      type: mimeType\n    };\n    return Promise.resolve(file);\n  }\n\n  render() {\n    // get screen recorder state\n    const recorderState = this.getPluginState();\n\n    if (!recorderState.streamActive && !this.captureActive && !this.userDenied) {\n      this.start();\n    }\n\n    return (0, _preact.h)(CaptureScreen, _extends({}, recorderState, {\n      // eslint-disable-line react/jsx-props-no-spreading\n      onStartRecording: this.startRecording,\n      onStopRecording: this.stopRecording,\n      onStop: this.stop,\n      onSubmit: this.submit,\n      i18n: this.i18n,\n      stream: this.videoStream\n    }));\n  }\n\n}\n\nScreenCapture.VERSION = packageJson.version;\nmodule.exports = ScreenCapture;", "\"use strict\";\n\nmodule.exports = require(\"./ScreenCapture.js\");", "\"use strict\";\n\nfunction canvasToBlob(canvas, type, quality) {\n  return new Promise(resolve => {\n    canvas.toBlob(resolve, type, quality);\n  });\n}\n\n/**\n * Save a <canvas> element's content to a Blob object.\n *\n * @param {HTMLCanvasElement} canvas\n * @returns {Promise}\n */\nmodule.exports = canvasToBlob;", "\"use strict\";\n\nfunction supportsMediaRecorder() {\n  /* eslint-disable compat/compat */\n  return typeof MediaRecorder === 'function' && !!MediaRecorder.prototype && typeof MediaRecorder.prototype.start === 'function';\n  /* eslint-enable compat/compat */\n}\n\nmodule.exports = supportsMediaRecorder;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = () => {\n  return (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    fill: \"#0097DC\",\n    width: \"66\",\n    height: \"55\",\n    viewBox: \"0 0 66 55\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M57.3 8.433c4.59 0 8.1 3.51 8.1 8.1v29.7c0 4.59-3.51 8.1-8.1 8.1H8.7c-4.59 0-8.1-3.51-8.1-8.1v-29.7c0-4.59 3.51-8.1 8.1-8.1h9.45l4.59-7.02c.54-.54 1.35-1.08 2.16-1.08h16.2c.81 0 1.62.54 2.16 1.08l4.59 7.02h9.45zM33 14.64c-8.62 0-15.393 6.773-15.393 15.393 0 8.62 6.773 15.393 15.393 15.393 8.62 0 15.393-6.773 15.393-15.393 0-8.62-6.773-15.393-15.393-15.393zM33 40c-5.648 0-9.966-4.319-9.966-9.967 0-5.647 4.318-9.966 9.966-9.966s9.966 4.319 9.966 9.966C42.966 35.681 38.648 40 33 40z\",\n    fillRule: \"evenodd\"\n  }));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst CameraIcon = require(\"./CameraIcon.js\");\n\nmodule.exports = _ref => {\n  let {\n    onSnapshot,\n    i18n\n  } = _ref;\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-Webcam-button uppy-Webcam-button--picture\",\n    type: \"button\",\n    title: i18n('takePicture'),\n    \"aria-label\": i18n('takePicture'),\n    onClick: onSnapshot,\n    \"data-uppy-super-focusable\": true\n  }, CameraIcon());\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction RecordButton(_ref) {\n  let {\n    recording,\n    onStartRecording,\n    onStopRecording,\n    i18n\n  } = _ref;\n\n  if (recording) {\n    return (0, _preact.h)(\"button\", {\n      className: \"uppy-u-reset uppy-c-btn uppy-Webcam-button\",\n      type: \"button\",\n      title: i18n('stopRecording'),\n      \"aria-label\": i18n('stopRecording'),\n      onClick: onStopRecording,\n      \"data-uppy-super-focusable\": true\n    }, (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      className: \"uppy-c-icon\",\n      width: \"100\",\n      height: \"100\",\n      viewBox: \"0 0 100 100\"\n    }, (0, _preact.h)(\"rect\", {\n      x: \"15\",\n      y: \"15\",\n      width: \"70\",\n      height: \"70\"\n    })));\n  }\n\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-Webcam-button\",\n    type: \"button\",\n    title: i18n('startRecording'),\n    \"aria-label\": i18n('startRecording'),\n    onClick: onStartRecording,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\",\n    width: \"100\",\n    height: \"100\",\n    viewBox: \"0 0 100 100\"\n  }, (0, _preact.h)(\"circle\", {\n    cx: \"50\",\n    cy: \"50\",\n    r: \"40\"\n  })));\n}\n\nmodule.exports = RecordButton;", "\"use strict\";\n\nfunction formatSeconds(seconds) {\n  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, 0)}`;\n}\n\n/**\n * Takes an Integer value of seconds (e.g. 83) and converts it into a human-readable formatted string (e.g. '1:23').\n *\n * @param {Integer} seconds\n * @returns {string} the formatted seconds (e.g. '1:23' for 1 minute and 23 seconds)\n *\n */\nmodule.exports = formatSeconds;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nconst formatSeconds = require(\"./formatSeconds.js\");\n\nfunction RecordingLength(_ref) {\n  let {\n    recordingLengthSeconds,\n    i18n\n  } = _ref;\n  const formattedRecordingLengthSeconds = formatSeconds(recordingLengthSeconds);\n  return (0, _preact.h)(\"span\", {\n    \"aria-label\": i18n('recordingLength', {\n      recording_length: formattedRecordingLengthSeconds\n    })\n  }, formattedRecordingLengthSeconds);\n}\n\nmodule.exports = RecordingLength;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    currentDeviceId,\n    videoSources,\n    onChangeVideoSource\n  } = _ref;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Webcam-videoSource\"\n  }, (0, _preact.h)(\"select\", {\n    className: \"uppy-u-reset uppy-Webcam-videoSource-select\",\n    onChange: event => {\n      onChangeVideoSource(event.target.value);\n    }\n  }, videoSources.map(videoSource => (0, _preact.h)(\"option\", {\n    key: videoSource.deviceId,\n    value: videoSource.deviceId,\n    selected: videoSource.deviceId === currentDeviceId\n  }, videoSource.label))));\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction SubmitButton(_ref) {\n  let {\n    onSubmit,\n    i18n\n  } = _ref;\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-Webcam-button uppy-Webcam-button--submit\",\n    type: \"button\",\n    title: i18n('submitRecordedFile'),\n    \"aria-label\": i18n('submitRecordedFile'),\n    onClick: onSubmit,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    width: \"12\",\n    height: \"9\",\n    viewBox: \"0 0 12 9\",\n    xmlns: \"http://www.w3.org/2000/svg\",\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\"\n  }, (0, _preact.h)(\"path\", {\n    fill: \"#fff\",\n    fillRule: \"nonzero\",\n    d: \"M10.66 0L12 1.31 4.136 9 0 4.956l1.34-1.31L4.136 6.38z\"\n  })));\n}\n\nmodule.exports = SubmitButton;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction DiscardButton(_ref) {\n  let {\n    onDiscard,\n    i18n\n  } = _ref;\n  return (0, _preact.h)(\"button\", {\n    className: \"uppy-u-reset uppy-c-btn uppy-Webcam-button uppy-Webcam-button--discard\",\n    type: \"button\",\n    title: i18n('discardRecordedFile'),\n    \"aria-label\": i18n('discardRecordedFile'),\n    onClick: onDiscard,\n    \"data-uppy-super-focusable\": true\n  }, (0, _preact.h)(\"svg\", {\n    width: \"13\",\n    height: \"13\",\n    viewBox: \"0 0 13 13\",\n    xmlns: \"http://www.w3.org/2000/svg\",\n    \"aria-hidden\": \"true\",\n    focusable: \"false\",\n    className: \"uppy-c-icon\"\n  }, (0, _preact.h)(\"g\", {\n    fill: \"#FFF\",\n    fillRule: \"evenodd\"\n  }, (0, _preact.h)(\"path\", {\n    d: \"M.496 11.367L11.103.76l1.414 1.414L1.911 12.781z\"\n  }), (0, _preact.h)(\"path\", {\n    d: \"M11.104 12.782L.497 2.175 1.911.76l10.607 10.606z\"\n  }))));\n}\n\nmodule.exports = DiscardButton;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nconst SnapshotButton = require(\"./SnapshotButton.js\");\n\nconst RecordButton = require(\"./RecordButton.js\");\n\nconst RecordingLength = require(\"./RecordingLength.js\");\n\nconst VideoSourceSelect = require(\"./VideoSourceSelect.js\");\n\nconst SubmitButton = require(\"./SubmitButton.js\");\n\nconst DiscardButton = require(\"./DiscardButton.js\");\n\nfunction isModeAvailable(modes, mode) {\n  return modes.indexOf(mode) !== -1;\n}\n\nclass CameraScreen extends _preact.Component {\n  componentDidMount() {\n    const {\n      onFocus\n    } = this.props;\n    onFocus();\n  }\n\n  componentWillUnmount() {\n    const {\n      onStop\n    } = this.props;\n    onStop();\n  }\n\n  render() {\n    const {\n      src,\n      recordedVideo,\n      recording,\n      modes,\n      supportsRecording,\n      videoSources,\n      showVideoSourceDropdown,\n      showRecordingLength,\n      onSubmit,\n      i18n,\n      mirror,\n      onSnapshot,\n      onStartRecording,\n      onStopRecording,\n      onDiscardRecordedVideo,\n      recordingLengthSeconds\n    } = this.props;\n    const hasRecordedVideo = !!recordedVideo;\n    const shouldShowRecordButton = !hasRecordedVideo && supportsRecording && (isModeAvailable(modes, 'video-only') || isModeAvailable(modes, 'audio-only') || isModeAvailable(modes, 'video-audio'));\n    const shouldShowSnapshotButton = !hasRecordedVideo && isModeAvailable(modes, 'picture');\n    const shouldShowRecordingLength = supportsRecording && showRecordingLength && !hasRecordedVideo;\n    const shouldShowVideoSourceDropdown = showVideoSourceDropdown && videoSources && videoSources.length > 1;\n    const videoProps = {\n      playsinline: true\n    };\n\n    if (recordedVideo) {\n      videoProps.muted = false;\n      videoProps.controls = true;\n      videoProps.src = recordedVideo; // reset srcObject in dom. If not resetted, stream sticks in element\n\n      if (this.videoElement) {\n        this.videoElement.srcObject = undefined;\n      }\n    } else {\n      videoProps.muted = true;\n      videoProps.autoplay = true;\n      videoProps.srcObject = src;\n    }\n\n    return (0, _preact.h)(\"div\", {\n      className: \"uppy uppy-Webcam-container\"\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-Webcam-videoContainer\"\n    }, (0, _preact.h)(\"video\", _extends({\n      /* eslint-disable-next-line no-return-assign */\n      ref: videoElement => this.videoElement = videoElement,\n      className: `uppy-Webcam-video  ${mirror ? 'uppy-Webcam-video--mirrored' : ''}`\n      /* eslint-disable-next-line react/jsx-props-no-spreading */\n\n    }, videoProps))), (0, _preact.h)(\"div\", {\n      className: \"uppy-Webcam-footer\"\n    }, (0, _preact.h)(\"div\", {\n      className: \"uppy-Webcam-videoSourceContainer\"\n    }, shouldShowVideoSourceDropdown ? VideoSourceSelect(this.props) : null), (0, _preact.h)(\"div\", {\n      className: \"uppy-Webcam-buttonContainer\"\n    }, shouldShowSnapshotButton && (0, _preact.h)(SnapshotButton, {\n      onSnapshot: onSnapshot,\n      i18n: i18n\n    }), shouldShowRecordButton && (0, _preact.h)(RecordButton, {\n      recording: recording,\n      onStartRecording: onStartRecording,\n      onStopRecording: onStopRecording,\n      i18n: i18n\n    }), hasRecordedVideo && (0, _preact.h)(SubmitButton, {\n      onSubmit: onSubmit,\n      i18n: i18n\n    }), hasRecordedVideo && (0, _preact.h)(DiscardButton, {\n      onDiscard: onDiscardRecordedVideo,\n      i18n: i18n\n    })), (0, _preact.h)(\"div\", {\n      className: \"uppy-Webcam-recordingLength\"\n    }, shouldShowRecordingLength && (0, _preact.h)(RecordingLength, {\n      recordingLengthSeconds: recordingLengthSeconds,\n      i18n: i18n\n    }))));\n  }\n\n}\n\nmodule.exports = CameraScreen;", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nmodule.exports = _ref => {\n  let {\n    icon,\n    i18n,\n    hasCamera\n  } = _ref;\n  return (0, _preact.h)(\"div\", {\n    className: \"uppy-Webcam-permissons\"\n  }, (0, _preact.h)(\"div\", {\n    className: \"uppy-Webcam-permissonsIcon\"\n  }, icon()), (0, _preact.h)(\"h1\", {\n    className: \"uppy-Webcam-title\"\n  }, hasCamera ? i18n('allowAccessTitle') : i18n('noCameraTitle')), (0, _preact.h)(\"p\", null, hasCamera ? i18n('allowAccessDescription') : i18n('noCameraDescription')));\n};", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    pluginNameCamera: 'Camera',\n    noCameraTitle: 'Camera Not Available',\n    noCameraDescription: 'In order to take pictures or record video, please connect a camera device',\n    recordingStoppedMaxSize: 'Recording stopped because the file size is about to exceed the limit',\n    submitRecordedFile: 'Submit recorded file',\n    discardRecordedFile: 'Discard recorded file',\n    // Shown before a picture is taken when the `countdown` option is set.\n    smile: 'Smile!',\n    // Used as the label for the button that takes a picture.\n    // This is not visibly rendered but is picked up by screen readers.\n    takePicture: 'Take a picture',\n    // Used as the label for the button that starts a video recording.\n    // This is not visibly rendered but is picked up by screen readers.\n    startRecording: 'Begin video recording',\n    // Used as the label for the button that stops a video recording.\n    // This is not visibly rendered but is picked up by screen readers.\n    stopRecording: 'Stop video recording',\n    // Used as the label for the recording length counter. See the showRecordingLength option.\n    // This is not visibly rendered but is picked up by screen readers.\n    recordingLength: 'Recording length %{recording_length}',\n    // Title on the \u201Callow access\u201D screen\n    allowAccessTitle: 'Please allow access to your camera',\n    // Description on the \u201Callow access\u201D screen\n    allowAccessDescription: 'In order to take pictures or record video with your camera, please allow camera access for this site.'\n  }\n};", "\"use strict\";\n\nvar _preact = require(\"preact\");\n\nvar _core = require(\"@uppy/core\");\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst getFileTypeExtension = require(\"@uppy/utils/lib/getFileTypeExtension\");\n\nconst mimeTypes = require(\"@uppy/utils/lib/mimeTypes\");\n\nconst canvasToBlob = require(\"@uppy/utils/lib/canvasToBlob\");\n\nconst supportsMediaRecorder = require(\"./supportsMediaRecorder.js\");\n\nconst CameraIcon = require(\"./CameraIcon.js\");\n\nconst CameraScreen = require(\"./CameraScreen.js\");\n\nconst PermissionsScreen = require(\"./PermissionsScreen.js\");\n\nconst packageJson = {\n  \"version\": \"2.2.2\"\n};\n\nconst locale = require(\"./locale.js\");\n/**\n * Normalize a MIME type or file extension into a MIME type.\n *\n * @param {string} fileType - MIME type or a file extension prefixed with `.`.\n * @returns {string|undefined} The MIME type or `undefined` if the fileType is an extension and is not known.\n */\n\n\nfunction toMimeType(fileType) {\n  if (fileType[0] === '.') {\n    return mimeTypes[fileType.slice(1)];\n  }\n\n  return fileType;\n}\n/**\n * Is this MIME type a video?\n *\n * @param {string} mimeType - MIME type.\n * @returns {boolean}\n */\n\n\nfunction isVideoMimeType(mimeType) {\n  return /^video\\/[^*]+$/.test(mimeType);\n}\n/**\n * Is this MIME type an image?\n *\n * @param {string} mimeType - MIME type.\n * @returns {boolean}\n */\n\n\nfunction isImageMimeType(mimeType) {\n  return /^image\\/[^*]+$/.test(mimeType);\n}\n\nfunction getMediaDevices() {\n  // bug in the compatibility data\n  // eslint-disable-next-line compat/compat\n  return navigator.mediaDevices;\n}\n/**\n * Webcam\n */\n\n\nvar _enableMirror = /*#__PURE__*/_classPrivateFieldLooseKey(\"enableMirror\");\n\nclass Webcam extends _core.UIPlugin {\n  // enableMirror is used to toggle mirroring, for instance when discarding the video,\n  // while `opts.mirror` is used to remember the initial user setting\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    Object.defineProperty(this, _enableMirror, {\n      writable: true,\n      value: void 0\n    });\n    this.mediaDevices = getMediaDevices();\n    this.supportsUserMedia = !!this.mediaDevices; // eslint-disable-next-line no-restricted-globals\n\n    this.protocol = location.protocol.match(/https/i) ? 'https' : 'http';\n    this.id = this.opts.id || 'Webcam';\n    this.type = 'acquirer';\n    this.capturedMediaFile = null;\n\n    this.icon = () => (0, _preact.h)(\"svg\", {\n      \"aria-hidden\": \"true\",\n      focusable: \"false\",\n      width: \"32\",\n      height: \"32\",\n      viewBox: \"0 0 32 32\"\n    }, (0, _preact.h)(\"g\", {\n      fill: \"none\",\n      fillRule: \"evenodd\"\n    }, (0, _preact.h)(\"rect\", {\n      className: \"uppy-ProviderIconBg\",\n      fill: \"#03BFEF\",\n      width: \"32\",\n      height: \"32\",\n      rx: \"16\"\n    }), (0, _preact.h)(\"path\", {\n      d: \"M22 11c1.133 0 2 .867 2 2v7.333c0 1.134-.867 2-2 2H10c-1.133 0-2-.866-2-2V13c0-1.133.867-2 2-2h2.333l1.134-1.733C13.6 9.133 13.8 9 14 9h4c.2 0 .4.133.533.267L19.667 11H22zm-6 1.533a3.764 3.764 0 0 0-3.8 3.8c0 2.129 1.672 3.801 3.8 3.801s3.8-1.672 3.8-3.8c0-2.13-1.672-3.801-3.8-3.801zm0 6.261c-1.395 0-2.46-1.066-2.46-2.46 0-1.395 1.065-2.461 2.46-2.461s2.46 1.066 2.46 2.46c0 1.395-1.065 2.461-2.46 2.461z\",\n      fill: \"#FFF\",\n      fillRule: \"nonzero\"\n    })));\n\n    this.defaultLocale = locale; // set default options\n\n    const defaultOptions = {\n      onBeforeSnapshot: () => Promise.resolve(),\n      countdown: false,\n      modes: ['video-audio', 'video-only', 'audio-only', 'picture'],\n      mirror: true,\n      showVideoSourceDropdown: false,\n      facingMode: 'user',\n      preferredImageMimeType: null,\n      preferredVideoMimeType: null,\n      showRecordingLength: false\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.i18nInit();\n    this.title = this.i18n('pluginNameCamera');\n    _classPrivateFieldLooseBase(this, _enableMirror)[_enableMirror] = this.opts.mirror;\n    this.install = this.install.bind(this);\n    this.setPluginState = this.setPluginState.bind(this);\n    this.render = this.render.bind(this); // Camera controls\n\n    this.start = this.start.bind(this);\n    this.stop = this.stop.bind(this);\n    this.takeSnapshot = this.takeSnapshot.bind(this);\n    this.startRecording = this.startRecording.bind(this);\n    this.stopRecording = this.stopRecording.bind(this);\n    this.discardRecordedVideo = this.discardRecordedVideo.bind(this);\n    this.submit = this.submit.bind(this);\n    this.oneTwoThreeSmile = this.oneTwoThreeSmile.bind(this);\n    this.focus = this.focus.bind(this);\n    this.changeVideoSource = this.changeVideoSource.bind(this);\n    this.webcamActive = false;\n\n    if (this.opts.countdown) {\n      this.opts.onBeforeSnapshot = this.oneTwoThreeSmile;\n    }\n\n    this.setPluginState({\n      hasCamera: false,\n      cameraReady: false,\n      cameraError: null,\n      recordingLengthSeconds: 0,\n      videoSources: [],\n      currentDeviceId: null\n    });\n  }\n\n  setOptions(newOpts) {\n    super.setOptions({ ...newOpts,\n      videoConstraints: { // May be undefined but ... handles that\n        ...this.opts.videoConstraints,\n        ...(newOpts == null ? void 0 : newOpts.videoConstraints)\n      }\n    });\n  }\n\n  hasCameraCheck() {\n    if (!this.mediaDevices) {\n      return Promise.resolve(false);\n    }\n\n    return this.mediaDevices.enumerateDevices().then(devices => {\n      return devices.some(device => device.kind === 'videoinput');\n    });\n  }\n\n  isAudioOnly() {\n    return this.opts.modes.length === 1 && this.opts.modes[0] === 'audio-only';\n  }\n\n  getConstraints(deviceId) {\n    if (deviceId === void 0) {\n      deviceId = null;\n    }\n\n    const acceptsAudio = this.opts.modes.indexOf('video-audio') !== -1 || this.opts.modes.indexOf('audio-only') !== -1;\n    const acceptsVideo = !this.isAudioOnly() && (this.opts.modes.indexOf('video-audio') !== -1 || this.opts.modes.indexOf('video-only') !== -1 || this.opts.modes.indexOf('picture') !== -1);\n    const videoConstraints = { ...(this.opts.videoConstraints || {\n        facingMode: this.opts.facingMode\n      }),\n      // facingMode takes precedence over deviceId, and not needed\n      // when specific device is selected\n      ...(deviceId ? {\n        deviceId,\n        facingMode: null\n      } : {})\n    };\n    return {\n      audio: acceptsAudio,\n      video: acceptsVideo ? videoConstraints : false\n    };\n  } // eslint-disable-next-line consistent-return\n\n\n  start(options) {\n    if (options === void 0) {\n      options = null;\n    }\n\n    if (!this.supportsUserMedia) {\n      return Promise.reject(new Error('Webcam access not supported'));\n    }\n\n    this.webcamActive = true;\n\n    if (this.opts.mirror) {\n      _classPrivateFieldLooseBase(this, _enableMirror)[_enableMirror] = true;\n    }\n\n    const constraints = this.getConstraints(options && options.deviceId ? options.deviceId : null);\n    this.hasCameraCheck().then(hasCamera => {\n      this.setPluginState({\n        hasCamera\n      }); // ask user for access to their camera\n\n      return this.mediaDevices.getUserMedia(constraints).then(stream => {\n        this.stream = stream;\n        let currentDeviceId = null;\n        const tracks = this.isAudioOnly() ? stream.getAudioTracks() : stream.getVideoTracks();\n\n        if (!options || !options.deviceId) {\n          currentDeviceId = tracks[0].getSettings().deviceId;\n        } else {\n          tracks.forEach(track => {\n            if (track.getSettings().deviceId === options.deviceId) {\n              currentDeviceId = track.getSettings().deviceId;\n            }\n          });\n        } // Update the sources now, so we can access the names.\n\n\n        this.updateVideoSources();\n        this.setPluginState({\n          currentDeviceId,\n          cameraReady: true\n        });\n      }).catch(err => {\n        this.setPluginState({\n          cameraReady: false,\n          cameraError: err\n        });\n        this.uppy.info(err.message, 'error');\n      });\n    });\n  }\n  /**\n   * @returns {object}\n   */\n\n\n  getMediaRecorderOptions() {\n    const options = {}; // Try to use the `opts.preferredVideoMimeType` or one of the `allowedFileTypes` for the recording.\n    // If the browser doesn't support it, we'll fall back to the browser default instead.\n    // Safari doesn't have the `isTypeSupported` API.\n\n    if (MediaRecorder.isTypeSupported) {\n      const {\n        restrictions\n      } = this.uppy.opts;\n      let preferredVideoMimeTypes = [];\n\n      if (this.opts.preferredVideoMimeType) {\n        preferredVideoMimeTypes = [this.opts.preferredVideoMimeType];\n      } else if (restrictions.allowedFileTypes) {\n        preferredVideoMimeTypes = restrictions.allowedFileTypes.map(toMimeType).filter(isVideoMimeType);\n      }\n\n      const filterSupportedTypes = candidateType => MediaRecorder.isTypeSupported(candidateType) && getFileTypeExtension(candidateType);\n\n      const acceptableMimeTypes = preferredVideoMimeTypes.filter(filterSupportedTypes);\n\n      if (acceptableMimeTypes.length > 0) {\n        // eslint-disable-next-line prefer-destructuring\n        options.mimeType = acceptableMimeTypes[0];\n      }\n    }\n\n    return options;\n  }\n\n  startRecording() {\n    // only used if supportsMediaRecorder() returned true\n    // eslint-disable-next-line compat/compat\n    this.recorder = new MediaRecorder(this.stream, this.getMediaRecorderOptions());\n    this.recordingChunks = [];\n    let stoppingBecauseOfMaxSize = false;\n    this.recorder.addEventListener('dataavailable', event => {\n      this.recordingChunks.push(event.data);\n      const {\n        restrictions\n      } = this.uppy.opts;\n\n      if (this.recordingChunks.length > 1 && restrictions.maxFileSize != null && !stoppingBecauseOfMaxSize) {\n        const totalSize = this.recordingChunks.reduce((acc, chunk) => acc + chunk.size, 0); // Exclude the initial chunk from the average size calculation because it is likely to be a very small outlier\n\n        const averageChunkSize = (totalSize - this.recordingChunks[0].size) / (this.recordingChunks.length - 1);\n        const expectedEndChunkSize = averageChunkSize * 3;\n        const maxSize = Math.max(0, restrictions.maxFileSize - expectedEndChunkSize);\n\n        if (totalSize > maxSize) {\n          stoppingBecauseOfMaxSize = true;\n          this.uppy.info(this.i18n('recordingStoppedMaxSize'), 'warning', 4000);\n          this.stopRecording();\n        }\n      }\n    }); // use a \"time slice\" of 500ms: ondataavailable will be called each 500ms\n    // smaller time slices mean we can more accurately check the max file size restriction\n\n    this.recorder.start(500);\n\n    if (this.opts.showRecordingLength) {\n      // Start the recordingLengthTimer if we are showing the recording length.\n      this.recordingLengthTimer = setInterval(() => {\n        const currentRecordingLength = this.getPluginState().recordingLengthSeconds;\n        this.setPluginState({\n          recordingLengthSeconds: currentRecordingLength + 1\n        });\n      }, 1000);\n    }\n\n    this.setPluginState({\n      isRecording: true\n    });\n  }\n\n  stopRecording() {\n    const stopped = new Promise(resolve => {\n      this.recorder.addEventListener('stop', () => {\n        resolve();\n      });\n      this.recorder.stop();\n\n      if (this.opts.showRecordingLength) {\n        // Stop the recordingLengthTimer if we are showing the recording length.\n        clearInterval(this.recordingLengthTimer);\n        this.setPluginState({\n          recordingLengthSeconds: 0\n        });\n      }\n    });\n    return stopped.then(() => {\n      this.setPluginState({\n        isRecording: false\n      });\n      return this.getVideo();\n    }).then(file => {\n      try {\n        this.capturedMediaFile = file; // create object url for capture result preview\n\n        this.setPluginState({\n          // eslint-disable-next-line compat/compat\n          recordedVideo: URL.createObjectURL(file.data)\n        });\n        _classPrivateFieldLooseBase(this, _enableMirror)[_enableMirror] = false;\n      } catch (err) {\n        // Logging the error, exept restrictions, which is handled in Core\n        if (!err.isRestriction) {\n          this.uppy.log(err);\n        }\n      }\n    }).then(() => {\n      this.recordingChunks = null;\n      this.recorder = null;\n    }, error => {\n      this.recordingChunks = null;\n      this.recorder = null;\n      throw error;\n    });\n  }\n\n  discardRecordedVideo() {\n    this.setPluginState({\n      recordedVideo: null\n    });\n\n    if (this.opts.mirror) {\n      _classPrivateFieldLooseBase(this, _enableMirror)[_enableMirror] = true;\n    }\n\n    this.capturedMediaFile = null;\n  }\n\n  submit() {\n    try {\n      if (this.capturedMediaFile) {\n        this.uppy.addFile(this.capturedMediaFile);\n      }\n    } catch (err) {\n      // Logging the error, exept restrictions, which is handled in Core\n      if (!err.isRestriction) {\n        this.uppy.log(err, 'error');\n      }\n    }\n  }\n\n  async stop() {\n    if (this.stream) {\n      const audioTracks = this.stream.getAudioTracks();\n      const videoTracks = this.stream.getVideoTracks();\n      audioTracks.concat(videoTracks).forEach(track => track.stop());\n    }\n\n    if (this.recorder) {\n      await new Promise(resolve => {\n        this.recorder.addEventListener('stop', resolve, {\n          once: true\n        });\n        this.recorder.stop();\n\n        if (this.opts.showRecordingLength) {\n          clearInterval(this.recordingLengthTimer);\n        }\n      });\n    }\n\n    this.recordingChunks = null;\n    this.recorder = null;\n    this.webcamActive = false;\n    this.stream = null;\n    this.setPluginState({\n      recordedVideo: null,\n      isRecording: false,\n      recordingLengthSeconds: 0\n    });\n  }\n\n  getVideoElement() {\n    return this.el.querySelector('.uppy-Webcam-video');\n  }\n\n  oneTwoThreeSmile() {\n    return new Promise((resolve, reject) => {\n      let count = this.opts.countdown; // eslint-disable-next-line consistent-return\n\n      const countDown = setInterval(() => {\n        if (!this.webcamActive) {\n          clearInterval(countDown);\n          this.captureInProgress = false;\n          return reject(new Error('Webcam is not active'));\n        }\n\n        if (count > 0) {\n          this.uppy.info(`${count}...`, 'warning', 800);\n          count--;\n        } else {\n          clearInterval(countDown);\n          this.uppy.info(this.i18n('smile'), 'success', 1500);\n          setTimeout(() => resolve(), 1500);\n        }\n      }, 1000);\n    });\n  }\n\n  takeSnapshot() {\n    if (this.captureInProgress) return;\n    this.captureInProgress = true;\n    this.opts.onBeforeSnapshot().catch(err => {\n      const message = typeof err === 'object' ? err.message : err;\n      this.uppy.info(message, 'error', 5000);\n      return Promise.reject(new Error(`onBeforeSnapshot: ${message}`));\n    }).then(() => {\n      return this.getImage();\n    }).then(tagFile => {\n      this.captureInProgress = false;\n\n      try {\n        this.uppy.addFile(tagFile);\n      } catch (err) {\n        // Logging the error, except restrictions, which is handled in Core\n        if (!err.isRestriction) {\n          this.uppy.log(err);\n        }\n      }\n    }, error => {\n      this.captureInProgress = false;\n      throw error;\n    });\n  }\n\n  getImage() {\n    const video = this.getVideoElement();\n\n    if (!video) {\n      return Promise.reject(new Error('No video element found, likely due to the Webcam tab being closed.'));\n    }\n\n    const width = video.videoWidth;\n    const height = video.videoHeight;\n    const canvas = document.createElement('canvas');\n    canvas.width = width;\n    canvas.height = height;\n    const ctx = canvas.getContext('2d');\n    ctx.drawImage(video, 0, 0);\n    const {\n      restrictions\n    } = this.uppy.opts;\n    let preferredImageMimeTypes = [];\n\n    if (this.opts.preferredImageMimeType) {\n      preferredImageMimeTypes = [this.opts.preferredImageMimeType];\n    } else if (restrictions.allowedFileTypes) {\n      preferredImageMimeTypes = restrictions.allowedFileTypes.map(toMimeType).filter(isImageMimeType);\n    }\n\n    const mimeType = preferredImageMimeTypes[0] || 'image/jpeg';\n    const ext = getFileTypeExtension(mimeType) || 'jpg';\n    const name = `cam-${Date.now()}.${ext}`;\n    return canvasToBlob(canvas, mimeType).then(blob => {\n      return {\n        source: this.id,\n        name,\n        data: new Blob([blob], {\n          type: mimeType\n        }),\n        type: mimeType\n      };\n    });\n  }\n\n  getVideo() {\n    // Sometimes in iOS Safari, Blobs (especially the first Blob in the recordingChunks Array)\n    // have empty 'type' attributes (e.g. '') so we need to find a Blob that has a defined 'type'\n    // attribute in order to determine the correct MIME type.\n    const mimeType = this.recordingChunks.find(blob => {\n      var _blob$type;\n\n      return ((_blob$type = blob.type) == null ? void 0 : _blob$type.length) > 0;\n    }).type;\n    const fileExtension = getFileTypeExtension(mimeType);\n\n    if (!fileExtension) {\n      return Promise.reject(new Error(`Could not retrieve recording: Unsupported media type \"${mimeType}\"`));\n    }\n\n    const name = `webcam-${Date.now()}.${fileExtension}`;\n    const blob = new Blob(this.recordingChunks, {\n      type: mimeType\n    });\n    const file = {\n      source: this.id,\n      name,\n      data: new Blob([blob], {\n        type: mimeType\n      }),\n      type: mimeType\n    };\n    return Promise.resolve(file);\n  }\n\n  focus() {\n    if (!this.opts.countdown) return;\n    setTimeout(() => {\n      this.uppy.info(this.i18n('smile'), 'success', 1500);\n    }, 1000);\n  }\n\n  changeVideoSource(deviceId) {\n    this.stop();\n    this.start({\n      deviceId\n    });\n  }\n\n  updateVideoSources() {\n    this.mediaDevices.enumerateDevices().then(devices => {\n      this.setPluginState({\n        videoSources: devices.filter(device => device.kind === 'videoinput')\n      });\n    });\n  }\n\n  render() {\n    if (!this.webcamActive) {\n      this.start();\n    }\n\n    const webcamState = this.getPluginState();\n\n    if (!webcamState.cameraReady || !webcamState.hasCamera) {\n      return (0, _preact.h)(PermissionsScreen, {\n        icon: CameraIcon,\n        i18n: this.i18n,\n        hasCamera: webcamState.hasCamera\n      });\n    }\n\n    return (0, _preact.h)(CameraScreen // eslint-disable-next-line react/jsx-props-no-spreading\n    , _extends({}, webcamState, {\n      onChangeVideoSource: this.changeVideoSource,\n      onSnapshot: this.takeSnapshot,\n      onStartRecording: this.startRecording,\n      onStopRecording: this.stopRecording,\n      onDiscardRecordedVideo: this.discardRecordedVideo,\n      onSubmit: this.submit,\n      onFocus: this.focus,\n      onStop: this.stop,\n      i18n: this.i18n,\n      modes: this.opts.modes,\n      showRecordingLength: this.opts.showRecordingLength,\n      showVideoSourceDropdown: this.opts.showVideoSourceDropdown,\n      supportsRecording: supportsMediaRecorder(),\n      recording: webcamState.isRecording,\n      mirror: _classPrivateFieldLooseBase(this, _enableMirror)[_enableMirror],\n      src: this.stream\n    }));\n  }\n\n  install() {\n    this.setPluginState({\n      cameraReady: false,\n      recordingLengthSeconds: 0\n    });\n    const {\n      target\n    } = this.opts;\n\n    if (target) {\n      this.mount(target, this);\n    }\n\n    if (this.mediaDevices) {\n      this.updateVideoSources();\n\n      this.mediaDevices.ondevicechange = () => {\n        this.updateVideoSources();\n\n        if (this.stream) {\n          let restartStream = true;\n          const {\n            videoSources,\n            currentDeviceId\n          } = this.getPluginState();\n          videoSources.forEach(videoSource => {\n            if (currentDeviceId === videoSource.deviceId) {\n              restartStream = false;\n            }\n          });\n\n          if (restartStream) {\n            this.stop();\n            this.start();\n          }\n        }\n      };\n    }\n  }\n\n  uninstall() {\n    this.stop();\n    this.unmount();\n  }\n\n  onUnmount() {\n    this.stop();\n  }\n\n}\n\nWebcam.VERSION = packageJson.version;\nmodule.exports = Webcam;", "\"use strict\";\n\nmodule.exports = require(\"./Webcam.js\");", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.internalRateLimitedQueue = exports.RateLimitedQueue = void 0;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nfunction createCancelError() {\n  return new Error('Cancelled');\n}\n\nvar _activeRequests = /*#__PURE__*/_classPrivateFieldLooseKey(\"activeRequests\");\n\nvar _queuedHandlers = /*#__PURE__*/_classPrivateFieldLooseKey(\"queuedHandlers\");\n\nvar _paused = /*#__PURE__*/_classPrivateFieldLooseKey(\"paused\");\n\nvar _pauseTimer = /*#__PURE__*/_classPrivateFieldLooseKey(\"pauseTimer\");\n\nvar _downLimit = /*#__PURE__*/_classPrivateFieldLooseKey(\"downLimit\");\n\nvar _upperLimit = /*#__PURE__*/_classPrivateFieldLooseKey(\"upperLimit\");\n\nvar _rateLimitingTimer = /*#__PURE__*/_classPrivateFieldLooseKey(\"rateLimitingTimer\");\n\nvar _call = /*#__PURE__*/_classPrivateFieldLooseKey(\"call\");\n\nvar _queueNext = /*#__PURE__*/_classPrivateFieldLooseKey(\"queueNext\");\n\nvar _next = /*#__PURE__*/_classPrivateFieldLooseKey(\"next\");\n\nvar _queue = /*#__PURE__*/_classPrivateFieldLooseKey(\"queue\");\n\nvar _dequeue = /*#__PURE__*/_classPrivateFieldLooseKey(\"dequeue\");\n\nvar _resume = /*#__PURE__*/_classPrivateFieldLooseKey(\"resume\");\n\nvar _increaseLimit = /*#__PURE__*/_classPrivateFieldLooseKey(\"increaseLimit\");\n\nclass RateLimitedQueue {\n  constructor(limit) {\n    Object.defineProperty(this, _dequeue, {\n      value: _dequeue2\n    });\n    Object.defineProperty(this, _queue, {\n      value: _queue2\n    });\n    Object.defineProperty(this, _next, {\n      value: _next2\n    });\n    Object.defineProperty(this, _queueNext, {\n      value: _queueNext2\n    });\n    Object.defineProperty(this, _call, {\n      value: _call2\n    });\n    Object.defineProperty(this, _activeRequests, {\n      writable: true,\n      value: 0\n    });\n    Object.defineProperty(this, _queuedHandlers, {\n      writable: true,\n      value: []\n    });\n    Object.defineProperty(this, _paused, {\n      writable: true,\n      value: false\n    });\n    Object.defineProperty(this, _pauseTimer, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _downLimit, {\n      writable: true,\n      value: 1\n    });\n    Object.defineProperty(this, _upperLimit, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _rateLimitingTimer, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _resume, {\n      writable: true,\n      value: () => this.resume()\n    });\n    Object.defineProperty(this, _increaseLimit, {\n      writable: true,\n      value: () => {\n        if (_classPrivateFieldLooseBase(this, _paused)[_paused]) {\n          _classPrivateFieldLooseBase(this, _rateLimitingTimer)[_rateLimitingTimer] = setTimeout(_classPrivateFieldLooseBase(this, _increaseLimit)[_increaseLimit], 0);\n          return;\n        }\n\n        _classPrivateFieldLooseBase(this, _downLimit)[_downLimit] = this.limit;\n        this.limit = Math.ceil((_classPrivateFieldLooseBase(this, _upperLimit)[_upperLimit] + _classPrivateFieldLooseBase(this, _downLimit)[_downLimit]) / 2);\n\n        for (let i = _classPrivateFieldLooseBase(this, _downLimit)[_downLimit]; i <= this.limit; i++) {\n          _classPrivateFieldLooseBase(this, _queueNext)[_queueNext]();\n        }\n\n        if (_classPrivateFieldLooseBase(this, _upperLimit)[_upperLimit] - _classPrivateFieldLooseBase(this, _downLimit)[_downLimit] > 3) {\n          _classPrivateFieldLooseBase(this, _rateLimitingTimer)[_rateLimitingTimer] = setTimeout(_classPrivateFieldLooseBase(this, _increaseLimit)[_increaseLimit], 2000);\n        } else {\n          _classPrivateFieldLooseBase(this, _downLimit)[_downLimit] = Math.floor(_classPrivateFieldLooseBase(this, _downLimit)[_downLimit] / 2);\n        }\n      }\n    });\n\n    if (typeof limit !== 'number' || limit === 0) {\n      this.limit = Infinity;\n    } else {\n      this.limit = limit;\n    }\n  }\n\n  run(fn, queueOptions) {\n    if (!_classPrivateFieldLooseBase(this, _paused)[_paused] && _classPrivateFieldLooseBase(this, _activeRequests)[_activeRequests] < this.limit) {\n      return _classPrivateFieldLooseBase(this, _call)[_call](fn);\n    }\n\n    return _classPrivateFieldLooseBase(this, _queue)[_queue](fn, queueOptions);\n  }\n\n  wrapPromiseFunction(fn, queueOptions) {\n    var _this = this;\n\n    return function () {\n      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n        args[_key] = arguments[_key];\n      }\n\n      let queuedRequest;\n      const outerPromise = new Promise((resolve, reject) => {\n        queuedRequest = _this.run(() => {\n          let cancelError;\n          let innerPromise;\n\n          try {\n            innerPromise = Promise.resolve(fn(...args));\n          } catch (err) {\n            innerPromise = Promise.reject(err);\n          }\n\n          innerPromise.then(result => {\n            if (cancelError) {\n              reject(cancelError);\n            } else {\n              queuedRequest.done();\n              resolve(result);\n            }\n          }, err => {\n            if (cancelError) {\n              reject(cancelError);\n            } else {\n              queuedRequest.done();\n              reject(err);\n            }\n          });\n          return () => {\n            cancelError = createCancelError();\n          };\n        }, queueOptions);\n      });\n\n      outerPromise.abort = () => {\n        queuedRequest.abort();\n      };\n\n      return outerPromise;\n    };\n  }\n\n  resume() {\n    _classPrivateFieldLooseBase(this, _paused)[_paused] = false;\n    clearTimeout(_classPrivateFieldLooseBase(this, _pauseTimer)[_pauseTimer]);\n\n    for (let i = 0; i < this.limit; i++) {\n      _classPrivateFieldLooseBase(this, _queueNext)[_queueNext]();\n    }\n  }\n\n  /**\n   * Freezes the queue for a while or indefinitely.\n   *\n   * @param {number | null } [duration] Duration for the pause to happen, in milliseconds.\n   *                                    If omitted, the queue won't resume automatically.\n   */\n  pause(duration) {\n    if (duration === void 0) {\n      duration = null;\n    }\n\n    _classPrivateFieldLooseBase(this, _paused)[_paused] = true;\n    clearTimeout(_classPrivateFieldLooseBase(this, _pauseTimer)[_pauseTimer]);\n\n    if (duration != null) {\n      _classPrivateFieldLooseBase(this, _pauseTimer)[_pauseTimer] = setTimeout(_classPrivateFieldLooseBase(this, _resume)[_resume], duration);\n    }\n  }\n  /**\n   * Pauses the queue for a duration, and lower the limit of concurrent requests\n   * when the queue resumes. When the queue resumes, it tries to progressively\n   * increase the limit in `this.#increaseLimit` until another call is made to\n   * `this.rateLimit`.\n   * Call this function when using the RateLimitedQueue for network requests and\n   * the remote server responds with 429 HTTP code.\n   *\n   * @param {number} duration in milliseconds.\n   */\n\n\n  rateLimit(duration) {\n    clearTimeout(_classPrivateFieldLooseBase(this, _rateLimitingTimer)[_rateLimitingTimer]);\n    this.pause(duration);\n\n    if (this.limit > 1 && Number.isFinite(this.limit)) {\n      _classPrivateFieldLooseBase(this, _upperLimit)[_upperLimit] = this.limit - 1;\n      this.limit = _classPrivateFieldLooseBase(this, _downLimit)[_downLimit];\n      _classPrivateFieldLooseBase(this, _rateLimitingTimer)[_rateLimitingTimer] = setTimeout(_classPrivateFieldLooseBase(this, _increaseLimit)[_increaseLimit], duration);\n    }\n  }\n\n  get isPaused() {\n    return _classPrivateFieldLooseBase(this, _paused)[_paused];\n  }\n\n}\n\nexports.RateLimitedQueue = RateLimitedQueue;\n\nfunction _call2(fn) {\n  _classPrivateFieldLooseBase(this, _activeRequests)[_activeRequests] += 1;\n  let done = false;\n  let cancelActive;\n\n  try {\n    cancelActive = fn();\n  } catch (err) {\n    _classPrivateFieldLooseBase(this, _activeRequests)[_activeRequests] -= 1;\n    throw err;\n  }\n\n  return {\n    abort: () => {\n      if (done) return;\n      done = true;\n      _classPrivateFieldLooseBase(this, _activeRequests)[_activeRequests] -= 1;\n      cancelActive();\n\n      _classPrivateFieldLooseBase(this, _queueNext)[_queueNext]();\n    },\n    done: () => {\n      if (done) return;\n      done = true;\n      _classPrivateFieldLooseBase(this, _activeRequests)[_activeRequests] -= 1;\n\n      _classPrivateFieldLooseBase(this, _queueNext)[_queueNext]();\n    }\n  };\n}\n\nfunction _queueNext2() {\n  // Do it soon but not immediately, this allows clearing out the entire queue synchronously\n  // one by one without continuously _advancing_ it (and starting new tasks before immediately\n  // aborting them)\n  queueMicrotask(() => _classPrivateFieldLooseBase(this, _next)[_next]());\n}\n\nfunction _next2() {\n  if (_classPrivateFieldLooseBase(this, _paused)[_paused] || _classPrivateFieldLooseBase(this, _activeRequests)[_activeRequests] >= this.limit) {\n    return;\n  }\n\n  if (_classPrivateFieldLooseBase(this, _queuedHandlers)[_queuedHandlers].length === 0) {\n    return;\n  } // Dispatch the next request, and update the abort/done handlers\n  // so that cancelling it does the Right Thing (and doesn't just try\n  // to dequeue an already-running request).\n\n\n  const next = _classPrivateFieldLooseBase(this, _queuedHandlers)[_queuedHandlers].shift();\n\n  const handler = _classPrivateFieldLooseBase(this, _call)[_call](next.fn);\n\n  next.abort = handler.abort;\n  next.done = handler.done;\n}\n\nfunction _queue2(fn, options) {\n  if (options === void 0) {\n    options = {};\n  }\n\n  const handler = {\n    fn,\n    priority: options.priority || 0,\n    abort: () => {\n      _classPrivateFieldLooseBase(this, _dequeue)[_dequeue](handler);\n    },\n    done: () => {\n      throw new Error('Cannot mark a queued request as done: this indicates a bug');\n    }\n  };\n\n  const index = _classPrivateFieldLooseBase(this, _queuedHandlers)[_queuedHandlers].findIndex(other => {\n    return handler.priority > other.priority;\n  });\n\n  if (index === -1) {\n    _classPrivateFieldLooseBase(this, _queuedHandlers)[_queuedHandlers].push(handler);\n  } else {\n    _classPrivateFieldLooseBase(this, _queuedHandlers)[_queuedHandlers].splice(index, 0, handler);\n  }\n\n  return handler;\n}\n\nfunction _dequeue2(handler) {\n  const index = _classPrivateFieldLooseBase(this, _queuedHandlers)[_queuedHandlers].indexOf(handler);\n\n  if (index !== -1) {\n    _classPrivateFieldLooseBase(this, _queuedHandlers)[_queuedHandlers].splice(index, 1);\n  }\n}\n\nconst internalRateLimitedQueue = Symbol('__queue');\nexports.internalRateLimitedQueue = internalRateLimitedQueue;", "\"use strict\";\n\nconst throttle = require(\"lodash.throttle\");\n\nfunction emitSocketProgress(uploader, progressData, file) {\n  const {\n    progress,\n    bytesUploaded,\n    bytesTotal\n  } = progressData;\n\n  if (progress) {\n    uploader.uppy.log(`Upload progress: ${progress}`);\n    uploader.uppy.emit('upload-progress', file, {\n      uploader,\n      bytesUploaded,\n      bytesTotal\n    });\n  }\n}\n\nmodule.exports = throttle(emitSocketProgress, 300, {\n  leading: true,\n  trailing: true\n});", "\"use strict\";\n\nfunction getSocketHost(url) {\n  // get the host domain\n  const regex = /^(?:https?:\\/\\/|\\/\\/)?(?:[^@\\n]+@)?(?:www\\.)?([^\\n]+)/i;\n  const host = regex.exec(url)[1];\n  const socketProtocol = /^http:\\/\\//i.test(url) ? 'ws' : 'wss';\n  return `${socketProtocol}://${host}`;\n}\n\nmodule.exports = getSocketHost;", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nvar _emitter = /*#__PURE__*/_classPrivateFieldLooseKey(\"emitter\");\n\nvar _events = /*#__PURE__*/_classPrivateFieldLooseKey(\"events\");\n\nclass EventTracker {\n  constructor(emitter) {\n    Object.defineProperty(this, _emitter, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _events, {\n      writable: true,\n      value: []\n    });\n    _classPrivateFieldLooseBase(this, _emitter)[_emitter] = emitter;\n  }\n\n  on(event, fn) {\n    _classPrivateFieldLooseBase(this, _events)[_events].push([event, fn]);\n\n    return _classPrivateFieldLooseBase(this, _emitter)[_emitter].on(event, fn);\n  }\n\n  remove() {\n    for (const [event, fn] of _classPrivateFieldLooseBase(this, _events)[_events].splice(0)) {\n      _classPrivateFieldLooseBase(this, _emitter)[_emitter].off(event, fn);\n    }\n  }\n\n}\n\n/**\n * Create a wrapper around an event emitter with a `remove` method to remove\n * all events that were added using the wrapped emitter.\n */\nmodule.exports = EventTracker;", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nvar _aliveTimer = /*#__PURE__*/_classPrivateFieldLooseKey(\"aliveTimer\");\n\nvar _isDone = /*#__PURE__*/_classPrivateFieldLooseKey(\"isDone\");\n\nvar _onTimedOut = /*#__PURE__*/_classPrivateFieldLooseKey(\"onTimedOut\");\n\nvar _timeout = /*#__PURE__*/_classPrivateFieldLooseKey(\"timeout\");\n\n/**\n * Helper to abort upload requests if there has not been any progress for `timeout` ms.\n * Create an instance using `timer = new ProgressTimeout(10000, onTimeout)`\n * Call `timer.progress()` to signal that there has been progress of any kind.\n * Call `timer.done()` when the upload has completed.\n */\nclass ProgressTimeout {\n  constructor(timeout, timeoutHandler) {\n    Object.defineProperty(this, _aliveTimer, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _isDone, {\n      writable: true,\n      value: false\n    });\n    Object.defineProperty(this, _onTimedOut, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _timeout, {\n      writable: true,\n      value: void 0\n    });\n    _classPrivateFieldLooseBase(this, _timeout)[_timeout] = timeout;\n    _classPrivateFieldLooseBase(this, _onTimedOut)[_onTimedOut] = timeoutHandler;\n  }\n\n  progress() {\n    // Some browsers fire another progress event when the upload is\n    // cancelled, so we have to ignore progress after the timer was\n    // told to stop.\n    if (_classPrivateFieldLooseBase(this, _isDone)[_isDone]) return;\n\n    if (_classPrivateFieldLooseBase(this, _timeout)[_timeout] > 0) {\n      clearTimeout(_classPrivateFieldLooseBase(this, _aliveTimer)[_aliveTimer]);\n      _classPrivateFieldLooseBase(this, _aliveTimer)[_aliveTimer] = setTimeout(_classPrivateFieldLooseBase(this, _onTimedOut)[_onTimedOut], _classPrivateFieldLooseBase(this, _timeout)[_timeout]);\n    }\n  }\n\n  done() {\n    if (!_classPrivateFieldLooseBase(this, _isDone)[_isDone]) {\n      clearTimeout(_classPrivateFieldLooseBase(this, _aliveTimer)[_aliveTimer]);\n      _classPrivateFieldLooseBase(this, _aliveTimer)[_aliveTimer] = null;\n      _classPrivateFieldLooseBase(this, _isDone)[_isDone] = true;\n    }\n  }\n\n}\n\nmodule.exports = ProgressTimeout;", "\"use strict\";\n\nfunction isNetworkError(xhr) {\n  if (!xhr) {\n    return false;\n  }\n\n  return xhr.readyState !== 0 && xhr.readyState !== 4 || xhr.status === 0;\n}\n\nmodule.exports = isNetworkError;", "\"use strict\";\n\nvar _nonSecure = require(\"nanoid/non-secure\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _RateLimitedQueue = require(\"@uppy/utils/lib/RateLimitedQueue\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst emitSocketProgress = require(\"@uppy/utils/lib/emitSocketProgress\");\n\nconst getSocketHost = require(\"@uppy/utils/lib/getSocketHost\");\n\nconst EventTracker = require(\"@uppy/utils/lib/EventTracker\");\n\nconst ProgressTimeout = require(\"@uppy/utils/lib/ProgressTimeout\");\n\nconst ErrorWithCause = require(\"@uppy/utils/lib/ErrorWithCause\");\n\nconst NetworkError = require(\"@uppy/utils/lib/NetworkError\");\n\nconst isNetworkError = require(\"@uppy/utils/lib/isNetworkError\");\n\n// See XHRUpload\nfunction buildResponseError(xhr, error) {\n  if (isNetworkError(xhr)) return new NetworkError(error, xhr);\n  const err = new ErrorWithCause('Upload error', {\n    cause: error\n  });\n  err.request = xhr;\n  return err;\n} // See XHRUpload\n\n\nfunction setTypeInBlob(file) {\n  const dataWithUpdatedType = file.data.slice(0, file.data.size, file.meta.type);\n  return dataWithUpdatedType;\n}\n\nfunction addMetadata(formData, meta, opts) {\n  const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default.\n  : Object.keys(meta);\n  metaFields.forEach(item => {\n    formData.append(item, meta[item]);\n  });\n}\n\nfunction createFormDataUpload(file, opts) {\n  const formPost = new FormData();\n  addMetadata(formPost, file.meta, opts);\n  const dataWithUpdatedType = setTypeInBlob(file);\n\n  if (file.name) {\n    formPost.append(opts.fieldName, dataWithUpdatedType, file.meta.name);\n  } else {\n    formPost.append(opts.fieldName, dataWithUpdatedType);\n  }\n\n  return formPost;\n}\n\nconst createBareUpload = file => file.data;\n\nvar _queueRequestSocketToken = /*#__PURE__*/_classPrivateFieldLooseKey(\"queueRequestSocketToken\");\n\nvar _getOptions = /*#__PURE__*/_classPrivateFieldLooseKey(\"getOptions\");\n\nvar _addEventHandlerForFile = /*#__PURE__*/_classPrivateFieldLooseKey(\"addEventHandlerForFile\");\n\nvar _addEventHandlerIfFileStillExists = /*#__PURE__*/_classPrivateFieldLooseKey(\"addEventHandlerIfFileStillExists\");\n\nvar _uploadLocalFile = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploadLocalFile\");\n\nvar _requestSocketToken = /*#__PURE__*/_classPrivateFieldLooseKey(\"requestSocketToken\");\n\nvar _uploadRemoteFile = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploadRemoteFile\");\n\nclass MiniXHRUpload {\n  constructor(_uppy, _opts) {\n    Object.defineProperty(this, _uploadRemoteFile, {\n      value: _uploadRemoteFile2\n    });\n    Object.defineProperty(this, _uploadLocalFile, {\n      value: _uploadLocalFile2\n    });\n    Object.defineProperty(this, _addEventHandlerIfFileStillExists, {\n      value: _addEventHandlerIfFileStillExists2\n    });\n    Object.defineProperty(this, _addEventHandlerForFile, {\n      value: _addEventHandlerForFile2\n    });\n    Object.defineProperty(this, _getOptions, {\n      value: _getOptions2\n    });\n    Object.defineProperty(this, _queueRequestSocketToken, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _requestSocketToken, {\n      writable: true,\n      value: async file => {\n        const opts = _classPrivateFieldLooseBase(this, _getOptions)[_getOptions](file);\n\n        const Client = file.remote.providerOptions.provider ? _companionClient.Provider : _companionClient.RequestClient;\n        const client = new Client(this.uppy, file.remote.providerOptions);\n        const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default.\n        : Object.keys(file.meta);\n\n        if (file.tus) {\n          // Install file-specific upload overrides.\n          Object.assign(opts, file.tus);\n        }\n\n        const res = await client.post(file.remote.url, { ...file.remote.body,\n          endpoint: opts.endpoint,\n          size: file.data.size,\n          fieldname: opts.fieldName,\n          metadata: Object.fromEntries(metaFields.map(name => [name, file.meta[name]])),\n          httpMethod: opts.method,\n          useFormData: opts.formData,\n          headers: opts.headers\n        });\n        return res.token;\n      }\n    });\n    this.uppy = _uppy;\n    this.opts = {\n      validateStatus(status) {\n        return status >= 200 && status < 300;\n      },\n\n      ..._opts\n    };\n    this.requests = _opts[_RateLimitedQueue.internalRateLimitedQueue];\n    this.uploaderEvents = Object.create(null);\n    this.i18n = _opts.i18n;\n    _classPrivateFieldLooseBase(this, _queueRequestSocketToken)[_queueRequestSocketToken] = this.requests.wrapPromiseFunction(_classPrivateFieldLooseBase(this, _requestSocketToken)[_requestSocketToken], {\n      priority: -1\n    });\n  }\n\n  uploadFile(id, current, total) {\n    const file = this.uppy.getFile(id);\n\n    if (file.error) {\n      throw new Error(file.error);\n    } else if (file.isRemote) {\n      return _classPrivateFieldLooseBase(this, _uploadRemoteFile)[_uploadRemoteFile](file, current, total);\n    }\n\n    return _classPrivateFieldLooseBase(this, _uploadLocalFile)[_uploadLocalFile](file, current, total);\n  }\n\n  connectToServerSocket(file) {\n    return new Promise((resolve, reject) => {\n      const opts = _classPrivateFieldLooseBase(this, _getOptions)[_getOptions](file);\n\n      const token = file.serverToken;\n      const host = getSocketHost(file.remote.companionUrl);\n      let socket;\n\n      const createSocket = () => {\n        if (socket != null) return;\n        socket = new _companionClient.Socket({\n          target: `${host}/api/${token}`\n        });\n        socket.on('progress', progressData => emitSocketProgress(this, progressData, file));\n        socket.on('success', data => {\n          const body = opts.getResponseData(data.response.responseText, data.response);\n          const uploadURL = body[opts.responseUrlFieldName];\n          const uploadResp = {\n            status: data.response.status,\n            body,\n            uploadURL,\n            bytesUploaded: data.bytesUploaded\n          };\n          this.uppy.emit('upload-success', file, uploadResp);\n          queuedRequest.done(); // eslint-disable-line no-use-before-define\n\n          socket.close();\n\n          if (this.uploaderEvents[file.id]) {\n            this.uploaderEvents[file.id].remove();\n            this.uploaderEvents[file.id] = null;\n          }\n\n          return resolve();\n        });\n        socket.on('error', errData => {\n          const resp = errData.response;\n          const error = resp ? opts.getResponseError(resp.responseText, resp) : new ErrorWithCause(errData.error.message, {\n            cause: errData.error\n          });\n          this.uppy.emit('upload-error', file, error);\n          queuedRequest.done(); // eslint-disable-line no-use-before-define\n\n          if (this.uploaderEvents[file.id]) {\n            this.uploaderEvents[file.id].remove();\n            this.uploaderEvents[file.id] = null;\n          }\n\n          reject(error);\n        });\n      };\n\n      this.uploaderEvents[file.id] = new EventTracker(this.uppy);\n      let queuedRequest = this.requests.run(() => {\n        if (file.isPaused) {\n          var _socket;\n\n          (_socket = socket) == null ? void 0 : _socket.send('pause', {});\n        } else {\n          createSocket();\n        }\n\n        return () => socket.close();\n      });\n\n      _classPrivateFieldLooseBase(this, _addEventHandlerForFile)[_addEventHandlerForFile]('file-removed', file.id, () => {\n        var _socket2;\n\n        (_socket2 = socket) == null ? void 0 : _socket2.send('cancel', {});\n        queuedRequest.abort();\n        resolve(`upload ${file.id} was removed`);\n      });\n\n      _classPrivateFieldLooseBase(this, _addEventHandlerIfFileStillExists)[_addEventHandlerIfFileStillExists]('cancel-all', file.id, function (_temp) {\n        let {\n          reason\n        } = _temp === void 0 ? {} : _temp;\n\n        if (reason === 'user') {\n          var _socket3;\n\n          (_socket3 = socket) == null ? void 0 : _socket3.send('cancel', {});\n          queuedRequest.abort();\n        }\n\n        resolve(`upload ${file.id} was canceled`);\n      });\n\n      const onRetryRequest = () => {\n        if (socket == null) {\n          queuedRequest.abort();\n        } else {\n          socket.send('pause', {});\n          queuedRequest.done();\n        }\n\n        queuedRequest = this.requests.run(() => {\n          if (!file.isPaused) {\n            if (socket == null) {\n              createSocket();\n            } else {\n              socket.send('resume', {});\n            }\n          }\n\n          return () => socket.close();\n        });\n      };\n\n      _classPrivateFieldLooseBase(this, _addEventHandlerForFile)[_addEventHandlerForFile]('upload-retry', file.id, onRetryRequest);\n\n      _classPrivateFieldLooseBase(this, _addEventHandlerIfFileStillExists)[_addEventHandlerIfFileStillExists]('retry-all', file.id, onRetryRequest);\n    }).catch(err => {\n      this.uppy.emit('upload-error', file, err);\n      return Promise.reject(err);\n    });\n  }\n\n}\n\nfunction _getOptions2(file) {\n  var _file$xhrUpload;\n\n  const {\n    uppy\n  } = this;\n  const overrides = uppy.getState().xhrUpload;\n  const opts = { ...this.opts,\n    ...(overrides || {}),\n    ...(file.xhrUpload || {}),\n    headers: { ...this.opts.headers,\n      ...(overrides == null ? void 0 : overrides.headers),\n      ...((_file$xhrUpload = file.xhrUpload) == null ? void 0 : _file$xhrUpload.headers)\n    }\n  };\n  return opts;\n}\n\nfunction _addEventHandlerForFile2(eventName, fileID, eventHandler) {\n  this.uploaderEvents[fileID].on(eventName, targetFileID => {\n    if (fileID === targetFileID) eventHandler();\n  });\n}\n\nfunction _addEventHandlerIfFileStillExists2(eventName, fileID, eventHandler) {\n  var _this = this;\n\n  this.uploaderEvents[fileID].on(eventName, function () {\n    if (_this.uppy.getFile(fileID)) eventHandler(...arguments);\n  });\n}\n\nfunction _uploadLocalFile2(file, current, total) {\n  const opts = _classPrivateFieldLooseBase(this, _getOptions)[_getOptions](file);\n\n  this.uppy.log(`uploading ${current} of ${total}`);\n  return new Promise((resolve, reject) => {\n    // This is done in index.js in the S3 plugin.\n    // this.uppy.emit('upload-started', file)\n    const data = opts.formData ? createFormDataUpload(file, opts) : createBareUpload(file, opts);\n    const xhr = new XMLHttpRequest();\n    this.uploaderEvents[file.id] = new EventTracker(this.uppy);\n    const timer = new ProgressTimeout(opts.timeout, () => {\n      xhr.abort(); // eslint-disable-next-line no-use-before-define\n\n      queuedRequest.done();\n      const error = new Error(this.i18n('timedOut', {\n        seconds: Math.ceil(opts.timeout / 1000)\n      }));\n      this.uppy.emit('upload-error', file, error);\n      reject(error);\n    });\n    const id = (0, _nonSecure.nanoid)();\n    xhr.upload.addEventListener('loadstart', () => {\n      this.uppy.log(`[AwsS3/XHRUpload] ${id} started`);\n    });\n    xhr.upload.addEventListener('progress', ev => {\n      this.uppy.log(`[AwsS3/XHRUpload] ${id} progress: ${ev.loaded} / ${ev.total}`); // Begin checking for timeouts when progress starts, instead of loading,\n      // to avoid timing out requests on browser concurrency queue\n\n      timer.progress();\n\n      if (ev.lengthComputable) {\n        this.uppy.emit('upload-progress', file, {\n          uploader: this,\n          bytesUploaded: ev.loaded,\n          bytesTotal: ev.total\n        });\n      }\n    });\n    xhr.addEventListener('load', ev => {\n      this.uppy.log(`[AwsS3/XHRUpload] ${id} finished`);\n      timer.done(); // eslint-disable-next-line no-use-before-define\n\n      queuedRequest.done();\n\n      if (this.uploaderEvents[file.id]) {\n        this.uploaderEvents[file.id].remove();\n        this.uploaderEvents[file.id] = null;\n      }\n\n      if (opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {\n        const body = opts.getResponseData(xhr.responseText, xhr);\n        const uploadURL = body[opts.responseUrlFieldName];\n        const uploadResp = {\n          status: ev.target.status,\n          body,\n          uploadURL\n        };\n        this.uppy.emit('upload-success', file, uploadResp);\n\n        if (uploadURL) {\n          this.uppy.log(`Download ${file.name} from ${uploadURL}`);\n        }\n\n        return resolve(file);\n      }\n\n      const body = opts.getResponseData(xhr.responseText, xhr);\n      const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));\n      const response = {\n        status: ev.target.status,\n        body\n      };\n      this.uppy.emit('upload-error', file, error, response);\n      return reject(error);\n    });\n    xhr.addEventListener('error', () => {\n      this.uppy.log(`[AwsS3/XHRUpload] ${id} errored`);\n      timer.done(); // eslint-disable-next-line no-use-before-define\n\n      queuedRequest.done();\n\n      if (this.uploaderEvents[file.id]) {\n        this.uploaderEvents[file.id].remove();\n        this.uploaderEvents[file.id] = null;\n      }\n\n      const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));\n      this.uppy.emit('upload-error', file, error);\n      return reject(error);\n    });\n    xhr.open(opts.method.toUpperCase(), opts.endpoint, true); // IE10 does not allow setting `withCredentials` and `responseType`\n    // before `open()` is called. It\u2019s important to set withCredentials\n    // to a boolean, otherwise React Native crashes\n\n    xhr.withCredentials = Boolean(opts.withCredentials);\n\n    if (opts.responseType !== '') {\n      xhr.responseType = opts.responseType;\n    }\n\n    Object.keys(opts.headers).forEach(header => {\n      xhr.setRequestHeader(header, opts.headers[header]);\n    });\n    const queuedRequest = this.requests.run(() => {\n      xhr.send(data);\n      return () => {\n        // eslint-disable-next-line no-use-before-define\n        timer.done();\n        xhr.abort();\n      };\n    }, {\n      priority: 1\n    });\n\n    _classPrivateFieldLooseBase(this, _addEventHandlerForFile)[_addEventHandlerForFile]('file-removed', file.id, () => {\n      queuedRequest.abort();\n      reject(new Error('File removed'));\n    });\n\n    _classPrivateFieldLooseBase(this, _addEventHandlerIfFileStillExists)[_addEventHandlerIfFileStillExists]('cancel-all', file.id, function (_temp2) {\n      let {\n        reason\n      } = _temp2 === void 0 ? {} : _temp2;\n\n      if (reason === 'user') {\n        queuedRequest.abort();\n      }\n\n      reject(new Error('Upload cancelled'));\n    });\n  });\n}\n\nasync function _uploadRemoteFile2(file) {\n  // TODO: we could rewrite this to use server-sent events instead of creating WebSockets.\n  try {\n    if (file.serverToken) {\n      return this.connectToServerSocket(file);\n    }\n\n    const serverToken = await _classPrivateFieldLooseBase(this, _queueRequestSocketToken)[_queueRequestSocketToken](file);\n    if (!this.uppy.getState().files[file.id]) return undefined;\n    this.uppy.setFileState(file.id, {\n      serverToken\n    });\n    return this.connectToServerSocket(this.uppy.getFile(file.id));\n  } catch (err) {\n    this.uppy.emit('upload-error', file, err);\n    throw err;\n  }\n}\n\nmodule.exports = MiniXHRUpload;", "\"use strict\";\n\n/**\n * Remove parameters like `charset=utf-8` from the end of a mime type string.\n *\n * @param {string} mimeType - The mime type string that may have optional parameters.\n * @returns {string} The \"base\" mime type, i.e. only 'category/type'.\n */\nfunction removeMimeParameters(mimeType) {\n  return mimeType.replace(/;.*$/, '');\n}\n/**\n * Check if a response contains XML based on the response object and its text content.\n *\n * @param {string} content - The text body of the response.\n * @param {object|XMLHttpRequest} xhr - The XHR object or response object from Companion.\n * @returns {bool} Whether the content is (probably) XML.\n */\n\n\nfunction isXml(content, xhr) {\n  const rawContentType = xhr.headers ? xhr.headers['content-type'] : xhr.getResponseHeader('Content-Type');\n\n  if (typeof rawContentType === 'string') {\n    const contentType = removeMimeParameters(rawContentType).toLowerCase();\n\n    if (contentType === 'application/xml' || contentType === 'text/xml') {\n      return true;\n    } // GCS uses text/html for some reason\n    // https://github.com/transloadit/uppy/issues/896\n\n\n    if (contentType === 'text/html' && /^<\\?xml /.test(content)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nmodule.exports = isXml;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    timedOut: 'Upload stalled for %{seconds} seconds, aborting.'\n  }\n};", "\"use strict\";\n\nvar _RateLimitedQueue = require(\"@uppy/utils/lib/RateLimitedQueue\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nlet _Symbol$for;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\n/**\n * This plugin is currently a A Big Hack\u2122! The core reason for that is how this plugin\n * interacts with Uppy's current pipeline design. The pipeline can handle files in steps,\n * including preprocessing, uploading, and postprocessing steps. This plugin initially\n * was designed to do its work in a preprocessing step, and let XHRUpload deal with the\n * actual file upload as an uploading step. However, Uppy runs steps on all files at once,\n * sequentially: first, all files go through a preprocessing step, then, once they are all\n * done, they go through the uploading step.\n *\n * For S3, this causes severely broken behaviour when users upload many files. The\n * preprocessing step will request S3 upload URLs that are valid for a short time only,\n * but it has to do this for _all_ files, which can take a long time if there are hundreds\n * or even thousands of files. By the time the uploader step starts, the first URLs may\n * already have expired. If not, the uploading might take such a long time that later URLs\n * will expire before some files can be uploaded.\n *\n * The long-term solution to this problem is to change the upload pipeline so that files\n * can be sent to the next step individually. That requires a breaking change, so it is\n * planned for some future Uppy version.\n *\n * In the mean time, this plugin is stuck with a hackier approach: the necessary parts\n * of the XHRUpload implementation were copied into this plugin, as the MiniXHRUpload\n * class, and this plugin calls into it immediately once it receives an upload URL.\n * This isn't as nicely modular as we'd like and requires us to maintain two copies of\n * the XHRUpload code, but at least it's not horrifically broken :)\n */\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst packageJson = {\n  \"version\": \"2.2.4\"\n};\n\nconst MiniXHRUpload = require(\"./MiniXHRUpload.js\");\n\nconst isXml = require(\"./isXml.js\");\n\nconst locale = require(\"./locale.js\");\n\nfunction resolveUrl(origin, link) {\n  return new URL(link, origin || undefined).toString();\n}\n/**\n * Get the contents of a named tag in an XML source string.\n *\n * @param {string} source - The XML source string.\n * @param {string} tagName - The name of the tag.\n * @returns {string} The contents of the tag, or the empty string if the tag does not exist.\n */\n\n\nfunction getXmlValue(source, tagName) {\n  const start = source.indexOf(`<${tagName}>`);\n  const end = source.indexOf(`</${tagName}>`, start);\n  return start !== -1 && end !== -1 ? source.slice(start + tagName.length + 2, end) : '';\n}\n\nfunction assertServerError(res) {\n  if (res && res.error) {\n    const error = new Error(res.message);\n    Object.assign(error, res.error);\n    throw error;\n  }\n\n  return res;\n}\n\nfunction validateParameters(file, params) {\n  const valid = params != null && typeof params.url === 'string' && (typeof params.fields === 'object' || params.fields == null);\n\n  if (!valid) {\n    const err = new TypeError(`AwsS3: got incorrect result from 'getUploadParameters()' for file '${file.name}', expected an object '{ url, method, fields, headers }' but got '${JSON.stringify(params)}' instead.\\nSee https://uppy.io/docs/aws-s3/#getUploadParameters-file for more on the expected format.`);\n    throw err;\n  }\n\n  const methodIsValid = params.method == null || /^p(u|os)t$/i.test(params.method);\n\n  if (!methodIsValid) {\n    const err = new TypeError(`AwsS3: got incorrect method from 'getUploadParameters()' for file '${file.name}', expected  'put' or 'post' but got '${params.method}' instead.\\nSee https://uppy.io/docs/aws-s3/#getUploadParameters-file for more on the expected format.`);\n    throw err;\n  }\n} // Get the error data from a failed XMLHttpRequest instance.\n// `content` is the S3 response as a string.\n// `xhr` is the XMLHttpRequest instance.\n\n\nfunction defaultGetResponseError(content, xhr) {\n  // If no response, we don't have a specific error message, use the default.\n  if (!isXml(content, xhr)) {\n    return undefined;\n  }\n\n  const error = getXmlValue(content, 'Message');\n  return new Error(error);\n} // warning deduplication flag: see `getResponseData()` XHRUpload option definition\n\n\nlet warnedSuccessActionStatus = false;\n\nvar _client = /*#__PURE__*/_classPrivateFieldLooseKey(\"client\");\n\nvar _requests = /*#__PURE__*/_classPrivateFieldLooseKey(\"requests\");\n\nvar _uploader = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploader\");\n\nvar _handleUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"handleUpload\");\n\nvar _setCompanionHeaders = /*#__PURE__*/_classPrivateFieldLooseKey(\"setCompanionHeaders\");\n\n_Symbol$for = Symbol.for('uppy test: getClient');\n\nclass AwsS3 extends BasePlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    Object.defineProperty(this, _client, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _requests, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _uploader, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _handleUpload, {\n      writable: true,\n      value: fileIDs => {\n        /**\n         * keep track of `getUploadParameters()` responses\n         * so we can cancel the calls individually using just a file ID\n         *\n         * @type {Record<string, import('@uppy/utils/lib/RateLimitedQueue').AbortablePromise<unknown>>}\n         */\n        const paramsPromises = Object.create(null);\n\n        function onremove(file) {\n          var _paramsPromises$id;\n\n          const {\n            id\n          } = file;\n          (_paramsPromises$id = paramsPromises[id]) == null ? void 0 : _paramsPromises$id.abort();\n        }\n\n        this.uppy.on('file-removed', onremove);\n        fileIDs.forEach(id => {\n          const file = this.uppy.getFile(id);\n          this.uppy.emit('upload-started', file);\n        });\n\n        const getUploadParameters = _classPrivateFieldLooseBase(this, _requests)[_requests].wrapPromiseFunction(file => {\n          return this.opts.getUploadParameters(file);\n        });\n\n        const numberOfFiles = fileIDs.length;\n        return Promise.allSettled(fileIDs.map((id, index) => {\n          paramsPromises[id] = getUploadParameters(this.uppy.getFile(id));\n          return paramsPromises[id].then(params => {\n            delete paramsPromises[id];\n            const file = this.uppy.getFile(id);\n            validateParameters(file, params);\n            const {\n              method = 'post',\n              url,\n              fields,\n              headers\n            } = params;\n            const xhrOpts = {\n              method,\n              formData: method.toLowerCase() === 'post',\n              endpoint: url,\n              metaFields: fields ? Object.keys(fields) : []\n            };\n\n            if (headers) {\n              xhrOpts.headers = headers;\n            }\n\n            this.uppy.setFileState(file.id, {\n              meta: { ...file.meta,\n                ...fields\n              },\n              xhrUpload: xhrOpts\n            });\n            return _classPrivateFieldLooseBase(this, _uploader)[_uploader].uploadFile(file.id, index, numberOfFiles);\n          }).catch(error => {\n            delete paramsPromises[id];\n            const file = this.uppy.getFile(id);\n            this.uppy.emit('upload-error', file, error);\n            return Promise.reject(error);\n          });\n        })).finally(() => {\n          // cleanup.\n          this.uppy.off('file-removed', onremove);\n        });\n      }\n    });\n    Object.defineProperty(this, _setCompanionHeaders, {\n      writable: true,\n      value: () => {\n        _classPrivateFieldLooseBase(this, _client)[_client].setCompanionHeaders(this.opts.companionHeaders);\n\n        return Promise.resolve();\n      }\n    });\n    this.type = 'uploader';\n    this.id = this.opts.id || 'AwsS3';\n    this.title = 'AWS S3';\n    this.defaultLocale = locale;\n    const defaultOptions = {\n      timeout: 30 * 1000,\n      limit: 0,\n      metaFields: [],\n      // have to opt in\n      getUploadParameters: this.getUploadParameters.bind(this),\n      companionHeaders: {}\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    }; // TODO: remove i18n once we can depend on XHRUpload instead of MiniXHRUpload\n\n    this.i18nInit();\n    _classPrivateFieldLooseBase(this, _client)[_client] = new _companionClient.RequestClient(uppy, opts);\n    _classPrivateFieldLooseBase(this, _requests)[_requests] = new _RateLimitedQueue.RateLimitedQueue(this.opts.limit);\n  }\n\n  [_Symbol$for]() {\n    return _classPrivateFieldLooseBase(this, _client)[_client];\n  } // TODO: remove getter and setter for #client on the next major release\n\n\n  get client() {\n    return _classPrivateFieldLooseBase(this, _client)[_client];\n  }\n\n  set client(client) {\n    _classPrivateFieldLooseBase(this, _client)[_client] = client;\n  }\n\n  getUploadParameters(file) {\n    if (!this.opts.companionUrl) {\n      throw new Error('Expected a `companionUrl` option containing a Companion address.');\n    }\n\n    const filename = file.meta.name;\n    const {\n      type\n    } = file.meta;\n    const metadata = Object.fromEntries(this.opts.metaFields.filter(key => file.meta[key] != null).map(key => [`metadata[${key}]`, file.meta[key].toString()]));\n    const query = new URLSearchParams({\n      filename,\n      type,\n      ...metadata\n    });\n    return _classPrivateFieldLooseBase(this, _client)[_client].get(`s3/params?${query}`).then(assertServerError);\n  }\n\n  install() {\n    const {\n      uppy\n    } = this;\n    uppy.addPreProcessor(_classPrivateFieldLooseBase(this, _setCompanionHeaders)[_setCompanionHeaders]);\n    uppy.addUploader(_classPrivateFieldLooseBase(this, _handleUpload)[_handleUpload]); // Get the response data from a successful XMLHttpRequest instance.\n    // `content` is the S3 response as a string.\n    // `xhr` is the XMLHttpRequest instance.\n\n    function defaultGetResponseData(content, xhr) {\n      const opts = this; // If no response, we've hopefully done a PUT request to the file\n      // in the bucket on its full URL.\n\n      if (!isXml(content, xhr)) {\n        if (opts.method.toUpperCase() === 'POST') {\n          if (!warnedSuccessActionStatus) {\n            uppy.log('[AwsS3] No response data found, make sure to set the success_action_status AWS SDK option to 201. See https://uppy.io/docs/aws-s3/#POST-Uploads', 'warning');\n            warnedSuccessActionStatus = true;\n          } // The responseURL won't contain the object key. Give up.\n\n\n          return {\n            location: null\n          };\n        } // responseURL is not available in older browsers.\n\n\n        if (!xhr.responseURL) {\n          return {\n            location: null\n          };\n        } // Trim the query string because it's going to be a bunch of presign\n        // parameters for a PUT request\u2014doing a GET request with those will\n        // always result in an error\n\n\n        return {\n          location: xhr.responseURL.replace(/\\?.*$/, '')\n        };\n      }\n\n      return {\n        // Some S3 alternatives do not reply with an absolute URL.\n        // Eg DigitalOcean Spaces uses /$bucketName/xyz\n        location: resolveUrl(xhr.responseURL, getXmlValue(content, 'Location')),\n        bucket: getXmlValue(content, 'Bucket'),\n        key: getXmlValue(content, 'Key'),\n        etag: getXmlValue(content, 'ETag')\n      };\n    }\n\n    const xhrOptions = {\n      fieldName: 'file',\n      responseUrlFieldName: 'location',\n      timeout: this.opts.timeout,\n      // Share the rate limiting queue with XHRUpload.\n      [_RateLimitedQueue.internalRateLimitedQueue]: _classPrivateFieldLooseBase(this, _requests)[_requests],\n      responseType: 'text',\n      getResponseData: this.opts.getResponseData || defaultGetResponseData,\n      getResponseError: defaultGetResponseError\n    }; // TODO: remove i18n once we can depend on XHRUpload instead of MiniXHRUpload\n\n    xhrOptions.i18n = this.i18n; // Revert to `uppy.use(XHRUpload)` once the big comment block at the top of\n    // this file is solved\n\n    _classPrivateFieldLooseBase(this, _uploader)[_uploader] = new MiniXHRUpload(uppy, xhrOptions);\n  }\n\n  uninstall() {\n    this.uppy.removePreProcessor(_classPrivateFieldLooseBase(this, _setCompanionHeaders)[_setCompanionHeaders]);\n    this.uppy.removeUploader(_classPrivateFieldLooseBase(this, _handleUpload)[_handleUpload]);\n  }\n\n}\n\nAwsS3.VERSION = packageJson.version;\nmodule.exports = AwsS3;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.createAbortError = exports.AbortSignal = exports.AbortController = void 0;\n\n/**\n * Little AbortController proxy module so we can swap out the implementation easily later.\n */\nconst {\n  AbortController\n} = globalThis;\nexports.AbortController = AbortController;\nconst {\n  AbortSignal\n} = globalThis;\nexports.AbortSignal = AbortSignal;\n\nconst createAbortError = function (message) {\n  if (message === void 0) {\n    message = 'Aborted';\n  }\n\n  return new DOMException(message, 'AbortError');\n};\n\nexports.createAbortError = createAbortError;", "\"use strict\";\n\nvar _AbortController = require(\"./AbortController.js\");\n\nfunction delay(ms, opts) {\n  return new Promise((resolve, reject) => {\n    var _opts$signal, _opts$signal2;\n\n    if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n      return reject((0, _AbortController.createAbortError)());\n    }\n\n    const timeout = setTimeout(() => {\n      cleanup(); // eslint-disable-line no-use-before-define\n\n      resolve();\n    }, ms);\n\n    function onabort() {\n      clearTimeout(timeout);\n      cleanup(); // eslint-disable-line no-use-before-define\n\n      reject((0, _AbortController.createAbortError)());\n    }\n\n    opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener('abort', onabort);\n\n    function cleanup() {\n      var _opts$signal3;\n\n      opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener('abort', onabort);\n    }\n\n    return undefined;\n  });\n}\n\n/**\n * Return a Promise that resolves after `ms` milliseconds.\n *\n * @param {number} ms - Number of milliseconds to wait.\n * @param {{ signal?: AbortSignal }} [opts] - An abort signal that can be used to cancel the delay early.\n * @returns {Promise<void>} A Promise that resolves after the given amount of `ms`.\n */\nmodule.exports = delay;", "\"use strict\";\n\nvar _AbortController = require(\"@uppy/utils/lib/AbortController\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst delay = require(\"@uppy/utils/lib/delay\");\n\nconst MB = 1024 * 1024;\nconst defaultOptions = {\n  limit: 1,\n  retryDelays: [0, 1000, 3000, 5000],\n\n  getChunkSize(file) {\n    return Math.ceil(file.size / 10000);\n  },\n\n  onStart() {},\n\n  onProgress() {},\n\n  onPartComplete() {},\n\n  onSuccess() {},\n\n  onError(err) {\n    throw err;\n  }\n\n};\n\nfunction ensureInt(value) {\n  if (typeof value === 'string') {\n    return parseInt(value, 10);\n  }\n\n  if (typeof value === 'number') {\n    return value;\n  }\n\n  throw new TypeError('Expected a number');\n}\n\nvar _aborted = /*#__PURE__*/_classPrivateFieldLooseKey(\"aborted\");\n\nvar _initChunks = /*#__PURE__*/_classPrivateFieldLooseKey(\"initChunks\");\n\nvar _createUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"createUpload\");\n\nvar _resumeUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"resumeUpload\");\n\nvar _uploadParts = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploadParts\");\n\nvar _retryable = /*#__PURE__*/_classPrivateFieldLooseKey(\"retryable\");\n\nvar _prepareUploadParts = /*#__PURE__*/_classPrivateFieldLooseKey(\"prepareUploadParts\");\n\nvar _uploadPartRetryable = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploadPartRetryable\");\n\nvar _uploadPart = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploadPart\");\n\nvar _onPartProgress = /*#__PURE__*/_classPrivateFieldLooseKey(\"onPartProgress\");\n\nvar _onPartComplete = /*#__PURE__*/_classPrivateFieldLooseKey(\"onPartComplete\");\n\nvar _uploadPartBytes = /*#__PURE__*/_classPrivateFieldLooseKey(\"uploadPartBytes\");\n\nvar _completeUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"completeUpload\");\n\nvar _abortUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"abortUpload\");\n\nvar _onError = /*#__PURE__*/_classPrivateFieldLooseKey(\"onError\");\n\nclass MultipartUploader {\n  constructor(file, options) {\n    Object.defineProperty(this, _onError, {\n      value: _onError2\n    });\n    Object.defineProperty(this, _abortUpload, {\n      value: _abortUpload2\n    });\n    Object.defineProperty(this, _completeUpload, {\n      value: _completeUpload2\n    });\n    Object.defineProperty(this, _uploadPartBytes, {\n      value: _uploadPartBytes2\n    });\n    Object.defineProperty(this, _onPartComplete, {\n      value: _onPartComplete2\n    });\n    Object.defineProperty(this, _onPartProgress, {\n      value: _onPartProgress2\n    });\n    Object.defineProperty(this, _uploadPart, {\n      value: _uploadPart2\n    });\n    Object.defineProperty(this, _uploadPartRetryable, {\n      value: _uploadPartRetryable2\n    });\n    Object.defineProperty(this, _prepareUploadParts, {\n      value: _prepareUploadParts2\n    });\n    Object.defineProperty(this, _retryable, {\n      value: _retryable2\n    });\n    Object.defineProperty(this, _uploadParts, {\n      value: _uploadParts2\n    });\n    Object.defineProperty(this, _resumeUpload, {\n      value: _resumeUpload2\n    });\n    Object.defineProperty(this, _createUpload, {\n      value: _createUpload2\n    });\n    Object.defineProperty(this, _initChunks, {\n      value: _initChunks2\n    });\n    Object.defineProperty(this, _aborted, {\n      value: _aborted2\n    });\n    this.options = { ...defaultOptions,\n      ...options\n    }; // Use default `getChunkSize` if it was null or something\n\n    if (!this.options.getChunkSize) {\n      this.options.getChunkSize = defaultOptions.getChunkSize;\n    }\n\n    this.file = file;\n    this.abortController = new _AbortController.AbortController();\n    this.key = this.options.key || null;\n    this.uploadId = this.options.uploadId || null;\n    this.parts = []; // Do `this.createdPromise.then(OP)` to execute an operation `OP` _only_ if the\n    // upload was created already. That also ensures that the sequencing is right\n    // (so the `OP` definitely happens if the upload is created).\n    //\n    // This mostly exists to make `#abortUpload` work well: only sending the abort request if\n    // the upload was already created, and if the createMultipartUpload request is still in flight,\n    // aborting it immediately after it finishes.\n\n    this.createdPromise = Promise.reject(); // eslint-disable-line prefer-promise-reject-errors\n\n    this.isPaused = false;\n    this.partsInProgress = 0;\n    this.chunks = null;\n    this.chunkState = null;\n\n    _classPrivateFieldLooseBase(this, _initChunks)[_initChunks]();\n\n    this.createdPromise.catch(() => {}); // silence uncaught rejection warning\n  }\n  /**\n   * Was this upload aborted?\n   *\n   * If yes, we may need to throw an AbortError.\n   *\n   * @returns {boolean}\n   */\n\n\n  start() {\n    this.isPaused = false;\n\n    if (this.uploadId) {\n      _classPrivateFieldLooseBase(this, _resumeUpload)[_resumeUpload]();\n    } else {\n      _classPrivateFieldLooseBase(this, _createUpload)[_createUpload]();\n    }\n  }\n\n  pause() {\n    this.abortController.abort(); // Swap it out for a new controller, because this instance may be resumed later.\n\n    this.abortController = new _AbortController.AbortController();\n    this.isPaused = true;\n  }\n\n  abort(opts) {\n    var _opts;\n\n    if (opts === void 0) {\n      opts = undefined;\n    }\n\n    if ((_opts = opts) != null && _opts.really) _classPrivateFieldLooseBase(this, _abortUpload)[_abortUpload]();else this.pause();\n  }\n\n}\n\nfunction _aborted2() {\n  return this.abortController.signal.aborted;\n}\n\nfunction _initChunks2() {\n  const chunks = [];\n  const desiredChunkSize = this.options.getChunkSize(this.file); // at least 5MB per request, at most 10k requests\n\n  const minChunkSize = Math.max(5 * MB, Math.ceil(this.file.size / 10000));\n  const chunkSize = Math.max(desiredChunkSize, minChunkSize); // Upload zero-sized files in one zero-sized chunk\n\n  if (this.file.size === 0) {\n    chunks.push(this.file);\n  } else {\n    for (let i = 0; i < this.file.size; i += chunkSize) {\n      const end = Math.min(this.file.size, i + chunkSize);\n      chunks.push(this.file.slice(i, end));\n    }\n  }\n\n  this.chunks = chunks;\n  this.chunkState = chunks.map(() => ({\n    uploaded: 0,\n    busy: false,\n    done: false\n  }));\n}\n\nfunction _createUpload2() {\n  this.createdPromise = Promise.resolve().then(() => this.options.createMultipartUpload());\n  return this.createdPromise.then(result => {\n    if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) throw (0, _AbortController.createAbortError)();\n    const valid = typeof result === 'object' && result && typeof result.uploadId === 'string' && typeof result.key === 'string';\n\n    if (!valid) {\n      throw new TypeError('AwsS3/Multipart: Got incorrect result from `createMultipartUpload()`, expected an object `{ uploadId, key }`.');\n    }\n\n    this.key = result.key;\n    this.uploadId = result.uploadId;\n    this.options.onStart(result);\n\n    _classPrivateFieldLooseBase(this, _uploadParts)[_uploadParts]();\n  }).catch(err => {\n    _classPrivateFieldLooseBase(this, _onError)[_onError](err);\n  });\n}\n\nasync function _resumeUpload2() {\n  try {\n    const parts = await this.options.listParts({\n      uploadId: this.uploadId,\n      key: this.key\n    });\n    if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) throw (0, _AbortController.createAbortError)();\n    parts.forEach(part => {\n      const i = part.PartNumber - 1;\n      this.chunkState[i] = {\n        uploaded: ensureInt(part.Size),\n        etag: part.ETag,\n        done: true\n      }; // Only add if we did not yet know about this part.\n\n      if (!this.parts.some(p => p.PartNumber === part.PartNumber)) {\n        this.parts.push({\n          PartNumber: part.PartNumber,\n          ETag: part.ETag\n        });\n      }\n    });\n\n    _classPrivateFieldLooseBase(this, _uploadParts)[_uploadParts]();\n  } catch (err) {\n    _classPrivateFieldLooseBase(this, _onError)[_onError](err);\n  }\n}\n\nfunction _uploadParts2() {\n  if (this.isPaused) return; // All parts are uploaded.\n\n  if (this.chunkState.every(state => state.done)) {\n    _classPrivateFieldLooseBase(this, _completeUpload)[_completeUpload]();\n\n    return;\n  } // For a 100MB file, with the default min chunk size of 5MB and a limit of 10:\n  //\n  // Total 20 parts\n  // ---------\n  // Need 1 is 10\n  // Need 2 is 5\n  // Need 3 is 5\n\n\n  const need = this.options.limit - this.partsInProgress;\n  const completeChunks = this.chunkState.filter(state => state.done).length;\n  const remainingChunks = this.chunks.length - completeChunks;\n  let minNeeded = Math.ceil(this.options.limit / 2);\n\n  if (minNeeded > remainingChunks) {\n    minNeeded = remainingChunks;\n  }\n\n  if (need < minNeeded) return;\n  const candidates = [];\n\n  for (let i = 0; i < this.chunkState.length; i++) {\n    const state = this.chunkState[i]; // eslint-disable-next-line no-continue\n\n    if (state.done || state.busy) continue;\n    candidates.push(i);\n\n    if (candidates.length >= need) {\n      break;\n    }\n  }\n\n  if (candidates.length === 0) return;\n\n  _classPrivateFieldLooseBase(this, _prepareUploadParts)[_prepareUploadParts](candidates).then(result => {\n    candidates.forEach(index => {\n      const partNumber = index + 1;\n      const prePreparedPart = {\n        url: result.presignedUrls[partNumber],\n        headers: result.headers\n      };\n\n      _classPrivateFieldLooseBase(this, _uploadPartRetryable)[_uploadPartRetryable](index, prePreparedPart).then(() => {\n        _classPrivateFieldLooseBase(this, _uploadParts)[_uploadParts]();\n      }, err => {\n        _classPrivateFieldLooseBase(this, _onError)[_onError](err);\n      });\n    });\n  });\n}\n\nfunction _retryable2(_ref) {\n  let {\n    before,\n    attempt,\n    after\n  } = _ref;\n  const {\n    retryDelays\n  } = this.options;\n  const {\n    signal\n  } = this.abortController;\n  if (before) before();\n\n  function shouldRetry(err) {\n    if (err.source && typeof err.source.status === 'number') {\n      const {\n        status\n      } = err.source; // 0 probably indicates network failure\n\n      return status === 0 || status === 409 || status === 423 || status >= 500 && status < 600;\n    }\n\n    return false;\n  }\n\n  const doAttempt = retryAttempt => attempt().catch(err => {\n    if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) throw (0, _AbortController.createAbortError)();\n\n    if (shouldRetry(err) && retryAttempt < retryDelays.length) {\n      return delay(retryDelays[retryAttempt], {\n        signal\n      }).then(() => doAttempt(retryAttempt + 1));\n    }\n\n    throw err;\n  });\n\n  return doAttempt(0).then(result => {\n    if (after) after();\n    return result;\n  }, err => {\n    if (after) after();\n    throw err;\n  });\n}\n\nasync function _prepareUploadParts2(candidates) {\n  candidates.forEach(i => {\n    this.chunkState[i].busy = true;\n  });\n  const result = await _classPrivateFieldLooseBase(this, _retryable)[_retryable]({\n    attempt: () => this.options.prepareUploadParts({\n      key: this.key,\n      uploadId: this.uploadId,\n      partNumbers: candidates.map(index => index + 1),\n      chunks: candidates.reduce((chunks, candidate) => ({ ...chunks,\n        // Use the part number as the index\n        [candidate + 1]: this.chunks[candidate]\n      }), {})\n    })\n  });\n\n  if (typeof (result == null ? void 0 : result.presignedUrls) !== 'object') {\n    throw new TypeError('AwsS3/Multipart: Got incorrect result from `prepareUploadParts()`, expected an object `{ presignedUrls }`.');\n  }\n\n  return result;\n}\n\nfunction _uploadPartRetryable2(index, prePreparedPart) {\n  return _classPrivateFieldLooseBase(this, _retryable)[_retryable]({\n    before: () => {\n      this.chunkState[index].busy = true;\n      this.partsInProgress += 1;\n    },\n    attempt: () => _classPrivateFieldLooseBase(this, _uploadPart)[_uploadPart](index, prePreparedPart),\n    after: () => {\n      this.chunkState[index].busy = false;\n      this.partsInProgress -= 1;\n    }\n  });\n}\n\nfunction _uploadPart2(index, prePreparedPart) {\n  const valid = typeof (prePreparedPart == null ? void 0 : prePreparedPart.url) === 'string';\n\n  if (!valid) {\n    throw new TypeError('AwsS3/Multipart: Got incorrect result for `prePreparedPart`, expected an object `{ url }`.');\n  }\n\n  const {\n    url,\n    headers\n  } = prePreparedPart;\n\n  if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) {\n    throw (0, _AbortController.createAbortError)();\n  }\n\n  return _classPrivateFieldLooseBase(this, _uploadPartBytes)[_uploadPartBytes](index, url, headers);\n}\n\nfunction _onPartProgress2(index, sent) {\n  this.chunkState[index].uploaded = ensureInt(sent);\n  const totalUploaded = this.chunkState.reduce((n, c) => n + c.uploaded, 0);\n  this.options.onProgress(totalUploaded, this.file.size);\n}\n\nfunction _onPartComplete2(index, etag) {\n  this.chunkState[index].etag = etag;\n  this.chunkState[index].done = true;\n  const part = {\n    PartNumber: index + 1,\n    ETag: etag\n  };\n  this.parts.push(part);\n  this.options.onPartComplete(part);\n}\n\nfunction _uploadPartBytes2(index, url, headers) {\n  const body = this.chunks[index];\n  const {\n    signal\n  } = this.abortController;\n  let defer;\n  const promise = new Promise((resolve, reject) => {\n    defer = {\n      resolve,\n      reject\n    };\n  });\n  const xhr = new XMLHttpRequest();\n  xhr.open('PUT', url, true);\n\n  if (headers) {\n    Object.keys(headers).forEach(key => {\n      xhr.setRequestHeader(key, headers[key]);\n    });\n  }\n\n  xhr.responseType = 'text';\n\n  function cleanup() {\n    // eslint-disable-next-line no-use-before-define\n    signal.removeEventListener('abort', onabort);\n  }\n\n  function onabort() {\n    xhr.abort();\n  }\n\n  signal.addEventListener('abort', onabort);\n  xhr.upload.addEventListener('progress', ev => {\n    if (!ev.lengthComputable) return;\n\n    _classPrivateFieldLooseBase(this, _onPartProgress)[_onPartProgress](index, ev.loaded, ev.total);\n  });\n  xhr.addEventListener('abort', () => {\n    cleanup();\n    defer.reject((0, _AbortController.createAbortError)());\n  });\n  xhr.addEventListener('load', ev => {\n    cleanup();\n\n    if (ev.target.status < 200 || ev.target.status >= 300) {\n      const error = new Error('Non 2xx');\n      error.source = ev.target;\n      defer.reject(error);\n      return;\n    } // This avoids the net::ERR_OUT_OF_MEMORY in Chromium Browsers.\n\n\n    this.chunks[index] = null;\n\n    _classPrivateFieldLooseBase(this, _onPartProgress)[_onPartProgress](index, body.size, body.size); // NOTE This must be allowed by CORS.\n\n\n    const etag = ev.target.getResponseHeader('ETag');\n\n    if (etag === null) {\n      defer.reject(new Error('AwsS3/Multipart: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions.'));\n      return;\n    }\n\n    _classPrivateFieldLooseBase(this, _onPartComplete)[_onPartComplete](index, etag);\n\n    defer.resolve();\n  });\n  xhr.addEventListener('error', ev => {\n    cleanup();\n    const error = new Error('Unknown error');\n    error.source = ev.target;\n    defer.reject(error);\n  });\n  xhr.send(body);\n  return promise;\n}\n\nasync function _completeUpload2() {\n  // Parts may not have completed uploading in sorted order, if limit > 1.\n  this.parts.sort((a, b) => a.PartNumber - b.PartNumber);\n\n  try {\n    const result = await this.options.completeMultipartUpload({\n      key: this.key,\n      uploadId: this.uploadId,\n      parts: this.parts\n    });\n    this.options.onSuccess(result);\n  } catch (err) {\n    _classPrivateFieldLooseBase(this, _onError)[_onError](err);\n  }\n}\n\nfunction _abortUpload2() {\n  this.abortController.abort();\n  this.createdPromise.then(() => this.options.abortMultipartUpload({\n    key: this.key,\n    uploadId: this.uploadId\n  })).catch(() => {// if the creation failed we do not need to abort\n  });\n}\n\nfunction _onError2(err) {\n  if (err && err.name === 'AbortError') {\n    return;\n  }\n\n  this.options.onError(err);\n}\n\nmodule.exports = MultipartUploader;", "\"use strict\";\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _RateLimitedQueue = require(\"@uppy/utils/lib/RateLimitedQueue\");\n\nlet _Symbol$for;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst EventTracker = require(\"@uppy/utils/lib/EventTracker\");\n\nconst emitSocketProgress = require(\"@uppy/utils/lib/emitSocketProgress\");\n\nconst getSocketHost = require(\"@uppy/utils/lib/getSocketHost\");\n\nconst packageJson = {\n  \"version\": \"2.4.3\"\n};\n\nconst MultipartUploader = require(\"./MultipartUploader.js\");\n\nfunction assertServerError(res) {\n  if (res && res.error) {\n    const error = new Error(res.message);\n    Object.assign(error, res.error);\n    throw error;\n  }\n\n  return res;\n}\n\nvar _queueRequestSocketToken = /*#__PURE__*/_classPrivateFieldLooseKey(\"queueRequestSocketToken\");\n\nvar _client = /*#__PURE__*/_classPrivateFieldLooseKey(\"client\");\n\nvar _requestSocketToken = /*#__PURE__*/_classPrivateFieldLooseKey(\"requestSocketToken\");\n\nvar _setCompanionHeaders = /*#__PURE__*/_classPrivateFieldLooseKey(\"setCompanionHeaders\");\n\n_Symbol$for = Symbol.for('uppy test: getClient');\n\nclass AwsS3Multipart extends BasePlugin {\n  constructor(uppy, _opts) {\n    super(uppy, _opts);\n    Object.defineProperty(this, _queueRequestSocketToken, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _client, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _requestSocketToken, {\n      writable: true,\n      value: async file => {\n        const Client = file.remote.providerOptions.provider ? _companionClient.Provider : _companionClient.RequestClient;\n        const client = new Client(this.uppy, file.remote.providerOptions);\n        const opts = { ...this.opts\n        };\n\n        if (file.tus) {\n          // Install file-specific upload overrides.\n          Object.assign(opts, file.tus);\n        }\n\n        const res = await client.post(file.remote.url, { ...file.remote.body,\n          protocol: 's3-multipart',\n          size: file.data.size,\n          metadata: file.meta\n        });\n        return res.token;\n      }\n    });\n    Object.defineProperty(this, _setCompanionHeaders, {\n      writable: true,\n      value: () => {\n        _classPrivateFieldLooseBase(this, _client)[_client].setCompanionHeaders(this.opts.companionHeaders);\n\n        return Promise.resolve();\n      }\n    });\n    this.type = 'uploader';\n    this.id = this.opts.id || 'AwsS3Multipart';\n    this.title = 'AWS S3 Multipart';\n    _classPrivateFieldLooseBase(this, _client)[_client] = new _companionClient.RequestClient(uppy, _opts);\n    const defaultOptions = {\n      timeout: 30 * 1000,\n      limit: 0,\n      retryDelays: [0, 1000, 3000, 5000],\n      createMultipartUpload: this.createMultipartUpload.bind(this),\n      listParts: this.listParts.bind(this),\n      prepareUploadParts: this.prepareUploadParts.bind(this),\n      abortMultipartUpload: this.abortMultipartUpload.bind(this),\n      completeMultipartUpload: this.completeMultipartUpload.bind(this),\n      companionHeaders: {}\n    };\n    this.opts = { ...defaultOptions,\n      ..._opts\n    };\n    this.upload = this.upload.bind(this);\n    this.requests = new _RateLimitedQueue.RateLimitedQueue(this.opts.limit);\n    this.uploaders = Object.create(null);\n    this.uploaderEvents = Object.create(null);\n    this.uploaderSockets = Object.create(null);\n    _classPrivateFieldLooseBase(this, _queueRequestSocketToken)[_queueRequestSocketToken] = this.requests.wrapPromiseFunction(_classPrivateFieldLooseBase(this, _requestSocketToken)[_requestSocketToken]);\n  }\n\n  [_Symbol$for]() {\n    return _classPrivateFieldLooseBase(this, _client)[_client];\n  } // TODO: remove getter and setter for #client on the next major release\n\n\n  get client() {\n    return _classPrivateFieldLooseBase(this, _client)[_client];\n  }\n\n  set client(client) {\n    _classPrivateFieldLooseBase(this, _client)[_client] = client;\n  }\n  /**\n   * Clean up all references for a file's upload: the MultipartUploader instance,\n   * any events related to the file, and the Companion WebSocket connection.\n   *\n   * Set `opts.abort` to tell S3 that the multipart upload is cancelled and must be removed.\n   * This should be done when the user cancels the upload, not when the upload is completed or errored.\n   */\n\n\n  resetUploaderReferences(fileID, opts) {\n    if (opts === void 0) {\n      opts = {};\n    }\n\n    if (this.uploaders[fileID]) {\n      this.uploaders[fileID].abort({\n        really: opts.abort || false\n      });\n      this.uploaders[fileID] = null;\n    }\n\n    if (this.uploaderEvents[fileID]) {\n      this.uploaderEvents[fileID].remove();\n      this.uploaderEvents[fileID] = null;\n    }\n\n    if (this.uploaderSockets[fileID]) {\n      this.uploaderSockets[fileID].close();\n      this.uploaderSockets[fileID] = null;\n    }\n  }\n\n  assertHost(method) {\n    if (!this.opts.companionUrl) {\n      throw new Error(`Expected a \\`companionUrl\\` option containing a Companion address, or if you are not using Companion, a custom \\`${method}\\` implementation.`);\n    }\n  }\n\n  createMultipartUpload(file) {\n    this.assertHost('createMultipartUpload');\n    const metadata = {};\n    Object.keys(file.meta).forEach(key => {\n      if (file.meta[key] != null) {\n        metadata[key] = file.meta[key].toString();\n      }\n    });\n    return _classPrivateFieldLooseBase(this, _client)[_client].post('s3/multipart', {\n      filename: file.name,\n      type: file.type,\n      metadata\n    }).then(assertServerError);\n  }\n\n  listParts(file, _ref) {\n    let {\n      key,\n      uploadId\n    } = _ref;\n    this.assertHost('listParts');\n    const filename = encodeURIComponent(key);\n    return _classPrivateFieldLooseBase(this, _client)[_client].get(`s3/multipart/${uploadId}?key=${filename}`).then(assertServerError);\n  }\n\n  prepareUploadParts(file, _ref2) {\n    let {\n      key,\n      uploadId,\n      partNumbers\n    } = _ref2;\n    this.assertHost('prepareUploadParts');\n    const filename = encodeURIComponent(key);\n    return _classPrivateFieldLooseBase(this, _client)[_client].get(`s3/multipart/${uploadId}/batch?key=${filename}&partNumbers=${partNumbers.join(',')}`).then(assertServerError);\n  }\n\n  completeMultipartUpload(file, _ref3) {\n    let {\n      key,\n      uploadId,\n      parts\n    } = _ref3;\n    this.assertHost('completeMultipartUpload');\n    const filename = encodeURIComponent(key);\n    const uploadIdEnc = encodeURIComponent(uploadId);\n    return _classPrivateFieldLooseBase(this, _client)[_client].post(`s3/multipart/${uploadIdEnc}/complete?key=${filename}`, {\n      parts\n    }).then(assertServerError);\n  }\n\n  abortMultipartUpload(file, _ref4) {\n    let {\n      key,\n      uploadId\n    } = _ref4;\n    this.assertHost('abortMultipartUpload');\n    const filename = encodeURIComponent(key);\n    const uploadIdEnc = encodeURIComponent(uploadId);\n    return _classPrivateFieldLooseBase(this, _client)[_client].delete(`s3/multipart/${uploadIdEnc}?key=${filename}`).then(assertServerError);\n  }\n\n  uploadFile(file) {\n    var _this = this;\n\n    return new Promise((resolve, reject) => {\n      let queuedRequest;\n\n      const onStart = data => {\n        const cFile = this.uppy.getFile(file.id);\n        this.uppy.setFileState(file.id, {\n          s3Multipart: { ...cFile.s3Multipart,\n            key: data.key,\n            uploadId: data.uploadId\n          }\n        });\n      };\n\n      const onProgress = (bytesUploaded, bytesTotal) => {\n        this.uppy.emit('upload-progress', file, {\n          uploader: this,\n          bytesUploaded,\n          bytesTotal\n        });\n      };\n\n      const onError = err => {\n        this.uppy.log(err);\n        this.uppy.emit('upload-error', file, err);\n        queuedRequest.done();\n        this.resetUploaderReferences(file.id);\n        reject(err);\n      };\n\n      const onSuccess = result => {\n        const uploadObject = upload; // eslint-disable-line no-use-before-define\n\n        const uploadResp = {\n          body: { ...result\n          },\n          uploadURL: result.location\n        };\n        queuedRequest.done();\n        this.resetUploaderReferences(file.id);\n        const cFile = this.uppy.getFile(file.id);\n        this.uppy.emit('upload-success', cFile || file, uploadResp);\n\n        if (result.location) {\n          this.uppy.log(`Download ${uploadObject.file.name} from ${result.location}`);\n        }\n\n        resolve(uploadObject);\n      };\n\n      const onPartComplete = part => {\n        const cFile = this.uppy.getFile(file.id);\n\n        if (!cFile) {\n          return;\n        }\n\n        this.uppy.emit('s3-multipart:part-uploaded', cFile, part);\n      };\n\n      const upload = new MultipartUploader(file.data, {\n        // .bind to pass the file object to each handler.\n        createMultipartUpload: this.opts.createMultipartUpload.bind(this, file),\n        listParts: this.opts.listParts.bind(this, file),\n        prepareUploadParts: this.opts.prepareUploadParts.bind(this, file),\n        completeMultipartUpload: this.opts.completeMultipartUpload.bind(this, file),\n        abortMultipartUpload: this.opts.abortMultipartUpload.bind(this, file),\n        getChunkSize: this.opts.getChunkSize ? this.opts.getChunkSize.bind(this) : null,\n        onStart,\n        onProgress,\n        onError,\n        onSuccess,\n        onPartComplete,\n        limit: this.opts.limit || 5,\n        retryDelays: this.opts.retryDelays || [],\n        ...file.s3Multipart\n      });\n      this.uploaders[file.id] = upload;\n      this.uploaderEvents[file.id] = new EventTracker(this.uppy);\n      queuedRequest = this.requests.run(() => {\n        if (!file.isPaused) {\n          upload.start();\n        } // Don't do anything here, the caller will take care of cancelling the upload itself\n        // using resetUploaderReferences(). This is because resetUploaderReferences() has to be\n        // called when this request is still in the queue, and has not been started yet, too. At\n        // that point this cancellation function is not going to be called.\n\n\n        return () => {};\n      });\n      this.onFileRemove(file.id, removed => {\n        queuedRequest.abort();\n        this.resetUploaderReferences(file.id, {\n          abort: true\n        });\n        resolve(`upload ${removed.id} was removed`);\n      });\n      this.onCancelAll(file.id, function (_temp) {\n        let {\n          reason\n        } = _temp === void 0 ? {} : _temp;\n\n        if (reason === 'user') {\n          queuedRequest.abort();\n\n          _this.resetUploaderReferences(file.id, {\n            abort: true\n          });\n        }\n\n        resolve(`upload ${file.id} was canceled`);\n      });\n      this.onFilePause(file.id, isPaused => {\n        if (isPaused) {\n          // Remove this file from the queue so another file can start in its place.\n          queuedRequest.abort();\n          upload.pause();\n        } else {\n          // Resuming an upload should be queued, else you could pause and then\n          // resume a queued upload to make it skip the queue.\n          queuedRequest.abort();\n          queuedRequest = this.requests.run(() => {\n            upload.start();\n            return () => {};\n          });\n        }\n      });\n      this.onPauseAll(file.id, () => {\n        queuedRequest.abort();\n        upload.pause();\n      });\n      this.onResumeAll(file.id, () => {\n        queuedRequest.abort();\n\n        if (file.error) {\n          upload.abort();\n        }\n\n        queuedRequest = this.requests.run(() => {\n          upload.start();\n          return () => {};\n        });\n      }); // Don't double-emit upload-started for Golden Retriever-restored files that were already started\n\n      if (!file.progress.uploadStarted || !file.isRestored) {\n        this.uppy.emit('upload-started', file);\n      }\n    });\n  }\n\n  async uploadRemote(file) {\n    this.resetUploaderReferences(file.id); // Don't double-emit upload-started for Golden Retriever-restored files that were already started\n\n    if (!file.progress.uploadStarted || !file.isRestored) {\n      this.uppy.emit('upload-started', file);\n    }\n\n    try {\n      if (file.serverToken) {\n        return this.connectToServerSocket(file);\n      }\n\n      const serverToken = await _classPrivateFieldLooseBase(this, _queueRequestSocketToken)[_queueRequestSocketToken](file);\n      this.uppy.setFileState(file.id, {\n        serverToken\n      });\n      return this.connectToServerSocket(this.uppy.getFile(file.id));\n    } catch (err) {\n      this.uppy.emit('upload-error', file, err);\n      throw err;\n    }\n  }\n\n  connectToServerSocket(file) {\n    var _this2 = this;\n\n    return new Promise((resolve, reject) => {\n      let queuedRequest;\n      const token = file.serverToken;\n      const host = getSocketHost(file.remote.companionUrl);\n      const socket = new _companionClient.Socket({\n        target: `${host}/api/${token}`\n      });\n      this.uploaderSockets[file.id] = socket;\n      this.uploaderEvents[file.id] = new EventTracker(this.uppy);\n      this.onFileRemove(file.id, () => {\n        queuedRequest.abort();\n        socket.send('cancel', {});\n        this.resetUploaderReferences(file.id, {\n          abort: true\n        });\n        resolve(`upload ${file.id} was removed`);\n      });\n      this.onFilePause(file.id, isPaused => {\n        if (isPaused) {\n          // Remove this file from the queue so another file can start in its place.\n          queuedRequest.abort();\n          socket.send('pause', {});\n        } else {\n          // Resuming an upload should be queued, else you could pause and then\n          // resume a queued upload to make it skip the queue.\n          queuedRequest.abort();\n          queuedRequest = this.requests.run(() => {\n            socket.send('resume', {});\n            return () => {};\n          });\n        }\n      });\n      this.onPauseAll(file.id, () => {\n        queuedRequest.abort();\n        socket.send('pause', {});\n      });\n      this.onCancelAll(file.id, function (_temp2) {\n        let {\n          reason\n        } = _temp2 === void 0 ? {} : _temp2;\n\n        if (reason === 'user') {\n          queuedRequest.abort();\n          socket.send('cancel', {});\n\n          _this2.resetUploaderReferences(file.id);\n        }\n\n        resolve(`upload ${file.id} was canceled`);\n      });\n      this.onResumeAll(file.id, () => {\n        queuedRequest.abort();\n\n        if (file.error) {\n          socket.send('pause', {});\n        }\n\n        queuedRequest = this.requests.run(() => {\n          socket.send('resume', {});\n        });\n      });\n      this.onRetry(file.id, () => {\n        // Only do the retry if the upload is actually in progress;\n        // else we could try to send these messages when the upload is still queued.\n        // We may need a better check for this since the socket may also be closed\n        // for other reasons, like network failures.\n        if (socket.isOpen) {\n          socket.send('pause', {});\n          socket.send('resume', {});\n        }\n      });\n      this.onRetryAll(file.id, () => {\n        if (socket.isOpen) {\n          socket.send('pause', {});\n          socket.send('resume', {});\n        }\n      });\n      socket.on('progress', progressData => emitSocketProgress(this, progressData, file));\n      socket.on('error', errData => {\n        this.uppy.emit('upload-error', file, new Error(errData.error));\n        this.resetUploaderReferences(file.id);\n        queuedRequest.done();\n        reject(new Error(errData.error));\n      });\n      socket.on('success', data => {\n        const uploadResp = {\n          uploadURL: data.url\n        };\n        this.uppy.emit('upload-success', file, uploadResp);\n        this.resetUploaderReferences(file.id);\n        queuedRequest.done();\n        resolve();\n      });\n      queuedRequest = this.requests.run(() => {\n        if (file.isPaused) {\n          socket.send('pause', {});\n        }\n\n        return () => {};\n      });\n    });\n  }\n\n  upload(fileIDs) {\n    if (fileIDs.length === 0) return Promise.resolve();\n    const promises = fileIDs.map(id => {\n      const file = this.uppy.getFile(id);\n\n      if (file.isRemote) {\n        return this.uploadRemote(file);\n      }\n\n      return this.uploadFile(file);\n    });\n    return Promise.all(promises);\n  }\n\n  onFileRemove(fileID, cb) {\n    this.uploaderEvents[fileID].on('file-removed', file => {\n      if (fileID === file.id) cb(file.id);\n    });\n  }\n\n  onFilePause(fileID, cb) {\n    this.uploaderEvents[fileID].on('upload-pause', (targetFileID, isPaused) => {\n      if (fileID === targetFileID) {\n        // const isPaused = this.uppy.pauseResume(fileID)\n        cb(isPaused);\n      }\n    });\n  }\n\n  onRetry(fileID, cb) {\n    this.uploaderEvents[fileID].on('upload-retry', targetFileID => {\n      if (fileID === targetFileID) {\n        cb();\n      }\n    });\n  }\n\n  onRetryAll(fileID, cb) {\n    this.uploaderEvents[fileID].on('retry-all', () => {\n      if (!this.uppy.getFile(fileID)) return;\n      cb();\n    });\n  }\n\n  onPauseAll(fileID, cb) {\n    this.uploaderEvents[fileID].on('pause-all', () => {\n      if (!this.uppy.getFile(fileID)) return;\n      cb();\n    });\n  }\n\n  onCancelAll(fileID, eventHandler) {\n    var _this3 = this;\n\n    this.uploaderEvents[fileID].on('cancel-all', function () {\n      if (!_this3.uppy.getFile(fileID)) return;\n      eventHandler(...arguments);\n    });\n  }\n\n  onResumeAll(fileID, cb) {\n    this.uploaderEvents[fileID].on('resume-all', () => {\n      if (!this.uppy.getFile(fileID)) return;\n      cb();\n    });\n  }\n\n  install() {\n    const {\n      capabilities\n    } = this.uppy.getState();\n    this.uppy.setState({\n      capabilities: { ...capabilities,\n        resumableUploads: true\n      }\n    });\n    this.uppy.addPreProcessor(_classPrivateFieldLooseBase(this, _setCompanionHeaders)[_setCompanionHeaders]);\n    this.uppy.addUploader(this.upload);\n  }\n\n  uninstall() {\n    const {\n      capabilities\n    } = this.uppy.getState();\n    this.uppy.setState({\n      capabilities: { ...capabilities,\n        resumableUploads: false\n      }\n    });\n    this.uppy.removePreProcessor(_classPrivateFieldLooseBase(this, _setCompanionHeaders)[_setCompanionHeaders]);\n    this.uppy.removeUploader(this.upload);\n  }\n\n}\n\nAwsS3Multipart.VERSION = packageJson.version;\nmodule.exports = AwsS3Multipart;", "/*\n *  base64.js\n *\n *  Licensed under the BSD 3-Clause License.\n *    http://opensource.org/licenses/BSD-3-Clause\n *\n *  References:\n *    http://en.wikipedia.org/wiki/Base64\n */\n;(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined'\n        ? module.exports = factory(global)\n        : typeof define === 'function' && define.amd\n        ? define(factory) : factory(global)\n}((\n    typeof self !== 'undefined' ? self\n        : typeof window !== 'undefined' ? window\n        : typeof global !== 'undefined' ? global\n: this\n), function(global) {\n    'use strict';\n    // existing version for noConflict()\n    global = global || {};\n    var _Base64 = global.Base64;\n    var version = \"2.6.4\";\n    // constants\n    var b64chars\n        = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n    var b64tab = function(bin) {\n        var t = {};\n        for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;\n        return t;\n    }(b64chars);\n    var fromCharCode = String.fromCharCode;\n    // encoder stuff\n    var cb_utob = function(c) {\n        if (c.length < 2) {\n            var cc = c.charCodeAt(0);\n            return cc < 0x80 ? c\n                : cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6))\n                                + fromCharCode(0x80 | (cc & 0x3f)))\n                : (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f))\n                    + fromCharCode(0x80 | ((cc >>>  6) & 0x3f))\n                    + fromCharCode(0x80 | ( cc         & 0x3f)));\n        } else {\n            var cc = 0x10000\n                + (c.charCodeAt(0) - 0xD800) * 0x400\n                + (c.charCodeAt(1) - 0xDC00);\n            return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07))\n                    + fromCharCode(0x80 | ((cc >>> 12) & 0x3f))\n                    + fromCharCode(0x80 | ((cc >>>  6) & 0x3f))\n                    + fromCharCode(0x80 | ( cc         & 0x3f)));\n        }\n    };\n    var re_utob = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFFF]|[^\\x00-\\x7F]/g;\n    var utob = function(u) {\n        return u.replace(re_utob, cb_utob);\n    };\n    var cb_encode = function(ccc) {\n        var padlen = [0, 2, 1][ccc.length % 3],\n        ord = ccc.charCodeAt(0) << 16\n            | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8)\n            | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)),\n        chars = [\n            b64chars.charAt( ord >>> 18),\n            b64chars.charAt((ord >>> 12) & 63),\n            padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),\n            padlen >= 1 ? '=' : b64chars.charAt(ord & 63)\n        ];\n        return chars.join('');\n    };\n    var btoa = global.btoa && typeof global.btoa == 'function'\n        ? function(b){ return global.btoa(b) } : function(b) {\n        if (b.match(/[^\\x00-\\xFF]/)) throw new RangeError(\n            'The string contains invalid characters.'\n        );\n        return b.replace(/[\\s\\S]{1,3}/g, cb_encode);\n    };\n    var _encode = function(u) {\n        return btoa(utob(String(u)));\n    };\n    var mkUriSafe = function (b64) {\n        return b64.replace(/[+\\/]/g, function(m0) {\n            return m0 == '+' ? '-' : '_';\n        }).replace(/=/g, '');\n    };\n    var encode = function(u, urisafe) {\n        return urisafe ? mkUriSafe(_encode(u)) : _encode(u);\n    };\n    var encodeURI = function(u) { return encode(u, true) };\n    var fromUint8Array;\n    if (global.Uint8Array) fromUint8Array = function(a, urisafe) {\n        // return btoa(fromCharCode.apply(null, a));\n        var b64 = '';\n        for (var i = 0, l = a.length; i < l; i += 3) {\n            var a0 = a[i], a1 = a[i+1], a2 = a[i+2];\n            var ord = a0 << 16 | a1 << 8 | a2;\n            b64 +=    b64chars.charAt( ord >>> 18)\n                +     b64chars.charAt((ord >>> 12) & 63)\n                + ( typeof a1 != 'undefined'\n                    ? b64chars.charAt((ord >>>  6) & 63) : '=')\n                + ( typeof a2 != 'undefined'\n                    ? b64chars.charAt( ord         & 63) : '=');\n        }\n        return urisafe ? mkUriSafe(b64) : b64;\n    };\n    // decoder stuff\n    var re_btou = /[\\xC0-\\xDF][\\x80-\\xBF]|[\\xE0-\\xEF][\\x80-\\xBF]{2}|[\\xF0-\\xF7][\\x80-\\xBF]{3}/g;\n    var cb_btou = function(cccc) {\n        switch(cccc.length) {\n        case 4:\n            var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n                |    ((0x3f & cccc.charCodeAt(1)) << 12)\n                |    ((0x3f & cccc.charCodeAt(2)) <<  6)\n                |     (0x3f & cccc.charCodeAt(3)),\n            offset = cp - 0x10000;\n            return (fromCharCode((offset  >>> 10) + 0xD800)\n                    + fromCharCode((offset & 0x3FF) + 0xDC00));\n        case 3:\n            return fromCharCode(\n                ((0x0f & cccc.charCodeAt(0)) << 12)\n                    | ((0x3f & cccc.charCodeAt(1)) << 6)\n                    |  (0x3f & cccc.charCodeAt(2))\n            );\n        default:\n            return  fromCharCode(\n                ((0x1f & cccc.charCodeAt(0)) << 6)\n                    |  (0x3f & cccc.charCodeAt(1))\n            );\n        }\n    };\n    var btou = function(b) {\n        return b.replace(re_btou, cb_btou);\n    };\n    var cb_decode = function(cccc) {\n        var len = cccc.length,\n        padlen = len % 4,\n        n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0)\n            | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0)\n            | (len > 2 ? b64tab[cccc.charAt(2)] <<  6 : 0)\n            | (len > 3 ? b64tab[cccc.charAt(3)]       : 0),\n        chars = [\n            fromCharCode( n >>> 16),\n            fromCharCode((n >>>  8) & 0xff),\n            fromCharCode( n         & 0xff)\n        ];\n        chars.length -= [0, 0, 2, 1][padlen];\n        return chars.join('');\n    };\n    var _atob = global.atob && typeof global.atob == 'function'\n        ? function(a){ return global.atob(a) } : function(a){\n        return a.replace(/\\S{1,4}/g, cb_decode);\n    };\n    var atob = function(a) {\n        return _atob(String(a).replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n    };\n    var _decode = function(a) { return btou(_atob(a)) };\n    var _fromURI = function(a) {\n        return String(a).replace(/[-_]/g, function(m0) {\n            return m0 == '-' ? '+' : '/'\n        }).replace(/[^A-Za-z0-9\\+\\/]/g, '');\n    };\n    var decode = function(a){\n        return _decode(_fromURI(a));\n    };\n    var toUint8Array;\n    if (global.Uint8Array) toUint8Array = function(a) {\n        return Uint8Array.from(atob(_fromURI(a)), function(c) {\n            return c.charCodeAt(0);\n        });\n    };\n    var noConflict = function() {\n        var Base64 = global.Base64;\n        global.Base64 = _Base64;\n        return Base64;\n    };\n    // export Base64\n    global.Base64 = {\n        VERSION: version,\n        atob: atob,\n        btoa: btoa,\n        fromBase64: decode,\n        toBase64: encode,\n        utob: utob,\n        encode: encode,\n        encodeURI: encodeURI,\n        btou: btou,\n        decode: decode,\n        noConflict: noConflict,\n        fromUint8Array: fromUint8Array,\n        toUint8Array: toUint8Array\n    };\n    // if ES5 is available, make Base64.extendString() available\n    if (typeof Object.defineProperty === 'function') {\n        var noEnum = function(v){\n            return {value:v,enumerable:false,writable:true,configurable:true};\n        };\n        global.Base64.extendString = function () {\n            Object.defineProperty(\n                String.prototype, 'fromBase64', noEnum(function () {\n                    return decode(this)\n                }));\n            Object.defineProperty(\n                String.prototype, 'toBase64', noEnum(function (urisafe) {\n                    return encode(this, urisafe)\n                }));\n            Object.defineProperty(\n                String.prototype, 'toBase64URI', noEnum(function () {\n                    return encode(this, true)\n                }));\n        };\n    }\n    //\n    // export Base64 to the namespace\n    //\n    if (global['Meteor']) { // Meteor.js\n        Base64 = global.Base64;\n    }\n    // module.exports and AMD are mutually exclusive.\n    // module.exports has precedence.\n    if (typeof module !== 'undefined' && module.exports) {\n        module.exports.Base64 = global.Base64;\n    }\n    else if (typeof define === 'function' && define.amd) {\n        // AMD. Register as an anonymous module.\n        define([], function(){ return global.Base64 });\n    }\n    // that's it!\n    return {Base64: global.Base64}\n}));\n", "'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n  protocol = protocol.split(':')[0];\n  port = +port;\n\n  if (!port) return false;\n\n  switch (protocol) {\n    case 'http':\n    case 'ws':\n    return port !== 80;\n\n    case 'https':\n    case 'wss':\n    return port !== 443;\n\n    case 'ftp':\n    return port !== 21;\n\n    case 'gopher':\n    return port !== 70;\n\n    case 'file':\n    return false;\n  }\n\n  return port !== 0;\n};\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n  , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n  try {\n    return decodeURIComponent(input.replace(/\\+/g, ' '));\n  } catch (e) {\n    return null;\n  }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n  try {\n    return encodeURIComponent(input);\n  } catch (e) {\n    return null;\n  }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n  var parser = /([^=?#&]+)=?([^&]*)/g\n    , result = {}\n    , part;\n\n  while (part = parser.exec(query)) {\n    var key = decode(part[1])\n      , value = decode(part[2]);\n\n    //\n    // Prevent overriding of existing properties. This ensures that build-in\n    // methods like `toString` or __proto__ are not overriden by malicious\n    // querystrings.\n    //\n    // In the case if failed decoding, we want to omit the key/value pairs\n    // from the result.\n    //\n    if (key === null || value === null || key in result) continue;\n    result[key] = value;\n  }\n\n  return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n  prefix = prefix || '';\n\n  var pairs = []\n    , value\n    , key;\n\n  //\n  // Optionally prefix with a '?' if needed\n  //\n  if ('string' !== typeof prefix) prefix = '?';\n\n  for (key in obj) {\n    if (has.call(obj, key)) {\n      value = obj[key];\n\n      //\n      // Edge cases where we actually want to encode the value to an empty\n      // string instead of the stringified value.\n      //\n      if (!value && (value === null || value === undef || isNaN(value))) {\n        value = '';\n      }\n\n      key = encode(key);\n      value = encode(value);\n\n      //\n      // If we failed to encode the strings, we should bail out as we don't\n      // want to add invalid strings to the query.\n      //\n      if (key === null || value === null) continue;\n      pairs.push(key +'='+ value);\n    }\n  }\n\n  return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n", "'use strict';\n\nvar required = require('requires-port')\n  , qs = require('querystringify')\n  , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n  , CRHTLF = /[\\n\\r\\t]/g\n  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n  , port = /:\\d+$/\n  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n  , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n *     characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n  return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n *    indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n *    the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n  ['#', 'hash'],                        // Extract from the back.\n  ['?', 'query'],                       // Extract from the back.\n  function sanitize(address, url) {     // Sanitize what is left of the address\n    return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n  },\n  ['/', 'pathname'],                    // Extract from the back.\n  ['@', 'auth', 1],                     // Extract from the front.\n  [NaN, 'host', undefined, 1, 1],       // Set left over value.\n  [/:(\\d*)$/, 'port', undefined, 1],    // RegExp the back.\n  [NaN, 'hostname', undefined, 1, 1]    // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n  var globalVar;\n\n  if (typeof window !== 'undefined') globalVar = window;\n  else if (typeof global !== 'undefined') globalVar = global;\n  else if (typeof self !== 'undefined') globalVar = self;\n  else globalVar = {};\n\n  var location = globalVar.location || {};\n  loc = loc || location;\n\n  var finaldestination = {}\n    , type = typeof loc\n    , key;\n\n  if ('blob:' === loc.protocol) {\n    finaldestination = new Url(unescape(loc.pathname), {});\n  } else if ('string' === type) {\n    finaldestination = new Url(loc, {});\n    for (key in ignore) delete finaldestination[key];\n  } else if ('object' === type) {\n    for (key in loc) {\n      if (key in ignore) continue;\n      finaldestination[key] = loc[key];\n    }\n\n    if (finaldestination.slashes === undefined) {\n      finaldestination.slashes = slashes.test(loc.href);\n    }\n  }\n\n  return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n  return (\n    scheme === 'file:' ||\n    scheme === 'ftp:' ||\n    scheme === 'http:' ||\n    scheme === 'https:' ||\n    scheme === 'ws:' ||\n    scheme === 'wss:'\n  );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n  address = trimLeft(address);\n  address = address.replace(CRHTLF, '');\n  location = location || {};\n\n  var match = protocolre.exec(address);\n  var protocol = match[1] ? match[1].toLowerCase() : '';\n  var forwardSlashes = !!match[2];\n  var otherSlashes = !!match[3];\n  var slashesCount = 0;\n  var rest;\n\n  if (forwardSlashes) {\n    if (otherSlashes) {\n      rest = match[2] + match[3] + match[4];\n      slashesCount = match[2].length + match[3].length;\n    } else {\n      rest = match[2] + match[4];\n      slashesCount = match[2].length;\n    }\n  } else {\n    if (otherSlashes) {\n      rest = match[3] + match[4];\n      slashesCount = match[3].length;\n    } else {\n      rest = match[4]\n    }\n  }\n\n  if (protocol === 'file:') {\n    if (slashesCount >= 2) {\n      rest = rest.slice(2);\n    }\n  } else if (isSpecial(protocol)) {\n    rest = match[4];\n  } else if (protocol) {\n    if (forwardSlashes) {\n      rest = rest.slice(2);\n    }\n  } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n    rest = match[4];\n  }\n\n  return {\n    protocol: protocol,\n    slashes: forwardSlashes || isSpecial(protocol),\n    slashesCount: slashesCount,\n    rest: rest\n  };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n  if (relative === '') return base;\n\n  var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n    , i = path.length\n    , last = path[i - 1]\n    , unshift = false\n    , up = 0;\n\n  while (i--) {\n    if (path[i] === '.') {\n      path.splice(i, 1);\n    } else if (path[i] === '..') {\n      path.splice(i, 1);\n      up++;\n    } else if (up) {\n      if (i === 0) unshift = true;\n      path.splice(i, 1);\n      up--;\n    }\n  }\n\n  if (unshift) path.unshift('');\n  if (last === '.' || last === '..') path.push('');\n\n  return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n  address = trimLeft(address);\n  address = address.replace(CRHTLF, '');\n\n  if (!(this instanceof Url)) {\n    return new Url(address, location, parser);\n  }\n\n  var relative, extracted, parse, instruction, index, key\n    , instructions = rules.slice()\n    , type = typeof location\n    , url = this\n    , i = 0;\n\n  //\n  // The following if statements allows this module two have compatibility with\n  // 2 different API:\n  //\n  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n  //    where the boolean indicates that the query string should also be parsed.\n  //\n  // 2. The `URL` interface of the browser which accepts a URL, object as\n  //    arguments. The supplied object will be used as default values / fall-back\n  //    for relative paths.\n  //\n  if ('object' !== type && 'string' !== type) {\n    parser = location;\n    location = null;\n  }\n\n  if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n  location = lolcation(location);\n\n  //\n  // Extract protocol information before running the instructions.\n  //\n  extracted = extractProtocol(address || '', location);\n  relative = !extracted.protocol && !extracted.slashes;\n  url.slashes = extracted.slashes || relative && location.slashes;\n  url.protocol = extracted.protocol || location.protocol || '';\n  address = extracted.rest;\n\n  //\n  // When the authority component is absent the URL starts with a path\n  // component.\n  //\n  if (\n    extracted.protocol === 'file:' && (\n      extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n    (!extracted.slashes &&\n      (extracted.protocol ||\n        extracted.slashesCount < 2 ||\n        !isSpecial(url.protocol)))\n  ) {\n    instructions[3] = [/(.*)/, 'pathname'];\n  }\n\n  for (; i < instructions.length; i++) {\n    instruction = instructions[i];\n\n    if (typeof instruction === 'function') {\n      address = instruction(address, url);\n      continue;\n    }\n\n    parse = instruction[0];\n    key = instruction[1];\n\n    if (parse !== parse) {\n      url[key] = address;\n    } else if ('string' === typeof parse) {\n      index = parse === '@'\n        ? address.lastIndexOf(parse)\n        : address.indexOf(parse);\n\n      if (~index) {\n        if ('number' === typeof instruction[2]) {\n          url[key] = address.slice(0, index);\n          address = address.slice(index + instruction[2]);\n        } else {\n          url[key] = address.slice(index);\n          address = address.slice(0, index);\n        }\n      }\n    } else if ((index = parse.exec(address))) {\n      url[key] = index[1];\n      address = address.slice(0, index.index);\n    }\n\n    url[key] = url[key] || (\n      relative && instruction[3] ? location[key] || '' : ''\n    );\n\n    //\n    // Hostname, host and protocol should be lowercased so they can be used to\n    // create a proper `origin`.\n    //\n    if (instruction[4]) url[key] = url[key].toLowerCase();\n  }\n\n  //\n  // Also parse the supplied query string in to an object. If we're supplied\n  // with a custom parser as function use that instead of the default build-in\n  // parser.\n  //\n  if (parser) url.query = parser(url.query);\n\n  //\n  // If the URL is relative, resolve the pathname against the base URL.\n  //\n  if (\n      relative\n    && location.slashes\n    && url.pathname.charAt(0) !== '/'\n    && (url.pathname !== '' || location.pathname !== '')\n  ) {\n    url.pathname = resolve(url.pathname, location.pathname);\n  }\n\n  //\n  // Default to a / for pathname if none exists. This normalizes the URL\n  // to always have a /\n  //\n  if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n    url.pathname = '/' + url.pathname;\n  }\n\n  //\n  // We should not add port numbers if they are already the default port number\n  // for a given protocol. As the host also contains the port number we're going\n  // override it with the hostname which contains no port number.\n  //\n  if (!required(url.port, url.protocol)) {\n    url.host = url.hostname;\n    url.port = '';\n  }\n\n  //\n  // Parse down the `auth` for the username and password.\n  //\n  url.username = url.password = '';\n\n  if (url.auth) {\n    index = url.auth.indexOf(':');\n\n    if (~index) {\n      url.username = url.auth.slice(0, index);\n      url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n      url.password = url.auth.slice(index + 1);\n      url.password = encodeURIComponent(decodeURIComponent(url.password))\n    } else {\n      url.username = encodeURIComponent(decodeURIComponent(url.auth));\n    }\n\n    url.auth = url.password ? url.username +':'+ url.password : url.username;\n  }\n\n  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  //\n  // The href is just the compiled result.\n  //\n  url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part          Property we need to adjust.\n * @param {Mixed} value          The newly assigned value.\n * @param {Boolean|Function} fn  When setting the query, it will be the function\n *                               used to parse the query.\n *                               When setting the protocol, double slash will be\n *                               removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n  var url = this;\n\n  switch (part) {\n    case 'query':\n      if ('string' === typeof value && value.length) {\n        value = (fn || qs.parse)(value);\n      }\n\n      url[part] = value;\n      break;\n\n    case 'port':\n      url[part] = value;\n\n      if (!required(value, url.protocol)) {\n        url.host = url.hostname;\n        url[part] = '';\n      } else if (value) {\n        url.host = url.hostname +':'+ value;\n      }\n\n      break;\n\n    case 'hostname':\n      url[part] = value;\n\n      if (url.port) value += ':'+ url.port;\n      url.host = value;\n      break;\n\n    case 'host':\n      url[part] = value;\n\n      if (port.test(value)) {\n        value = value.split(':');\n        url.port = value.pop();\n        url.hostname = value.join(':');\n      } else {\n        url.hostname = value;\n        url.port = '';\n      }\n\n      break;\n\n    case 'protocol':\n      url.protocol = value.toLowerCase();\n      url.slashes = !fn;\n      break;\n\n    case 'pathname':\n    case 'hash':\n      if (value) {\n        var char = part === 'pathname' ? '/' : '#';\n        url[part] = value.charAt(0) !== char ? char + value : value;\n      } else {\n        url[part] = value;\n      }\n      break;\n\n    case 'username':\n    case 'password':\n      url[part] = encodeURIComponent(value);\n      break;\n\n    case 'auth':\n      var index = value.indexOf(':');\n\n      if (~index) {\n        url.username = value.slice(0, index);\n        url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n        url.password = value.slice(index + 1);\n        url.password = encodeURIComponent(decodeURIComponent(url.password));\n      } else {\n        url.username = encodeURIComponent(decodeURIComponent(value));\n      }\n  }\n\n  for (var i = 0; i < rules.length; i++) {\n    var ins = rules[i];\n\n    if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n  }\n\n  url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n    ? url.protocol +'//'+ url.host\n    : 'null';\n\n  url.href = url.toString();\n\n  return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n  var query\n    , url = this\n    , host = url.host\n    , protocol = url.protocol;\n\n  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n  var result =\n    protocol +\n    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n  if (url.username) {\n    result += url.username;\n    if (url.password) result += ':'+ url.password;\n    result += '@';\n  } else if (url.password) {\n    result += ':'+ url.password;\n    result += '@';\n  } else if (\n    url.protocol !== 'file:' &&\n    isSpecial(url.protocol) &&\n    !host &&\n    url.pathname !== '/'\n  ) {\n    //\n    // Add back the empty userinfo, otherwise the original invalid URL\n    // might be transformed into a valid one with `url.pathname` as host.\n    //\n    result += '@';\n  }\n\n  //\n  // Trailing colon is removed from `url.host` when it is parsed. If it still\n  // ends with a colon, then add back the trailing colon that was removed. This\n  // prevents an invalid URL from being transformed into a valid one.\n  //\n  if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n    host += ':';\n  }\n\n  result += host + url.pathname;\n\n  query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n  if (url.hash) result += url.hash;\n\n  return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nfunction _typeof(obj) {\n  \"@babel/helpers - typeof\";\n\n  if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n    _typeof = function _typeof(obj) {\n      return typeof obj;\n    };\n  } else {\n    _typeof = function _typeof(obj) {\n      return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n    };\n  }\n\n  return _typeof(obj);\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _inherits(subClass, superClass) {\n  if (typeof superClass !== \"function\" && superClass !== null) {\n    throw new TypeError(\"Super expression must either be null or a function\");\n  }\n\n  subClass.prototype = Object.create(superClass && superClass.prototype, {\n    constructor: {\n      value: subClass,\n      writable: true,\n      configurable: true\n    }\n  });\n  if (superClass) _setPrototypeOf(subClass, superClass);\n}\n\nfunction _createSuper(Derived) {\n  var hasNativeReflectConstruct = _isNativeReflectConstruct();\n\n  return function _createSuperInternal() {\n    var Super = _getPrototypeOf(Derived),\n        result;\n\n    if (hasNativeReflectConstruct) {\n      var NewTarget = _getPrototypeOf(this).constructor;\n\n      result = Reflect.construct(Super, arguments, NewTarget);\n    } else {\n      result = Super.apply(this, arguments);\n    }\n\n    return _possibleConstructorReturn(this, result);\n  };\n}\n\nfunction _possibleConstructorReturn(self, call) {\n  if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n    return call;\n  }\n\n  return _assertThisInitialized(self);\n}\n\nfunction _assertThisInitialized(self) {\n  if (self === void 0) {\n    throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n  }\n\n  return self;\n}\n\nfunction _wrapNativeSuper(Class) {\n  var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n  _wrapNativeSuper = function _wrapNativeSuper(Class) {\n    if (Class === null || !_isNativeFunction(Class)) return Class;\n\n    if (typeof Class !== \"function\") {\n      throw new TypeError(\"Super expression must either be null or a function\");\n    }\n\n    if (typeof _cache !== \"undefined\") {\n      if (_cache.has(Class)) return _cache.get(Class);\n\n      _cache.set(Class, Wrapper);\n    }\n\n    function Wrapper() {\n      return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n    }\n\n    Wrapper.prototype = Object.create(Class.prototype, {\n      constructor: {\n        value: Wrapper,\n        enumerable: false,\n        writable: true,\n        configurable: true\n      }\n    });\n    return _setPrototypeOf(Wrapper, Class);\n  };\n\n  return _wrapNativeSuper(Class);\n}\n\nfunction _construct(Parent, args, Class) {\n  if (_isNativeReflectConstruct()) {\n    _construct = Reflect.construct;\n  } else {\n    _construct = function _construct(Parent, args, Class) {\n      var a = [null];\n      a.push.apply(a, args);\n      var Constructor = Function.bind.apply(Parent, a);\n      var instance = new Constructor();\n      if (Class) _setPrototypeOf(instance, Class.prototype);\n      return instance;\n    };\n  }\n\n  return _construct.apply(null, arguments);\n}\n\nfunction _isNativeReflectConstruct() {\n  if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n  if (Reflect.construct.sham) return false;\n  if (typeof Proxy === \"function\") return true;\n\n  try {\n    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n    return true;\n  } catch (e) {\n    return false;\n  }\n}\n\nfunction _isNativeFunction(fn) {\n  return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}\n\nfunction _setPrototypeOf(o, p) {\n  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n    o.__proto__ = p;\n    return o;\n  };\n\n  return _setPrototypeOf(o, p);\n}\n\nfunction _getPrototypeOf(o) {\n  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n    return o.__proto__ || Object.getPrototypeOf(o);\n  };\n  return _getPrototypeOf(o);\n}\n\nvar DetailedError = /*#__PURE__*/function (_Error) {\n  _inherits(DetailedError, _Error);\n\n  var _super = _createSuper(DetailedError);\n\n  function DetailedError(message) {\n    var _this;\n\n    var causingErr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n    var req = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n    var res = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n\n    _classCallCheck(this, DetailedError);\n\n    _this = _super.call(this, message);\n    _this.originalRequest = req;\n    _this.originalResponse = res;\n    _this.causingError = causingErr;\n\n    if (causingErr != null) {\n      message += \", caused by \".concat(causingErr.toString());\n    }\n\n    if (req != null) {\n      var requestId = req.getHeader('X-Request-ID') || 'n/a';\n      var method = req.getMethod();\n      var url = req.getURL();\n      var status = res ? res.getStatus() : 'n/a';\n      var body = res ? res.getBody() || '' : 'n/a';\n      message += \", originated from request (method: \".concat(method, \", url: \").concat(url, \", response code: \").concat(status, \", response text: \").concat(body, \", request id: \").concat(requestId, \")\");\n    }\n\n    _this.message = message;\n    return _this;\n  }\n\n  return _createClass(DetailedError);\n}( /*#__PURE__*/_wrapNativeSuper(Error));\n\nvar _default = DetailedError;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.enableDebugLog = enableDebugLog;\nexports.log = log;\n\n/* eslint no-console: \"off\" */\nvar isEnabled = false;\n\nfunction enableDebugLog() {\n  isEnabled = true;\n}\n\nfunction log(msg) {\n  if (!isEnabled) return;\n  console.log(msg);\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = uuid;\n\n/**\n * Generate a UUID v4 based on random numbers. We intentioanlly use the less\n * secure Math.random function here since the more secure crypto.getRandomNumbers\n * is not available on all platforms.\n * This is not a problem for us since we use the UUID only for generating a\n * request ID, so we can correlate server logs to client errors.\n *\n * This function is taken from following site:\n * https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript\n *\n * @return {string} The generate UUID\n */\nfunction uuid() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    var r = Math.random() * 16 | 0;\n    var v = c == 'x' ? r : r & 0x3 | 0x8;\n    return v.toString(16);\n  });\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nvar _jsBase = require(\"js-base64\");\n\nvar _urlParse = _interopRequireDefault(require(\"url-parse\"));\n\nvar _error = _interopRequireDefault(require(\"./error\"));\n\nvar _logger = require(\"./logger\");\n\nvar _uuid = _interopRequireDefault(require(\"./uuid\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction ownKeys(object, enumerableOnly) {\n  var keys = Object.keys(object);\n\n  if (Object.getOwnPropertySymbols) {\n    var symbols = Object.getOwnPropertySymbols(object);\n    if (enumerableOnly) symbols = symbols.filter(function (sym) {\n      return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n    });\n    keys.push.apply(keys, symbols);\n  }\n\n  return keys;\n}\n\nfunction _objectSpread(target) {\n  for (var i = 1; i < arguments.length; i++) {\n    var source = arguments[i] != null ? arguments[i] : {};\n\n    if (i % 2) {\n      ownKeys(Object(source), true).forEach(function (key) {\n        _defineProperty(target, key, source[key]);\n      });\n    } else if (Object.getOwnPropertyDescriptors) {\n      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n    } else {\n      ownKeys(Object(source)).forEach(function (key) {\n        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n      });\n    }\n  }\n\n  return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n  if (key in obj) {\n    Object.defineProperty(obj, key, {\n      value: value,\n      enumerable: true,\n      configurable: true,\n      writable: true\n    });\n  } else {\n    obj[key] = value;\n  }\n\n  return obj;\n}\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n/* global window */\n\n\nvar defaultOptions = {\n  endpoint: null,\n  uploadUrl: null,\n  metadata: {},\n  fingerprint: null,\n  uploadSize: null,\n  onProgress: null,\n  onChunkComplete: null,\n  onSuccess: null,\n  onError: null,\n  _onUploadUrlAvailable: null,\n  overridePatchMethod: false,\n  headers: {},\n  addRequestId: false,\n  onBeforeRequest: null,\n  onAfterResponse: null,\n  onShouldRetry: null,\n  chunkSize: Infinity,\n  retryDelays: [0, 1000, 3000, 5000],\n  parallelUploads: 1,\n  storeFingerprintForResuming: true,\n  removeFingerprintOnSuccess: false,\n  uploadLengthDeferred: false,\n  uploadDataDuringCreation: false,\n  urlStorage: null,\n  fileReader: null,\n  httpStack: null\n};\n\nvar BaseUpload = /*#__PURE__*/function () {\n  function BaseUpload(file, options) {\n    _classCallCheck(this, BaseUpload); // Warn about removed options from previous versions\n\n\n    if ('resume' in options) {\n      console.log('tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead.'); // eslint-disable-line no-console\n    } // The default options will already be added from the wrapper classes.\n\n\n    this.options = options; // Cast chunkSize to integer\n\n    this.options.chunkSize = +this.options.chunkSize; // The storage module used to store URLs\n\n    this._urlStorage = this.options.urlStorage; // The underlying File/Blob object\n\n    this.file = file; // The URL against which the file will be uploaded\n\n    this.url = null; // The underlying request object for the current PATCH request\n\n    this._req = null; // The fingerpinrt for the current file (set after start())\n\n    this._fingerprint = null; // The key that the URL storage returned when saving an URL with a fingerprint,\n\n    this._urlStorageKey = null; // The offset used in the current PATCH request\n\n    this._offset = null; // True if the current PATCH request has been aborted\n\n    this._aborted = false; // The file's size in bytes\n\n    this._size = null; // The Source object which will wrap around the given file and provides us\n    // with a unified interface for getting its size and slice chunks from its\n    // content allowing us to easily handle Files, Blobs, Buffers and Streams.\n\n    this._source = null; // The current count of attempts which have been made. Zero indicates none.\n\n    this._retryAttempt = 0; // The timeout's ID which is used to delay the next retry\n\n    this._retryTimeout = null; // The offset of the remote upload before the latest attempt was started.\n\n    this._offsetBeforeRetry = 0; // An array of BaseUpload instances which are used for uploading the different\n    // parts, if the parallelUploads option is used.\n\n    this._parallelUploads = null; // An array of upload URLs which are used for uploading the different\n    // parts, if the parallelUploads option is used.\n\n    this._parallelUploadUrls = null;\n  }\n  /**\n   * Use the Termination extension to delete an upload from the server by sending a DELETE\n   * request to the specified upload URL. This is only possible if the server supports the\n   * Termination extension. If the `options.retryDelays` property is set, the method will\n   * also retry if an error ocurrs.\n   *\n   * @param {String} url The upload's URL which will be terminated.\n   * @param {object} options Optional options for influencing HTTP requests.\n   * @return {Promise} The Promise will be resolved/rejected when the requests finish.\n   */\n\n\n  _createClass(BaseUpload, [{\n    key: \"findPreviousUploads\",\n    value: function findPreviousUploads() {\n      var _this = this;\n\n      return this.options.fingerprint(this.file, this.options).then(function (fingerprint) {\n        return _this._urlStorage.findUploadsByFingerprint(fingerprint);\n      });\n    }\n  }, {\n    key: \"resumeFromPreviousUpload\",\n    value: function resumeFromPreviousUpload(previousUpload) {\n      this.url = previousUpload.uploadUrl || null;\n      this._parallelUploadUrls = previousUpload.parallelUploadUrls || null;\n      this._urlStorageKey = previousUpload.urlStorageKey;\n    }\n  }, {\n    key: \"start\",\n    value: function start() {\n      var _this2 = this;\n\n      var file = this.file;\n\n      if (!file) {\n        this._emitError(new Error('tus: no file or stream to upload provided'));\n\n        return;\n      }\n\n      if (!this.options.endpoint && !this.options.uploadUrl) {\n        this._emitError(new Error('tus: neither an endpoint or an upload URL is provided'));\n\n        return;\n      }\n\n      var retryDelays = this.options.retryDelays;\n\n      if (retryDelays != null && Object.prototype.toString.call(retryDelays) !== '[object Array]') {\n        this._emitError(new Error('tus: the `retryDelays` option must either be an array or null'));\n\n        return;\n      }\n\n      if (this.options.parallelUploads > 1) {\n        // Test which options are incompatible with parallel uploads.\n        ['uploadUrl', 'uploadSize', 'uploadLengthDeferred'].forEach(function (optionName) {\n          if (_this2.options[optionName]) {\n            _this2._emitError(new Error(\"tus: cannot use the \".concat(optionName, \" option when parallelUploads is enabled\")));\n          }\n        });\n      }\n\n      this.options.fingerprint(file, this.options).then(function (fingerprint) {\n        if (fingerprint == null) {\n          (0, _logger.log)('No fingerprint was calculated meaning that the upload cannot be stored in the URL storage.');\n        } else {\n          (0, _logger.log)(\"Calculated fingerprint: \".concat(fingerprint));\n        }\n\n        _this2._fingerprint = fingerprint;\n\n        if (_this2._source) {\n          return _this2._source;\n        }\n\n        return _this2.options.fileReader.openFile(file, _this2.options.chunkSize);\n      }).then(function (source) {\n        _this2._source = source; // If the upload was configured to use multiple requests or if we resume from\n        // an upload which used multiple requests, we start a parallel upload.\n\n        if (_this2.options.parallelUploads > 1 || _this2._parallelUploadUrls != null) {\n          _this2._startParallelUpload();\n        } else {\n          _this2._startSingleUpload();\n        }\n      })[\"catch\"](function (err) {\n        _this2._emitError(err);\n      });\n    }\n    /**\n     * Initiate the uploading procedure for a parallelized upload, where one file is split into\n     * multiple request which are run in parallel.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_startParallelUpload\",\n    value: function _startParallelUpload() {\n      var _this3 = this;\n\n      var totalSize = this._size = this._source.size;\n      var totalProgress = 0;\n      this._parallelUploads = [];\n      var partCount = this._parallelUploadUrls != null ? this._parallelUploadUrls.length : this.options.parallelUploads; // The input file will be split into multiple slices which are uploaded in separate\n      // requests. Here we generate the start and end position for the slices.\n\n      var parts = splitSizeIntoParts(this._source.size, partCount, this._parallelUploadUrls); // Create an empty list for storing the upload URLs\n\n      this._parallelUploadUrls = new Array(parts.length); // Generate a promise for each slice that will be resolve if the respective\n      // upload is completed.\n\n      var uploads = parts.map(function (part, index) {\n        var lastPartProgress = 0;\n        return _this3._source.slice(part.start, part.end).then(function (_ref) {\n          var value = _ref.value;\n          return new Promise(function (resolve, reject) {\n            // Merge with the user supplied options but overwrite some values.\n            var options = _objectSpread(_objectSpread({}, _this3.options), {}, {\n              // If available, the partial upload should be resumed from a previous URL.\n              uploadUrl: part.uploadUrl || null,\n              // We take manually care of resuming for partial uploads, so they should\n              // not be stored in the URL storage.\n              storeFingerprintForResuming: false,\n              removeFingerprintOnSuccess: false,\n              // Reset the parallelUploads option to not cause recursion.\n              parallelUploads: 1,\n              metadata: {},\n              // Add the header to indicate the this is a partial upload.\n              headers: _objectSpread(_objectSpread({}, _this3.options.headers), {}, {\n                'Upload-Concat': 'partial'\n              }),\n              // Reject or resolve the promise if the upload errors or completes.\n              onSuccess: resolve,\n              onError: reject,\n              // Based in the progress for this partial upload, calculate the progress\n              // for the entire final upload.\n              onProgress: function onProgress(newPartProgress) {\n                totalProgress = totalProgress - lastPartProgress + newPartProgress;\n                lastPartProgress = newPartProgress;\n\n                _this3._emitProgress(totalProgress, totalSize);\n              },\n              // Wait until every partial upload has an upload URL, so we can add\n              // them to the URL storage.\n              _onUploadUrlAvailable: function _onUploadUrlAvailable() {\n                _this3._parallelUploadUrls[index] = upload.url; // Test if all uploads have received an URL\n\n                if (_this3._parallelUploadUrls.filter(function (u) {\n                  return !!u;\n                }).length === parts.length) {\n                  _this3._saveUploadInUrlStorage();\n                }\n              }\n            });\n\n            var upload = new BaseUpload(value, options);\n            upload.start(); // Store the upload in an array, so we can later abort them if necessary.\n\n            _this3._parallelUploads.push(upload);\n          });\n        });\n      });\n      var req; // Wait until all partial uploads are finished and we can send the POST request for\n      // creating the final upload.\n\n      Promise.all(uploads).then(function () {\n        req = _this3._openRequest('POST', _this3.options.endpoint);\n        req.setHeader('Upload-Concat', \"final;\".concat(_this3._parallelUploadUrls.join(' '))); // Add metadata if values have been added\n\n        var metadata = encodeMetadata(_this3.options.metadata);\n\n        if (metadata !== '') {\n          req.setHeader('Upload-Metadata', metadata);\n        }\n\n        return _this3._sendRequest(req, null);\n      }).then(function (res) {\n        if (!inStatusCategory(res.getStatus(), 200)) {\n          _this3._emitHttpError(req, res, 'tus: unexpected response while creating upload');\n\n          return;\n        }\n\n        var location = res.getHeader('Location');\n\n        if (location == null) {\n          _this3._emitHttpError(req, res, 'tus: invalid or missing Location header');\n\n          return;\n        }\n\n        _this3.url = resolveUrl(_this3.options.endpoint, location);\n        (0, _logger.log)(\"Created upload at \".concat(_this3.url));\n\n        _this3._emitSuccess();\n      })[\"catch\"](function (err) {\n        _this3._emitError(err);\n      });\n    }\n    /**\n     * Initiate the uploading procedure for a non-parallel upload. Here the entire file is\n     * uploaded in a sequential matter.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_startSingleUpload\",\n    value: function _startSingleUpload() {\n      // First, we look at the uploadLengthDeferred option.\n      // Next, we check if the caller has supplied a manual upload size.\n      // Finally, we try to use the calculated size from the source object.\n      if (this.options.uploadLengthDeferred) {\n        this._size = null;\n      } else if (this.options.uploadSize != null) {\n        this._size = +this.options.uploadSize;\n\n        if (isNaN(this._size)) {\n          this._emitError(new Error('tus: cannot convert `uploadSize` option into a number'));\n\n          return;\n        }\n      } else {\n        this._size = this._source.size;\n\n        if (this._size == null) {\n          this._emitError(new Error(\"tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option\"));\n\n          return;\n        }\n      } // Reset the aborted flag when the upload is started or else the\n      // _performUpload will stop before sending a request if the upload has been\n      // aborted previously.\n\n\n      this._aborted = false; // The upload had been started previously and we should reuse this URL.\n\n      if (this.url != null) {\n        (0, _logger.log)(\"Resuming upload from previous URL: \".concat(this.url));\n\n        this._resumeUpload();\n\n        return;\n      } // A URL has manually been specified, so we try to resume\n\n\n      if (this.options.uploadUrl != null) {\n        (0, _logger.log)(\"Resuming upload from provided URL: \".concat(this.options.uploadUrl));\n        this.url = this.options.uploadUrl;\n\n        this._resumeUpload();\n\n        return;\n      } // An upload has not started for the file yet, so we start a new one\n\n\n      (0, _logger.log)('Creating a new upload');\n\n      this._createUpload();\n    }\n    /**\n     * Abort any running request and stop the current upload. After abort is called, no event\n     * handler will be invoked anymore. You can use the `start` method to resume the upload\n     * again.\n     * If `shouldTerminate` is true, the `terminate` function will be called to remove the\n     * current upload from the server.\n     *\n     * @param {boolean} shouldTerminate True if the upload should be deleted from the server.\n     * @return {Promise} The Promise will be resolved/rejected when the requests finish.\n     */\n\n  }, {\n    key: \"abort\",\n    value: function abort(shouldTerminate) {\n      var _this4 = this; // Count the number of arguments to see if a callback is being provided in the old style required by tus-js-client 1.x, then throw an error if it is.\n      // `arguments` is a JavaScript built-in variable that contains all of the function's arguments.\n\n\n      if (arguments.length > 1 && typeof arguments[1] === 'function') {\n        throw new Error('tus: the abort function does not accept a callback since v2 anymore; please use the returned Promise instead');\n      } // Stop any parallel partial uploads, that have been started in _startParallelUploads.\n\n\n      if (this._parallelUploads != null) {\n        this._parallelUploads.forEach(function (upload) {\n          upload.abort(shouldTerminate);\n        });\n      } // Stop any current running request.\n\n\n      if (this._req !== null) {\n        this._req.abort();\n\n        this._source.close();\n      }\n\n      this._aborted = true; // Stop any timeout used for initiating a retry.\n\n      if (this._retryTimeout != null) {\n        clearTimeout(this._retryTimeout);\n        this._retryTimeout = null;\n      }\n\n      if (!shouldTerminate || this.url == null) {\n        return Promise.resolve();\n      }\n\n      return BaseUpload.terminate(this.url, this.options) // Remove entry from the URL storage since the upload URL is no longer valid.\n      .then(function () {\n        return _this4._removeFromUrlStorage();\n      });\n    }\n  }, {\n    key: \"_emitHttpError\",\n    value: function _emitHttpError(req, res, message, causingErr) {\n      this._emitError(new _error.default(message, causingErr, req, res));\n    }\n  }, {\n    key: \"_emitError\",\n    value: function _emitError(err) {\n      var _this5 = this; // Do not emit errors, e.g. from aborted HTTP requests, if the upload has been stopped.\n\n\n      if (this._aborted) return; // Check if we should retry, when enabled, before sending the error to the user.\n\n      if (this.options.retryDelays != null) {\n        // We will reset the attempt counter if\n        // - we were already able to connect to the server (offset != null) and\n        // - we were able to upload a small chunk of data to the server\n        var shouldResetDelays = this._offset != null && this._offset > this._offsetBeforeRetry;\n\n        if (shouldResetDelays) {\n          this._retryAttempt = 0;\n        }\n\n        if (shouldRetry(err, this._retryAttempt, this.options)) {\n          var delay = this.options.retryDelays[this._retryAttempt++];\n          this._offsetBeforeRetry = this._offset;\n          this._retryTimeout = setTimeout(function () {\n            _this5.start();\n          }, delay);\n          return;\n        }\n      }\n\n      if (typeof this.options.onError === 'function') {\n        this.options.onError(err);\n      } else {\n        throw err;\n      }\n    }\n    /**\n     * Publishes notification if the upload has been successfully completed.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_emitSuccess\",\n    value: function _emitSuccess() {\n      if (this.options.removeFingerprintOnSuccess) {\n        // Remove stored fingerprint and corresponding endpoint. This causes\n        // new uploads of the same file to be treated as a different file.\n        this._removeFromUrlStorage();\n      }\n\n      if (typeof this.options.onSuccess === 'function') {\n        this.options.onSuccess();\n      }\n    }\n    /**\n     * Publishes notification when data has been sent to the server. This\n     * data may not have been accepted by the server yet.\n     *\n     * @param {number} bytesSent  Number of bytes sent to the server.\n     * @param {number} bytesTotal Total number of bytes to be sent to the server.\n     * @api private\n     */\n\n  }, {\n    key: \"_emitProgress\",\n    value: function _emitProgress(bytesSent, bytesTotal) {\n      if (typeof this.options.onProgress === 'function') {\n        this.options.onProgress(bytesSent, bytesTotal);\n      }\n    }\n    /**\n     * Publishes notification when a chunk of data has been sent to the server\n     * and accepted by the server.\n     * @param {number} chunkSize  Size of the chunk that was accepted by the server.\n     * @param {number} bytesAccepted Total number of bytes that have been\n     *                                accepted by the server.\n     * @param {number} bytesTotal Total number of bytes to be sent to the server.\n     * @api private\n     */\n\n  }, {\n    key: \"_emitChunkComplete\",\n    value: function _emitChunkComplete(chunkSize, bytesAccepted, bytesTotal) {\n      if (typeof this.options.onChunkComplete === 'function') {\n        this.options.onChunkComplete(chunkSize, bytesAccepted, bytesTotal);\n      }\n    }\n    /**\n     * Create a new upload using the creation extension by sending a POST\n     * request to the endpoint. After successful creation the file will be\n     * uploaded\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_createUpload\",\n    value: function _createUpload() {\n      var _this6 = this;\n\n      if (!this.options.endpoint) {\n        this._emitError(new Error('tus: unable to create upload because no endpoint is provided'));\n\n        return;\n      }\n\n      var req = this._openRequest('POST', this.options.endpoint);\n\n      if (this.options.uploadLengthDeferred) {\n        req.setHeader('Upload-Defer-Length', 1);\n      } else {\n        req.setHeader('Upload-Length', this._size);\n      } // Add metadata if values have been added\n\n\n      var metadata = encodeMetadata(this.options.metadata);\n\n      if (metadata !== '') {\n        req.setHeader('Upload-Metadata', metadata);\n      }\n\n      var promise;\n\n      if (this.options.uploadDataDuringCreation && !this.options.uploadLengthDeferred) {\n        this._offset = 0;\n        promise = this._addChunkToRequest(req);\n      } else {\n        promise = this._sendRequest(req, null);\n      }\n\n      promise.then(function (res) {\n        if (!inStatusCategory(res.getStatus(), 200)) {\n          _this6._emitHttpError(req, res, 'tus: unexpected response while creating upload');\n\n          return;\n        }\n\n        var location = res.getHeader('Location');\n\n        if (location == null) {\n          _this6._emitHttpError(req, res, 'tus: invalid or missing Location header');\n\n          return;\n        }\n\n        _this6.url = resolveUrl(_this6.options.endpoint, location);\n        (0, _logger.log)(\"Created upload at \".concat(_this6.url));\n\n        if (typeof _this6.options._onUploadUrlAvailable === 'function') {\n          _this6.options._onUploadUrlAvailable();\n        }\n\n        if (_this6._size === 0) {\n          // Nothing to upload and file was successfully created\n          _this6._emitSuccess();\n\n          _this6._source.close();\n\n          return;\n        }\n\n        _this6._saveUploadInUrlStorage();\n\n        if (_this6.options.uploadDataDuringCreation) {\n          _this6._handleUploadResponse(req, res);\n        } else {\n          _this6._offset = 0;\n\n          _this6._performUpload();\n        }\n      })[\"catch\"](function (err) {\n        _this6._emitHttpError(req, null, 'tus: failed to create upload', err);\n      });\n    }\n    /*\n     * Try to resume an existing upload. First a HEAD request will be sent\n     * to retrieve the offset. If the request fails a new upload will be\n     * created. In the case of a successful response the file will be uploaded.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_resumeUpload\",\n    value: function _resumeUpload() {\n      var _this7 = this;\n\n      var req = this._openRequest('HEAD', this.url);\n\n      var promise = this._sendRequest(req, null);\n\n      promise.then(function (res) {\n        var status = res.getStatus();\n\n        if (!inStatusCategory(status, 200)) {\n          if (inStatusCategory(status, 400)) {\n            // Remove stored fingerprint and corresponding endpoint,\n            // on client errors since the file can not be found\n            _this7._removeFromUrlStorage();\n          } // If the upload is locked (indicated by the 423 Locked status code), we\n          // emit an error instead of directly starting a new upload. This way the\n          // retry logic can catch the error and will retry the upload. An upload\n          // is usually locked for a short period of time and will be available\n          // afterwards.\n\n\n          if (status === 423) {\n            _this7._emitHttpError(req, res, 'tus: upload is currently locked; retry later');\n\n            return;\n          }\n\n          if (!_this7.options.endpoint) {\n            // Don't attempt to create a new upload if no endpoint is provided.\n            _this7._emitHttpError(req, res, 'tus: unable to resume upload (new upload cannot be created without an endpoint)');\n\n            return;\n          } // Try to create a new upload\n\n\n          _this7.url = null;\n\n          _this7._createUpload();\n\n          return;\n        }\n\n        var offset = parseInt(res.getHeader('Upload-Offset'), 10);\n\n        if (isNaN(offset)) {\n          _this7._emitHttpError(req, res, 'tus: invalid or missing offset value');\n\n          return;\n        }\n\n        var length = parseInt(res.getHeader('Upload-Length'), 10);\n\n        if (isNaN(length) && !_this7.options.uploadLengthDeferred) {\n          _this7._emitHttpError(req, res, 'tus: invalid or missing length value');\n\n          return;\n        }\n\n        if (typeof _this7.options._onUploadUrlAvailable === 'function') {\n          _this7.options._onUploadUrlAvailable();\n        } // Upload has already been completed and we do not need to send additional\n        // data to the server\n\n\n        if (offset === length) {\n          _this7._emitProgress(length, length);\n\n          _this7._emitSuccess();\n\n          return;\n        }\n\n        _this7._offset = offset;\n\n        _this7._performUpload();\n      })[\"catch\"](function (err) {\n        _this7._emitHttpError(req, null, 'tus: failed to resume upload', err);\n      });\n    }\n    /**\n     * Start uploading the file using PATCH requests. The file will be divided\n     * into chunks as specified in the chunkSize option. During the upload\n     * the onProgress event handler may be invoked multiple times.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_performUpload\",\n    value: function _performUpload() {\n      var _this8 = this; // If the upload has been aborted, we will not send the next PATCH request.\n      // This is important if the abort method was called during a callback, such\n      // as onChunkComplete or onProgress.\n\n\n      if (this._aborted) {\n        return;\n      }\n\n      var req; // Some browser and servers may not support the PATCH method. For those\n      // cases, you can tell tus-js-client to use a POST request with the\n      // X-HTTP-Method-Override header for simulating a PATCH request.\n\n      if (this.options.overridePatchMethod) {\n        req = this._openRequest('POST', this.url);\n        req.setHeader('X-HTTP-Method-Override', 'PATCH');\n      } else {\n        req = this._openRequest('PATCH', this.url);\n      }\n\n      req.setHeader('Upload-Offset', this._offset);\n\n      var promise = this._addChunkToRequest(req);\n\n      promise.then(function (res) {\n        if (!inStatusCategory(res.getStatus(), 200)) {\n          _this8._emitHttpError(req, res, 'tus: unexpected response while uploading chunk');\n\n          return;\n        }\n\n        _this8._handleUploadResponse(req, res);\n      })[\"catch\"](function (err) {\n        // Don't emit an error if the upload was aborted manually\n        if (_this8._aborted) {\n          return;\n        }\n\n        _this8._emitHttpError(req, null, \"tus: failed to upload chunk at offset \".concat(_this8._offset), err);\n      });\n    }\n    /**\n     * _addChunktoRequest reads a chunk from the source and sends it using the\n     * supplied request object. It will not handle the response.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_addChunkToRequest\",\n    value: function _addChunkToRequest(req) {\n      var _this9 = this;\n\n      var start = this._offset;\n      var end = this._offset + this.options.chunkSize;\n      req.setProgressHandler(function (bytesSent) {\n        _this9._emitProgress(start + bytesSent, _this9._size);\n      });\n      req.setHeader('Content-Type', 'application/offset+octet-stream'); // The specified chunkSize may be Infinity or the calcluated end position\n      // may exceed the file's size. In both cases, we limit the end position to\n      // the input's total size for simpler calculations and correctness.\n\n      if ((end === Infinity || end > this._size) && !this.options.uploadLengthDeferred) {\n        end = this._size;\n      }\n\n      return this._source.slice(start, end).then(function (_ref2) {\n        var value = _ref2.value,\n            done = _ref2.done; // If the upload length is deferred, the upload size was not specified during\n        // upload creation. So, if the file reader is done reading, we know the total\n        // upload size and can tell the tus server.\n\n        if (_this9.options.uploadLengthDeferred && done) {\n          _this9._size = _this9._offset + (value && value.size ? value.size : 0);\n          req.setHeader('Upload-Length', _this9._size);\n        }\n\n        if (value === null) {\n          return _this9._sendRequest(req);\n        }\n\n        _this9._emitProgress(_this9._offset, _this9._size);\n\n        return _this9._sendRequest(req, value);\n      });\n    }\n    /**\n     * _handleUploadResponse is used by requests that haven been sent using _addChunkToRequest\n     * and already have received a response.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_handleUploadResponse\",\n    value: function _handleUploadResponse(req, res) {\n      var offset = parseInt(res.getHeader('Upload-Offset'), 10);\n\n      if (isNaN(offset)) {\n        this._emitHttpError(req, res, 'tus: invalid or missing offset value');\n\n        return;\n      }\n\n      this._emitProgress(offset, this._size);\n\n      this._emitChunkComplete(offset - this._offset, offset, this._size);\n\n      this._offset = offset;\n\n      if (offset == this._size) {\n        // Yay, finally done :)\n        this._emitSuccess();\n\n        this._source.close();\n\n        return;\n      }\n\n      this._performUpload();\n    }\n    /**\n     * Create a new HTTP request object with the given method and URL.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_openRequest\",\n    value: function _openRequest(method, url) {\n      var req = openRequest(method, url, this.options);\n      this._req = req;\n      return req;\n    }\n    /**\n     * Remove the entry in the URL storage, if it has been saved before.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_removeFromUrlStorage\",\n    value: function _removeFromUrlStorage() {\n      var _this10 = this;\n\n      if (!this._urlStorageKey) return;\n\n      this._urlStorage.removeUpload(this._urlStorageKey)[\"catch\"](function (err) {\n        _this10._emitError(err);\n      });\n\n      this._urlStorageKey = null;\n    }\n    /**\n     * Add the upload URL to the URL storage, if possible.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_saveUploadInUrlStorage\",\n    value: function _saveUploadInUrlStorage() {\n      var _this11 = this; // Only if a fingerprint was calculated for the input (i.e. not a stream), we can store the upload URL.\n\n\n      if (!this.options.storeFingerprintForResuming || !this._fingerprint) {\n        return;\n      }\n\n      var storedUpload = {\n        size: this._size,\n        metadata: this.options.metadata,\n        creationTime: new Date().toString()\n      };\n\n      if (this._parallelUploads) {\n        // Save multiple URLs if the parallelUploads option is used ...\n        storedUpload.parallelUploadUrls = this._parallelUploadUrls;\n      } else {\n        // ... otherwise we just save the one available URL.\n        storedUpload.uploadUrl = this.url;\n      }\n\n      this._urlStorage.addUpload(this._fingerprint, storedUpload).then(function (urlStorageKey) {\n        return _this11._urlStorageKey = urlStorageKey;\n      })[\"catch\"](function (err) {\n        _this11._emitError(err);\n      });\n    }\n    /**\n     * Send a request with the provided body.\n     *\n     * @api private\n     */\n\n  }, {\n    key: \"_sendRequest\",\n    value: function _sendRequest(req) {\n      var body = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n      return sendRequest(req, body, this.options);\n    }\n  }], [{\n    key: \"terminate\",\n    value: function terminate(url, options) {\n      // Count the number of arguments to see if a callback is being provided as the last\n      // argument in the old style required by tus-js-client 1.x, then throw an error if it is.\n      // `arguments` is a JavaScript built-in variable that contains all of the function's arguments.\n      if (arguments.length > 1 && typeof arguments[arguments.length - 1] === 'function') {\n        throw new Error('tus: the terminate function does not accept a callback since v2 anymore; please use the returned Promise instead');\n      } // Note that in order for the trick above to work, a default value cannot be set for `options`,\n      // so the check below replaces the old default `{}`.\n\n\n      if (options === undefined) {\n        options = {};\n      }\n\n      var req = openRequest('DELETE', url, options);\n      return sendRequest(req, null, options).then(function (res) {\n        // A 204 response indicates a successfull request\n        if (res.getStatus() === 204) {\n          return;\n        }\n\n        throw new _error.default('tus: unexpected response while terminating upload', null, req, res);\n      })[\"catch\"](function (err) {\n        if (!(err instanceof _error.default)) {\n          err = new _error.default('tus: failed to terminate upload', err, req, null);\n        }\n\n        if (!shouldRetry(err, 0, options)) {\n          throw err;\n        } // Instead of keeping track of the retry attempts, we remove the first element from the delays\n        // array. If the array is empty, all retry attempts are used up and we will bubble up the error.\n        // We recursively call the terminate function will removing elements from the retryDelays array.\n\n\n        var delay = options.retryDelays[0];\n        var remainingDelays = options.retryDelays.slice(1);\n\n        var newOptions = _objectSpread(_objectSpread({}, options), {}, {\n          retryDelays: remainingDelays\n        });\n\n        return new Promise(function (resolve) {\n          return setTimeout(resolve, delay);\n        }).then(function () {\n          return BaseUpload.terminate(url, newOptions);\n        });\n      });\n    }\n  }]);\n\n  return BaseUpload;\n}();\n\nfunction encodeMetadata(metadata) {\n  var encoded = [];\n\n  for (var key in metadata) {\n    encoded.push(\"\".concat(key, \" \").concat(_jsBase.Base64.encode(metadata[key])));\n  }\n\n  return encoded.join(',');\n}\n/**\n * Checks whether a given status is in the range of the expected category.\n * For example, only a status between 200 and 299 will satisfy the category 200.\n *\n * @api private\n */\n\n\nfunction inStatusCategory(status, category) {\n  return status >= category && status < category + 100;\n}\n/**\n * Create a new HTTP request with the specified method and URL.\n * The necessary headers that are included in every request\n * will be added, including the request ID.\n *\n * @api private\n */\n\n\nfunction openRequest(method, url, options) {\n  var req = options.httpStack.createRequest(method, url);\n  req.setHeader('Tus-Resumable', '1.0.0');\n  var headers = options.headers || {};\n\n  for (var name in headers) {\n    req.setHeader(name, headers[name]);\n  }\n\n  if (options.addRequestId) {\n    var requestId = (0, _uuid.default)();\n    req.setHeader('X-Request-ID', requestId);\n  }\n\n  return req;\n}\n/**\n * Send a request with the provided body while invoking the onBeforeRequest\n * and onAfterResponse callbacks.\n *\n * @api private\n */\n\n\nfunction sendRequest(req, body, options) {\n  var onBeforeRequestPromise = typeof options.onBeforeRequest === 'function' ? Promise.resolve(options.onBeforeRequest(req)) : Promise.resolve();\n  return onBeforeRequestPromise.then(function () {\n    return req.send(body).then(function (res) {\n      var onAfterResponsePromise = typeof options.onAfterResponse === 'function' ? Promise.resolve(options.onAfterResponse(req, res)) : Promise.resolve();\n      return onAfterResponsePromise.then(function () {\n        return res;\n      });\n    });\n  });\n}\n/**\n * Checks whether the browser running this code has internet access.\n * This function will always return true in the node.js environment\n *\n * @api private\n */\n\n\nfunction isOnline() {\n  var online = true;\n\n  if (typeof window !== 'undefined' && 'navigator' in window && window.navigator.onLine === false) {\n    online = false;\n  }\n\n  return online;\n}\n/**\n * Checks whether or not it is ok to retry a request.\n * @param {Error} err the error returned from the last request\n * @param {number} retryAttempt the number of times the request has already been retried\n * @param {object} options tus Upload options\n *\n * @api private\n */\n\n\nfunction shouldRetry(err, retryAttempt, options) {\n  // We only attempt a retry if\n  // - retryDelays option is set\n  // - we didn't exceed the maxium number of retries, yet, and\n  // - this error was caused by a request or it's response and\n  // - the error is server error (i.e. not a status 4xx except a 409 or 423) or\n  // a onShouldRetry is specified and returns true\n  // - the browser does not indicate that we are offline\n  if (options.retryDelays == null || retryAttempt >= options.retryDelays.length || err.originalRequest == null) {\n    return false;\n  }\n\n  if (options && typeof options.onShouldRetry === 'function') {\n    return options.onShouldRetry(err, retryAttempt, options);\n  }\n\n  var status = err.originalResponse ? err.originalResponse.getStatus() : 0;\n  return (!inStatusCategory(status, 400) || status === 409 || status === 423) && isOnline();\n}\n/**\n * Resolve a relative link given the origin as source. For example,\n * if a HTTP request to http://example.com/files/ returns a Location\n * header with the value /upload/abc, the resolved URL will be:\n * http://example.com/upload/abc\n */\n\n\nfunction resolveUrl(origin, link) {\n  return new _urlParse.default(link, origin).toString();\n}\n/**\n * Calculate the start and end positions for the parts if an upload\n * is split into multiple parallel requests.\n *\n * @param {number} totalSize The byte size of the upload, which will be split.\n * @param {number} partCount The number in how many parts the upload will be split.\n * @param {string[]} previousUrls The upload URLs for previous parts.\n * @return {object[]}\n * @api private\n */\n\n\nfunction splitSizeIntoParts(totalSize, partCount, previousUrls) {\n  var partSize = Math.floor(totalSize / partCount);\n  var parts = [];\n\n  for (var i = 0; i < partCount; i++) {\n    parts.push({\n      start: partSize * i,\n      end: partSize * (i + 1)\n    });\n  }\n\n  parts[partCount - 1].end = totalSize; // Attach URLs from previous uploads, if available.\n\n  if (previousUrls) {\n    parts.forEach(function (part, index) {\n      part.uploadUrl = previousUrls[index] || null;\n    });\n  }\n\n  return parts;\n}\n\nBaseUpload.defaultOptions = defaultOptions;\nvar _default = BaseUpload;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n/* eslint no-unused-vars: \"off\" */\n\n\nvar NoopUrlStorage = /*#__PURE__*/function () {\n  function NoopUrlStorage() {\n    _classCallCheck(this, NoopUrlStorage);\n  }\n\n  _createClass(NoopUrlStorage, [{\n    key: \"listAllUploads\",\n    value: function listAllUploads() {\n      return Promise.resolve([]);\n    }\n  }, {\n    key: \"findUploadsByFingerprint\",\n    value: function findUploadsByFingerprint(fingerprint) {\n      return Promise.resolve([]);\n    }\n  }, {\n    key: \"removeUpload\",\n    value: function removeUpload(urlStorageKey) {\n      return Promise.resolve();\n    }\n  }, {\n    key: \"addUpload\",\n    value: function addUpload(fingerprint, upload) {\n      return Promise.resolve(null);\n    }\n  }]);\n\n  return NoopUrlStorage;\n}();\n\nexports.default = NoopUrlStorage;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.canStoreURLs = exports.WebStorageUrlStorage = void 0;\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n/* global window, localStorage */\n\n\nvar hasStorage = false;\n\ntry {\n  hasStorage = 'localStorage' in window; // Attempt to store and read entries from the local storage to detect Private\n  // Mode on Safari on iOS (see #49)\n\n  var key = 'tusSupport';\n  localStorage.setItem(key, localStorage.getItem(key));\n} catch (e) {\n  // If we try to access localStorage inside a sandboxed iframe, a SecurityError\n  // is thrown. When in private mode on iOS Safari, a QuotaExceededError is\n  // thrown (see #49)\n  if (e.code === e.SECURITY_ERR || e.code === e.QUOTA_EXCEEDED_ERR) {\n    hasStorage = false;\n  } else {\n    throw e;\n  }\n}\n\nvar canStoreURLs = hasStorage;\nexports.canStoreURLs = canStoreURLs;\n\nvar WebStorageUrlStorage = /*#__PURE__*/function () {\n  function WebStorageUrlStorage() {\n    _classCallCheck(this, WebStorageUrlStorage);\n  }\n\n  _createClass(WebStorageUrlStorage, [{\n    key: \"findAllUploads\",\n    value: function findAllUploads() {\n      var results = this._findEntries('tus::');\n\n      return Promise.resolve(results);\n    }\n  }, {\n    key: \"findUploadsByFingerprint\",\n    value: function findUploadsByFingerprint(fingerprint) {\n      var results = this._findEntries(\"tus::\".concat(fingerprint, \"::\"));\n\n      return Promise.resolve(results);\n    }\n  }, {\n    key: \"removeUpload\",\n    value: function removeUpload(urlStorageKey) {\n      localStorage.removeItem(urlStorageKey);\n      return Promise.resolve();\n    }\n  }, {\n    key: \"addUpload\",\n    value: function addUpload(fingerprint, upload) {\n      var id = Math.round(Math.random() * 1e12);\n      var key = \"tus::\".concat(fingerprint, \"::\").concat(id);\n      localStorage.setItem(key, JSON.stringify(upload));\n      return Promise.resolve(key);\n    }\n  }, {\n    key: \"_findEntries\",\n    value: function _findEntries(prefix) {\n      var results = [];\n\n      for (var i = 0; i < localStorage.length; i++) {\n        var _key = localStorage.key(i);\n\n        if (_key.indexOf(prefix) !== 0) continue;\n\n        try {\n          var upload = JSON.parse(localStorage.getItem(_key));\n          upload.urlStorageKey = _key;\n          results.push(upload);\n        } catch (e) {// The JSON parse error is intentionally ignored here, so a malformed\n          // entry in the storage cannot prevent an upload.\n        }\n      }\n\n      return results;\n    }\n  }]);\n\n  return WebStorageUrlStorage;\n}();\n\nexports.WebStorageUrlStorage = WebStorageUrlStorage;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n/* eslint-disable max-classes-per-file */\n\n\nvar XHRHttpStack = /*#__PURE__*/function () {\n  function XHRHttpStack() {\n    _classCallCheck(this, XHRHttpStack);\n  }\n\n  _createClass(XHRHttpStack, [{\n    key: \"createRequest\",\n    value: function createRequest(method, url) {\n      return new Request(method, url);\n    }\n  }, {\n    key: \"getName\",\n    value: function getName() {\n      return 'XHRHttpStack';\n    }\n  }]);\n\n  return XHRHttpStack;\n}();\n\nexports.default = XHRHttpStack;\n\nvar Request = /*#__PURE__*/function () {\n  function Request(method, url) {\n    _classCallCheck(this, Request);\n\n    this._xhr = new XMLHttpRequest();\n\n    this._xhr.open(method, url, true);\n\n    this._method = method;\n    this._url = url;\n    this._headers = {};\n  }\n\n  _createClass(Request, [{\n    key: \"getMethod\",\n    value: function getMethod() {\n      return this._method;\n    }\n  }, {\n    key: \"getURL\",\n    value: function getURL() {\n      return this._url;\n    }\n  }, {\n    key: \"setHeader\",\n    value: function setHeader(header, value) {\n      this._xhr.setRequestHeader(header, value);\n\n      this._headers[header] = value;\n    }\n  }, {\n    key: \"getHeader\",\n    value: function getHeader(header) {\n      return this._headers[header];\n    }\n  }, {\n    key: \"setProgressHandler\",\n    value: function setProgressHandler(progressHandler) {\n      // Test support for progress events before attaching an event listener\n      if (!('upload' in this._xhr)) {\n        return;\n      }\n\n      this._xhr.upload.onprogress = function (e) {\n        if (!e.lengthComputable) {\n          return;\n        }\n\n        progressHandler(e.loaded);\n      };\n    }\n  }, {\n    key: \"send\",\n    value: function send() {\n      var _this = this;\n\n      var body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n      return new Promise(function (resolve, reject) {\n        _this._xhr.onload = function () {\n          resolve(new Response(_this._xhr));\n        };\n\n        _this._xhr.onerror = function (err) {\n          reject(err);\n        };\n\n        _this._xhr.send(body);\n      });\n    }\n  }, {\n    key: \"abort\",\n    value: function abort() {\n      this._xhr.abort();\n\n      return Promise.resolve();\n    }\n  }, {\n    key: \"getUnderlyingObject\",\n    value: function getUnderlyingObject() {\n      return this._xhr;\n    }\n  }]);\n\n  return Request;\n}();\n\nvar Response = /*#__PURE__*/function () {\n  function Response(xhr) {\n    _classCallCheck(this, Response);\n\n    this._xhr = xhr;\n  }\n\n  _createClass(Response, [{\n    key: \"getStatus\",\n    value: function getStatus() {\n      return this._xhr.status;\n    }\n  }, {\n    key: \"getHeader\",\n    value: function getHeader(header) {\n      return this._xhr.getResponseHeader(header);\n    }\n  }, {\n    key: \"getBody\",\n    value: function getBody() {\n      return this._xhr.responseText;\n    }\n  }, {\n    key: \"getUnderlyingObject\",\n    value: function getUnderlyingObject() {\n      return this._xhr;\n    }\n  }]);\n\n  return Response;\n}();", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nvar isReactNative = function isReactNative() {\n  return typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative';\n};\n\nvar _default = isReactNative;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = uriToBlob;\n\n/**\n * uriToBlob resolves a URI to a Blob object. This is used for\n * React Native to retrieve a file (identified by a file://\n * URI) as a blob.\n */\nfunction uriToBlob(uri) {\n  return new Promise(function (resolve, reject) {\n    var xhr = new XMLHttpRequest();\n    xhr.responseType = 'blob';\n\n    xhr.onload = function () {\n      var blob = xhr.response;\n      resolve(blob);\n    };\n\n    xhr.onerror = function (err) {\n      reject(err);\n    };\n\n    xhr.open('GET', uri);\n    xhr.send();\n  });\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nvar isCordova = function isCordova() {\n  return typeof window != 'undefined' && (typeof window.PhoneGap != 'undefined' || typeof window.Cordova != 'undefined' || typeof window.cordova != 'undefined');\n};\n\nvar _default = isCordova;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = readAsByteArray;\n\n/**\n * readAsByteArray converts a File object to a Uint8Array.\n * This function is only used on the Apache Cordova platform.\n * See https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#read-a-file\n */\nfunction readAsByteArray(chunk) {\n  return new Promise(function (resolve, reject) {\n    var reader = new FileReader();\n\n    reader.onload = function () {\n      var value = new Uint8Array(reader.result);\n      resolve({\n        value: value\n      });\n    };\n\n    reader.onerror = function (err) {\n      reject(err);\n    };\n\n    reader.readAsArrayBuffer(chunk);\n  });\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nvar _isCordova = _interopRequireDefault(require(\"./isCordova\"));\n\nvar _readAsByteArray = _interopRequireDefault(require(\"./readAsByteArray\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n\nvar FileSource = /*#__PURE__*/function () {\n  // Make this.size a method\n  function FileSource(file) {\n    _classCallCheck(this, FileSource);\n\n    this._file = file;\n    this.size = file.size;\n  }\n\n  _createClass(FileSource, [{\n    key: \"slice\",\n    value: function slice(start, end) {\n      // In Apache Cordova applications, a File must be resolved using\n      // FileReader instances, see\n      // https://cordova.apache.org/docs/en/8.x/reference/cordova-plugin-file/index.html#read-a-file\n      if ((0, _isCordova.default)()) {\n        return (0, _readAsByteArray.default)(this._file.slice(start, end));\n      }\n\n      var value = this._file.slice(start, end);\n\n      return Promise.resolve({\n        value: value\n      });\n    }\n  }, {\n    key: \"close\",\n    value: function close() {// Nothing to do here since we don't need to release any resources.\n    }\n  }]);\n\n  return FileSource;\n}();\n\nexports.default = FileSource;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n\nfunction len(blobOrArray) {\n  if (blobOrArray === undefined) return 0;\n  if (blobOrArray.size !== undefined) return blobOrArray.size;\n  return blobOrArray.length;\n}\n/*\n  Typed arrays and blobs don't have a concat method.\n  This function helps StreamSource accumulate data to reach chunkSize.\n*/\n\n\nfunction concat(a, b) {\n  if (a.concat) {\n    // Is `a` an Array?\n    return a.concat(b);\n  }\n\n  if (a instanceof Blob) {\n    return new Blob([a, b], {\n      type: a.type\n    });\n  }\n\n  if (a.set) {\n    // Is `a` a typed array?\n    var c = new a.constructor(a.length + b.length);\n    c.set(a);\n    c.set(b, a.length);\n    return c;\n  }\n\n  throw new Error('Unknown data type');\n}\n\nvar StreamSource = /*#__PURE__*/function () {\n  function StreamSource(reader, chunkSize) {\n    _classCallCheck(this, StreamSource);\n\n    this._chunkSize = chunkSize;\n    this._buffer = undefined;\n    this._bufferOffset = 0;\n    this._reader = reader;\n    this._done = false;\n  }\n\n  _createClass(StreamSource, [{\n    key: \"slice\",\n    value: function slice(start, end) {\n      if (start < this._bufferOffset) {\n        return Promise.reject(new Error(\"Requested data is before the reader's current offset\"));\n      }\n\n      return this._readUntilEnoughDataOrDone(start, end);\n    }\n  }, {\n    key: \"_readUntilEnoughDataOrDone\",\n    value: function _readUntilEnoughDataOrDone(start, end) {\n      var _this = this;\n\n      var hasEnoughData = end <= this._bufferOffset + len(this._buffer);\n\n      if (this._done || hasEnoughData) {\n        var value = this._getDataFromBuffer(start, end);\n\n        var done = value == null ? this._done : false;\n        return Promise.resolve({\n          value: value,\n          done: done\n        });\n      }\n\n      return this._reader.read().then(function (_ref) {\n        var value = _ref.value,\n            done = _ref.done;\n\n        if (done) {\n          _this._done = true;\n        } else if (_this._buffer === undefined) {\n          _this._buffer = value;\n        } else {\n          _this._buffer = concat(_this._buffer, value);\n        }\n\n        return _this._readUntilEnoughDataOrDone(start, end);\n      });\n    }\n  }, {\n    key: \"_getDataFromBuffer\",\n    value: function _getDataFromBuffer(start, end) {\n      // Remove data from buffer before `start`.\n      // Data might be reread from the buffer if an upload fails, so we can only\n      // safely delete data when it comes *before* what is currently being read.\n      if (start > this._bufferOffset) {\n        this._buffer = this._buffer.slice(start - this._bufferOffset);\n        this._bufferOffset = start;\n      } // If the buffer is empty after removing old data, all data has been read.\n\n\n      var hasAllDataBeenRead = len(this._buffer) === 0;\n\n      if (this._done && hasAllDataBeenRead) {\n        return null;\n      } // We already removed data before `start`, so we just return the first\n      // chunk from the buffer.\n\n\n      return this._buffer.slice(0, end - start);\n    }\n  }, {\n    key: \"close\",\n    value: function close() {\n      if (this._reader.cancel) {\n        this._reader.cancel();\n      }\n    }\n  }]);\n\n  return StreamSource;\n}();\n\nexports.default = StreamSource;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nvar _isReactNative = _interopRequireDefault(require(\"./isReactNative\"));\n\nvar _uriToBlob = _interopRequireDefault(require(\"./uriToBlob\"));\n\nvar _FileSource = _interopRequireDefault(require(\"./sources/FileSource\"));\n\nvar _StreamSource = _interopRequireDefault(require(\"./sources/StreamSource\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n\nvar FileReader = /*#__PURE__*/function () {\n  function FileReader() {\n    _classCallCheck(this, FileReader);\n  }\n\n  _createClass(FileReader, [{\n    key: \"openFile\",\n    value: function openFile(input, chunkSize) {\n      // In React Native, when user selects a file, instead of a File or Blob,\n      // you usually get a file object {} with a uri property that contains\n      // a local path to the file. We use XMLHttpRequest to fetch\n      // the file blob, before uploading with tus.\n      if ((0, _isReactNative.default)() && input && typeof input.uri !== 'undefined') {\n        return (0, _uriToBlob.default)(input.uri).then(function (blob) {\n          return new _FileSource.default(blob);\n        })[\"catch\"](function (err) {\n          throw new Error(\"tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. \".concat(err));\n        });\n      } // Since we emulate the Blob type in our tests (not all target browsers\n      // support it), we cannot use `instanceof` for testing whether the input value\n      // can be handled. Instead, we simply check is the slice() function and the\n      // size property are available.\n\n\n      if (typeof input.slice === 'function' && typeof input.size !== 'undefined') {\n        return Promise.resolve(new _FileSource.default(input));\n      }\n\n      if (typeof input.read === 'function') {\n        chunkSize = +chunkSize;\n\n        if (!isFinite(chunkSize)) {\n          return Promise.reject(new Error('cannot create source for stream without a finite value for the `chunkSize` option'));\n        }\n\n        return Promise.resolve(new _StreamSource.default(input, chunkSize));\n      }\n\n      return Promise.reject(new Error('source object may only be an instance of File, Blob, or Reader in this environment'));\n    }\n  }]);\n\n  return FileReader;\n}();\n\nexports.default = FileReader;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = fingerprint;\n\nvar _isReactNative = _interopRequireDefault(require(\"./isReactNative\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// TODO: Differenciate between input types\n\n/**\n * Generate a fingerprint for a file which will be used the store the endpoint\n *\n * @param {File} file\n * @param {Object} options\n * @param {Function} callback\n */\nfunction fingerprint(file, options) {\n  if ((0, _isReactNative.default)()) {\n    return Promise.resolve(reactNativeFingerprint(file, options));\n  }\n\n  return Promise.resolve(['tus-br', file.name, file.type, file.size, file.lastModified, options.endpoint].join('-'));\n}\n\nfunction reactNativeFingerprint(file, options) {\n  var exifHash = file.exif ? hashCode(JSON.stringify(file.exif)) : 'noexif';\n  return ['tus-rn', file.name || 'noname', file.size || 'nosize', exifHash, options.endpoint].join('/');\n}\n\nfunction hashCode(str) {\n  // from https://stackoverflow.com/a/8831937/151666\n  var hash = 0;\n\n  if (str.length === 0) {\n    return hash;\n  }\n\n  for (var i = 0; i < str.length; i++) {\n    var _char = str.charCodeAt(i);\n\n    hash = (hash << 5) - hash + _char;\n    hash &= hash; // Convert to 32bit integer\n  }\n\n  return hash;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nObject.defineProperty(exports, \"DetailedError\", {\n  enumerable: true,\n  get: function () {\n    return _error.default;\n  }\n});\nObject.defineProperty(exports, \"HttpStack\", {\n  enumerable: true,\n  get: function () {\n    return _httpStack.default;\n  }\n});\nexports.Upload = void 0;\nObject.defineProperty(exports, \"canStoreURLs\", {\n  enumerable: true,\n  get: function () {\n    return _urlStorage.canStoreURLs;\n  }\n});\nexports.defaultOptions = void 0;\nObject.defineProperty(exports, \"enableDebugLog\", {\n  enumerable: true,\n  get: function () {\n    return _logger.enableDebugLog;\n  }\n});\nexports.isSupported = void 0;\n\nvar _upload = _interopRequireDefault(require(\"../upload\"));\n\nvar _noopUrlStorage = _interopRequireDefault(require(\"../noopUrlStorage\"));\n\nvar _logger = require(\"../logger\");\n\nvar _error = _interopRequireDefault(require(\"../error\"));\n\nvar _urlStorage = require(\"./urlStorage\");\n\nvar _httpStack = _interopRequireDefault(require(\"./httpStack\"));\n\nvar _fileReader = _interopRequireDefault(require(\"./fileReader\"));\n\nvar _fingerprint = _interopRequireDefault(require(\"./fingerprint\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) {\n  \"@babel/helpers - typeof\";\n\n  if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n    _typeof = function _typeof(obj) {\n      return typeof obj;\n    };\n  } else {\n    _typeof = function _typeof(obj) {\n      return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n    };\n  }\n\n  return _typeof(obj);\n}\n\nfunction _classCallCheck(instance, Constructor) {\n  if (!(instance instanceof Constructor)) {\n    throw new TypeError(\"Cannot call a class as a function\");\n  }\n}\n\nfunction _defineProperties(target, props) {\n  for (var i = 0; i < props.length; i++) {\n    var descriptor = props[i];\n    descriptor.enumerable = descriptor.enumerable || false;\n    descriptor.configurable = true;\n    if (\"value\" in descriptor) descriptor.writable = true;\n    Object.defineProperty(target, descriptor.key, descriptor);\n  }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n  if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n  if (staticProps) _defineProperties(Constructor, staticProps);\n  return Constructor;\n}\n\nfunction _inherits(subClass, superClass) {\n  if (typeof superClass !== \"function\" && superClass !== null) {\n    throw new TypeError(\"Super expression must either be null or a function\");\n  }\n\n  subClass.prototype = Object.create(superClass && superClass.prototype, {\n    constructor: {\n      value: subClass,\n      writable: true,\n      configurable: true\n    }\n  });\n  if (superClass) _setPrototypeOf(subClass, superClass);\n}\n\nfunction _setPrototypeOf(o, p) {\n  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n    o.__proto__ = p;\n    return o;\n  };\n\n  return _setPrototypeOf(o, p);\n}\n\nfunction _createSuper(Derived) {\n  var hasNativeReflectConstruct = _isNativeReflectConstruct();\n\n  return function _createSuperInternal() {\n    var Super = _getPrototypeOf(Derived),\n        result;\n\n    if (hasNativeReflectConstruct) {\n      var NewTarget = _getPrototypeOf(this).constructor;\n\n      result = Reflect.construct(Super, arguments, NewTarget);\n    } else {\n      result = Super.apply(this, arguments);\n    }\n\n    return _possibleConstructorReturn(this, result);\n  };\n}\n\nfunction _possibleConstructorReturn(self, call) {\n  if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n    return call;\n  }\n\n  return _assertThisInitialized(self);\n}\n\nfunction _assertThisInitialized(self) {\n  if (self === void 0) {\n    throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n  }\n\n  return self;\n}\n\nfunction _isNativeReflectConstruct() {\n  if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n  if (Reflect.construct.sham) return false;\n  if (typeof Proxy === \"function\") return true;\n\n  try {\n    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n    return true;\n  } catch (e) {\n    return false;\n  }\n}\n\nfunction _getPrototypeOf(o) {\n  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n    return o.__proto__ || Object.getPrototypeOf(o);\n  };\n  return _getPrototypeOf(o);\n}\n\nfunction ownKeys(object, enumerableOnly) {\n  var keys = Object.keys(object);\n\n  if (Object.getOwnPropertySymbols) {\n    var symbols = Object.getOwnPropertySymbols(object);\n    if (enumerableOnly) symbols = symbols.filter(function (sym) {\n      return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n    });\n    keys.push.apply(keys, symbols);\n  }\n\n  return keys;\n}\n\nfunction _objectSpread(target) {\n  for (var i = 1; i < arguments.length; i++) {\n    var source = arguments[i] != null ? arguments[i] : {};\n\n    if (i % 2) {\n      ownKeys(Object(source), true).forEach(function (key) {\n        _defineProperty(target, key, source[key]);\n      });\n    } else if (Object.getOwnPropertyDescriptors) {\n      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n    } else {\n      ownKeys(Object(source)).forEach(function (key) {\n        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n      });\n    }\n  }\n\n  return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n  if (key in obj) {\n    Object.defineProperty(obj, key, {\n      value: value,\n      enumerable: true,\n      configurable: true,\n      writable: true\n    });\n  } else {\n    obj[key] = value;\n  }\n\n  return obj;\n}\n\nvar defaultOptions = _objectSpread(_objectSpread({}, _upload.default.defaultOptions), {}, {\n  httpStack: new _httpStack.default(),\n  fileReader: new _fileReader.default(),\n  urlStorage: _urlStorage.canStoreURLs ? new _urlStorage.WebStorageUrlStorage() : new _noopUrlStorage.default(),\n  fingerprint: _fingerprint.default\n});\n\nexports.defaultOptions = defaultOptions;\n\nvar Upload = /*#__PURE__*/function (_BaseUpload) {\n  _inherits(Upload, _BaseUpload);\n\n  var _super = _createSuper(Upload);\n\n  function Upload() {\n    var file = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n    _classCallCheck(this, Upload);\n\n    options = _objectSpread(_objectSpread({}, defaultOptions), options);\n    return _super.call(this, file, options);\n  }\n\n  _createClass(Upload, null, [{\n    key: \"terminate\",\n    value: function terminate(url, options, cb) {\n      options = _objectSpread(_objectSpread({}, defaultOptions), options);\n      return _upload.default.terminate(url, options, cb);\n    }\n  }]);\n\n  return Upload;\n}(_upload.default);\n\nexports.Upload = Upload;\nvar _window = window,\n    XMLHttpRequest = _window.XMLHttpRequest,\n    Blob = _window.Blob;\nvar isSupported = XMLHttpRequest && Blob && typeof Blob.prototype.slice === 'function';\nexports.isSupported = isSupported;", "\"use strict\";\n\nfunction settle(promises) {\n  const resolutions = [];\n  const rejections = [];\n\n  function resolved(value) {\n    resolutions.push(value);\n  }\n\n  function rejected(error) {\n    rejections.push(error);\n  }\n\n  const wait = Promise.all(promises.map(promise => promise.then(resolved, rejected)));\n  return wait.then(() => {\n    return {\n      successful: resolutions,\n      failed: rejections\n    };\n  });\n}\n\nmodule.exports = settle;", "\"use strict\";\n\nvar tus = require(\"tus-js-client\");\n\nfunction isCordova() {\n  return typeof window !== 'undefined' && (typeof window.PhoneGap !== 'undefined' || typeof window.Cordova !== 'undefined' || typeof window.cordova !== 'undefined');\n}\n\nfunction isReactNative() {\n  return typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative';\n} // We override tus fingerprint to uppy\u2019s `file.id`, since the `file.id`\n// now also includes `relativePath` for files added from folders.\n// This means you can add 2 identical files, if one is in folder a,\n// the other in folder b \u2014 `a/file.jpg` and `b/file.jpg`, when added\n// together with a folder, will be treated as 2 separate files.\n//\n// For React Native and Cordova, we let tus-js-client\u2019s default\n// fingerprint handling take charge.\n\n\nfunction getFingerprint(uppyFileObj) {\n  return (file, options) => {\n    if (isCordova() || isReactNative()) {\n      return tus.defaultOptions.fingerprint(file, options);\n    }\n\n    const uppyFingerprint = ['tus', uppyFileObj.id, options.endpoint].join('-');\n    return Promise.resolve(uppyFingerprint);\n  };\n}\n\nmodule.exports = getFingerprint;", "\"use strict\";\n\nvar tus = require(\"tus-js-client\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _RateLimitedQueue = require(\"@uppy/utils/lib/RateLimitedQueue\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst emitSocketProgress = require(\"@uppy/utils/lib/emitSocketProgress\");\n\nconst getSocketHost = require(\"@uppy/utils/lib/getSocketHost\");\n\nconst settle = require(\"@uppy/utils/lib/settle\");\n\nconst EventTracker = require(\"@uppy/utils/lib/EventTracker\");\n\nconst NetworkError = require(\"@uppy/utils/lib/NetworkError\");\n\nconst isNetworkError = require(\"@uppy/utils/lib/isNetworkError\");\n\nconst hasProperty = require(\"@uppy/utils/lib/hasProperty\");\n\nconst getFingerprint = require(\"./getFingerprint.js\");\n\nconst packageJson = {\n  \"version\": \"2.4.6\"\n};\n/** @typedef {import('..').TusOptions} TusOptions */\n\n/** @typedef {import('tus-js-client').UploadOptions} RawTusOptions */\n\n/** @typedef {import('@uppy/core').Uppy} Uppy */\n\n/** @typedef {import('@uppy/core').UppyFile} UppyFile */\n\n/** @typedef {import('@uppy/core').FailedUppyFile<{}>} FailedUppyFile */\n\n/**\n * Extracted from https://github.com/tus/tus-js-client/blob/master/lib/upload.js#L13\n * excepted we removed 'fingerprint' key to avoid adding more dependencies\n *\n * @type {RawTusOptions}\n */\n\nconst tusDefaultOptions = {\n  endpoint: '',\n  uploadUrl: null,\n  metadata: {},\n  uploadSize: null,\n  onProgress: null,\n  onChunkComplete: null,\n  onSuccess: null,\n  onError: null,\n  overridePatchMethod: false,\n  headers: {},\n  addRequestId: false,\n  chunkSize: Infinity,\n  retryDelays: [100, 1000, 3000, 5000],\n  parallelUploads: 1,\n  removeFingerprintOnSuccess: false,\n  uploadLengthDeferred: false,\n  uploadDataDuringCreation: false\n};\n/**\n * Tus resumable file uploader\n */\n\nvar _retryDelayIterator = /*#__PURE__*/_classPrivateFieldLooseKey(\"retryDelayIterator\");\n\nvar _queueRequestSocketToken = /*#__PURE__*/_classPrivateFieldLooseKey(\"queueRequestSocketToken\");\n\nvar _requestSocketToken = /*#__PURE__*/_classPrivateFieldLooseKey(\"requestSocketToken\");\n\nclass Tus extends BasePlugin {\n  /**\n   * @param {Uppy} uppy\n   * @param {TusOptions} opts\n   */\n  constructor(uppy, _opts) {\n    var _this$opts$rateLimite, _this$opts$retryDelay;\n\n    super(uppy, _opts);\n    Object.defineProperty(this, _retryDelayIterator, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _queueRequestSocketToken, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _requestSocketToken, {\n      writable: true,\n      value: async file => {\n        const Client = file.remote.providerOptions.provider ? _companionClient.Provider : _companionClient.RequestClient;\n        const client = new Client(this.uppy, file.remote.providerOptions);\n        const opts = { ...this.opts\n        };\n\n        if (file.tus) {\n          // Install file-specific upload overrides.\n          Object.assign(opts, file.tus);\n        }\n\n        const res = await client.post(file.remote.url, { ...file.remote.body,\n          endpoint: opts.endpoint,\n          uploadUrl: opts.uploadUrl,\n          protocol: 'tus',\n          size: file.data.size,\n          headers: opts.headers,\n          metadata: file.meta\n        });\n        return res.token;\n      }\n    });\n    this.type = 'uploader';\n    this.id = this.opts.id || 'Tus';\n    this.title = 'Tus'; // set default options\n\n    const defaultOptions = {\n      useFastRemoteRetry: true,\n      limit: 20,\n      retryDelays: tusDefaultOptions.retryDelays,\n      withCredentials: false\n    }; // merge default options with the ones set by user\n\n    /** @type {import(\"..\").TusOptions} */\n\n    this.opts = { ...defaultOptions,\n      ..._opts\n    };\n\n    if ('autoRetry' in _opts) {\n      throw new Error('The `autoRetry` option was deprecated and has been removed.');\n    }\n    /**\n     * Simultaneous upload limiting is shared across all uploads with this plugin.\n     *\n     * @type {RateLimitedQueue}\n     */\n\n\n    this.requests = (_this$opts$rateLimite = this.opts.rateLimitedQueue) != null ? _this$opts$rateLimite : new _RateLimitedQueue.RateLimitedQueue(this.opts.limit);\n    _classPrivateFieldLooseBase(this, _retryDelayIterator)[_retryDelayIterator] = (_this$opts$retryDelay = this.opts.retryDelays) == null ? void 0 : _this$opts$retryDelay.values();\n    this.uploaders = Object.create(null);\n    this.uploaderEvents = Object.create(null);\n    this.uploaderSockets = Object.create(null);\n    this.handleResetProgress = this.handleResetProgress.bind(this);\n    this.handleUpload = this.handleUpload.bind(this);\n    _classPrivateFieldLooseBase(this, _queueRequestSocketToken)[_queueRequestSocketToken] = this.requests.wrapPromiseFunction(_classPrivateFieldLooseBase(this, _requestSocketToken)[_requestSocketToken]);\n  }\n\n  handleResetProgress() {\n    const files = { ...this.uppy.getState().files\n    };\n    Object.keys(files).forEach(fileID => {\n      // Only clone the file object if it has a Tus `uploadUrl` attached.\n      if (files[fileID].tus && files[fileID].tus.uploadUrl) {\n        const tusState = { ...files[fileID].tus\n        };\n        delete tusState.uploadUrl;\n        files[fileID] = { ...files[fileID],\n          tus: tusState\n        };\n      }\n    });\n    this.uppy.setState({\n      files\n    });\n  }\n  /**\n   * Clean up all references for a file's upload: the tus.Upload instance,\n   * any events related to the file, and the Companion WebSocket connection.\n   *\n   * @param {string} fileID\n   */\n\n\n  resetUploaderReferences(fileID, opts) {\n    if (opts === void 0) {\n      opts = {};\n    }\n\n    if (this.uploaders[fileID]) {\n      const uploader = this.uploaders[fileID];\n      uploader.abort();\n\n      if (opts.abort) {\n        uploader.abort(true);\n      }\n\n      this.uploaders[fileID] = null;\n    }\n\n    if (this.uploaderEvents[fileID]) {\n      this.uploaderEvents[fileID].remove();\n      this.uploaderEvents[fileID] = null;\n    }\n\n    if (this.uploaderSockets[fileID]) {\n      this.uploaderSockets[fileID].close();\n      this.uploaderSockets[fileID] = null;\n    }\n  }\n  /**\n   * Create a new Tus upload.\n   *\n   * A lot can happen during an upload, so this is quite hard to follow!\n   * - First, the upload is started. If the file was already paused by the time the upload starts, nothing should happen.\n   *   If the `limit` option is used, the upload must be queued onto the `this.requests` queue.\n   *   When an upload starts, we store the tus.Upload instance, and an EventTracker instance that manages the event listeners\n   *   for pausing, cancellation, removal, etc.\n   * - While the upload is in progress, it may be paused or cancelled.\n   *   Pausing aborts the underlying tus.Upload, and removes the upload from the `this.requests` queue. All other state is\n   *   maintained.\n   *   Cancelling removes the upload from the `this.requests` queue, and completely aborts the upload-- the `tus.Upload`\n   *   instance is aborted and discarded, the EventTracker instance is destroyed (removing all listeners).\n   *   Resuming the upload uses the `this.requests` queue as well, to prevent selectively pausing and resuming uploads from\n   *   bypassing the limit.\n   * - After completing an upload, the tus.Upload and EventTracker instances are cleaned up, and the upload is marked as done\n   *   in the `this.requests` queue.\n   * - When an upload completed with an error, the same happens as on successful completion, but the `upload()` promise is\n   *   rejected.\n   *\n   * When working on this function, keep in mind:\n   *  - When an upload is completed or cancelled for any reason, the tus.Upload and EventTracker instances need to be cleaned\n   *    up using this.resetUploaderReferences().\n   *  - When an upload is cancelled or paused, for any reason, it needs to be removed from the `this.requests` queue using\n   *    `queuedRequest.abort()`.\n   *  - When an upload is completed for any reason, including errors, it needs to be marked as such using\n   *    `queuedRequest.done()`.\n   *  - When an upload is started or resumed, it needs to go through the `this.requests` queue. The `queuedRequest` variable\n   *    must be updated so the other uses of it are valid.\n   *  - Before replacing the `queuedRequest` variable, the previous `queuedRequest` must be aborted, else it will keep taking\n   *    up a spot in the queue.\n   *\n   * @param {UppyFile} file for use with upload\n   * @returns {Promise<void>}\n   */\n\n\n  upload(file) {\n    var _this = this;\n\n    this.resetUploaderReferences(file.id); // Create a new tus upload\n\n    return new Promise((resolve, reject) => {\n      let queuedRequest;\n      let qRequest;\n      let upload;\n      this.uppy.emit('upload-started', file);\n      const opts = { ...this.opts,\n        ...(file.tus || {})\n      };\n\n      if (typeof opts.headers === 'function') {\n        opts.headers = opts.headers(file);\n      }\n      /** @type {RawTusOptions} */\n\n\n      const uploadOptions = { ...tusDefaultOptions,\n        ...opts\n      }; // We override tus fingerprint to uppy\u2019s `file.id`, since the `file.id`\n      // now also includes `relativePath` for files added from folders.\n      // This means you can add 2 identical files, if one is in folder a,\n      // the other in folder b.\n\n      uploadOptions.fingerprint = getFingerprint(file);\n\n      uploadOptions.onBeforeRequest = req => {\n        const xhr = req.getUnderlyingObject();\n        xhr.withCredentials = !!opts.withCredentials;\n        let userProvidedPromise;\n\n        if (typeof opts.onBeforeRequest === 'function') {\n          userProvidedPromise = opts.onBeforeRequest(req, file);\n        }\n\n        if (hasProperty(queuedRequest, 'shouldBeRequeued')) {\n          if (!queuedRequest.shouldBeRequeued) return Promise.reject();\n          let done;\n          const p = new Promise(res => {\n            // eslint-disable-line promise/param-names\n            done = res;\n          });\n          queuedRequest = this.requests.run(() => {\n            if (file.isPaused) {\n              queuedRequest.abort();\n            }\n\n            done();\n            return () => {};\n          }); // If the request has been requeued because it was rate limited by the\n          // remote server, we want to wait for `RateLimitedQueue` to dispatch\n          // the re-try request.\n          // Therefore we create a promise that the queue will resolve when\n          // enough time has elapsed to expect not to be rate-limited again.\n          // This means we can hold the Tus retry here with a `Promise.all`,\n          // together with the returned value of the user provided\n          // `onBeforeRequest` option callback (in case it returns a promise).\n\n          return Promise.all([p, userProvidedPromise]);\n        }\n\n        return userProvidedPromise;\n      };\n\n      uploadOptions.onError = err => {\n        var _queuedRequest;\n\n        this.uppy.log(err);\n        const xhr = err.originalRequest ? err.originalRequest.getUnderlyingObject() : null;\n\n        if (isNetworkError(xhr)) {\n          // eslint-disable-next-line no-param-reassign\n          err = new NetworkError(err, xhr);\n        }\n\n        this.resetUploaderReferences(file.id);\n        (_queuedRequest = queuedRequest) == null ? void 0 : _queuedRequest.abort();\n        this.uppy.emit('upload-error', file, err);\n        reject(err);\n      };\n\n      uploadOptions.onProgress = (bytesUploaded, bytesTotal) => {\n        this.onReceiveUploadUrl(file, upload.url);\n        this.uppy.emit('upload-progress', file, {\n          uploader: this,\n          bytesUploaded,\n          bytesTotal\n        });\n      };\n\n      uploadOptions.onSuccess = () => {\n        const uploadResp = {\n          uploadURL: upload.url\n        };\n        this.resetUploaderReferences(file.id);\n        queuedRequest.done();\n        this.uppy.emit('upload-success', file, uploadResp);\n\n        if (upload.url) {\n          this.uppy.log(`Download ${upload.file.name} from ${upload.url}`);\n        }\n\n        resolve(upload);\n      };\n\n      const defaultOnShouldRetry = err => {\n        var _err$originalResponse;\n\n        const status = err == null ? void 0 : (_err$originalResponse = err.originalResponse) == null ? void 0 : _err$originalResponse.getStatus();\n\n        if (status === 429) {\n          // HTTP 429 Too Many Requests => to avoid the whole download to fail, pause all requests.\n          if (!this.requests.isPaused) {\n            var _classPrivateFieldLoo;\n\n            const next = (_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _retryDelayIterator)[_retryDelayIterator]) == null ? void 0 : _classPrivateFieldLoo.next();\n\n            if (next == null || next.done) {\n              return false;\n            }\n\n            this.requests.rateLimit(next.value);\n          }\n        } else if (status > 400 && status < 500 && status !== 409) {\n          // HTTP 4xx, the server won't send anything, it's doesn't make sense to retry\n          return false;\n        } else if (typeof navigator !== 'undefined' && navigator.onLine === false) {\n          // The navigator is offline, let's wait for it to come back online.\n          if (!this.requests.isPaused) {\n            this.requests.pause();\n            window.addEventListener('online', () => {\n              this.requests.resume();\n            }, {\n              once: true\n            });\n          }\n        }\n\n        queuedRequest.abort();\n        queuedRequest = {\n          shouldBeRequeued: true,\n\n          abort() {\n            this.shouldBeRequeued = false;\n          },\n\n          done() {\n            throw new Error('Cannot mark a queued request as done: this indicates a bug');\n          },\n\n          fn() {\n            throw new Error('Cannot run a queued request: this indicates a bug');\n          }\n\n        };\n        return true;\n      };\n\n      if (opts.onShouldRetry != null) {\n        uploadOptions.onShouldRetry = function () {\n          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n            args[_key] = arguments[_key];\n          }\n\n          return opts.onShouldRetry(...args, defaultOnShouldRetry);\n        };\n      } else {\n        uploadOptions.onShouldRetry = defaultOnShouldRetry;\n      }\n\n      const copyProp = (obj, srcProp, destProp) => {\n        if (hasProperty(obj, srcProp) && !hasProperty(obj, destProp)) {\n          // eslint-disable-next-line no-param-reassign\n          obj[destProp] = obj[srcProp];\n        }\n      };\n      /** @type {Record<string, string>} */\n\n\n      const meta = {};\n      const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default.\n      : Object.keys(file.meta);\n      metaFields.forEach(item => {\n        meta[item] = file.meta[item];\n      }); // tusd uses metadata fields 'filetype' and 'filename'\n\n      copyProp(meta, 'type', 'filetype');\n      copyProp(meta, 'name', 'filename');\n      uploadOptions.metadata = meta;\n      upload = new tus.Upload(file.data, uploadOptions);\n      this.uploaders[file.id] = upload;\n      this.uploaderEvents[file.id] = new EventTracker(this.uppy); // eslint-disable-next-line prefer-const\n\n      qRequest = () => {\n        if (!file.isPaused) {\n          upload.start();\n        } // Don't do anything here, the caller will take care of cancelling the upload itself\n        // using resetUploaderReferences(). This is because resetUploaderReferences() has to be\n        // called when this request is still in the queue, and has not been started yet, too. At\n        // that point this cancellation function is not going to be called.\n        // Also, we need to remove the request from the queue _without_ destroying everything\n        // related to this upload to handle pauses.\n\n\n        return () => {};\n      };\n\n      upload.findPreviousUploads().then(previousUploads => {\n        const previousUpload = previousUploads[0];\n\n        if (previousUpload) {\n          this.uppy.log(`[Tus] Resuming upload of ${file.id} started at ${previousUpload.creationTime}`);\n          upload.resumeFromPreviousUpload(previousUpload);\n        }\n      });\n      queuedRequest = this.requests.run(qRequest);\n      this.onFileRemove(file.id, targetFileID => {\n        queuedRequest.abort();\n        this.resetUploaderReferences(file.id, {\n          abort: !!upload.url\n        });\n        resolve(`upload ${targetFileID} was removed`);\n      });\n      this.onPause(file.id, isPaused => {\n        queuedRequest.abort();\n\n        if (isPaused) {\n          // Remove this file from the queue so another file can start in its place.\n          upload.abort();\n        } else {\n          // Resuming an upload should be queued, else you could pause and then\n          // resume a queued upload to make it skip the queue.\n          queuedRequest = this.requests.run(qRequest);\n        }\n      });\n      this.onPauseAll(file.id, () => {\n        queuedRequest.abort();\n        upload.abort();\n      });\n      this.onCancelAll(file.id, function (_temp) {\n        let {\n          reason\n        } = _temp === void 0 ? {} : _temp;\n\n        if (reason === 'user') {\n          queuedRequest.abort();\n\n          _this.resetUploaderReferences(file.id, {\n            abort: !!upload.url\n          });\n        }\n\n        resolve(`upload ${file.id} was canceled`);\n      });\n      this.onResumeAll(file.id, () => {\n        queuedRequest.abort();\n\n        if (file.error) {\n          upload.abort();\n        }\n\n        queuedRequest = this.requests.run(qRequest);\n      });\n    }).catch(err => {\n      this.uppy.emit('upload-error', file, err);\n      throw err;\n    });\n  }\n\n  /**\n   * @param {UppyFile} file for use with upload\n   * @returns {Promise<void>}\n   */\n  async uploadRemote(file) {\n    this.resetUploaderReferences(file.id); // Don't double-emit upload-started for Golden Retriever-restored files that were already started\n\n    if (!file.progress.uploadStarted || !file.isRestored) {\n      this.uppy.emit('upload-started', file);\n    }\n\n    try {\n      if (file.serverToken) {\n        return this.connectToServerSocket(file);\n      }\n\n      const serverToken = await _classPrivateFieldLooseBase(this, _queueRequestSocketToken)[_queueRequestSocketToken](file);\n      if (!this.uppy.getState().files[file.id]) return undefined;\n      this.uppy.setFileState(file.id, {\n        serverToken\n      });\n      return this.connectToServerSocket(this.uppy.getFile(file.id));\n    } catch (err) {\n      this.uppy.emit('upload-error', file, err);\n      throw err;\n    }\n  }\n  /**\n   * See the comment on the upload() method.\n   *\n   * Additionally, when an upload is removed, completed, or cancelled, we need to close the WebSocket connection. This is\n   * handled by the resetUploaderReferences() function, so the same guidelines apply as in upload().\n   *\n   * @param {UppyFile} file\n   */\n\n\n  connectToServerSocket(file) {\n    var _this2 = this;\n\n    return new Promise((resolve, reject) => {\n      const token = file.serverToken;\n      const host = getSocketHost(file.remote.companionUrl);\n      const socket = new _companionClient.Socket({\n        target: `${host}/api/${token}`\n      });\n      this.uploaderSockets[file.id] = socket;\n      this.uploaderEvents[file.id] = new EventTracker(this.uppy);\n      let queuedRequest;\n      this.onFileRemove(file.id, () => {\n        queuedRequest.abort();\n        socket.send('cancel', {});\n        this.resetUploaderReferences(file.id);\n        resolve(`upload ${file.id} was removed`);\n      });\n      this.onPause(file.id, isPaused => {\n        if (isPaused) {\n          // Remove this file from the queue so another file can start in its place.\n          queuedRequest.abort();\n          socket.send('pause', {});\n        } else {\n          // Resuming an upload should be queued, else you could pause and then\n          // resume a queued upload to make it skip the queue.\n          queuedRequest.abort();\n          queuedRequest = this.requests.run(() => {\n            socket.send('resume', {});\n            return () => {};\n          });\n        }\n      });\n      this.onPauseAll(file.id, () => {\n        queuedRequest.abort();\n        socket.send('pause', {});\n      });\n      this.onCancelAll(file.id, function (_temp2) {\n        let {\n          reason\n        } = _temp2 === void 0 ? {} : _temp2;\n\n        if (reason === 'user') {\n          queuedRequest.abort();\n          socket.send('cancel', {});\n\n          _this2.resetUploaderReferences(file.id);\n        }\n\n        resolve(`upload ${file.id} was canceled`);\n      });\n      this.onResumeAll(file.id, () => {\n        queuedRequest.abort();\n\n        if (file.error) {\n          socket.send('pause', {});\n        }\n\n        queuedRequest = this.requests.run(() => {\n          socket.send('resume', {});\n          return () => {};\n        });\n      });\n      this.onRetry(file.id, () => {\n        // Only do the retry if the upload is actually in progress;\n        // else we could try to send these messages when the upload is still queued.\n        // We may need a better check for this since the socket may also be closed\n        // for other reasons, like network failures.\n        if (socket.isOpen) {\n          socket.send('pause', {});\n          socket.send('resume', {});\n        }\n      });\n      this.onRetryAll(file.id, () => {\n        // See the comment in the onRetry() call\n        if (socket.isOpen) {\n          socket.send('pause', {});\n          socket.send('resume', {});\n        }\n      });\n      socket.on('progress', progressData => emitSocketProgress(this, progressData, file));\n      socket.on('error', errData => {\n        const {\n          message\n        } = errData.error;\n        const error = Object.assign(new Error(message), {\n          cause: errData.error\n        }); // If the remote retry optimisation should not be used,\n        // close the socket\u2014this will tell companion to clear state and delete the file.\n\n        if (!this.opts.useFastRemoteRetry) {\n          this.resetUploaderReferences(file.id); // Remove the serverToken so that a new one will be created for the retry.\n\n          this.uppy.setFileState(file.id, {\n            serverToken: null\n          });\n        } else {\n          socket.close();\n        }\n\n        this.uppy.emit('upload-error', file, error);\n        queuedRequest.done();\n        reject(error);\n      });\n      socket.on('success', data => {\n        const uploadResp = {\n          uploadURL: data.url\n        };\n        this.uppy.emit('upload-success', file, uploadResp);\n        this.resetUploaderReferences(file.id);\n        queuedRequest.done();\n        resolve();\n      });\n      queuedRequest = this.requests.run(() => {\n        if (file.isPaused) {\n          socket.send('pause', {});\n        } // Don't do anything here, the caller will take care of cancelling the upload itself\n        // using resetUploaderReferences(). This is because resetUploaderReferences() has to be\n        // called when this request is still in the queue, and has not been started yet, too. At\n        // that point this cancellation function is not going to be called.\n        // Also, we need to remove the request from the queue _without_ destroying everything\n        // related to this upload to handle pauses.\n\n\n        return () => {};\n      });\n    });\n  }\n  /**\n   * Store the uploadUrl on the file options, so that when Golden Retriever\n   * restores state, we will continue uploading to the correct URL.\n   *\n   * @param {UppyFile} file\n   * @param {string} uploadURL\n   */\n\n\n  onReceiveUploadUrl(file, uploadURL) {\n    const currentFile = this.uppy.getFile(file.id);\n    if (!currentFile) return; // Only do the update if we didn't have an upload URL yet.\n\n    if (!currentFile.tus || currentFile.tus.uploadUrl !== uploadURL) {\n      this.uppy.log('[Tus] Storing upload url');\n      this.uppy.setFileState(currentFile.id, {\n        tus: { ...currentFile.tus,\n          uploadUrl: uploadURL\n        }\n      });\n    }\n  }\n  /**\n   * @param {string} fileID\n   * @param {function(string): void} cb\n   */\n\n\n  onFileRemove(fileID, cb) {\n    this.uploaderEvents[fileID].on('file-removed', file => {\n      if (fileID === file.id) cb(file.id);\n    });\n  }\n  /**\n   * @param {string} fileID\n   * @param {function(boolean): void} cb\n   */\n\n\n  onPause(fileID, cb) {\n    this.uploaderEvents[fileID].on('upload-pause', (targetFileID, isPaused) => {\n      if (fileID === targetFileID) {\n        // const isPaused = this.uppy.pauseResume(fileID)\n        cb(isPaused);\n      }\n    });\n  }\n  /**\n   * @param {string} fileID\n   * @param {function(): void} cb\n   */\n\n\n  onRetry(fileID, cb) {\n    this.uploaderEvents[fileID].on('upload-retry', targetFileID => {\n      if (fileID === targetFileID) {\n        cb();\n      }\n    });\n  }\n  /**\n   * @param {string} fileID\n   * @param {function(): void} cb\n   */\n\n\n  onRetryAll(fileID, cb) {\n    this.uploaderEvents[fileID].on('retry-all', () => {\n      if (!this.uppy.getFile(fileID)) return;\n      cb();\n    });\n  }\n  /**\n   * @param {string} fileID\n   * @param {function(): void} cb\n   */\n\n\n  onPauseAll(fileID, cb) {\n    this.uploaderEvents[fileID].on('pause-all', () => {\n      if (!this.uppy.getFile(fileID)) return;\n      cb();\n    });\n  }\n  /**\n   * @param {string} fileID\n   * @param {function(): void} eventHandler\n   */\n\n\n  onCancelAll(fileID, eventHandler) {\n    var _this3 = this;\n\n    this.uploaderEvents[fileID].on('cancel-all', function () {\n      if (!_this3.uppy.getFile(fileID)) return;\n      eventHandler(...arguments);\n    });\n  }\n  /**\n   * @param {string} fileID\n   * @param {function(): void} cb\n   */\n\n\n  onResumeAll(fileID, cb) {\n    this.uploaderEvents[fileID].on('resume-all', () => {\n      if (!this.uppy.getFile(fileID)) return;\n      cb();\n    });\n  }\n  /**\n   * @param {(UppyFile | FailedUppyFile)[]} files\n   */\n\n\n  uploadFiles(files) {\n    const promises = files.map((file, i) => {\n      const current = i + 1;\n      const total = files.length;\n\n      if ('error' in file && file.error) {\n        return Promise.reject(new Error(file.error));\n      }\n\n      if (file.isRemote) {\n        // We emit upload-started here, so that it's also emitted for files\n        // that have to wait due to the `limit` option.\n        // Don't double-emit upload-started for Golden Retriever-restored files that were already started\n        if (!file.progress.uploadStarted || !file.isRestored) {\n          this.uppy.emit('upload-started', file);\n        }\n\n        return this.uploadRemote(file, current, total);\n      } // Don't double-emit upload-started for Golden Retriever-restored files that were already started\n\n\n      if (!file.progress.uploadStarted || !file.isRestored) {\n        this.uppy.emit('upload-started', file);\n      }\n\n      return this.upload(file, current, total);\n    });\n    return settle(promises);\n  }\n  /**\n   * @param {string[]} fileIDs\n   */\n\n\n  handleUpload(fileIDs) {\n    if (fileIDs.length === 0) {\n      this.uppy.log('[Tus] No files to upload');\n      return Promise.resolve();\n    }\n\n    if (this.opts.limit === 0) {\n      this.uppy.log('[Tus] When uploading multiple files at once, consider setting the `limit` option (to `10` for example), to limit the number of concurrent uploads, which helps prevent memory and network issues: https://uppy.io/docs/tus/#limit-0', 'warning');\n    }\n\n    this.uppy.log('[Tus] Uploading...');\n    const filesToUpload = fileIDs.map(fileID => this.uppy.getFile(fileID));\n    return this.uploadFiles(filesToUpload).then(() => null);\n  }\n\n  install() {\n    this.uppy.setState({\n      capabilities: { ...this.uppy.getState().capabilities,\n        resumableUploads: true\n      }\n    });\n    this.uppy.addUploader(this.handleUpload);\n    this.uppy.on('reset-progress', this.handleResetProgress);\n  }\n\n  uninstall() {\n    this.uppy.setState({\n      capabilities: { ...this.uppy.getState().capabilities,\n        resumableUploads: false\n      }\n    });\n    this.uppy.removeUploader(this.handleUpload);\n  }\n\n}\n\nTus.VERSION = packageJson.version;\nmodule.exports = Tus;", "\n/**\n * Expose `Emitter`.\n */\n\nif (typeof module !== 'undefined') {\n  module.exports = Emitter;\n}\n\n/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nfunction Emitter(obj) {\n  if (obj) return mixin(obj);\n};\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n  for (var key in Emitter.prototype) {\n    obj[key] = Emitter.prototype[key];\n  }\n  return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n  this._callbacks = this._callbacks || {};\n  (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n    .push(fn);\n  return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n  function on() {\n    this.off(event, on);\n    fn.apply(this, arguments);\n  }\n\n  on.fn = fn;\n  this.on(event, on);\n  return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n  this._callbacks = this._callbacks || {};\n\n  // all\n  if (0 == arguments.length) {\n    this._callbacks = {};\n    return this;\n  }\n\n  // specific event\n  var callbacks = this._callbacks['$' + event];\n  if (!callbacks) return this;\n\n  // remove all handlers\n  if (1 == arguments.length) {\n    delete this._callbacks['$' + event];\n    return this;\n  }\n\n  // remove specific handler\n  var cb;\n  for (var i = 0; i < callbacks.length; i++) {\n    cb = callbacks[i];\n    if (cb === fn || cb.fn === fn) {\n      callbacks.splice(i, 1);\n      break;\n    }\n  }\n\n  // Remove event specific arrays for event types that no\n  // one is subscribed for to avoid memory leak.\n  if (callbacks.length === 0) {\n    delete this._callbacks['$' + event];\n  }\n\n  return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n  this._callbacks = this._callbacks || {};\n\n  var args = new Array(arguments.length - 1)\n    , callbacks = this._callbacks['$' + event];\n\n  for (var i = 1; i < arguments.length; i++) {\n    args[i - 1] = arguments[i];\n  }\n\n  if (callbacks) {\n    callbacks = callbacks.slice(0);\n    for (var i = 0, len = callbacks.length; i < len; ++i) {\n      callbacks[i].apply(this, args);\n    }\n  }\n\n  return this;\n};\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n  this._callbacks = this._callbacks || {};\n  return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n  return !! this.listeners(event).length;\n};\n", "\"use strict\";\n\nfunction parseUrl(url) {\n  const scheme = /^\\w+:\\/\\//.exec(url);\n  let i = 0;\n\n  if (scheme) {\n    i = scheme[0].length + 1;\n  }\n\n  const slashIndex = url.indexOf('/', i);\n\n  if (slashIndex === -1) {\n    return {\n      origin: url,\n      pathname: '/'\n    };\n  }\n\n  return {\n    origin: url.slice(0, slashIndex),\n    pathname: url.slice(slashIndex)\n  };\n}\n\nmodule.exports = parseUrl;", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ERROR_PACKET = exports.PACKET_TYPES_REVERSE = exports.PACKET_TYPES = void 0;\nconst PACKET_TYPES = Object.create(null); // no Map = no polyfill\nexports.PACKET_TYPES = PACKET_TYPES;\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nexports.PACKET_TYPES_REVERSE = PACKET_TYPES_REVERSE;\nObject.keys(PACKET_TYPES).forEach((key) => {\n    PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexports.ERROR_PACKET = ERROR_PACKET;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.encodePacket = void 0;\nexports.encodePacketToBinary = encodePacketToBinary;\nconst commons_js_1 = require(\"./commons.js\");\nconst withNativeBlob = typeof Blob === \"function\" ||\n    (typeof Blob !== \"undefined\" &&\n        Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = (obj) => {\n    return typeof ArrayBuffer.isView === \"function\"\n        ? ArrayBuffer.isView(obj)\n        : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n    if (withNativeBlob && data instanceof Blob) {\n        if (supportsBinary) {\n            return callback(data);\n        }\n        else {\n            return encodeBlobAsBase64(data, callback);\n        }\n    }\n    else if (withNativeArrayBuffer &&\n        (data instanceof ArrayBuffer || isView(data))) {\n        if (supportsBinary) {\n            return callback(data);\n        }\n        else {\n            return encodeBlobAsBase64(new Blob([data]), callback);\n        }\n    }\n    // plain string\n    return callback(commons_js_1.PACKET_TYPES[type] + (data || \"\"));\n};\nexports.encodePacket = encodePacket;\nconst encodeBlobAsBase64 = (data, callback) => {\n    const fileReader = new FileReader();\n    fileReader.onload = function () {\n        const content = fileReader.result.split(\",\")[1];\n        callback(\"b\" + (content || \"\"));\n    };\n    return fileReader.readAsDataURL(data);\n};\nfunction toArray(data) {\n    if (data instanceof Uint8Array) {\n        return data;\n    }\n    else if (data instanceof ArrayBuffer) {\n        return new Uint8Array(data);\n    }\n    else {\n        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n    }\n}\nlet TEXT_ENCODER;\nfunction encodePacketToBinary(packet, callback) {\n    if (withNativeBlob && packet.data instanceof Blob) {\n        return packet.data.arrayBuffer().then(toArray).then(callback);\n    }\n    else if (withNativeArrayBuffer &&\n        (packet.data instanceof ArrayBuffer || isView(packet.data))) {\n        return callback(toArray(packet.data));\n    }\n    encodePacket(packet, false, (encoded) => {\n        if (!TEXT_ENCODER) {\n            TEXT_ENCODER = new TextEncoder();\n        }\n        callback(TEXT_ENCODER.encode(encoded));\n    });\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decode = exports.encode = void 0;\n// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n    lookup[chars.charCodeAt(i)] = i;\n}\nconst encode = (arraybuffer) => {\n    let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n    for (i = 0; i < len; i += 3) {\n        base64 += chars[bytes[i] >> 2];\n        base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n        base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n        base64 += chars[bytes[i + 2] & 63];\n    }\n    if (len % 3 === 2) {\n        base64 = base64.substring(0, base64.length - 1) + '=';\n    }\n    else if (len % 3 === 1) {\n        base64 = base64.substring(0, base64.length - 2) + '==';\n    }\n    return base64;\n};\nexports.encode = encode;\nconst decode = (base64) => {\n    let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n    if (base64[base64.length - 1] === '=') {\n        bufferLength--;\n        if (base64[base64.length - 2] === '=') {\n            bufferLength--;\n        }\n    }\n    const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n    for (i = 0; i < len; i += 4) {\n        encoded1 = lookup[base64.charCodeAt(i)];\n        encoded2 = lookup[base64.charCodeAt(i + 1)];\n        encoded3 = lookup[base64.charCodeAt(i + 2)];\n        encoded4 = lookup[base64.charCodeAt(i + 3)];\n        bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n        bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n        bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n    }\n    return arraybuffer;\n};\nexports.decode = decode;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decodePacket = void 0;\nconst commons_js_1 = require(\"./commons.js\");\nconst base64_arraybuffer_js_1 = require(\"./contrib/base64-arraybuffer.js\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst decodePacket = (encodedPacket, binaryType) => {\n    if (typeof encodedPacket !== \"string\") {\n        return {\n            type: \"message\",\n            data: mapBinary(encodedPacket, binaryType),\n        };\n    }\n    const type = encodedPacket.charAt(0);\n    if (type === \"b\") {\n        return {\n            type: \"message\",\n            data: decodeBase64Packet(encodedPacket.substring(1), binaryType),\n        };\n    }\n    const packetType = commons_js_1.PACKET_TYPES_REVERSE[type];\n    if (!packetType) {\n        return commons_js_1.ERROR_PACKET;\n    }\n    return encodedPacket.length > 1\n        ? {\n            type: commons_js_1.PACKET_TYPES_REVERSE[type],\n            data: encodedPacket.substring(1),\n        }\n        : {\n            type: commons_js_1.PACKET_TYPES_REVERSE[type],\n        };\n};\nexports.decodePacket = decodePacket;\nconst decodeBase64Packet = (data, binaryType) => {\n    if (withNativeArrayBuffer) {\n        const decoded = (0, base64_arraybuffer_js_1.decode)(data);\n        return mapBinary(decoded, binaryType);\n    }\n    else {\n        return { base64: true, data }; // fallback for old browsers\n    }\n};\nconst mapBinary = (data, binaryType) => {\n    switch (binaryType) {\n        case \"blob\":\n            if (data instanceof Blob) {\n                // from WebSocket + binaryType \"blob\"\n                return data;\n            }\n            else {\n                // from HTTP long-polling or WebTransport\n                return new Blob([data]);\n            }\n        case \"arraybuffer\":\n        default:\n            if (data instanceof ArrayBuffer) {\n                // from HTTP long-polling (base64) or WebSocket + binaryType \"arraybuffer\"\n                return data;\n            }\n            else {\n                // from WebTransport (Uint8Array)\n                return data.buffer;\n            }\n    }\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decodePayload = exports.decodePacket = exports.encodePayload = exports.encodePacket = exports.protocol = void 0;\nexports.createPacketEncoderStream = createPacketEncoderStream;\nexports.createPacketDecoderStream = createPacketDecoderStream;\nconst encodePacket_js_1 = require(\"./encodePacket.js\");\nObject.defineProperty(exports, \"encodePacket\", { enumerable: true, get: function () { return encodePacket_js_1.encodePacket; } });\nconst decodePacket_js_1 = require(\"./decodePacket.js\");\nObject.defineProperty(exports, \"decodePacket\", { enumerable: true, get: function () { return decodePacket_js_1.decodePacket; } });\nconst commons_js_1 = require(\"./commons.js\");\nconst SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text\nconst encodePayload = (packets, callback) => {\n    // some packets may be added to the array while encoding, so the initial length must be saved\n    const length = packets.length;\n    const encodedPackets = new Array(length);\n    let count = 0;\n    packets.forEach((packet, i) => {\n        // force base64 encoding for binary packets\n        (0, encodePacket_js_1.encodePacket)(packet, false, (encodedPacket) => {\n            encodedPackets[i] = encodedPacket;\n            if (++count === length) {\n                callback(encodedPackets.join(SEPARATOR));\n            }\n        });\n    });\n};\nexports.encodePayload = encodePayload;\nconst decodePayload = (encodedPayload, binaryType) => {\n    const encodedPackets = encodedPayload.split(SEPARATOR);\n    const packets = [];\n    for (let i = 0; i < encodedPackets.length; i++) {\n        const decodedPacket = (0, decodePacket_js_1.decodePacket)(encodedPackets[i], binaryType);\n        packets.push(decodedPacket);\n        if (decodedPacket.type === \"error\") {\n            break;\n        }\n    }\n    return packets;\n};\nexports.decodePayload = decodePayload;\nfunction createPacketEncoderStream() {\n    return new TransformStream({\n        transform(packet, controller) {\n            (0, encodePacket_js_1.encodePacketToBinary)(packet, (encodedPacket) => {\n                const payloadLength = encodedPacket.length;\n                let header;\n                // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length\n                if (payloadLength < 126) {\n                    header = new Uint8Array(1);\n                    new DataView(header.buffer).setUint8(0, payloadLength);\n                }\n                else if (payloadLength < 65536) {\n                    header = new Uint8Array(3);\n                    const view = new DataView(header.buffer);\n                    view.setUint8(0, 126);\n                    view.setUint16(1, payloadLength);\n                }\n                else {\n                    header = new Uint8Array(9);\n                    const view = new DataView(header.buffer);\n                    view.setUint8(0, 127);\n                    view.setBigUint64(1, BigInt(payloadLength));\n                }\n                // first bit indicates whether the payload is plain text (0) or binary (1)\n                if (packet.data && typeof packet.data !== \"string\") {\n                    header[0] |= 0x80;\n                }\n                controller.enqueue(header);\n                controller.enqueue(encodedPacket);\n            });\n        },\n    });\n}\nlet TEXT_DECODER;\nfunction totalLength(chunks) {\n    return chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n}\nfunction concatChunks(chunks, size) {\n    if (chunks[0].length === size) {\n        return chunks.shift();\n    }\n    const buffer = new Uint8Array(size);\n    let j = 0;\n    for (let i = 0; i < size; i++) {\n        buffer[i] = chunks[0][j++];\n        if (j === chunks[0].length) {\n            chunks.shift();\n            j = 0;\n        }\n    }\n    if (chunks.length && j < chunks[0].length) {\n        chunks[0] = chunks[0].slice(j);\n    }\n    return buffer;\n}\nfunction createPacketDecoderStream(maxPayload, binaryType) {\n    if (!TEXT_DECODER) {\n        TEXT_DECODER = new TextDecoder();\n    }\n    const chunks = [];\n    let state = 0 /* State.READ_HEADER */;\n    let expectedLength = -1;\n    let isBinary = false;\n    return new TransformStream({\n        transform(chunk, controller) {\n            chunks.push(chunk);\n            while (true) {\n                if (state === 0 /* State.READ_HEADER */) {\n                    if (totalLength(chunks) < 1) {\n                        break;\n                    }\n                    const header = concatChunks(chunks, 1);\n                    isBinary = (header[0] & 0x80) === 0x80;\n                    expectedLength = header[0] & 0x7f;\n                    if (expectedLength < 126) {\n                        state = 3 /* State.READ_PAYLOAD */;\n                    }\n                    else if (expectedLength === 126) {\n                        state = 1 /* State.READ_EXTENDED_LENGTH_16 */;\n                    }\n                    else {\n                        state = 2 /* State.READ_EXTENDED_LENGTH_64 */;\n                    }\n                }\n                else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {\n                    if (totalLength(chunks) < 2) {\n                        break;\n                    }\n                    const headerArray = concatChunks(chunks, 2);\n                    expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);\n                    state = 3 /* State.READ_PAYLOAD */;\n                }\n                else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {\n                    if (totalLength(chunks) < 8) {\n                        break;\n                    }\n                    const headerArray = concatChunks(chunks, 8);\n                    const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);\n                    const n = view.getUint32(0);\n                    if (n > Math.pow(2, 53 - 32) - 1) {\n                        // the maximum safe integer in JavaScript is 2^53 - 1\n                        controller.enqueue(commons_js_1.ERROR_PACKET);\n                        break;\n                    }\n                    expectedLength = n * Math.pow(2, 32) + view.getUint32(4);\n                    state = 3 /* State.READ_PAYLOAD */;\n                }\n                else {\n                    if (totalLength(chunks) < expectedLength) {\n                        break;\n                    }\n                    const data = concatChunks(chunks, expectedLength);\n                    controller.enqueue((0, decodePacket_js_1.decodePacket)(isBinary ? data : TEXT_DECODER.decode(data), binaryType));\n                    state = 0 /* State.READ_HEADER */;\n                }\n                if (expectedLength === 0 || expectedLength > maxPayload) {\n                    controller.enqueue(commons_js_1.ERROR_PACKET);\n                    break;\n                }\n            }\n        },\n    });\n}\nexports.protocol = 4;\n", "\n/**\n * Expose `Emitter`.\n */\n\nexports.Emitter = Emitter;\n\n/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nfunction Emitter(obj) {\n  if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n  for (var key in Emitter.prototype) {\n    obj[key] = Emitter.prototype[key];\n  }\n  return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n  this._callbacks = this._callbacks || {};\n  (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\n    .push(fn);\n  return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n  function on() {\n    this.off(event, on);\n    fn.apply(this, arguments);\n  }\n\n  on.fn = fn;\n  this.on(event, on);\n  return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n  this._callbacks = this._callbacks || {};\n\n  // all\n  if (0 == arguments.length) {\n    this._callbacks = {};\n    return this;\n  }\n\n  // specific event\n  var callbacks = this._callbacks['$' + event];\n  if (!callbacks) return this;\n\n  // remove all handlers\n  if (1 == arguments.length) {\n    delete this._callbacks['$' + event];\n    return this;\n  }\n\n  // remove specific handler\n  var cb;\n  for (var i = 0; i < callbacks.length; i++) {\n    cb = callbacks[i];\n    if (cb === fn || cb.fn === fn) {\n      callbacks.splice(i, 1);\n      break;\n    }\n  }\n\n  // Remove event specific arrays for event types that no\n  // one is subscribed for to avoid memory leak.\n  if (callbacks.length === 0) {\n    delete this._callbacks['$' + event];\n  }\n\n  return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n  this._callbacks = this._callbacks || {};\n\n  var args = new Array(arguments.length - 1)\n    , callbacks = this._callbacks['$' + event];\n\n  for (var i = 1; i < arguments.length; i++) {\n    args[i - 1] = arguments[i];\n  }\n\n  if (callbacks) {\n    callbacks = callbacks.slice(0);\n    for (var i = 0, len = callbacks.length; i < len; ++i) {\n      callbacks[i].apply(this, args);\n    }\n  }\n\n  return this;\n};\n\n// alias used for reserved events (protected method)\nEmitter.prototype.emitReserved = Emitter.prototype.emit;\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n  this._callbacks = this._callbacks || {};\n  return this._callbacks['$' + event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n  return !! this.listeners(event).length;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultBinaryType = exports.globalThisShim = exports.nextTick = void 0;\nexports.createCookieJar = createCookieJar;\nexports.nextTick = (() => {\n    const isPromiseAvailable = typeof Promise === \"function\" && typeof Promise.resolve === \"function\";\n    if (isPromiseAvailable) {\n        return (cb) => Promise.resolve().then(cb);\n    }\n    else {\n        return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);\n    }\n})();\nexports.globalThisShim = (() => {\n    if (typeof self !== \"undefined\") {\n        return self;\n    }\n    else if (typeof window !== \"undefined\") {\n        return window;\n    }\n    else {\n        return Function(\"return this\")();\n    }\n})();\nexports.defaultBinaryType = \"arraybuffer\";\nfunction createCookieJar() { }\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.pick = pick;\nexports.installTimerFunctions = installTimerFunctions;\nexports.byteLength = byteLength;\nexports.randomString = randomString;\nconst globals_node_js_1 = require(\"./globals.node.js\");\nfunction pick(obj, ...attr) {\n    return attr.reduce((acc, k) => {\n        if (obj.hasOwnProperty(k)) {\n            acc[k] = obj[k];\n        }\n        return acc;\n    }, {});\n}\n// Keep a reference to the real timeout functions so they can be used when overridden\nconst NATIVE_SET_TIMEOUT = globals_node_js_1.globalThisShim.setTimeout;\nconst NATIVE_CLEAR_TIMEOUT = globals_node_js_1.globalThisShim.clearTimeout;\nfunction installTimerFunctions(obj, opts) {\n    if (opts.useNativeTimers) {\n        obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globals_node_js_1.globalThisShim);\n        obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globals_node_js_1.globalThisShim);\n    }\n    else {\n        obj.setTimeoutFn = globals_node_js_1.globalThisShim.setTimeout.bind(globals_node_js_1.globalThisShim);\n        obj.clearTimeoutFn = globals_node_js_1.globalThisShim.clearTimeout.bind(globals_node_js_1.globalThisShim);\n    }\n}\n// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)\nconst BASE64_OVERHEAD = 1.33;\n// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9\nfunction byteLength(obj) {\n    if (typeof obj === \"string\") {\n        return utf8Length(obj);\n    }\n    // arraybuffer or blob\n    return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);\n}\nfunction utf8Length(str) {\n    let c = 0, length = 0;\n    for (let i = 0, l = str.length; i < l; i++) {\n        c = str.charCodeAt(i);\n        if (c < 0x80) {\n            length += 1;\n        }\n        else if (c < 0x800) {\n            length += 2;\n        }\n        else if (c < 0xd800 || c >= 0xe000) {\n            length += 3;\n        }\n        else {\n            i++;\n            length += 4;\n        }\n    }\n    return length;\n}\n/**\n * Generates a random 8-characters string.\n */\nfunction randomString() {\n    return (Date.now().toString(36).substring(3) +\n        Math.random().toString(36).substring(2, 5));\n}\n", "\"use strict\";\n// imported from https://github.com/galkn/querystring\n/**\n * Compiles a querystring\n * Returns string representation of the object\n *\n * @param {Object}\n * @api private\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.encode = encode;\nexports.decode = decode;\nfunction encode(obj) {\n    let str = '';\n    for (let i in obj) {\n        if (obj.hasOwnProperty(i)) {\n            if (str.length)\n                str += '&';\n            str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);\n        }\n    }\n    return str;\n}\n/**\n * Parses a simple querystring into an object\n *\n * @param {String} qs\n * @api private\n */\nfunction decode(qs) {\n    let qry = {};\n    let pairs = qs.split('&');\n    for (let i = 0, l = pairs.length; i < l; i++) {\n        let pair = pairs[i].split('=');\n        qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);\n    }\n    return qry;\n}\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n *  - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n  options = options || {};\n  var type = typeof val;\n  if (type === 'string' && val.length > 0) {\n    return parse(val);\n  } else if (type === 'number' && isFinite(val)) {\n    return options.long ? fmtLong(val) : fmtShort(val);\n  }\n  throw new Error(\n    'val is not a non-empty string or a valid number. val=' +\n      JSON.stringify(val)\n  );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n  str = String(str);\n  if (str.length > 100) {\n    return;\n  }\n  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(\n    str\n  );\n  if (!match) {\n    return;\n  }\n  var n = parseFloat(match[1]);\n  var type = (match[2] || 'ms').toLowerCase();\n  switch (type) {\n    case 'years':\n    case 'year':\n    case 'yrs':\n    case 'yr':\n    case 'y':\n      return n * y;\n    case 'weeks':\n    case 'week':\n    case 'w':\n      return n * w;\n    case 'days':\n    case 'day':\n    case 'd':\n      return n * d;\n    case 'hours':\n    case 'hour':\n    case 'hrs':\n    case 'hr':\n    case 'h':\n      return n * h;\n    case 'minutes':\n    case 'minute':\n    case 'mins':\n    case 'min':\n    case 'm':\n      return n * m;\n    case 'seconds':\n    case 'second':\n    case 'secs':\n    case 'sec':\n    case 's':\n      return n * s;\n    case 'milliseconds':\n    case 'millisecond':\n    case 'msecs':\n    case 'msec':\n    case 'ms':\n      return n;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n  var msAbs = Math.abs(ms);\n  if (msAbs >= d) {\n    return Math.round(ms / d) + 'd';\n  }\n  if (msAbs >= h) {\n    return Math.round(ms / h) + 'h';\n  }\n  if (msAbs >= m) {\n    return Math.round(ms / m) + 'm';\n  }\n  if (msAbs >= s) {\n    return Math.round(ms / s) + 's';\n  }\n  return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n  var msAbs = Math.abs(ms);\n  if (msAbs >= d) {\n    return plural(ms, msAbs, d, 'day');\n  }\n  if (msAbs >= h) {\n    return plural(ms, msAbs, h, 'hour');\n  }\n  if (msAbs >= m) {\n    return plural(ms, msAbs, m, 'minute');\n  }\n  if (msAbs >= s) {\n    return plural(ms, msAbs, s, 'second');\n  }\n  return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n  var isPlural = msAbs >= n * 1.5;\n  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Transport = exports.TransportError = void 0;\nconst engine_io_parser_1 = require(\"engine.io-parser\");\nconst component_emitter_1 = require(\"@socket.io/component-emitter\");\nconst util_js_1 = require(\"./util.js\");\nconst parseqs_js_1 = require(\"./contrib/parseqs.js\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"engine.io-client:transport\"); // debug()\nclass TransportError extends Error {\n    constructor(reason, description, context) {\n        super(reason);\n        this.description = description;\n        this.context = context;\n        this.type = \"TransportError\";\n    }\n}\nexports.TransportError = TransportError;\nclass Transport extends component_emitter_1.Emitter {\n    /**\n     * Transport abstract constructor.\n     *\n     * @param {Object} opts - options\n     * @protected\n     */\n    constructor(opts) {\n        super();\n        this.writable = false;\n        (0, util_js_1.installTimerFunctions)(this, opts);\n        this.opts = opts;\n        this.query = opts.query;\n        this.socket = opts.socket;\n        this.supportsBinary = !opts.forceBase64;\n    }\n    /**\n     * Emits an error.\n     *\n     * @param {String} reason\n     * @param description\n     * @param context - the error context\n     * @return {Transport} for chaining\n     * @protected\n     */\n    onError(reason, description, context) {\n        super.emitReserved(\"error\", new TransportError(reason, description, context));\n        return this;\n    }\n    /**\n     * Opens the transport.\n     */\n    open() {\n        this.readyState = \"opening\";\n        this.doOpen();\n        return this;\n    }\n    /**\n     * Closes the transport.\n     */\n    close() {\n        if (this.readyState === \"opening\" || this.readyState === \"open\") {\n            this.doClose();\n            this.onClose();\n        }\n        return this;\n    }\n    /**\n     * Sends multiple packets.\n     *\n     * @param {Array} packets\n     */\n    send(packets) {\n        if (this.readyState === \"open\") {\n            this.write(packets);\n        }\n        else {\n            // this might happen if the transport was silently closed in the beforeunload event handler\n            debug(\"transport is not open, discarding packets\");\n        }\n    }\n    /**\n     * Called upon open\n     *\n     * @protected\n     */\n    onOpen() {\n        this.readyState = \"open\";\n        this.writable = true;\n        super.emitReserved(\"open\");\n    }\n    /**\n     * Called with data.\n     *\n     * @param {String} data\n     * @protected\n     */\n    onData(data) {\n        const packet = (0, engine_io_parser_1.decodePacket)(data, this.socket.binaryType);\n        this.onPacket(packet);\n    }\n    /**\n     * Called with a decoded packet.\n     *\n     * @protected\n     */\n    onPacket(packet) {\n        super.emitReserved(\"packet\", packet);\n    }\n    /**\n     * Called upon close.\n     *\n     * @protected\n     */\n    onClose(details) {\n        this.readyState = \"closed\";\n        super.emitReserved(\"close\", details);\n    }\n    /**\n     * Pauses the transport, in order not to lose packets during an upgrade.\n     *\n     * @param onPause\n     */\n    pause(onPause) { }\n    createUri(schema, query = {}) {\n        return (schema +\n            \"://\" +\n            this._hostname() +\n            this._port() +\n            this.opts.path +\n            this._query(query));\n    }\n    _hostname() {\n        const hostname = this.opts.hostname;\n        return hostname.indexOf(\":\") === -1 ? hostname : \"[\" + hostname + \"]\";\n    }\n    _port() {\n        if (this.opts.port &&\n            ((this.opts.secure && Number(this.opts.port) !== 443) ||\n                (!this.opts.secure && Number(this.opts.port) !== 80))) {\n            return \":\" + this.opts.port;\n        }\n        else {\n            return \"\";\n        }\n    }\n    _query(query) {\n        const encodedQuery = (0, parseqs_js_1.encode)(query);\n        return encodedQuery.length ? \"?\" + encodedQuery : \"\";\n    }\n}\nexports.Transport = Transport;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Polling = void 0;\nconst transport_js_1 = require(\"../transport.js\");\nconst util_js_1 = require(\"../util.js\");\nconst engine_io_parser_1 = require(\"engine.io-parser\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"engine.io-client:polling\"); // debug()\nclass Polling extends transport_js_1.Transport {\n    constructor() {\n        super(...arguments);\n        this._polling = false;\n    }\n    get name() {\n        return \"polling\";\n    }\n    /**\n     * Opens the socket (triggers polling). We write a PING message to determine\n     * when the transport is open.\n     *\n     * @protected\n     */\n    doOpen() {\n        this._poll();\n    }\n    /**\n     * Pauses polling.\n     *\n     * @param {Function} onPause - callback upon buffers are flushed and transport is paused\n     * @package\n     */\n    pause(onPause) {\n        this.readyState = \"pausing\";\n        const pause = () => {\n            debug(\"paused\");\n            this.readyState = \"paused\";\n            onPause();\n        };\n        if (this._polling || !this.writable) {\n            let total = 0;\n            if (this._polling) {\n                debug(\"we are currently polling - waiting to pause\");\n                total++;\n                this.once(\"pollComplete\", function () {\n                    debug(\"pre-pause polling complete\");\n                    --total || pause();\n                });\n            }\n            if (!this.writable) {\n                debug(\"we are currently writing - waiting to pause\");\n                total++;\n                this.once(\"drain\", function () {\n                    debug(\"pre-pause writing complete\");\n                    --total || pause();\n                });\n            }\n        }\n        else {\n            pause();\n        }\n    }\n    /**\n     * Starts polling cycle.\n     *\n     * @private\n     */\n    _poll() {\n        debug(\"polling\");\n        this._polling = true;\n        this.doPoll();\n        this.emitReserved(\"poll\");\n    }\n    /**\n     * Overloads onData to detect payloads.\n     *\n     * @protected\n     */\n    onData(data) {\n        debug(\"polling got data %s\", data);\n        const callback = (packet) => {\n            // if its the first message we consider the transport open\n            if (\"opening\" === this.readyState && packet.type === \"open\") {\n                this.onOpen();\n            }\n            // if its a close packet, we close the ongoing requests\n            if (\"close\" === packet.type) {\n                this.onClose({ description: \"transport closed by the server\" });\n                return false;\n            }\n            // otherwise bypass onData and handle the message\n            this.onPacket(packet);\n        };\n        // decode payload\n        (0, engine_io_parser_1.decodePayload)(data, this.socket.binaryType).forEach(callback);\n        // if an event did not trigger closing\n        if (\"closed\" !== this.readyState) {\n            // if we got data we're not polling\n            this._polling = false;\n            this.emitReserved(\"pollComplete\");\n            if (\"open\" === this.readyState) {\n                this._poll();\n            }\n            else {\n                debug('ignoring poll - transport state \"%s\"', this.readyState);\n            }\n        }\n    }\n    /**\n     * For polling, send a close packet.\n     *\n     * @protected\n     */\n    doClose() {\n        const close = () => {\n            debug(\"writing close packet\");\n            this.write([{ type: \"close\" }]);\n        };\n        if (\"open\" === this.readyState) {\n            debug(\"transport open - closing\");\n            close();\n        }\n        else {\n            // in case we're trying to close while\n            // handshaking is in progress (GH-164)\n            debug(\"transport not open - deferring close\");\n            this.once(\"open\", close);\n        }\n    }\n    /**\n     * Writes a packets payload.\n     *\n     * @param {Array} packets - data packets\n     * @protected\n     */\n    write(packets) {\n        this.writable = false;\n        (0, engine_io_parser_1.encodePayload)(packets, (data) => {\n            this.doWrite(data, () => {\n                this.writable = true;\n                this.emitReserved(\"drain\");\n            });\n        });\n    }\n    /**\n     * Generates uri for connection.\n     *\n     * @private\n     */\n    uri() {\n        const schema = this.opts.secure ? \"https\" : \"http\";\n        const query = this.query || {};\n        // cache busting is forced\n        if (false !== this.opts.timestampRequests) {\n            query[this.opts.timestampParam] = (0, util_js_1.randomString)();\n        }\n        if (!this.supportsBinary && !query.sid) {\n            query.b64 = 1;\n        }\n        return this.createUri(schema, query);\n    }\n}\nexports.Polling = Polling;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hasCORS = void 0;\n// imported from https://github.com/component/has-cors\nlet value = false;\ntry {\n    value = typeof XMLHttpRequest !== 'undefined' &&\n        'withCredentials' in new XMLHttpRequest();\n}\ncatch (err) {\n    // if XMLHttp support is disabled in IE then it will throw\n    // when trying to create\n}\nexports.hasCORS = value;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.XHR = exports.Request = exports.BaseXHR = void 0;\nconst polling_js_1 = require(\"./polling.js\");\nconst component_emitter_1 = require(\"@socket.io/component-emitter\");\nconst util_js_1 = require(\"../util.js\");\nconst globals_node_js_1 = require(\"../globals.node.js\");\nconst has_cors_js_1 = require(\"../contrib/has-cors.js\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"engine.io-client:polling\"); // debug()\nfunction empty() { }\nclass BaseXHR extends polling_js_1.Polling {\n    /**\n     * XHR Polling constructor.\n     *\n     * @param {Object} opts\n     * @package\n     */\n    constructor(opts) {\n        super(opts);\n        if (typeof location !== \"undefined\") {\n            const isSSL = \"https:\" === location.protocol;\n            let port = location.port;\n            // some user agents have empty `location.port`\n            if (!port) {\n                port = isSSL ? \"443\" : \"80\";\n            }\n            this.xd =\n                (typeof location !== \"undefined\" &&\n                    opts.hostname !== location.hostname) ||\n                    port !== opts.port;\n        }\n    }\n    /**\n     * Sends data.\n     *\n     * @param {String} data - data to send.\n     * @param {Function} fn - called upon flush.\n     * @private\n     */\n    doWrite(data, fn) {\n        const req = this.request({\n            method: \"POST\",\n            data: data,\n        });\n        req.on(\"success\", fn);\n        req.on(\"error\", (xhrStatus, context) => {\n            this.onError(\"xhr post error\", xhrStatus, context);\n        });\n    }\n    /**\n     * Starts a poll cycle.\n     *\n     * @private\n     */\n    doPoll() {\n        debug(\"xhr poll\");\n        const req = this.request();\n        req.on(\"data\", this.onData.bind(this));\n        req.on(\"error\", (xhrStatus, context) => {\n            this.onError(\"xhr poll error\", xhrStatus, context);\n        });\n        this.pollXhr = req;\n    }\n}\nexports.BaseXHR = BaseXHR;\nclass Request extends component_emitter_1.Emitter {\n    /**\n     * Request constructor\n     *\n     * @param {Object} options\n     * @package\n     */\n    constructor(createRequest, uri, opts) {\n        super();\n        this.createRequest = createRequest;\n        (0, util_js_1.installTimerFunctions)(this, opts);\n        this._opts = opts;\n        this._method = opts.method || \"GET\";\n        this._uri = uri;\n        this._data = undefined !== opts.data ? opts.data : null;\n        this._create();\n    }\n    /**\n     * Creates the XHR object and sends the request.\n     *\n     * @private\n     */\n    _create() {\n        var _a;\n        const opts = (0, util_js_1.pick)(this._opts, \"agent\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"autoUnref\");\n        opts.xdomain = !!this._opts.xd;\n        const xhr = (this._xhr = this.createRequest(opts));\n        try {\n            debug(\"xhr open %s: %s\", this._method, this._uri);\n            xhr.open(this._method, this._uri, true);\n            try {\n                if (this._opts.extraHeaders) {\n                    // @ts-ignore\n                    xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);\n                    for (let i in this._opts.extraHeaders) {\n                        if (this._opts.extraHeaders.hasOwnProperty(i)) {\n                            xhr.setRequestHeader(i, this._opts.extraHeaders[i]);\n                        }\n                    }\n                }\n            }\n            catch (e) { }\n            if (\"POST\" === this._method) {\n                try {\n                    xhr.setRequestHeader(\"Content-type\", \"text/plain;charset=UTF-8\");\n                }\n                catch (e) { }\n            }\n            try {\n                xhr.setRequestHeader(\"Accept\", \"*/*\");\n            }\n            catch (e) { }\n            (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);\n            // ie6 check\n            if (\"withCredentials\" in xhr) {\n                xhr.withCredentials = this._opts.withCredentials;\n            }\n            if (this._opts.requestTimeout) {\n                xhr.timeout = this._opts.requestTimeout;\n            }\n            xhr.onreadystatechange = () => {\n                var _a;\n                if (xhr.readyState === 3) {\n                    (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(\n                    // @ts-ignore\n                    xhr.getResponseHeader(\"set-cookie\"));\n                }\n                if (4 !== xhr.readyState)\n                    return;\n                if (200 === xhr.status || 1223 === xhr.status) {\n                    this._onLoad();\n                }\n                else {\n                    // make sure the `error` event handler that's user-set\n                    // does not throw in the same tick and gets caught here\n                    this.setTimeoutFn(() => {\n                        this._onError(typeof xhr.status === \"number\" ? xhr.status : 0);\n                    }, 0);\n                }\n            };\n            debug(\"xhr data %s\", this._data);\n            xhr.send(this._data);\n        }\n        catch (e) {\n            // Need to defer since .create() is called directly from the constructor\n            // and thus the 'error' event can only be only bound *after* this exception\n            // occurs.  Therefore, also, we cannot throw here at all.\n            this.setTimeoutFn(() => {\n                this._onError(e);\n            }, 0);\n            return;\n        }\n        if (typeof document !== \"undefined\") {\n            this._index = Request.requestsCount++;\n            Request.requests[this._index] = this;\n        }\n    }\n    /**\n     * Called upon error.\n     *\n     * @private\n     */\n    _onError(err) {\n        this.emitReserved(\"error\", err, this._xhr);\n        this._cleanup(true);\n    }\n    /**\n     * Cleans up house.\n     *\n     * @private\n     */\n    _cleanup(fromError) {\n        if (\"undefined\" === typeof this._xhr || null === this._xhr) {\n            return;\n        }\n        this._xhr.onreadystatechange = empty;\n        if (fromError) {\n            try {\n                this._xhr.abort();\n            }\n            catch (e) { }\n        }\n        if (typeof document !== \"undefined\") {\n            delete Request.requests[this._index];\n        }\n        this._xhr = null;\n    }\n    /**\n     * Called upon load.\n     *\n     * @private\n     */\n    _onLoad() {\n        const data = this._xhr.responseText;\n        if (data !== null) {\n            this.emitReserved(\"data\", data);\n            this.emitReserved(\"success\");\n            this._cleanup();\n        }\n    }\n    /**\n     * Aborts the request.\n     *\n     * @package\n     */\n    abort() {\n        this._cleanup();\n    }\n}\nexports.Request = Request;\nRequest.requestsCount = 0;\nRequest.requests = {};\n/**\n * Aborts pending requests when unloading the window. This is needed to prevent\n * memory leaks (e.g. when using IE) and to ensure that no spurious error is\n * emitted.\n */\nif (typeof document !== \"undefined\") {\n    // @ts-ignore\n    if (typeof attachEvent === \"function\") {\n        // @ts-ignore\n        attachEvent(\"onunload\", unloadHandler);\n    }\n    else if (typeof addEventListener === \"function\") {\n        const terminationEvent = \"onpagehide\" in globals_node_js_1.globalThisShim ? \"pagehide\" : \"unload\";\n        addEventListener(terminationEvent, unloadHandler, false);\n    }\n}\nfunction unloadHandler() {\n    for (let i in Request.requests) {\n        if (Request.requests.hasOwnProperty(i)) {\n            Request.requests[i].abort();\n        }\n    }\n}\nconst hasXHR2 = (function () {\n    const xhr = newRequest({\n        xdomain: false,\n    });\n    return xhr && xhr.responseType !== null;\n})();\n/**\n * HTTP long-polling based on the built-in `XMLHttpRequest` object.\n *\n * Usage: browser\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\n */\nclass XHR extends BaseXHR {\n    constructor(opts) {\n        super(opts);\n        const forceBase64 = opts && opts.forceBase64;\n        this.supportsBinary = hasXHR2 && !forceBase64;\n    }\n    request(opts = {}) {\n        Object.assign(opts, { xd: this.xd }, this.opts);\n        return new Request(newRequest, this.uri(), opts);\n    }\n}\nexports.XHR = XHR;\nfunction newRequest(opts) {\n    const xdomain = opts.xdomain;\n    // XMLHttpRequest can be disabled on IE\n    try {\n        if (\"undefined\" !== typeof XMLHttpRequest && (!xdomain || has_cors_js_1.hasCORS)) {\n            return new XMLHttpRequest();\n        }\n    }\n    catch (e) { }\n    if (!xdomain) {\n        try {\n            return new globals_node_js_1.globalThisShim[[\"Active\"].concat(\"Object\").join(\"X\")](\"Microsoft.XMLHTTP\");\n        }\n        catch (e) { }\n    }\n}\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WS = exports.BaseWS = void 0;\nconst transport_js_1 = require(\"../transport.js\");\nconst util_js_1 = require(\"../util.js\");\nconst engine_io_parser_1 = require(\"engine.io-parser\");\nconst globals_node_js_1 = require(\"../globals.node.js\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"engine.io-client:websocket\"); // debug()\n// detect ReactNative environment\nconst isReactNative = typeof navigator !== \"undefined\" &&\n    typeof navigator.product === \"string\" &&\n    navigator.product.toLowerCase() === \"reactnative\";\nclass BaseWS extends transport_js_1.Transport {\n    get name() {\n        return \"websocket\";\n    }\n    doOpen() {\n        const uri = this.uri();\n        const protocols = this.opts.protocols;\n        // React Native only supports the 'headers' option, and will print a warning if anything else is passed\n        const opts = isReactNative\n            ? {}\n            : (0, util_js_1.pick)(this.opts, \"agent\", \"perMessageDeflate\", \"pfx\", \"key\", \"passphrase\", \"cert\", \"ca\", \"ciphers\", \"rejectUnauthorized\", \"localAddress\", \"protocolVersion\", \"origin\", \"maxPayload\", \"family\", \"checkServerIdentity\");\n        if (this.opts.extraHeaders) {\n            opts.headers = this.opts.extraHeaders;\n        }\n        try {\n            this.ws = this.createSocket(uri, protocols, opts);\n        }\n        catch (err) {\n            return this.emitReserved(\"error\", err);\n        }\n        this.ws.binaryType = this.socket.binaryType;\n        this.addEventListeners();\n    }\n    /**\n     * Adds event listeners to the socket\n     *\n     * @private\n     */\n    addEventListeners() {\n        this.ws.onopen = () => {\n            if (this.opts.autoUnref) {\n                this.ws._socket.unref();\n            }\n            this.onOpen();\n        };\n        this.ws.onclose = (closeEvent) => this.onClose({\n            description: \"websocket connection closed\",\n            context: closeEvent,\n        });\n        this.ws.onmessage = (ev) => this.onData(ev.data);\n        this.ws.onerror = (e) => this.onError(\"websocket error\", e);\n    }\n    write(packets) {\n        this.writable = false;\n        // encodePacket efficient as it uses WS framing\n        // no need for encodePayload\n        for (let i = 0; i < packets.length; i++) {\n            const packet = packets[i];\n            const lastPacket = i === packets.length - 1;\n            (0, engine_io_parser_1.encodePacket)(packet, this.supportsBinary, (data) => {\n                // Sometimes the websocket has already been closed but the browser didn't\n                // have a chance of informing us about it yet, in that case send will\n                // throw an error\n                try {\n                    this.doWrite(packet, data);\n                }\n                catch (e) {\n                    debug(\"websocket closed before onclose event\");\n                }\n                if (lastPacket) {\n                    // fake drain\n                    // defer to next tick to allow Socket to clear writeBuffer\n                    (0, globals_node_js_1.nextTick)(() => {\n                        this.writable = true;\n                        this.emitReserved(\"drain\");\n                    }, this.setTimeoutFn);\n                }\n            });\n        }\n    }\n    doClose() {\n        if (typeof this.ws !== \"undefined\") {\n            this.ws.onerror = () => { };\n            this.ws.close();\n            this.ws = null;\n        }\n    }\n    /**\n     * Generates uri for connection.\n     *\n     * @private\n     */\n    uri() {\n        const schema = this.opts.secure ? \"wss\" : \"ws\";\n        const query = this.query || {};\n        // append timestamp to URI\n        if (this.opts.timestampRequests) {\n            query[this.opts.timestampParam] = (0, util_js_1.randomString)();\n        }\n        // communicate binary support capabilities\n        if (!this.supportsBinary) {\n            query.b64 = 1;\n        }\n        return this.createUri(schema, query);\n    }\n}\nexports.BaseWS = BaseWS;\nconst WebSocketCtor = globals_node_js_1.globalThisShim.WebSocket || globals_node_js_1.globalThisShim.MozWebSocket;\n/**\n * WebSocket transport based on the built-in `WebSocket` object.\n *\n * Usage: browser, Node.js (since v21), Deno, Bun\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket\n * @see https://caniuse.com/mdn-api_websocket\n * @see https://nodejs.org/api/globals.html#websocket\n */\nclass WS extends BaseWS {\n    createSocket(uri, protocols, opts) {\n        return !isReactNative\n            ? protocols\n                ? new WebSocketCtor(uri, protocols)\n                : new WebSocketCtor(uri)\n            : new WebSocketCtor(uri, protocols, opts);\n    }\n    doWrite(_packet, data) {\n        this.ws.send(data);\n    }\n}\nexports.WS = WS;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WT = void 0;\nconst transport_js_1 = require(\"../transport.js\");\nconst globals_node_js_1 = require(\"../globals.node.js\");\nconst engine_io_parser_1 = require(\"engine.io-parser\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"engine.io-client:webtransport\"); // debug()\n/**\n * WebTransport transport based on the built-in `WebTransport` object.\n *\n * Usage: browser, Node.js (with the `@fails-components/webtransport` package)\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport\n * @see https://caniuse.com/webtransport\n */\nclass WT extends transport_js_1.Transport {\n    get name() {\n        return \"webtransport\";\n    }\n    doOpen() {\n        try {\n            // @ts-ignore\n            this._transport = new WebTransport(this.createUri(\"https\"), this.opts.transportOptions[this.name]);\n        }\n        catch (err) {\n            return this.emitReserved(\"error\", err);\n        }\n        this._transport.closed\n            .then(() => {\n            debug(\"transport closed gracefully\");\n            this.onClose();\n        })\n            .catch((err) => {\n            debug(\"transport closed due to %s\", err);\n            this.onError(\"webtransport error\", err);\n        });\n        // note: we could have used async/await, but that would require some additional polyfills\n        this._transport.ready.then(() => {\n            this._transport.createBidirectionalStream().then((stream) => {\n                const decoderStream = (0, engine_io_parser_1.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER, this.socket.binaryType);\n                const reader = stream.readable.pipeThrough(decoderStream).getReader();\n                const encoderStream = (0, engine_io_parser_1.createPacketEncoderStream)();\n                encoderStream.readable.pipeTo(stream.writable);\n                this._writer = encoderStream.writable.getWriter();\n                const read = () => {\n                    reader\n                        .read()\n                        .then(({ done, value }) => {\n                        if (done) {\n                            debug(\"session is closed\");\n                            return;\n                        }\n                        debug(\"received chunk: %o\", value);\n                        this.onPacket(value);\n                        read();\n                    })\n                        .catch((err) => {\n                        debug(\"an error occurred while reading: %s\", err);\n                    });\n                };\n                read();\n                const packet = { type: \"open\" };\n                if (this.query.sid) {\n                    packet.data = `{\"sid\":\"${this.query.sid}\"}`;\n                }\n                this._writer.write(packet).then(() => this.onOpen());\n            });\n        });\n    }\n    write(packets) {\n        this.writable = false;\n        for (let i = 0; i < packets.length; i++) {\n            const packet = packets[i];\n            const lastPacket = i === packets.length - 1;\n            this._writer.write(packet).then(() => {\n                if (lastPacket) {\n                    (0, globals_node_js_1.nextTick)(() => {\n                        this.writable = true;\n                        this.emitReserved(\"drain\");\n                    }, this.setTimeoutFn);\n                }\n            });\n        }\n    }\n    doClose() {\n        var _a;\n        (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();\n    }\n}\nexports.WT = WT;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.transports = void 0;\nconst polling_xhr_node_js_1 = require(\"./polling-xhr.node.js\");\nconst websocket_node_js_1 = require(\"./websocket.node.js\");\nconst webtransport_js_1 = require(\"./webtransport.js\");\nexports.transports = {\n    websocket: websocket_node_js_1.WS,\n    webtransport: webtransport_js_1.WT,\n    polling: polling_xhr_node_js_1.XHR,\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parse = parse;\n// imported from https://github.com/galkn/parseuri\n/**\n * Parses a URI\n *\n * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.\n *\n * See:\n * - https://developer.mozilla.org/en-US/docs/Web/API/URL\n * - https://caniuse.com/url\n * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B\n *\n * History of the parse() method:\n * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c\n * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3\n * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242\n *\n * @author Steven Levithan <stevenlevithan.com> (MIT license)\n * @api private\n */\nconst re = /^(?:(?![^:@\\/?#]+:[^:@\\/]*@)(http|https|ws|wss):\\/\\/)?((?:(([^:@\\/?#]*)(?::([^:@\\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\nconst parts = [\n    'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'\n];\nfunction parse(str) {\n    if (str.length > 8000) {\n        throw \"URI too long\";\n    }\n    const src = str, b = str.indexOf('['), e = str.indexOf(']');\n    if (b != -1 && e != -1) {\n        str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);\n    }\n    let m = re.exec(str || ''), uri = {}, i = 14;\n    while (i--) {\n        uri[parts[i]] = m[i] || '';\n    }\n    if (b != -1 && e != -1) {\n        uri.source = src;\n        uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');\n        uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');\n        uri.ipv6uri = true;\n    }\n    uri.pathNames = pathNames(uri, uri['path']);\n    uri.queryKey = queryKey(uri, uri['query']);\n    return uri;\n}\nfunction pathNames(obj, path) {\n    const regx = /\\/{2,9}/g, names = path.replace(regx, \"/\").split(\"/\");\n    if (path.slice(0, 1) == '/' || path.length === 0) {\n        names.splice(0, 1);\n    }\n    if (path.slice(-1) == '/') {\n        names.splice(names.length - 1, 1);\n    }\n    return names;\n}\nfunction queryKey(uri, query) {\n    const data = {};\n    query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {\n        if ($1) {\n            data[$1] = $2;\n        }\n    });\n    return data;\n}\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Socket = void 0;\nconst index_js_1 = require(\"./transports/index.js\");\nconst util_js_1 = require(\"./util.js\");\nconst parseqs_js_1 = require(\"./contrib/parseqs.js\");\nconst parseuri_js_1 = require(\"./contrib/parseuri.js\");\nconst component_emitter_1 = require(\"@socket.io/component-emitter\");\nconst engine_io_parser_1 = require(\"engine.io-parser\");\nconst globals_node_js_1 = require(\"./globals.node.js\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"engine.io-client:socket\"); // debug()\nconst withEventListeners = typeof addEventListener === \"function\" &&\n    typeof removeEventListener === \"function\";\nconst OFFLINE_EVENT_LISTENERS = [];\nif (withEventListeners) {\n    // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the\n    // script, so we create one single event listener here which will forward the event to the socket instances\n    addEventListener(\"offline\", () => {\n        debug(\"closing %d connection(s) because the network was lost\", OFFLINE_EVENT_LISTENERS.length);\n        OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());\n    }, false);\n}\n/**\n * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established\n * with one of the available low-level transports, like HTTP long-polling, WebSocket, or WebTransport.\n *\n * This class comes with an upgrade mechanism, which means that once the connection is established with the first\n * low-level transport, it will try to upgrade to a better transport.\n *\n * @example\n * import { Socket } from \"engine.io-client\";\n *\n * const socket = new Socket();\n *\n * socket.on(\"open\", () => {\n *   socket.send(\"hello\");\n * });\n *\n */\nclass Socket extends component_emitter_1.Emitter {\n    constructor(uri, opts = {}) {\n        var _a, _b;\n        super();\n        this.binaryType = globals_node_js_1.defaultBinaryType;\n        this.writeBuffer = [];\n        this._prevBufferLen = 0;\n        this._upgrades = [];\n        this._pingInterval = -1;\n        this._pingTimeout = -1;\n        this._maxPayload = -1;\n        /**\n         * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the\n         * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.\n         */\n        this._pingTimeoutTime = Infinity;\n        if (uri && \"object\" === typeof uri) {\n            opts = uri;\n            uri = null;\n        }\n        if (uri) {\n            const parsedUri = (0, parseuri_js_1.parse)(uri);\n            opts.hostname = parsedUri.host;\n            opts.secure =\n                parsedUri.protocol === \"https\" || parsedUri.protocol === \"wss\";\n            opts.port = parsedUri.port;\n            if (parsedUri.query)\n                opts.query = parsedUri.query;\n        }\n        else if (opts.host) {\n            opts.hostname = (0, parseuri_js_1.parse)(opts.host).host;\n        }\n        (0, util_js_1.installTimerFunctions)(this, opts);\n        this.secure =\n            null != opts.secure\n                ? opts.secure\n                : typeof location !== \"undefined\" && \"https:\" === location.protocol;\n        if (opts.hostname && !opts.port) {\n            // if no port is specified manually, use the protocol default\n            opts.port = this.secure ? \"443\" : \"80\";\n        }\n        this.hostname =\n            opts.hostname ||\n                (typeof location !== \"undefined\" ? location.hostname : \"localhost\");\n        this.port =\n            opts.port ||\n                (typeof location !== \"undefined\" && location.port\n                    ? location.port\n                    : this.secure\n                        ? \"443\"\n                        : \"80\");\n        if (opts.transportImplementations && opts.transports) {\n            throw new Error(\"specifying both 'transportImplementations' and 'transports' options is not supported\");\n        }\n        if (opts.transportImplementations ||\n            (((_a = opts.transports) === null || _a === void 0 ? void 0 : _a.length) && typeof opts.transports[0] === \"function\")) {\n            // 'transports' option as an array of transport implementations is kept for backward compatibility\n            this.transports = [];\n            this._transportsByName = Object.create(null);\n            ((_b = opts.transportImplementations) !== null && _b !== void 0 ? _b : opts.transports).forEach((t) => {\n                const transportName = t.prototype.name;\n                this.transports.push(transportName);\n                this._transportsByName[transportName] = t;\n            });\n        }\n        else {\n            this.transports = opts.transports\n                ? [...opts.transports]\n                : [\"polling\", \"websocket\", \"webtransport\"];\n            this._transportsByName = index_js_1.transports;\n        }\n        this.opts = Object.assign({\n            path: \"/engine.io\",\n            agent: false,\n            withCredentials: false,\n            upgrade: true,\n            timestampParam: \"t\",\n            rememberUpgrade: false,\n            addTrailingSlash: true,\n            rejectUnauthorized: true,\n            perMessageDeflate: {\n                threshold: 1024,\n            },\n            transportOptions: {},\n            closeOnBeforeunload: false,\n        }, opts);\n        this.opts.path =\n            this.opts.path.replace(/\\/$/, \"\") +\n                (this.opts.addTrailingSlash ? \"/\" : \"\");\n        if (typeof this.opts.query === \"string\") {\n            this.opts.query = (0, parseqs_js_1.decode)(this.opts.query);\n        }\n        if (withEventListeners) {\n            if (this.opts.closeOnBeforeunload) {\n                // Firefox closes the connection when the \"beforeunload\" event is emitted but not Chrome. This event listener\n                // ensures every browser behaves the same (no \"disconnect\" event at the Socket.IO level when the page is\n                // closed/reloaded)\n                this._beforeunloadEventListener = () => {\n                    if (this.transport) {\n                        // silently close the transport\n                        this.transport.removeAllListeners();\n                        this.transport.close();\n                    }\n                };\n                addEventListener(\"beforeunload\", this._beforeunloadEventListener, false);\n            }\n            if (this.hostname !== \"localhost\") {\n                debug(\"adding listener for the 'offline' event\");\n                this._offlineEventListener = () => {\n                    this._onClose(\"transport close\", {\n                        description: \"network connection lost\",\n                    });\n                };\n                OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);\n            }\n        }\n        if (this.opts.withCredentials) {\n            this._cookieJar = (0, globals_node_js_1.createCookieJar)();\n        }\n        this._open();\n    }\n    /**\n     * Creates transport of the given type.\n     *\n     * @param {String} name - transport name\n     * @return {Transport}\n     * @private\n     */\n    createTransport(name) {\n        debug('creating transport \"%s\"', name);\n        const query = Object.assign({}, this.opts.query);\n        // append engine.io protocol identifier\n        query.EIO = engine_io_parser_1.protocol;\n        // transport name\n        query.transport = name;\n        // session id if we already have one\n        if (this.id)\n            query.sid = this.id;\n        const opts = Object.assign({}, this.opts, {\n            query,\n            socket: this,\n            hostname: this.hostname,\n            secure: this.secure,\n            port: this.port,\n        }, this.opts.transportOptions[name]);\n        debug(\"options: %j\", opts);\n        return new this._transportsByName[name](opts);\n    }\n    /**\n     * Initializes transport to use and starts probe.\n     *\n     * @private\n     */\n    _open() {\n        if (this.transports.length === 0) {\n            // Emit error on next tick so it can be listened to\n            this.setTimeoutFn(() => {\n                this.emitReserved(\"error\", \"No transports available\");\n            }, 0);\n            return;\n        }\n        const transportName = this.opts.rememberUpgrade &&\n            Socket.priorWebsocketSuccess &&\n            this.transports.indexOf(\"websocket\") !== -1\n            ? \"websocket\"\n            : this.transports[0];\n        this.readyState = \"opening\";\n        const transport = this.createTransport(transportName);\n        transport.open();\n        this.setTransport(transport);\n    }\n    /**\n     * Sets the current transport. Disables the existing one (if any).\n     *\n     * @private\n     */\n    setTransport(transport) {\n        debug(\"setting transport %s\", transport.name);\n        if (this.transport) {\n            debug(\"clearing existing transport %s\", this.transport.name);\n            this.transport.removeAllListeners();\n        }\n        // set up transport\n        this.transport = transport;\n        // set up transport listeners\n        transport\n            .on(\"drain\", this._onDrain.bind(this))\n            .on(\"packet\", this._onPacket.bind(this))\n            .on(\"error\", this._onError.bind(this))\n            .on(\"close\", (reason) => this._onClose(\"transport close\", reason));\n    }\n    /**\n     * Probes a transport.\n     *\n     * @param {String} name - transport name\n     * @private\n     */\n    _probe(name) {\n        debug('probing transport \"%s\"', name);\n        let transport = this.createTransport(name);\n        let failed = false;\n        Socket.priorWebsocketSuccess = false;\n        const onTransportOpen = () => {\n            if (failed)\n                return;\n            debug('probe transport \"%s\" opened', name);\n            transport.send([{ type: \"ping\", data: \"probe\" }]);\n            transport.once(\"packet\", (msg) => {\n                if (failed)\n                    return;\n                if (\"pong\" === msg.type && \"probe\" === msg.data) {\n                    debug('probe transport \"%s\" pong', name);\n                    this.upgrading = true;\n                    this.emitReserved(\"upgrading\", transport);\n                    if (!transport)\n                        return;\n                    Socket.priorWebsocketSuccess = \"websocket\" === transport.name;\n                    debug('pausing current transport \"%s\"', this.transport.name);\n                    this.transport.pause(() => {\n                        if (failed)\n                            return;\n                        if (\"closed\" === this.readyState)\n                            return;\n                        debug(\"changing transport and sending upgrade packet\");\n                        cleanup();\n                        this.setTransport(transport);\n                        transport.send([{ type: \"upgrade\" }]);\n                        this.emitReserved(\"upgrade\", transport);\n                        transport = null;\n                        this.upgrading = false;\n                        this.flush();\n                    });\n                }\n                else {\n                    debug('probe transport \"%s\" failed', name);\n                    const err = new Error(\"probe error\");\n                    // @ts-ignore\n                    err.transport = transport.name;\n                    this.emitReserved(\"upgradeError\", err);\n                }\n            });\n        };\n        function freezeTransport() {\n            if (failed)\n                return;\n            // Any callback called by transport should be ignored since now\n            failed = true;\n            cleanup();\n            transport.close();\n            transport = null;\n        }\n        // Handle any error that happens while probing\n        const onerror = (err) => {\n            const error = new Error(\"probe error: \" + err);\n            // @ts-ignore\n            error.transport = transport.name;\n            freezeTransport();\n            debug('probe transport \"%s\" failed because of error: %s', name, err);\n            this.emitReserved(\"upgradeError\", error);\n        };\n        function onTransportClose() {\n            onerror(\"transport closed\");\n        }\n        // When the socket is closed while we're probing\n        function onclose() {\n            onerror(\"socket closed\");\n        }\n        // When the socket is upgraded while we're probing\n        function onupgrade(to) {\n            if (transport && to.name !== transport.name) {\n                debug('\"%s\" works - aborting \"%s\"', to.name, transport.name);\n                freezeTransport();\n            }\n        }\n        // Remove all listeners on the transport and on self\n        const cleanup = () => {\n            transport.removeListener(\"open\", onTransportOpen);\n            transport.removeListener(\"error\", onerror);\n            transport.removeListener(\"close\", onTransportClose);\n            this.off(\"close\", onclose);\n            this.off(\"upgrading\", onupgrade);\n        };\n        transport.once(\"open\", onTransportOpen);\n        transport.once(\"error\", onerror);\n        transport.once(\"close\", onTransportClose);\n        this.once(\"close\", onclose);\n        this.once(\"upgrading\", onupgrade);\n        if (this._upgrades.indexOf(\"webtransport\") !== -1 &&\n            name !== \"webtransport\") {\n            // favor WebTransport\n            this.setTimeoutFn(() => {\n                if (!failed) {\n                    transport.open();\n                }\n            }, 200);\n        }\n        else {\n            transport.open();\n        }\n    }\n    /**\n     * Called when connection is deemed open.\n     *\n     * @private\n     */\n    onOpen() {\n        debug(\"socket open\");\n        this.readyState = \"open\";\n        Socket.priorWebsocketSuccess = \"websocket\" === this.transport.name;\n        this.emitReserved(\"open\");\n        this.flush();\n        if (\"open\" === this.readyState && this.opts.upgrade) {\n            debug(\"starting upgrade probes\");\n            for (let i = 0; i < this._upgrades.length; i++) {\n                this._probe(this._upgrades[i]);\n            }\n        }\n    }\n    /**\n     * Handles a packet.\n     *\n     * @private\n     */\n    _onPacket(packet) {\n        if (\"opening\" === this.readyState ||\n            \"open\" === this.readyState ||\n            \"closing\" === this.readyState) {\n            debug('socket receive: type \"%s\", data \"%s\"', packet.type, packet.data);\n            this.emitReserved(\"packet\", packet);\n            // Socket is live - any packet counts\n            this.emitReserved(\"heartbeat\");\n            switch (packet.type) {\n                case \"open\":\n                    this.onHandshake(JSON.parse(packet.data));\n                    break;\n                case \"ping\":\n                    this._sendPacket(\"pong\");\n                    this.emitReserved(\"ping\");\n                    this.emitReserved(\"pong\");\n                    this._resetPingTimeout();\n                    break;\n                case \"error\":\n                    const err = new Error(\"server error\");\n                    // @ts-ignore\n                    err.code = packet.data;\n                    this._onError(err);\n                    break;\n                case \"message\":\n                    this.emitReserved(\"data\", packet.data);\n                    this.emitReserved(\"message\", packet.data);\n                    break;\n            }\n        }\n        else {\n            debug('packet received with socket readyState \"%s\"', this.readyState);\n        }\n    }\n    /**\n     * Called upon handshake completion.\n     *\n     * @param {Object} data - handshake obj\n     * @private\n     */\n    onHandshake(data) {\n        this.emitReserved(\"handshake\", data);\n        this.id = data.sid;\n        this.transport.query.sid = data.sid;\n        this._upgrades = this._filterUpgrades(data.upgrades);\n        this._pingInterval = data.pingInterval;\n        this._pingTimeout = data.pingTimeout;\n        this._maxPayload = data.maxPayload;\n        this.onOpen();\n        // In case open handler closes socket\n        if (\"closed\" === this.readyState)\n            return;\n        this._resetPingTimeout();\n    }\n    /**\n     * Sets and resets ping timeout timer based on server pings.\n     *\n     * @private\n     */\n    _resetPingTimeout() {\n        this.clearTimeoutFn(this._pingTimeoutTimer);\n        const delay = this._pingInterval + this._pingTimeout;\n        this._pingTimeoutTime = Date.now() + delay;\n        this._pingTimeoutTimer = this.setTimeoutFn(() => {\n            this._onClose(\"ping timeout\");\n        }, delay);\n        if (this.opts.autoUnref) {\n            this._pingTimeoutTimer.unref();\n        }\n    }\n    /**\n     * Called on `drain` event\n     *\n     * @private\n     */\n    _onDrain() {\n        this.writeBuffer.splice(0, this._prevBufferLen);\n        // setting prevBufferLen = 0 is very important\n        // for example, when upgrading, upgrade packet is sent over,\n        // and a nonzero prevBufferLen could cause problems on `drain`\n        this._prevBufferLen = 0;\n        if (0 === this.writeBuffer.length) {\n            this.emitReserved(\"drain\");\n        }\n        else {\n            this.flush();\n        }\n    }\n    /**\n     * Flush write buffers.\n     *\n     * @private\n     */\n    flush() {\n        if (\"closed\" !== this.readyState &&\n            this.transport.writable &&\n            !this.upgrading &&\n            this.writeBuffer.length) {\n            const packets = this._getWritablePackets();\n            debug(\"flushing %d packets in socket\", packets.length);\n            this.transport.send(packets);\n            // keep track of current length of writeBuffer\n            // splice writeBuffer and callbackBuffer on `drain`\n            this._prevBufferLen = packets.length;\n            this.emitReserved(\"flush\");\n        }\n    }\n    /**\n     * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP\n     * long-polling)\n     *\n     * @private\n     */\n    _getWritablePackets() {\n        const shouldCheckPayloadSize = this._maxPayload &&\n            this.transport.name === \"polling\" &&\n            this.writeBuffer.length > 1;\n        if (!shouldCheckPayloadSize) {\n            return this.writeBuffer;\n        }\n        let payloadSize = 1; // first packet type\n        for (let i = 0; i < this.writeBuffer.length; i++) {\n            const data = this.writeBuffer[i].data;\n            if (data) {\n                payloadSize += (0, util_js_1.byteLength)(data);\n            }\n            if (i > 0 && payloadSize > this._maxPayload) {\n                debug(\"only send %d out of %d packets\", i, this.writeBuffer.length);\n                return this.writeBuffer.slice(0, i);\n            }\n            payloadSize += 2; // separator + packet type\n        }\n        debug(\"payload size is %d (max: %d)\", payloadSize, this._maxPayload);\n        return this.writeBuffer;\n    }\n    /**\n     * Checks whether the heartbeat timer has expired but the socket has not yet been notified.\n     *\n     * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the\n     * `write()` method then the message would not be buffered by the Socket.IO client.\n     *\n     * @return {boolean}\n     * @private\n     */\n    /* private */ _hasPingExpired() {\n        if (!this._pingTimeoutTime)\n            return true;\n        const hasExpired = Date.now() > this._pingTimeoutTime;\n        if (hasExpired) {\n            debug(\"throttled timer detected, scheduling connection close\");\n            this._pingTimeoutTime = 0;\n            (0, globals_node_js_1.nextTick)(() => {\n                this._onClose(\"ping timeout\");\n            }, this.setTimeoutFn);\n        }\n        return hasExpired;\n    }\n    /**\n     * Sends a message.\n     *\n     * @param {String} msg - message.\n     * @param {Object} options.\n     * @param {Function} fn - callback function.\n     * @return {Socket} for chaining.\n     */\n    write(msg, options, fn) {\n        this._sendPacket(\"message\", msg, options, fn);\n        return this;\n    }\n    /**\n     * Sends a message. Alias of {@link Socket#write}.\n     *\n     * @param {String} msg - message.\n     * @param {Object} options.\n     * @param {Function} fn - callback function.\n     * @return {Socket} for chaining.\n     */\n    send(msg, options, fn) {\n        this._sendPacket(\"message\", msg, options, fn);\n        return this;\n    }\n    /**\n     * Sends a packet.\n     *\n     * @param {String} type - packet type.\n     * @param {String} data.\n     * @param {Object} options.\n     * @param {Function} fn - callback function.\n     * @private\n     */\n    _sendPacket(type, data, options, fn) {\n        if (\"function\" === typeof data) {\n            fn = data;\n            data = undefined;\n        }\n        if (\"function\" === typeof options) {\n            fn = options;\n            options = null;\n        }\n        if (\"closing\" === this.readyState || \"closed\" === this.readyState) {\n            return;\n        }\n        options = options || {};\n        options.compress = false !== options.compress;\n        const packet = {\n            type: type,\n            data: data,\n            options: options,\n        };\n        this.emitReserved(\"packetCreate\", packet);\n        this.writeBuffer.push(packet);\n        if (fn)\n            this.once(\"flush\", fn);\n        this.flush();\n    }\n    /**\n     * Closes the connection.\n     */\n    close() {\n        const close = () => {\n            this._onClose(\"forced close\");\n            debug(\"socket closing - telling transport to close\");\n            this.transport.close();\n        };\n        const cleanupAndClose = () => {\n            this.off(\"upgrade\", cleanupAndClose);\n            this.off(\"upgradeError\", cleanupAndClose);\n            close();\n        };\n        const waitForUpgrade = () => {\n            // wait for upgrade to finish since we can't send packets while pausing a transport\n            this.once(\"upgrade\", cleanupAndClose);\n            this.once(\"upgradeError\", cleanupAndClose);\n        };\n        if (\"opening\" === this.readyState || \"open\" === this.readyState) {\n            this.readyState = \"closing\";\n            if (this.writeBuffer.length) {\n                this.once(\"drain\", () => {\n                    if (this.upgrading) {\n                        waitForUpgrade();\n                    }\n                    else {\n                        close();\n                    }\n                });\n            }\n            else if (this.upgrading) {\n                waitForUpgrade();\n            }\n            else {\n                close();\n            }\n        }\n        return this;\n    }\n    /**\n     * Called upon transport error\n     *\n     * @private\n     */\n    _onError(err) {\n        debug(\"socket error %j\", err);\n        Socket.priorWebsocketSuccess = false;\n        if (this.opts.tryAllTransports &&\n            this.transports.length > 1 &&\n            this.readyState === \"opening\") {\n            debug(\"trying next transport\");\n            this.transports.shift();\n            return this._open();\n        }\n        this.emitReserved(\"error\", err);\n        this._onClose(\"transport error\", err);\n    }\n    /**\n     * Called upon transport close.\n     *\n     * @private\n     */\n    _onClose(reason, description) {\n        if (\"opening\" === this.readyState ||\n            \"open\" === this.readyState ||\n            \"closing\" === this.readyState) {\n            debug('socket close with reason: \"%s\"', reason);\n            // clear timers\n            this.clearTimeoutFn(this._pingTimeoutTimer);\n            // stop event from firing again for transport\n            this.transport.removeAllListeners(\"close\");\n            // ensure transport won't stay open\n            this.transport.close();\n            // ignore further transport communication\n            this.transport.removeAllListeners();\n            if (withEventListeners) {\n                if (this._beforeunloadEventListener) {\n                    removeEventListener(\"beforeunload\", this._beforeunloadEventListener, false);\n                }\n                if (this._offlineEventListener) {\n                    const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);\n                    if (i !== -1) {\n                        debug(\"removing listener for the 'offline' event\");\n                        OFFLINE_EVENT_LISTENERS.splice(i, 1);\n                    }\n                }\n            }\n            // set ready state\n            this.readyState = \"closed\";\n            // clear session id\n            this.id = null;\n            // emit close event\n            this.emitReserved(\"close\", reason, description);\n            // clean buffers after, so users can still\n            // grab the buffers on `close` event\n            this.writeBuffer = [];\n            this._prevBufferLen = 0;\n        }\n    }\n    /**\n     * Filters upgrades, returning only those matching client transports.\n     *\n     * @param {Array} upgrades - server upgrades\n     * @private\n     */\n    _filterUpgrades(upgrades) {\n        const filteredUpgrades = [];\n        for (let i = 0; i < upgrades.length; i++) {\n            if (~this.transports.indexOf(upgrades[i]))\n                filteredUpgrades.push(upgrades[i]);\n        }\n        return filteredUpgrades;\n    }\n}\nexports.Socket = Socket;\nSocket.protocol = engine_io_parser_1.protocol;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Fetch = void 0;\nconst polling_js_1 = require(\"./polling.js\");\n/**\n * HTTP long-polling based on the built-in `fetch()` method.\n *\n * Usage: browser, Node.js (since v18), Deno, Bun\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/fetch\n * @see https://caniuse.com/fetch\n * @see https://nodejs.org/api/globals.html#fetch\n */\nclass Fetch extends polling_js_1.Polling {\n    doPoll() {\n        this._fetch()\n            .then((res) => {\n            if (!res.ok) {\n                return this.onError(\"fetch read error\", res.status, res);\n            }\n            res.text().then((data) => this.onData(data));\n        })\n            .catch((err) => {\n            this.onError(\"fetch read error\", err);\n        });\n    }\n    doWrite(data, callback) {\n        this._fetch(data)\n            .then((res) => {\n            if (!res.ok) {\n                return this.onError(\"fetch write error\", res.status, res);\n            }\n            callback();\n        })\n            .catch((err) => {\n            this.onError(\"fetch write error\", err);\n        });\n    }\n    _fetch(data) {\n        var _a;\n        const isPost = data !== undefined;\n        const headers = new Headers(this.opts.extraHeaders);\n        if (isPost) {\n            headers.set(\"content-type\", \"text/plain;charset=UTF-8\");\n        }\n        (_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.appendCookies(headers);\n        return fetch(this.uri(), {\n            method: isPost ? \"POST\" : \"GET\",\n            body: isPost ? data : null,\n            headers,\n            credentials: this.opts.withCredentials ? \"include\" : \"omit\",\n        }).then((res) => {\n            var _a;\n            // @ts-ignore getSetCookie() was added in Node.js v19.7.0\n            (_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(res.headers.getSetCookie());\n            return res;\n        });\n    }\n}\nexports.Fetch = Fetch;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WebTransport = exports.WebSocket = exports.NodeWebSocket = exports.XHR = exports.NodeXHR = exports.Fetch = exports.nextTick = exports.parse = exports.installTimerFunctions = exports.transports = exports.TransportError = exports.Transport = exports.protocol = exports.Socket = void 0;\nconst socket_js_1 = require(\"./socket.js\");\nObject.defineProperty(exports, \"Socket\", { enumerable: true, get: function () { return socket_js_1.Socket; } });\nexports.protocol = socket_js_1.Socket.protocol;\nvar transport_js_1 = require(\"./transport.js\");\nObject.defineProperty(exports, \"Transport\", { enumerable: true, get: function () { return transport_js_1.Transport; } });\nObject.defineProperty(exports, \"TransportError\", { enumerable: true, get: function () { return transport_js_1.TransportError; } });\nvar index_js_1 = require(\"./transports/index.js\");\nObject.defineProperty(exports, \"transports\", { enumerable: true, get: function () { return index_js_1.transports; } });\nvar util_js_1 = require(\"./util.js\");\nObject.defineProperty(exports, \"installTimerFunctions\", { enumerable: true, get: function () { return util_js_1.installTimerFunctions; } });\nvar parseuri_js_1 = require(\"./contrib/parseuri.js\");\nObject.defineProperty(exports, \"parse\", { enumerable: true, get: function () { return parseuri_js_1.parse; } });\nvar globals_node_js_1 = require(\"./globals.node.js\");\nObject.defineProperty(exports, \"nextTick\", { enumerable: true, get: function () { return globals_node_js_1.nextTick; } });\nvar polling_fetch_js_1 = require(\"./transports/polling-fetch.js\");\nObject.defineProperty(exports, \"Fetch\", { enumerable: true, get: function () { return polling_fetch_js_1.Fetch; } });\nvar polling_xhr_node_js_1 = require(\"./transports/polling-xhr.node.js\");\nObject.defineProperty(exports, \"NodeXHR\", { enumerable: true, get: function () { return polling_xhr_node_js_1.XHR; } });\nvar polling_xhr_js_1 = require(\"./transports/polling-xhr.js\");\nObject.defineProperty(exports, \"XHR\", { enumerable: true, get: function () { return polling_xhr_js_1.XHR; } });\nvar websocket_node_js_1 = require(\"./transports/websocket.node.js\");\nObject.defineProperty(exports, \"NodeWebSocket\", { enumerable: true, get: function () { return websocket_node_js_1.WS; } });\nvar websocket_js_1 = require(\"./transports/websocket.js\");\nObject.defineProperty(exports, \"WebSocket\", { enumerable: true, get: function () { return websocket_js_1.WS; } });\nvar webtransport_js_1 = require(\"./transports/webtransport.js\");\nObject.defineProperty(exports, \"WebTransport\", { enumerable: true, get: function () { return webtransport_js_1.WT; } });\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.url = url;\nconst engine_io_client_1 = require(\"engine.io-client\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"socket.io-client:url\"); // debug()\n/**\n * URL parser.\n *\n * @param uri - url\n * @param path - the request path of the connection\n * @param loc - An object meant to mimic window.location.\n *        Defaults to window.location.\n * @public\n */\nfunction url(uri, path = \"\", loc) {\n    let obj = uri;\n    // default to window.location\n    loc = loc || (typeof location !== \"undefined\" && location);\n    if (null == uri)\n        uri = loc.protocol + \"//\" + loc.host;\n    // relative path support\n    if (typeof uri === \"string\") {\n        if (\"/\" === uri.charAt(0)) {\n            if (\"/\" === uri.charAt(1)) {\n                uri = loc.protocol + uri;\n            }\n            else {\n                uri = loc.host + uri;\n            }\n        }\n        if (!/^(https?|wss?):\\/\\//.test(uri)) {\n            debug(\"protocol-less url %s\", uri);\n            if (\"undefined\" !== typeof loc) {\n                uri = loc.protocol + \"//\" + uri;\n            }\n            else {\n                uri = \"https://\" + uri;\n            }\n        }\n        // parse\n        debug(\"parse %s\", uri);\n        obj = (0, engine_io_client_1.parse)(uri);\n    }\n    // make sure we treat `localhost:80` and `localhost` equally\n    if (!obj.port) {\n        if (/^(http|ws)$/.test(obj.protocol)) {\n            obj.port = \"80\";\n        }\n        else if (/^(http|ws)s$/.test(obj.protocol)) {\n            obj.port = \"443\";\n        }\n    }\n    obj.path = obj.path || \"/\";\n    const ipv6 = obj.host.indexOf(\":\") !== -1;\n    const host = ipv6 ? \"[\" + obj.host + \"]\" : obj.host;\n    // define unique id\n    obj.id = obj.protocol + \"://\" + host + \":\" + obj.port + path;\n    // define href\n    obj.href =\n        obj.protocol +\n            \"://\" +\n            host +\n            (loc && loc.port === obj.port ? \"\" : \":\" + obj.port);\n    return obj;\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isBinary = isBinary;\nexports.hasBinary = hasBinary;\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\nconst isView = (obj) => {\n    return typeof ArrayBuffer.isView === \"function\"\n        ? ArrayBuffer.isView(obj)\n        : obj.buffer instanceof ArrayBuffer;\n};\nconst toString = Object.prototype.toString;\nconst withNativeBlob = typeof Blob === \"function\" ||\n    (typeof Blob !== \"undefined\" &&\n        toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeFile = typeof File === \"function\" ||\n    (typeof File !== \"undefined\" &&\n        toString.call(File) === \"[object FileConstructor]\");\n/**\n * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.\n *\n * @private\n */\nfunction isBinary(obj) {\n    return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||\n        (withNativeBlob && obj instanceof Blob) ||\n        (withNativeFile && obj instanceof File));\n}\nfunction hasBinary(obj, toJSON) {\n    if (!obj || typeof obj !== \"object\") {\n        return false;\n    }\n    if (Array.isArray(obj)) {\n        for (let i = 0, l = obj.length; i < l; i++) {\n            if (hasBinary(obj[i])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    if (isBinary(obj)) {\n        return true;\n    }\n    if (obj.toJSON &&\n        typeof obj.toJSON === \"function\" &&\n        arguments.length === 1) {\n        return hasBinary(obj.toJSON(), true);\n    }\n    for (const key in obj) {\n        if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {\n            return true;\n        }\n    }\n    return false;\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.deconstructPacket = deconstructPacket;\nexports.reconstructPacket = reconstructPacket;\nconst is_binary_js_1 = require(\"./is-binary.js\");\n/**\n * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.\n *\n * @param {Object} packet - socket.io event packet\n * @return {Object} with deconstructed packet and list of buffers\n * @public\n */\nfunction deconstructPacket(packet) {\n    const buffers = [];\n    const packetData = packet.data;\n    const pack = packet;\n    pack.data = _deconstructPacket(packetData, buffers);\n    pack.attachments = buffers.length; // number of binary 'attachments'\n    return { packet: pack, buffers: buffers };\n}\nfunction _deconstructPacket(data, buffers, toJSON) {\n    if (!data)\n        return data;\n    if ((0, is_binary_js_1.isBinary)(data)) {\n        const placeholder = { _placeholder: true, num: buffers.length };\n        buffers.push(data);\n        return placeholder;\n    }\n    else if (Array.isArray(data)) {\n        const newData = new Array(data.length);\n        for (let i = 0; i < data.length; i++) {\n            newData[i] = _deconstructPacket(data[i], buffers);\n        }\n        return newData;\n    }\n    else if (typeof data === \"object\" && !(data instanceof Date)) {\n        if (data.toJSON && typeof data.toJSON === \"function\" && !toJSON) {\n            return _deconstructPacket(data.toJSON(), buffers, true);\n        }\n        const newData = {};\n        for (const key in data) {\n            if (Object.prototype.hasOwnProperty.call(data, key)) {\n                newData[key] = _deconstructPacket(data[key], buffers);\n            }\n        }\n        return newData;\n    }\n    return data;\n}\n/**\n * Reconstructs a binary packet from its placeholder packet and buffers\n *\n * @param {Object} packet - event packet with placeholders\n * @param {Array} buffers - binary buffers to put in placeholder positions\n * @return {Object} reconstructed packet\n * @public\n */\nfunction reconstructPacket(packet, buffers) {\n    packet.data = _reconstructPacket(packet.data, buffers);\n    delete packet.attachments; // no longer useful\n    return packet;\n}\nfunction _reconstructPacket(data, buffers) {\n    if (!data)\n        return data;\n    if (data && data._placeholder === true) {\n        const isIndexValid = typeof data.num === \"number\" &&\n            data.num >= 0 &&\n            data.num < buffers.length;\n        if (isIndexValid) {\n            return buffers[data.num]; // appropriate buffer (should be natural order anyway)\n        }\n        else {\n            throw new Error(\"illegal attachments\");\n        }\n    }\n    else if (Array.isArray(data)) {\n        for (let i = 0; i < data.length; i++) {\n            data[i] = _reconstructPacket(data[i], buffers);\n        }\n    }\n    else if (typeof data === \"object\") {\n        for (const key in data) {\n            if (Object.prototype.hasOwnProperty.call(data, key)) {\n                data[key] = _reconstructPacket(data[key], buffers);\n            }\n        }\n    }\n    return data;\n}\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Decoder = exports.Encoder = exports.PacketType = exports.protocol = void 0;\nexports.isPacketValid = isPacketValid;\nconst component_emitter_1 = require(\"@socket.io/component-emitter\");\nconst binary_js_1 = require(\"./binary.js\");\nconst is_binary_js_1 = require(\"./is-binary.js\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"socket.io-parser\"); // debug()\n/**\n * These strings must not be used as event names, as they have a special meaning.\n */\nconst RESERVED_EVENTS = [\n    \"connect\", // used on the client side\n    \"connect_error\", // used on the client side\n    \"disconnect\", // used on both sides\n    \"disconnecting\", // used on the server side\n    \"newListener\", // used by the Node.js EventEmitter\n    \"removeListener\", // used by the Node.js EventEmitter\n];\n/**\n * Protocol version.\n *\n * @public\n */\nexports.protocol = 5;\nvar PacketType;\n(function (PacketType) {\n    PacketType[PacketType[\"CONNECT\"] = 0] = \"CONNECT\";\n    PacketType[PacketType[\"DISCONNECT\"] = 1] = \"DISCONNECT\";\n    PacketType[PacketType[\"EVENT\"] = 2] = \"EVENT\";\n    PacketType[PacketType[\"ACK\"] = 3] = \"ACK\";\n    PacketType[PacketType[\"CONNECT_ERROR\"] = 4] = \"CONNECT_ERROR\";\n    PacketType[PacketType[\"BINARY_EVENT\"] = 5] = \"BINARY_EVENT\";\n    PacketType[PacketType[\"BINARY_ACK\"] = 6] = \"BINARY_ACK\";\n})(PacketType || (exports.PacketType = PacketType = {}));\n/**\n * A socket.io Encoder instance\n */\nclass Encoder {\n    /**\n     * Encoder constructor\n     *\n     * @param {function} replacer - custom replacer to pass down to JSON.parse\n     */\n    constructor(replacer) {\n        this.replacer = replacer;\n    }\n    /**\n     * Encode a packet as a single string if non-binary, or as a\n     * buffer sequence, depending on packet type.\n     *\n     * @param {Object} obj - packet object\n     */\n    encode(obj) {\n        debug(\"encoding packet %j\", obj);\n        if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {\n            if ((0, is_binary_js_1.hasBinary)(obj)) {\n                return this.encodeAsBinary({\n                    type: obj.type === PacketType.EVENT\n                        ? PacketType.BINARY_EVENT\n                        : PacketType.BINARY_ACK,\n                    nsp: obj.nsp,\n                    data: obj.data,\n                    id: obj.id,\n                });\n            }\n        }\n        return [this.encodeAsString(obj)];\n    }\n    /**\n     * Encode packet as string.\n     */\n    encodeAsString(obj) {\n        // first is type\n        let str = \"\" + obj.type;\n        // attachments if we have them\n        if (obj.type === PacketType.BINARY_EVENT ||\n            obj.type === PacketType.BINARY_ACK) {\n            str += obj.attachments + \"-\";\n        }\n        // if we have a namespace other than `/`\n        // we append it followed by a comma `,`\n        if (obj.nsp && \"/\" !== obj.nsp) {\n            str += obj.nsp + \",\";\n        }\n        // immediately followed by the id\n        if (null != obj.id) {\n            str += obj.id;\n        }\n        // json data\n        if (null != obj.data) {\n            str += JSON.stringify(obj.data, this.replacer);\n        }\n        debug(\"encoded %j as %s\", obj, str);\n        return str;\n    }\n    /**\n     * Encode packet as 'buffer sequence' by removing blobs, and\n     * deconstructing packet into object with placeholders and\n     * a list of buffers.\n     */\n    encodeAsBinary(obj) {\n        const deconstruction = (0, binary_js_1.deconstructPacket)(obj);\n        const pack = this.encodeAsString(deconstruction.packet);\n        const buffers = deconstruction.buffers;\n        buffers.unshift(pack); // add packet info to beginning of data list\n        return buffers; // write all the buffers\n    }\n}\nexports.Encoder = Encoder;\n/**\n * A socket.io Decoder instance\n *\n * @return {Object} decoder\n */\nclass Decoder extends component_emitter_1.Emitter {\n    /**\n     * Decoder constructor\n     */\n    constructor(opts) {\n        super();\n        this.opts = Object.assign({\n            reviver: undefined,\n            maxAttachments: 10,\n        }, typeof opts === \"function\" ? { reviver: opts } : opts);\n    }\n    /**\n     * Decodes an encoded packet string into packet JSON.\n     *\n     * @param {String} obj - encoded packet\n     */\n    add(obj) {\n        let packet;\n        if (typeof obj === \"string\") {\n            if (this.reconstructor) {\n                throw new Error(\"got plaintext data when reconstructing a packet\");\n            }\n            packet = this.decodeString(obj);\n            const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;\n            if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {\n                packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;\n                // binary packet's json\n                this.reconstructor = new BinaryReconstructor(packet);\n            }\n            else {\n                // non-binary full packet\n                super.emitReserved(\"decoded\", packet);\n            }\n        }\n        else if ((0, is_binary_js_1.isBinary)(obj) || obj.base64) {\n            // raw binary data\n            if (!this.reconstructor) {\n                throw new Error(\"got binary data when not reconstructing a packet\");\n            }\n            else {\n                packet = this.reconstructor.takeBinaryData(obj);\n                if (packet) {\n                    // received final buffer\n                    this.reconstructor = null;\n                    super.emitReserved(\"decoded\", packet);\n                }\n            }\n        }\n        else {\n            throw new Error(\"Unknown type: \" + obj);\n        }\n    }\n    /**\n     * Decode a packet String (JSON data)\n     *\n     * @param {String} str\n     * @return {Object} packet\n     */\n    decodeString(str) {\n        let i = 0;\n        // look up type\n        const p = {\n            type: Number(str.charAt(0)),\n        };\n        if (PacketType[p.type] === undefined) {\n            throw new Error(\"unknown packet type \" + p.type);\n        }\n        // look up attachments if type binary\n        if (p.type === PacketType.BINARY_EVENT ||\n            p.type === PacketType.BINARY_ACK) {\n            const start = i + 1;\n            while (str.charAt(++i) !== \"-\" && i != str.length) { }\n            const buf = str.substring(start, i);\n            if (buf != Number(buf) || str.charAt(i) !== \"-\") {\n                throw new Error(\"Illegal attachments\");\n            }\n            const n = Number(buf);\n            if (!isInteger(n) || n < 1) {\n                throw new Error(\"Illegal attachments\");\n            }\n            else if (n > this.opts.maxAttachments) {\n                throw new Error(\"too many attachments\");\n            }\n            p.attachments = n;\n        }\n        // look up namespace (if any)\n        if (\"/\" === str.charAt(i + 1)) {\n            const start = i + 1;\n            while (++i) {\n                const c = str.charAt(i);\n                if (\",\" === c)\n                    break;\n                if (i === str.length)\n                    break;\n            }\n            p.nsp = str.substring(start, i);\n        }\n        else {\n            p.nsp = \"/\";\n        }\n        // look up id\n        const next = str.charAt(i + 1);\n        if (\"\" !== next && Number(next) == next) {\n            const start = i + 1;\n            while (++i) {\n                const c = str.charAt(i);\n                if (null == c || Number(c) != c) {\n                    --i;\n                    break;\n                }\n                if (i === str.length)\n                    break;\n            }\n            p.id = Number(str.substring(start, i + 1));\n        }\n        // look up json data\n        if (str.charAt(++i)) {\n            const payload = this.tryParse(str.substr(i));\n            if (Decoder.isPayloadValid(p.type, payload)) {\n                p.data = payload;\n            }\n            else {\n                throw new Error(\"invalid payload\");\n            }\n        }\n        debug(\"decoded %s as %j\", str, p);\n        return p;\n    }\n    tryParse(str) {\n        try {\n            return JSON.parse(str, this.opts.reviver);\n        }\n        catch (e) {\n            return false;\n        }\n    }\n    static isPayloadValid(type, payload) {\n        switch (type) {\n            case PacketType.CONNECT:\n                return isObject(payload);\n            case PacketType.DISCONNECT:\n                return payload === undefined;\n            case PacketType.CONNECT_ERROR:\n                return typeof payload === \"string\" || isObject(payload);\n            case PacketType.EVENT:\n            case PacketType.BINARY_EVENT:\n                return (Array.isArray(payload) &&\n                    (typeof payload[0] === \"number\" ||\n                        (typeof payload[0] === \"string\" &&\n                            RESERVED_EVENTS.indexOf(payload[0]) === -1)));\n            case PacketType.ACK:\n            case PacketType.BINARY_ACK:\n                return Array.isArray(payload);\n        }\n    }\n    /**\n     * Deallocates a parser's resources\n     */\n    destroy() {\n        if (this.reconstructor) {\n            this.reconstructor.finishedReconstruction();\n            this.reconstructor = null;\n        }\n    }\n}\nexports.Decoder = Decoder;\n/**\n * A manager of a binary event's 'buffer sequence'. Should\n * be constructed whenever a packet of type BINARY_EVENT is\n * decoded.\n *\n * @param {Object} packet\n * @return {BinaryReconstructor} initialized reconstructor\n */\nclass BinaryReconstructor {\n    constructor(packet) {\n        this.packet = packet;\n        this.buffers = [];\n        this.reconPack = packet;\n    }\n    /**\n     * Method to be called when binary data received from connection\n     * after a BINARY_EVENT packet.\n     *\n     * @param {Buffer | ArrayBuffer} binData - the raw binary data received\n     * @return {null | Object} returns null if more binary data is expected or\n     *   a reconstructed packet object if all buffers have been received.\n     */\n    takeBinaryData(binData) {\n        this.buffers.push(binData);\n        if (this.buffers.length === this.reconPack.attachments) {\n            // done with buffer list\n            const packet = (0, binary_js_1.reconstructPacket)(this.reconPack, this.buffers);\n            this.finishedReconstruction();\n            return packet;\n        }\n        return null;\n    }\n    /**\n     * Cleans up binary packet reconstruction variables.\n     */\n    finishedReconstruction() {\n        this.reconPack = null;\n        this.buffers = [];\n    }\n}\nfunction isNamespaceValid(nsp) {\n    return typeof nsp === \"string\";\n}\n// see https://caniuse.com/mdn-javascript_builtins_number_isinteger\nconst isInteger = Number.isInteger ||\n    function (value) {\n        return (typeof value === \"number\" &&\n            isFinite(value) &&\n            Math.floor(value) === value);\n    };\nfunction isAckIdValid(id) {\n    return id === undefined || isInteger(id);\n}\n// see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript\nfunction isObject(value) {\n    return Object.prototype.toString.call(value) === \"[object Object]\";\n}\nfunction isDataValid(type, payload) {\n    switch (type) {\n        case PacketType.CONNECT:\n            return payload === undefined || isObject(payload);\n        case PacketType.DISCONNECT:\n            return payload === undefined;\n        case PacketType.EVENT:\n            return (Array.isArray(payload) &&\n                (typeof payload[0] === \"number\" ||\n                    (typeof payload[0] === \"string\" &&\n                        RESERVED_EVENTS.indexOf(payload[0]) === -1)));\n        case PacketType.ACK:\n            return Array.isArray(payload);\n        case PacketType.CONNECT_ERROR:\n            return typeof payload === \"string\" || isObject(payload);\n        default:\n            return false;\n    }\n}\nfunction isPacketValid(packet) {\n    return (isNamespaceValid(packet.nsp) &&\n        isAckIdValid(packet.id) &&\n        isDataValid(packet.type, packet.data));\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.on = on;\nfunction on(obj, ev, fn) {\n    obj.on(ev, fn);\n    return function subDestroy() {\n        obj.off(ev, fn);\n    };\n}\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Socket = void 0;\nconst socket_io_parser_1 = require(\"socket.io-parser\");\nconst on_js_1 = require(\"./on.js\");\nconst component_emitter_1 = require(\"@socket.io/component-emitter\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"socket.io-client:socket\"); // debug()\n/**\n * Internal events.\n * These events can't be emitted by the user.\n */\nconst RESERVED_EVENTS = Object.freeze({\n    connect: 1,\n    connect_error: 1,\n    disconnect: 1,\n    disconnecting: 1,\n    // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener\n    newListener: 1,\n    removeListener: 1,\n});\n/**\n * A Socket is the fundamental class for interacting with the server.\n *\n * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.\n *\n * @example\n * const socket = io();\n *\n * socket.on(\"connect\", () => {\n *   console.log(\"connected\");\n * });\n *\n * // send an event to the server\n * socket.emit(\"foo\", \"bar\");\n *\n * socket.on(\"foobar\", () => {\n *   // an event was received from the server\n * });\n *\n * // upon disconnection\n * socket.on(\"disconnect\", (reason) => {\n *   console.log(`disconnected due to ${reason}`);\n * });\n */\nclass Socket extends component_emitter_1.Emitter {\n    /**\n     * `Socket` constructor.\n     */\n    constructor(io, nsp, opts) {\n        super();\n        /**\n         * Whether the socket is currently connected to the server.\n         *\n         * @example\n         * const socket = io();\n         *\n         * socket.on(\"connect\", () => {\n         *   console.log(socket.connected); // true\n         * });\n         *\n         * socket.on(\"disconnect\", () => {\n         *   console.log(socket.connected); // false\n         * });\n         */\n        this.connected = false;\n        /**\n         * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will\n         * be transmitted by the server.\n         */\n        this.recovered = false;\n        /**\n         * Buffer for packets received before the CONNECT packet\n         */\n        this.receiveBuffer = [];\n        /**\n         * Buffer for packets that will be sent once the socket is connected\n         */\n        this.sendBuffer = [];\n        /**\n         * The queue of packets to be sent with retry in case of failure.\n         *\n         * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.\n         * @private\n         */\n        this._queue = [];\n        /**\n         * A sequence to generate the ID of the {@link QueuedPacket}.\n         * @private\n         */\n        this._queueSeq = 0;\n        this.ids = 0;\n        /**\n         * A map containing acknowledgement handlers.\n         *\n         * The `withError` attribute is used to differentiate handlers that accept an error as first argument:\n         *\n         * - `socket.emit(\"test\", (err, value) => { ... })` with `ackTimeout` option\n         * - `socket.timeout(5000).emit(\"test\", (err, value) => { ... })`\n         * - `const value = await socket.emitWithAck(\"test\")`\n         *\n         * From those that don't:\n         *\n         * - `socket.emit(\"test\", (value) => { ... });`\n         *\n         * In the first case, the handlers will be called with an error when:\n         *\n         * - the timeout is reached\n         * - the socket gets disconnected\n         *\n         * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive\n         * an acknowledgement from the server.\n         *\n         * @private\n         */\n        this.acks = {};\n        this.flags = {};\n        this.io = io;\n        this.nsp = nsp;\n        if (opts && opts.auth) {\n            this.auth = opts.auth;\n        }\n        this._opts = Object.assign({}, opts);\n        if (this.io._autoConnect)\n            this.open();\n    }\n    /**\n     * Whether the socket is currently disconnected\n     *\n     * @example\n     * const socket = io();\n     *\n     * socket.on(\"connect\", () => {\n     *   console.log(socket.disconnected); // false\n     * });\n     *\n     * socket.on(\"disconnect\", () => {\n     *   console.log(socket.disconnected); // true\n     * });\n     */\n    get disconnected() {\n        return !this.connected;\n    }\n    /**\n     * Subscribe to open, close and packet events\n     *\n     * @private\n     */\n    subEvents() {\n        if (this.subs)\n            return;\n        const io = this.io;\n        this.subs = [\n            (0, on_js_1.on)(io, \"open\", this.onopen.bind(this)),\n            (0, on_js_1.on)(io, \"packet\", this.onpacket.bind(this)),\n            (0, on_js_1.on)(io, \"error\", this.onerror.bind(this)),\n            (0, on_js_1.on)(io, \"close\", this.onclose.bind(this)),\n        ];\n    }\n    /**\n     * Whether the Socket will try to reconnect when its Manager connects or reconnects.\n     *\n     * @example\n     * const socket = io();\n     *\n     * console.log(socket.active); // true\n     *\n     * socket.on(\"disconnect\", (reason) => {\n     *   if (reason === \"io server disconnect\") {\n     *     // the disconnection was initiated by the server, you need to manually reconnect\n     *     console.log(socket.active); // false\n     *   }\n     *   // else the socket will automatically try to reconnect\n     *   console.log(socket.active); // true\n     * });\n     */\n    get active() {\n        return !!this.subs;\n    }\n    /**\n     * \"Opens\" the socket.\n     *\n     * @example\n     * const socket = io({\n     *   autoConnect: false\n     * });\n     *\n     * socket.connect();\n     */\n    connect() {\n        if (this.connected)\n            return this;\n        this.subEvents();\n        if (!this.io[\"_reconnecting\"])\n            this.io.open(); // ensure open\n        if (\"open\" === this.io._readyState)\n            this.onopen();\n        return this;\n    }\n    /**\n     * Alias for {@link connect()}.\n     */\n    open() {\n        return this.connect();\n    }\n    /**\n     * Sends a `message` event.\n     *\n     * This method mimics the WebSocket.send() method.\n     *\n     * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send\n     *\n     * @example\n     * socket.send(\"hello\");\n     *\n     * // this is equivalent to\n     * socket.emit(\"message\", \"hello\");\n     *\n     * @return self\n     */\n    send(...args) {\n        args.unshift(\"message\");\n        this.emit.apply(this, args);\n        return this;\n    }\n    /**\n     * Override `emit`.\n     * If the event is in `events`, it's emitted normally.\n     *\n     * @example\n     * socket.emit(\"hello\", \"world\");\n     *\n     * // all serializable datastructures are supported (no need to call JSON.stringify)\n     * socket.emit(\"hello\", 1, \"2\", { 3: [\"4\"], 5: Uint8Array.from([6]) });\n     *\n     * // with an acknowledgement from the server\n     * socket.emit(\"hello\", \"world\", (val) => {\n     *   // ...\n     * });\n     *\n     * @return self\n     */\n    emit(ev, ...args) {\n        var _a, _b, _c;\n        if (RESERVED_EVENTS.hasOwnProperty(ev)) {\n            throw new Error('\"' + ev.toString() + '\" is a reserved event name');\n        }\n        args.unshift(ev);\n        if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {\n            this._addToQueue(args);\n            return this;\n        }\n        const packet = {\n            type: socket_io_parser_1.PacketType.EVENT,\n            data: args,\n        };\n        packet.options = {};\n        packet.options.compress = this.flags.compress !== false;\n        // event ack callback\n        if (\"function\" === typeof args[args.length - 1]) {\n            const id = this.ids++;\n            debug(\"emitting packet with ack id %d\", id);\n            const ack = args.pop();\n            this._registerAckCallback(id, ack);\n            packet.id = id;\n        }\n        const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;\n        const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());\n        const discardPacket = this.flags.volatile && !isTransportWritable;\n        if (discardPacket) {\n            debug(\"discard packet as the transport is not currently writable\");\n        }\n        else if (isConnected) {\n            this.notifyOutgoingListeners(packet);\n            this.packet(packet);\n        }\n        else {\n            this.sendBuffer.push(packet);\n        }\n        this.flags = {};\n        return this;\n    }\n    /**\n     * @private\n     */\n    _registerAckCallback(id, ack) {\n        var _a;\n        const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;\n        if (timeout === undefined) {\n            this.acks[id] = ack;\n            return;\n        }\n        // @ts-ignore\n        const timer = this.io.setTimeoutFn(() => {\n            delete this.acks[id];\n            for (let i = 0; i < this.sendBuffer.length; i++) {\n                if (this.sendBuffer[i].id === id) {\n                    debug(\"removing packet with ack id %d from the buffer\", id);\n                    this.sendBuffer.splice(i, 1);\n                }\n            }\n            debug(\"event with ack id %d has timed out after %d ms\", id, timeout);\n            ack.call(this, new Error(\"operation has timed out\"));\n        }, timeout);\n        const fn = (...args) => {\n            // @ts-ignore\n            this.io.clearTimeoutFn(timer);\n            ack.apply(this, args);\n        };\n        fn.withError = true;\n        this.acks[id] = fn;\n    }\n    /**\n     * Emits an event and waits for an acknowledgement\n     *\n     * @example\n     * // without timeout\n     * const response = await socket.emitWithAck(\"hello\", \"world\");\n     *\n     * // with a specific timeout\n     * try {\n     *   const response = await socket.timeout(1000).emitWithAck(\"hello\", \"world\");\n     * } catch (err) {\n     *   // the server did not acknowledge the event in the given delay\n     * }\n     *\n     * @return a Promise that will be fulfilled when the server acknowledges the event\n     */\n    emitWithAck(ev, ...args) {\n        return new Promise((resolve, reject) => {\n            const fn = (arg1, arg2) => {\n                return arg1 ? reject(arg1) : resolve(arg2);\n            };\n            fn.withError = true;\n            args.push(fn);\n            this.emit(ev, ...args);\n        });\n    }\n    /**\n     * Add the packet to the queue.\n     * @param args\n     * @private\n     */\n    _addToQueue(args) {\n        let ack;\n        if (typeof args[args.length - 1] === \"function\") {\n            ack = args.pop();\n        }\n        const packet = {\n            id: this._queueSeq++,\n            tryCount: 0,\n            pending: false,\n            args,\n            flags: Object.assign({ fromQueue: true }, this.flags),\n        };\n        args.push((err, ...responseArgs) => {\n            if (packet !== this._queue[0]) {\n                return debug(\"packet [%d] already acknowledged\", packet.id);\n            }\n            const hasError = err !== null;\n            if (hasError) {\n                if (packet.tryCount > this._opts.retries) {\n                    debug(\"packet [%d] is discarded after %d tries\", packet.id, packet.tryCount);\n                    this._queue.shift();\n                    if (ack) {\n                        ack(err);\n                    }\n                }\n            }\n            else {\n                debug(\"packet [%d] was successfully sent\", packet.id);\n                this._queue.shift();\n                if (ack) {\n                    ack(null, ...responseArgs);\n                }\n            }\n            packet.pending = false;\n            return this._drainQueue();\n        });\n        this._queue.push(packet);\n        this._drainQueue();\n    }\n    /**\n     * Send the first packet of the queue, and wait for an acknowledgement from the server.\n     * @param force - whether to resend a packet that has not been acknowledged yet\n     *\n     * @private\n     */\n    _drainQueue(force = false) {\n        debug(\"draining queue\");\n        if (!this.connected || this._queue.length === 0) {\n            return;\n        }\n        const packet = this._queue[0];\n        if (packet.pending && !force) {\n            debug(\"packet [%d] has already been sent and is waiting for an ack\", packet.id);\n            return;\n        }\n        packet.pending = true;\n        packet.tryCount++;\n        debug(\"sending packet [%d] (try n\u00B0%d)\", packet.id, packet.tryCount);\n        this.flags = packet.flags;\n        this.emit.apply(this, packet.args);\n    }\n    /**\n     * Sends a packet.\n     *\n     * @param packet\n     * @private\n     */\n    packet(packet) {\n        packet.nsp = this.nsp;\n        this.io._packet(packet);\n    }\n    /**\n     * Called upon engine `open`.\n     *\n     * @private\n     */\n    onopen() {\n        debug(\"transport is open - connecting\");\n        if (typeof this.auth == \"function\") {\n            this.auth((data) => {\n                this._sendConnectPacket(data);\n            });\n        }\n        else {\n            this._sendConnectPacket(this.auth);\n        }\n    }\n    /**\n     * Sends a CONNECT packet to initiate the Socket.IO session.\n     *\n     * @param data\n     * @private\n     */\n    _sendConnectPacket(data) {\n        this.packet({\n            type: socket_io_parser_1.PacketType.CONNECT,\n            data: this._pid\n                ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)\n                : data,\n        });\n    }\n    /**\n     * Called upon engine or manager `error`.\n     *\n     * @param err\n     * @private\n     */\n    onerror(err) {\n        if (!this.connected) {\n            this.emitReserved(\"connect_error\", err);\n        }\n    }\n    /**\n     * Called upon engine `close`.\n     *\n     * @param reason\n     * @param description\n     * @private\n     */\n    onclose(reason, description) {\n        debug(\"close (%s)\", reason);\n        this.connected = false;\n        delete this.id;\n        this.emitReserved(\"disconnect\", reason, description);\n        this._clearAcks();\n    }\n    /**\n     * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from\n     * the server.\n     *\n     * @private\n     */\n    _clearAcks() {\n        Object.keys(this.acks).forEach((id) => {\n            const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);\n            if (!isBuffered) {\n                // note: handlers that do not accept an error as first argument are ignored here\n                const ack = this.acks[id];\n                delete this.acks[id];\n                if (ack.withError) {\n                    ack.call(this, new Error(\"socket has been disconnected\"));\n                }\n            }\n        });\n    }\n    /**\n     * Called with socket packet.\n     *\n     * @param packet\n     * @private\n     */\n    onpacket(packet) {\n        const sameNamespace = packet.nsp === this.nsp;\n        if (!sameNamespace)\n            return;\n        switch (packet.type) {\n            case socket_io_parser_1.PacketType.CONNECT:\n                if (packet.data && packet.data.sid) {\n                    this.onconnect(packet.data.sid, packet.data.pid);\n                }\n                else {\n                    this.emitReserved(\"connect_error\", new Error(\"It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)\"));\n                }\n                break;\n            case socket_io_parser_1.PacketType.EVENT:\n            case socket_io_parser_1.PacketType.BINARY_EVENT:\n                this.onevent(packet);\n                break;\n            case socket_io_parser_1.PacketType.ACK:\n            case socket_io_parser_1.PacketType.BINARY_ACK:\n                this.onack(packet);\n                break;\n            case socket_io_parser_1.PacketType.DISCONNECT:\n                this.ondisconnect();\n                break;\n            case socket_io_parser_1.PacketType.CONNECT_ERROR:\n                this.destroy();\n                const err = new Error(packet.data.message);\n                err.data = packet.data.data;\n                this.emitReserved(\"connect_error\", err);\n                break;\n        }\n    }\n    /**\n     * Called upon a server event.\n     *\n     * @param packet\n     * @private\n     */\n    onevent(packet) {\n        const args = packet.data || [];\n        debug(\"emitting event %j\", args);\n        if (null != packet.id) {\n            debug(\"attaching ack callback to event\");\n            args.push(this.ack(packet.id));\n        }\n        if (this.connected) {\n            this.emitEvent(args);\n        }\n        else {\n            this.receiveBuffer.push(Object.freeze(args));\n        }\n    }\n    emitEvent(args) {\n        if (this._anyListeners && this._anyListeners.length) {\n            const listeners = this._anyListeners.slice();\n            for (const listener of listeners) {\n                listener.apply(this, args);\n            }\n        }\n        super.emit.apply(this, args);\n        if (this._pid && args.length && typeof args[args.length - 1] === \"string\") {\n            this._lastOffset = args[args.length - 1];\n        }\n    }\n    /**\n     * Produces an ack callback to emit with an event.\n     *\n     * @private\n     */\n    ack(id) {\n        const self = this;\n        let sent = false;\n        return function (...args) {\n            // prevent double callbacks\n            if (sent)\n                return;\n            sent = true;\n            debug(\"sending ack %j\", args);\n            self.packet({\n                type: socket_io_parser_1.PacketType.ACK,\n                id: id,\n                data: args,\n            });\n        };\n    }\n    /**\n     * Called upon a server acknowledgement.\n     *\n     * @param packet\n     * @private\n     */\n    onack(packet) {\n        const ack = this.acks[packet.id];\n        if (typeof ack !== \"function\") {\n            debug(\"bad ack %s\", packet.id);\n            return;\n        }\n        delete this.acks[packet.id];\n        debug(\"calling ack %s with %j\", packet.id, packet.data);\n        // @ts-ignore FIXME ack is incorrectly inferred as 'never'\n        if (ack.withError) {\n            packet.data.unshift(null);\n        }\n        // @ts-ignore\n        ack.apply(this, packet.data);\n    }\n    /**\n     * Called upon server connect.\n     *\n     * @private\n     */\n    onconnect(id, pid) {\n        debug(\"socket connected with id %s\", id);\n        this.id = id;\n        this.recovered = pid && this._pid === pid;\n        this._pid = pid; // defined only if connection state recovery is enabled\n        this.connected = true;\n        this.emitBuffered();\n        this._drainQueue(true);\n        this.emitReserved(\"connect\");\n    }\n    /**\n     * Emit buffered events (received and emitted).\n     *\n     * @private\n     */\n    emitBuffered() {\n        this.receiveBuffer.forEach((args) => this.emitEvent(args));\n        this.receiveBuffer = [];\n        this.sendBuffer.forEach((packet) => {\n            this.notifyOutgoingListeners(packet);\n            this.packet(packet);\n        });\n        this.sendBuffer = [];\n    }\n    /**\n     * Called upon server disconnect.\n     *\n     * @private\n     */\n    ondisconnect() {\n        debug(\"server disconnect (%s)\", this.nsp);\n        this.destroy();\n        this.onclose(\"io server disconnect\");\n    }\n    /**\n     * Called upon forced client/server side disconnections,\n     * this method ensures the manager stops tracking us and\n     * that reconnections don't get triggered for this.\n     *\n     * @private\n     */\n    destroy() {\n        if (this.subs) {\n            // clean subscriptions to avoid reconnections\n            this.subs.forEach((subDestroy) => subDestroy());\n            this.subs = undefined;\n        }\n        this.io[\"_destroy\"](this);\n    }\n    /**\n     * Disconnects the socket manually. In that case, the socket will not try to reconnect.\n     *\n     * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.\n     *\n     * @example\n     * const socket = io();\n     *\n     * socket.on(\"disconnect\", (reason) => {\n     *   // console.log(reason); prints \"io client disconnect\"\n     * });\n     *\n     * socket.disconnect();\n     *\n     * @return self\n     */\n    disconnect() {\n        if (this.connected) {\n            debug(\"performing disconnect (%s)\", this.nsp);\n            this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });\n        }\n        // remove socket from pool\n        this.destroy();\n        if (this.connected) {\n            // fire events\n            this.onclose(\"io client disconnect\");\n        }\n        return this;\n    }\n    /**\n     * Alias for {@link disconnect()}.\n     *\n     * @return self\n     */\n    close() {\n        return this.disconnect();\n    }\n    /**\n     * Sets the compress flag.\n     *\n     * @example\n     * socket.compress(false).emit(\"hello\");\n     *\n     * @param compress - if `true`, compresses the sending data\n     * @return self\n     */\n    compress(compress) {\n        this.flags.compress = compress;\n        return this;\n    }\n    /**\n     * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not\n     * ready to send messages.\n     *\n     * @example\n     * socket.volatile.emit(\"hello\"); // the server may or may not receive it\n     *\n     * @returns self\n     */\n    get volatile() {\n        this.flags.volatile = true;\n        return this;\n    }\n    /**\n     * Sets a modifier for a subsequent event emission that the callback will be called with an error when the\n     * given number of milliseconds have elapsed without an acknowledgement from the server:\n     *\n     * @example\n     * socket.timeout(5000).emit(\"my-event\", (err) => {\n     *   if (err) {\n     *     // the server did not acknowledge the event in the given delay\n     *   }\n     * });\n     *\n     * @returns self\n     */\n    timeout(timeout) {\n        this.flags.timeout = timeout;\n        return this;\n    }\n    /**\n     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n     * callback.\n     *\n     * @example\n     * socket.onAny((event, ...args) => {\n     *   console.log(`got ${event}`);\n     * });\n     *\n     * @param listener\n     */\n    onAny(listener) {\n        this._anyListeners = this._anyListeners || [];\n        this._anyListeners.push(listener);\n        return this;\n    }\n    /**\n     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n     * callback. The listener is added to the beginning of the listeners array.\n     *\n     * @example\n     * socket.prependAny((event, ...args) => {\n     *   console.log(`got event ${event}`);\n     * });\n     *\n     * @param listener\n     */\n    prependAny(listener) {\n        this._anyListeners = this._anyListeners || [];\n        this._anyListeners.unshift(listener);\n        return this;\n    }\n    /**\n     * Removes the listener that will be fired when any event is emitted.\n     *\n     * @example\n     * const catchAllListener = (event, ...args) => {\n     *   console.log(`got event ${event}`);\n     * }\n     *\n     * socket.onAny(catchAllListener);\n     *\n     * // remove a specific listener\n     * socket.offAny(catchAllListener);\n     *\n     * // or remove all listeners\n     * socket.offAny();\n     *\n     * @param listener\n     */\n    offAny(listener) {\n        if (!this._anyListeners) {\n            return this;\n        }\n        if (listener) {\n            const listeners = this._anyListeners;\n            for (let i = 0; i < listeners.length; i++) {\n                if (listener === listeners[i]) {\n                    listeners.splice(i, 1);\n                    return this;\n                }\n            }\n        }\n        else {\n            this._anyListeners = [];\n        }\n        return this;\n    }\n    /**\n     * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n     * e.g. to remove listeners.\n     */\n    listenersAny() {\n        return this._anyListeners || [];\n    }\n    /**\n     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n     * callback.\n     *\n     * Note: acknowledgements sent to the server are not included.\n     *\n     * @example\n     * socket.onAnyOutgoing((event, ...args) => {\n     *   console.log(`sent event ${event}`);\n     * });\n     *\n     * @param listener\n     */\n    onAnyOutgoing(listener) {\n        this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n        this._anyOutgoingListeners.push(listener);\n        return this;\n    }\n    /**\n     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the\n     * callback. The listener is added to the beginning of the listeners array.\n     *\n     * Note: acknowledgements sent to the server are not included.\n     *\n     * @example\n     * socket.prependAnyOutgoing((event, ...args) => {\n     *   console.log(`sent event ${event}`);\n     * });\n     *\n     * @param listener\n     */\n    prependAnyOutgoing(listener) {\n        this._anyOutgoingListeners = this._anyOutgoingListeners || [];\n        this._anyOutgoingListeners.unshift(listener);\n        return this;\n    }\n    /**\n     * Removes the listener that will be fired when any event is emitted.\n     *\n     * @example\n     * const catchAllListener = (event, ...args) => {\n     *   console.log(`sent event ${event}`);\n     * }\n     *\n     * socket.onAnyOutgoing(catchAllListener);\n     *\n     * // remove a specific listener\n     * socket.offAnyOutgoing(catchAllListener);\n     *\n     * // or remove all listeners\n     * socket.offAnyOutgoing();\n     *\n     * @param [listener] - the catch-all listener (optional)\n     */\n    offAnyOutgoing(listener) {\n        if (!this._anyOutgoingListeners) {\n            return this;\n        }\n        if (listener) {\n            const listeners = this._anyOutgoingListeners;\n            for (let i = 0; i < listeners.length; i++) {\n                if (listener === listeners[i]) {\n                    listeners.splice(i, 1);\n                    return this;\n                }\n            }\n        }\n        else {\n            this._anyOutgoingListeners = [];\n        }\n        return this;\n    }\n    /**\n     * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,\n     * e.g. to remove listeners.\n     */\n    listenersAnyOutgoing() {\n        return this._anyOutgoingListeners || [];\n    }\n    /**\n     * Notify the listeners for each packet sent\n     *\n     * @param packet\n     *\n     * @private\n     */\n    notifyOutgoingListeners(packet) {\n        if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {\n            const listeners = this._anyOutgoingListeners.slice();\n            for (const listener of listeners) {\n                listener.apply(this, packet.data);\n            }\n        }\n    }\n}\nexports.Socket = Socket;\n", "\"use strict\";\n/**\n * Initialize backoff timer with `opts`.\n *\n * - `min` initial timeout in milliseconds [100]\n * - `max` max timeout [10000]\n * - `jitter` [0]\n * - `factor` [2]\n *\n * @param {Object} opts\n * @api public\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Backoff = Backoff;\nfunction Backoff(opts) {\n    opts = opts || {};\n    this.ms = opts.min || 100;\n    this.max = opts.max || 10000;\n    this.factor = opts.factor || 2;\n    this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;\n    this.attempts = 0;\n}\n/**\n * Return the backoff duration.\n *\n * @return {Number}\n * @api public\n */\nBackoff.prototype.duration = function () {\n    var ms = this.ms * Math.pow(this.factor, this.attempts++);\n    if (this.jitter) {\n        var rand = Math.random();\n        var deviation = Math.floor(rand * this.jitter * ms);\n        ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;\n    }\n    return Math.min(ms, this.max) | 0;\n};\n/**\n * Reset the number of attempts.\n *\n * @api public\n */\nBackoff.prototype.reset = function () {\n    this.attempts = 0;\n};\n/**\n * Set the minimum duration\n *\n * @api public\n */\nBackoff.prototype.setMin = function (min) {\n    this.ms = min;\n};\n/**\n * Set the maximum duration\n *\n * @api public\n */\nBackoff.prototype.setMax = function (max) {\n    this.max = max;\n};\n/**\n * Set the jitter\n *\n * @api public\n */\nBackoff.prototype.setJitter = function (jitter) {\n    this.jitter = jitter;\n};\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    var desc = Object.getOwnPropertyDescriptor(m, k);\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n    }\n    Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n    o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || (function () {\n    var ownKeys = function(o) {\n        ownKeys = Object.getOwnPropertyNames || function (o) {\n            var ar = [];\n            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n            return ar;\n        };\n        return ownKeys(o);\n    };\n    return function (mod) {\n        if (mod && mod.__esModule) return mod;\n        var result = {};\n        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n        __setModuleDefault(result, mod);\n        return result;\n    };\n})();\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Manager = void 0;\nconst engine_io_client_1 = require(\"engine.io-client\");\nconst socket_js_1 = require(\"./socket.js\");\nconst parser = __importStar(require(\"socket.io-parser\"));\nconst on_js_1 = require(\"./on.js\");\nconst backo2_js_1 = require(\"./contrib/backo2.js\");\nconst component_emitter_1 = require(\"@socket.io/component-emitter\");\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"socket.io-client:manager\"); // debug()\nclass Manager extends component_emitter_1.Emitter {\n    constructor(uri, opts) {\n        var _a;\n        super();\n        this.nsps = {};\n        this.subs = [];\n        if (uri && \"object\" === typeof uri) {\n            opts = uri;\n            uri = undefined;\n        }\n        opts = opts || {};\n        opts.path = opts.path || \"/socket.io\";\n        this.opts = opts;\n        (0, engine_io_client_1.installTimerFunctions)(this, opts);\n        this.reconnection(opts.reconnection !== false);\n        this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);\n        this.reconnectionDelay(opts.reconnectionDelay || 1000);\n        this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);\n        this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);\n        this.backoff = new backo2_js_1.Backoff({\n            min: this.reconnectionDelay(),\n            max: this.reconnectionDelayMax(),\n            jitter: this.randomizationFactor(),\n        });\n        this.timeout(null == opts.timeout ? 20000 : opts.timeout);\n        this._readyState = \"closed\";\n        this.uri = uri;\n        const _parser = opts.parser || parser;\n        this.encoder = new _parser.Encoder();\n        this.decoder = new _parser.Decoder();\n        this._autoConnect = opts.autoConnect !== false;\n        if (this._autoConnect)\n            this.open();\n    }\n    reconnection(v) {\n        if (!arguments.length)\n            return this._reconnection;\n        this._reconnection = !!v;\n        if (!v) {\n            this.skipReconnect = true;\n        }\n        return this;\n    }\n    reconnectionAttempts(v) {\n        if (v === undefined)\n            return this._reconnectionAttempts;\n        this._reconnectionAttempts = v;\n        return this;\n    }\n    reconnectionDelay(v) {\n        var _a;\n        if (v === undefined)\n            return this._reconnectionDelay;\n        this._reconnectionDelay = v;\n        (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);\n        return this;\n    }\n    randomizationFactor(v) {\n        var _a;\n        if (v === undefined)\n            return this._randomizationFactor;\n        this._randomizationFactor = v;\n        (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);\n        return this;\n    }\n    reconnectionDelayMax(v) {\n        var _a;\n        if (v === undefined)\n            return this._reconnectionDelayMax;\n        this._reconnectionDelayMax = v;\n        (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);\n        return this;\n    }\n    timeout(v) {\n        if (!arguments.length)\n            return this._timeout;\n        this._timeout = v;\n        return this;\n    }\n    /**\n     * Starts trying to reconnect if reconnection is enabled and we have not\n     * started reconnecting yet\n     *\n     * @private\n     */\n    maybeReconnectOnOpen() {\n        // Only try to reconnect if it's the first time we're connecting\n        if (!this._reconnecting &&\n            this._reconnection &&\n            this.backoff.attempts === 0) {\n            // keeps reconnection from firing twice for the same reconnection loop\n            this.reconnect();\n        }\n    }\n    /**\n     * Sets the current transport `socket`.\n     *\n     * @param {Function} fn - optional, callback\n     * @return self\n     * @public\n     */\n    open(fn) {\n        debug(\"readyState %s\", this._readyState);\n        if (~this._readyState.indexOf(\"open\"))\n            return this;\n        debug(\"opening %s\", this.uri);\n        this.engine = new engine_io_client_1.Socket(this.uri, this.opts);\n        const socket = this.engine;\n        const self = this;\n        this._readyState = \"opening\";\n        this.skipReconnect = false;\n        // emit `open`\n        const openSubDestroy = (0, on_js_1.on)(socket, \"open\", function () {\n            self.onopen();\n            fn && fn();\n        });\n        const onError = (err) => {\n            debug(\"error\");\n            this.cleanup();\n            this._readyState = \"closed\";\n            this.emitReserved(\"error\", err);\n            if (fn) {\n                fn(err);\n            }\n            else {\n                // Only do this if there is no fn to handle the error\n                this.maybeReconnectOnOpen();\n            }\n        };\n        // emit `error`\n        const errorSub = (0, on_js_1.on)(socket, \"error\", onError);\n        if (false !== this._timeout) {\n            const timeout = this._timeout;\n            debug(\"connect attempt will timeout after %d\", timeout);\n            // set timer\n            const timer = this.setTimeoutFn(() => {\n                debug(\"connect attempt timed out after %d\", timeout);\n                openSubDestroy();\n                onError(new Error(\"timeout\"));\n                socket.close();\n            }, timeout);\n            if (this.opts.autoUnref) {\n                timer.unref();\n            }\n            this.subs.push(() => {\n                this.clearTimeoutFn(timer);\n            });\n        }\n        this.subs.push(openSubDestroy);\n        this.subs.push(errorSub);\n        return this;\n    }\n    /**\n     * Alias for open()\n     *\n     * @return self\n     * @public\n     */\n    connect(fn) {\n        return this.open(fn);\n    }\n    /**\n     * Called upon transport open.\n     *\n     * @private\n     */\n    onopen() {\n        debug(\"open\");\n        // clear old subs\n        this.cleanup();\n        // mark as open\n        this._readyState = \"open\";\n        this.emitReserved(\"open\");\n        // add new subs\n        const socket = this.engine;\n        this.subs.push((0, on_js_1.on)(socket, \"ping\", this.onping.bind(this)), (0, on_js_1.on)(socket, \"data\", this.ondata.bind(this)), (0, on_js_1.on)(socket, \"error\", this.onerror.bind(this)), (0, on_js_1.on)(socket, \"close\", this.onclose.bind(this)), \n        // @ts-ignore\n        (0, on_js_1.on)(this.decoder, \"decoded\", this.ondecoded.bind(this)));\n    }\n    /**\n     * Called upon a ping.\n     *\n     * @private\n     */\n    onping() {\n        this.emitReserved(\"ping\");\n    }\n    /**\n     * Called with data.\n     *\n     * @private\n     */\n    ondata(data) {\n        try {\n            this.decoder.add(data);\n        }\n        catch (e) {\n            this.onclose(\"parse error\", e);\n        }\n    }\n    /**\n     * Called when parser fully decodes a packet.\n     *\n     * @private\n     */\n    ondecoded(packet) {\n        // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a \"parse error\"\n        (0, engine_io_client_1.nextTick)(() => {\n            this.emitReserved(\"packet\", packet);\n        }, this.setTimeoutFn);\n    }\n    /**\n     * Called upon socket error.\n     *\n     * @private\n     */\n    onerror(err) {\n        debug(\"error\", err);\n        this.emitReserved(\"error\", err);\n    }\n    /**\n     * Creates a new socket for the given `nsp`.\n     *\n     * @return {Socket}\n     * @public\n     */\n    socket(nsp, opts) {\n        let socket = this.nsps[nsp];\n        if (!socket) {\n            socket = new socket_js_1.Socket(this, nsp, opts);\n            this.nsps[nsp] = socket;\n        }\n        else if (this._autoConnect && !socket.active) {\n            socket.connect();\n        }\n        return socket;\n    }\n    /**\n     * Called upon a socket close.\n     *\n     * @param socket\n     * @private\n     */\n    _destroy(socket) {\n        const nsps = Object.keys(this.nsps);\n        for (const nsp of nsps) {\n            const socket = this.nsps[nsp];\n            if (socket.active) {\n                debug(\"socket %s is still active, skipping close\", nsp);\n                return;\n            }\n        }\n        this._close();\n    }\n    /**\n     * Writes a packet.\n     *\n     * @param packet\n     * @private\n     */\n    _packet(packet) {\n        debug(\"writing packet %j\", packet);\n        const encodedPackets = this.encoder.encode(packet);\n        for (let i = 0; i < encodedPackets.length; i++) {\n            this.engine.write(encodedPackets[i], packet.options);\n        }\n    }\n    /**\n     * Clean up transport subscriptions and packet buffer.\n     *\n     * @private\n     */\n    cleanup() {\n        debug(\"cleanup\");\n        this.subs.forEach((subDestroy) => subDestroy());\n        this.subs.length = 0;\n        this.decoder.destroy();\n    }\n    /**\n     * Close the current socket.\n     *\n     * @private\n     */\n    _close() {\n        debug(\"disconnect\");\n        this.skipReconnect = true;\n        this._reconnecting = false;\n        this.onclose(\"forced close\");\n    }\n    /**\n     * Alias for close()\n     *\n     * @private\n     */\n    disconnect() {\n        return this._close();\n    }\n    /**\n     * Called when:\n     *\n     * - the low-level engine is closed\n     * - the parser encountered a badly formatted packet\n     * - all sockets are disconnected\n     *\n     * @private\n     */\n    onclose(reason, description) {\n        var _a;\n        debug(\"closed due to %s\", reason);\n        this.cleanup();\n        (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();\n        this.backoff.reset();\n        this._readyState = \"closed\";\n        this.emitReserved(\"close\", reason, description);\n        if (this._reconnection && !this.skipReconnect) {\n            this.reconnect();\n        }\n    }\n    /**\n     * Attempt a reconnection.\n     *\n     * @private\n     */\n    reconnect() {\n        if (this._reconnecting || this.skipReconnect)\n            return this;\n        const self = this;\n        if (this.backoff.attempts >= this._reconnectionAttempts) {\n            debug(\"reconnect failed\");\n            this.backoff.reset();\n            this.emitReserved(\"reconnect_failed\");\n            this._reconnecting = false;\n        }\n        else {\n            const delay = this.backoff.duration();\n            debug(\"will wait %dms before reconnect attempt\", delay);\n            this._reconnecting = true;\n            const timer = this.setTimeoutFn(() => {\n                if (self.skipReconnect)\n                    return;\n                debug(\"attempting reconnect\");\n                this.emitReserved(\"reconnect_attempt\", self.backoff.attempts);\n                // check again for the case socket closed in above events\n                if (self.skipReconnect)\n                    return;\n                self.open((err) => {\n                    if (err) {\n                        debug(\"reconnect attempt error\");\n                        self._reconnecting = false;\n                        self.reconnect();\n                        this.emitReserved(\"reconnect_error\", err);\n                    }\n                    else {\n                        debug(\"reconnect success\");\n                        self.onreconnect();\n                    }\n                });\n            }, delay);\n            if (this.opts.autoUnref) {\n                timer.unref();\n            }\n            this.subs.push(() => {\n                this.clearTimeoutFn(timer);\n            });\n        }\n    }\n    /**\n     * Called upon successful reconnect.\n     *\n     * @private\n     */\n    onreconnect() {\n        const attempt = this.backoff.attempts;\n        this._reconnecting = false;\n        this.backoff.reset();\n        this.emitReserved(\"reconnect\", attempt);\n    }\n}\nexports.Manager = Manager;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WebTransport = exports.WebSocket = exports.NodeWebSocket = exports.XHR = exports.NodeXHR = exports.Fetch = exports.Socket = exports.Manager = exports.protocol = void 0;\nexports.io = lookup;\nexports.connect = lookup;\nexports.default = lookup;\nconst url_js_1 = require(\"./url.js\");\nconst manager_js_1 = require(\"./manager.js\");\nObject.defineProperty(exports, \"Manager\", { enumerable: true, get: function () { return manager_js_1.Manager; } });\nconst socket_js_1 = require(\"./socket.js\");\nObject.defineProperty(exports, \"Socket\", { enumerable: true, get: function () { return socket_js_1.Socket; } });\nconst debug_1 = __importDefault(require(\"debug\")); // debug()\nconst debug = (0, debug_1.default)(\"socket.io-client\"); // debug()\n/**\n * Managers cache.\n */\nconst cache = {};\nfunction lookup(uri, opts) {\n    if (typeof uri === \"object\") {\n        opts = uri;\n        uri = undefined;\n    }\n    opts = opts || {};\n    const parsed = (0, url_js_1.url)(uri, opts.path || \"/socket.io\");\n    const source = parsed.source;\n    const id = parsed.id;\n    const path = parsed.path;\n    const sameNamespace = cache[id] && path in cache[id][\"nsps\"];\n    const newConnection = opts.forceNew ||\n        opts[\"force new connection\"] ||\n        false === opts.multiplex ||\n        sameNamespace;\n    let io;\n    if (newConnection) {\n        debug(\"ignoring socket cache for %s\", source);\n        io = new manager_js_1.Manager(source, opts);\n    }\n    else {\n        if (!cache[id]) {\n            debug(\"new io instance for %s\", source);\n            cache[id] = new manager_js_1.Manager(source, opts);\n        }\n        io = cache[id];\n    }\n    if (parsed.query && !opts.query) {\n        opts.query = parsed.queryKey;\n    }\n    return io.socket(parsed.path, opts);\n}\n// so that \"lookup\" can be used both as a function (e.g. `io(...)`) and as a\n// namespace (e.g. `io.connect(...)`), for backward compatibility\nObject.assign(lookup, {\n    Manager: manager_js_1.Manager,\n    Socket: socket_js_1.Socket,\n    io: lookup,\n    connect: lookup,\n});\n/**\n * Protocol version.\n *\n * @public\n */\nvar socket_io_parser_1 = require(\"socket.io-parser\");\nObject.defineProperty(exports, \"protocol\", { enumerable: true, get: function () { return socket_io_parser_1.protocol; } });\nvar engine_io_client_1 = require(\"engine.io-client\");\nObject.defineProperty(exports, \"Fetch\", { enumerable: true, get: function () { return engine_io_client_1.Fetch; } });\nObject.defineProperty(exports, \"NodeXHR\", { enumerable: true, get: function () { return engine_io_client_1.NodeXHR; } });\nObject.defineProperty(exports, \"XHR\", { enumerable: true, get: function () { return engine_io_client_1.XHR; } });\nObject.defineProperty(exports, \"NodeWebSocket\", { enumerable: true, get: function () { return engine_io_client_1.NodeWebSocket; } });\nObject.defineProperty(exports, \"WebSocket\", { enumerable: true, get: function () { return engine_io_client_1.WebSocket; } });\nObject.defineProperty(exports, \"WebTransport\", { enumerable: true, get: function () { return engine_io_client_1.WebTransport; } });\n\nmodule.exports = lookup;\n", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst Emitter = require(\"component-emitter\");\n\nconst has = require(\"@uppy/utils/lib/hasProperty\");\n\nconst NetworkError = require(\"@uppy/utils/lib/NetworkError\");\n\nconst fetchWithNetworkError = require(\"@uppy/utils/lib/fetchWithNetworkError\");\n\nconst parseUrl = require(\"./parseUrl.js\"); // We used to lazy load socket.io to avoid a console error\n// in IE 10 when the Transloadit plugin is not used.\n// (The console.error call comes from `buffer`. I\n// think we actually don't use that part of socket.io\n// at all\u2026)\n// TODO: remove this hack in the next release.\n\n\nlet socketIo;\n\nfunction requireSocketIo() {\n  var _socketIo;\n\n  // eslint-disable-next-line no-return-assign, no-restricted-globals, global-require, no-undef\n  return (_socketIo = socketIo) != null ? _socketIo : socketIo = require('socket.io-client');\n}\n\nconst ASSEMBLY_UPLOADING = 'ASSEMBLY_UPLOADING';\nconst ASSEMBLY_EXECUTING = 'ASSEMBLY_EXECUTING';\nconst ASSEMBLY_COMPLETED = 'ASSEMBLY_COMPLETED';\nconst statusOrder = [ASSEMBLY_UPLOADING, ASSEMBLY_EXECUTING, ASSEMBLY_COMPLETED];\n/**\n * Check that an assembly status is equal to or larger than some desired status.\n * It checks for things that are larger so that a comparison like this works,\n * when the old assembly status is UPLOADING but the new is FINISHED:\n *\n * !isStatus(oldStatus, ASSEMBLY_EXECUTING) && isStatus(newState, ASSEMBLY_EXECUTING)\n *\n * \u2026so that we can emit the 'executing' event even if the execution step was so\n * fast that we missed it.\n */\n\nfunction isStatus(status, test) {\n  return statusOrder.indexOf(status) >= statusOrder.indexOf(test);\n}\n\nvar _rateLimitedQueue = /*#__PURE__*/_classPrivateFieldLooseKey(\"rateLimitedQueue\");\n\nvar _fetchWithNetworkError = /*#__PURE__*/_classPrivateFieldLooseKey(\"fetchWithNetworkError\");\n\nvar _previousFetchStatusStillPending = /*#__PURE__*/_classPrivateFieldLooseKey(\"previousFetchStatusStillPending\");\n\nvar _onFinished = /*#__PURE__*/_classPrivateFieldLooseKey(\"onFinished\");\n\nvar _connectSocket = /*#__PURE__*/_classPrivateFieldLooseKey(\"connectSocket\");\n\nvar _onError = /*#__PURE__*/_classPrivateFieldLooseKey(\"onError\");\n\nvar _beginPolling = /*#__PURE__*/_classPrivateFieldLooseKey(\"beginPolling\");\n\nvar _fetchStatus = /*#__PURE__*/_classPrivateFieldLooseKey(\"fetchStatus\");\n\nvar _diffStatus = /*#__PURE__*/_classPrivateFieldLooseKey(\"diffStatus\");\n\nclass TransloaditAssembly extends Emitter {\n  constructor(assembly, rateLimitedQueue) {\n    super(); // The current assembly status.\n\n    Object.defineProperty(this, _diffStatus, {\n      value: _diffStatus2\n    });\n    Object.defineProperty(this, _fetchStatus, {\n      value: _fetchStatus2\n    });\n    Object.defineProperty(this, _beginPolling, {\n      value: _beginPolling2\n    });\n    Object.defineProperty(this, _onError, {\n      value: _onError2\n    });\n    Object.defineProperty(this, _connectSocket, {\n      value: _connectSocket2\n    });\n    Object.defineProperty(this, _onFinished, {\n      value: _onFinished2\n    });\n    Object.defineProperty(this, _rateLimitedQueue, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _fetchWithNetworkError, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _previousFetchStatusStillPending, {\n      writable: true,\n      value: false\n    });\n    this.status = assembly; // The socket.io connection.\n\n    this.socket = null; // The interval timer for full status updates.\n\n    this.pollInterval = null; // Whether this assembly has been closed (finished or errored)\n\n    this.closed = false;\n    _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue] = rateLimitedQueue;\n    _classPrivateFieldLooseBase(this, _fetchWithNetworkError)[_fetchWithNetworkError] = rateLimitedQueue.wrapPromiseFunction(fetchWithNetworkError);\n  }\n\n  connect() {\n    _classPrivateFieldLooseBase(this, _connectSocket)[_connectSocket]();\n\n    _classPrivateFieldLooseBase(this, _beginPolling)[_beginPolling]();\n  }\n\n  update() {\n    return _classPrivateFieldLooseBase(this, _fetchStatus)[_fetchStatus]({\n      diff: true\n    });\n  }\n  /**\n   * Update this assembly's status with a full new object. Events will be\n   * emitted for status changes, new files, and new results.\n   *\n   * @param {object} next The new assembly status object.\n   */\n\n\n  updateStatus(next) {\n    _classPrivateFieldLooseBase(this, _diffStatus)[_diffStatus](this.status, next);\n\n    this.status = next;\n  }\n  /**\n   * Diff two assembly statuses, and emit the events necessary to go from `prev`\n   * to `next`.\n   *\n   * @param {object} prev The previous assembly status.\n   * @param {object} next The new assembly status.\n   */\n\n\n  /**\n   * Stop updating this assembly.\n   */\n  close() {\n    this.closed = true;\n\n    if (this.socket) {\n      this.socket.disconnect();\n      this.socket = null;\n    }\n\n    clearInterval(this.pollInterval);\n    this.pollInterval = null;\n  }\n\n}\n\nfunction _onFinished2() {\n  this.emit('finished');\n  this.close();\n}\n\nfunction _connectSocket2() {\n  const parsed = parseUrl(this.status.websocket_url);\n  const socket = requireSocketIo().connect(parsed.origin, {\n    transports: ['websocket'],\n    path: parsed.pathname\n  });\n  socket.on('connect', () => {\n    socket.emit('assembly_connect', {\n      id: this.status.assembly_id\n    });\n    this.emit('connect');\n  });\n  socket.on('connect_error', () => {\n    socket.disconnect();\n    this.socket = null;\n  });\n  socket.on('assembly_finished', () => {\n    _classPrivateFieldLooseBase(this, _onFinished)[_onFinished]();\n  });\n  socket.on('assembly_upload_finished', file => {\n    this.emit('upload', file);\n    this.status.uploads.push(file);\n  });\n  socket.on('assembly_uploading_finished', () => {\n    this.emit('executing');\n  });\n  socket.on('assembly_upload_meta_data_extracted', () => {\n    this.emit('metadata');\n\n    _classPrivateFieldLooseBase(this, _fetchStatus)[_fetchStatus]({\n      diff: false\n    });\n  });\n  socket.on('assembly_result_finished', (stepName, result) => {\n    this.emit('result', stepName, result);\n\n    if (!this.status.results[stepName]) {\n      this.status.results[stepName] = [];\n    }\n\n    this.status.results[stepName].push(result);\n  });\n  socket.on('assembly_error', err => {\n    _classPrivateFieldLooseBase(this, _onError)[_onError](err); // Refetch for updated status code\n\n\n    _classPrivateFieldLooseBase(this, _fetchStatus)[_fetchStatus]({\n      diff: false\n    });\n  });\n  this.socket = socket;\n}\n\nfunction _onError2(err) {\n  this.emit('error', Object.assign(new Error(err.message), err));\n  this.close();\n}\n\nfunction _beginPolling2() {\n  this.pollInterval = setInterval(() => {\n    if (!this.socket || !this.socket.connected) {\n      _classPrivateFieldLooseBase(this, _fetchStatus)[_fetchStatus]();\n    }\n  }, 2000);\n}\n\nasync function _fetchStatus2(_temp) {\n  let {\n    diff = true\n  } = _temp === void 0 ? {} : _temp;\n  if (this.closed || _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue].isPaused || _classPrivateFieldLooseBase(this, _previousFetchStatusStillPending)[_previousFetchStatusStillPending]) return;\n\n  try {\n    _classPrivateFieldLooseBase(this, _previousFetchStatusStillPending)[_previousFetchStatusStillPending] = true;\n    const response = await _classPrivateFieldLooseBase(this, _fetchWithNetworkError)[_fetchWithNetworkError](this.status.assembly_ssl_url);\n    _classPrivateFieldLooseBase(this, _previousFetchStatusStillPending)[_previousFetchStatusStillPending] = false;\n    if (this.closed) return;\n\n    if (response.status === 429) {\n      _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue].rateLimit(2000);\n\n      return;\n    }\n\n    if (!response.ok) {\n      _classPrivateFieldLooseBase(this, _onError)[_onError](new NetworkError(response.statusText));\n\n      return;\n    }\n\n    const status = await response.json(); // Avoid updating if we closed during this request's lifetime.\n\n    if (this.closed) return;\n    this.emit('status', status);\n\n    if (diff) {\n      this.updateStatus(status);\n    } else {\n      this.status = status;\n    }\n  } catch (err) {\n    _classPrivateFieldLooseBase(this, _onError)[_onError](err);\n  }\n}\n\nfunction _diffStatus2(prev, next) {\n  const prevStatus = prev.ok;\n  const nextStatus = next.ok;\n\n  if (next.error && !prev.error) {\n    return _classPrivateFieldLooseBase(this, _onError)[_onError](next);\n  } // Desired emit order:\n  //  - executing\n  //  - (n \u00D7 upload)\n  //  - metadata\n  //  - (m \u00D7 result)\n  //  - finished\n  // The below checks run in this order, that way even if we jump from\n  // UPLOADING straight to FINISHED all the events are emitted as expected.\n\n\n  const nowExecuting = isStatus(nextStatus, ASSEMBLY_EXECUTING) && !isStatus(prevStatus, ASSEMBLY_EXECUTING);\n\n  if (nowExecuting) {\n    // Without WebSockets, this is our only way to tell if uploading finished.\n    // Hence, we emit this just before the 'upload's and before the 'metadata'\n    // event for the most intuitive ordering, corresponding to the _usual_\n    // ordering (if not guaranteed) that you'd get on the WebSocket.\n    this.emit('executing');\n  } // Find new uploaded files.\n\n\n  Object.keys(next.uploads).filter(upload => !has(prev.uploads, upload)).forEach(upload => {\n    this.emit('upload', next.uploads[upload]);\n  });\n\n  if (nowExecuting) {\n    this.emit('metadata');\n  } // Find new results.\n\n\n  Object.keys(next.results).forEach(stepName => {\n    const nextResults = next.results[stepName];\n    const prevResults = prev.results[stepName];\n    nextResults.filter(n => !prevResults || !prevResults.some(p => p.id === n.id)).forEach(result => {\n      this.emit('result', stepName, result);\n    });\n  });\n\n  if (isStatus(nextStatus, ASSEMBLY_COMPLETED) && !isStatus(prevStatus, ASSEMBLY_COMPLETED)) {\n    this.emit('finished');\n  }\n\n  return undefined;\n}\n\nmodule.exports = TransloaditAssembly;", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst fetchWithNetworkError = require(\"@uppy/utils/lib/fetchWithNetworkError\");\n\nconst ASSEMBLIES_ENDPOINT = '/assemblies';\n/**\n * A Barebones HTTP API client for Transloadit.\n */\n\nvar _headers = /*#__PURE__*/_classPrivateFieldLooseKey(\"headers\");\n\nvar _fetchWithNetworkError = /*#__PURE__*/_classPrivateFieldLooseKey(\"fetchWithNetworkError\");\n\nvar _fetchJSON = /*#__PURE__*/_classPrivateFieldLooseKey(\"fetchJSON\");\n\nvar _reportError = /*#__PURE__*/_classPrivateFieldLooseKey(\"reportError\");\n\nclass Client {\n  constructor(_opts) {\n    if (_opts === void 0) {\n      _opts = {};\n    }\n\n    Object.defineProperty(this, _fetchJSON, {\n      value: _fetchJSON2\n    });\n    Object.defineProperty(this, _headers, {\n      writable: true,\n      value: {}\n    });\n    Object.defineProperty(this, _fetchWithNetworkError, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _reportError, {\n      writable: true,\n      value: (err, params) => {\n        if (this.opts.errorReporting === false) {\n          throw err;\n        }\n\n        const opts = {\n          type: params.type\n        };\n\n        if (params.assembly) {\n          opts.assembly = params.assembly.assembly_id;\n          opts.instance = params.assembly.instance;\n        }\n\n        if (params.url) {\n          opts.endpoint = params.url;\n        }\n\n        this.submitError(err, opts).catch(() => {// not much we can do then is there\n        });\n        throw err;\n      }\n    });\n    this.opts = _opts;\n\n    if (this.opts.client != null) {\n      _classPrivateFieldLooseBase(this, _headers)[_headers]['Transloadit-Client'] = this.opts.client;\n    }\n\n    _classPrivateFieldLooseBase(this, _fetchWithNetworkError)[_fetchWithNetworkError] = this.opts.rateLimitedQueue.wrapPromiseFunction(fetchWithNetworkError);\n  }\n  /**\n   * @param  {RequestInfo | URL} input\n   * @param  {RequestInit} init\n   * @returns {Promise<any>}\n   */\n\n\n  /**\n   * Create a new assembly.\n   *\n   * @param {object} options\n   * @param {string|object} options.params\n   * @param {object} options.fields\n   * @param {string} options.signature\n   * @param {number} options.expectedFiles\n   */\n  createAssembly(_ref) {\n    let {\n      params,\n      fields,\n      signature,\n      expectedFiles\n    } = _ref;\n    const data = new FormData();\n    data.append('params', typeof params === 'string' ? params : JSON.stringify(params));\n\n    if (signature) {\n      data.append('signature', signature);\n    }\n\n    Object.keys(fields).forEach(key => {\n      data.append(key, fields[key]);\n    });\n    data.append('num_expected_upload_files', expectedFiles);\n    const url = new URL(ASSEMBLIES_ENDPOINT, `${this.opts.service}`).href;\n    return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {\n      method: 'post',\n      headers: _classPrivateFieldLooseBase(this, _headers)[_headers],\n      body: data\n    }).catch(err => _classPrivateFieldLooseBase(this, _reportError)[_reportError](err, {\n      url,\n      type: 'API_ERROR'\n    }));\n  }\n  /**\n   * Reserve resources for a file in an Assembly. Then addFile can be used later.\n   *\n   * @param {object} assembly\n   * @param {UppyFile} file\n   */\n\n\n  reserveFile(assembly, file) {\n    const size = encodeURIComponent(file.size);\n    const url = `${assembly.assembly_ssl_url}/reserve_file?size=${size}`;\n    return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {\n      method: 'post',\n      headers: _classPrivateFieldLooseBase(this, _headers)[_headers]\n    }).catch(err => _classPrivateFieldLooseBase(this, _reportError)[_reportError](err, {\n      assembly,\n      file,\n      url,\n      type: 'API_ERROR'\n    }));\n  }\n  /**\n   * Import a remote file to an Assembly.\n   *\n   * @param {object} assembly\n   * @param {UppyFile} file\n   */\n\n\n  addFile(assembly, file) {\n    if (!file.uploadURL) {\n      return Promise.reject(new Error('File does not have an `uploadURL`.'));\n    }\n\n    const size = encodeURIComponent(file.size);\n    const uploadUrl = encodeURIComponent(file.uploadURL);\n    const filename = encodeURIComponent(file.name);\n    const fieldname = 'file';\n    const qs = `size=${size}&filename=${filename}&fieldname=${fieldname}&s3Url=${uploadUrl}`;\n    const url = `${assembly.assembly_ssl_url}/add_file?${qs}`;\n    return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {\n      method: 'post',\n      headers: _classPrivateFieldLooseBase(this, _headers)[_headers]\n    }).catch(err => _classPrivateFieldLooseBase(this, _reportError)[_reportError](err, {\n      assembly,\n      file,\n      url,\n      type: 'API_ERROR'\n    }));\n  }\n  /**\n   * Update the number of expected files in an already created assembly.\n   *\n   * @param {object} assembly\n   * @param {number} num_expected_upload_files\n   */\n\n\n  updateNumberOfFilesInAssembly(assembly, num_expected_upload_files) {\n    const url = new URL(assembly.assembly_ssl_url);\n    url.pathname = '/update_assemblies';\n    const body = JSON.stringify({\n      assembly_updates: [{\n        assembly_id: assembly.assembly_id,\n        num_expected_upload_files\n      }]\n    });\n    return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {\n      method: 'post',\n      headers: _classPrivateFieldLooseBase(this, _headers)[_headers],\n      body\n    }).catch(err => _classPrivateFieldLooseBase(this, _reportError)[_reportError](err, {\n      url,\n      type: 'API_ERROR'\n    }));\n  }\n  /**\n   * Cancel a running Assembly.\n   *\n   * @param {object} assembly\n   */\n\n\n  cancelAssembly(assembly) {\n    const url = assembly.assembly_ssl_url;\n    return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {\n      method: 'delete',\n      headers: _classPrivateFieldLooseBase(this, _headers)[_headers]\n    }).catch(err => _classPrivateFieldLooseBase(this, _reportError)[_reportError](err, {\n      url,\n      type: 'API_ERROR'\n    }));\n  }\n  /**\n   * Get the current status for an assembly.\n   *\n   * @param {string} url The status endpoint of the assembly.\n   */\n\n\n  getAssemblyStatus(url) {\n    return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](url, {\n      headers: _classPrivateFieldLooseBase(this, _headers)[_headers]\n    }).catch(err => _classPrivateFieldLooseBase(this, _reportError)[_reportError](err, {\n      url,\n      type: 'STATUS_ERROR'\n    }));\n  }\n\n  submitError(err, _temp) {\n    let {\n      endpoint,\n      instance,\n      assembly\n    } = _temp === void 0 ? {} : _temp;\n    const message = err.details ? `${err.message} (${err.details})` : err.message;\n    return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON]('https://transloaditstatus.com/client_error', {\n      method: 'post',\n      body: JSON.stringify({\n        endpoint,\n        instance,\n        assembly_id: assembly,\n        agent: typeof navigator !== 'undefined' ? navigator.userAgent : '',\n        client: this.opts.client,\n        error: message\n      })\n    });\n  }\n\n}\n\nfunction _fetchJSON2() {\n  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n    args[_key] = arguments[_key];\n  }\n\n  return _classPrivateFieldLooseBase(this, _fetchWithNetworkError)[_fetchWithNetworkError](...args).then(response => {\n    if (response.status === 429) {\n      this.opts.rateLimitedQueue.rateLimit(2000);\n      return _classPrivateFieldLooseBase(this, _fetchJSON)[_fetchJSON](...args);\n    }\n\n    if (!response.ok) {\n      const serverError = new Error(response.statusText);\n      serverError.statusCode = response.status;\n      if (!`${args[0]}`.endsWith(ASSEMBLIES_ENDPOINT)) return Promise.reject(serverError); // Failed assembly requests should return a more detailed error in JSON.\n\n      return response.json().then(assembly => {\n        if (!assembly.error) throw serverError;\n        const error = new Error(assembly.error);\n        error.details = assembly.message;\n        error.assembly = assembly;\n\n        if (assembly.assembly_id) {\n          error.details += ` Assembly ID: ${assembly.assembly_id}`;\n        }\n\n        throw error;\n      }, err => {\n        // eslint-disable-next-line no-param-reassign\n        err.cause = serverError;\n        throw err;\n      });\n    }\n\n    return response.json();\n  });\n}\n\nmodule.exports = Client;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.validateParams = validateParams;\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst ErrorWithCause = require(\"@uppy/utils/lib/ErrorWithCause\");\n/**\n * Check that Assembly parameters are present and include all required fields.\n */\n\n\nfunction validateParams(params) {\n  if (params == null) {\n    throw new Error('Transloadit: The `params` option is required.');\n  }\n\n  if (typeof params === 'string') {\n    try {\n      // eslint-disable-next-line no-param-reassign\n      params = JSON.parse(params);\n    } catch (err) {\n      // Tell the user that this is not an Uppy bug!\n      throw new ErrorWithCause('Transloadit: The `params` option is a malformed JSON string.', {\n        cause: err\n      });\n    }\n  }\n\n  if (!params.auth || !params.auth.key) {\n    throw new Error('Transloadit: The `params.auth.key` option is required. ' + 'You can find your Transloadit API key at https://transloadit.com/c/template-credentials');\n  }\n}\n/**\n * Combine Assemblies with the same options into a single Assembly for all the\n * relevant files.\n */\n\n\nfunction dedupe(list) {\n  const dedupeMap = Object.create(null);\n\n  for (const {\n    fileIDs,\n    options\n  } of list.filter(Boolean)) {\n    const id = JSON.stringify(options);\n\n    if (id in dedupeMap) {\n      dedupeMap[id].fileIDArrays.push(fileIDs);\n    } else {\n      dedupeMap[id] = {\n        options,\n        fileIDArrays: [fileIDs]\n      };\n    }\n  }\n\n  return Object.values(dedupeMap).map(_ref => {\n    let {\n      options,\n      fileIDArrays\n    } = _ref;\n    return {\n      options,\n      fileIDs: fileIDArrays.flat(1)\n    };\n  });\n}\n/**\n * Turn Transloadit plugin options and a list of files into a list of Assembly\n * options.\n */\n\n\nvar _getAssemblyOptions = /*#__PURE__*/_classPrivateFieldLooseKey(\"getAssemblyOptions\");\n\nclass AssemblyOptions {\n  constructor(files, opts) {\n    Object.defineProperty(this, _getAssemblyOptions, {\n      value: _getAssemblyOptions2\n    });\n    this.files = files;\n    this.opts = opts;\n  }\n  /**\n   * Get Assembly options for a file.\n   */\n\n\n  /**\n   * Generate a set of Assemblies that will handle the upload.\n   * Returns a Promise for an object with keys:\n   *  - fileIDs - an array of file IDs to add to this Assembly\n   *  - options - Assembly options\n   */\n  async build() {\n    const options = this.opts;\n\n    if (this.files.length > 0) {\n      return Promise.all(this.files.map(file => _classPrivateFieldLooseBase(this, _getAssemblyOptions)[_getAssemblyOptions](file))).then(dedupe);\n    }\n\n    if (options.alwaysRunAssembly) {\n      // No files, just generate one Assembly\n      const assemblyOptions = await options.getAssemblyOptions(null, options);\n      validateParams(assemblyOptions.params);\n      return [{\n        fileIDs: this.files.map(file => file.id),\n        options: assemblyOptions\n      }];\n    } // If there are no files and we do not `alwaysRunAssembly`,\n    // don't do anything.\n\n\n    return [];\n  }\n\n}\n\nasync function _getAssemblyOptions2(file) {\n  if (file == null) return undefined;\n  const options = this.opts;\n  const assemblyOptions = await options.getAssemblyOptions(file, options); // We check if the file is present here again, because it could had been\n  // removed during the await, e.g. if the user hit cancel while we were\n  // waiting for the options.\n\n  if (file == null) return undefined;\n\n  if (Array.isArray(assemblyOptions.fields)) {\n    assemblyOptions.fields = Object.fromEntries(assemblyOptions.fields.map(fieldName => [fieldName, file.meta[fieldName]]));\n  } else if (assemblyOptions.fields == null) {\n    assemblyOptions.fields = {};\n  }\n\n  validateParams(assemblyOptions.params);\n  return {\n    fileIDs: [file.id],\n    options: assemblyOptions\n  };\n}\n\nmodule.exports = AssemblyOptions;\n// Backward compatibility: we want `validateParams` to keep being a static\n// method of `AssemblyOptions` to avoid a breaking change.\nAssemblyOptions.validateParams = validateParams; // TODO: remove this line on the next major", "\"use strict\";\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst Emitter = require(\"component-emitter\");\n/**\n * Track completion of multiple assemblies.\n *\n * Emits 'assembly-complete' when an assembly completes.\n * Emits 'assembly-error' when an assembly fails.\n * Exposes a `.promise` property that resolves when all assemblies have\n * completed (or failed).\n */\n\n\nvar _assemblyIDs = /*#__PURE__*/_classPrivateFieldLooseKey(\"assemblyIDs\");\n\nvar _reject = /*#__PURE__*/_classPrivateFieldLooseKey(\"reject\");\n\nvar _remaining = /*#__PURE__*/_classPrivateFieldLooseKey(\"remaining\");\n\nvar _resolve = /*#__PURE__*/_classPrivateFieldLooseKey(\"resolve\");\n\nvar _uppy = /*#__PURE__*/_classPrivateFieldLooseKey(\"uppy\");\n\nvar _watching = /*#__PURE__*/_classPrivateFieldLooseKey(\"watching\");\n\nvar _onAssemblyComplete = /*#__PURE__*/_classPrivateFieldLooseKey(\"onAssemblyComplete\");\n\nvar _onAssemblyCancel = /*#__PURE__*/_classPrivateFieldLooseKey(\"onAssemblyCancel\");\n\nvar _onAssemblyError = /*#__PURE__*/_classPrivateFieldLooseKey(\"onAssemblyError\");\n\nvar _onImportError = /*#__PURE__*/_classPrivateFieldLooseKey(\"onImportError\");\n\nvar _checkAllComplete = /*#__PURE__*/_classPrivateFieldLooseKey(\"checkAllComplete\");\n\nvar _removeListeners = /*#__PURE__*/_classPrivateFieldLooseKey(\"removeListeners\");\n\nvar _addListeners = /*#__PURE__*/_classPrivateFieldLooseKey(\"addListeners\");\n\nclass TransloaditAssemblyWatcher extends Emitter {\n  constructor(uppy, assemblyIDs) {\n    super();\n    Object.defineProperty(this, _addListeners, {\n      value: _addListeners2\n    });\n    Object.defineProperty(this, _removeListeners, {\n      value: _removeListeners2\n    });\n    Object.defineProperty(this, _checkAllComplete, {\n      value: _checkAllComplete2\n    });\n    Object.defineProperty(this, _watching, {\n      value: _watching2\n    });\n    Object.defineProperty(this, _assemblyIDs, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _reject, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _remaining, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _resolve, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _uppy, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _onAssemblyComplete, {\n      writable: true,\n      value: assembly => {\n        if (!_classPrivateFieldLooseBase(this, _watching)[_watching](assembly.assembly_id)) {\n          return;\n        }\n\n        _classPrivateFieldLooseBase(this, _uppy)[_uppy].log(`[Transloadit] AssemblyWatcher: Got Assembly finish ${assembly.assembly_id}`);\n\n        this.emit('assembly-complete', assembly.assembly_id);\n\n        _classPrivateFieldLooseBase(this, _checkAllComplete)[_checkAllComplete]();\n      }\n    });\n    Object.defineProperty(this, _onAssemblyCancel, {\n      writable: true,\n      value: assembly => {\n        if (!_classPrivateFieldLooseBase(this, _watching)[_watching](assembly.assembly_id)) {\n          return;\n        }\n\n        _classPrivateFieldLooseBase(this, _checkAllComplete)[_checkAllComplete]();\n      }\n    });\n    Object.defineProperty(this, _onAssemblyError, {\n      writable: true,\n      value: (assembly, error) => {\n        if (!_classPrivateFieldLooseBase(this, _watching)[_watching](assembly.assembly_id)) {\n          return;\n        }\n\n        _classPrivateFieldLooseBase(this, _uppy)[_uppy].log(`[Transloadit] AssemblyWatcher: Got Assembly error ${assembly.assembly_id}`);\n\n        _classPrivateFieldLooseBase(this, _uppy)[_uppy].log(error);\n\n        this.emit('assembly-error', assembly.assembly_id, error);\n\n        _classPrivateFieldLooseBase(this, _checkAllComplete)[_checkAllComplete]();\n      }\n    });\n    Object.defineProperty(this, _onImportError, {\n      writable: true,\n      value: (assembly, fileID, error) => {\n        if (!_classPrivateFieldLooseBase(this, _watching)[_watching](assembly.assembly_id)) {\n          return;\n        } // Not sure if we should be doing something when it's just one file failing.\n        // ATM, the only options are 1) ignoring or 2) failing the entire upload.\n        // I think failing the upload is better than silently ignoring.\n        // In the future we should maybe have a way to resolve uploads with some failures,\n        // like returning an object with `{ successful, failed }` uploads.\n\n\n        _classPrivateFieldLooseBase(this, _onAssemblyError)[_onAssemblyError](assembly, error);\n      }\n    });\n    _classPrivateFieldLooseBase(this, _uppy)[_uppy] = uppy;\n    _classPrivateFieldLooseBase(this, _assemblyIDs)[_assemblyIDs] = assemblyIDs;\n    _classPrivateFieldLooseBase(this, _remaining)[_remaining] = assemblyIDs.length;\n    this.promise = new Promise((resolve, reject) => {\n      _classPrivateFieldLooseBase(this, _resolve)[_resolve] = resolve;\n      _classPrivateFieldLooseBase(this, _reject)[_reject] = reject;\n    });\n\n    _classPrivateFieldLooseBase(this, _addListeners)[_addListeners]();\n  }\n  /**\n   * Are we watching this assembly ID?\n   */\n\n\n}\n\nfunction _watching2(id) {\n  return _classPrivateFieldLooseBase(this, _assemblyIDs)[_assemblyIDs].indexOf(id) !== -1;\n}\n\nfunction _checkAllComplete2() {\n  _classPrivateFieldLooseBase(this, _remaining)[_remaining] -= 1;\n\n  if (_classPrivateFieldLooseBase(this, _remaining)[_remaining] === 0) {\n    // We're done, these listeners can be removed\n    _classPrivateFieldLooseBase(this, _removeListeners)[_removeListeners]();\n\n    _classPrivateFieldLooseBase(this, _resolve)[_resolve]();\n  }\n}\n\nfunction _removeListeners2() {\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].off('transloadit:complete', _classPrivateFieldLooseBase(this, _onAssemblyComplete)[_onAssemblyComplete]);\n\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].off('transloadit:assembly-cancel', _classPrivateFieldLooseBase(this, _onAssemblyCancel)[_onAssemblyCancel]);\n\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].off('transloadit:assembly-error', _classPrivateFieldLooseBase(this, _onAssemblyError)[_onAssemblyError]);\n\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].off('transloadit:import-error', _classPrivateFieldLooseBase(this, _onImportError)[_onImportError]);\n}\n\nfunction _addListeners2() {\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].on('transloadit:complete', _classPrivateFieldLooseBase(this, _onAssemblyComplete)[_onAssemblyComplete]);\n\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].on('transloadit:assembly-cancel', _classPrivateFieldLooseBase(this, _onAssemblyCancel)[_onAssemblyCancel]);\n\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].on('transloadit:assembly-error', _classPrivateFieldLooseBase(this, _onAssemblyError)[_onAssemblyError]);\n\n  _classPrivateFieldLooseBase(this, _uppy)[_uppy].on('transloadit:import-error', _classPrivateFieldLooseBase(this, _onImportError)[_onImportError]);\n}\n\nmodule.exports = TransloaditAssemblyWatcher;", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // Shown while Assemblies are being created for an upload.\n    creatingAssembly: 'Preparing upload...',\n    // Shown if an Assembly could not be created.\n    creatingAssemblyFailed: 'Transloadit: Could not create Assembly',\n    // Shown after uploads have succeeded, but when the Assembly is still executing.\n    // This only shows if `waitForMetadata` or `waitForEncoding` was enabled.\n    encoding: 'Encoding...'\n  }\n};", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.COMPANION_PATTERN = exports.COMPANION = exports.ALLOWED_COMPANION_PATTERN = void 0;\n\nvar _RateLimitedQueue = require(\"@uppy/utils/lib/RateLimitedQueue\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst hasProperty = require(\"@uppy/utils/lib/hasProperty\");\n\nconst ErrorWithCause = require(\"@uppy/utils/lib/ErrorWithCause\");\n\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst Tus = require(\"@uppy/tus\");\n\nconst Assembly = require(\"./Assembly.js\");\n\nconst Client = require(\"./Client.js\");\n\nconst AssemblyOptions = require(\"./AssemblyOptions.js\");\n\nconst {\n  validateParams: validateParams\n} = AssemblyOptions;\n\nconst AssemblyWatcher = require(\"./AssemblyWatcher.js\");\n\nconst locale = require(\"./locale.js\");\n\nconst packageJson = {\n  \"version\": \"2.3.7\"\n};\n\nfunction defaultGetAssemblyOptions(file, options) {\n  return {\n    params: options.params,\n    signature: options.signature,\n    fields: options.fields\n  };\n}\n\nconst sendErrorToConsole = originalErr => err => {\n  const error = new ErrorWithCause('Failed to send error to the client', {\n    cause: err\n  }); // eslint-disable-next-line no-console\n\n  console.error(error, originalErr);\n};\n\nconst COMPANION = 'https://api2.transloadit.com/companion'; // Regex matching acceptable postMessage() origins for authentication feedback from companion.\n\nexports.COMPANION = COMPANION;\nconst ALLOWED_COMPANION_PATTERN = /\\.transloadit\\.com$/; // Regex used to check if a Companion address is run by Transloadit.\n\nexports.COMPANION_PATTERN = exports.ALLOWED_COMPANION_PATTERN = ALLOWED_COMPANION_PATTERN;\nconst TL_COMPANION = /https?:\\/\\/api2(?:-\\w+)?\\.transloadit\\.com\\/companion/;\n/**\n * Upload files to Transloadit using Tus.\n */\n\nvar _rateLimitedQueue = /*#__PURE__*/_classPrivateFieldLooseKey(\"rateLimitedQueue\");\n\nvar _getClientVersion = /*#__PURE__*/_classPrivateFieldLooseKey(\"getClientVersion\");\n\nvar _attachAssemblyMetadata = /*#__PURE__*/_classPrivateFieldLooseKey(\"attachAssemblyMetadata\");\n\nvar _createAssembly = /*#__PURE__*/_classPrivateFieldLooseKey(\"createAssembly\");\n\nvar _createAssemblyWatcher = /*#__PURE__*/_classPrivateFieldLooseKey(\"createAssemblyWatcher\");\n\nvar _shouldWaitAfterUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"shouldWaitAfterUpload\");\n\nvar _reserveFiles = /*#__PURE__*/_classPrivateFieldLooseKey(\"reserveFiles\");\n\nvar _onFileUploadURLAvailable = /*#__PURE__*/_classPrivateFieldLooseKey(\"onFileUploadURLAvailable\");\n\nvar _findFile = /*#__PURE__*/_classPrivateFieldLooseKey(\"findFile\");\n\nvar _onFileUploadComplete = /*#__PURE__*/_classPrivateFieldLooseKey(\"onFileUploadComplete\");\n\nvar _onResult = /*#__PURE__*/_classPrivateFieldLooseKey(\"onResult\");\n\nvar _onAssemblyFinished = /*#__PURE__*/_classPrivateFieldLooseKey(\"onAssemblyFinished\");\n\nvar _cancelAssembly = /*#__PURE__*/_classPrivateFieldLooseKey(\"cancelAssembly\");\n\nvar _onCancelAll = /*#__PURE__*/_classPrivateFieldLooseKey(\"onCancelAll\");\n\nvar _getPersistentData = /*#__PURE__*/_classPrivateFieldLooseKey(\"getPersistentData\");\n\nvar _onRestored = /*#__PURE__*/_classPrivateFieldLooseKey(\"onRestored\");\n\nvar _connectAssembly = /*#__PURE__*/_classPrivateFieldLooseKey(\"connectAssembly\");\n\nvar _prepareUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"prepareUpload\");\n\nvar _afterUpload = /*#__PURE__*/_classPrivateFieldLooseKey(\"afterUpload\");\n\nvar _closeAssemblyIfExists = /*#__PURE__*/_classPrivateFieldLooseKey(\"closeAssemblyIfExists\");\n\nvar _onError = /*#__PURE__*/_classPrivateFieldLooseKey(\"onError\");\n\nvar _onTusError = /*#__PURE__*/_classPrivateFieldLooseKey(\"onTusError\");\n\nclass Transloadit extends BasePlugin {\n  constructor(uppy, opts) {\n    var _this;\n\n    super(uppy, opts);\n    _this = this;\n    Object.defineProperty(this, _connectAssembly, {\n      value: _connectAssembly2\n    });\n    Object.defineProperty(this, _cancelAssembly, {\n      value: _cancelAssembly2\n    });\n    Object.defineProperty(this, _onAssemblyFinished, {\n      value: _onAssemblyFinished2\n    });\n    Object.defineProperty(this, _onResult, {\n      value: _onResult2\n    });\n    Object.defineProperty(this, _onFileUploadComplete, {\n      value: _onFileUploadComplete2\n    });\n    Object.defineProperty(this, _findFile, {\n      value: _findFile2\n    });\n    Object.defineProperty(this, _reserveFiles, {\n      value: _reserveFiles2\n    });\n    Object.defineProperty(this, _shouldWaitAfterUpload, {\n      value: _shouldWaitAfterUpload2\n    });\n    Object.defineProperty(this, _createAssemblyWatcher, {\n      value: _createAssemblyWatcher2\n    });\n    Object.defineProperty(this, _createAssembly, {\n      value: _createAssembly2\n    });\n    Object.defineProperty(this, _attachAssemblyMetadata, {\n      value: _attachAssemblyMetadata2\n    });\n    Object.defineProperty(this, _getClientVersion, {\n      value: _getClientVersion2\n    });\n    Object.defineProperty(this, _rateLimitedQueue, {\n      writable: true,\n      value: void 0\n    });\n    Object.defineProperty(this, _onFileUploadURLAvailable, {\n      writable: true,\n      value: rawFile => {\n        var _file$transloadit;\n\n        const file = this.uppy.getFile(rawFile.id);\n\n        if (!(file != null && (_file$transloadit = file.transloadit) != null && _file$transloadit.assembly)) {\n          return;\n        }\n\n        const {\n          assemblies\n        } = this.getPluginState();\n        const assembly = assemblies[file.transloadit.assembly];\n        this.client.addFile(assembly, file).catch(err => {\n          this.uppy.log(err);\n          this.uppy.emit('transloadit:import-error', assembly, file.id, err);\n        });\n      }\n    });\n    Object.defineProperty(this, _onCancelAll, {\n      writable: true,\n      value: async function (_temp) {\n        let {\n          reason\n        } = _temp === void 0 ? {} : _temp;\n\n        try {\n          if (reason !== 'user') return;\n\n          const {\n            uploadsAssemblies\n          } = _this.getPluginState();\n\n          const assemblyIDs = Object.values(uploadsAssemblies).flat(1);\n          const assemblies = assemblyIDs.map(assemblyID => _this.getAssembly(assemblyID));\n          await Promise.all(assemblies.map(assembly => _classPrivateFieldLooseBase(_this, _cancelAssembly)[_cancelAssembly](assembly)));\n        } catch (err) {\n          _this.uppy.log(err);\n        }\n      }\n    });\n    Object.defineProperty(this, _getPersistentData, {\n      writable: true,\n      value: setData => {\n        const {\n          assemblies,\n          uploadsAssemblies\n        } = this.getPluginState();\n        setData({\n          [this.id]: {\n            assemblies,\n            uploadsAssemblies\n          }\n        });\n      }\n    });\n    Object.defineProperty(this, _onRestored, {\n      writable: true,\n      value: pluginData => {\n        const savedState = pluginData && pluginData[this.id] ? pluginData[this.id] : {};\n        const previousAssemblies = savedState.assemblies || {};\n        const uploadsAssemblies = savedState.uploadsAssemblies || {};\n\n        if (Object.keys(uploadsAssemblies).length === 0) {\n          // Nothing to restore.\n          return;\n        } // Convert loaded Assembly statuses to a Transloadit plugin state object.\n\n\n        const restoreState = assemblies => {\n          const files = {};\n          const results = [];\n\n          for (const [id, status] of Object.entries(assemblies)) {\n            status.uploads.forEach(uploadedFile => {\n              const file = _classPrivateFieldLooseBase(this, _findFile)[_findFile](uploadedFile);\n\n              files[uploadedFile.id] = {\n                id: file.id,\n                assembly: id,\n                uploadedFile\n              };\n            });\n            const state = this.getPluginState();\n            Object.keys(status.results).forEach(stepName => {\n              for (const result of status.results[stepName]) {\n                const file = state.files[result.original_id];\n                result.localId = file ? file.id : null;\n                results.push({\n                  id: result.id,\n                  result,\n                  stepName,\n                  assembly: id\n                });\n              }\n            });\n          }\n\n          this.setPluginState({\n            assemblies,\n            files,\n            results,\n            uploadsAssemblies\n          });\n        }; // Set up the Assembly instances and AssemblyWatchers for existing Assemblies.\n\n\n        const restoreAssemblies = () => {\n          // eslint-disable-next-line no-shadow\n          const {\n            assemblies,\n            uploadsAssemblies\n          } = this.getPluginState(); // Set up the assembly watchers again for all the ongoing uploads.\n\n          Object.keys(uploadsAssemblies).forEach(uploadID => {\n            const assemblyIDs = uploadsAssemblies[uploadID];\n\n            _classPrivateFieldLooseBase(this, _createAssemblyWatcher)[_createAssemblyWatcher](assemblyIDs, uploadID);\n          });\n          const allAssemblyIDs = Object.keys(assemblies);\n          allAssemblyIDs.forEach(id => {\n            const assembly = new Assembly(assemblies[id], _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue]);\n\n            _classPrivateFieldLooseBase(this, _connectAssembly)[_connectAssembly](assembly);\n          });\n        }; // Force-update all Assemblies to check for missed events.\n\n\n        const updateAssemblies = () => {\n          const {\n            assemblies\n          } = this.getPluginState();\n          return Promise.all(Object.keys(assemblies).map(id => {\n            return this.activeAssemblies[id].update();\n          }));\n        }; // Restore all Assembly state.\n\n\n        this.restored = Promise.resolve().then(() => {\n          restoreState(previousAssemblies);\n          restoreAssemblies();\n          return updateAssemblies();\n        });\n        this.restored.then(() => {\n          this.restored = null;\n        });\n      }\n    });\n    Object.defineProperty(this, _prepareUpload, {\n      writable: true,\n      value: (fileIDs, uploadID) => {\n        const files = fileIDs.map(id => this.uppy.getFile(id));\n        const filesWithoutErrors = files.filter(file => {\n          if (!file.error) {\n            this.uppy.emit('preprocess-progress', file, {\n              mode: 'indeterminate',\n              message: this.i18n('creatingAssembly')\n            });\n            return true;\n          }\n\n          return false;\n        }); // eslint-disable-next-line no-shadow\n\n        const createAssembly = async _ref => {\n          let {\n            fileIDs,\n            options\n          } = _ref;\n\n          try {\n            const assembly = await _classPrivateFieldLooseBase(this, _createAssembly)[_createAssembly](fileIDs, uploadID, options);\n\n            if (this.opts.importFromUploadURLs) {\n              await _classPrivateFieldLooseBase(this, _reserveFiles)[_reserveFiles](assembly, fileIDs);\n            }\n\n            fileIDs.forEach(fileID => {\n              const file = this.uppy.getFile(fileID);\n              this.uppy.emit('preprocess-complete', file);\n            });\n            return assembly;\n          } catch (err) {\n            fileIDs.forEach(fileID => {\n              const file = this.uppy.getFile(fileID); // Clear preprocessing state when the Assembly could not be created,\n              // otherwise the UI gets confused about the lingering progress keys\n\n              this.uppy.emit('preprocess-complete', file);\n              this.uppy.emit('upload-error', file, err);\n            });\n            throw err;\n          }\n        };\n\n        const {\n          uploadsAssemblies\n        } = this.getPluginState();\n        this.setPluginState({\n          uploadsAssemblies: { ...uploadsAssemblies,\n            [uploadID]: []\n          }\n        });\n        const assemblyOptions = new AssemblyOptions(filesWithoutErrors, this.opts);\n        return assemblyOptions.build().then(assemblies => Promise.all(assemblies.map(createAssembly))).then(maybeCreatedAssemblies => {\n          const createdAssemblies = maybeCreatedAssemblies.filter(Boolean);\n          const assemblyIDs = createdAssemblies.map(assembly => assembly.status.assembly_id);\n\n          _classPrivateFieldLooseBase(this, _createAssemblyWatcher)[_createAssemblyWatcher](assemblyIDs, uploadID);\n\n          return Promise.all(createdAssemblies.map(assembly => _classPrivateFieldLooseBase(this, _connectAssembly)[_connectAssembly](assembly)));\n        }) // If something went wrong before any Assemblies could be created,\n        // clear all processing state.\n        .catch(err => {\n          filesWithoutErrors.forEach(file => {\n            this.uppy.emit('preprocess-complete', file);\n            this.uppy.emit('upload-error', file, err);\n          });\n          throw err;\n        });\n      }\n    });\n    Object.defineProperty(this, _afterUpload, {\n      writable: true,\n      value: (fileIDs, uploadID) => {\n        const files = fileIDs.map(fileID => this.uppy.getFile(fileID)); // Only use files without errors\n\n        const filteredFileIDs = files.filter(file => !file.error).map(file => file.id);\n        const state = this.getPluginState(); // If we're still restoring state, wait for that to be done.\n\n        if (this.restored) {\n          return this.restored.then(() => {\n            return _classPrivateFieldLooseBase(this, _afterUpload)[_afterUpload](filteredFileIDs, uploadID);\n          });\n        }\n\n        const assemblyIDs = state.uploadsAssemblies[uploadID];\n\n        const closeSocketConnections = () => {\n          assemblyIDs.forEach(assemblyID => {\n            const assembly = this.activeAssemblies[assemblyID];\n            assembly.close();\n            delete this.activeAssemblies[assemblyID];\n          });\n        }; // If we don't have to wait for encoding metadata or results, we can close\n        // the socket immediately and finish the upload.\n\n\n        if (!_classPrivateFieldLooseBase(this, _shouldWaitAfterUpload)[_shouldWaitAfterUpload]()) {\n          closeSocketConnections();\n          const assemblies = assemblyIDs.map(id => this.getAssembly(id));\n          this.uppy.addResultData(uploadID, {\n            transloadit: assemblies\n          });\n          return Promise.resolve();\n        } // If no Assemblies were created for this upload, we also do not have to wait.\n        // There's also no sockets or anything to close, so just return immediately.\n\n\n        if (assemblyIDs.length === 0) {\n          this.uppy.addResultData(uploadID, {\n            transloadit: []\n          });\n          return Promise.resolve();\n        }\n\n        const incompleteFiles = files.filter(file => !hasProperty(this.completedFiles, file.id));\n        incompleteFiles.forEach(file => {\n          this.uppy.emit('postprocess-progress', file, {\n            mode: 'indeterminate',\n            message: this.i18n('encoding')\n          });\n        });\n        const watcher = this.assemblyWatchers[uploadID];\n        return watcher.promise.then(() => {\n          closeSocketConnections();\n          const assemblies = assemblyIDs.map(id => this.getAssembly(id)); // Remove the Assembly ID list for this upload,\n          // it's no longer going to be used anywhere.\n\n          const uploadsAssemblies = { ...this.getPluginState().uploadsAssemblies\n          };\n          delete uploadsAssemblies[uploadID];\n          this.setPluginState({\n            uploadsAssemblies\n          });\n          this.uppy.addResultData(uploadID, {\n            transloadit: assemblies\n          });\n        });\n      }\n    });\n    Object.defineProperty(this, _closeAssemblyIfExists, {\n      writable: true,\n      value: assemblyID => {\n        var _this$activeAssemblie;\n\n        (_this$activeAssemblie = this.activeAssemblies[assemblyID]) == null ? void 0 : _this$activeAssemblie.close();\n      }\n    });\n    Object.defineProperty(this, _onError, {\n      writable: true,\n      value: function (err, uploadID) {\n        if (err === void 0) {\n          err = null;\n        }\n\n        const state = _this.getPluginState();\n\n        const assemblyIDs = state.uploadsAssemblies[uploadID];\n        assemblyIDs == null ? void 0 : assemblyIDs.forEach(_classPrivateFieldLooseBase(_this, _closeAssemblyIfExists)[_closeAssemblyIfExists]);\n\n        _this.client.submitError(err) // if we can't report the error that sucks\n        .catch(sendErrorToConsole(err));\n      }\n    });\n    Object.defineProperty(this, _onTusError, {\n      writable: true,\n      value: (file, err) => {\n        var _file$transloadit2, _err$message;\n\n        _classPrivateFieldLooseBase(this, _closeAssemblyIfExists)[_closeAssemblyIfExists](file == null ? void 0 : (_file$transloadit2 = file.transloadit) == null ? void 0 : _file$transloadit2.assembly);\n\n        if (err != null && (_err$message = err.message) != null && _err$message.startsWith('tus: ')) {\n          var _err$originalRequest, _err$originalRequest$;\n\n          const endpoint = (_err$originalRequest = err.originalRequest) == null ? void 0 : (_err$originalRequest$ = _err$originalRequest.getUnderlyingObject()) == null ? void 0 : _err$originalRequest$.responseURL;\n          this.client.submitError(err, {\n            endpoint,\n            type: 'TUS_ERROR'\n          }) // if we can't report the error that sucks\n          .catch(sendErrorToConsole(err));\n        }\n      }\n    });\n    this.type = 'uploader';\n    this.id = this.opts.id || 'Transloadit';\n    this.title = 'Transloadit';\n    this.defaultLocale = locale;\n    const defaultOptions = {\n      service: 'https://api2.transloadit.com',\n      errorReporting: true,\n      waitForEncoding: false,\n      waitForMetadata: false,\n      alwaysRunAssembly: false,\n      importFromUploadURLs: false,\n      signature: null,\n      params: null,\n      fields: {},\n      getAssemblyOptions: defaultGetAssemblyOptions,\n      limit: 20,\n      retryDelays: [7000, 10000, 15000, 20000]\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue] = new _RateLimitedQueue.RateLimitedQueue(this.opts.limit);\n    this.i18nInit();\n    const hasCustomAssemblyOptions = this.opts.getAssemblyOptions !== defaultOptions.getAssemblyOptions;\n\n    if (this.opts.params) {\n      validateParams(this.opts.params);\n    } else if (!hasCustomAssemblyOptions) {\n      // Throw the same error that we'd throw if the `params` returned from a\n      // `getAssemblyOptions()` function is null.\n      validateParams(null);\n    }\n\n    this.client = new Client({\n      service: this.opts.service,\n      client: _classPrivateFieldLooseBase(this, _getClientVersion)[_getClientVersion](),\n      errorReporting: this.opts.errorReporting,\n      rateLimitedQueue: _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue]\n    }); // Contains Assembly instances for in-progress Assemblies.\n\n    this.activeAssemblies = {}; // Contains a mapping of uploadID to AssemblyWatcher\n\n    this.assemblyWatchers = {}; // Contains a file IDs that have completed postprocessing before the upload\n    // they belong to has entered the postprocess stage.\n\n    this.completedFiles = Object.create(null);\n  }\n\n  install() {\n    this.uppy.addPreProcessor(_classPrivateFieldLooseBase(this, _prepareUpload)[_prepareUpload]);\n    this.uppy.addPostProcessor(_classPrivateFieldLooseBase(this, _afterUpload)[_afterUpload]); // We may need to close socket.io connections on error.\n\n    this.uppy.on('error', _classPrivateFieldLooseBase(this, _onError)[_onError]); // Handle cancellation.\n\n    this.uppy.on('cancel-all', _classPrivateFieldLooseBase(this, _onCancelAll)[_onCancelAll]); // For error reporting.\n\n    this.uppy.on('upload-error', _classPrivateFieldLooseBase(this, _onTusError)[_onTusError]);\n\n    if (this.opts.importFromUploadURLs) {\n      // No uploader needed when importing; instead we take the upload URL from an existing uploader.\n      this.uppy.on('upload-success', _classPrivateFieldLooseBase(this, _onFileUploadURLAvailable)[_onFileUploadURLAvailable]);\n    } else {\n      this.uppy.use(Tus, {\n        // Disable tus-js-client fingerprinting, otherwise uploading the same file at different times\n        // will upload to an outdated Assembly, and we won't get socket events for it.\n        //\n        // To resume a Transloadit upload, we need to reconnect to the websocket, and the state that's\n        // required to do that is not saved by tus-js-client's fingerprinting. We need the tus URL,\n        // the Assembly URL, and the WebSocket URL, at least. We also need to know _all_ the files that\n        // were added to the Assembly, so we can properly complete it. All that state is handled by\n        // Golden Retriever. So, Golden Retriever is required to do resumability with the Transloadit plugin,\n        // and we disable Tus's default resume implementation to prevent bad behaviours.\n        storeFingerprintForResuming: false,\n        // Disable Companion's retry optimisation; we need to change the endpoint on retry\n        // so it can't just reuse the same tus.Upload instance server-side.\n        useFastRemoteRetry: false,\n        // Only send Assembly metadata to the tus endpoint.\n        metaFields: ['assembly_url', 'filename', 'fieldname'],\n        // Pass the limit option to @uppy/tus\n        limit: this.opts.limit,\n        rateLimitedQueue: _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue],\n        retryDelays: this.opts.retryDelays\n      });\n    }\n\n    this.uppy.on('restore:get-data', _classPrivateFieldLooseBase(this, _getPersistentData)[_getPersistentData]);\n    this.uppy.on('restored', _classPrivateFieldLooseBase(this, _onRestored)[_onRestored]);\n    this.setPluginState({\n      // Contains Assembly status objects, indexed by their ID.\n      assemblies: {},\n      // Contains arrays of Assembly IDs, indexed by the upload ID that they belong to.\n      uploadsAssemblies: {},\n      // Contains file data from Transloadit, indexed by their Transloadit-assigned ID.\n      files: {},\n      // Contains result data from Transloadit.\n      results: []\n    }); // We cannot cancel individual files because Assemblies tend to contain many files.\n\n    const {\n      capabilities\n    } = this.uppy.getState();\n    this.uppy.setState({\n      capabilities: { ...capabilities,\n        individualCancellation: false\n      }\n    });\n  }\n\n  uninstall() {\n    this.uppy.removePreProcessor(_classPrivateFieldLooseBase(this, _prepareUpload)[_prepareUpload]);\n    this.uppy.removePostProcessor(_classPrivateFieldLooseBase(this, _afterUpload)[_afterUpload]);\n    this.uppy.off('error', _classPrivateFieldLooseBase(this, _onError)[_onError]);\n\n    if (this.opts.importFromUploadURLs) {\n      this.uppy.off('upload-success', _classPrivateFieldLooseBase(this, _onFileUploadURLAvailable)[_onFileUploadURLAvailable]);\n    }\n\n    const {\n      capabilities\n    } = this.uppy.getState();\n    this.uppy.setState({\n      capabilities: { ...capabilities,\n        individualCancellation: true\n      }\n    });\n  }\n\n  getAssembly(id) {\n    const {\n      assemblies\n    } = this.getPluginState();\n    return assemblies[id];\n  }\n\n  getAssemblyFiles(assemblyID) {\n    return this.uppy.getFiles().filter(file => {\n      var _file$transloadit3;\n\n      return (file == null ? void 0 : (_file$transloadit3 = file.transloadit) == null ? void 0 : _file$transloadit3.assembly) === assemblyID;\n    });\n  }\n\n}\n\nfunction _getClientVersion2() {\n  const list = [`uppy-core:${this.uppy.constructor.VERSION}`, `uppy-transloadit:${this.constructor.VERSION}`, `uppy-tus:${Tus.VERSION}`];\n\n  const addPluginVersion = (pluginName, versionName) => {\n    const plugin = this.uppy.getPlugin(pluginName);\n\n    if (plugin) {\n      list.push(`${versionName}:${plugin.constructor.VERSION}`);\n    }\n  };\n\n  if (this.opts.importFromUploadURLs) {\n    addPluginVersion('XHRUpload', 'uppy-xhr-upload');\n    addPluginVersion('AwsS3', 'uppy-aws-s3');\n    addPluginVersion('AwsS3Multipart', 'uppy-aws-s3-multipart');\n  }\n\n  addPluginVersion('Dropbox', 'uppy-dropbox');\n  addPluginVersion('Box', 'uppy-box');\n  addPluginVersion('Facebook', 'uppy-facebook');\n  addPluginVersion('GoogleDrive', 'uppy-google-drive');\n  addPluginVersion('Instagram', 'uppy-instagram');\n  addPluginVersion('OneDrive', 'uppy-onedrive');\n  addPluginVersion('Zoom', 'uppy-zoom');\n  addPluginVersion('Url', 'uppy-url');\n  return list.join(',');\n}\n\nfunction _attachAssemblyMetadata2(file, status) {\n  // Add the metadata parameters Transloadit needs.\n  const meta = { ...file.meta,\n    assembly_url: status.assembly_url,\n    filename: file.name,\n    fieldname: 'file'\n  }; // Add Assembly-specific Tus endpoint.\n\n  const tus = { ...file.tus,\n    endpoint: status.tus_url,\n    // Include X-Request-ID headers for better debugging.\n    addRequestId: true\n  }; // Set Companion location. We only add this, if 'file' has the attribute\n  // remote, because this is the criteria to identify remote files.\n  // We only replace the hostname for Transloadit's companions, so that\n  // people can also self-host them while still using Transloadit for encoding.\n\n  let {\n    remote\n  } = file;\n\n  if (file.remote && TL_COMPANION.test(file.remote.companionUrl)) {\n    const newHost = status.companion_url.replace(/\\/$/, '');\n    const path = file.remote.url.replace(file.remote.companionUrl, '').replace(/^\\//, '');\n    remote = { ...file.remote,\n      companionUrl: newHost,\n      url: `${newHost}/${path}`\n    };\n  } // Store the Assembly ID this file is in on the file under the `transloadit` key.\n\n\n  const newFile = { ...file,\n    transloadit: {\n      assembly: status.assembly_id\n    }\n  }; // Only configure the Tus plugin if we are uploading straight to Transloadit (the default).\n\n  if (!this.opts.importFromUploadURLs) {\n    Object.assign(newFile, {\n      meta,\n      tus,\n      remote\n    });\n  }\n\n  return newFile;\n}\n\nfunction _createAssembly2(fileIDs, uploadID, options) {\n  this.uppy.log('[Transloadit] Create Assembly');\n  return this.client.createAssembly({\n    params: options.params,\n    fields: options.fields,\n    expectedFiles: fileIDs.length,\n    signature: options.signature\n  }).then(async newAssembly => {\n    const files = this.uppy.getFiles().filter(_ref2 => {\n      let {\n        id\n      } = _ref2;\n      return fileIDs.includes(id);\n    });\n\n    if (files.length !== fileIDs.length) {\n      if (files.length === 0) {\n        // All files have been removed, cancelling.\n        await this.client.cancelAssembly(newAssembly);\n        return null;\n      } // At least one file has been removed.\n\n\n      await this.client.updateNumberOfFilesInAssembly(newAssembly, files.length);\n    }\n\n    const assembly = new Assembly(newAssembly, _classPrivateFieldLooseBase(this, _rateLimitedQueue)[_rateLimitedQueue]);\n    const {\n      status\n    } = assembly;\n    const assemblyID = status.assembly_id;\n    const {\n      assemblies,\n      uploadsAssemblies\n    } = this.getPluginState();\n    this.setPluginState({\n      // Store the Assembly status.\n      assemblies: { ...assemblies,\n        [assemblyID]: status\n      },\n      // Store the list of Assemblies related to this upload.\n      uploadsAssemblies: { ...uploadsAssemblies,\n        [uploadID]: [...uploadsAssemblies[uploadID], assemblyID]\n      }\n    });\n    const updatedFiles = {};\n    files.forEach(file => {\n      updatedFiles[file.id] = _classPrivateFieldLooseBase(this, _attachAssemblyMetadata)[_attachAssemblyMetadata](file, status);\n    });\n    this.uppy.setState({\n      files: { ...this.uppy.getState().files,\n        ...updatedFiles\n      }\n    });\n\n    const fileRemovedHandler = (fileRemoved, reason) => {\n      if (reason === 'cancel-all') {\n        assembly.close();\n        this.uppy.off(fileRemovedHandler);\n      } else if (fileRemoved.id in updatedFiles) {\n        delete updatedFiles[fileRemoved.id];\n        const nbOfRemainingFiles = Object.keys(updatedFiles).length;\n\n        if (nbOfRemainingFiles === 0) {\n          assembly.close();\n\n          _classPrivateFieldLooseBase(this, _cancelAssembly)[_cancelAssembly](newAssembly).catch(() => {\n            /* ignore potential errors */\n          });\n\n          this.uppy.off(fileRemovedHandler);\n        } else {\n          this.client.updateNumberOfFilesInAssembly(newAssembly, nbOfRemainingFiles).catch(() => {\n            /* ignore potential errors */\n          });\n        }\n      }\n    };\n\n    this.uppy.on('file-removed', fileRemovedHandler);\n    this.uppy.emit('transloadit:assembly-created', status, fileIDs);\n    this.uppy.log(`[Transloadit] Created Assembly ${assemblyID}`);\n    return assembly;\n  }).catch(err => {\n    const wrapped = new ErrorWithCause(`${this.i18n('creatingAssemblyFailed')}: ${err.message}`, {\n      cause: err\n    });\n\n    if ('details' in err) {\n      wrapped.details = err.details;\n    }\n\n    if ('assembly' in err) {\n      wrapped.assembly = err.assembly;\n    }\n\n    throw wrapped;\n  });\n}\n\nfunction _createAssemblyWatcher2(assemblyID, uploadID) {\n  // AssemblyWatcher tracks completion states of all Assemblies in this upload.\n  const watcher = new AssemblyWatcher(this.uppy, assemblyID);\n  watcher.on('assembly-complete', id => {\n    const files = this.getAssemblyFiles(id);\n    files.forEach(file => {\n      this.completedFiles[file.id] = true;\n      this.uppy.emit('postprocess-complete', file);\n    });\n  });\n  watcher.on('assembly-error', (id, error) => {\n    // Clear postprocessing state for all our files.\n    const files = this.getAssemblyFiles(id);\n    files.forEach(file => {\n      // TODO Maybe make a postprocess-error event here?\n      this.uppy.emit('upload-error', file, error);\n      this.uppy.emit('postprocess-complete', file);\n    });\n  });\n  this.assemblyWatchers[uploadID] = watcher;\n}\n\nfunction _shouldWaitAfterUpload2() {\n  return this.opts.waitForEncoding || this.opts.waitForMetadata;\n}\n\nfunction _reserveFiles2(assembly, fileIDs) {\n  return Promise.all(fileIDs.map(fileID => {\n    const file = this.uppy.getFile(fileID);\n    return this.client.reserveFile(assembly.status, file);\n  }));\n}\n\nfunction _findFile2(uploadedFile) {\n  const files = this.uppy.getFiles();\n\n  for (let i = 0; i < files.length; i++) {\n    const file = files[i]; // Completed file upload.\n\n    if (file.uploadURL === uploadedFile.tus_upload_url) {\n      return file;\n    } // In-progress file upload.\n\n\n    if (file.tus && file.tus.uploadUrl === uploadedFile.tus_upload_url) {\n      return file;\n    }\n\n    if (!uploadedFile.is_tus_file) {\n      // Fingers-crossed check for non-tus uploads, eg imported from S3.\n      if (file.name === uploadedFile.name && file.size === uploadedFile.size) {\n        return file;\n      }\n    }\n  }\n\n  return undefined;\n}\n\nfunction _onFileUploadComplete2(assemblyId, uploadedFile) {\n  const state = this.getPluginState();\n\n  const file = _classPrivateFieldLooseBase(this, _findFile)[_findFile](uploadedFile);\n\n  if (!file) {\n    this.uppy.log('[Transloadit] Couldn\u2019t file the file, it was likely removed in the process');\n    return;\n  }\n\n  this.setPluginState({\n    files: { ...state.files,\n      [uploadedFile.id]: {\n        assembly: assemblyId,\n        id: file.id,\n        uploadedFile\n      }\n    }\n  });\n  this.uppy.emit('transloadit:upload', uploadedFile, this.getAssembly(assemblyId));\n}\n\nfunction _onResult2(assemblyId, stepName, result) {\n  const state = this.getPluginState();\n  const file = state.files[result.original_id]; // The `file` may not exist if an import robot was used instead of a file upload.\n\n  result.localId = file ? file.id : null; // eslint-disable-line no-param-reassign\n\n  const entry = {\n    result,\n    stepName,\n    id: result.id,\n    assembly: assemblyId\n  };\n  this.setPluginState({\n    results: [...state.results, entry]\n  });\n  this.uppy.emit('transloadit:result', stepName, result, this.getAssembly(assemblyId));\n}\n\nfunction _onAssemblyFinished2(status) {\n  const url = status.assembly_ssl_url;\n  this.client.getAssemblyStatus(url).then(finalStatus => {\n    const assemblyId = finalStatus.assembly_id;\n    const state = this.getPluginState();\n    this.setPluginState({\n      assemblies: { ...state.assemblies,\n        [assemblyId]: finalStatus\n      }\n    });\n    this.uppy.emit('transloadit:complete', finalStatus);\n  });\n}\n\nasync function _cancelAssembly2(assembly) {\n  await this.client.cancelAssembly(assembly); // TODO bubble this through AssemblyWatcher so its event handlers can clean up correctly\n\n  this.uppy.emit('transloadit:assembly-cancelled', assembly);\n}\n\nfunction _connectAssembly2(assembly) {\n  const {\n    status\n  } = assembly;\n  const id = status.assembly_id;\n  this.activeAssemblies[id] = assembly; // Sync local `assemblies` state\n\n  assembly.on('status', newStatus => {\n    const {\n      assemblies\n    } = this.getPluginState();\n    this.setPluginState({\n      assemblies: { ...assemblies,\n        [id]: newStatus\n      }\n    });\n  });\n  assembly.on('upload', file => {\n    _classPrivateFieldLooseBase(this, _onFileUploadComplete)[_onFileUploadComplete](id, file);\n  });\n  assembly.on('error', error => {\n    error.assembly = assembly.status; // eslint-disable-line no-param-reassign\n\n    this.uppy.emit('transloadit:assembly-error', assembly.status, error);\n  });\n  assembly.on('executing', () => {\n    this.uppy.emit('transloadit:assembly-executing', assembly.status);\n  });\n\n  if (this.opts.waitForEncoding) {\n    assembly.on('result', (stepName, result) => {\n      _classPrivateFieldLooseBase(this, _onResult)[_onResult](id, stepName, result);\n    });\n  }\n\n  if (this.opts.waitForEncoding) {\n    assembly.on('finished', () => {\n      _classPrivateFieldLooseBase(this, _onAssemblyFinished)[_onAssemblyFinished](assembly.status);\n    });\n  } else if (this.opts.waitForMetadata) {\n    assembly.on('metadata', () => {\n      _classPrivateFieldLooseBase(this, _onAssemblyFinished)[_onAssemblyFinished](assembly.status);\n    });\n  } // No need to connect to the socket if the Assembly has completed by now.\n\n\n  if (assembly.ok === 'ASSEMBLY_COMPLETE') {\n    return assembly;\n  }\n\n  assembly.connect();\n  return assembly;\n}\n\nTransloadit.VERSION = packageJson.version;\nmodule.exports = Transloadit;\n// Backward compatibility: we want `COMPANION` and `COMPANION_PATTERN`\n// to keep being accessible as static properties of `Transloadit` to avoid a\n// breaking change.\nTransloadit.ALLOWED_COMPANION_PATTERN = ALLOWED_COMPANION_PATTERN; // TODO: remove this line on the next major\n\nTransloadit.COMPANION = COMPANION; // TODO: remove this line on the next major\n\nTransloadit.COMPANION_PATTERN = ALLOWED_COMPANION_PATTERN; // TODO: remove this line on the next major", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // Shown in the Informer if an upload is being canceled because it stalled for too long.\n    timedOut: 'Upload stalled for %{seconds} seconds, aborting.'\n  }\n};", "\"use strict\";\n\nvar _nonSecure = require(\"nanoid/non-secure\");\n\nvar _companionClient = require(\"@uppy/companion-client\");\n\nvar _RateLimitedQueue = require(\"@uppy/utils/lib/RateLimitedQueue\");\n\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst emitSocketProgress = require(\"@uppy/utils/lib/emitSocketProgress\");\n\nconst getSocketHost = require(\"@uppy/utils/lib/getSocketHost\");\n\nconst settle = require(\"@uppy/utils/lib/settle\");\n\nconst EventTracker = require(\"@uppy/utils/lib/EventTracker\");\n\nconst ProgressTimeout = require(\"@uppy/utils/lib/ProgressTimeout\");\n\nconst NetworkError = require(\"@uppy/utils/lib/NetworkError\");\n\nconst isNetworkError = require(\"@uppy/utils/lib/isNetworkError\");\n\nconst packageJson = {\n  \"version\": \"2.1.3\"\n};\n\nconst locale = require(\"./locale.js\");\n\nfunction buildResponseError(xhr, err) {\n  let error = err; // No error message\n\n  if (!error) error = new Error('Upload error'); // Got an error message string\n\n  if (typeof error === 'string') error = new Error(error); // Got something else\n\n  if (!(error instanceof Error)) {\n    error = Object.assign(new Error('Upload error'), {\n      data: error\n    });\n  }\n\n  if (isNetworkError(xhr)) {\n    error = new NetworkError(error, xhr);\n    return error;\n  }\n\n  error.request = xhr;\n  return error;\n}\n/**\n * Set `data.type` in the blob to `file.meta.type`,\n * because we might have detected a more accurate file type in Uppy\n * https://stackoverflow.com/a/50875615\n *\n * @param {object} file File object with `data`, `size` and `meta` properties\n * @returns {object} blob updated with the new `type` set from `file.meta.type`\n */\n\n\nfunction setTypeInBlob(file) {\n  const dataWithUpdatedType = file.data.slice(0, file.data.size, file.meta.type);\n  return dataWithUpdatedType;\n}\n\nclass XHRUpload extends BasePlugin {\n  // eslint-disable-next-line global-require\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.type = 'uploader';\n    this.id = this.opts.id || 'XHRUpload';\n    this.title = 'XHRUpload';\n    this.defaultLocale = locale; // Default options\n\n    const defaultOptions = {\n      formData: true,\n      fieldName: opts.bundle ? 'files[]' : 'file',\n      method: 'post',\n      metaFields: null,\n      responseUrlFieldName: 'url',\n      bundle: false,\n      headers: {},\n      timeout: 30 * 1000,\n      limit: 5,\n      withCredentials: false,\n      responseType: '',\n\n      /**\n       * @param {string} responseText the response body string\n       */\n      getResponseData(responseText) {\n        let parsedResponse = {};\n\n        try {\n          parsedResponse = JSON.parse(responseText);\n        } catch (err) {\n          uppy.log(err);\n        }\n\n        return parsedResponse;\n      },\n\n      /**\n       *\n       * @param {string} _ the response body string\n       * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)\n       */\n      getResponseError(_, response) {\n        let error = new Error('Upload error');\n\n        if (isNetworkError(response)) {\n          error = new NetworkError(error, response);\n        }\n\n        return error;\n      },\n\n      /**\n       * Check if the response from the upload endpoint indicates that the upload was successful.\n       *\n       * @param {number} status the response status code\n       */\n      validateStatus(status) {\n        return status >= 200 && status < 300;\n      }\n\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.i18nInit();\n    this.handleUpload = this.handleUpload.bind(this); // Simultaneous upload limiting is shared across all uploads with this plugin.\n\n    if (_RateLimitedQueue.internalRateLimitedQueue in this.opts) {\n      this.requests = this.opts[_RateLimitedQueue.internalRateLimitedQueue];\n    } else {\n      this.requests = new _RateLimitedQueue.RateLimitedQueue(this.opts.limit);\n    }\n\n    if (this.opts.bundle && !this.opts.formData) {\n      throw new Error('`opts.formData` must be true when `opts.bundle` is enabled.');\n    }\n\n    this.uploaderEvents = Object.create(null);\n  }\n\n  getOptions(file) {\n    const overrides = this.uppy.getState().xhrUpload;\n    const {\n      headers\n    } = this.opts;\n    const opts = { ...this.opts,\n      ...(overrides || {}),\n      ...(file.xhrUpload || {}),\n      headers: {}\n    }; // Support for `headers` as a function, only in the XHRUpload settings.\n    // Options set by other plugins in Uppy state or on the files themselves are still merged in afterward.\n    //\n    // ```js\n    // headers: (file) => ({ expires: file.meta.expires })\n    // ```\n\n    if (typeof headers === 'function') {\n      opts.headers = headers(file);\n    } else {\n      Object.assign(opts.headers, this.opts.headers);\n    }\n\n    if (overrides) {\n      Object.assign(opts.headers, overrides.headers);\n    }\n\n    if (file.xhrUpload) {\n      Object.assign(opts.headers, file.xhrUpload.headers);\n    }\n\n    return opts;\n  } // eslint-disable-next-line class-methods-use-this\n\n\n  addMetadata(formData, meta, opts) {\n    const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields : Object.keys(meta); // Send along all fields by default.\n\n    metaFields.forEach(item => {\n      formData.append(item, meta[item]);\n    });\n  }\n\n  createFormDataUpload(file, opts) {\n    const formPost = new FormData();\n    this.addMetadata(formPost, file.meta, opts);\n    const dataWithUpdatedType = setTypeInBlob(file);\n\n    if (file.name) {\n      formPost.append(opts.fieldName, dataWithUpdatedType, file.meta.name);\n    } else {\n      formPost.append(opts.fieldName, dataWithUpdatedType);\n    }\n\n    return formPost;\n  }\n\n  createBundledUpload(files, opts) {\n    const formPost = new FormData();\n    const {\n      meta\n    } = this.uppy.getState();\n    this.addMetadata(formPost, meta, opts);\n    files.forEach(file => {\n      const options = this.getOptions(file);\n      const dataWithUpdatedType = setTypeInBlob(file);\n\n      if (file.name) {\n        formPost.append(options.fieldName, dataWithUpdatedType, file.name);\n      } else {\n        formPost.append(options.fieldName, dataWithUpdatedType);\n      }\n    });\n    return formPost;\n  }\n\n  upload(file, current, total) {\n    const opts = this.getOptions(file);\n    this.uppy.log(`uploading ${current} of ${total}`);\n    return new Promise((resolve, reject) => {\n      this.uppy.emit('upload-started', file);\n      const data = opts.formData ? this.createFormDataUpload(file, opts) : file.data;\n      const xhr = new XMLHttpRequest();\n      this.uploaderEvents[file.id] = new EventTracker(this.uppy);\n      let queuedRequest;\n      const timer = new ProgressTimeout(opts.timeout, () => {\n        xhr.abort();\n        queuedRequest.done();\n        const error = new Error(this.i18n('timedOut', {\n          seconds: Math.ceil(opts.timeout / 1000)\n        }));\n        this.uppy.emit('upload-error', file, error);\n        reject(error);\n      });\n      const id = (0, _nonSecure.nanoid)();\n      xhr.upload.addEventListener('loadstart', () => {\n        this.uppy.log(`[XHRUpload] ${id} started`);\n      });\n      xhr.upload.addEventListener('progress', ev => {\n        this.uppy.log(`[XHRUpload] ${id} progress: ${ev.loaded} / ${ev.total}`); // Begin checking for timeouts when progress starts, instead of loading,\n        // to avoid timing out requests on browser concurrency queue\n\n        timer.progress();\n\n        if (ev.lengthComputable) {\n          this.uppy.emit('upload-progress', file, {\n            uploader: this,\n            bytesUploaded: ev.loaded,\n            bytesTotal: ev.total\n          });\n        }\n      });\n      xhr.addEventListener('load', () => {\n        this.uppy.log(`[XHRUpload] ${id} finished`);\n        timer.done();\n        queuedRequest.done();\n\n        if (this.uploaderEvents[file.id]) {\n          this.uploaderEvents[file.id].remove();\n          this.uploaderEvents[file.id] = null;\n        }\n\n        if (opts.validateStatus(xhr.status, xhr.responseText, xhr)) {\n          const body = opts.getResponseData(xhr.responseText, xhr);\n          const uploadURL = body[opts.responseUrlFieldName];\n          const uploadResp = {\n            status: xhr.status,\n            body,\n            uploadURL\n          };\n          this.uppy.emit('upload-success', file, uploadResp);\n\n          if (uploadURL) {\n            this.uppy.log(`Download ${file.name} from ${uploadURL}`);\n          }\n\n          return resolve(file);\n        }\n\n        const body = opts.getResponseData(xhr.responseText, xhr);\n        const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));\n        const response = {\n          status: xhr.status,\n          body\n        };\n        this.uppy.emit('upload-error', file, error, response);\n        return reject(error);\n      });\n      xhr.addEventListener('error', () => {\n        this.uppy.log(`[XHRUpload] ${id} errored`);\n        timer.done();\n        queuedRequest.done();\n\n        if (this.uploaderEvents[file.id]) {\n          this.uploaderEvents[file.id].remove();\n          this.uploaderEvents[file.id] = null;\n        }\n\n        const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));\n        this.uppy.emit('upload-error', file, error);\n        return reject(error);\n      });\n      xhr.open(opts.method.toUpperCase(), opts.endpoint, true); // IE10 does not allow setting `withCredentials` and `responseType`\n      // before `open()` is called.\n\n      xhr.withCredentials = opts.withCredentials;\n\n      if (opts.responseType !== '') {\n        xhr.responseType = opts.responseType;\n      }\n\n      queuedRequest = this.requests.run(() => {\n        this.uppy.emit('upload-started', file); // When using an authentication system like JWT, the bearer token goes as a header. This\n        // header needs to be fresh each time the token is refreshed so computing and setting the\n        // headers just before the upload starts enables this kind of authentication to work properly.\n        // Otherwise, half-way through the list of uploads the token could be stale and the upload would fail.\n\n        const currentOpts = this.getOptions(file);\n        Object.keys(currentOpts.headers).forEach(header => {\n          xhr.setRequestHeader(header, currentOpts.headers[header]);\n        });\n        xhr.send(data);\n        return () => {\n          timer.done();\n          xhr.abort();\n        };\n      });\n      this.onFileRemove(file.id, () => {\n        queuedRequest.abort();\n        reject(new Error('File removed'));\n      });\n      this.onCancelAll(file.id, _ref => {\n        let {\n          reason\n        } = _ref;\n\n        if (reason === 'user') {\n          queuedRequest.abort();\n        }\n\n        reject(new Error('Upload cancelled'));\n      });\n    });\n  }\n\n  uploadRemote(file) {\n    const opts = this.getOptions(file);\n    return new Promise((resolve, reject) => {\n      this.uppy.emit('upload-started', file);\n      const fields = {};\n      const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default.\n      : Object.keys(file.meta);\n      metaFields.forEach(name => {\n        fields[name] = file.meta[name];\n      });\n      const Client = file.remote.providerOptions.provider ? _companionClient.Provider : _companionClient.RequestClient;\n      const client = new Client(this.uppy, file.remote.providerOptions);\n      client.post(file.remote.url, { ...file.remote.body,\n        endpoint: opts.endpoint,\n        size: file.data.size,\n        fieldname: opts.fieldName,\n        metadata: fields,\n        httpMethod: opts.method,\n        useFormData: opts.formData,\n        headers: opts.headers\n      }).then(res => {\n        const {\n          token\n        } = res;\n        const host = getSocketHost(file.remote.companionUrl);\n        const socket = new _companionClient.Socket({\n          target: `${host}/api/${token}`,\n          autoOpen: false\n        });\n        this.uploaderEvents[file.id] = new EventTracker(this.uppy);\n        let queuedRequest;\n        this.onFileRemove(file.id, () => {\n          socket.send('cancel', {});\n          queuedRequest.abort();\n          resolve(`upload ${file.id} was removed`);\n        });\n        this.onCancelAll(file.id, function (_temp) {\n          let {\n            reason\n          } = _temp === void 0 ? {} : _temp;\n\n          if (reason === 'user') {\n            socket.send('cancel', {});\n            queuedRequest.abort();\n          }\n\n          resolve(`upload ${file.id} was canceled`);\n        });\n        this.onRetry(file.id, () => {\n          socket.send('pause', {});\n          socket.send('resume', {});\n        });\n        this.onRetryAll(file.id, () => {\n          socket.send('pause', {});\n          socket.send('resume', {});\n        });\n        socket.on('progress', progressData => emitSocketProgress(this, progressData, file));\n        socket.on('success', data => {\n          const body = opts.getResponseData(data.response.responseText, data.response);\n          const uploadURL = body[opts.responseUrlFieldName];\n          const uploadResp = {\n            status: data.response.status,\n            body,\n            uploadURL\n          };\n          this.uppy.emit('upload-success', file, uploadResp);\n          queuedRequest.done();\n\n          if (this.uploaderEvents[file.id]) {\n            this.uploaderEvents[file.id].remove();\n            this.uploaderEvents[file.id] = null;\n          }\n\n          return resolve();\n        });\n        socket.on('error', errData => {\n          const resp = errData.response;\n          const error = resp ? opts.getResponseError(resp.responseText, resp) : Object.assign(new Error(errData.error.message), {\n            cause: errData.error\n          });\n          this.uppy.emit('upload-error', file, error);\n          queuedRequest.done();\n\n          if (this.uploaderEvents[file.id]) {\n            this.uploaderEvents[file.id].remove();\n            this.uploaderEvents[file.id] = null;\n          }\n\n          reject(error);\n        });\n        queuedRequest = this.requests.run(() => {\n          socket.open();\n\n          if (file.isPaused) {\n            socket.send('pause', {});\n          }\n\n          return () => socket.close();\n        });\n      }).catch(err => {\n        this.uppy.emit('upload-error', file, err);\n        reject(err);\n      });\n    });\n  }\n\n  uploadBundle(files) {\n    return new Promise((resolve, reject) => {\n      const {\n        endpoint\n      } = this.opts;\n      const {\n        method\n      } = this.opts;\n      const optsFromState = this.uppy.getState().xhrUpload;\n      const formData = this.createBundledUpload(files, { ...this.opts,\n        ...(optsFromState || {})\n      });\n      const xhr = new XMLHttpRequest();\n\n      const emitError = error => {\n        files.forEach(file => {\n          this.uppy.emit('upload-error', file, error);\n        });\n      };\n\n      const timer = new ProgressTimeout(this.opts.timeout, () => {\n        xhr.abort();\n        const error = new Error(this.i18n('timedOut', {\n          seconds: Math.ceil(this.opts.timeout / 1000)\n        }));\n        emitError(error);\n        reject(error);\n      });\n      xhr.upload.addEventListener('loadstart', () => {\n        this.uppy.log('[XHRUpload] started uploading bundle');\n        timer.progress();\n      });\n      xhr.upload.addEventListener('progress', ev => {\n        timer.progress();\n        if (!ev.lengthComputable) return;\n        files.forEach(file => {\n          this.uppy.emit('upload-progress', file, {\n            uploader: this,\n            bytesUploaded: ev.loaded / ev.total * file.size,\n            bytesTotal: file.size\n          });\n        });\n      });\n      xhr.addEventListener('load', ev => {\n        timer.done();\n\n        if (this.opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {\n          const body = this.opts.getResponseData(xhr.responseText, xhr);\n          const uploadResp = {\n            status: ev.target.status,\n            body\n          };\n          files.forEach(file => {\n            this.uppy.emit('upload-success', file, uploadResp);\n          });\n          return resolve();\n        }\n\n        const error = this.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');\n        error.request = xhr;\n        emitError(error);\n        return reject(error);\n      });\n      xhr.addEventListener('error', () => {\n        timer.done();\n        const error = this.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');\n        emitError(error);\n        return reject(error);\n      });\n      this.uppy.on('cancel-all', function (_temp2) {\n        let {\n          reason\n        } = _temp2 === void 0 ? {} : _temp2;\n        if (reason !== 'user') return;\n        timer.done();\n        xhr.abort();\n      });\n      xhr.open(method.toUpperCase(), endpoint, true); // IE10 does not allow setting `withCredentials` and `responseType`\n      // before `open()` is called.\n\n      xhr.withCredentials = this.opts.withCredentials;\n\n      if (this.opts.responseType !== '') {\n        xhr.responseType = this.opts.responseType;\n      }\n\n      Object.keys(this.opts.headers).forEach(header => {\n        xhr.setRequestHeader(header, this.opts.headers[header]);\n      });\n      xhr.send(formData);\n      files.forEach(file => {\n        this.uppy.emit('upload-started', file);\n      });\n    });\n  }\n\n  uploadFiles(files) {\n    const promises = files.map((file, i) => {\n      const current = parseInt(i, 10) + 1;\n      const total = files.length;\n\n      if (file.error) {\n        return Promise.reject(new Error(file.error));\n      }\n\n      if (file.isRemote) {\n        return this.uploadRemote(file, current, total);\n      }\n\n      return this.upload(file, current, total);\n    });\n    return settle(promises);\n  }\n\n  onFileRemove(fileID, cb) {\n    this.uploaderEvents[fileID].on('file-removed', file => {\n      if (fileID === file.id) cb(file.id);\n    });\n  }\n\n  onRetry(fileID, cb) {\n    this.uploaderEvents[fileID].on('upload-retry', targetFileID => {\n      if (fileID === targetFileID) {\n        cb();\n      }\n    });\n  }\n\n  onRetryAll(fileID, cb) {\n    this.uploaderEvents[fileID].on('retry-all', () => {\n      if (!this.uppy.getFile(fileID)) return;\n      cb();\n    });\n  }\n\n  onCancelAll(fileID, eventHandler) {\n    var _this = this;\n\n    this.uploaderEvents[fileID].on('cancel-all', function () {\n      if (!_this.uppy.getFile(fileID)) return;\n      eventHandler(...arguments);\n    });\n  }\n\n  handleUpload(fileIDs) {\n    if (fileIDs.length === 0) {\n      this.uppy.log('[XHRUpload] No files to upload!');\n      return Promise.resolve();\n    } // No limit configured by the user, and no RateLimitedQueue passed in by a \"parent\" plugin\n    // (basically just AwsS3) using the internal symbol\n\n\n    if (this.opts.limit === 0 && !this.opts[_RateLimitedQueue.internalRateLimitedQueue]) {\n      this.uppy.log('[XHRUpload] When uploading multiple files at once, consider setting the `limit` option (to `10` for example), to limit the number of concurrent uploads, which helps prevent memory and network issues: https://uppy.io/docs/xhr-upload/#limit-0', 'warning');\n    }\n\n    this.uppy.log('[XHRUpload] Uploading...');\n    const files = fileIDs.map(fileID => this.uppy.getFile(fileID));\n\n    if (this.opts.bundle) {\n      // if bundle: true, we don\u2019t support remote uploads\n      const isSomeFileRemote = files.some(file => file.isRemote);\n\n      if (isSomeFileRemote) {\n        throw new Error('Can\u2019t upload remote files when the `bundle: true` option is set');\n      }\n\n      if (typeof this.opts.headers === 'function') {\n        throw new TypeError('`headers` may not be a function when the `bundle: true` option is set');\n      }\n\n      return this.uploadBundle(files);\n    }\n\n    return this.uploadFiles(files).then(() => null);\n  }\n\n  install() {\n    if (this.opts.bundle) {\n      const {\n        capabilities\n      } = this.uppy.getState();\n      this.uppy.setState({\n        capabilities: { ...capabilities,\n          individualCancellation: false\n        }\n      });\n    }\n\n    this.uppy.addUploader(this.handleUpload);\n  }\n\n  uninstall() {\n    if (this.opts.bundle) {\n      const {\n        capabilities\n      } = this.uppy.getState();\n      this.uppy.setState({\n        capabilities: { ...capabilities,\n          individualCancellation: true\n        }\n      });\n    }\n\n    this.uppy.removeUploader(this.handleUpload);\n  }\n\n}\n\nXHRUpload.VERSION = packageJson.version;\nmodule.exports = XHRUpload;", "// Adapted from https://github.com/Flet/prettier-bytes/\n// Changing 1000 bytes to 1024, so we can keep uppercase KB vs kB\n// ISC License (c) Dan Flettre https://github.com/Flet/prettier-bytes/blob/master/LICENSE\nmodule.exports = function prettierBytes (num) {\n  if (typeof num !== 'number' || isNaN(num)) {\n    throw new TypeError(`Expected a number, got ${typeof num}`)\n  }\n\n  const neg = num < 0\n  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n  if (neg) {\n    num = -num\n  }\n\n  if (num < 1) {\n    return `${(neg ? '-' : '') + num} B`\n  }\n\n  const exponent = Math.min(Math.floor(Math.log(num) / Math.log(1024)), units.length - 1)\n  num = Number(num / Math.pow(1024, exponent))\n  const unit = units[exponent]\n\n  if (num >= 10 || num % 1 === 0) {\n    // Do not show decimals when the number is two-digit, or if the number has no\n    // decimal component.\n    return `${(neg ? '-' : '') + num.toFixed(0)} ${unit}`\n  }\n  return `${(neg ? '-' : '') + num.toFixed(1)} ${unit}`\n}\n", "/*!\n * Compressor.js v1.4.0\n * https://fengyuanchen.github.io/compressorjs\n *\n * Copyright 2018-present Chen Fengyuan\n * Released under the MIT license\n *\n * Date: 2026-10-01T04:45:36.902Z\n */\n\n'use strict';\n\nfunction _classCallCheck(a, n) {\n  if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\");\n}\nfunction _defineProperties(e, r) {\n  for (var t = 0; t < r.length; t++) {\n    var o = r[t];\n    o.enumerable = o.enumerable || !1, o.configurable = !0, \"value\" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);\n  }\n}\nfunction _createClass(e, r, t) {\n  return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, \"prototype\", {\n    writable: !1\n  }), e;\n}\nfunction _defineProperty(e, r, t) {\n  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n    value: t,\n    enumerable: !0,\n    configurable: !0,\n    writable: !0\n  }) : e[r] = t, e;\n}\nfunction _extends() {\n  return _extends = Object.assign ? Object.assign.bind() : function (n) {\n    for (var e = 1; e < arguments.length; e++) {\n      var t = arguments[e];\n      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n    }\n    return n;\n  }, _extends.apply(null, arguments);\n}\nfunction ownKeys(e, r) {\n  var t = Object.keys(e);\n  if (Object.getOwnPropertySymbols) {\n    var o = Object.getOwnPropertySymbols(e);\n    r && (o = o.filter(function (r) {\n      return Object.getOwnPropertyDescriptor(e, r).enumerable;\n    })), t.push.apply(t, o);\n  }\n  return t;\n}\nfunction _objectSpread2(e) {\n  for (var r = 1; r < arguments.length; r++) {\n    var t = null != arguments[r] ? arguments[r] : {};\n    r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n      _defineProperty(e, r, t[r]);\n    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n      Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n    });\n  }\n  return e;\n}\nfunction _toPrimitive(t, r) {\n  if (\"object\" != typeof t || !t) return t;\n  var e = t[Symbol.toPrimitive];\n  if (void 0 !== e) {\n    var i = e.call(t, r || \"default\");\n    if (\"object\" != typeof i) return i;\n    throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n  }\n  return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n  var i = _toPrimitive(t, \"string\");\n  return \"symbol\" == typeof i ? i : i + \"\";\n}\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar canvasToBlob = {exports: {}};\n\n/*\n * JavaScript Canvas to Blob\n * https://github.com/blueimp/JavaScript-Canvas-to-Blob\n *\n * Copyright 2012, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on stackoverflow user Stoive's code snippet:\n * http://stackoverflow.com/q/4998908\n */\n(function (module) {\n  if (typeof window === 'undefined') {\n    return;\n  }\n  (function (window) {\n\n    var CanvasPrototype = window.HTMLCanvasElement && window.HTMLCanvasElement.prototype;\n    var hasBlobConstructor = window.Blob && function () {\n      try {\n        return Boolean(new Blob());\n      } catch (e) {\n        return false;\n      }\n    }();\n    var hasArrayBufferViewSupport = hasBlobConstructor && window.Uint8Array && function () {\n      try {\n        return new Blob([new Uint8Array(100)]).size === 100;\n      } catch (e) {\n        return false;\n      }\n    }();\n    var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;\n    var dataURIPattern = /^data:((.*?)(;charset=.*?)?)(;base64)?,/;\n    var dataURLtoBlob = (hasBlobConstructor || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array && function (dataURI) {\n      var matches, mediaType, isBase64, dataString, byteString, arrayBuffer, intArray, i, bb;\n      // Parse the dataURI components as per RFC 2397\n      matches = dataURI.match(dataURIPattern);\n      if (!matches) {\n        throw new Error('invalid data URI');\n      }\n      // Default to text/plain;charset=US-ASCII\n      mediaType = matches[2] ? matches[1] : 'text/plain' + (matches[3] || ';charset=US-ASCII');\n      isBase64 = !!matches[4];\n      dataString = dataURI.slice(matches[0].length);\n      if (isBase64) {\n        // Convert base64 to raw binary data held in a string:\n        byteString = atob(dataString);\n      } else {\n        // Convert base64/URLEncoded data component to raw binary:\n        byteString = decodeURIComponent(dataString);\n      }\n      // Write the bytes of the string to an ArrayBuffer:\n      arrayBuffer = new ArrayBuffer(byteString.length);\n      intArray = new Uint8Array(arrayBuffer);\n      for (i = 0; i < byteString.length; i += 1) {\n        intArray[i] = byteString.charCodeAt(i);\n      }\n      // Write the ArrayBuffer (or ArrayBufferView) to a blob:\n      if (hasBlobConstructor) {\n        return new Blob([hasArrayBufferViewSupport ? intArray : arrayBuffer], {\n          type: mediaType\n        });\n      }\n      bb = new BlobBuilder();\n      bb.append(arrayBuffer);\n      return bb.getBlob(mediaType);\n    };\n    if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) {\n      if (CanvasPrototype.mozGetAsFile) {\n        CanvasPrototype.toBlob = function (callback, type, quality) {\n          var self = this;\n          setTimeout(function () {\n            if (quality && CanvasPrototype.toDataURL && dataURLtoBlob) {\n              callback(dataURLtoBlob(self.toDataURL(type, quality)));\n            } else {\n              callback(self.mozGetAsFile('blob', type));\n            }\n          });\n        };\n      } else if (CanvasPrototype.toDataURL && dataURLtoBlob) {\n        if (CanvasPrototype.msToBlob) {\n          CanvasPrototype.toBlob = function (callback, type, quality) {\n            var self = this;\n            setTimeout(function () {\n              if ((type && type !== 'image/png' || quality) && CanvasPrototype.toDataURL && dataURLtoBlob) {\n                callback(dataURLtoBlob(self.toDataURL(type, quality)));\n              } else {\n                callback(self.msToBlob(type));\n              }\n            });\n          };\n        } else {\n          CanvasPrototype.toBlob = function (callback, type, quality) {\n            var self = this;\n            setTimeout(function () {\n              callback(dataURLtoBlob(self.toDataURL(type, quality)));\n            });\n          };\n        }\n      }\n    }\n    if (module.exports) {\n      module.exports = dataURLtoBlob;\n    } else {\n      window.dataURLtoBlob = dataURLtoBlob;\n    }\n  })(window);\n})(canvasToBlob);\nvar canvasToBlobExports = canvasToBlob.exports;\nvar toBlob = /*@__PURE__*/getDefaultExportFromCjs(canvasToBlobExports);\n\nvar isBlob = function isBlob(value) {\n  if (typeof Blob === 'undefined') {\n    return false;\n  }\n  return value instanceof Blob || Object.prototype.toString.call(value) === '[object Blob]';\n};\nvar isBlob$1 = /*@__PURE__*/getDefaultExportFromCjs(isBlob);\n\nvar DEFAULTS = {\n  /**\n   * Indicates whether to output the original image instead of the compressed one\n   * when the size of the compressed image is greater than the original one's\n   * @type {boolean}\n   */\n  strict: true,\n  /**\n   * Indicates whether to read the image's Exif Orientation information,\n   * and then rotate or flip the image automatically.\n   * @type {boolean}\n   */\n  checkOrientation: true,\n  /**\n   * Indicates whether to retain the image's Exif information after compression.\n   * @type {boolean}\n  */\n  retainExif: false,\n  /**\n   * The max width of the output image.\n   * @type {number}\n   */\n  maxWidth: Infinity,\n  /**\n   * The max height of the output image.\n   * @type {number}\n   */\n  maxHeight: Infinity,\n  /**\n   * The min width of the output image.\n   * @type {number}\n   */\n  minWidth: 0,\n  /**\n   * The min height of the output image.\n   * @type {number}\n   */\n  minHeight: 0,\n  /**\n   * The width of the output image.\n   * If not specified, the natural width of the source image will be used.\n   * @type {number}\n   */\n  width: undefined,\n  /**\n   * The height of the output image.\n   * If not specified, the natural height of the source image will be used.\n   * @type {number}\n   */\n  height: undefined,\n  /**\n   * Sets how the size of the image should be resized to the container\n   * specified by the `width` and `height` options.\n   * @type {string}\n   */\n  resize: 'none',\n  /**\n   * The quality of the output image.\n   * It must be a number between `0` and `1`,\n   * and only available for `image/jpeg` and `image/webp` images.\n   * Check out {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob canvas.toBlob}.\n   * @type {number}\n   */\n  quality: 0.8,\n  /**\n   * The mime type of the output image.\n   * By default, the original mime type of the source image file will be used.\n   * @type {string}\n   */\n  mimeType: 'auto',\n  /**\n   * Files whose file type is included in this list,\n   * and whose file size exceeds the `convertSize` value will be converted to JPEGs.\n   * @type {string|string[]}\n   */\n  convertTypes: ['image/png'],\n  /**\n   * PNG files over this size (5 MB by default) will be converted to JPEGs.\n   * To disable this, just set the value to `Infinity`.\n   * @type {number}\n   */\n  convertSize: 5000000,\n  /**\n   * The hook function to execute before drawing the image into the canvas for compression.\n   * @type {Function}\n   * @param {CanvasRenderingContext2D} context - The 2D rendering context of the canvas.\n   * @param {HTMLCanvasElement} canvas - The canvas for compression.\n   * @example\n   * function (context, canvas) {\n   *   context.fillStyle = '#fff';\n   * }\n   */\n  beforeDraw: null,\n  /**\n   * The hook function to execute after drawing the image into the canvas for compression.\n   * @type {Function}\n   * @param {CanvasRenderingContext2D} context - The 2D rendering context of the canvas.\n   * @param {HTMLCanvasElement} canvas - The canvas for compression.\n   * @example\n   * function (context, canvas) {\n   *   context.filter = 'grayscale(100%)';\n   * }\n   */\n  drew: null,\n  /**\n   * The hook function to execute when the image is compressed successfully.\n   * @type {Function}\n   * @param {File} file - The compressed image File object.\n   * @example\n   * function (file) {\n   *   console.log(file);\n   * }\n   */\n  success: null,\n  /**\n   * The hook function to execute when fail to compress the image.\n   * @type {Function}\n   * @param {Error} err - An Error object.\n   * @example\n   * function (err) {\n   *   console.log(err.message);\n   * }\n   */\n  error: null\n};\n\nvar IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined';\nvar WINDOW = IS_BROWSER ? window : {};\n\n/**\n * Check if the given value is a positive number.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a positive number, else `false`.\n */\nvar isPositiveNumber = function isPositiveNumber(value) {\n  return value > 0 && value < Infinity;\n};\nvar slice = Array.prototype.slice;\n\n/**\n * Convert array-like or iterable object to an array.\n * @param {*} value - The value to convert.\n * @returns {Array} Returns a new array.\n */\nfunction toArray(value) {\n  return Array.from ? Array.from(value) : slice.call(value);\n}\nvar REGEXP_IMAGE_TYPE = /^image\\/.+$/;\n\n/**\n * Check if the given value is an image MIME type.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is an image MIME type, else `false`.\n */\nfunction isImageType(value) {\n  return REGEXP_IMAGE_TYPE.test(value);\n}\n\n/**\n * Convert image type to extension.\n * @param {string} value - The image type to convert.\n * @returns {string} Returns the image extension.\n */\nfunction imageTypeToExtension(value) {\n  var extension = isImageType(value) ? value.substr(6) : '';\n  if (extension === 'jpeg') {\n    extension = 'jpg';\n  }\n  return \".\".concat(extension);\n}\nvar fromCharCode = String.fromCharCode;\n\n/**\n * Get string from char code in data view.\n * @param {DataView} dataView - The data view for read.\n * @param {number} start - The start index.\n * @param {number} length - The read length.\n * @returns {string} The read result.\n */\nfunction getStringFromCharCode(dataView, start, length) {\n  var str = '';\n  var i;\n  length += start;\n  for (i = start; i < length; i += 1) {\n    str += fromCharCode(dataView.getUint8(i));\n  }\n  return str;\n}\n\n/**\n * Check if `canvas.getContext('2d').getImageData` is available,\n * Firefox randomizes the output of that function in `privacy.resistFingerprinting` mode (#137)\n * @link https://github.com/nodeca/pica/blob/master/lib/utils.js\n * @returns {boolean} Returns `true` if it is available, else `false`.\n */\nfunction isCanvasAvailable() {\n  try {\n    var canvas = document.createElement('canvas');\n    canvas.width = 2;\n    canvas.height = 1;\n    var context = canvas.getContext('2d');\n    if (!context) return false;\n\n    // Create 2x1 image data containing RGBA values for two pixels\n    var imageData = context.createImageData(2, 1);\n\n    // First pixel: R=12, G=23, B=34, A=255\n    imageData.data[0] = 12;\n    imageData.data[1] = 23;\n    imageData.data[2] = 34;\n    imageData.data[3] = 255;\n\n    // Second pixel: R=45, G=56, B=67, A=255\n    imageData.data[4] = 45;\n    imageData.data[5] = 56;\n    imageData.data[6] = 67;\n    imageData.data[7] = 255;\n    context.putImageData(imageData, 0, 0);\n    var readBack = context.getImageData(0, 0, 2, 1);\n\n    // Expected pixel data (matching the written values)\n    var expected = [12, 23, 34, 255, 45, 56, 67, 255];\n\n    // Compare element by element to ensure write and read consistency\n    return readBack.data.every(function (value, index) {\n      return value === expected[index];\n    });\n  } catch (error) {\n    return false;\n  }\n}\nvar btoa = WINDOW.btoa;\n\n/**\n * Transform array buffer to Data URL.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.\n * @param {string} mimeType - The MIME type of the Data URL.\n * @returns {string} The result Data URL.\n */\nfunction arrayBufferToDataURL(arrayBuffer, mimeType) {\n  var chunks = [];\n  var chunkSize = 8192;\n  var uint8 = new Uint8Array(arrayBuffer);\n  while (uint8.length > 0) {\n    // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9\n    // eslint-disable-next-line prefer-spread\n    chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));\n    uint8 = uint8.subarray(chunkSize);\n  }\n  return \"data:\".concat(mimeType, \";base64,\").concat(btoa(chunks.join('')));\n}\n\n/**\n * Get orientation value from given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to read.\n * @returns {number} The read orientation value.\n */\nfunction resetAndGetOrientation(arrayBuffer) {\n  var dataView = new DataView(arrayBuffer);\n  var orientation;\n\n  // Ignores range error when the image does not have correct Exif information\n  try {\n    var littleEndian;\n    var app1Start;\n    var ifdStart;\n\n    // Only handle JPEG image (start by 0xFFD8)\n    if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {\n      var length = dataView.byteLength;\n      var offset = 2;\n      while (offset + 1 < length) {\n        if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {\n          app1Start = offset;\n          break;\n        }\n        offset += 1;\n      }\n    }\n    if (app1Start) {\n      var exifIDCode = app1Start + 4;\n      var tiffOffset = app1Start + 10;\n      if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {\n        var endianness = dataView.getUint16(tiffOffset);\n        littleEndian = endianness === 0x4949;\n        if (littleEndian || endianness === 0x4D4D /* bigEndian */) {\n          if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {\n            var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);\n            if (firstIFDOffset >= 0x00000008) {\n              ifdStart = tiffOffset + firstIFDOffset;\n            }\n          }\n        }\n      }\n    }\n    if (ifdStart) {\n      var _length = dataView.getUint16(ifdStart, littleEndian);\n      var _offset;\n      var i;\n      for (i = 0; i < _length; i += 1) {\n        _offset = ifdStart + i * 12 + 2;\n        if (dataView.getUint16(_offset, littleEndian) === 0x0112 /* Orientation */) {\n          // 8 is the offset of the current tag's value\n          _offset += 8;\n\n          // Get the original orientation value\n          orientation = dataView.getUint16(_offset, littleEndian);\n\n          // Override the orientation with its default value\n          dataView.setUint16(_offset, 1, littleEndian);\n          break;\n        }\n      }\n    }\n  } catch (e) {\n    orientation = 1;\n  }\n  return orientation;\n}\n\n/**\n * Parse Exif Orientation value.\n * @param {number} orientation - The orientation to parse.\n * @returns {Object} The parsed result.\n */\nfunction parseOrientation(orientation) {\n  var rotate = 0;\n  var scaleX = 1;\n  var scaleY = 1;\n  switch (orientation) {\n    // Flip horizontal\n    case 2:\n      scaleX = -1;\n      break;\n\n    // Rotate left 180\u00B0\n    case 3:\n      rotate = -180;\n      break;\n\n    // Flip vertical\n    case 4:\n      scaleY = -1;\n      break;\n\n    // Flip vertical and rotate right 90\u00B0\n    case 5:\n      rotate = 90;\n      scaleY = -1;\n      break;\n\n    // Rotate right 90\u00B0\n    case 6:\n      rotate = 90;\n      break;\n\n    // Flip horizontal and rotate right 90\u00B0\n    case 7:\n      rotate = 90;\n      scaleX = -1;\n      break;\n\n    // Rotate left 90\u00B0\n    case 8:\n      rotate = -90;\n      break;\n  }\n  return {\n    rotate: rotate,\n    scaleX: scaleX,\n    scaleY: scaleY\n  };\n}\nvar REGEXP_DECIMALS = /\\.\\d*(?:0|9){12}\\d*$/;\n\n/**\n * Normalize decimal number.\n * Check out {@link https://0.30000000000000004.com/}\n * @param {number} value - The value to normalize.\n * @param {number} [times=100000000000] - The times for normalizing.\n * @returns {number} Returns the normalized number.\n */\nfunction normalizeDecimalNumber(value) {\n  var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;\n  return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;\n}\n\n/**\n * Get the max sizes in a rectangle under the given aspect ratio.\n * @param {Object} data - The original sizes.\n * @param {string} [type='contain'] - The adjust type.\n * @returns {Object} The result sizes.\n */\nfunction getAdjustedSizes(_ref) {\n  var aspectRatio = _ref.aspectRatio,\n    height = _ref.height,\n    width = _ref.width;\n  var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'none';\n  var isValidWidth = isPositiveNumber(width);\n  var isValidHeight = isPositiveNumber(height);\n  if (isValidWidth && isValidHeight) {\n    var adjustedWidth = height * aspectRatio;\n    if ((type === 'contain' || type === 'none') && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {\n      height = width / aspectRatio;\n    } else {\n      width = height * aspectRatio;\n    }\n  } else if (isValidWidth) {\n    height = width / aspectRatio;\n  } else if (isValidHeight) {\n    width = height * aspectRatio;\n  }\n  return {\n    width: width,\n    height: height\n  };\n}\n\n/**\n * Get Exif information from the given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to read.\n * @returns {Array} The read Exif information.\n */\nfunction getExif(arrayBuffer) {\n  var array = toArray(new Uint8Array(arrayBuffer));\n  var length = array.length;\n  var segments = [];\n  var start = 0;\n  while (start + 3 < length) {\n    var value = array[start];\n    var next = array[start + 1];\n\n    // SOS (Start of Scan)\n    if (value === 0xFF && next === 0xDA) {\n      break;\n    }\n\n    // SOI (Start of Image)\n    if (value === 0xFF && next === 0xD8) {\n      start += 2;\n    } else {\n      var offset = array[start + 2] * 256 + array[start + 3];\n      var end = start + offset + 2;\n      var segment = array.slice(start, end);\n      segments.push(segment);\n      start = end;\n    }\n  }\n  return segments.reduce(function (exifArray, current) {\n    if (current[0] === 0xFF && current[1] === 0xE1) {\n      return exifArray.concat(current);\n    }\n    return exifArray;\n  }, []);\n}\n\n/**\n * Insert Exif information into the given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.\n * @param {Array} exifArray - The Exif information to insert.\n * @returns {ArrayBuffer} The transformed array buffer.\n */\nfunction insertExif(arrayBuffer, exifArray) {\n  var array = toArray(new Uint8Array(arrayBuffer));\n  if (array[2] !== 0xFF || array[3] !== 0xE0) {\n    return arrayBuffer;\n  }\n  var app0Length = array[4] * 256 + array[5];\n  var newArrayBuffer = [0xFF, 0xD8].concat(exifArray, array.slice(4 + app0Length));\n  return new Uint8Array(newArrayBuffer);\n}\n\nvar ArrayBuffer$1 = WINDOW.ArrayBuffer,\n  FileReader = WINDOW.FileReader;\nvar URL = WINDOW.URL || WINDOW.webkitURL;\nvar REGEXP_EXTENSION = /\\.\\w+$/;\nvar AnotherCompressor = WINDOW.Compressor;\n\n/**\n * Creates a new image compressor.\n * @class\n */\nvar Compressor = /*#__PURE__*/function () {\n  /**\n   * Create a new Compressor.\n   * @param {File|Blob} file - The target image file to compress.\n   * @param {Object} [options={}] - The configuration options.\n   */\n  function Compressor(file) {\n    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    _classCallCheck(this, Compressor);\n    this.file = file;\n    this.exif = [];\n    this.image = new Image();\n    this.options = _objectSpread2(_objectSpread2({}, DEFAULTS), options);\n    this.aborted = false;\n    this.result = null;\n    this.init();\n  }\n  return _createClass(Compressor, [{\n    key: \"init\",\n    value: function init() {\n      var _this = this;\n      var file = this.file,\n        options = this.options;\n      if (!isBlob$1(file)) {\n        this.fail(new Error('The first argument must be a File or Blob object.'));\n        return;\n      }\n      var mimeType = file.type;\n      if (!isImageType(mimeType)) {\n        this.fail(new Error('The first argument must be an image File or Blob object.'));\n        return;\n      }\n      if (!URL || !FileReader) {\n        this.fail(new Error('The current browser does not support image compression.'));\n        return;\n      }\n      if (!ArrayBuffer$1) {\n        options.checkOrientation = false;\n        options.retainExif = false;\n      }\n      var isJPEGImage = mimeType === 'image/jpeg';\n      var checkOrientation = isJPEGImage && options.checkOrientation;\n      var retainExif = isJPEGImage && options.retainExif;\n      if (URL && !checkOrientation && !retainExif) {\n        this.load({\n          url: URL.createObjectURL(file)\n        });\n      } else {\n        var reader = new FileReader();\n        this.reader = reader;\n        reader.onload = function (_ref) {\n          var target = _ref.target;\n          var result = target.result;\n          var data = {};\n          var orientation = 1;\n          if (checkOrientation) {\n            // Reset the orientation value to its default value 1\n            // as some iOS browsers will render image with its orientation\n            orientation = resetAndGetOrientation(result);\n            if (orientation > 1) {\n              _extends(data, parseOrientation(orientation));\n            }\n          }\n          if (retainExif) {\n            _this.exif = getExif(result);\n          }\n          if (checkOrientation || retainExif) {\n            if (!URL\n\n            // Generate a new URL with the default orientation value 1.\n            || orientation > 1) {\n              data.url = arrayBufferToDataURL(result, mimeType);\n            } else {\n              data.url = URL.createObjectURL(file);\n            }\n          } else {\n            data.url = result;\n          }\n          _this.load(data);\n        };\n        reader.onabort = function () {\n          _this.fail(new Error('Aborted to read the image with FileReader.'));\n        };\n        reader.onerror = function () {\n          _this.fail(new Error('Failed to read the image with FileReader.'));\n        };\n        reader.onloadend = function () {\n          _this.reader = null;\n        };\n        if (checkOrientation || retainExif) {\n          reader.readAsArrayBuffer(file);\n        } else {\n          reader.readAsDataURL(file);\n        }\n      }\n    }\n  }, {\n    key: \"load\",\n    value: function load(data) {\n      var _this2 = this;\n      var file = this.file,\n        image = this.image;\n      image.onload = function () {\n        if (isCanvasAvailable()) {\n          _this2.draw(_objectSpread2(_objectSpread2({}, data), {}, {\n            naturalWidth: image.naturalWidth,\n            naturalHeight: image.naturalHeight\n          }));\n        } else {\n          _this2.done({\n            naturalWidth: image.naturalWidth,\n            naturalHeight: image.naturalHeight,\n            result: null\n          });\n        }\n      };\n      image.onabort = function () {\n        _this2.fail(new Error('Aborted to load the image.'));\n      };\n      image.onerror = function () {\n        _this2.fail(new Error('Failed to load the image.'));\n      };\n\n      // Match all browsers that use WebKit as the layout engine in iOS devices,\n      // such as Safari for iOS, Chrome for iOS, and in-app browsers.\n      if (WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent)) {\n        // Fix the `The operation is insecure` error (#57)\n        image.crossOrigin = 'anonymous';\n      }\n      image.alt = file.name;\n      image.src = data.url;\n    }\n  }, {\n    key: \"draw\",\n    value: function draw(_ref2) {\n      var _this3 = this;\n      var naturalWidth = _ref2.naturalWidth,\n        naturalHeight = _ref2.naturalHeight,\n        _ref2$rotate = _ref2.rotate,\n        rotate = _ref2$rotate === void 0 ? 0 : _ref2$rotate,\n        _ref2$scaleX = _ref2.scaleX,\n        scaleX = _ref2$scaleX === void 0 ? 1 : _ref2$scaleX,\n        _ref2$scaleY = _ref2.scaleY,\n        scaleY = _ref2$scaleY === void 0 ? 1 : _ref2$scaleY;\n      var file = this.file,\n        image = this.image,\n        options = this.options;\n      var canvas = document.createElement('canvas');\n      var context = canvas.getContext('2d');\n      var is90DegreesRotated = Math.abs(rotate) % 180 === 90;\n      var resizable = (options.resize === 'contain' || options.resize === 'cover') && isPositiveNumber(options.width) && isPositiveNumber(options.height);\n      var maxWidth = Math.max(options.maxWidth, 0) || Infinity;\n      var maxHeight = Math.max(options.maxHeight, 0) || Infinity;\n      var minWidth = Math.max(options.minWidth, 0) || 0;\n      var minHeight = Math.max(options.minHeight, 0) || 0;\n      var aspectRatio = naturalWidth / naturalHeight;\n      var width = options.width,\n        height = options.height;\n      if (is90DegreesRotated) {\n        var _ref3 = [maxHeight, maxWidth];\n        maxWidth = _ref3[0];\n        maxHeight = _ref3[1];\n        var _ref4 = [minHeight, minWidth];\n        minWidth = _ref4[0];\n        minHeight = _ref4[1];\n        var _ref5 = [height, width];\n        width = _ref5[0];\n        height = _ref5[1];\n      }\n      if (resizable) {\n        aspectRatio = width / height;\n      }\n      var _getAdjustedSizes = getAdjustedSizes({\n        aspectRatio: aspectRatio,\n        width: maxWidth,\n        height: maxHeight\n      }, 'contain');\n      maxWidth = _getAdjustedSizes.width;\n      maxHeight = _getAdjustedSizes.height;\n      var _getAdjustedSizes2 = getAdjustedSizes({\n        aspectRatio: aspectRatio,\n        width: minWidth,\n        height: minHeight\n      }, 'cover');\n      minWidth = _getAdjustedSizes2.width;\n      minHeight = _getAdjustedSizes2.height;\n      if (resizable) {\n        var _getAdjustedSizes3 = getAdjustedSizes({\n          aspectRatio: aspectRatio,\n          width: width,\n          height: height\n        }, options.resize);\n        width = _getAdjustedSizes3.width;\n        height = _getAdjustedSizes3.height;\n      } else {\n        var _getAdjustedSizes4 = getAdjustedSizes({\n          aspectRatio: aspectRatio,\n          width: width,\n          height: height\n        });\n        var _getAdjustedSizes4$wi = _getAdjustedSizes4.width;\n        width = _getAdjustedSizes4$wi === void 0 ? naturalWidth : _getAdjustedSizes4$wi;\n        var _getAdjustedSizes4$he = _getAdjustedSizes4.height;\n        height = _getAdjustedSizes4$he === void 0 ? naturalHeight : _getAdjustedSizes4$he;\n      }\n      width = Math.floor(normalizeDecimalNumber(Math.min(Math.max(width, minWidth), maxWidth)));\n      height = Math.floor(normalizeDecimalNumber(Math.min(Math.max(height, minHeight), maxHeight)));\n      var destX = -width / 2;\n      var destY = -height / 2;\n      var destWidth = width;\n      var destHeight = height;\n      var params = [];\n      if (resizable) {\n        var srcX = 0;\n        var srcY = 0;\n        var srcWidth = naturalWidth;\n        var srcHeight = naturalHeight;\n        var _getAdjustedSizes5 = getAdjustedSizes({\n          aspectRatio: aspectRatio,\n          width: naturalWidth,\n          height: naturalHeight\n        }, {\n          contain: 'cover',\n          cover: 'contain'\n        }[options.resize]);\n        srcWidth = _getAdjustedSizes5.width;\n        srcHeight = _getAdjustedSizes5.height;\n        srcX = (naturalWidth - srcWidth) / 2;\n        srcY = (naturalHeight - srcHeight) / 2;\n        params.push(srcX, srcY, srcWidth, srcHeight);\n      }\n      params.push(destX, destY, destWidth, destHeight);\n      if (is90DegreesRotated) {\n        var _ref6 = [height, width];\n        width = _ref6[0];\n        height = _ref6[1];\n      }\n      canvas.width = width;\n      canvas.height = height;\n      if (!isImageType(options.mimeType)) {\n        options.mimeType = file.type;\n      }\n      var fillStyle = 'transparent';\n\n      // Converts PNG files over the `convertSize` to JPEGs.\n      if (file.size > options.convertSize && options.convertTypes.indexOf(options.mimeType) >= 0) {\n        options.mimeType = 'image/jpeg';\n      }\n      var isJPEGImage = options.mimeType === 'image/jpeg';\n      if (isJPEGImage) {\n        fillStyle = '#fff';\n      }\n\n      // Override the default fill color (#000, black)\n      context.fillStyle = fillStyle;\n      context.fillRect(0, 0, width, height);\n      if (options.beforeDraw) {\n        options.beforeDraw.call(this, context, canvas);\n      }\n      if (this.aborted) {\n        return;\n      }\n      context.save();\n      context.translate(width / 2, height / 2);\n      context.rotate(rotate * Math.PI / 180);\n      context.scale(scaleX, scaleY);\n      context.drawImage.apply(context, [image].concat(params));\n      context.restore();\n      if (options.drew) {\n        options.drew.call(this, context, canvas);\n      }\n      if (this.aborted) {\n        return;\n      }\n      var callback = function callback(blob) {\n        if (!_this3.aborted) {\n          var done = function done(result) {\n            return _this3.done({\n              naturalWidth: naturalWidth,\n              naturalHeight: naturalHeight,\n              result: result\n            });\n          };\n          if (blob && isJPEGImage && options.retainExif && _this3.exif && _this3.exif.length > 0) {\n            var next = function next(arrayBuffer) {\n              return done(toBlob(arrayBufferToDataURL(insertExif(arrayBuffer, _this3.exif), options.mimeType)));\n            };\n            if (blob.arrayBuffer) {\n              blob.arrayBuffer().then(next).catch(function () {\n                _this3.fail(new Error('Failed to read the compressed image with Blob.arrayBuffer().'));\n              });\n            } else {\n              var reader = new FileReader();\n              _this3.reader = reader;\n              reader.onload = function (_ref7) {\n                var target = _ref7.target;\n                next(target.result);\n              };\n              reader.onabort = function () {\n                _this3.fail(new Error('Aborted to read the compressed image with FileReader.'));\n              };\n              reader.onerror = function () {\n                _this3.fail(new Error('Failed to read the compressed image with FileReader.'));\n              };\n              reader.onloadend = function () {\n                _this3.reader = null;\n              };\n              reader.readAsArrayBuffer(blob);\n            }\n          } else {\n            done(blob);\n          }\n        }\n      };\n      if (canvas.toBlob) {\n        canvas.toBlob(callback, options.mimeType, options.quality);\n      } else {\n        callback(toBlob(canvas.toDataURL(options.mimeType, options.quality)));\n      }\n    }\n  }, {\n    key: \"done\",\n    value: function done(_ref8) {\n      var naturalWidth = _ref8.naturalWidth,\n        naturalHeight = _ref8.naturalHeight,\n        result = _ref8.result;\n      var file = this.file,\n        image = this.image,\n        options = this.options;\n      if (URL && image.src.indexOf('blob:') === 0) {\n        URL.revokeObjectURL(image.src);\n      }\n      if (result) {\n        // Returns original file if the result is greater than it and without size related options\n        if (options.strict && !options.retainExif && result.size > file.size && options.mimeType === file.type && !(options.width > naturalWidth || options.height > naturalHeight || options.minWidth > naturalWidth || options.minHeight > naturalHeight || options.maxWidth < naturalWidth || options.maxHeight < naturalHeight)) {\n          result = file;\n        } else {\n          var fileName = file.name;\n\n          // Convert the extension to match its type\n          if (fileName && result.type !== file.type) {\n            fileName = fileName.replace(REGEXP_EXTENSION, imageTypeToExtension(result.type));\n          }\n          try {\n            // Convert the resulting Blob object into a File object for modern browsers.\n            result = new File([result], fileName, {\n              type: result.type\n            });\n          } catch (error) {\n            // Fallback to Blob if the File constructor is not supported.\n            var date = new Date();\n            result.name = fileName;\n\n            // The last modified date is not accurate, but it's better than nothing.\n            result.lastModified = date.getTime();\n            result.lastModifiedDate = date;\n          }\n        }\n      } else {\n        // Returns original file if the result is null in some cases.\n        result = file;\n      }\n      this.result = result;\n      if (options.success) {\n        options.success.call(this, result);\n      }\n    }\n  }, {\n    key: \"fail\",\n    value: function fail(err) {\n      var options = this.options;\n      if (options.error) {\n        options.error.call(this, err);\n      } else {\n        throw err;\n      }\n    }\n  }, {\n    key: \"abort\",\n    value: function abort() {\n      if (!this.aborted) {\n        this.aborted = true;\n        if (this.reader) {\n          this.reader.abort();\n        } else if (!this.image.complete) {\n          this.image.onload = null;\n          this.image.onabort();\n        } else {\n          this.fail(new Error('The compression process has been aborted.'));\n        }\n      }\n    }\n\n    /**\n     * Creates a new Compressor instance.\n     * @param {File|Blob} file - The target image file to compress.\n     * @param {Object} [options={}] - The configuration options.\n     * @returns {Compressor} A new Compressor instance.\n     */\n  }], [{\n    key: \"create\",\n    value: function create(file, options) {\n      return new Compressor(file, options);\n    }\n\n    /**\n     * Change the default options.\n     * @param {Object} options - The new default options.\n     */\n  }, {\n    key: \"setDefaults\",\n    value: function setDefaults(options) {\n      _extends(DEFAULTS, options);\n    }\n\n    /**\n     * Get the no conflict compressor class.\n     * @returns {Compressor} The compressor class.\n     */\n  }, {\n    key: \"noConflict\",\n    value: function noConflict() {\n      window.Compressor = AnotherCompressor;\n      return Compressor;\n    }\n  }]);\n}();\n\nmodule.exports = Compressor;\n", "\"use strict\";\n\nmodule.exports = {\n  strings: {\n    // Shown in the Status Bar\n    compressingImages: 'Compressing images...',\n    compressedX: 'Saved %{size} by compressing images'\n  }\n};", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nvar _RateLimitedQueue2 = require(\"@uppy/utils/lib/RateLimitedQueue\");\n\nfunction _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError(\"attempted to use private field on non-instance\"); } return receiver; }\n\nvar id = 0;\n\nfunction _classPrivateFieldLooseKey(name) { return \"__private_\" + id++ + \"_\" + name; }\n\nconst getFileNameAndExtension = require(\"@uppy/utils/lib/getFileNameAndExtension\");\n\nconst prettierBytes = require(\"@transloadit/prettier-bytes\");\n\nconst CompressorJS = require(\"compressorjs/dist/compressor.common.js\");\n\nconst locale = require(\"./locale.js\");\n\nvar _RateLimitedQueue = /*#__PURE__*/_classPrivateFieldLooseKey(\"RateLimitedQueue\");\n\nclass Compressor extends _core.BasePlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    Object.defineProperty(this, _RateLimitedQueue, {\n      writable: true,\n      value: void 0\n    });\n    this.id = this.opts.id || 'Compressor';\n    this.type = 'modifier';\n    this.defaultLocale = locale;\n    const defaultOptions = {\n      quality: 0.6,\n      limit: 10\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    _classPrivateFieldLooseBase(this, _RateLimitedQueue)[_RateLimitedQueue] = new _RateLimitedQueue2.RateLimitedQueue(this.opts.limit);\n    this.i18nInit();\n    this.prepareUpload = this.prepareUpload.bind(this);\n    this.compress = this.compress.bind(this);\n  }\n\n  compress(blob) {\n    return new Promise((resolve, reject) => {\n      /* eslint-disable no-new */\n      new CompressorJS(blob, { ...this.opts,\n        success: resolve,\n        error: reject\n      });\n    });\n  }\n\n  async prepareUpload(fileIDs) {\n    let totalCompressedSize = 0;\n    const compressedFiles = [];\n\n    const compressAndApplyResult = _classPrivateFieldLooseBase(this, _RateLimitedQueue)[_RateLimitedQueue].wrapPromiseFunction(async file => {\n      try {\n        const compressedBlob = await this.compress(file.data);\n        const compressedSavingsSize = file.data.size - compressedBlob.size;\n        this.uppy.log(`[Image Compressor] Image ${file.id} compressed by ${prettierBytes(compressedSavingsSize)}`);\n        totalCompressedSize += compressedSavingsSize;\n        const {\n          name,\n          type,\n          size\n        } = compressedBlob;\n        const extension = name && getFileNameAndExtension(name).extension;\n        this.uppy.setFileState(file.id, { ...(name && {\n            name\n          }),\n          ...(extension && {\n            extension\n          }),\n          ...(type && {\n            type\n          }),\n          ...(size && {\n            size\n          }),\n          data: compressedBlob\n        });\n        this.uppy.setFileMeta(file.id, {\n          type\n        });\n        compressedFiles.push(file);\n      } catch (err) {\n        this.uppy.log(`[Image Compressor] Failed to compress ${file.id}:`, 'warning');\n        this.uppy.log(err, 'warning');\n      }\n    });\n\n    const promises = fileIDs.map(fileID => {\n      const file = this.uppy.getFile(fileID);\n      this.uppy.emit('preprocess-progress', file, {\n        mode: 'indeterminate',\n        message: this.i18n('compressingImages')\n      });\n\n      if (file.isRemote) {\n        return Promise.resolve();\n      } // Some browsers (Firefox) add blobs with empty file type, when files are\n      // added from a folder. Uppy auto-detects type from extension, but leaves the original blob intact.\n      // However, Compressor.js failes when file has no type, so we set it here\n\n\n      if (!file.data.type) {\n        file.data = file.data.slice(0, file.data.size, file.type);\n      }\n\n      if (!file.type.startsWith('image/')) {\n        return Promise.resolve();\n      }\n\n      return compressAndApplyResult(file);\n    }); // Why emit `preprocess-complete` for all files at once, instead of\n    // above when each is processed?\n    // Because it leads to StatusBar showing a weird \u201Cupload 6 files\u201D button,\n    // while waiting for all the files to complete pre-processing.\n\n    await Promise.all(promises);\n    this.uppy.emit('compressor:complete', compressedFiles); // Only show informer if Compressor mananged to save at least a kilobyte\n\n    if (totalCompressedSize > 1024) {\n      this.uppy.info(this.i18n('compressedX', {\n        size: prettierBytes(totalCompressedSize)\n      }), 'info');\n    }\n\n    for (const fileID of fileIDs) {\n      const file = this.uppy.getFile(fileID);\n      this.uppy.emit('preprocess-complete', file);\n    }\n  }\n\n  install() {\n    this.uppy.addPreProcessor(this.prepareUpload);\n  }\n\n  uninstall() {\n    this.uppy.removePreProcessor(this.prepareUpload);\n  }\n\n}\n\nmodule.exports = Compressor;", "'use strict';\n\nexports.__esModule = true;\nexports.default = getFormData;\nexports.getFieldData = getFieldData;\nvar NODE_LIST_CLASSES = {\n  '[object HTMLCollection]': true,\n  '[object NodeList]': true,\n  '[object RadioNodeList]': true\n\n  // .type values for elements which can appear in .elements and should be ignored\n};var IGNORED_ELEMENT_TYPES = {\n  'button': true,\n  'fieldset': true,\n  'reset': true,\n  'submit': true\n};\n\nvar CHECKED_INPUT_TYPES = {\n  'checkbox': true,\n  'radio': true\n};\n\nvar TRIM_RE = /^\\s+|\\s+$/g;\n\nvar slice = Array.prototype.slice;\nvar toString = Object.prototype.toString;\n\n/**\n * @param {HTMLFormElement} form\n * @param {Object} options\n * @return {Object.<string,(string|Array.<string>)>} an object containing\n *   submittable value(s) held in the form's .elements collection, with\n *   properties named as per element names or ids.\n */\n\nfunction getFormData(form) {\n  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { trim: false };\n\n  if (!form) {\n    throw new Error('A form is required by getFormData, was given form=' + form);\n  }\n\n  var data = {};\n  var elementName = void 0;\n  var elementNames = [];\n  var elementNameLookup = {};\n\n  // Get unique submittable element names for the form\n  for (var i = 0, l = form.elements.length; i < l; i++) {\n    var element = form.elements[i];\n    if (IGNORED_ELEMENT_TYPES[element.type] || element.disabled) {\n      continue;\n    }\n    elementName = element.name || element.id;\n    if (elementName && !elementNameLookup[elementName]) {\n      elementNames.push(elementName);\n      elementNameLookup[elementName] = true;\n    }\n  }\n\n  // Extract element data name-by-name for consistent handling of special cases\n  // around elements which contain multiple inputs.\n  for (var _i = 0, _l = elementNames.length; _i < _l; _i++) {\n    elementName = elementNames[_i];\n    var value = getFieldData(form, elementName, options);\n    if (value != null) {\n      data[elementName] = value;\n    }\n  }\n\n  return data;\n}\n\n/**\n * @param {HTMLFormElement} form\n * @param {string} fieldName\n * @param {Object} options\n * @return {(string|Array.<string>)} submittable value(s) in the form for a\n *   named element from its .elements collection, or null if there was no\n *   element with that name or the element had no submittable value(s).\n */\nfunction getFieldData(form, fieldName) {\n  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { trim: false };\n\n  if (!form) {\n    throw new Error('A form is required by getFieldData, was given form=' + form);\n  }\n  if (!fieldName && toString.call(fieldName) !== '[object String]') {\n    throw new Error('A field name is required by getFieldData, was given fieldName=' + fieldName);\n  }\n\n  var element = form.elements[fieldName];\n  if (!element || element.disabled) {\n    return null;\n  }\n\n  if (!NODE_LIST_CLASSES[toString.call(element)]) {\n    return getFormElementValue(element, options.trim);\n  }\n\n  // Deal with multiple form controls which have the same name\n  var data = [];\n  var allRadios = true;\n  for (var i = 0, l = element.length; i < l; i++) {\n    if (element[i].disabled) {\n      continue;\n    }\n    if (allRadios && element[i].type !== 'radio') {\n      allRadios = false;\n    }\n    var value = getFormElementValue(element[i], options.trim);\n    if (value != null) {\n      data = data.concat(value);\n    }\n  }\n\n  // Special case for an element with multiple same-named inputs which were all\n  // radio buttons: if there was a selected value, only return the value.\n  if (allRadios && data.length === 1) {\n    return data[0];\n  }\n\n  return data.length > 0 ? data : null;\n}\n\n/**\n * @param {HTMLElement} element a form element.\n * @param {booleam} trim should values for text entry inputs be trimmed?\n * @return {(string|Array.<string>|File|Array.<File>)} the element's submittable\n *   value(s), or null if it had none.\n */\nfunction getFormElementValue(element, trim) {\n  var value = null;\n  var type = element.type;\n\n\n  if (type === 'select-one') {\n    if (element.options.length) {\n      value = element.options[element.selectedIndex].value;\n    }\n    return value;\n  }\n\n  if (type === 'select-multiple') {\n    value = [];\n    for (var i = 0, l = element.options.length; i < l; i++) {\n      if (element.options[i].selected) {\n        value.push(element.options[i].value);\n      }\n    }\n    if (value.length === 0) {\n      value = null;\n    }\n    return value;\n  }\n\n  // If a file input doesn't have a files attribute, fall through to using its\n  // value attribute.\n  if (type === 'file' && 'files' in element) {\n    if (element.multiple) {\n      value = slice.call(element.files);\n      if (value.length === 0) {\n        value = null;\n      }\n    } else {\n      // Should be null if not present, according to the spec\n      value = element.files[0];\n    }\n    return value;\n  }\n\n  if (!CHECKED_INPUT_TYPES[type]) {\n    value = trim ? element.value.replace(TRIM_RE, '') : element.value;\n  } else if (element.checked) {\n    value = element.value;\n  }\n\n  return value;\n}\n\n// For UMD build access to getFieldData\ngetFormData.getFieldData = getFieldData;", "\"use strict\";\n\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst findDOMElement = require(\"@uppy/utils/lib/findDOMElement\");\n\nconst toArray = require(\"@uppy/utils/lib/toArray\");\n\nconst getFormData = require(\"get-form-data\").default || require(\"get-form-data\");\n\nconst packageJson = {\n  \"version\": \"2.0.7\"\n};\n/**\n * Form\n */\n\nclass Form extends BasePlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.type = 'acquirer';\n    this.id = this.opts.id || 'Form';\n    this.title = 'Form'; // set default options\n\n    const defaultOptions = {\n      target: null,\n      resultName: 'uppyResult',\n      getMetaFromForm: true,\n      addResultToForm: true,\n      submitOnSuccess: false,\n      triggerUploadOnSubmit: false\n    }; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.handleFormSubmit = this.handleFormSubmit.bind(this);\n    this.handleUploadStart = this.handleUploadStart.bind(this);\n    this.handleSuccess = this.handleSuccess.bind(this);\n    this.addResultToForm = this.addResultToForm.bind(this);\n    this.getMetaFromForm = this.getMetaFromForm.bind(this);\n  }\n\n  handleUploadStart() {\n    if (this.opts.getMetaFromForm) {\n      this.getMetaFromForm();\n    }\n  }\n\n  handleSuccess(result) {\n    if (this.opts.addResultToForm) {\n      this.addResultToForm(result);\n    }\n\n    if (this.opts.submitOnSuccess) {\n      this.form.submit();\n    }\n  }\n\n  handleFormSubmit(ev) {\n    if (this.opts.triggerUploadOnSubmit) {\n      ev.preventDefault();\n      const elements = toArray(ev.target.elements);\n      const disabledByUppy = [];\n      elements.forEach(el => {\n        const isButton = el.tagName === 'BUTTON' || el.tagName === 'INPUT' && el.type === 'submit';\n\n        if (isButton && !el.disabled) {\n          el.disabled = true; // eslint-disable-line no-param-reassign\n\n          disabledByUppy.push(el);\n        }\n      });\n      this.uppy.upload().then(() => {\n        disabledByUppy.forEach(button => {\n          button.disabled = false; // eslint-disable-line no-param-reassign\n        });\n      }, err => {\n        disabledByUppy.forEach(button => {\n          button.disabled = false; // eslint-disable-line no-param-reassign\n        });\n        return Promise.reject(err);\n      }).catch(err => {\n        this.uppy.log(err.stack || err.message || err);\n      });\n    }\n  }\n\n  addResultToForm(result) {\n    this.uppy.log('[Form] Adding result to the original form:');\n    this.uppy.log(result);\n    let resultInput = this.form.querySelector(`[name=\"${this.opts.resultName}\"]`);\n\n    if (resultInput) {\n      // Append new result to the previous result array.\n      // If the previous result is empty, or not an array,\n      // set it to an empty array.\n      let updatedResult;\n\n      try {\n        updatedResult = JSON.parse(resultInput.value);\n      } catch (err) {// Nothing, since we check for array below anyway\n      }\n\n      if (!Array.isArray(updatedResult)) {\n        updatedResult = [];\n      }\n\n      updatedResult.push(result);\n      resultInput.value = JSON.stringify(updatedResult);\n      return;\n    }\n\n    resultInput = document.createElement('input');\n    resultInput.name = this.opts.resultName;\n    resultInput.type = 'hidden';\n    resultInput.value = JSON.stringify([result]);\n    this.form.appendChild(resultInput);\n  }\n\n  getMetaFromForm() {\n    const formMeta = getFormData(this.form); // We want to exclude meta the the Form plugin itself has added\n    // See https://github.com/transloadit/uppy/issues/1637\n\n    delete formMeta[this.opts.resultName];\n    this.uppy.setMeta(formMeta);\n  }\n\n  install() {\n    this.form = findDOMElement(this.opts.target);\n\n    if (!this.form || this.form.nodeName !== 'FORM') {\n      this.uppy.log('Form plugin requires a <form> target element passed in options to operate, none was found', 'error');\n      return;\n    }\n\n    this.form.addEventListener('submit', this.handleFormSubmit);\n    this.uppy.on('upload', this.handleUploadStart);\n    this.uppy.on('complete', this.handleSuccess);\n  }\n\n  uninstall() {\n    this.form.removeEventListener('submit', this.handleFormSubmit);\n    this.uppy.off('upload', this.handleUploadStart);\n    this.uppy.off('complete', this.handleSuccess);\n  }\n\n}\n\nForm.VERSION = packageJson.version;\nmodule.exports = Form;", "\"use strict\";\n\nconst isSupported = typeof navigator !== 'undefined' && 'serviceWorker' in navigator;\n\nfunction waitForServiceWorker() {\n  return new Promise((resolve, reject) => {\n    if (!isSupported) {\n      reject(new Error('Unsupported'));\n    } else if (navigator.serviceWorker.controller) {\n      // A serviceWorker is already registered and active.\n      resolve();\n    } else {\n      navigator.serviceWorker.addEventListener('controllerchange', () => {\n        resolve();\n      });\n    }\n  });\n}\n\nclass ServiceWorkerStore {\n  constructor(opts) {\n    this.ready = waitForServiceWorker();\n    this.name = opts.storeName;\n  }\n\n  list() {\n    const defer = {};\n    const promise = new Promise((resolve, reject) => {\n      defer.resolve = resolve;\n      defer.reject = reject;\n    });\n\n    const onMessage = event => {\n      if (event.data.store !== this.name) {\n        return;\n      }\n\n      switch (event.data.type) {\n        case 'uppy/ALL_FILES':\n          defer.resolve(event.data.files);\n          navigator.serviceWorker.removeEventListener('message', onMessage);\n          break;\n\n        default:\n          defer.reject();\n      }\n    };\n\n    this.ready.then(() => {\n      navigator.serviceWorker.addEventListener('message', onMessage);\n      navigator.serviceWorker.controller.postMessage({\n        type: 'uppy/GET_FILES',\n        store: this.name\n      });\n    });\n    return promise;\n  }\n\n  put(file) {\n    return this.ready.then(() => {\n      navigator.serviceWorker.controller.postMessage({\n        type: 'uppy/ADD_FILE',\n        store: this.name,\n        file\n      });\n    });\n  }\n\n  delete(fileID) {\n    return this.ready.then(() => {\n      navigator.serviceWorker.controller.postMessage({\n        type: 'uppy/REMOVE_FILE',\n        store: this.name,\n        fileID\n      });\n    });\n  }\n\n}\n\nServiceWorkerStore.isSupported = isSupported;\nmodule.exports = ServiceWorkerStore;", "\"use strict\";\n\nconst indexedDB = typeof window !== 'undefined' && (window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB);\nconst isSupported = !!indexedDB;\nconst DB_NAME = 'uppy-blobs';\nconst STORE_NAME = 'files'; // maybe have a thumbnail store in the future\n\nconst DEFAULT_EXPIRY = 24 * 60 * 60 * 1000; // 24 hours\n\nconst DB_VERSION = 3; // Set default `expires` dates on existing stored blobs.\n\nfunction migrateExpiration(store) {\n  const request = store.openCursor();\n\n  request.onsuccess = event => {\n    const cursor = event.target.result;\n\n    if (!cursor) {\n      return;\n    }\n\n    const entry = cursor.value;\n    entry.expires = Date.now() + DEFAULT_EXPIRY;\n    cursor.update(entry);\n  };\n}\n\nfunction connect(dbName) {\n  const request = indexedDB.open(dbName, DB_VERSION);\n  return new Promise((resolve, reject) => {\n    request.onupgradeneeded = event => {\n      const db = event.target.result;\n      const {\n        transaction\n      } = event.currentTarget;\n\n      if (event.oldVersion < 2) {\n        // Added in v2: DB structure changed to a single shared object store\n        const store = db.createObjectStore(STORE_NAME, {\n          keyPath: 'id'\n        });\n        store.createIndex('store', 'store', {\n          unique: false\n        });\n      }\n\n      if (event.oldVersion < 3) {\n        // Added in v3\n        const store = transaction.objectStore(STORE_NAME);\n        store.createIndex('expires', 'expires', {\n          unique: false\n        });\n        migrateExpiration(store);\n      }\n\n      transaction.oncomplete = () => {\n        resolve(db);\n      };\n    };\n\n    request.onsuccess = event => {\n      resolve(event.target.result);\n    };\n\n    request.onerror = reject;\n  });\n}\n\nfunction waitForRequest(request) {\n  return new Promise((resolve, reject) => {\n    request.onsuccess = event => {\n      resolve(event.target.result);\n    };\n\n    request.onerror = reject;\n  });\n}\n\nlet cleanedUp = false;\n\nclass IndexedDBStore {\n  constructor(opts) {\n    this.opts = {\n      dbName: DB_NAME,\n      storeName: 'default',\n      expires: DEFAULT_EXPIRY,\n      // 24 hours\n      maxFileSize: 10 * 1024 * 1024,\n      // 10 MB\n      maxTotalSize: 300 * 1024 * 1024,\n      // 300 MB\n      ...opts\n    };\n    this.name = this.opts.storeName;\n\n    const createConnection = () => {\n      return connect(this.opts.dbName);\n    };\n\n    if (!cleanedUp) {\n      cleanedUp = true;\n      this.ready = IndexedDBStore.cleanup().then(createConnection, createConnection);\n    } else {\n      this.ready = createConnection();\n    }\n  }\n\n  key(fileID) {\n    return `${this.name}!${fileID}`;\n  }\n  /**\n   * List all file blobs currently in the store.\n   */\n\n\n  list() {\n    return this.ready.then(db => {\n      const transaction = db.transaction([STORE_NAME], 'readonly');\n      const store = transaction.objectStore(STORE_NAME);\n      const request = store.index('store').getAll(IDBKeyRange.only(this.name));\n      return waitForRequest(request);\n    }).then(files => {\n      const result = {};\n      files.forEach(file => {\n        result[file.fileID] = file.data;\n      });\n      return result;\n    });\n  }\n  /**\n   * Get one file blob from the store.\n   */\n\n\n  get(fileID) {\n    return this.ready.then(db => {\n      const transaction = db.transaction([STORE_NAME], 'readonly');\n      const request = transaction.objectStore(STORE_NAME).get(this.key(fileID));\n      return waitForRequest(request);\n    }).then(result => ({\n      id: result.data.fileID,\n      data: result.data.data\n    }));\n  }\n  /**\n   * Get the total size of all stored files.\n   *\n   * @private\n   */\n\n\n  getSize() {\n    return this.ready.then(db => {\n      const transaction = db.transaction([STORE_NAME], 'readonly');\n      const store = transaction.objectStore(STORE_NAME);\n      const request = store.index('store').openCursor(IDBKeyRange.only(this.name));\n      return new Promise((resolve, reject) => {\n        let size = 0;\n\n        request.onsuccess = event => {\n          const cursor = event.target.result;\n\n          if (cursor) {\n            size += cursor.value.data.size;\n            cursor.continue();\n          } else {\n            resolve(size);\n          }\n        };\n\n        request.onerror = () => {\n          reject(new Error('Could not retrieve stored blobs size'));\n        };\n      });\n    });\n  }\n  /**\n   * Save a file in the store.\n   */\n\n\n  put(file) {\n    if (file.data.size > this.opts.maxFileSize) {\n      return Promise.reject(new Error('File is too big to store.'));\n    }\n\n    return this.getSize().then(size => {\n      if (size > this.opts.maxTotalSize) {\n        return Promise.reject(new Error('No space left'));\n      }\n\n      return this.ready;\n    }).then(db => {\n      const transaction = db.transaction([STORE_NAME], 'readwrite');\n      const request = transaction.objectStore(STORE_NAME).add({\n        id: this.key(file.id),\n        fileID: file.id,\n        store: this.name,\n        expires: Date.now() + this.opts.expires,\n        data: file.data\n      });\n      return waitForRequest(request);\n    });\n  }\n  /**\n   * Delete a file blob from the store.\n   */\n\n\n  delete(fileID) {\n    return this.ready.then(db => {\n      const transaction = db.transaction([STORE_NAME], 'readwrite');\n      const request = transaction.objectStore(STORE_NAME).delete(this.key(fileID));\n      return waitForRequest(request);\n    });\n  }\n  /**\n   * Delete all stored blobs that have an expiry date that is before Date.now().\n   * This is a static method because it deletes expired blobs from _all_ Uppy instances.\n   */\n\n\n  static cleanup() {\n    return connect(DB_NAME).then(db => {\n      const transaction = db.transaction([STORE_NAME], 'readwrite');\n      const store = transaction.objectStore(STORE_NAME);\n      const request = store.index('expires').openCursor(IDBKeyRange.upperBound(Date.now()));\n      return new Promise((resolve, reject) => {\n        request.onsuccess = event => {\n          const cursor = event.target.result;\n\n          if (cursor) {\n            cursor.delete(); // Ignoring return value \u2026 it's not terrible if this goes wrong.\n\n            cursor.continue();\n          } else {\n            resolve(db);\n          }\n        };\n\n        request.onerror = reject;\n      });\n    }).then(db => {\n      db.close();\n    });\n  }\n\n}\n\nIndexedDBStore.isSupported = isSupported;\nmodule.exports = IndexedDBStore;", "\"use strict\";\n\n/**\n * Get uppy instance IDs for which state is stored.\n */\nfunction findUppyInstances() {\n  const instances = [];\n\n  for (let i = 0; i < localStorage.length; i++) {\n    const key = localStorage.key(i);\n\n    if (/^uppyState:/.test(key)) {\n      instances.push(key.slice('uppyState:'.length));\n    }\n  }\n\n  return instances;\n}\n/**\n * Try to JSON-parse a string, return null on failure.\n */\n\n\nfunction maybeParse(str) {\n  try {\n    return JSON.parse(str);\n  } catch (err) {\n    return null;\n  }\n}\n\nlet cleanedUp = false;\n\nclass MetaDataStore {\n  constructor(opts) {\n    this.opts = {\n      expires: 24 * 60 * 60 * 1000,\n      // 24 hours\n      ...opts\n    };\n    this.name = `uppyState:${opts.storeName}`;\n\n    if (!cleanedUp) {\n      cleanedUp = true;\n      MetaDataStore.cleanup();\n    }\n  }\n  /**\n   *\n   */\n\n\n  load() {\n    const savedState = localStorage.getItem(this.name);\n    if (!savedState) return null;\n    const data = maybeParse(savedState);\n    if (!data) return null; // Upgrade pre-0.20.0 uppyState: it used to be just a flat object,\n    // without `expires`.\n\n    if (!data.metadata) {\n      this.save(data);\n      return data;\n    }\n\n    return data.metadata;\n  }\n\n  save(metadata) {\n    const expires = Date.now() + this.opts.expires;\n    const state = JSON.stringify({\n      metadata,\n      expires\n    });\n    localStorage.setItem(this.name, state);\n  }\n  /**\n   * Remove all expired state.\n   */\n\n\n  static cleanup(instanceID) {\n    if (instanceID) {\n      localStorage.removeItem(`uppyState:${instanceID}`);\n      return;\n    }\n\n    const instanceIDs = findUppyInstances();\n    const now = Date.now();\n    instanceIDs.forEach(id => {\n      const data = localStorage.getItem(`uppyState:${id}`);\n      if (!data) return;\n      const obj = maybeParse(data);\n      if (!obj) return;\n\n      if (obj.expires && obj.expires < now) {\n        localStorage.removeItem(`uppyState:${id}`);\n      }\n    });\n  }\n\n}\n\nmodule.exports = MetaDataStore;", "\"use strict\";\n\nconst throttle = require(\"lodash.throttle\");\n\nconst BasePlugin = require(\"@uppy/core/lib/BasePlugin\");\n\nconst ServiceWorkerStore = require(\"./ServiceWorkerStore.js\");\n\nconst IndexedDBStore = require(\"./IndexedDBStore.js\");\n\nconst MetaDataStore = require(\"./MetaDataStore.js\");\n\nconst packageJson = {\n  \"version\": \"2.1.3\"\n};\n/**\n * The GoldenRetriever plugin \u2014 restores selected files and resumes uploads\n * after a closed tab or a browser crash!\n *\n * Uses localStorage, IndexedDB and ServiceWorker to do its magic, read more:\n * https://uppy.io/blog/2017/07/golden-retriever/\n */\n\nclass GoldenRetriever extends BasePlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n\n    this.addBlobToStores = file => {\n      if (file.isRemote) return;\n\n      if (this.ServiceWorkerStore) {\n        this.ServiceWorkerStore.put(file).catch(err => {\n          this.uppy.log('[GoldenRetriever] Could not store file', 'warning');\n          this.uppy.log(err);\n        });\n      }\n\n      this.IndexedDBStore.put(file).catch(err => {\n        this.uppy.log('[GoldenRetriever] Could not store file', 'warning');\n        this.uppy.log(err);\n      });\n    };\n\n    this.removeBlobFromStores = file => {\n      if (this.ServiceWorkerStore) {\n        this.ServiceWorkerStore.delete(file.id).catch(err => {\n          this.uppy.log('[GoldenRetriever] Failed to remove file', 'warning');\n          this.uppy.log(err);\n        });\n      }\n\n      this.IndexedDBStore.delete(file.id).catch(err => {\n        this.uppy.log('[GoldenRetriever] Failed to remove file', 'warning');\n        this.uppy.log(err);\n      });\n    };\n\n    this.replaceBlobInStores = file => {\n      this.removeBlobFromStores(file);\n      this.addBlobToStores(file);\n    };\n\n    this.handleRestoreConfirmed = () => {\n      this.uppy.log('[GoldenRetriever] Restore confirmed, proceeding...'); // start all uploads again when file blobs are restored\n\n      const {\n        currentUploads\n      } = this.uppy.getState();\n\n      if (currentUploads) {\n        this.uppy.resumeAll();\n        Object.keys(currentUploads).forEach(uploadId => {\n          this.uppy.restore(uploadId, currentUploads[uploadId]);\n        });\n      }\n\n      this.uppy.setState({\n        recoveredState: null\n      });\n    };\n\n    this.abortRestore = () => {\n      this.uppy.log('[GoldenRetriever] Aborting restore...');\n      const fileIDs = Object.keys(this.uppy.getState().files);\n      this.deleteBlobs(fileIDs).then(() => {\n        this.uppy.log(`[GoldenRetriever] Removed ${fileIDs.length} files`);\n      }).catch(err => {\n        this.uppy.log(`[GoldenRetriever] Could not remove ${fileIDs.length} files`, 'warning');\n        this.uppy.log(err);\n      });\n      this.uppy.cancelAll();\n      this.uppy.setState({\n        recoveredState: null\n      });\n      MetaDataStore.cleanup(this.uppy.opts.id);\n    };\n\n    this.handleComplete = _ref => {\n      let {\n        successful\n      } = _ref;\n      const fileIDs = successful.map(file => file.id);\n      this.deleteBlobs(fileIDs).then(() => {\n        this.uppy.log(`[GoldenRetriever] Removed ${successful.length} files that finished uploading`);\n      }).catch(err => {\n        this.uppy.log(`[GoldenRetriever] Could not remove ${successful.length} files that finished uploading`, 'warning');\n        this.uppy.log(err);\n      });\n      this.uppy.setState({\n        recoveredState: null\n      });\n      MetaDataStore.cleanup(this.uppy.opts.id);\n    };\n\n    this.restoreBlobs = () => {\n      if (this.uppy.getFiles().length > 0) {\n        Promise.all([this.loadFileBlobsFromServiceWorker(), this.loadFileBlobsFromIndexedDB()]).then(resultingArrayOfObjects => {\n          const blobs = { ...resultingArrayOfObjects[0],\n            ...resultingArrayOfObjects[1]\n          };\n          this.onBlobsLoaded(blobs);\n        });\n      } else {\n        this.uppy.log('[GoldenRetriever] No files need to be loaded, only restoring processing state...');\n      }\n    };\n\n    this.type = 'debugger';\n    this.id = this.opts.id || 'GoldenRetriever';\n    this.title = 'Golden Retriever';\n    const defaultOptions = {\n      expires: 24 * 60 * 60 * 1000,\n      // 24 hours\n      serviceWorker: false\n    };\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.MetaDataStore = new MetaDataStore({\n      expires: this.opts.expires,\n      storeName: uppy.getID()\n    });\n    this.ServiceWorkerStore = null;\n\n    if (this.opts.serviceWorker) {\n      this.ServiceWorkerStore = new ServiceWorkerStore({\n        storeName: uppy.getID()\n      });\n    }\n\n    this.IndexedDBStore = new IndexedDBStore({\n      expires: this.opts.expires,\n      ...(this.opts.indexedDB || {}),\n      storeName: uppy.getID()\n    });\n    this.saveFilesStateToLocalStorage = throttle(this.saveFilesStateToLocalStorage.bind(this), 500, {\n      leading: true,\n      trailing: true\n    });\n    this.restoreState = this.restoreState.bind(this);\n    this.loadFileBlobsFromServiceWorker = this.loadFileBlobsFromServiceWorker.bind(this);\n    this.loadFileBlobsFromIndexedDB = this.loadFileBlobsFromIndexedDB.bind(this);\n    this.onBlobsLoaded = this.onBlobsLoaded.bind(this);\n  }\n\n  restoreState() {\n    const savedState = this.MetaDataStore.load();\n\n    if (savedState) {\n      this.uppy.log('[GoldenRetriever] Recovered some state from Local Storage');\n      this.uppy.setState({\n        currentUploads: savedState.currentUploads || {},\n        files: savedState.files || {},\n        recoveredState: savedState\n      });\n      this.savedPluginData = savedState.pluginData;\n    }\n  }\n  /**\n   * Get file objects that are currently waiting: they've been selected,\n   * but aren't yet being uploaded.\n   */\n\n\n  getWaitingFiles() {\n    const waitingFiles = {};\n    this.uppy.getFiles().forEach(file => {\n      if (!file.progress || !file.progress.uploadStarted) {\n        waitingFiles[file.id] = file;\n      }\n    });\n    return waitingFiles;\n  }\n  /**\n   * Get file objects that are currently being uploaded. If a file has finished\n   * uploading, but the other files in the same batch have not, the finished\n   * file is also returned.\n   */\n\n\n  getUploadingFiles() {\n    const uploadingFiles = {};\n    const {\n      currentUploads\n    } = this.uppy.getState();\n\n    if (currentUploads) {\n      const uploadIDs = Object.keys(currentUploads);\n      uploadIDs.forEach(uploadID => {\n        const filesInUpload = currentUploads[uploadID].fileIDs;\n        filesInUpload.forEach(fileID => {\n          uploadingFiles[fileID] = this.uppy.getFile(fileID);\n        });\n      });\n    }\n\n    return uploadingFiles;\n  }\n\n  saveFilesStateToLocalStorage() {\n    const filesToSave = { ...this.getWaitingFiles(),\n      ...this.getUploadingFiles()\n    }; // If all files have been removed by the user, clear recovery state\n\n    if (Object.keys(filesToSave).length === 0) {\n      if (this.uppy.getState().recoveredState !== null) {\n        this.uppy.setState({\n          recoveredState: null\n        });\n      }\n\n      MetaDataStore.cleanup(this.uppy.opts.id);\n      return;\n    } // We dont\u2019t need to store file.data on local files, because the actual blob will be restored later,\n    // and we want to avoid having weird properties in the serialized object.\n    // Also adding file.isRestored to all files, since they will be restored from local storage\n\n\n    const filesToSaveWithoutData = {};\n    Object.keys(filesToSave).forEach(file => {\n      if (filesToSave[file].isRemote) {\n        filesToSaveWithoutData[file] = { ...filesToSave[file],\n          isRestored: true\n        };\n      } else {\n        filesToSaveWithoutData[file] = { ...filesToSave[file],\n          isRestored: true,\n          data: null,\n          preview: null\n        };\n      }\n    });\n    const pluginData = {}; // TODO Find a better way to do this?\n    // Other plugins can attach a restore:get-data listener that receives this callback.\n    // Plugins can then use this callback (sync) to provide data to be stored.\n\n    this.uppy.emit('restore:get-data', data => {\n      Object.assign(pluginData, data);\n    });\n    const {\n      currentUploads\n    } = this.uppy.getState();\n    this.MetaDataStore.save({\n      currentUploads,\n      files: filesToSaveWithoutData,\n      pluginData\n    });\n  }\n\n  loadFileBlobsFromServiceWorker() {\n    if (!this.ServiceWorkerStore) {\n      return Promise.resolve({});\n    }\n\n    return this.ServiceWorkerStore.list().then(blobs => {\n      const files = this.uppy.getFiles();\n      const localFilesOnly = files.filter(file => {\n        // maybe && !file.progress.uploadComplete\n        return !file.isRemote;\n      });\n      const numberOfFilesRecovered = Object.keys(blobs).length;\n      const numberOfFilesTryingToRecover = localFilesOnly.length;\n\n      if (numberOfFilesRecovered === numberOfFilesTryingToRecover) {\n        this.uppy.log(`[GoldenRetriever] Successfully recovered ${numberOfFilesRecovered} blobs from Service Worker!`);\n        return blobs;\n      }\n\n      this.uppy.log('[GoldenRetriever] No blobs found in Service Worker, trying IndexedDB now...');\n      return {};\n    }).catch(err => {\n      this.uppy.log('[GoldenRetriever] Failed to recover blobs from Service Worker', 'warning');\n      this.uppy.log(err);\n      return {};\n    });\n  }\n\n  loadFileBlobsFromIndexedDB() {\n    return this.IndexedDBStore.list().then(blobs => {\n      const numberOfFilesRecovered = Object.keys(blobs).length;\n\n      if (numberOfFilesRecovered > 0) {\n        this.uppy.log(`[GoldenRetriever] Successfully recovered ${numberOfFilesRecovered} blobs from IndexedDB!`);\n        return blobs;\n      }\n\n      this.uppy.log('[GoldenRetriever] No blobs found in IndexedDB');\n      return {};\n    }).catch(err => {\n      this.uppy.log('[GoldenRetriever] Failed to recover blobs from IndexedDB', 'warning');\n      this.uppy.log(err);\n      return {};\n    });\n  }\n\n  onBlobsLoaded(blobs) {\n    const obsoleteBlobs = [];\n    const updatedFiles = { ...this.uppy.getState().files\n    }; // Loop through blobs that we can restore, add blobs to file objects\n\n    Object.keys(blobs).forEach(fileID => {\n      const originalFile = this.uppy.getFile(fileID);\n\n      if (!originalFile) {\n        obsoleteBlobs.push(fileID);\n        return;\n      }\n\n      const cachedData = blobs[fileID];\n      const updatedFileData = {\n        data: cachedData,\n        isRestored: true,\n        isGhost: false\n      };\n      updatedFiles[fileID] = { ...originalFile,\n        ...updatedFileData\n      };\n    }); // Loop through files that we can\u2019t restore fully \u2014 we only have meta, not blobs,\n    // set .isGhost on them, also set isRestored to all files\n\n    Object.keys(updatedFiles).forEach(fileID => {\n      if (updatedFiles[fileID].data === null) {\n        updatedFiles[fileID] = { ...updatedFiles[fileID],\n          isGhost: true\n        };\n      }\n    });\n    this.uppy.setState({\n      files: updatedFiles\n    });\n    this.uppy.emit('restored', this.savedPluginData);\n\n    if (obsoleteBlobs.length) {\n      this.deleteBlobs(obsoleteBlobs).then(() => {\n        this.uppy.log(`[GoldenRetriever] Cleaned up ${obsoleteBlobs.length} old files`);\n      }).catch(err => {\n        this.uppy.log(`[GoldenRetriever] Could not clean up ${obsoleteBlobs.length} old files`, 'warning');\n        this.uppy.log(err);\n      });\n    }\n  }\n\n  deleteBlobs(fileIDs) {\n    const promises = [];\n    fileIDs.forEach(id => {\n      if (this.ServiceWorkerStore) {\n        promises.push(this.ServiceWorkerStore.delete(id));\n      }\n\n      if (this.IndexedDBStore) {\n        promises.push(this.IndexedDBStore.delete(id));\n      }\n    });\n    return Promise.all(promises);\n  }\n\n  install() {\n    this.restoreState();\n    this.restoreBlobs();\n    this.uppy.on('file-added', this.addBlobToStores);\n    this.uppy.on('file-editor:complete', this.replaceBlobInStores);\n    this.uppy.on('file-removed', this.removeBlobFromStores); // TODO: the `state-update` is bad practise. It fires on any state change in Uppy\n    // or any state change in any of the plugins. We should to able to only listen\n    // for the state changes we need, somehow.\n\n    this.uppy.on('state-update', this.saveFilesStateToLocalStorage);\n    this.uppy.on('restore-confirmed', this.handleRestoreConfirmed);\n    this.uppy.on('restore-canceled', this.abortRestore);\n    this.uppy.on('complete', this.handleComplete);\n  }\n\n  uninstall() {\n    this.uppy.off('file-added', this.addBlobToStores);\n    this.uppy.off('file-editor:complete', this.replaceBlobInStores);\n    this.uppy.off('file-removed', this.removeBlobFromStores);\n    this.uppy.off('state-update', this.saveFilesStateToLocalStorage);\n    this.uppy.off('restore-confirmed', this.handleRestoreConfirmed);\n    this.uppy.off('restore-canceled', this.abortRestore);\n    this.uppy.off('complete', this.handleComplete);\n  }\n\n}\n\nGoldenRetriever.VERSION = packageJson.version;\nmodule.exports = GoldenRetriever;", "\"use strict\";\n\nvar _core = require(\"@uppy/core\");\n\nconst packageJson = {\n  \"version\": \"2.1.1\"\n};\n/* eslint-disable max-len */\n\n/**\n * Add Redux DevTools support to Uppy\n *\n * See https://medium.com/@zalmoxis/redux-devtools-without-redux-or-how-to-have-a-predictable-state-with-any-architecture-61c5f5a7716f\n * and https://github.com/zalmoxisus/mobx-remotedev/blob/master/src/monitorActions.js\n */\n\n/* eslint-enable max-len */\n\nclass ReduxDevTools extends _core.UIPlugin {\n  constructor(uppy, opts) {\n    super(uppy, opts);\n    this.type = 'debugger';\n    this.id = this.opts.id || 'ReduxDevTools';\n    this.title = 'Redux DevTools'; // set default options\n\n    const defaultOptions = {}; // merge default options with the ones set by user\n\n    this.opts = { ...defaultOptions,\n      ...opts\n    };\n    this.handleStateChange = this.handleStateChange.bind(this);\n    this.initDevTools = this.initDevTools.bind(this);\n  }\n\n  handleStateChange(prevState, nextState) {\n    this.devTools.send('UPPY_STATE_UPDATE', nextState);\n  }\n\n  initDevTools() {\n    this.devTools = window.devToolsExtension.connect();\n    this.devToolsUnsubscribe = this.devTools.subscribe(message => {\n      if (message.type === 'DISPATCH') {\n        // Implement monitors actions\n        switch (message.payload.type) {\n          case 'RESET':\n            this.uppy.reset();\n            return;\n\n          case 'IMPORT_STATE':\n            {\n              const {\n                computedStates\n              } = message.payload.nextLiftedState;\n              this.uppy.store.state = { ...this.uppy.getState(),\n                ...computedStates[computedStates.length - 1].state\n              };\n              this.uppy.updateAll(this.uppy.getState());\n              return;\n            }\n\n          case 'JUMP_TO_STATE':\n          case 'JUMP_TO_ACTION':\n            this.uppy.store.state = { ...this.uppy.getState(),\n              ...JSON.parse(message.state)\n            };\n            this.uppy.updateAll(this.uppy.getState());\n            break;\n\n          default:\n        }\n      }\n    });\n  }\n\n  install() {\n    // eslint-disable-next-line no-underscore-dangle\n    this.withDevTools = typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__;\n\n    if (this.withDevTools) {\n      this.initDevTools();\n      this.uppy.on('state-update', this.handleStateChange);\n    }\n  }\n\n  uninstall() {\n    if (this.withDevTools) {\n      this.devToolsUnsubscribe();\n      this.uppy.off('state-update', this.handleStateUpdate);\n    }\n  }\n\n}\n\nReduxDevTools.VERSION = packageJson.version;\nmodule.exports = ReduxDevTools;", "\"use strict\";\n\nconst fr_FR = {\n  pluralize(n) {\n    if (n === 1) {\n      return 0;\n    }\n\n    return 1;\n  }\n\n};\nfr_FR.strings = {\n  addBulkFilesFailed: {\n    '0': 'L\\'ajout de %{smart_count} fichier a \u00E9chou\u00E9',\n    '1': 'L\\'ajout de %{smart_count} fichiers a \u00E9chou\u00E9'\n  },\n  addMore: 'Ajouter d\\'autres',\n  addMoreFiles: 'Ajouter d\\'autres fichiers',\n  addingMoreFiles: 'En train d\\'ajouter des fichiers',\n  allFilesFromFolderNamed: 'Tous les fichiers du dossier %{name}',\n  allowAccessDescription: 'Pour prendre des photos ou enregistrer une vid\u00E9o avec votre cam\u00E9ra, veuillez autoriser l\\'acc\u00E8s \u00E0 votre cam\u00E9ra pour ce site.',\n  allowAccessTitle: 'Veuillez autoriser l\\'acc\u00E8s \u00E0 votre cam\u00E9ra',\n  authAborted: 'Authentification interrompue',\n  authenticateWith: 'Se connecter \u00E0 %{pluginName}',\n  authenticateWithTitle: 'Veuillez vous authentifier avec %{pluginName} pour s\u00E9lectionner les fichiers',\n  back: 'Retour',\n  browse: 'naviguer',\n  browseFiles: 'naviguer',\n  cancel: 'Annuler',\n  cancelUpload: 'Annuler t\u00E9l\u00E9chargement',\n  chooseFiles: 'Choisir des fichiers',\n  closeModal: 'Fermer Fen\u00EAtre',\n  companionError: 'Connexion \u00E0 Companion a \u00E9chou\u00E9',\n  companionUnauthorizeHint: 'Pour vous d\u00E9connecter de votre compte %{provider}, veuillez aller \u00E0 %{url}',\n  complete: 'Termin\u00E9',\n  compressedX: '%{size} \u00E9conomis\u00E9(s) par la compression',\n  compressingImages: 'Compression des images...',\n  connectedToInternet: 'Connect\u00E9 \u00E0 Internet',\n  copyLink: 'Copier lien',\n  copyLinkToClipboardFallback: 'Copier le lien ci-dessous',\n  copyLinkToClipboardSuccess: 'Lien copi\u00E9',\n  creatingAssembly: 'Pr\u00E9paration du t\u00E9l\u00E9chargement...',\n  creatingAssemblyFailed: 'Transloadit: Impossible de cr\u00E9er Assembly',\n  dashboardTitle: 'T\u00E9l\u00E9chargeur de fichier',\n  dashboardWindowTitle: 'Fen\u00EAtre de t\u00E9l\u00E9chargeur de fichier (Appuyez sur echap pour fermer)',\n  dataUploadedOfTotal: '%{complete} sur %{total}',\n  done: 'Termin\u00E9',\n  dropHereOr: 'D\u00E9poser les fichiers ici ou %{browse}',\n  dropHint: 'D\u00E9posez vos fichiers ici',\n  dropPasteBoth: 'D\u00E9poser les fichiers ici, coller ou %{browse}',\n  dropPasteFiles: 'D\u00E9poser les fichiers ici, coller ou %{browse}',\n  dropPasteFolders: 'D\u00E9poser les fichiers ici, coller ou %{browse}',\n  dropPasteImportBoth: 'D\u00E9poser les fichiers ici, coller, %{browse} ou importer de',\n  dropPasteImportFiles: 'D\u00E9poser les fichiers ici, coller, %{browse} ou importer de',\n  dropPasteImportFolders: 'D\u00E9poser les fichiers ici, coller, %{browse} ou importer de',\n  editFile: 'Modifier le fichier',\n  editFileWithFilename: 'Modifier le fichier %{file}',\n  editing: 'Modification en cours de %{file}',\n  emptyFolderAdded: 'Aucun fichier n\\'a \u00E9t\u00E9 ajout\u00E9 depuis un dossier vide',\n  encoding: 'Traitement...',\n  enterCorrectUrl: 'Lien incorrect: Assurez-vous que vous entrez un lien direct vers le fichier',\n  enterUrlToImport: 'Entrez le lien pour importer un fichier',\n  exceedsSize: 'Ce fichier d\u00E9passe la taille maximale autoris\u00E9e de %{size}',\n  failedToFetch: 'Companion a \u00E9chou\u00E9 \u00E0 r\u00E9cup\u00E9rer ce lien, assurez-vous qu\\'il est correct',\n  failedToUpload: 'Le t\u00E9l\u00E9chargement de %{file} a \u00E9chou\u00E9',\n  fileSource: 'Fichier source: %{name}',\n  filesUploadedOfTotal: {\n    '0': '%{complete} sur %{smart_count} fichier t\u00E9l\u00E9charg\u00E9',\n    '1': '%{complete} sur %{smart_count} fichiers t\u00E9l\u00E9charg\u00E9s',\n    '2': '%{complete} sur %{smart_count} fichiers t\u00E9l\u00E9charg\u00E9s'\n  },\n  filter: 'Filtrer',\n  finishEditingFile: 'Terminer l\\'\u00E9dition du fichier',\n  folderAdded: {\n    '0': '%{smart_count} fichier ajout\u00E9 de %{folder}',\n    '1': '%{smart_count} fichiers ajout\u00E9s de %{folder}',\n    '2': '%{smart_count} fichiers ajout\u00E9s de %{folder}'\n  },\n  generatingThumbnails: 'Generating thumbnails...',\n  import: 'Importer',\n  importFrom: 'Importer de %{name}',\n  loading: 'Chargement...',\n  logOut: 'D\u00E9connexion',\n  micDisabled: 'Acc\u00E8s au micro refus\u00E9 par l\\'utilisateur',\n  myDevice: 'Mon Appareil',\n  noDuplicates: 'Impossible d\\'ajouter le fichier \"%{fileName}\", il existe d\u00E9j\u00E0',\n  noFilesFound: 'Vous n\\'avez aucun fichier ou dossier ici',\n  noInternetConnection: 'Pas de connexion \u00E0 Internet',\n  noMoreFilesAllowed: 'Impossible d\\'ajouter de nouveaux fichiers: en cours de chargement ',\n  openFolderNamed: 'Ouvrir %{name}',\n  pause: 'Pause',\n  pauseUpload: 'Mettre en pause le t\u00E9l\u00E9chargement',\n  paused: 'En pause',\n  poweredBy: 'Propuls\u00E9 par %{uppy}',\n  processingXFiles: {\n    '0': 'Traitement de %{smart_count} fichier',\n    '1': 'Traitement de %{smart_count} fichiers',\n    '2': 'Traitement de %{smart_count} fichiers'\n  },\n  recording: 'Enregistrement',\n  recordingLength: 'Dur\u00E9e d\\'enregistrement %{recording_length}',\n  recordingStoppedMaxSize: 'L\\'enregistrement s\\'est arr\u00E9t\u00E9 car la taille du fichier d\u00E9passe la limite',\n  removeFile: 'Effacer le fichier %{file}',\n  resetFilter: 'R\u00E9initialiser filtre',\n  resume: 'Reprendre',\n  resumeUpload: 'Reprendre le t\u00E9l\u00E9chargement',\n  retry: 'R\u00E9essayer',\n  retryUpload: 'R\u00E9essayer le t\u00E9l\u00E9chargement',\n  save: 'Sauvegarder',\n  saveChanges: 'Sauvegarder les modifications',\n  selectFileNamed: 'S\u00E9lectionner le fichier %{name}',\n  selectX: {\n    '0': 'S\u00E9lectionner %{smart_count}',\n    '1': 'S\u00E9lectionner %{smart_count}',\n    '2': 'S\u00E9lectionner %{smart_count}'\n  },\n  smile: 'Souriez !',\n  startRecording: 'Commencer l\\'enregistrement vid\u00E9o',\n  stopRecording: 'Arr\u00EAter l\\'enregistrement vid\u00E9o',\n  streamActive: 'Stream actif',\n  streamPassive: 'Stream passif',\n  submitRecordedFile: 'Envoyer la vid\u00E9o enregistr\u00E9e',\n  takePicture: 'Prendre une photo',\n  timedOut: 'T\u00E9l\u00E9chargement bloqu\u00E9 durant %{seconds} secondes, annulation.',\n  unselectFileNamed: 'D\u00E9s\u00E9lectionner le fichier %{name}',\n  upload: 'T\u00E9l\u00E9charger',\n  uploadComplete: 'T\u00E9l\u00E9chargement termin\u00E9',\n  uploadFailed: 'Le t\u00E9l\u00E9chargement a \u00E9chou\u00E9',\n  uploadPaused: 'T\u00E9l\u00E9chargement mis en pause',\n  uploadXFiles: {\n    '0': 'T\u00E9l\u00E9charger %{smart_count} fichier',\n    '1': 'T\u00E9l\u00E9charger %{smart_count} fichiers',\n    '2': 'T\u00E9l\u00E9charger %{smart_count} fichiers'\n  },\n  uploadXNewFiles: {\n    '0': 'T\u00E9l\u00E9charger +%{smart_count} fichier',\n    '1': 'T\u00E9l\u00E9charger +%{smart_count} fichiers',\n    '2': 'T\u00E9l\u00E9charger +%{smart_count} fichiers'\n  },\n  uploading: 'T\u00E9l\u00E9chargement en cours',\n  uploadingXFiles: {\n    '0': 'T\u00E9l\u00E9chargement de %{smart_count} fichier',\n    '1': 'T\u00E9l\u00E9chargement de %{smart_count} fichiers',\n    '2': 'T\u00E9l\u00E9chargement de %{smart_count} fichiers'\n  },\n  xFilesSelected: {\n    '0': '%{smart_count} fichier s\u00E9lectionn\u00E9',\n    '1': '%{smart_count} fichiers s\u00E9lectionn\u00E9s',\n    '2': '%{smart_count} fichiers s\u00E9lectionn\u00E9s'\n  },\n  xMoreFilesAdded: {\n    '0': '%{smart_count} autre fichier ajout\u00E9',\n    '1': '%{smart_count} autres fichiers ajout\u00E9s',\n    '2': '%{smart_count} autres fichiers ajout\u00E9s'\n  },\n  xTimeLeft: '%{time} restantes',\n  youCanOnlyUploadFileTypes: 'Vous pouvez seulement t\u00E9l\u00E9charger: %{types}',\n  youCanOnlyUploadX: {\n    '0': 'Vous pouvez seulement t\u00E9l\u00E9charger %{smart_count} fichier',\n    '1': 'Vous pouvez seulement t\u00E9l\u00E9charger %{smart_count} fichiers',\n    '2': 'Vous pouvez seulement t\u00E9l\u00E9charger %{smart_count} fichiers'\n  },\n  youHaveToAtLeastSelectX: {\n    '0': 'Vous devez s\u00E9lectionner au moins %{smart_count} fichier',\n    '1': 'Vous devez s\u00E9lectionner au moins %{smart_count} fichiers',\n    '2': 'Vous devez s\u00E9lectionner au moins %{smart_count} fichiers'\n  }\n};\n\nif (typeof Uppy !== 'undefined') {\n  globalThis.Uppy.locales.fr_FR = fr_FR;\n}\n\nmodule.exports = fr_FR;", "/*\r\n * @namespace Util\r\n *\r\n * Various utility functions, used by Leaflet internally.\r\n */\r\n\r\n// @function extend(dest: Object, src?: Object): Object\r\n// Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.\r\nexport function extend(dest) {\r\n\tvar i, j, len, src;\r\n\r\n\tfor (j = 1, len = arguments.length; j < len; j++) {\r\n\t\tsrc = arguments[j];\r\n\t\tfor (i in src) {\r\n\t\t\tdest[i] = src[i];\r\n\t\t}\r\n\t}\r\n\treturn dest;\r\n}\r\n\r\n// @function create(proto: Object, properties?: Object): Object\r\n// Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\r\nexport var create = Object.create || (function () {\r\n\tfunction F() {}\r\n\treturn function (proto) {\r\n\t\tF.prototype = proto;\r\n\t\treturn new F();\r\n\t};\r\n})();\r\n\r\n// @function bind(fn: Function, …): Function\r\n// Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).\r\n// Has a `L.bind()` shortcut.\r\nexport function bind(fn, obj) {\r\n\tvar slice = Array.prototype.slice;\r\n\r\n\tif (fn.bind) {\r\n\t\treturn fn.bind.apply(fn, slice.call(arguments, 1));\r\n\t}\r\n\r\n\tvar args = slice.call(arguments, 2);\r\n\r\n\treturn function () {\r\n\t\treturn fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);\r\n\t};\r\n}\r\n\r\n// @property lastId: Number\r\n// Last unique ID used by [`stamp()`](#util-stamp)\r\nexport var lastId = 0;\r\n\r\n// @function stamp(obj: Object): Number\r\n// Returns the unique ID of an object, assigning it one if it doesn't have it.\r\nexport function stamp(obj) {\r\n\tif (!('_leaflet_id' in obj)) {\r\n\t\tobj['_leaflet_id'] = ++lastId;\r\n\t}\r\n\treturn obj._leaflet_id;\r\n}\r\n\r\n// @function throttle(fn: Function, time: Number, context: Object): Function\r\n// Returns a function which executes function `fn` with the given scope `context`\r\n// (so that the `this` keyword refers to `context` inside `fn`'s code). The function\r\n// `fn` will be called no more than one time per given amount of `time`. The arguments\r\n// received by the bound function will be any arguments passed when binding the\r\n// function, followed by any arguments passed when invoking the bound function.\r\n// Has an `L.throttle` shortcut.\r\nexport function throttle(fn, time, context) {\r\n\tvar lock, args, wrapperFn, later;\r\n\r\n\tlater = function () {\r\n\t\t// reset lock and call if queued\r\n\t\tlock = false;\r\n\t\tif (args) {\r\n\t\t\twrapperFn.apply(context, args);\r\n\t\t\targs = false;\r\n\t\t}\r\n\t};\r\n\r\n\twrapperFn = function () {\r\n\t\tif (lock) {\r\n\t\t\t// called too soon, queue to call later\r\n\t\t\targs = arguments;\r\n\r\n\t\t} else {\r\n\t\t\t// call and lock until later\r\n\t\t\tfn.apply(context, arguments);\r\n\t\t\tsetTimeout(later, time);\r\n\t\t\tlock = true;\r\n\t\t}\r\n\t};\r\n\r\n\treturn wrapperFn;\r\n}\r\n\r\n// @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number\r\n// Returns the number `num` modulo `range` in such a way so it lies within\r\n// `range[0]` and `range[1]`. The returned value will be always smaller than\r\n// `range[1]` unless `includeMax` is set to `true`.\r\nexport function wrapNum(x, range, includeMax) {\r\n\tvar max = range[1],\r\n\t    min = range[0],\r\n\t    d = max - min;\r\n\treturn x === max && includeMax ? x : ((x - min) % d + d) % d + min;\r\n}\r\n\r\n// @function falseFn(): Function\r\n// Returns a function which always returns `false`.\r\nexport function falseFn() { return false; }\r\n\r\n// @function formatNum(num: Number, precision?: Number|false): Number\r\n// Returns the number `num` rounded with specified `precision`.\r\n// The default `precision` value is 6 decimal places.\r\n// `false` can be passed to skip any processing (can be useful to avoid round-off errors).\r\nexport function formatNum(num, precision) {\r\n\tif (precision === false) { return num; }\r\n\tvar pow = Math.pow(10, precision === undefined ? 6 : precision);\r\n\treturn Math.round(num * pow) / pow;\r\n}\r\n\r\n// @function trim(str: String): String\r\n// Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)\r\nexport function trim(str) {\r\n\treturn str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\r\n}\r\n\r\n// @function splitWords(str: String): String[]\r\n// Trims and splits the string on whitespace and returns the array of parts.\r\nexport function splitWords(str) {\r\n\treturn trim(str).split(/\\s+/);\r\n}\r\n\r\n// @function setOptions(obj: Object, options: Object): Object\r\n// Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.\r\nexport function setOptions(obj, options) {\r\n\tif (!Object.prototype.hasOwnProperty.call(obj, 'options')) {\r\n\t\tobj.options = obj.options ? create(obj.options) : {};\r\n\t}\r\n\tfor (var i in options) {\r\n\t\tobj.options[i] = options[i];\r\n\t}\r\n\treturn obj.options;\r\n}\r\n\r\n// @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String\r\n// Converts an object into a parameter URL string, e.g. `{a: \"foo\", b: \"bar\"}`\r\n// translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will\r\n// be appended at the end. If `uppercase` is `true`, the parameter names will\r\n// be uppercased (e.g. `'?A=foo&B=bar'`)\r\nexport function getParamString(obj, existingUrl, uppercase) {\r\n\tvar params = [];\r\n\tfor (var i in obj) {\r\n\t\tparams.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));\r\n\t}\r\n\treturn ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');\r\n}\r\n\r\nvar templateRe = /\\{ *([\\w_ -]+) *\\}/g;\r\n\r\n// @function template(str: String, data: Object): String\r\n// Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`\r\n// and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string\r\n// `('Hello foo, bar')`. You can also specify functions instead of strings for\r\n// data values — they will be evaluated passing `data` as an argument.\r\nexport function template(str, data) {\r\n\treturn str.replace(templateRe, function (str, key) {\r\n\t\tvar value = data[key];\r\n\r\n\t\tif (value === undefined) {\r\n\t\t\tthrow new Error('No value provided for variable ' + str);\r\n\r\n\t\t} else if (typeof value === 'function') {\r\n\t\t\tvalue = value(data);\r\n\t\t}\r\n\t\treturn value;\r\n\t});\r\n}\r\n\r\n// @function isArray(obj): Boolean\r\n// Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)\r\nexport var isArray = Array.isArray || function (obj) {\r\n\treturn (Object.prototype.toString.call(obj) === '[object Array]');\r\n};\r\n\r\n// @function indexOf(array: Array, el: Object): Number\r\n// Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)\r\nexport function indexOf(array, el) {\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\tif (array[i] === el) { return i; }\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\n// @property emptyImageUrl: String\r\n// Data URI string containing a base64-encoded empty GIF image.\r\n// Used as a hack to free memory from unused images on WebKit-powered\r\n// mobile devices (by setting image `src` to this string).\r\nexport var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';\r\n\r\n// inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/\r\n\r\nfunction getPrefixed(name) {\r\n\treturn window['webkit' + name] || window['moz' + name] || window['ms' + name];\r\n}\r\n\r\nvar lastTime = 0;\r\n\r\n// fallback for IE 7-8\r\nfunction timeoutDefer(fn) {\r\n\tvar time = +new Date(),\r\n\t    timeToCall = Math.max(0, 16 - (time - lastTime));\r\n\r\n\tlastTime = time + timeToCall;\r\n\treturn window.setTimeout(fn, timeToCall);\r\n}\r\n\r\nexport var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;\r\nexport var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||\r\n\t\tgetPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };\r\n\r\n// @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number\r\n// Schedules `fn` to be executed when the browser repaints. `fn` is bound to\r\n// `context` if given. When `immediate` is set, `fn` is called immediately if\r\n// the browser doesn't have native support for\r\n// [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),\r\n// otherwise it's delayed. Returns a request ID that can be used to cancel the request.\r\nexport function requestAnimFrame(fn, context, immediate) {\r\n\tif (immediate && requestFn === timeoutDefer) {\r\n\t\tfn.call(context);\r\n\t} else {\r\n\t\treturn requestFn.call(window, bind(fn, context));\r\n\t}\r\n}\r\n\r\n// @function cancelAnimFrame(id: Number): undefined\r\n// Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).\r\nexport function cancelAnimFrame(id) {\r\n\tif (id) {\r\n\t\tcancelFn.call(window, id);\r\n\t}\r\n}\r\n", "import * as Util from './Util';\r\n\r\n// @class Class\r\n// @aka L.Class\r\n\r\n// @section\r\n// @uninheritable\r\n\r\n// Thanks to John Resig and Dean Edwards for inspiration!\r\n\r\nexport function Class() {}\r\n\r\nClass.extend = function (props) {\r\n\r\n\t// @function extend(props: Object): Function\r\n\t// [Extends the current class](#class-inheritance) given the properties to be included.\r\n\t// Returns a Javascript function that is a class constructor (to be called with `new`).\r\n\tvar NewClass = function () {\r\n\r\n\t\tUtil.setOptions(this);\r\n\r\n\t\t// call the constructor\r\n\t\tif (this.initialize) {\r\n\t\t\tthis.initialize.apply(this, arguments);\r\n\t\t}\r\n\r\n\t\t// call all constructor hooks\r\n\t\tthis.callInitHooks();\r\n\t};\r\n\r\n\tvar parentProto = NewClass.__super__ = this.prototype;\r\n\r\n\tvar proto = Util.create(parentProto);\r\n\tproto.constructor = NewClass;\r\n\r\n\tNewClass.prototype = proto;\r\n\r\n\t// inherit parent's statics\r\n\tfor (var i in this) {\r\n\t\tif (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') {\r\n\t\t\tNewClass[i] = this[i];\r\n\t\t}\r\n\t}\r\n\r\n\t// mix static properties into the class\r\n\tif (props.statics) {\r\n\t\tUtil.extend(NewClass, props.statics);\r\n\t}\r\n\r\n\t// mix includes into the prototype\r\n\tif (props.includes) {\r\n\t\tcheckDeprecatedMixinEvents(props.includes);\r\n\t\tUtil.extend.apply(null, [proto].concat(props.includes));\r\n\t}\r\n\r\n\t// mix given properties into the prototype\r\n\tUtil.extend(proto, props);\r\n\tdelete proto.statics;\r\n\tdelete proto.includes;\r\n\r\n\t// merge options\r\n\tif (proto.options) {\r\n\t\tproto.options = parentProto.options ? Util.create(parentProto.options) : {};\r\n\t\tUtil.extend(proto.options, props.options);\r\n\t}\r\n\r\n\tproto._initHooks = [];\r\n\r\n\t// add method for calling all hooks\r\n\tproto.callInitHooks = function () {\r\n\r\n\t\tif (this._initHooksCalled) { return; }\r\n\r\n\t\tif (parentProto.callInitHooks) {\r\n\t\t\tparentProto.callInitHooks.call(this);\r\n\t\t}\r\n\r\n\t\tthis._initHooksCalled = true;\r\n\r\n\t\tfor (var i = 0, len = proto._initHooks.length; i < len; i++) {\r\n\t\t\tproto._initHooks[i].call(this);\r\n\t\t}\r\n\t};\r\n\r\n\treturn NewClass;\r\n};\r\n\r\n\r\n// @function include(properties: Object): this\r\n// [Includes a mixin](#class-includes) into the current class.\r\nClass.include = function (props) {\r\n\tvar parentOptions = this.prototype.options;\r\n\tUtil.extend(this.prototype, props);\r\n\tif (props.options) {\r\n\t\tthis.prototype.options = parentOptions;\r\n\t\tthis.mergeOptions(props.options);\r\n\t}\r\n\treturn this;\r\n};\r\n\r\n// @function mergeOptions(options: Object): this\r\n// [Merges `options`](#class-options) into the defaults of the class.\r\nClass.mergeOptions = function (options) {\r\n\tUtil.extend(this.prototype.options, options);\r\n\treturn this;\r\n};\r\n\r\n// @function addInitHook(fn: Function): this\r\n// Adds a [constructor hook](#class-constructor-hooks) to the class.\r\nClass.addInitHook = function (fn) { // (Function) || (String, args...)\r\n\tvar args = Array.prototype.slice.call(arguments, 1);\r\n\r\n\tvar init = typeof fn === 'function' ? fn : function () {\r\n\t\tthis[fn].apply(this, args);\r\n\t};\r\n\r\n\tthis.prototype._initHooks = this.prototype._initHooks || [];\r\n\tthis.prototype._initHooks.push(init);\r\n\treturn this;\r\n};\r\n\r\nfunction checkDeprecatedMixinEvents(includes) {\r\n\t/* global L: true */\r\n\tif (typeof L === 'undefined' || !L || !L.Mixin) { return; }\r\n\r\n\tincludes = Util.isArray(includes) ? includes : [includes];\r\n\r\n\tfor (var i = 0; i < includes.length; i++) {\r\n\t\tif (includes[i] === L.Mixin.Events) {\r\n\t\t\tconsole.warn('Deprecated include of L.Mixin.Events: ' +\r\n\t\t\t\t'this property will be removed in future releases, ' +\r\n\t\t\t\t'please inherit from L.Evented instead.', new Error().stack);\r\n\t\t}\r\n\t}\r\n}\r\n", "import {Class} from './Class';\r\nimport * as Util from './Util';\r\n\r\n/*\r\n * @class Evented\r\n * @aka L.Evented\r\n * @inherits Class\r\n *\r\n * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * map.on('click', function(e) {\r\n * \talert(e.latlng);\r\n * } );\r\n * ```\r\n *\r\n * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:\r\n *\r\n * ```js\r\n * function onClick(e) { ... }\r\n *\r\n * map.on('click', onClick);\r\n * map.off('click', onClick);\r\n * ```\r\n */\r\n\r\nexport var Events = {\r\n\t/* @method on(type: String, fn: Function, context?: Object): this\r\n\t * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).\r\n\t *\r\n\t * @alternative\r\n\t * @method on(eventMap: Object): this\r\n\t * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\n\t */\r\n\ton: function (types, fn, context) {\r\n\r\n\t\t// types can be a map of types/handlers\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\t// we don't process space-separated events here for performance;\r\n\t\t\t\t// it's a hot path since Layer uses the on(obj) syntax\r\n\t\t\t\tthis._on(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\t// types can be a string of space-separated words\r\n\t\t\ttypes = Util.splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._on(types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t/* @method off(type: String, fn?: Function, context?: Object): this\r\n\t * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.\r\n\t *\r\n\t * @alternative\r\n\t * @method off(eventMap: Object): this\r\n\t * Removes a set of type/listener pairs.\r\n\t *\r\n\t * @alternative\r\n\t * @method off: this\r\n\t * Removes all listeners to all events on the object. This includes implicitly attached events.\r\n\t */\r\n\toff: function (types, fn, context) {\r\n\r\n\t\tif (!arguments.length) {\r\n\t\t\t// clear all listeners if called without arguments\r\n\t\t\tdelete this._events;\r\n\r\n\t\t} else if (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\tthis._off(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\ttypes = Util.splitWords(types);\r\n\r\n\t\t\tvar removeAll = arguments.length === 1;\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tif (removeAll) {\r\n\t\t\t\t\tthis._off(types[i]);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthis._off(types[i], fn, context);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// attach listener (without syntactic sugar now)\r\n\t_on: function (type, fn, context, _once) {\r\n\t\tif (typeof fn !== 'function') {\r\n\t\t\tconsole.warn('wrong listener type: ' + typeof fn);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// check if fn already there\r\n\t\tif (this._listens(type, fn, context) !== false) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\t// Less memory footprint.\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tvar newListener = {fn: fn, ctx: context};\r\n\t\tif (_once) {\r\n\t\t\tnewListener.once = true;\r\n\t\t}\r\n\r\n\t\tthis._events = this._events || {};\r\n\t\tthis._events[type] = this._events[type] || [];\r\n\t\tthis._events[type].push(newListener);\r\n\t},\r\n\r\n\t_off: function (type, fn, context) {\r\n\t\tvar listeners,\r\n\t\t    i,\r\n\t\t    len;\r\n\r\n\t\tif (!this._events) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tlisteners = this._events[type];\r\n\t\tif (!listeners) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (arguments.length === 1) { // remove all\r\n\t\t\tif (this._firingCount) {\r\n\t\t\t\t// Set all removed listeners to noop\r\n\t\t\t\t// so they are not called if remove happens in fire\r\n\t\t\t\tfor (i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\t\tlisteners[i].fn = Util.falseFn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// clear all listeners for a type if function isn't specified\r\n\t\t\tdelete this._events[type];\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (typeof fn !== 'function') {\r\n\t\t\tconsole.warn('wrong listener type: ' + typeof fn);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// find fn and remove it\r\n\t\tvar index = this._listens(type, fn, context);\r\n\t\tif (index !== false) {\r\n\t\t\tvar listener = listeners[index];\r\n\t\t\tif (this._firingCount) {\r\n\t\t\t\t// set the removed listener to noop so that's not called if remove happens in fire\r\n\t\t\t\tlistener.fn = Util.falseFn;\r\n\r\n\t\t\t\t/* copy array in case events are being fired */\r\n\t\t\t\tthis._events[type] = listeners = listeners.slice();\r\n\t\t\t}\r\n\t\t\tlisteners.splice(index, 1);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method fire(type: String, data?: Object, propagate?: Boolean): this\r\n\t// Fires an event of the specified type. You can optionally provide a data\r\n\t// object — the first argument of the listener function will contain its\r\n\t// properties. The event can optionally be propagated to event parents.\r\n\tfire: function (type, data, propagate) {\r\n\t\tif (!this.listens(type, propagate)) { return this; }\r\n\r\n\t\tvar event = Util.extend({}, data, {\r\n\t\t\ttype: type,\r\n\t\t\ttarget: this,\r\n\t\t\tsourceTarget: data && data.sourceTarget || this\r\n\t\t});\r\n\r\n\t\tif (this._events) {\r\n\t\t\tvar listeners = this._events[type];\r\n\t\t\tif (listeners) {\r\n\t\t\t\tthis._firingCount = (this._firingCount + 1) || 1;\r\n\t\t\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\t\tvar l = listeners[i];\r\n\t\t\t\t\t// off overwrites l.fn, so we need to copy fn to a var\r\n\t\t\t\t\tvar fn = l.fn;\r\n\t\t\t\t\tif (l.once) {\r\n\t\t\t\t\t\tthis.off(type, fn, l.ctx);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfn.call(l.ctx || this, event);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthis._firingCount--;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// propagate the event to parents (set with addEventParent)\r\n\t\t\tthis._propagateEvent(event);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method listens(type: String, propagate?: Boolean): Boolean\r\n\t// @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean\r\n\t// Returns `true` if a particular event type has any listeners attached to it.\r\n\t// The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.\r\n\tlistens: function (type, fn, context, propagate) {\r\n\t\tif (typeof type !== 'string') {\r\n\t\t\tconsole.warn('\"string\" type argument expected');\r\n\t\t}\r\n\r\n\t\t// we don't overwrite the input `fn` value, because we need to use it for propagation\r\n\t\tvar _fn = fn;\r\n\t\tif (typeof fn !== 'function') {\r\n\t\t\tpropagate = !!fn;\r\n\t\t\t_fn = undefined;\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tvar listeners = this._events && this._events[type];\r\n\t\tif (listeners && listeners.length) {\r\n\t\t\tif (this._listens(type, _fn, context) !== false) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// also check parents for listeners if event propagates\r\n\t\t\tfor (var id in this._eventParents) {\r\n\t\t\t\tif (this._eventParents[id].listens(type, fn, context, propagate)) { return true; }\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t},\r\n\r\n\t// returns the index (number) or false\r\n\t_listens: function (type, fn, context) {\r\n\t\tif (!this._events) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tvar listeners = this._events[type] || [];\r\n\t\tif (!fn) {\r\n\t\t\treturn !!listeners.length;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\t// Less memory footprint.\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\tif (listeners[i].fn === fn && listeners[i].ctx === context) {\r\n\t\t\t\treturn i;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\r\n\t},\r\n\r\n\t// @method once(…): this\r\n\t// Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.\r\n\tonce: function (types, fn, context) {\r\n\r\n\t\t// types can be a map of types/handlers\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\t// we don't process space-separated events here for performance;\r\n\t\t\t\t// it's a hot path since Layer uses the on(obj) syntax\r\n\t\t\t\tthis._on(type, types[type], fn, true);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\t// types can be a string of space-separated words\r\n\t\t\ttypes = Util.splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._on(types[i], fn, context, true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method addEventParent(obj: Evented): this\r\n\t// Adds an event parent - an `Evented` that will receive propagated events\r\n\taddEventParent: function (obj) {\r\n\t\tthis._eventParents = this._eventParents || {};\r\n\t\tthis._eventParents[Util.stamp(obj)] = obj;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeEventParent(obj: Evented): this\r\n\t// Removes an event parent, so it will stop receiving propagated events\r\n\tremoveEventParent: function (obj) {\r\n\t\tif (this._eventParents) {\r\n\t\t\tdelete this._eventParents[Util.stamp(obj)];\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_propagateEvent: function (e) {\r\n\t\tfor (var id in this._eventParents) {\r\n\t\t\tthis._eventParents[id].fire(e.type, Util.extend({\r\n\t\t\t\tlayer: e.target,\r\n\t\t\t\tpropagatedFrom: e.target\r\n\t\t\t}, e), true);\r\n\t\t}\r\n\t}\r\n};\r\n\r\n// aliases; we should ditch those eventually\r\n\r\n// @method addEventListener(…): this\r\n// Alias to [`on(…)`](#evented-on)\r\nEvents.addEventListener = Events.on;\r\n\r\n// @method removeEventListener(…): this\r\n// Alias to [`off(…)`](#evented-off)\r\n\r\n// @method clearAllEventListeners(…): this\r\n// Alias to [`off()`](#evented-off)\r\nEvents.removeEventListener = Events.clearAllEventListeners = Events.off;\r\n\r\n// @method addOneTimeEventListener(…): this\r\n// Alias to [`once(…)`](#evented-once)\r\nEvents.addOneTimeEventListener = Events.once;\r\n\r\n// @method fireEvent(…): this\r\n// Alias to [`fire(…)`](#evented-fire)\r\nEvents.fireEvent = Events.fire;\r\n\r\n// @method hasEventListeners(…): Boolean\r\n// Alias to [`listens(…)`](#evented-listens)\r\nEvents.hasEventListeners = Events.listens;\r\n\r\nexport var Evented = Class.extend(Events);\r\n", "import {isArray, formatNum} from '../core/Util';\r\n\r\n/*\r\n * @class Point\r\n * @aka L.Point\r\n *\r\n * Represents a point with `x` and `y` coordinates in pixels.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var point = L.point(200, 300);\r\n * ```\r\n *\r\n * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```js\r\n * map.panBy([200, 300]);\r\n * map.panBy(L.point(200, 300));\r\n * ```\r\n *\r\n * Note that `Point` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function Point(x, y, round) {\r\n\t// @property x: Number; The `x` coordinate of the point\r\n\tthis.x = (round ? Math.round(x) : x);\r\n\t// @property y: Number; The `y` coordinate of the point\r\n\tthis.y = (round ? Math.round(y) : y);\r\n}\r\n\r\nvar trunc = Math.trunc || function (v) {\r\n\treturn v > 0 ? Math.floor(v) : Math.ceil(v);\r\n};\r\n\r\nPoint.prototype = {\r\n\r\n\t// @method clone(): Point\r\n\t// Returns a copy of the current point.\r\n\tclone: function () {\r\n\t\treturn new Point(this.x, this.y);\r\n\t},\r\n\r\n\t// @method add(otherPoint: Point): Point\r\n\t// Returns the result of addition of the current and the given points.\r\n\tadd: function (point) {\r\n\t\t// non-destructive, returns a new point\r\n\t\treturn this.clone()._add(toPoint(point));\r\n\t},\r\n\r\n\t_add: function (point) {\r\n\t\t// destructive, used directly for performance in situations where it's safe to modify existing point\r\n\t\tthis.x += point.x;\r\n\t\tthis.y += point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method subtract(otherPoint: Point): Point\r\n\t// Returns the result of subtraction of the given point from the current.\r\n\tsubtract: function (point) {\r\n\t\treturn this.clone()._subtract(toPoint(point));\r\n\t},\r\n\r\n\t_subtract: function (point) {\r\n\t\tthis.x -= point.x;\r\n\t\tthis.y -= point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method divideBy(num: Number): Point\r\n\t// Returns the result of division of the current point by the given number.\r\n\tdivideBy: function (num) {\r\n\t\treturn this.clone()._divideBy(num);\r\n\t},\r\n\r\n\t_divideBy: function (num) {\r\n\t\tthis.x /= num;\r\n\t\tthis.y /= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method multiplyBy(num: Number): Point\r\n\t// Returns the result of multiplication of the current point by the given number.\r\n\tmultiplyBy: function (num) {\r\n\t\treturn this.clone()._multiplyBy(num);\r\n\t},\r\n\r\n\t_multiplyBy: function (num) {\r\n\t\tthis.x *= num;\r\n\t\tthis.y *= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method scaleBy(scale: Point): Point\r\n\t// Multiply each coordinate of the current point by each coordinate of\r\n\t// `scale`. In linear algebra terms, multiply the point by the\r\n\t// [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)\r\n\t// defined by `scale`.\r\n\tscaleBy: function (point) {\r\n\t\treturn new Point(this.x * point.x, this.y * point.y);\r\n\t},\r\n\r\n\t// @method unscaleBy(scale: Point): Point\r\n\t// Inverse of `scaleBy`. Divide each coordinate of the current point by\r\n\t// each coordinate of `scale`.\r\n\tunscaleBy: function (point) {\r\n\t\treturn new Point(this.x / point.x, this.y / point.y);\r\n\t},\r\n\r\n\t// @method round(): Point\r\n\t// Returns a copy of the current point with rounded coordinates.\r\n\tround: function () {\r\n\t\treturn this.clone()._round();\r\n\t},\r\n\r\n\t_round: function () {\r\n\t\tthis.x = Math.round(this.x);\r\n\t\tthis.y = Math.round(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method floor(): Point\r\n\t// Returns a copy of the current point with floored coordinates (rounded down).\r\n\tfloor: function () {\r\n\t\treturn this.clone()._floor();\r\n\t},\r\n\r\n\t_floor: function () {\r\n\t\tthis.x = Math.floor(this.x);\r\n\t\tthis.y = Math.floor(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method ceil(): Point\r\n\t// Returns a copy of the current point with ceiled coordinates (rounded up).\r\n\tceil: function () {\r\n\t\treturn this.clone()._ceil();\r\n\t},\r\n\r\n\t_ceil: function () {\r\n\t\tthis.x = Math.ceil(this.x);\r\n\t\tthis.y = Math.ceil(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method trunc(): Point\r\n\t// Returns a copy of the current point with truncated coordinates (rounded towards zero).\r\n\ttrunc: function () {\r\n\t\treturn this.clone()._trunc();\r\n\t},\r\n\r\n\t_trunc: function () {\r\n\t\tthis.x = trunc(this.x);\r\n\t\tthis.y = trunc(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method distanceTo(otherPoint: Point): Number\r\n\t// Returns the cartesian distance between the current and the given points.\r\n\tdistanceTo: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\tvar x = point.x - this.x,\r\n\t\t    y = point.y - this.y;\r\n\r\n\t\treturn Math.sqrt(x * x + y * y);\r\n\t},\r\n\r\n\t// @method equals(otherPoint: Point): Boolean\r\n\t// Returns `true` if the given point has the same coordinates.\r\n\tequals: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn point.x === this.x &&\r\n\t\t       point.y === this.y;\r\n\t},\r\n\r\n\t// @method contains(otherPoint: Point): Boolean\r\n\t// Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).\r\n\tcontains: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn Math.abs(point.x) <= Math.abs(this.x) &&\r\n\t\t       Math.abs(point.y) <= Math.abs(this.y);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point for debugging purposes.\r\n\ttoString: function () {\r\n\t\treturn 'Point(' +\r\n\t\t        formatNum(this.x) + ', ' +\r\n\t\t        formatNum(this.y) + ')';\r\n\t}\r\n};\r\n\r\n// @factory L.point(x: Number, y: Number, round?: Boolean)\r\n// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Number[])\r\n// Expects an array of the form `[x, y]` instead.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Object)\r\n// Expects a plain object of the form `{x: Number, y: Number}` instead.\r\nexport function toPoint(x, y, round) {\r\n\tif (x instanceof Point) {\r\n\t\treturn x;\r\n\t}\r\n\tif (isArray(x)) {\r\n\t\treturn new Point(x[0], x[1]);\r\n\t}\r\n\tif (x === undefined || x === null) {\r\n\t\treturn x;\r\n\t}\r\n\tif (typeof x === 'object' && 'x' in x && 'y' in x) {\r\n\t\treturn new Point(x.x, x.y);\r\n\t}\r\n\treturn new Point(x, y, round);\r\n}\r\n", "import {Point, toPoint} from './Point';\r\n\r\n/*\r\n * @class Bounds\r\n * @aka L.Bounds\r\n *\r\n * Represents a rectangular area in pixel coordinates.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var p1 = L.point(10, 10),\r\n * p2 = L.point(40, 60),\r\n * bounds = L.bounds(p1, p2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * otherBounds.intersects([[10, 10], [40, 60]]);\r\n * ```\r\n *\r\n * Note that `Bounds` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function Bounds(a, b) {\r\n\tif (!a) { return; }\r\n\r\n\tvar points = b ? [a, b] : a;\r\n\r\n\tfor (var i = 0, len = points.length; i < len; i++) {\r\n\t\tthis.extend(points[i]);\r\n\t}\r\n}\r\n\r\nBounds.prototype = {\r\n\t// @method extend(point: Point): this\r\n\t// Extends the bounds to contain the given point.\r\n\r\n\t// @alternative\r\n\t// @method extend(otherBounds: Bounds): this\r\n\t// Extend the bounds to contain the given bounds\r\n\textend: function (obj) {\r\n\t\tvar min2, max2;\r\n\t\tif (!obj) { return this; }\r\n\r\n\t\tif (obj instanceof Point || typeof obj[0] === 'number' || 'x' in obj) {\r\n\t\t\tmin2 = max2 = toPoint(obj);\r\n\t\t} else {\r\n\t\t\tobj = toBounds(obj);\r\n\t\t\tmin2 = obj.min;\r\n\t\t\tmax2 = obj.max;\r\n\r\n\t\t\tif (!min2 || !max2) { return this; }\r\n\t\t}\r\n\r\n\t\t// @property min: Point\r\n\t\t// The top left corner of the rectangle.\r\n\t\t// @property max: Point\r\n\t\t// The bottom right corner of the rectangle.\r\n\t\tif (!this.min && !this.max) {\r\n\t\t\tthis.min = min2.clone();\r\n\t\t\tthis.max = max2.clone();\r\n\t\t} else {\r\n\t\t\tthis.min.x = Math.min(min2.x, this.min.x);\r\n\t\t\tthis.max.x = Math.max(max2.x, this.max.x);\r\n\t\t\tthis.min.y = Math.min(min2.y, this.min.y);\r\n\t\t\tthis.max.y = Math.max(max2.y, this.max.y);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getCenter(round?: Boolean): Point\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function (round) {\r\n\t\treturn toPoint(\r\n\t\t        (this.min.x + this.max.x) / 2,\r\n\t\t        (this.min.y + this.max.y) / 2, round);\r\n\t},\r\n\r\n\t// @method getBottomLeft(): Point\r\n\t// Returns the bottom-left point of the bounds.\r\n\tgetBottomLeft: function () {\r\n\t\treturn toPoint(this.min.x, this.max.y);\r\n\t},\r\n\r\n\t// @method getTopRight(): Point\r\n\t// Returns the top-right point of the bounds.\r\n\tgetTopRight: function () { // -> Point\r\n\t\treturn toPoint(this.max.x, this.min.y);\r\n\t},\r\n\r\n\t// @method getTopLeft(): Point\r\n\t// Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).\r\n\tgetTopLeft: function () {\r\n\t\treturn this.min; // left, top\r\n\t},\r\n\r\n\t// @method getBottomRight(): Point\r\n\t// Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).\r\n\tgetBottomRight: function () {\r\n\t\treturn this.max; // right, bottom\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the size of the given bounds\r\n\tgetSize: function () {\r\n\t\treturn this.max.subtract(this.min);\r\n\t},\r\n\r\n\t// @method contains(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\t// @alternative\r\n\t// @method contains(point: Point): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) {\r\n\t\tvar min, max;\r\n\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof Point) {\r\n\t\t\tobj = toPoint(obj);\r\n\t\t} else {\r\n\t\t\tobj = toBounds(obj);\r\n\t\t}\r\n\r\n\t\tif (obj instanceof Bounds) {\r\n\t\t\tmin = obj.min;\r\n\t\t\tmax = obj.max;\r\n\t\t} else {\r\n\t\t\tmin = max = obj;\r\n\t\t}\r\n\r\n\t\treturn (min.x >= this.min.x) &&\r\n\t\t       (max.x <= this.max.x) &&\r\n\t\t       (min.y >= this.min.y) &&\r\n\t\t       (max.y <= this.max.y);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds\r\n\t// intersect if they have at least one point in common.\r\n\tintersects: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t    max = this.max,\r\n\t\t    min2 = bounds.min,\r\n\t\t    max2 = bounds.max,\r\n\t\t    xIntersects = (max2.x >= min.x) && (min2.x <= max.x),\r\n\t\t    yIntersects = (max2.y >= min.y) && (min2.y <= max.y);\r\n\r\n\t\treturn xIntersects && yIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds\r\n\t// overlap if their intersection is an area.\r\n\toverlaps: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t    max = this.max,\r\n\t\t    min2 = bounds.min,\r\n\t\t    max2 = bounds.max,\r\n\t\t    xOverlaps = (max2.x > min.x) && (min2.x < max.x),\r\n\t\t    yOverlaps = (max2.y > min.y) && (min2.y < max.y);\r\n\r\n\t\treturn xOverlaps && yOverlaps;\r\n\t},\r\n\r\n\t// @method isValid(): Boolean\r\n\t// Returns `true` if the bounds are properly initialized.\r\n\tisValid: function () {\r\n\t\treturn !!(this.min && this.max);\r\n\t},\r\n\r\n\r\n\t// @method pad(bufferRatio: Number): Bounds\r\n\t// Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.\r\n\t// For example, a ratio of 0.5 extends the bounds by 50% in each direction.\r\n\t// Negative values will retract the bounds.\r\n\tpad: function (bufferRatio) {\r\n\t\tvar min = this.min,\r\n\t\tmax = this.max,\r\n\t\theightBuffer = Math.abs(min.x - max.x) * bufferRatio,\r\n\t\twidthBuffer = Math.abs(min.y - max.y) * bufferRatio;\r\n\r\n\r\n\t\treturn toBounds(\r\n\t\t\ttoPoint(min.x - heightBuffer, min.y - widthBuffer),\r\n\t\t\ttoPoint(max.x + heightBuffer, max.y + widthBuffer));\r\n\t},\r\n\r\n\r\n\t// @method equals(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle is equivalent to the given bounds.\r\n\tequals: function (bounds) {\r\n\t\tif (!bounds) { return false; }\r\n\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\treturn this.min.equals(bounds.getTopLeft()) &&\r\n\t\t\tthis.max.equals(bounds.getBottomRight());\r\n\t},\r\n};\r\n\r\n\r\n// @factory L.bounds(corner1: Point, corner2: Point)\r\n// Creates a Bounds object from two corners coordinate pairs.\r\n// @alternative\r\n// @factory L.bounds(points: Point[])\r\n// Creates a Bounds object from the given array of points.\r\nexport function toBounds(a, b) {\r\n\tif (!a || a instanceof Bounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new Bounds(a, b);\r\n}\r\n", "import {LatLng, toLatLng} from './LatLng';\r\n\r\n/*\r\n * @class LatLngBounds\r\n * @aka L.LatLngBounds\r\n *\r\n * Represents a rectangular geographical area on a map.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var corner1 = L.latLng(40.712, -74.227),\r\n * corner2 = L.latLng(40.774, -74.125),\r\n * bounds = L.latLngBounds(corner1, corner2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * map.fitBounds([\r\n * \t[40.712, -74.227],\r\n * \t[40.774, -74.125]\r\n * ]);\r\n * ```\r\n *\r\n * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.\r\n *\r\n * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])\r\n\tif (!corner1) { return; }\r\n\r\n\tvar latlngs = corner2 ? [corner1, corner2] : corner1;\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\tthis.extend(latlngs[i]);\r\n\t}\r\n}\r\n\r\nLatLngBounds.prototype = {\r\n\r\n\t// @method extend(latlng: LatLng): this\r\n\t// Extend the bounds to contain the given point\r\n\r\n\t// @alternative\r\n\t// @method extend(otherBounds: LatLngBounds): this\r\n\t// Extend the bounds to contain the given bounds\r\n\textend: function (obj) {\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLng) {\r\n\t\t\tsw2 = obj;\r\n\t\t\tne2 = obj;\r\n\r\n\t\t} else if (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj._southWest;\r\n\t\t\tne2 = obj._northEast;\r\n\r\n\t\t\tif (!sw2 || !ne2) { return this; }\r\n\r\n\t\t} else {\r\n\t\t\treturn obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;\r\n\t\t}\r\n\r\n\t\tif (!sw && !ne) {\r\n\t\t\tthis._southWest = new LatLng(sw2.lat, sw2.lng);\r\n\t\t\tthis._northEast = new LatLng(ne2.lat, ne2.lng);\r\n\t\t} else {\r\n\t\t\tsw.lat = Math.min(sw2.lat, sw.lat);\r\n\t\t\tsw.lng = Math.min(sw2.lng, sw.lng);\r\n\t\t\tne.lat = Math.max(ne2.lat, ne.lat);\r\n\t\t\tne.lng = Math.max(ne2.lng, ne.lng);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method pad(bufferRatio: Number): LatLngBounds\r\n\t// Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.\r\n\t// For example, a ratio of 0.5 extends the bounds by 50% in each direction.\r\n\t// Negative values will retract the bounds.\r\n\tpad: function (bufferRatio) {\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,\r\n\t\t    widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;\r\n\r\n\t\treturn new LatLngBounds(\r\n\t\t        new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),\r\n\t\t        new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));\r\n\t},\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function () {\r\n\t\treturn new LatLng(\r\n\t\t        (this._southWest.lat + this._northEast.lat) / 2,\r\n\t\t        (this._southWest.lng + this._northEast.lng) / 2);\r\n\t},\r\n\r\n\t// @method getSouthWest(): LatLng\r\n\t// Returns the south-west point of the bounds.\r\n\tgetSouthWest: function () {\r\n\t\treturn this._southWest;\r\n\t},\r\n\r\n\t// @method getNorthEast(): LatLng\r\n\t// Returns the north-east point of the bounds.\r\n\tgetNorthEast: function () {\r\n\t\treturn this._northEast;\r\n\t},\r\n\r\n\t// @method getNorthWest(): LatLng\r\n\t// Returns the north-west point of the bounds.\r\n\tgetNorthWest: function () {\r\n\t\treturn new LatLng(this.getNorth(), this.getWest());\r\n\t},\r\n\r\n\t// @method getSouthEast(): LatLng\r\n\t// Returns the south-east point of the bounds.\r\n\tgetSouthEast: function () {\r\n\t\treturn new LatLng(this.getSouth(), this.getEast());\r\n\t},\r\n\r\n\t// @method getWest(): Number\r\n\t// Returns the west longitude of the bounds\r\n\tgetWest: function () {\r\n\t\treturn this._southWest.lng;\r\n\t},\r\n\r\n\t// @method getSouth(): Number\r\n\t// Returns the south latitude of the bounds\r\n\tgetSouth: function () {\r\n\t\treturn this._southWest.lat;\r\n\t},\r\n\r\n\t// @method getEast(): Number\r\n\t// Returns the east longitude of the bounds\r\n\tgetEast: function () {\r\n\t\treturn this._northEast.lng;\r\n\t},\r\n\r\n\t// @method getNorth(): Number\r\n\t// Returns the north latitude of the bounds\r\n\tgetNorth: function () {\r\n\t\treturn this._northEast.lat;\r\n\t},\r\n\r\n\t// @method contains(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\r\n\t// @alternative\r\n\t// @method contains (latlng: LatLng): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {\r\n\t\t\tobj = toLatLng(obj);\r\n\t\t} else {\r\n\t\t\tobj = toLatLngBounds(obj);\r\n\t\t}\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj.getSouthWest();\r\n\t\t\tne2 = obj.getNorthEast();\r\n\t\t} else {\r\n\t\t\tsw2 = ne2 = obj;\r\n\t\t}\r\n\r\n\t\treturn (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&\r\n\t\t       (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.\r\n\tintersects: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2 = bounds.getSouthWest(),\r\n\t\t    ne2 = bounds.getNorthEast(),\r\n\r\n\t\t    latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),\r\n\t\t    lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);\r\n\r\n\t\treturn latIntersects && lngIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.\r\n\toverlaps: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2 = bounds.getSouthWest(),\r\n\t\t    ne2 = bounds.getNorthEast(),\r\n\r\n\t\t    latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),\r\n\t\t    lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);\r\n\r\n\t\treturn latOverlaps && lngOverlaps;\r\n\t},\r\n\r\n\t// @method toBBoxString(): String\r\n\t// Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.\r\n\ttoBBoxString: function () {\r\n\t\treturn [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');\r\n\t},\r\n\r\n\t// @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (bounds, maxMargin) {\r\n\t\tif (!bounds) { return false; }\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\treturn this._southWest.equals(bounds.getSouthWest(), maxMargin) &&\r\n\t\t       this._northEast.equals(bounds.getNorthEast(), maxMargin);\r\n\t},\r\n\r\n\t// @method isValid(): Boolean\r\n\t// Returns `true` if the bounds are properly initialized.\r\n\tisValid: function () {\r\n\t\treturn !!(this._southWest && this._northEast);\r\n\t}\r\n};\r\n\r\n// TODO International date line?\r\n\r\n// @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)\r\n// Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.\r\n\r\n// @alternative\r\n// @factory L.latLngBounds(latlngs: LatLng[])\r\n// Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).\r\nexport function toLatLngBounds(a, b) {\r\n\tif (a instanceof LatLngBounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new LatLngBounds(a, b);\r\n}\r\n", "import * as Util from '../core/Util';\r\nimport {Earth} from './crs/CRS.Earth';\r\nimport {toLatLngBounds} from './LatLngBounds';\r\n\r\n/* @class LatLng\r\n * @aka L.LatLng\r\n *\r\n * Represents a geographical point with a certain latitude and longitude.\r\n *\r\n * @example\r\n *\r\n * ```\r\n * var latlng = L.latLng(50.5, 30.5);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```\r\n * map.panTo([50, 30]);\r\n * map.panTo({lon: 30, lat: 50});\r\n * map.panTo({lat: 50, lng: 30});\r\n * map.panTo(L.latLng(50, 30));\r\n * ```\r\n *\r\n * Note that `LatLng` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function LatLng(lat, lng, alt) {\r\n\tif (isNaN(lat) || isNaN(lng)) {\r\n\t\tthrow new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');\r\n\t}\r\n\r\n\t// @property lat: Number\r\n\t// Latitude in degrees\r\n\tthis.lat = +lat;\r\n\r\n\t// @property lng: Number\r\n\t// Longitude in degrees\r\n\tthis.lng = +lng;\r\n\r\n\t// @property alt: Number\r\n\t// Altitude in meters (optional)\r\n\tif (alt !== undefined) {\r\n\t\tthis.alt = +alt;\r\n\t}\r\n}\r\n\r\nLatLng.prototype = {\r\n\t// @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (obj, maxMargin) {\r\n\t\tif (!obj) { return false; }\r\n\r\n\t\tobj = toLatLng(obj);\r\n\r\n\t\tvar margin = Math.max(\r\n\t\t        Math.abs(this.lat - obj.lat),\r\n\t\t        Math.abs(this.lng - obj.lng));\r\n\r\n\t\treturn margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point (for debugging purposes).\r\n\ttoString: function (precision) {\r\n\t\treturn 'LatLng(' +\r\n\t\t        Util.formatNum(this.lat, precision) + ', ' +\r\n\t\t        Util.formatNum(this.lng, precision) + ')';\r\n\t},\r\n\r\n\t// @method distanceTo(otherLatLng: LatLng): Number\r\n\t// Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).\r\n\tdistanceTo: function (other) {\r\n\t\treturn Earth.distance(this, toLatLng(other));\r\n\t},\r\n\r\n\t// @method wrap(): LatLng\r\n\t// Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.\r\n\twrap: function () {\r\n\t\treturn Earth.wrapLatLng(this);\r\n\t},\r\n\r\n\t// @method toBounds(sizeInMeters: Number): LatLngBounds\r\n\t// Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.\r\n\ttoBounds: function (sizeInMeters) {\r\n\t\tvar latAccuracy = 180 * sizeInMeters / 40075017,\r\n\t\t    lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);\r\n\r\n\t\treturn toLatLngBounds(\r\n\t\t        [this.lat - latAccuracy, this.lng - lngAccuracy],\r\n\t\t        [this.lat + latAccuracy, this.lng + lngAccuracy]);\r\n\t},\r\n\r\n\tclone: function () {\r\n\t\treturn new LatLng(this.lat, this.lng, this.alt);\r\n\t}\r\n};\r\n\r\n\r\n\r\n// @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng\r\n// Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Array): LatLng\r\n// Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Object): LatLng\r\n// Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.\r\n\r\nexport function toLatLng(a, b, c) {\r\n\tif (a instanceof LatLng) {\r\n\t\treturn a;\r\n\t}\r\n\tif (Util.isArray(a) && typeof a[0] !== 'object') {\r\n\t\tif (a.length === 3) {\r\n\t\t\treturn new LatLng(a[0], a[1], a[2]);\r\n\t\t}\r\n\t\tif (a.length === 2) {\r\n\t\t\treturn new LatLng(a[0], a[1]);\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\tif (a === undefined || a === null) {\r\n\t\treturn a;\r\n\t}\r\n\tif (typeof a === 'object' && 'lat' in a) {\r\n\t\treturn new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);\r\n\t}\r\n\tif (b === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\treturn new LatLng(a, b, c);\r\n}\r\n", "\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {LatLng} from '../LatLng';\r\nimport {LatLngBounds} from '../LatLngBounds';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.Base\r\n * Object that defines coordinate reference systems for projecting\r\n * geographical points into pixel (screen) coordinates and back (and to\r\n * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See\r\n * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system).\r\n *\r\n * Leaflet defines the most usual CRSs by default. If you want to use a\r\n * CRS not defined by default, take a look at the\r\n * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.\r\n *\r\n * Note that the CRS instances do not inherit from Leaflet's `Class` object,\r\n * and can't be instantiated. Also, new classes can't inherit from them,\r\n * and methods can't be added to them with the `include` function.\r\n */\r\n\r\nexport var CRS = {\r\n\t// @method latLngToPoint(latlng: LatLng, zoom: Number): Point\r\n\t// Projects geographical coordinates into pixel coordinates for a given zoom.\r\n\tlatLngToPoint: function (latlng, zoom) {\r\n\t\tvar projectedPoint = this.projection.project(latlng),\r\n\t\t    scale = this.scale(zoom);\r\n\r\n\t\treturn this.transformation._transform(projectedPoint, scale);\r\n\t},\r\n\r\n\t// @method pointToLatLng(point: Point, zoom: Number): LatLng\r\n\t// The inverse of `latLngToPoint`. Projects pixel coordinates on a given\r\n\t// zoom into geographical coordinates.\r\n\tpointToLatLng: function (point, zoom) {\r\n\t\tvar scale = this.scale(zoom),\r\n\t\t    untransformedPoint = this.transformation.untransform(point, scale);\r\n\r\n\t\treturn this.projection.unproject(untransformedPoint);\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng): Point\r\n\t// Projects geographical coordinates into coordinates in units accepted for\r\n\t// this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).\r\n\tproject: function (latlng) {\r\n\t\treturn this.projection.project(latlng);\r\n\t},\r\n\r\n\t// @method unproject(point: Point): LatLng\r\n\t// Given a projected coordinate returns the corresponding LatLng.\r\n\t// The inverse of `project`.\r\n\tunproject: function (point) {\r\n\t\treturn this.projection.unproject(point);\r\n\t},\r\n\r\n\t// @method scale(zoom: Number): Number\r\n\t// Returns the scale used when transforming projected coordinates into\r\n\t// pixel coordinates for a particular zoom. For example, it returns\r\n\t// `256 * 2^zoom` for Mercator-based CRS.\r\n\tscale: function (zoom) {\r\n\t\treturn 256 * Math.pow(2, zoom);\r\n\t},\r\n\r\n\t// @method zoom(scale: Number): Number\r\n\t// Inverse of `scale()`, returns the zoom level corresponding to a scale\r\n\t// factor of `scale`.\r\n\tzoom: function (scale) {\r\n\t\treturn Math.log(scale / 256) / Math.LN2;\r\n\t},\r\n\r\n\t// @method getProjectedBounds(zoom: Number): Bounds\r\n\t// Returns the projection's bounds scaled and transformed for the provided `zoom`.\r\n\tgetProjectedBounds: function (zoom) {\r\n\t\tif (this.infinite) { return null; }\r\n\r\n\t\tvar b = this.projection.bounds,\r\n\t\t    s = this.scale(zoom),\r\n\t\t    min = this.transformation.transform(b.min, s),\r\n\t\t    max = this.transformation.transform(b.max, s);\r\n\r\n\t\treturn new Bounds(min, max);\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates.\r\n\r\n\t// @property code: String\r\n\t// Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)\r\n\t//\r\n\t// @property wrapLng: Number[]\r\n\t// An array of two numbers defining whether the longitude (horizontal) coordinate\r\n\t// axis wraps around a given range and how. Defaults to `[-180, 180]` in most\r\n\t// geographical CRSs. If `undefined`, the longitude axis does not wrap around.\r\n\t//\r\n\t// @property wrapLat: Number[]\r\n\t// Like `wrapLng`, but for the latitude (vertical) axis.\r\n\r\n\t// wrapLng: [min, max],\r\n\t// wrapLat: [min, max],\r\n\r\n\t// @property infinite: Boolean\r\n\t// If true, the coordinate space will be unbounded (infinite in both axes)\r\n\tinfinite: false,\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where lat and lng has been wrapped according to the\r\n\t// CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.\r\n\twrapLatLng: function (latlng) {\r\n\t\tvar lng = this.wrapLng ? Util.wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,\r\n\t\t    lat = this.wrapLat ? Util.wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,\r\n\t\t    alt = latlng.alt;\r\n\r\n\t\treturn new LatLng(lat, lng, alt);\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring\r\n\t// that its center is within the CRS's bounds.\r\n\t// Only accepts actual `L.LatLngBounds` instances, not arrays.\r\n\twrapLatLngBounds: function (bounds) {\r\n\t\tvar center = bounds.getCenter(),\r\n\t\t    newCenter = this.wrapLatLng(center),\r\n\t\t    latShift = center.lat - newCenter.lat,\r\n\t\t    lngShift = center.lng - newCenter.lng;\r\n\r\n\t\tif (latShift === 0 && lngShift === 0) {\r\n\t\t\treturn bounds;\r\n\t\t}\r\n\r\n\t\tvar sw = bounds.getSouthWest(),\r\n\t\t    ne = bounds.getNorthEast(),\r\n\t\t    newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),\r\n\t\t    newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);\r\n\r\n\t\treturn new LatLngBounds(newSw, newNe);\r\n\t}\r\n};\r\n", "import {CRS} from './CRS';\nimport * as Util from '../../core/Util';\n\n/*\n * @namespace CRS\n * @crs L.CRS.Earth\n *\n * Serves as the base for CRS that are global such that they cover the earth.\n * Can only be used as the base for other CRS and cannot be used directly,\n * since it does not have a `code`, `projection` or `transformation`. `distance()` returns\n * meters.\n */\n\nexport var Earth = Util.extend({}, CRS, {\n\twrapLng: [-180, 180],\n\n\t// Mean Earth Radius, as recommended for use by\n\t// the International Union of Geodesy and Geophysics,\n\t// see https://rosettacode.org/wiki/Haversine_formula\n\tR: 6371000,\n\n\t// distance between two geographical points using spherical law of cosines approximation\n\tdistance: function (latlng1, latlng2) {\n\t\tvar rad = Math.PI / 180,\n\t\t    lat1 = latlng1.lat * rad,\n\t\t    lat2 = latlng2.lat * rad,\n\t\t    sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),\n\t\t    sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),\n\t\t    a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,\n\t\t    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\t\treturn this.R * c;\n\t}\n});\n", "import {LatLng} from '../LatLng';\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {Point} from '../../geometry/Point';\r\n\r\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.SphericalMercator\r\n *\r\n * Spherical Mercator projection — the most common projection for online maps,\r\n * used by almost all free and commercial tile providers. Assumes that Earth is\r\n * a sphere. Used by the `EPSG:3857` CRS.\r\n */\r\n\r\nvar earthRadius = 6378137;\r\n\r\nexport var SphericalMercator = {\r\n\r\n\tR: earthRadius,\r\n\tMAX_LATITUDE: 85.0511287798,\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t    max = this.MAX_LATITUDE,\r\n\t\t    lat = Math.max(Math.min(max, latlng.lat), -max),\r\n\t\t    sin = Math.sin(lat * d);\r\n\r\n\t\treturn new Point(\r\n\t\t\tthis.R * latlng.lng * d,\r\n\t\t\tthis.R * Math.log((1 + sin) / (1 - sin)) / 2);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI;\r\n\r\n\t\treturn new LatLng(\r\n\t\t\t(2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,\r\n\t\t\tpoint.x * d / this.R);\r\n\t},\r\n\r\n\tbounds: (function () {\r\n\t\tvar d = earthRadius * Math.PI;\r\n\t\treturn new Bounds([-d, -d], [d, d]);\r\n\t})()\r\n};\r\n", "import {Point} from './Point';\r\nimport * as Util from '../core/Util';\r\n\r\n/*\r\n * @class Transformation\r\n * @aka L.Transformation\r\n *\r\n * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`\r\n * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing\r\n * the reverse. Used by Leaflet in its projections code.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var transformation = L.transformation(2, 5, -1, 10),\r\n * \tp = L.point(1, 2),\r\n * \tp2 = transformation.transform(p), //  L.point(7, 8)\r\n * \tp3 = transformation.untransform(p2); //  L.point(1, 2)\r\n * ```\r\n */\r\n\r\n\r\n// factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Creates a `Transformation` object with the given coefficients.\r\nexport function Transformation(a, b, c, d) {\r\n\tif (Util.isArray(a)) {\r\n\t\t// use array properties\r\n\t\tthis._a = a[0];\r\n\t\tthis._b = a[1];\r\n\t\tthis._c = a[2];\r\n\t\tthis._d = a[3];\r\n\t\treturn;\r\n\t}\r\n\tthis._a = a;\r\n\tthis._b = b;\r\n\tthis._c = c;\r\n\tthis._d = d;\r\n}\r\n\r\nTransformation.prototype = {\r\n\t// @method transform(point: Point, scale?: Number): Point\r\n\t// Returns a transformed point, optionally multiplied by the given scale.\r\n\t// Only accepts actual `L.Point` instances, not arrays.\r\n\ttransform: function (point, scale) { // (Point, Number) -> Point\r\n\t\treturn this._transform(point.clone(), scale);\r\n\t},\r\n\r\n\t// destructive transform (faster)\r\n\t_transform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\tpoint.x = scale * (this._a * point.x + this._b);\r\n\t\tpoint.y = scale * (this._c * point.y + this._d);\r\n\t\treturn point;\r\n\t},\r\n\r\n\t// @method untransform(point: Point, scale?: Number): Point\r\n\t// Returns the reverse transformation of the given point, optionally divided\r\n\t// by the given scale. Only accepts actual `L.Point` instances, not arrays.\r\n\tuntransform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\treturn new Point(\r\n\t\t        (point.x / scale - this._b) / this._a,\r\n\t\t        (point.y / scale - this._d) / this._c);\r\n\t}\r\n};\r\n\r\n// factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n\r\n// @factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Instantiates a Transformation object with the given coefficients.\r\n\r\n// @alternative\r\n// @factory L.transformation(coefficients: Array): Transformation\r\n// Expects an coefficients array of the form\r\n// `[a: Number, b: Number, c: Number, d: Number]`.\r\n\r\nexport function toTransformation(a, b, c, d) {\r\n\treturn new Transformation(a, b, c, d);\r\n}\r\n", "import {Earth} from './CRS.Earth';\r\nimport {SphericalMercator} from '../projection/Projection.SphericalMercator';\r\nimport {toTransformation} from '../../geometry/Transformation';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3857\r\n *\r\n * The most common CRS for online maps, used by almost all free and commercial\r\n * tile providers. Uses Spherical Mercator projection. Set in by default in\r\n * Map's `crs` option.\r\n */\r\n\r\nexport var EPSG3857 = Util.extend({}, Earth, {\r\n\tcode: 'EPSG:3857',\r\n\tprojection: SphericalMercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * SphericalMercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\r\n\r\nexport var EPSG900913 = Util.extend({}, EPSG3857, {\r\n\tcode: 'EPSG:900913'\r\n});\r\n", "import Browser from '../../core/Browser';\n\n// @namespace SVG; @section\n// There are several static functions which can be called without instantiating L.SVG:\n\n// @function create(name: String): SVGElement\n// Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),\n// corresponding to the class name passed. For example, using 'line' will return\n// an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).\nexport function svgCreate(name) {\n\treturn document.createElementNS('http://www.w3.org/2000/svg', name);\n}\n\n// @function pointsToPath(rings: Point[], closed: Boolean): String\n// Generates a SVG path string for multiple rings, with each ring turning\n// into \"M..L..L..\" instructions\nexport function pointsToPath(rings, closed) {\n\tvar str = '',\n\ti, j, len, len2, points, p;\n\n\tfor (i = 0, len = rings.length; i < len; i++) {\n\t\tpoints = rings[i];\n\n\t\tfor (j = 0, len2 = points.length; j < len2; j++) {\n\t\t\tp = points[j];\n\t\t\tstr += (j ? 'L' : 'M') + p.x + ' ' + p.y;\n\t\t}\n\n\t\t// closes the ring for polygons; \"x\" is VML syntax\n\t\tstr += closed ? (Browser.svg ? 'z' : 'x') : '';\n\t}\n\n\t// SVG complains about empty path strings\n\treturn str || 'M0 0';\n}\n\n\n\n\n", "import * as Util from './Util';\r\nimport {svgCreate} from '../layer/vector/SVG.Util';\r\n\r\n/*\r\n * @namespace Browser\r\n * @aka L.Browser\r\n *\r\n * A namespace with static properties for browser/feature detection used by Leaflet internally.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * if (L.Browser.ielt9) {\r\n *   alert('Upgrade your browser, dude!');\r\n * }\r\n * ```\r\n */\r\n\r\nvar style = document.documentElement.style;\r\n\r\n// @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).\r\nvar ie = 'ActiveXObject' in window;\r\n\r\n// @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.\r\nvar ielt9 = ie && !document.addEventListener;\r\n\r\n// @property edge: Boolean; `true` for the Edge web browser.\r\nvar edge = 'msLaunchUri' in navigator && !('documentMode' in document);\r\n\r\n// @property webkit: Boolean;\r\n// `true` for webkit-based browsers like Chrome and Safari (including mobile versions).\r\nvar webkit = userAgentContains('webkit');\r\n\r\n// @property android: Boolean\r\n// **Deprecated.** `true` for any browser running on an Android platform.\r\nvar android = userAgentContains('android');\r\n\r\n// @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3.\r\nvar android23 = userAgentContains('android 2') || userAgentContains('android 3');\r\n\r\n/* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */\r\nvar webkitVer = parseInt(/WebKit\\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit\r\n// @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome)\r\nvar androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);\r\n\r\n// @property opera: Boolean; `true` for the Opera browser\r\nvar opera = !!window.opera;\r\n\r\n// @property chrome: Boolean; `true` for the Chrome browser.\r\nvar chrome = !edge && userAgentContains('chrome');\r\n\r\n// @property gecko: Boolean; `true` for gecko-based browsers like Firefox.\r\nvar gecko = userAgentContains('gecko') && !webkit && !opera && !ie;\r\n\r\n// @property safari: Boolean; `true` for the Safari browser.\r\nvar safari = !chrome && userAgentContains('safari');\r\n\r\nvar phantom = userAgentContains('phantom');\r\n\r\n// @property opera12: Boolean\r\n// `true` for the Opera browser supporting CSS transforms (version 12 or later).\r\nvar opera12 = 'OTransition' in style;\r\n\r\n// @property win: Boolean; `true` when the browser is running in a Windows platform\r\nvar win = navigator.platform.indexOf('Win') === 0;\r\n\r\n// @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.\r\nvar ie3d = ie && ('transition' in style);\r\n\r\n// @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.\r\nvar webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;\r\n\r\n// @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.\r\nvar gecko3d = 'MozPerspective' in style;\r\n\r\n// @property any3d: Boolean\r\n// `true` for all browsers supporting CSS transforms.\r\nvar any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;\r\n\r\n// @property mobile: Boolean; `true` for all browsers running in a mobile device.\r\nvar mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');\r\n\r\n// @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.\r\nvar mobileWebkit = mobile && webkit;\r\n\r\n// @property mobileWebkit3d: Boolean\r\n// `true` for all webkit-based browsers in a mobile device supporting CSS transforms.\r\nvar mobileWebkit3d = mobile && webkit3d;\r\n\r\n// @property msPointer: Boolean\r\n// `true` for browsers implementing the Microsoft touch events model (notably IE10).\r\nvar msPointer = !window.PointerEvent && window.MSPointerEvent;\r\n\r\n// @property pointer: Boolean\r\n// `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).\r\nvar pointer = !!(window.PointerEvent || msPointer);\r\n\r\n// @property touchNative: Boolean\r\n// `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).\r\n// **This does not necessarily mean** that the browser is running in a computer with\r\n// a touchscreen, it only means that the browser is capable of understanding\r\n// touch events.\r\nvar touchNative = 'ontouchstart' in window || !!window.TouchEvent;\r\n\r\n// @property touch: Boolean\r\n// `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events.\r\n// Note: pointer events will be preferred (if available), and processed for all `touch*` listeners.\r\nvar touch = !window.L_NO_TOUCH && (touchNative || pointer);\r\n\r\n// @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.\r\nvar mobileOpera = mobile && opera;\r\n\r\n// @property mobileGecko: Boolean\r\n// `true` for gecko-based browsers running in a mobile device.\r\nvar mobileGecko = mobile && gecko;\r\n\r\n// @property retina: Boolean\r\n// `true` for browsers on a high-resolution \"retina\" screen or on any screen when browser's display zoom is more than 100%.\r\nvar retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;\r\n\r\n// @property passiveEvents: Boolean\r\n// `true` for browsers that support passive events.\r\nvar passiveEvents = (function () {\r\n\tvar supportsPassiveOption = false;\r\n\ttry {\r\n\t\tvar opts = Object.defineProperty({}, 'passive', {\r\n\t\t\tget: function () { // eslint-disable-line getter-return\r\n\t\t\t\tsupportsPassiveOption = true;\r\n\t\t\t}\r\n\t\t});\r\n\t\twindow.addEventListener('testPassiveEventSupport', Util.falseFn, opts);\r\n\t\twindow.removeEventListener('testPassiveEventSupport', Util.falseFn, opts);\r\n\t} catch (e) {\r\n\t\t// Errors can safely be ignored since this is only a browser support test.\r\n\t}\r\n\treturn supportsPassiveOption;\r\n}());\r\n\r\n// @property canvas: Boolean\r\n// `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).\r\nvar canvas = (function () {\r\n\treturn !!document.createElement('canvas').getContext;\r\n}());\r\n\r\n// @property svg: Boolean\r\n// `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).\r\nvar svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);\r\n\r\nvar inlineSvg = !!svg && (function () {\r\n\tvar div = document.createElement('div');\r\n\tdiv.innerHTML = '<svg/>';\r\n\treturn (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';\r\n})();\r\n\r\n// @property vml: Boolean\r\n// `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).\r\nvar vml = !svg && (function () {\r\n\ttry {\r\n\t\tvar div = document.createElement('div');\r\n\t\tdiv.innerHTML = '<v:shape adj=\"1\"/>';\r\n\r\n\t\tvar shape = div.firstChild;\r\n\t\tshape.style.behavior = 'url(#default#VML)';\r\n\r\n\t\treturn shape && (typeof shape.adj === 'object');\r\n\r\n\t} catch (e) {\r\n\t\treturn false;\r\n\t}\r\n}());\r\n\r\n\r\n// @property mac: Boolean; `true` when the browser is running in a Mac platform\r\nvar mac = navigator.platform.indexOf('Mac') === 0;\r\n\r\n// @property mac: Boolean; `true` when the browser is running in a Linux platform\r\nvar linux = navigator.platform.indexOf('Linux') === 0;\r\n\r\nfunction userAgentContains(str) {\r\n\treturn navigator.userAgent.toLowerCase().indexOf(str) >= 0;\r\n}\r\n\r\n\r\nexport default {\r\n\tie: ie,\r\n\tielt9: ielt9,\r\n\tedge: edge,\r\n\twebkit: webkit,\r\n\tandroid: android,\r\n\tandroid23: android23,\r\n\tandroidStock: androidStock,\r\n\topera: opera,\r\n\tchrome: chrome,\r\n\tgecko: gecko,\r\n\tsafari: safari,\r\n\tphantom: phantom,\r\n\topera12: opera12,\r\n\twin: win,\r\n\tie3d: ie3d,\r\n\twebkit3d: webkit3d,\r\n\tgecko3d: gecko3d,\r\n\tany3d: any3d,\r\n\tmobile: mobile,\r\n\tmobileWebkit: mobileWebkit,\r\n\tmobileWebkit3d: mobileWebkit3d,\r\n\tmsPointer: msPointer,\r\n\tpointer: pointer,\r\n\ttouch: touch,\r\n\ttouchNative: touchNative,\r\n\tmobileOpera: mobileOpera,\r\n\tmobileGecko: mobileGecko,\r\n\tretina: retina,\r\n\tpassiveEvents: passiveEvents,\r\n\tcanvas: canvas,\r\n\tsvg: svg,\r\n\tvml: vml,\r\n\tinlineSvg: inlineSvg,\r\n\tmac: mac,\r\n\tlinux: linux\r\n};\r\n", "import * as DomEvent from './DomEvent';\nimport Browser from '../core/Browser';\nimport {falseFn} from '../core/Util';\n\n/*\n * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.\n */\n\nvar POINTER_DOWN =   Browser.msPointer ? 'MSPointerDown'   : 'pointerdown';\nvar POINTER_MOVE =   Browser.msPointer ? 'MSPointerMove'   : 'pointermove';\nvar POINTER_UP =     Browser.msPointer ? 'MSPointerUp'     : 'pointerup';\nvar POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel';\nvar pEvent = {\n\ttouchstart  : POINTER_DOWN,\n\ttouchmove   : POINTER_MOVE,\n\ttouchend    : POINTER_UP,\n\ttouchcancel : POINTER_CANCEL\n};\nvar handle = {\n\ttouchstart  : _onPointerStart,\n\ttouchmove   : _handlePointer,\n\ttouchend    : _handlePointer,\n\ttouchcancel : _handlePointer\n};\nvar _pointers = {};\nvar _pointerDocListener = false;\n\n// Provides a touch events wrapper for (ms)pointer events.\n// ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890\n\nexport function addPointerListener(obj, type, handler) {\n\tif (type === 'touchstart') {\n\t\t_addPointerDocListener();\n\t}\n\tif (!handle[type]) {\n\t\tconsole.warn('wrong event specified:', type);\n\t\treturn falseFn;\n\t}\n\thandler = handle[type].bind(this, handler);\n\tobj.addEventListener(pEvent[type], handler, false);\n\treturn handler;\n}\n\nexport function removePointerListener(obj, type, handler) {\n\tif (!pEvent[type]) {\n\t\tconsole.warn('wrong event specified:', type);\n\t\treturn;\n\t}\n\tobj.removeEventListener(pEvent[type], handler, false);\n}\n\nfunction _globalPointerDown(e) {\n\t_pointers[e.pointerId] = e;\n}\n\nfunction _globalPointerMove(e) {\n\tif (_pointers[e.pointerId]) {\n\t\t_pointers[e.pointerId] = e;\n\t}\n}\n\nfunction _globalPointerUp(e) {\n\tdelete _pointers[e.pointerId];\n}\n\nfunction _addPointerDocListener() {\n\t// need to keep track of what pointers and how many are active to provide e.touches emulation\n\tif (!_pointerDocListener) {\n\t\t// we listen document as any drags that end by moving the touch off the screen get fired there\n\t\tdocument.addEventListener(POINTER_DOWN, _globalPointerDown, true);\n\t\tdocument.addEventListener(POINTER_MOVE, _globalPointerMove, true);\n\t\tdocument.addEventListener(POINTER_UP, _globalPointerUp, true);\n\t\tdocument.addEventListener(POINTER_CANCEL, _globalPointerUp, true);\n\n\t\t_pointerDocListener = true;\n\t}\n}\n\nfunction _handlePointer(handler, e) {\n\tif (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; }\n\n\te.touches = [];\n\tfor (var i in _pointers) {\n\t\te.touches.push(_pointers[i]);\n\t}\n\te.changedTouches = [e];\n\n\thandler(e);\n}\n\nfunction _onPointerStart(handler, e) {\n\t// IE10 specific: MsTouch needs preventDefault. See #2000\n\tif (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {\n\t\tDomEvent.preventDefault(e);\n\t}\n\t_handlePointer(handler, e);\n}\n", "import * as DomEvent from './DomEvent';\r\n\r\n/*\r\n * Extends the event handling code with double tap support for mobile browsers.\r\n *\r\n * Note: currently most browsers fire native dblclick, with only a few exceptions\r\n * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386)\r\n */\r\n\r\nfunction makeDblclick(event) {\r\n\t// in modern browsers `type` cannot be just overridden:\r\n\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only\r\n\tvar newEvent = {},\r\n\t    prop, i;\r\n\tfor (i in event) {\r\n\t\tprop = event[i];\r\n\t\tnewEvent[i] = prop && prop.bind ? prop.bind(event) : prop;\r\n\t}\r\n\tevent = newEvent;\r\n\tnewEvent.type = 'dblclick';\r\n\tnewEvent.detail = 2;\r\n\tnewEvent.isTrusted = false;\r\n\tnewEvent._simulated = true; // for debug purposes\r\n\treturn newEvent;\r\n}\r\n\r\nvar delay = 200;\r\nexport function addDoubleTapListener(obj, handler) {\r\n\t// Most browsers handle double tap natively\r\n\tobj.addEventListener('dblclick', handler);\r\n\r\n\t// On some platforms the browser doesn't fire native dblclicks for touch events.\r\n\t// It seems that in all such cases `detail` property of `click` event is always `1`.\r\n\t// So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed.\r\n\tvar last = 0,\r\n\t    detail;\r\n\tfunction simDblclick(e) {\r\n\t\tif (e.detail !== 1) {\r\n\t\t\tdetail = e.detail; // keep in sync to avoid false dblclick in some cases\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (e.pointerType === 'mouse' ||\r\n\t\t\t(e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) {\r\n\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// When clicking on an <input>, the browser generates a click on its\r\n\t\t// <label> (and vice versa) triggering two clicks in quick succession.\r\n\t\t// This ignores clicks on elements which are a label with a 'for'\r\n\t\t// attribute (or children of such a label), but not children of\r\n\t\t// a <input>.\r\n\t\tvar path = DomEvent.getPropagationPath(e);\r\n\t\tif (path.some(function (el) {\r\n\t\t\treturn el instanceof HTMLLabelElement && el.attributes.for;\r\n\t\t}) &&\r\n\t\t\t!path.some(function (el) {\r\n\t\t\t\treturn (\r\n\t\t\t\t\tel instanceof HTMLInputElement ||\r\n\t\t\t\t\tel instanceof HTMLSelectElement\r\n\t\t\t\t);\r\n\t\t\t})\r\n\t\t) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar now = Date.now();\r\n\t\tif (now - last <= delay) {\r\n\t\t\tdetail++;\r\n\t\t\tif (detail === 2) {\r\n\t\t\t\thandler(makeDblclick(e));\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tdetail = 1;\r\n\t\t}\r\n\t\tlast = now;\r\n\t}\r\n\r\n\tobj.addEventListener('click', simDblclick);\r\n\r\n\treturn {\r\n\t\tdblclick: handler,\r\n\t\tsimDblclick: simDblclick\r\n\t};\r\n}\r\n\r\nexport function removeDoubleTapListener(obj, handlers) {\r\n\tobj.removeEventListener('dblclick', handlers.dblclick);\r\n\tobj.removeEventListener('click', handlers.simDblclick);\r\n}\r\n", "import * as DomEvent from './DomEvent';\r\nimport * as Util from '../core/Util';\r\nimport {Point} from '../geometry/Point';\r\nimport Browser from '../core/Browser';\r\n\r\n/*\r\n * @namespace DomUtil\r\n *\r\n * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)\r\n * tree, used by Leaflet internally.\r\n *\r\n * Most functions expecting or returning a `HTMLElement` also work for\r\n * SVG elements. The only difference is that classes refer to CSS classes\r\n * in HTML and SVG classes in SVG.\r\n */\r\n\r\n\r\n// @property TRANSFORM: String\r\n// Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).\r\nexport var TRANSFORM = testProp(\r\n\t['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);\r\n\r\n// webkitTransition comes first because some browser versions that drop vendor prefix don't do\r\n// the same for the transitionend event, in particular the Android 4.1 stock browser\r\n\r\n// @property TRANSITION: String\r\n// Vendor-prefixed transition style name.\r\nexport var TRANSITION = testProp(\r\n\t['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);\r\n\r\n// @property TRANSITION_END: String\r\n// Vendor-prefixed transitionend event name.\r\nexport var TRANSITION_END =\r\n\tTRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';\r\n\r\n\r\n// @function get(id: String|HTMLElement): HTMLElement\r\n// Returns an element given its DOM id, or returns the element itself\r\n// if it was passed directly.\r\nexport function get(id) {\r\n\treturn typeof id === 'string' ? document.getElementById(id) : id;\r\n}\r\n\r\n// @function getStyle(el: HTMLElement, styleAttrib: String): String\r\n// Returns the value for a certain style attribute on an element,\r\n// including computed values or values set through CSS.\r\nexport function getStyle(el, style) {\r\n\tvar value = el.style[style] || (el.currentStyle && el.currentStyle[style]);\r\n\r\n\tif ((!value || value === 'auto') && document.defaultView) {\r\n\t\tvar css = document.defaultView.getComputedStyle(el, null);\r\n\t\tvalue = css ? css[style] : null;\r\n\t}\r\n\treturn value === 'auto' ? null : value;\r\n}\r\n\r\n// @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement\r\n// Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.\r\nexport function create(tagName, className, container) {\r\n\tvar el = document.createElement(tagName);\r\n\tel.className = className || '';\r\n\r\n\tif (container) {\r\n\t\tcontainer.appendChild(el);\r\n\t}\r\n\treturn el;\r\n}\r\n\r\n// @function remove(el: HTMLElement)\r\n// Removes `el` from its parent element\r\nexport function remove(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent) {\r\n\t\tparent.removeChild(el);\r\n\t}\r\n}\r\n\r\n// @function empty(el: HTMLElement)\r\n// Removes all of `el`'s children elements from `el`\r\nexport function empty(el) {\r\n\twhile (el.firstChild) {\r\n\t\tel.removeChild(el.firstChild);\r\n\t}\r\n}\r\n\r\n// @function toFront(el: HTMLElement)\r\n// Makes `el` the last child of its parent, so it renders in front of the other children.\r\nexport function toFront(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.lastChild !== el) {\r\n\t\tparent.appendChild(el);\r\n\t}\r\n}\r\n\r\n// @function toBack(el: HTMLElement)\r\n// Makes `el` the first child of its parent, so it renders behind the other children.\r\nexport function toBack(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.firstChild !== el) {\r\n\t\tparent.insertBefore(el, parent.firstChild);\r\n\t}\r\n}\r\n\r\n// @function hasClass(el: HTMLElement, name: String): Boolean\r\n// Returns `true` if the element's class attribute contains `name`.\r\nexport function hasClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\treturn el.classList.contains(name);\r\n\t}\r\n\tvar className = getClass(el);\r\n\treturn className.length > 0 && new RegExp('(^|\\\\s)' + name + '(\\\\s|$)').test(className);\r\n}\r\n\r\n// @function addClass(el: HTMLElement, name: String)\r\n// Adds `name` to the element's class attribute.\r\nexport function addClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tvar classes = Util.splitWords(name);\r\n\t\tfor (var i = 0, len = classes.length; i < len; i++) {\r\n\t\t\tel.classList.add(classes[i]);\r\n\t\t}\r\n\t} else if (!hasClass(el, name)) {\r\n\t\tvar className = getClass(el);\r\n\t\tsetClass(el, (className ? className + ' ' : '') + name);\r\n\t}\r\n}\r\n\r\n// @function removeClass(el: HTMLElement, name: String)\r\n// Removes `name` from the element's class attribute.\r\nexport function removeClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tel.classList.remove(name);\r\n\t} else {\r\n\t\tsetClass(el, Util.trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));\r\n\t}\r\n}\r\n\r\n// @function setClass(el: HTMLElement, name: String)\r\n// Sets the element's class.\r\nexport function setClass(el, name) {\r\n\tif (el.className.baseVal === undefined) {\r\n\t\tel.className = name;\r\n\t} else {\r\n\t\t// in case of SVG element\r\n\t\tel.className.baseVal = name;\r\n\t}\r\n}\r\n\r\n// @function getClass(el: HTMLElement): String\r\n// Returns the element's class.\r\nexport function getClass(el) {\r\n\t// Check if the element is an SVGElementInstance and use the correspondingElement instead\r\n\t// (Required for linked SVG elements in IE11.)\r\n\tif (el.correspondingElement) {\r\n\t\tel = el.correspondingElement;\r\n\t}\r\n\treturn el.className.baseVal === undefined ? el.className : el.className.baseVal;\r\n}\r\n\r\n// @function setOpacity(el: HTMLElement, opacity: Number)\r\n// Set the opacity of an element (including old IE support).\r\n// `opacity` must be a number from `0` to `1`.\r\nexport function setOpacity(el, value) {\r\n\tif ('opacity' in el.style) {\r\n\t\tel.style.opacity = value;\r\n\t} else if ('filter' in el.style) {\r\n\t\t_setOpacityIE(el, value);\r\n\t}\r\n}\r\n\r\nfunction _setOpacityIE(el, value) {\r\n\tvar filter = false,\r\n\t    filterName = 'DXImageTransform.Microsoft.Alpha';\r\n\r\n\t// filters collection throws an error if we try to retrieve a filter that doesn't exist\r\n\ttry {\r\n\t\tfilter = el.filters.item(filterName);\r\n\t} catch (e) {\r\n\t\t// don't set opacity to 1 if we haven't already set an opacity,\r\n\t\t// it isn't needed and breaks transparent pngs.\r\n\t\tif (value === 1) { return; }\r\n\t}\r\n\r\n\tvalue = Math.round(value * 100);\r\n\r\n\tif (filter) {\r\n\t\tfilter.Enabled = (value !== 100);\r\n\t\tfilter.Opacity = value;\r\n\t} else {\r\n\t\tel.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';\r\n\t}\r\n}\r\n\r\n// @function testProp(props: String[]): String|false\r\n// Goes through the array of style names and returns the first name\r\n// that is a valid style name for an element. If no such name is found,\r\n// it returns false. Useful for vendor-prefixed styles like `transform`.\r\nexport function testProp(props) {\r\n\tvar style = document.documentElement.style;\r\n\r\n\tfor (var i = 0; i < props.length; i++) {\r\n\t\tif (props[i] in style) {\r\n\t\t\treturn props[i];\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n// @function setTransform(el: HTMLElement, offset: Point, scale?: Number)\r\n// Resets the 3D CSS transform of `el` so it is translated by `offset` pixels\r\n// and optionally scaled by `scale`. Does not have an effect if the\r\n// browser doesn't support 3D CSS transforms.\r\nexport function setTransform(el, offset, scale) {\r\n\tvar pos = offset || new Point(0, 0);\r\n\r\n\tel.style[TRANSFORM] =\r\n\t\t(Browser.ie3d ?\r\n\t\t\t'translate(' + pos.x + 'px,' + pos.y + 'px)' :\r\n\t\t\t'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +\r\n\t\t(scale ? ' scale(' + scale + ')' : '');\r\n}\r\n\r\n// @function setPosition(el: HTMLElement, position: Point)\r\n// Sets the position of `el` to coordinates specified by `position`,\r\n// using CSS translate or top/left positioning depending on the browser\r\n// (used by Leaflet internally to position its layers).\r\nexport function setPosition(el, point) {\r\n\r\n\t/*eslint-disable */\r\n\tel._leaflet_pos = point;\r\n\t/* eslint-enable */\r\n\r\n\tif (Browser.any3d) {\r\n\t\tsetTransform(el, point);\r\n\t} else {\r\n\t\tel.style.left = point.x + 'px';\r\n\t\tel.style.top = point.y + 'px';\r\n\t}\r\n}\r\n\r\n// @function getPosition(el: HTMLElement): Point\r\n// Returns the coordinates of an element previously positioned with setPosition.\r\nexport function getPosition(el) {\r\n\t// this method is only used for elements previously positioned using setPosition,\r\n\t// so it's safe to cache the position for performance\r\n\r\n\treturn el._leaflet_pos || new Point(0, 0);\r\n}\r\n\r\n// @function disableTextSelection()\r\n// Prevents the user from generating `selectstart` DOM events, usually generated\r\n// when the user drags the mouse through a page with text. Used internally\r\n// by Leaflet to override the behaviour of any click-and-drag interaction on\r\n// the map. Affects drag interactions on the whole document.\r\n\r\n// @function enableTextSelection()\r\n// Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).\r\nexport var disableTextSelection;\r\nexport var enableTextSelection;\r\nvar _userSelect;\r\nif ('onselectstart' in document) {\r\n\tdisableTextSelection = function () {\r\n\t\tDomEvent.on(window, 'selectstart', DomEvent.preventDefault);\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\tDomEvent.off(window, 'selectstart', DomEvent.preventDefault);\r\n\t};\r\n} else {\r\n\tvar userSelectProperty = testProp(\r\n\t\t['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);\r\n\r\n\tdisableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tvar style = document.documentElement.style;\r\n\t\t\t_userSelect = style[userSelectProperty];\r\n\t\t\tstyle[userSelectProperty] = 'none';\r\n\t\t}\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tdocument.documentElement.style[userSelectProperty] = _userSelect;\r\n\t\t\t_userSelect = undefined;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n// @function disableImageDrag()\r\n// As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but\r\n// for `dragstart` DOM events, usually generated when the user drags an image.\r\nexport function disableImageDrag() {\r\n\tDomEvent.on(window, 'dragstart', DomEvent.preventDefault);\r\n}\r\n\r\n// @function enableImageDrag()\r\n// Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).\r\nexport function enableImageDrag() {\r\n\tDomEvent.off(window, 'dragstart', DomEvent.preventDefault);\r\n}\r\n\r\nvar _outlineElement, _outlineStyle;\r\n// @function preventOutline(el: HTMLElement)\r\n// Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)\r\n// of the element `el` invisible. Used internally by Leaflet to prevent\r\n// focusable elements from displaying an outline when the user performs a\r\n// drag interaction on them.\r\nexport function preventOutline(element) {\r\n\twhile (element.tabIndex === -1) {\r\n\t\telement = element.parentNode;\r\n\t}\r\n\tif (!element.style) { return; }\r\n\trestoreOutline();\r\n\t_outlineElement = element;\r\n\t_outlineStyle = element.style.outlineStyle;\r\n\telement.style.outlineStyle = 'none';\r\n\tDomEvent.on(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function restoreOutline()\r\n// Cancels the effects of a previous [`L.DomUtil.preventOutline`]().\r\nexport function restoreOutline() {\r\n\tif (!_outlineElement) { return; }\r\n\t_outlineElement.style.outlineStyle = _outlineStyle;\r\n\t_outlineElement = undefined;\r\n\t_outlineStyle = undefined;\r\n\tDomEvent.off(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function getSizedParentNode(el: HTMLElement): HTMLElement\r\n// Finds the closest parent node which size (width and height) is not null.\r\nexport function getSizedParentNode(element) {\r\n\tdo {\r\n\t\telement = element.parentNode;\r\n\t} while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);\r\n\treturn element;\r\n}\r\n\r\n// @function getScale(el: HTMLElement): Object\r\n// Computes the CSS scale currently applied on the element.\r\n// Returns an object with `x` and `y` members as horizontal and vertical scales respectively,\r\n// and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).\r\nexport function getScale(element) {\r\n\tvar rect = element.getBoundingClientRect(); // Read-only in old browsers.\r\n\r\n\treturn {\r\n\t\tx: rect.width / element.offsetWidth || 1,\r\n\t\ty: rect.height / element.offsetHeight || 1,\r\n\t\tboundingClientRect: rect\r\n\t};\r\n}\r\n", "import {Point} from '../geometry/Point';\r\nimport * as Util from '../core/Util';\r\nimport Browser from '../core/Browser';\r\nimport {addPointerListener, removePointerListener} from './DomEvent.Pointer';\r\nimport {addDoubleTapListener, removeDoubleTapListener} from './DomEvent.DoubleTap';\r\nimport {getScale} from './DomUtil';\r\n\r\n/*\r\n * @namespace DomEvent\r\n * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.\r\n */\r\n\r\n// Inspired by John Resig, Dean Edwards and YUI addEvent implementations.\r\n\r\n// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Adds a listener function (`fn`) to a particular DOM event type of the\r\n// element `el`. You can optionally specify the context of the listener\r\n// (object the `this` keyword will point to). You can also pass several\r\n// space-separated types (e.g. `'click dblclick'`).\r\n\r\n// @alternative\r\n// @function on(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\nexport function on(obj, types, fn, context) {\r\n\r\n\tif (types && typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\taddOne(obj, type, types[type], fn);\r\n\t\t}\r\n\t} else {\r\n\t\ttypes = Util.splitWords(types);\r\n\r\n\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\taddOne(obj, types[i], fn, context);\r\n\t\t}\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nvar eventsKey = '_leaflet_events';\r\n\r\n// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Removes a previously added listener function.\r\n// Note that if you passed a custom context to on, you must pass the same\r\n// context to `off` in order to remove the listener.\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement, types: String): this\r\n// Removes all previously added listeners of given types.\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement): this\r\n// Removes all previously added listeners from given HTMLElement\r\nexport function off(obj, types, fn, context) {\r\n\r\n\tif (arguments.length === 1) {\r\n\t\tbatchRemove(obj);\r\n\t\tdelete obj[eventsKey];\r\n\r\n\t} else if (types && typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\tremoveOne(obj, type, types[type], fn);\r\n\t\t}\r\n\r\n\t} else {\r\n\t\ttypes = Util.splitWords(types);\r\n\r\n\t\tif (arguments.length === 2) {\r\n\t\t\tbatchRemove(obj, function (type) {\r\n\t\t\t\treturn Util.indexOf(types, type) !== -1;\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tremoveOne(obj, types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nfunction batchRemove(obj, filterFn) {\r\n\tfor (var id in obj[eventsKey]) {\r\n\t\tvar type = id.split(/\\d/)[0];\r\n\t\tif (!filterFn || filterFn(type)) {\r\n\t\t\tremoveOne(obj, type, null, null, id);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvar mouseSubst = {\r\n\tmouseenter: 'mouseover',\r\n\tmouseleave: 'mouseout',\r\n\twheel: !('onwheel' in window) && 'mousewheel'\r\n};\r\n\r\nfunction addOne(obj, type, fn, context) {\r\n\tvar id = type + Util.stamp(fn) + (context ? '_' + Util.stamp(context) : '');\r\n\r\n\tif (obj[eventsKey] && obj[eventsKey][id]) { return this; }\r\n\r\n\tvar handler = function (e) {\r\n\t\treturn fn.call(context || obj, e || window.event);\r\n\t};\r\n\r\n\tvar originalHandler = handler;\r\n\r\n\tif (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {\r\n\t\t// Needs DomEvent.Pointer.js\r\n\t\thandler = addPointerListener(obj, type, handler);\r\n\r\n\t} else if (Browser.touch && (type === 'dblclick')) {\r\n\t\thandler = addDoubleTapListener(obj, handler);\r\n\r\n\t} else if ('addEventListener' in obj) {\r\n\r\n\t\tif (type === 'touchstart' || type === 'touchmove' || type === 'wheel' ||  type === 'mousewheel') {\r\n\t\t\tobj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false);\r\n\r\n\t\t} else if (type === 'mouseenter' || type === 'mouseleave') {\r\n\t\t\thandler = function (e) {\r\n\t\t\t\te = e || window.event;\r\n\t\t\t\tif (isExternalTarget(obj, e)) {\r\n\t\t\t\t\toriginalHandler(e);\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tobj.addEventListener(mouseSubst[type], handler, false);\r\n\r\n\t\t} else {\r\n\t\t\tobj.addEventListener(type, originalHandler, false);\r\n\t\t}\r\n\r\n\t} else {\r\n\t\tobj.attachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey] = obj[eventsKey] || {};\r\n\tobj[eventsKey][id] = handler;\r\n}\r\n\r\nfunction removeOne(obj, type, fn, context, id) {\r\n\tid = id || type + Util.stamp(fn) + (context ? '_' + Util.stamp(context) : '');\r\n\tvar handler = obj[eventsKey] && obj[eventsKey][id];\r\n\r\n\tif (!handler) { return this; }\r\n\r\n\tif (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {\r\n\t\tremovePointerListener(obj, type, handler);\r\n\r\n\t} else if (Browser.touch && (type === 'dblclick')) {\r\n\t\tremoveDoubleTapListener(obj, handler);\r\n\r\n\t} else if ('removeEventListener' in obj) {\r\n\r\n\t\tobj.removeEventListener(mouseSubst[type] || type, handler, false);\r\n\r\n\t} else {\r\n\t\tobj.detachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey][id] = null;\r\n}\r\n\r\n// @function stopPropagation(ev: DOMEvent): this\r\n// Stop the given event from propagation to parent elements. Used inside the listener functions:\r\n// ```js\r\n// L.DomEvent.on(div, 'click', function (ev) {\r\n// \tL.DomEvent.stopPropagation(ev);\r\n// });\r\n// ```\r\nexport function stopPropagation(e) {\r\n\r\n\tif (e.stopPropagation) {\r\n\t\te.stopPropagation();\r\n\t} else if (e.originalEvent) {  // In case of Leaflet event.\r\n\t\te.originalEvent._stopped = true;\r\n\t} else {\r\n\t\te.cancelBubble = true;\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\n// @function disableScrollPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).\r\nexport function disableScrollPropagation(el) {\r\n\taddOne(el, 'wheel', stopPropagation);\r\n\treturn this;\r\n}\r\n\r\n// @function disableClickPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`,\r\n// `'mousedown'` and `'touchstart'` events (plus browser variants).\r\nexport function disableClickPropagation(el) {\r\n\ton(el, 'mousedown touchstart dblclick contextmenu', stopPropagation);\r\n\tel['_leaflet_disable_click'] = true;\r\n\treturn this;\r\n}\r\n\r\n// @function preventDefault(ev: DOMEvent): this\r\n// Prevents the default action of the DOM Event `ev` from happening (such as\r\n// following a link in the href of the a element, or doing a POST request\r\n// with page reload when a `<form>` is submitted).\r\n// Use it inside listener functions.\r\nexport function preventDefault(e) {\r\n\tif (e.preventDefault) {\r\n\t\te.preventDefault();\r\n\t} else {\r\n\t\te.returnValue = false;\r\n\t}\r\n\treturn this;\r\n}\r\n\r\n// @function stop(ev: DOMEvent): this\r\n// Does `stopPropagation` and `preventDefault` at the same time.\r\nexport function stop(e) {\r\n\tpreventDefault(e);\r\n\tstopPropagation(e);\r\n\treturn this;\r\n}\r\n\r\n// @function getPropagationPath(ev: DOMEvent): Array\r\n// Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath).\r\n// Returns an array containing the `HTMLElement`s that the given DOM event\r\n// should propagate to (if not stopped).\r\nexport function getPropagationPath(ev) {\r\n\tif (ev.composedPath) {\r\n\t\treturn ev.composedPath();\r\n\t}\r\n\r\n\tvar path = [];\r\n\tvar el = ev.target;\r\n\r\n\twhile (el) {\r\n\t\tpath.push(el);\r\n\t\tel = el.parentNode;\r\n\t}\r\n\treturn path;\r\n}\r\n\r\n\r\n// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point\r\n// Gets normalized mouse position from a DOM event relative to the\r\n// `container` (border excluded) or to the whole page if not specified.\r\nexport function getMousePosition(e, container) {\r\n\tif (!container) {\r\n\t\treturn new Point(e.clientX, e.clientY);\r\n\t}\r\n\r\n\tvar scale = getScale(container),\r\n\t    offset = scale.boundingClientRect; // left and top  values are in page scale (like the event clientX/Y)\r\n\r\n\treturn new Point(\r\n\t\t// offset.left/top values are in page scale (like clientX/Y),\r\n\t\t// whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).\r\n\t\t(e.clientX - offset.left) / scale.x - container.clientLeft,\r\n\t\t(e.clientY - offset.top) / scale.y - container.clientTop\r\n\t);\r\n}\r\n\r\n\r\n//  except , Safari and\r\n// We need double the scroll pixels (see #7403 and #4538) for all Browsers\r\n// except OSX (Mac) -> 3x, Chrome running on Linux 1x\r\n\r\nvar wheelPxFactor =\r\n\t(Browser.linux && Browser.chrome) ? window.devicePixelRatio :\r\n\tBrowser.mac ? window.devicePixelRatio * 3 :\r\n\twindow.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;\r\n// @function getWheelDelta(ev: DOMEvent): Number\r\n// Gets normalized wheel delta from a wheel DOM event, in vertical\r\n// pixels scrolled (negative if scrolling down).\r\n// Events from pointing devices without precise scrolling are mapped to\r\n// a best guess of 60 pixels.\r\nexport function getWheelDelta(e) {\r\n\treturn (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta\r\n\t       (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels\r\n\t       (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines\r\n\t       (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages\r\n\t       (e.deltaX || e.deltaZ) ? 0 :\t// Skip horizontal/depth wheel events\r\n\t       e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels\r\n\t       (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines\r\n\t       e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages\r\n\t       0;\r\n}\r\n\r\n// check if element really left/entered the event target (for mouseenter/mouseleave)\r\nexport function isExternalTarget(el, e) {\r\n\r\n\tvar related = e.relatedTarget;\r\n\r\n\tif (!related) { return true; }\r\n\r\n\ttry {\r\n\t\twhile (related && (related !== el)) {\r\n\t\t\trelated = related.parentNode;\r\n\t\t}\r\n\t} catch (err) {\r\n\t\treturn false;\r\n\t}\r\n\treturn (related !== el);\r\n}\r\n\r\n// @function addListener(…): this\r\n// Alias to [`L.DomEvent.on`](#domevent-on)\r\nexport {on as addListener};\r\n\r\n// @function removeListener(…): this\r\n// Alias to [`L.DomEvent.off`](#domevent-off)\r\nexport {off as removeListener};\r\n", "import * as Util from '../core/Util';\nimport {Evented} from '../core/Events';\nimport * as DomUtil from '../dom/DomUtil';\n\n\n/*\n * @class PosAnimation\n * @aka L.PosAnimation\n * @inherits Evented\n * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.\n *\n * @example\n * ```js\n * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);\n *\n * myPositionMarker.on(\"click\", function() {\n * \tvar pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());\n * \tpos.y -= 25;\n * \tvar fx = new L.PosAnimation();\n *\n * \tfx.once('end',function() {\n * \t\tpos.y += 25;\n * \t\tfx.run(myPositionMarker._icon, pos, 0.8);\n * \t});\n *\n * \tfx.run(myPositionMarker._icon, pos, 0.3);\n * });\n *\n * ```\n *\n * @constructor L.PosAnimation()\n * Creates a `PosAnimation` object.\n *\n */\n\nexport var PosAnimation = Evented.extend({\n\n\t// @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)\n\t// Run an animation of a given element to a new position, optionally setting\n\t// duration in seconds (`0.25` by default) and easing linearity factor (3rd\n\t// argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),\n\t// `0.5` by default).\n\trun: function (el, newPos, duration, easeLinearity) {\n\t\tthis.stop();\n\n\t\tthis._el = el;\n\t\tthis._inProgress = true;\n\t\tthis._duration = duration || 0.25;\n\t\tthis._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);\n\n\t\tthis._startPos = DomUtil.getPosition(el);\n\t\tthis._offset = newPos.subtract(this._startPos);\n\t\tthis._startTime = +new Date();\n\n\t\t// @event start: Event\n\t\t// Fired when the animation starts\n\t\tthis.fire('start');\n\n\t\tthis._animate();\n\t},\n\n\t// @method stop()\n\t// Stops the animation (if currently running).\n\tstop: function () {\n\t\tif (!this._inProgress) { return; }\n\n\t\tthis._step(true);\n\t\tthis._complete();\n\t},\n\n\t_animate: function () {\n\t\t// animation loop\n\t\tthis._animId = Util.requestAnimFrame(this._animate, this);\n\t\tthis._step();\n\t},\n\n\t_step: function (round) {\n\t\tvar elapsed = (+new Date()) - this._startTime,\n\t\t    duration = this._duration * 1000;\n\n\t\tif (elapsed < duration) {\n\t\t\tthis._runFrame(this._easeOut(elapsed / duration), round);\n\t\t} else {\n\t\t\tthis._runFrame(1);\n\t\t\tthis._complete();\n\t\t}\n\t},\n\n\t_runFrame: function (progress, round) {\n\t\tvar pos = this._startPos.add(this._offset.multiplyBy(progress));\n\t\tif (round) {\n\t\t\tpos._round();\n\t\t}\n\t\tDomUtil.setPosition(this._el, pos);\n\n\t\t// @event step: Event\n\t\t// Fired continuously during the animation.\n\t\tthis.fire('step');\n\t},\n\n\t_complete: function () {\n\t\tUtil.cancelAnimFrame(this._animId);\n\n\t\tthis._inProgress = false;\n\t\t// @event end: Event\n\t\t// Fired when the animation ends.\n\t\tthis.fire('end');\n\t},\n\n\t_easeOut: function (t) {\n\t\treturn 1 - Math.pow(1 - t, this._easeOutPower);\n\t}\n});\n", "import * as Util from '../core/Util';\r\nimport {Evented} from '../core/Events';\r\nimport {EPSG3857} from '../geo/crs/CRS.EPSG3857';\r\nimport {Point, toPoint} from '../geometry/Point';\r\nimport {Bounds, toBounds} from '../geometry/Bounds';\r\nimport {LatLng, toLatLng} from '../geo/LatLng';\r\nimport {LatLngBounds, toLatLngBounds} from '../geo/LatLngBounds';\r\nimport Browser from '../core/Browser';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport {PosAnimation} from '../dom/PosAnimation';\r\n\r\n/*\r\n * @class Map\r\n * @aka L.Map\r\n * @inherits Evented\r\n *\r\n * The central class of the API — it is used to create a map on a page and manipulate it.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * // initialize the map on the \"map\" div with a given center and zoom\r\n * var map = L.map('map', {\r\n * \tcenter: [51.505, -0.09],\r\n * \tzoom: 13\r\n * });\r\n * ```\r\n *\r\n */\r\n\r\nexport var Map = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section Map State Options\r\n\t\t// @option crs: CRS = L.CRS.EPSG3857\r\n\t\t// The [Coordinate Reference System](#crs) to use. Don't change this if you're not\r\n\t\t// sure what it means.\r\n\t\tcrs: EPSG3857,\r\n\r\n\t\t// @option center: LatLng = undefined\r\n\t\t// Initial geographic center of the map\r\n\t\tcenter: undefined,\r\n\r\n\t\t// @option zoom: Number = undefined\r\n\t\t// Initial map zoom level\r\n\t\tzoom: undefined,\r\n\r\n\t\t// @option minZoom: Number = *\r\n\t\t// Minimum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the lowest of their `minZoom` options will be used instead.\r\n\t\tminZoom: undefined,\r\n\r\n\t\t// @option maxZoom: Number = *\r\n\t\t// Maximum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the highest of their `maxZoom` options will be used instead.\r\n\t\tmaxZoom: undefined,\r\n\r\n\t\t// @option layers: Layer[] = []\r\n\t\t// Array of layers that will be added to the map initially\r\n\t\tlayers: [],\r\n\r\n\t\t// @option maxBounds: LatLngBounds = null\r\n\t\t// When this option is set, the map restricts the view to the given\r\n\t\t// geographical bounds, bouncing the user back if the user tries to pan\r\n\t\t// outside the view. To set the restriction dynamically, use\r\n\t\t// [`setMaxBounds`](#map-setmaxbounds) method.\r\n\t\tmaxBounds: undefined,\r\n\r\n\t\t// @option renderer: Renderer = *\r\n\t\t// The default method for drawing vector layers on the map. `L.SVG`\r\n\t\t// or `L.Canvas` by default depending on browser support.\r\n\t\trenderer: undefined,\r\n\r\n\r\n\t\t// @section Animation Options\r\n\t\t// @option zoomAnimation: Boolean = true\r\n\t\t// Whether the map zoom animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tzoomAnimation: true,\r\n\r\n\t\t// @option zoomAnimationThreshold: Number = 4\r\n\t\t// Won't animate zoom if the zoom difference exceeds this value.\r\n\t\tzoomAnimationThreshold: 4,\r\n\r\n\t\t// @option fadeAnimation: Boolean = true\r\n\t\t// Whether the tile fade animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tfadeAnimation: true,\r\n\r\n\t\t// @option markerZoomAnimation: Boolean = true\r\n\t\t// Whether markers animate their zoom with the zoom animation, if disabled\r\n\t\t// they will disappear for the length of the animation. By default it's\r\n\t\t// enabled in all browsers that support CSS3 Transitions except Android.\r\n\t\tmarkerZoomAnimation: true,\r\n\r\n\t\t// @option transform3DLimit: Number = 2^23\r\n\t\t// Defines the maximum size of a CSS translation transform. The default\r\n\t\t// value should not be changed unless a web browser positions layers in\r\n\t\t// the wrong place after doing a large `panBy`.\r\n\t\ttransform3DLimit: 8388608, // Precision limit of a 32-bit float\r\n\r\n\t\t// @section Interaction Options\r\n\t\t// @option zoomSnap: Number = 1\r\n\t\t// Forces the map's zoom level to always be a multiple of this, particularly\r\n\t\t// right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.\r\n\t\t// By default, the zoom level snaps to the nearest integer; lower values\r\n\t\t// (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`\r\n\t\t// means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.\r\n\t\tzoomSnap: 1,\r\n\r\n\t\t// @option zoomDelta: Number = 1\r\n\t\t// Controls how much the map's zoom level will change after a\r\n\t\t// [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`\r\n\t\t// or `-` on the keyboard, or using the [zoom controls](#control-zoom).\r\n\t\t// Values smaller than `1` (e.g. `0.5`) allow for greater granularity.\r\n\t\tzoomDelta: 1,\r\n\r\n\t\t// @option trackResize: Boolean = true\r\n\t\t// Whether the map automatically handles browser window resize to update itself.\r\n\t\ttrackResize: true\r\n\t},\r\n\r\n\tinitialize: function (id, options) { // (HTMLElement or String, Object)\r\n\t\toptions = Util.setOptions(this, options);\r\n\r\n\t\t// Make sure to assign internal flags at the beginning,\r\n\t\t// to avoid inconsistent state in some edge cases.\r\n\t\tthis._handlers = [];\r\n\t\tthis._layers = {};\r\n\t\tthis._zoomBoundLayers = {};\r\n\t\tthis._sizeChanged = true;\r\n\r\n\t\tthis._initContainer(id);\r\n\t\tthis._initLayout();\r\n\r\n\t\t// hack for https://github.com/Leaflet/Leaflet/issues/1980\r\n\t\tthis._onResize = Util.bind(this._onResize, this);\r\n\r\n\t\tthis._initEvents();\r\n\r\n\t\tif (options.maxBounds) {\r\n\t\t\tthis.setMaxBounds(options.maxBounds);\r\n\t\t}\r\n\r\n\t\tif (options.zoom !== undefined) {\r\n\t\t\tthis._zoom = this._limitZoom(options.zoom);\r\n\t\t}\r\n\r\n\t\tif (options.center && options.zoom !== undefined) {\r\n\t\t\tthis.setView(toLatLng(options.center), options.zoom, {reset: true});\r\n\t\t}\r\n\r\n\t\tthis.callInitHooks();\r\n\r\n\t\t// don't animate on browsers without hardware-accelerated transitions or old Android/Opera\r\n\t\tthis._zoomAnimated = DomUtil.TRANSITION && Browser.any3d && !Browser.mobileOpera &&\r\n\t\t\t\tthis.options.zoomAnimation;\r\n\r\n\t\t// zoom transitions run with the same duration for all layers, so if one of transitionend events\r\n\t\t// happens after starting zoom animation (propagating to the map pane), we know that it ended globally\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tthis._createAnimProxy();\r\n\t\t\tDomEvent.on(this._proxy, DomUtil.TRANSITION_END, this._catchTransitionEnd, this);\r\n\t\t}\r\n\r\n\t\tthis._addLayers(this.options.layers);\r\n\t},\r\n\r\n\r\n\t// @section Methods for modifying map state\r\n\r\n\t// @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) with the given\r\n\t// animation options.\r\n\tsetView: function (center, zoom, options) {\r\n\r\n\t\tzoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);\r\n\t\tcenter = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);\r\n\t\toptions = options || {};\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tif (this._loaded && !options.reset && options !== true) {\r\n\r\n\t\t\tif (options.animate !== undefined) {\r\n\t\t\t\toptions.zoom = Util.extend({animate: options.animate}, options.zoom);\r\n\t\t\t\toptions.pan = Util.extend({animate: options.animate, duration: options.duration}, options.pan);\r\n\t\t\t}\r\n\r\n\t\t\t// try animating pan or zoom\r\n\t\t\tvar moved = (this._zoom !== zoom) ?\r\n\t\t\t\tthis._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :\r\n\t\t\t\tthis._tryAnimatedPan(center, options.pan);\r\n\r\n\t\t\tif (moved) {\r\n\t\t\t\t// prevent resize handler call, the view will refresh after animation anyway\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// animation didn't start, just reset the map view\r\n\t\tthis._resetView(center, zoom, options.pan && options.pan.noMoveStart);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setZoom(zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the zoom of the map.\r\n\tsetZoom: function (zoom, options) {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthis._zoom = zoom;\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\treturn this.setView(this.getCenter(), zoom, {zoom: options});\r\n\t},\r\n\r\n\t// @method zoomIn(delta?: Number, options?: Zoom options): this\r\n\t// Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomIn: function (delta, options) {\r\n\t\tdelta = delta || (Browser.any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom + delta, options);\r\n\t},\r\n\r\n\t// @method zoomOut(delta?: Number, options?: Zoom options): this\r\n\t// Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomOut: function (delta, options) {\r\n\t\tdelta = delta || (Browser.any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom - delta, options);\r\n\t},\r\n\r\n\t// @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified geographical point on the map\r\n\t// stationary (e.g. used internally for scroll zoom and double-click zoom).\r\n\t// @alternative\r\n\t// @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.\r\n\tsetZoomAround: function (latlng, zoom, options) {\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t    viewHalf = this.getSize().divideBy(2),\r\n\t\t    containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),\r\n\r\n\t\t    centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),\r\n\t\t    newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));\r\n\r\n\t\treturn this.setView(newCenter, zoom, {zoom: options});\r\n\t},\r\n\r\n\t_getBoundsCenterZoom: function (bounds, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tbounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t    paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\r\n\t\t    zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));\r\n\r\n\t\tzoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;\r\n\r\n\t\tif (zoom === Infinity) {\r\n\t\t\treturn {\r\n\t\t\t\tcenter: bounds.getCenter(),\r\n\t\t\t\tzoom: zoom\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tvar paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),\r\n\r\n\t\t    swPoint = this.project(bounds.getSouthWest(), zoom),\r\n\t\t    nePoint = this.project(bounds.getNorthEast(), zoom),\r\n\t\t    center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);\r\n\r\n\t\treturn {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom\r\n\t\t};\r\n\t},\r\n\r\n\t// @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets a map view that contains the given geographical bounds with the\r\n\t// maximum zoom level possible.\r\n\tfitBounds: function (bounds, options) {\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthrow new Error('Bounds are not valid.');\r\n\t\t}\r\n\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.setView(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method fitWorld(options?: fitBounds options): this\r\n\t// Sets a map view that mostly contains the whole world with the maximum\r\n\t// zoom level possible.\r\n\tfitWorld: function (options) {\r\n\t\treturn this.fitBounds([[-90, -180], [90, 180]], options);\r\n\t},\r\n\r\n\t// @method panTo(latlng: LatLng, options?: Pan options): this\r\n\t// Pans the map to a given center.\r\n\tpanTo: function (center, options) { // (LatLng)\r\n\t\treturn this.setView(center, this._zoom, {pan: options});\r\n\t},\r\n\r\n\t// @method panBy(offset: Point, options?: Pan options): this\r\n\t// Pans the map by a given number of pixels (animated).\r\n\tpanBy: function (offset, options) {\r\n\t\toffset = toPoint(offset).round();\r\n\t\toptions = options || {};\r\n\r\n\t\tif (!offset.x && !offset.y) {\r\n\t\t\treturn this.fire('moveend');\r\n\t\t}\r\n\t\t// If we pan too far, Chrome gets issues with tiles\r\n\t\t// and makes them disappear or appear in the wrong place (slightly offset) #2602\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) {\r\n\t\t\tthis._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tif (!this._panAnim) {\r\n\t\t\tthis._panAnim = new PosAnimation();\r\n\r\n\t\t\tthis._panAnim.on({\r\n\t\t\t\t'step': this._onPanTransitionStep,\r\n\t\t\t\t'end': this._onPanTransitionEnd\r\n\t\t\t}, this);\r\n\t\t}\r\n\r\n\t\t// don't fire movestart if animating inertia\r\n\t\tif (!options.noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\r\n\t\t// animate pan unless animate: false specified\r\n\t\tif (options.animate !== false) {\r\n\t\t\tDomUtil.addClass(this._mapPane, 'leaflet-pan-anim');\r\n\r\n\t\t\tvar newPos = this._getMapPanePos().subtract(offset).round();\r\n\t\t\tthis._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);\r\n\t\t} else {\r\n\t\t\tthis._rawPanBy(offset);\r\n\t\t\tthis.fire('move').fire('moveend');\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) performing a smooth\r\n\t// pan-zoom animation.\r\n\tflyTo: function (targetCenter, targetZoom, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tif (options.animate === false || !Browser.any3d) {\r\n\t\t\treturn this.setView(targetCenter, targetZoom, options);\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tvar from = this.project(this.getCenter()),\r\n\t\t    to = this.project(targetCenter),\r\n\t\t    size = this.getSize(),\r\n\t\t    startZoom = this._zoom;\r\n\r\n\t\ttargetCenter = toLatLng(targetCenter);\r\n\t\ttargetZoom = targetZoom === undefined ? startZoom : targetZoom;\r\n\r\n\t\tvar w0 = Math.max(size.x, size.y),\r\n\t\t    w1 = w0 * this.getZoomScale(startZoom, targetZoom),\r\n\t\t    u1 = (to.distanceTo(from)) || 1,\r\n\t\t    rho = 1.42,\r\n\t\t    rho2 = rho * rho;\r\n\r\n\t\tfunction r(i) {\r\n\t\t\tvar s1 = i ? -1 : 1,\r\n\t\t\t    s2 = i ? w1 : w0,\r\n\t\t\t    t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,\r\n\t\t\t    b1 = 2 * s2 * rho2 * u1,\r\n\t\t\t    b = t1 / b1,\r\n\t\t\t    sq = Math.sqrt(b * b + 1) - b;\r\n\r\n\t\t\t    // workaround for floating point precision bug when sq = 0, log = -Infinite,\r\n\t\t\t    // thus triggering an infinite loop in flyTo\r\n\t\t\t    var log = sq < 0.000000001 ? -18 : Math.log(sq);\r\n\r\n\t\t\treturn log;\r\n\t\t}\r\n\r\n\t\tfunction sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }\r\n\t\tfunction cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }\r\n\t\tfunction tanh(n) { return sinh(n) / cosh(n); }\r\n\r\n\t\tvar r0 = r(0);\r\n\r\n\t\tfunction w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }\r\n\t\tfunction u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }\r\n\r\n\t\tfunction easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }\r\n\r\n\t\tvar start = Date.now(),\r\n\t\t    S = (r(1) - r0) / rho,\r\n\t\t    duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;\r\n\r\n\t\tfunction frame() {\r\n\t\t\tvar t = (Date.now() - start) / duration,\r\n\t\t\t    s = easeOut(t) * S;\r\n\r\n\t\t\tif (t <= 1) {\r\n\t\t\t\tthis._flyToFrame = Util.requestAnimFrame(frame, this);\r\n\r\n\t\t\t\tthis._move(\r\n\t\t\t\t\tthis.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),\r\n\t\t\t\t\tthis.getScaleZoom(w0 / w(s), startZoom),\r\n\t\t\t\t\t{flyTo: true});\r\n\r\n\t\t\t} else {\r\n\t\t\t\tthis\r\n\t\t\t\t\t._move(targetCenter, targetZoom)\r\n\t\t\t\t\t._moveEnd(true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._moveStart(true, options.noMoveStart);\r\n\r\n\t\tframe.call(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),\r\n\t// but takes a bounds parameter like [`fitBounds`](#map-fitbounds).\r\n\tflyToBounds: function (bounds, options) {\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.flyTo(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method setMaxBounds(bounds: LatLngBounds): this\r\n\t// Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).\r\n\tsetMaxBounds: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (this.listens('moveend', this._panInsideMaxBounds)) {\r\n\t\t\tthis.off('moveend', this._panInsideMaxBounds);\r\n\t\t}\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthis.options.maxBounds = null;\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tthis.options.maxBounds = bounds;\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\tthis._panInsideMaxBounds();\r\n\t\t}\r\n\r\n\t\treturn this.on('moveend', this._panInsideMaxBounds);\r\n\t},\r\n\r\n\t// @method setMinZoom(zoom: Number): this\r\n\t// Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).\r\n\tsetMinZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.minZoom;\r\n\t\tthis.options.minZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() < this.options.minZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setMaxZoom(zoom: Number): this\r\n\t// Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).\r\n\tsetMaxZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.maxZoom;\r\n\t\tthis.options.maxZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() > this.options.maxZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this\r\n\t// Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.\r\n\tpanInsideBounds: function (bounds, options) {\r\n\t\tthis._enforcingBounds = true;\r\n\t\tvar center = this.getCenter(),\r\n\t\t    newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));\r\n\r\n\t\tif (!center.equals(newCenter)) {\r\n\t\t\tthis.panTo(newCenter, options);\r\n\t\t}\r\n\r\n\t\tthis._enforcingBounds = false;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInside(latlng: LatLng, options?: padding options): this\r\n\t// Pans the map the minimum amount to make the `latlng` visible. Use\r\n\t// padding options to fit the display to more restricted bounds.\r\n\t// If `latlng` is already within the (optionally padded) display bounds,\r\n\t// the map will not be panned.\r\n\tpanInside: function (latlng, options) {\r\n\t\toptions = options || {};\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t    paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\t\t    pixelCenter = this.project(this.getCenter()),\r\n\t\t    pixelPoint = this.project(latlng),\r\n\t\t    pixelBounds = this.getPixelBounds(),\r\n\t\t    paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),\r\n\t\t    paddedSize = paddedBounds.getSize();\r\n\r\n\t\tif (!paddedBounds.contains(pixelPoint)) {\r\n\t\t\tthis._enforcingBounds = true;\r\n\t\t\tvar centerOffset = pixelPoint.subtract(paddedBounds.getCenter());\r\n\t\t\tvar offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);\r\n\t\t\tpixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;\r\n\t\t\tpixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;\r\n\t\t\tthis.panTo(this.unproject(pixelCenter), options);\r\n\t\t\tthis._enforcingBounds = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method invalidateSize(options: Zoom/pan options): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default. If `options.pan` is `false`, panning will not occur.\r\n\t// If `options.debounceMoveend` is `true`, it will delay `moveend` event so\r\n\t// that it doesn't happen often even if the method is called many\r\n\t// times in a row.\r\n\r\n\t// @alternative\r\n\t// @method invalidateSize(animate: Boolean): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default.\r\n\tinvalidateSize: function (options) {\r\n\t\tif (!this._loaded) { return this; }\r\n\r\n\t\toptions = Util.extend({\r\n\t\t\tanimate: false,\r\n\t\t\tpan: true\r\n\t\t}, options === true ? {animate: true} : options);\r\n\r\n\t\tvar oldSize = this.getSize();\r\n\t\tthis._sizeChanged = true;\r\n\t\tthis._lastCenter = null;\r\n\r\n\t\tvar newSize = this.getSize(),\r\n\t\t    oldCenter = oldSize.divideBy(2).round(),\r\n\t\t    newCenter = newSize.divideBy(2).round(),\r\n\t\t    offset = oldCenter.subtract(newCenter);\r\n\r\n\t\tif (!offset.x && !offset.y) { return this; }\r\n\r\n\t\tif (options.animate && options.pan) {\r\n\t\t\tthis.panBy(offset);\r\n\r\n\t\t} else {\r\n\t\t\tif (options.pan) {\r\n\t\t\t\tthis._rawPanBy(offset);\r\n\t\t\t}\r\n\r\n\t\t\tthis.fire('move');\r\n\r\n\t\t\tif (options.debounceMoveend) {\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\tthis._sizeTimer = setTimeout(Util.bind(this.fire, this, 'moveend'), 200);\r\n\t\t\t} else {\r\n\t\t\t\tthis.fire('moveend');\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @section Map state change events\r\n\t\t// @event resize: ResizeEvent\r\n\t\t// Fired when the map is resized.\r\n\t\treturn this.fire('resize', {\r\n\t\t\toldSize: oldSize,\r\n\t\t\tnewSize: newSize\r\n\t\t});\r\n\t},\r\n\r\n\t// @section Methods for modifying map state\r\n\t// @method stop(): this\r\n\t// Stops the currently running `panTo` or `flyTo` animation, if any.\r\n\tstop: function () {\r\n\t\tthis.setZoom(this._limitZoom(this._zoom));\r\n\t\tif (!this.options.zoomSnap) {\r\n\t\t\tthis.fire('viewreset');\r\n\t\t}\r\n\t\treturn this._stop();\r\n\t},\r\n\r\n\t// @section Geolocation methods\r\n\t// @method locate(options?: Locate options): this\r\n\t// Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)\r\n\t// event with location data on success or a [`locationerror`](#map-locationerror) event on failure,\r\n\t// and optionally sets the map view to the user's location with respect to\r\n\t// detection accuracy (or to the world view if geolocation failed).\r\n\t// Note that, if your page doesn't use HTTPS, this method will fail in\r\n\t// modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))\r\n\t// See `Locate options` for more details.\r\n\tlocate: function (options) {\r\n\r\n\t\toptions = this._locateOptions = Util.extend({\r\n\t\t\ttimeout: 10000,\r\n\t\t\twatch: false\r\n\t\t\t// setView: false\r\n\t\t\t// maxZoom: <Number>\r\n\t\t\t// maximumAge: 0\r\n\t\t\t// enableHighAccuracy: false\r\n\t\t}, options);\r\n\r\n\t\tif (!('geolocation' in navigator)) {\r\n\t\t\tthis._handleGeolocationError({\r\n\t\t\t\tcode: 0,\r\n\t\t\t\tmessage: 'Geolocation not supported.'\r\n\t\t\t});\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar onResponse = Util.bind(this._handleGeolocationResponse, this),\r\n\t\t    onError = Util.bind(this._handleGeolocationError, this);\r\n\r\n\t\tif (options.watch) {\r\n\t\t\tthis._locationWatchId =\r\n\t\t\t        navigator.geolocation.watchPosition(onResponse, onError, options);\r\n\t\t} else {\r\n\t\t\tnavigator.geolocation.getCurrentPosition(onResponse, onError, options);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method stopLocate(): this\r\n\t// Stops watching location previously initiated by `map.locate({watch: true})`\r\n\t// and aborts resetting the map view if map.locate was called with\r\n\t// `{setView: true}`.\r\n\tstopLocate: function () {\r\n\t\tif (navigator.geolocation && navigator.geolocation.clearWatch) {\r\n\t\t\tnavigator.geolocation.clearWatch(this._locationWatchId);\r\n\t\t}\r\n\t\tif (this._locateOptions) {\r\n\t\t\tthis._locateOptions.setView = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_handleGeolocationError: function (error) {\r\n\t\tif (!this._container._leaflet_id) { return; }\r\n\r\n\t\tvar c = error.code,\r\n\t\t    message = error.message ||\r\n\t\t            (c === 1 ? 'permission denied' :\r\n\t\t            (c === 2 ? 'position unavailable' : 'timeout'));\r\n\r\n\t\tif (this._locateOptions.setView && !this._loaded) {\r\n\t\t\tthis.fitWorld();\r\n\t\t}\r\n\r\n\t\t// @section Location events\r\n\t\t// @event locationerror: ErrorEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method) failed.\r\n\t\tthis.fire('locationerror', {\r\n\t\t\tcode: c,\r\n\t\t\tmessage: 'Geolocation error: ' + message + '.'\r\n\t\t});\r\n\t},\r\n\r\n\t_handleGeolocationResponse: function (pos) {\r\n\t\tif (!this._container._leaflet_id) { return; }\r\n\r\n\t\tvar lat = pos.coords.latitude,\r\n\t\t    lng = pos.coords.longitude,\r\n\t\t    latlng = new LatLng(lat, lng),\r\n\t\t    bounds = latlng.toBounds(pos.coords.accuracy * 2),\r\n\t\t    options = this._locateOptions;\r\n\r\n\t\tif (options.setView) {\r\n\t\t\tvar zoom = this.getBoundsZoom(bounds);\r\n\t\t\tthis.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);\r\n\t\t}\r\n\r\n\t\tvar data = {\r\n\t\t\tlatlng: latlng,\r\n\t\t\tbounds: bounds,\r\n\t\t\ttimestamp: pos.timestamp\r\n\t\t};\r\n\r\n\t\tfor (var i in pos.coords) {\r\n\t\t\tif (typeof pos.coords[i] === 'number') {\r\n\t\t\t\tdata[i] = pos.coords[i];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @event locationfound: LocationEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method)\r\n\t\t// went successfully.\r\n\t\tthis.fire('locationfound', data);\r\n\t},\r\n\r\n\t// TODO Appropriate docs section?\r\n\t// @section Other Methods\r\n\t// @method addHandler(name: String, HandlerClass: Function): this\r\n\t// Adds a new `Handler` to the map, given its name and constructor function.\r\n\taddHandler: function (name, HandlerClass) {\r\n\t\tif (!HandlerClass) { return this; }\r\n\r\n\t\tvar handler = this[name] = new HandlerClass(this);\r\n\r\n\t\tthis._handlers.push(handler);\r\n\r\n\t\tif (this.options[name]) {\r\n\t\t\thandler.enable();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove(): this\r\n\t// Destroys the map and clears all related event listeners.\r\n\tremove: function () {\r\n\r\n\t\tthis._initEvents(true);\r\n\t\tif (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }\r\n\r\n\t\tif (this._containerId !== this._container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is being reused by another instance');\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\t// throws error in IE6-8\r\n\t\t\tdelete this._container._leaflet_id;\r\n\t\t\tdelete this._containerId;\r\n\t\t} catch (e) {\r\n\t\t\t/*eslint-disable */\r\n\t\t\tthis._container._leaflet_id = undefined;\r\n\t\t\t/* eslint-enable */\r\n\t\t\tthis._containerId = undefined;\r\n\t\t}\r\n\r\n\t\tif (this._locationWatchId !== undefined) {\r\n\t\t\tthis.stopLocate();\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tDomUtil.remove(this._mapPane);\r\n\r\n\t\tif (this._clearControlPos) {\r\n\t\t\tthis._clearControlPos();\r\n\t\t}\r\n\t\tif (this._resizeRequest) {\r\n\t\t\tUtil.cancelAnimFrame(this._resizeRequest);\r\n\t\t\tthis._resizeRequest = null;\r\n\t\t}\r\n\r\n\t\tthis._clearHandlers();\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\t// @section Map state change events\r\n\t\t\t// @event unload: Event\r\n\t\t\t// Fired when the map is destroyed with [remove](#map-remove) method.\r\n\t\t\tthis.fire('unload');\r\n\t\t}\r\n\r\n\t\tvar i;\r\n\t\tfor (i in this._layers) {\r\n\t\t\tthis._layers[i].remove();\r\n\t\t}\r\n\t\tfor (i in this._panes) {\r\n\t\t\tDomUtil.remove(this._panes[i]);\r\n\t\t}\r\n\r\n\t\tthis._layers = [];\r\n\t\tthis._panes = [];\r\n\t\tdelete this._mapPane;\r\n\t\tdelete this._renderer;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\t// @method createPane(name: String, container?: HTMLElement): HTMLElement\r\n\t// Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,\r\n\t// then returns it. The pane is created as a child of `container`, or\r\n\t// as a child of the main map pane if not set.\r\n\tcreatePane: function (name, container) {\r\n\t\tvar className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),\r\n\t\t    pane = DomUtil.create('div', className, container || this._mapPane);\r\n\r\n\t\tif (name) {\r\n\t\t\tthis._panes[name] = pane;\r\n\t\t}\r\n\t\treturn pane;\r\n\t},\r\n\r\n\t// @section Methods for Getting Map State\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the geographical center of the map view\r\n\tgetCenter: function () {\r\n\t\tthis._checkIfLoaded();\r\n\r\n\t\tif (this._lastCenter && !this._moved()) {\r\n\t\t\treturn this._lastCenter.clone();\r\n\t\t}\r\n\t\treturn this.layerPointToLatLng(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// @method getZoom(): Number\r\n\t// Returns the current zoom level of the map view\r\n\tgetZoom: function () {\r\n\t\treturn this._zoom;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the geographical bounds visible in the current map view\r\n\tgetBounds: function () {\r\n\t\tvar bounds = this.getPixelBounds(),\r\n\t\t    sw = this.unproject(bounds.getBottomLeft()),\r\n\t\t    ne = this.unproject(bounds.getTopRight());\r\n\r\n\t\treturn new LatLngBounds(sw, ne);\r\n\t},\r\n\r\n\t// @method getMinZoom(): Number\r\n\t// Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.\r\n\tgetMinZoom: function () {\r\n\t\treturn this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;\r\n\t},\r\n\r\n\t// @method getMaxZoom(): Number\r\n\t// Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).\r\n\tgetMaxZoom: function () {\r\n\t\treturn this.options.maxZoom === undefined ?\r\n\t\t\t(this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :\r\n\t\t\tthis.options.maxZoom;\r\n\t},\r\n\r\n\t// @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number\r\n\t// Returns the maximum zoom level on which the given bounds fit to the map\r\n\t// view in its entirety. If `inside` (optional) is set to `true`, the method\r\n\t// instead returns the minimum zoom level on which the map view fits into\r\n\t// the given bounds in its entirety.\r\n\tgetBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\t\tpadding = toPoint(padding || [0, 0]);\r\n\r\n\t\tvar zoom = this.getZoom() || 0,\r\n\t\t    min = this.getMinZoom(),\r\n\t\t    max = this.getMaxZoom(),\r\n\t\t    nw = bounds.getNorthWest(),\r\n\t\t    se = bounds.getSouthEast(),\r\n\t\t    size = this.getSize().subtract(padding),\r\n\t\t    boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),\r\n\t\t    snap = Browser.any3d ? this.options.zoomSnap : 1,\r\n\t\t    scalex = size.x / boundsSize.x,\r\n\t\t    scaley = size.y / boundsSize.y,\r\n\t\t    scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);\r\n\r\n\t\tzoom = this.getScaleZoom(scale, zoom);\r\n\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level\r\n\t\t\tzoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;\r\n\t\t}\r\n\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the current size of the map container (in pixels).\r\n\tgetSize: function () {\r\n\t\tif (!this._size || this._sizeChanged) {\r\n\t\t\tthis._size = new Point(\r\n\t\t\t\tthis._container.clientWidth || 0,\r\n\t\t\t\tthis._container.clientHeight || 0);\r\n\r\n\t\t\tthis._sizeChanged = false;\r\n\t\t}\r\n\t\treturn this._size.clone();\r\n\t},\r\n\r\n\t// @method getPixelBounds(): Bounds\r\n\t// Returns the bounds of the current map view in projected pixel\r\n\t// coordinates (sometimes useful in layer and overlay implementations).\r\n\tgetPixelBounds: function (center, zoom) {\r\n\t\tvar topLeftPoint = this._getTopLeftPoint(center, zoom);\r\n\t\treturn new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));\r\n\t},\r\n\r\n\t// TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to\r\n\t// the map pane? \"left point of the map layer\" can be confusing, specially\r\n\t// since there can be negative offsets.\r\n\t// @method getPixelOrigin(): Point\r\n\t// Returns the projected pixel coordinates of the top left point of\r\n\t// the map layer (useful in custom layer and overlay implementations).\r\n\tgetPixelOrigin: function () {\r\n\t\tthis._checkIfLoaded();\r\n\t\treturn this._pixelOrigin;\r\n\t},\r\n\r\n\t// @method getPixelWorldBounds(zoom?: Number): Bounds\r\n\t// Returns the world's bounds in pixel coordinates for zoom level `zoom`.\r\n\t// If `zoom` is omitted, the map's current zoom level is used.\r\n\tgetPixelWorldBounds: function (zoom) {\r\n\t\treturn this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method getPane(pane: String|HTMLElement): HTMLElement\r\n\t// Returns a [map pane](#map-pane), given its name or its HTML element (its identity).\r\n\tgetPane: function (pane) {\r\n\t\treturn typeof pane === 'string' ? this._panes[pane] : pane;\r\n\t},\r\n\r\n\t// @method getPanes(): Object\r\n\t// Returns a plain object containing the names of all [panes](#map-pane) as keys and\r\n\t// the panes as values.\r\n\tgetPanes: function () {\r\n\t\treturn this._panes;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTML element that contains the map.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\r\n\t// @section Conversion Methods\r\n\r\n\t// @method getZoomScale(toZoom: Number, fromZoom: Number): Number\r\n\t// Returns the scale factor to be applied to a map transition from zoom level\r\n\t// `fromZoom` to `toZoom`. Used internally to help with zoom animations.\r\n\tgetZoomScale: function (toZoom, fromZoom) {\r\n\t\t// TODO replace with universal implementation after refactoring projections\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\treturn crs.scale(toZoom) / crs.scale(fromZoom);\r\n\t},\r\n\r\n\t// @method getScaleZoom(scale: Number, fromZoom: Number): Number\r\n\t// Returns the zoom level that the map would end up at, if it is at `fromZoom`\r\n\t// level and everything is scaled by a factor of `scale`. Inverse of\r\n\t// [`getZoomScale`](#map-getZoomScale).\r\n\tgetScaleZoom: function (scale, fromZoom) {\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\tvar zoom = crs.zoom(scale * crs.scale(fromZoom));\r\n\t\treturn isNaN(zoom) ? Infinity : zoom;\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng, zoom: Number): Point\r\n\t// Projects a geographical coordinate `LatLng` according to the projection\r\n\t// of the map's CRS, then scales it according to `zoom` and the CRS's\r\n\t// `Transformation`. The result is pixel coordinate relative to\r\n\t// the CRS origin.\r\n\tproject: function (latlng, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.latLngToPoint(toLatLng(latlng), zoom);\r\n\t},\r\n\r\n\t// @method unproject(point: Point, zoom: Number): LatLng\r\n\t// Inverse of [`project`](#map-project).\r\n\tunproject: function (point, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.pointToLatLng(toPoint(point), zoom);\r\n\t},\r\n\r\n\t// @method layerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding geographical coordinate (for the current zoom level).\r\n\tlayerPointToLatLng: function (point) {\r\n\t\tvar projectedPoint = toPoint(point).add(this.getPixelOrigin());\r\n\t\treturn this.unproject(projectedPoint);\r\n\t},\r\n\r\n\t// @method latLngToLayerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the [origin pixel](#map-getpixelorigin).\r\n\tlatLngToLayerPoint: function (latlng) {\r\n\t\tvar projectedPoint = this.project(toLatLng(latlng))._round();\r\n\t\treturn projectedPoint._subtract(this.getPixelOrigin());\r\n\t},\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where `lat` and `lng` has been wrapped according to the\r\n\t// map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the\r\n\t// CRS's bounds.\r\n\t// By default this means longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees.\r\n\twrapLatLng: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLng(toLatLng(latlng));\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring that\r\n\t// its center is within the CRS's bounds.\r\n\t// By default this means the center longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees, and the majority of the bounds\r\n\t// overlaps the CRS's bounds.\r\n\twrapLatLngBounds: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates according to\r\n\t// the map's CRS. By default this measures distance in meters.\r\n\tdistance: function (latlng1, latlng2) {\r\n\t\treturn this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));\r\n\t},\r\n\r\n\t// @method containerPointToLayerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the map container, returns the corresponding\r\n\t// pixel coordinate relative to the [origin pixel](#map-getpixelorigin).\r\n\tcontainerPointToLayerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method layerPointToContainerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding pixel coordinate relative to the map container.\r\n\tlayerPointToContainerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).add(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method containerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the map container, returns\r\n\t// the corresponding geographical coordinate (for the current zoom level).\r\n\tcontainerPointToLatLng: function (point) {\r\n\t\tvar layerPoint = this.containerPointToLayerPoint(toPoint(point));\r\n\t\treturn this.layerPointToLatLng(layerPoint);\r\n\t},\r\n\r\n\t// @method latLngToContainerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the map container.\r\n\tlatLngToContainerPoint: function (latlng) {\r\n\t\treturn this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));\r\n\t},\r\n\r\n\t// @method mouseEventToContainerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to the\r\n\t// map container where the event took place.\r\n\tmouseEventToContainerPoint: function (e) {\r\n\t\treturn DomEvent.getMousePosition(e, this._container);\r\n\t},\r\n\r\n\t// @method mouseEventToLayerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to\r\n\t// the [origin pixel](#map-getpixelorigin) where the event took place.\r\n\tmouseEventToLayerPoint: function (e) {\r\n\t\treturn this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));\r\n\t},\r\n\r\n\t// @method mouseEventToLatLng(ev: MouseEvent): LatLng\r\n\t// Given a MouseEvent object, returns geographical coordinate where the\r\n\t// event took place.\r\n\tmouseEventToLatLng: function (e) { // (MouseEvent)\r\n\t\treturn this.layerPointToLatLng(this.mouseEventToLayerPoint(e));\r\n\t},\r\n\r\n\r\n\t// map initialization methods\r\n\r\n\t_initContainer: function (id) {\r\n\t\tvar container = this._container = DomUtil.get(id);\r\n\r\n\t\tif (!container) {\r\n\t\t\tthrow new Error('Map container not found.');\r\n\t\t} else if (container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is already initialized.');\r\n\t\t}\r\n\r\n\t\tDomEvent.on(container, 'scroll', this._onScroll, this);\r\n\t\tthis._containerId = Util.stamp(container);\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar container = this._container;\r\n\r\n\t\tthis._fadeAnimated = this.options.fadeAnimation && Browser.any3d;\r\n\r\n\t\tDomUtil.addClass(container, 'leaflet-container' +\r\n\t\t\t(Browser.touch ? ' leaflet-touch' : '') +\r\n\t\t\t(Browser.retina ? ' leaflet-retina' : '') +\r\n\t\t\t(Browser.ielt9 ? ' leaflet-oldie' : '') +\r\n\t\t\t(Browser.safari ? ' leaflet-safari' : '') +\r\n\t\t\t(this._fadeAnimated ? ' leaflet-fade-anim' : ''));\r\n\r\n\t\tvar position = DomUtil.getStyle(container, 'position');\r\n\r\n\t\tif (position !== 'absolute' && position !== 'relative' && position !== 'fixed' && position !== 'sticky') {\r\n\t\t\tcontainer.style.position = 'relative';\r\n\t\t}\r\n\r\n\t\tthis._initPanes();\r\n\r\n\t\tif (this._initControlPos) {\r\n\t\t\tthis._initControlPos();\r\n\t\t}\r\n\t},\r\n\r\n\t_initPanes: function () {\r\n\t\tvar panes = this._panes = {};\r\n\t\tthis._paneRenderers = {};\r\n\r\n\t\t// @section\r\n\t\t//\r\n\t\t// Panes are DOM elements used to control the ordering of layers on the map. You\r\n\t\t// can access panes with [`map.getPane`](#map-getpane) or\r\n\t\t// [`map.getPanes`](#map-getpanes) methods. New panes can be created with the\r\n\t\t// [`map.createPane`](#map-createpane) method.\r\n\t\t//\r\n\t\t// Every map has the following default panes that differ only in zIndex.\r\n\t\t//\r\n\t\t// @pane mapPane: HTMLElement = 'auto'\r\n\t\t// Pane that contains all other map panes\r\n\r\n\t\tthis._mapPane = this.createPane('mapPane', this._container);\r\n\t\tDomUtil.setPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\t// @pane tilePane: HTMLElement = 200\r\n\t\t// Pane for `GridLayer`s and `TileLayer`s\r\n\t\tthis.createPane('tilePane');\r\n\t\t// @pane overlayPane: HTMLElement = 400\r\n\t\t// Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s\r\n\t\tthis.createPane('overlayPane');\r\n\t\t// @pane shadowPane: HTMLElement = 500\r\n\t\t// Pane for overlay shadows (e.g. `Marker` shadows)\r\n\t\tthis.createPane('shadowPane');\r\n\t\t// @pane markerPane: HTMLElement = 600\r\n\t\t// Pane for `Icon`s of `Marker`s\r\n\t\tthis.createPane('markerPane');\r\n\t\t// @pane tooltipPane: HTMLElement = 650\r\n\t\t// Pane for `Tooltip`s.\r\n\t\tthis.createPane('tooltipPane');\r\n\t\t// @pane popupPane: HTMLElement = 700\r\n\t\t// Pane for `Popup`s.\r\n\t\tthis.createPane('popupPane');\r\n\r\n\t\tif (!this.options.markerZoomAnimation) {\r\n\t\t\tDomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');\r\n\t\t\tDomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');\r\n\t\t}\r\n\t},\r\n\r\n\r\n\t// private methods that modify map state\r\n\r\n\t// @section Map state change events\r\n\t_resetView: function (center, zoom, noMoveStart) {\r\n\t\tDomUtil.setPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\tvar loading = !this._loaded;\r\n\t\tthis._loaded = true;\r\n\t\tzoom = this._limitZoom(zoom);\r\n\r\n\t\tthis.fire('viewprereset');\r\n\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\t\tthis\r\n\t\t\t._moveStart(zoomChanged, noMoveStart)\r\n\t\t\t._move(center, zoom)\r\n\t\t\t._moveEnd(zoomChanged);\r\n\r\n\t\t// @event viewreset: Event\r\n\t\t// Fired when the map needs to redraw its content (this usually happens\r\n\t\t// on map zoom or load). Very useful for creating custom overlays.\r\n\t\tthis.fire('viewreset');\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the map is initialized (when its center and zoom are set\r\n\t\t// for the first time).\r\n\t\tif (loading) {\r\n\t\t\tthis.fire('load');\r\n\t\t}\r\n\t},\r\n\r\n\t_moveStart: function (zoomChanged, noMoveStart) {\r\n\t\t// @event zoomstart: Event\r\n\t\t// Fired when the map zoom is about to change (e.g. before zoom animation).\r\n\t\t// @event movestart: Event\r\n\t\t// Fired when the view of the map starts changing (e.g. user starts dragging the map).\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomstart');\r\n\t\t}\r\n\t\tif (!noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_move: function (center, zoom, data, supressEvent) {\r\n\t\tif (zoom === undefined) {\r\n\t\t\tzoom = this._zoom;\r\n\t\t}\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\r\n\t\tthis._zoom = zoom;\r\n\t\tthis._lastCenter = center;\r\n\t\tthis._pixelOrigin = this._getNewPixelOrigin(center);\r\n\r\n\t\tif (!supressEvent) {\r\n\t\t\t// @event zoom: Event\r\n\t\t\t// Fired repeatedly during any change in zoom level,\r\n\t\t\t// including zoom and fly animations.\r\n\t\t\tif (zoomChanged || (data && data.pinch)) {\t// Always fire 'zoom' if pinching because #3530\r\n\t\t\t\tthis.fire('zoom', data);\r\n\t\t\t}\r\n\r\n\t\t\t// @event move: Event\r\n\t\t\t// Fired repeatedly during any movement of the map,\r\n\t\t\t// including pan and fly animations.\r\n\t\t\tthis.fire('move', data);\r\n\t\t} else if (data && data.pinch) {\t// Always fire 'zoom' if pinching because #3530\r\n\t\t\tthis.fire('zoom', data);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_moveEnd: function (zoomChanged) {\r\n\t\t// @event zoomend: Event\r\n\t\t// Fired when the map zoom changed, after any animations.\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomend');\r\n\t\t}\r\n\r\n\t\t// @event moveend: Event\r\n\t\t// Fired when the center of the map stops changing\r\n\t\t// (e.g. user stopped dragging the map or after non-centered zoom).\r\n\t\treturn this.fire('moveend');\r\n\t},\r\n\r\n\t_stop: function () {\r\n\t\tUtil.cancelAnimFrame(this._flyToFrame);\r\n\t\tif (this._panAnim) {\r\n\t\t\tthis._panAnim.stop();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_rawPanBy: function (offset) {\r\n\t\tDomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));\r\n\t},\r\n\r\n\t_getZoomSpan: function () {\r\n\t\treturn this.getMaxZoom() - this.getMinZoom();\r\n\t},\r\n\r\n\t_panInsideMaxBounds: function () {\r\n\t\tif (!this._enforcingBounds) {\r\n\t\t\tthis.panInsideBounds(this.options.maxBounds);\r\n\t\t}\r\n\t},\r\n\r\n\t_checkIfLoaded: function () {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthrow new Error('Set map center and zoom first.');\r\n\t\t}\r\n\t},\r\n\r\n\t// DOM event handling\r\n\r\n\t// @section Interaction events\r\n\t_initEvents: function (remove) {\r\n\t\tthis._targets = {};\r\n\t\tthis._targets[Util.stamp(this._container)] = this;\r\n\r\n\t\tvar onOff = remove ? DomEvent.off : DomEvent.on;\r\n\r\n\t\t// @event click: MouseEvent\r\n\t\t// Fired when the user clicks (or taps) the map.\r\n\t\t// @event dblclick: MouseEvent\r\n\t\t// Fired when the user double-clicks (or double-taps) the map.\r\n\t\t// @event mousedown: MouseEvent\r\n\t\t// Fired when the user pushes the mouse button on the map.\r\n\t\t// @event mouseup: MouseEvent\r\n\t\t// Fired when the user releases the mouse button on the map.\r\n\t\t// @event mouseover: MouseEvent\r\n\t\t// Fired when the mouse enters the map.\r\n\t\t// @event mouseout: MouseEvent\r\n\t\t// Fired when the mouse leaves the map.\r\n\t\t// @event mousemove: MouseEvent\r\n\t\t// Fired while the mouse moves over the map.\r\n\t\t// @event contextmenu: MouseEvent\r\n\t\t// Fired when the user pushes the right mouse button on the map, prevents\r\n\t\t// default browser context menu from showing if there are listeners on\r\n\t\t// this event. Also fired on mobile when the user holds a single touch\r\n\t\t// for a second (also called long press).\r\n\t\t// @event keypress: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard that produces a character value while the map is focused.\r\n\t\t// @event keydown: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,\r\n\t\t// the `keydown` event is fired for keys that produce a character value and for keys\r\n\t\t// that do not produce a character value.\r\n\t\t// @event keyup: KeyboardEvent\r\n\t\t// Fired when the user releases a key from the keyboard while the map is focused.\r\n\t\tonOff(this._container, 'click dblclick mousedown mouseup ' +\r\n\t\t\t'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);\r\n\r\n\t\tif (this.options.trackResize) {\r\n\t\t\tonOff(window, 'resize', this._onResize, this);\r\n\t\t}\r\n\r\n\t\tif (Browser.any3d && this.options.transform3DLimit) {\r\n\t\t\t(remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);\r\n\t\t}\r\n\t},\r\n\r\n\t_onResize: function () {\r\n\t\tUtil.cancelAnimFrame(this._resizeRequest);\r\n\t\tthis._resizeRequest = Util.requestAnimFrame(\r\n\t\t        function () { this.invalidateSize({debounceMoveend: true}); }, this);\r\n\t},\r\n\r\n\t_onScroll: function () {\r\n\t\tthis._container.scrollTop  = 0;\r\n\t\tthis._container.scrollLeft = 0;\r\n\t},\r\n\r\n\t_onMoveEnd: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\tif (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {\r\n\t\t\t// https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have\r\n\t\t\t// a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/\r\n\t\t\tthis._resetView(this.getCenter(), this.getZoom());\r\n\t\t}\r\n\t},\r\n\r\n\t_findEventTargets: function (e, type) {\r\n\t\tvar targets = [],\r\n\t\t    target,\r\n\t\t    isHover = type === 'mouseout' || type === 'mouseover',\r\n\t\t    src = e.target || e.srcElement,\r\n\t\t    dragging = false;\r\n\r\n\t\twhile (src) {\r\n\t\t\ttarget = this._targets[Util.stamp(src)];\r\n\t\t\tif (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {\r\n\t\t\t\t// Prevent firing click after you just dragged an object.\r\n\t\t\t\tdragging = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (target && target.listens(type, true)) {\r\n\t\t\t\tif (isHover && !DomEvent.isExternalTarget(src, e)) { break; }\r\n\t\t\t\ttargets.push(target);\r\n\t\t\t\tif (isHover) { break; }\r\n\t\t\t}\r\n\t\t\tif (src === this._container) { break; }\r\n\t\t\tsrc = src.parentNode;\r\n\t\t}\r\n\t\tif (!targets.length && !dragging && !isHover && this.listens(type, true)) {\r\n\t\t\ttargets = [this];\r\n\t\t}\r\n\t\treturn targets;\r\n\t},\r\n\r\n\t_isClickDisabled: function (el) {\r\n\t\twhile (el && el !== this._container) {\r\n\t\t\tif (el['_leaflet_disable_click']) { return true; }\r\n\t\t\tel = el.parentNode;\r\n\t\t}\r\n\t},\r\n\r\n\t_handleDOMEvent: function (e) {\r\n\t\tvar el = (e.target || e.srcElement);\r\n\t\tif (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar type = e.type;\r\n\r\n\t\tif (type === 'mousedown') {\r\n\t\t\t// prevents outline when clicking on keyboard-focusable element\r\n\t\t\tDomUtil.preventOutline(el);\r\n\t\t}\r\n\r\n\t\tthis._fireDOMEvent(e, type);\r\n\t},\r\n\r\n\t_mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],\r\n\r\n\t_fireDOMEvent: function (e, type, canvasTargets) {\r\n\r\n\t\tif (e.type === 'click') {\r\n\t\t\t// Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).\r\n\t\t\t// @event preclick: MouseEvent\r\n\t\t\t// Fired before mouse click on the map (sometimes useful when you\r\n\t\t\t// want something to happen on click before any existing click\r\n\t\t\t// handlers start running).\r\n\t\t\tvar synth = Util.extend({}, e);\r\n\t\t\tsynth.type = 'preclick';\r\n\t\t\tthis._fireDOMEvent(synth, synth.type, canvasTargets);\r\n\t\t}\r\n\r\n\t\t// Find the layer the event is propagating from and its parents.\r\n\t\tvar targets = this._findEventTargets(e, type);\r\n\r\n\t\tif (canvasTargets) {\r\n\t\t\tvar filtered = []; // pick only targets with listeners\r\n\t\t\tfor (var i = 0; i < canvasTargets.length; i++) {\r\n\t\t\t\tif (canvasTargets[i].listens(type, true)) {\r\n\t\t\t\t\tfiltered.push(canvasTargets[i]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttargets = filtered.concat(targets);\r\n\t\t}\r\n\r\n\t\tif (!targets.length) { return; }\r\n\r\n\t\tif (type === 'contextmenu') {\r\n\t\t\tDomEvent.preventDefault(e);\r\n\t\t}\r\n\r\n\t\tvar target = targets[0];\r\n\t\tvar data = {\r\n\t\t\toriginalEvent: e\r\n\t\t};\r\n\r\n\t\tif (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {\r\n\t\t\tvar isMarker = target.getLatLng && (!target._radius || target._radius <= 10);\r\n\t\t\tdata.containerPoint = isMarker ?\r\n\t\t\t\tthis.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);\r\n\t\t\tdata.layerPoint = this.containerPointToLayerPoint(data.containerPoint);\r\n\t\t\tdata.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);\r\n\t\t}\r\n\r\n\t\tfor (i = 0; i < targets.length; i++) {\r\n\t\t\ttargets[i].fire(type, data, true);\r\n\t\t\tif (data.originalEvent._stopped ||\r\n\t\t\t\t(targets[i].options.bubblingMouseEvents === false && Util.indexOf(this._mouseEvents, type) !== -1)) { return; }\r\n\t\t}\r\n\t},\r\n\r\n\t_draggableMoved: function (obj) {\r\n\t\tobj = obj.dragging && obj.dragging.enabled() ? obj : this;\r\n\t\treturn (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());\r\n\t},\r\n\r\n\t_clearHandlers: function () {\r\n\t\tfor (var i = 0, len = this._handlers.length; i < len; i++) {\r\n\t\t\tthis._handlers[i].disable();\r\n\t\t}\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method whenReady(fn: Function, context?: Object): this\r\n\t// Runs the given function `fn` when the map gets initialized with\r\n\t// a view (center and zoom) and at least one layer, or immediately\r\n\t// if it's already initialized, optionally passing a function context.\r\n\twhenReady: function (callback, context) {\r\n\t\tif (this._loaded) {\r\n\t\t\tcallback.call(context || this, {target: this});\r\n\t\t} else {\r\n\t\t\tthis.on('load', callback, context);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\r\n\t// private methods for getting map state\r\n\r\n\t_getMapPanePos: function () {\r\n\t\treturn DomUtil.getPosition(this._mapPane) || new Point(0, 0);\r\n\t},\r\n\r\n\t_moved: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\treturn pos && !pos.equals([0, 0]);\r\n\t},\r\n\r\n\t_getTopLeftPoint: function (center, zoom) {\r\n\t\tvar pixelOrigin = center && zoom !== undefined ?\r\n\t\t\tthis._getNewPixelOrigin(center, zoom) :\r\n\t\t\tthis.getPixelOrigin();\r\n\t\treturn pixelOrigin.subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t_getNewPixelOrigin: function (center, zoom) {\r\n\t\tvar viewHalf = this.getSize()._divideBy(2);\r\n\t\treturn this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();\r\n\t},\r\n\r\n\t_latLngToNewLayerPoint: function (latlng, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn this.project(latlng, zoom)._subtract(topLeft);\r\n\t},\r\n\r\n\t_latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn toBounds([\r\n\t\t\tthis.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)\r\n\t\t]);\r\n\t},\r\n\r\n\t// layer point of the current center\r\n\t_getCenterLayerPoint: function () {\r\n\t\treturn this.containerPointToLayerPoint(this.getSize()._divideBy(2));\r\n\t},\r\n\r\n\t// offset of the specified place to the current center in pixels\r\n\t_getCenterOffset: function (latlng) {\r\n\t\treturn this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// adjust center for view to get inside bounds\r\n\t_limitCenter: function (center, zoom, bounds) {\r\n\r\n\t\tif (!bounds) { return center; }\r\n\r\n\t\tvar centerPoint = this.project(center, zoom),\r\n\t\t    viewHalf = this.getSize().divideBy(2),\r\n\t\t    viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),\r\n\t\t    offset = this._getBoundsOffset(viewBounds, bounds, zoom);\r\n\r\n\t\t// If offset is less than a pixel, ignore.\r\n\t\t// This prevents unstable projections from getting into\r\n\t\t// an infinite loop of tiny offsets.\r\n\t\tif (Math.abs(offset.x) <= 1 && Math.abs(offset.y) <= 1) {\r\n\t\t\treturn center;\r\n\t\t}\r\n\r\n\t\treturn this.unproject(centerPoint.add(offset), zoom);\r\n\t},\r\n\r\n\t// adjust offset for view to get inside bounds\r\n\t_limitOffset: function (offset, bounds) {\r\n\t\tif (!bounds) { return offset; }\r\n\r\n\t\tvar viewBounds = this.getPixelBounds(),\r\n\t\t    newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));\r\n\r\n\t\treturn offset.add(this._getBoundsOffset(newBounds, bounds));\r\n\t},\r\n\r\n\t// returns offset needed for pxBounds to get inside maxBounds at a specified zoom\r\n\t_getBoundsOffset: function (pxBounds, maxBounds, zoom) {\r\n\t\tvar projectedMaxBounds = toBounds(\r\n\t\t        this.project(maxBounds.getNorthEast(), zoom),\r\n\t\t        this.project(maxBounds.getSouthWest(), zoom)\r\n\t\t    ),\r\n\t\t    minOffset = projectedMaxBounds.min.subtract(pxBounds.min),\r\n\t\t    maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),\r\n\r\n\t\t    dx = this._rebound(minOffset.x, -maxOffset.x),\r\n\t\t    dy = this._rebound(minOffset.y, -maxOffset.y);\r\n\r\n\t\treturn new Point(dx, dy);\r\n\t},\r\n\r\n\t_rebound: function (left, right) {\r\n\t\treturn left + right > 0 ?\r\n\t\t\tMath.round(left - right) / 2 :\r\n\t\t\tMath.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));\r\n\t},\r\n\r\n\t_limitZoom: function (zoom) {\r\n\t\tvar min = this.getMinZoom(),\r\n\t\t    max = this.getMaxZoom(),\r\n\t\t    snap = Browser.any3d ? this.options.zoomSnap : 1;\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / snap) * snap;\r\n\t\t}\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t_onPanTransitionStep: function () {\r\n\t\tthis.fire('move');\r\n\t},\r\n\r\n\t_onPanTransitionEnd: function () {\r\n\t\tDomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');\r\n\t\tthis.fire('moveend');\r\n\t},\r\n\r\n\t_tryAnimatedPan: function (center, options) {\r\n\t\t// difference between the new and current centers in pixels\r\n\t\tvar offset = this._getCenterOffset(center)._trunc();\r\n\r\n\t\t// don't animate too far unless animate: true specified in options\r\n\t\tif ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\tthis.panBy(offset, options);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_createAnimProxy: function () {\r\n\r\n\t\tvar proxy = this._proxy = DomUtil.create('div', 'leaflet-proxy leaflet-zoom-animated');\r\n\t\tthis._panes.mapPane.appendChild(proxy);\r\n\r\n\t\tthis.on('zoomanim', function (e) {\r\n\t\t\tvar prop = DomUtil.TRANSFORM,\r\n\t\t\t    transform = this._proxy.style[prop];\r\n\r\n\t\t\tDomUtil.setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));\r\n\r\n\t\t\t// workaround for case when transform is the same and so transitionend event is not fired\r\n\t\t\tif (transform === this._proxy.style[prop] && this._animatingZoom) {\r\n\t\t\t\tthis._onZoomTransitionEnd();\r\n\t\t\t}\r\n\t\t}, this);\r\n\r\n\t\tthis.on('load moveend', this._animMoveEnd, this);\r\n\r\n\t\tthis._on('unload', this._destroyAnimProxy, this);\r\n\t},\r\n\r\n\t_destroyAnimProxy: function () {\r\n\t\tDomUtil.remove(this._proxy);\r\n\t\tthis.off('load moveend', this._animMoveEnd, this);\r\n\t\tdelete this._proxy;\r\n\t},\r\n\r\n\t_animMoveEnd: function () {\r\n\t\tvar c = this.getCenter(),\r\n\t\t    z = this.getZoom();\r\n\t\tDomUtil.setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));\r\n\t},\r\n\r\n\t_catchTransitionEnd: function (e) {\r\n\t\tif (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {\r\n\t\t\tthis._onZoomTransitionEnd();\r\n\t\t}\r\n\t},\r\n\r\n\t_nothingToAnimate: function () {\r\n\t\treturn !this._container.getElementsByClassName('leaflet-zoom-animated').length;\r\n\t},\r\n\r\n\t_tryAnimatedZoom: function (center, zoom, options) {\r\n\r\n\t\tif (this._animatingZoom) { return true; }\r\n\r\n\t\toptions = options || {};\r\n\r\n\t\t// don't animate if disabled, not supported or zoom difference is too large\r\n\t\tif (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||\r\n\t\t        Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }\r\n\r\n\t\t// offset is the pixel coords of the zoom origin relative to the current center\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t    offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);\r\n\r\n\t\t// don't animate if the zoom origin isn't within one screen from the current center, unless forced\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\tUtil.requestAnimFrame(function () {\r\n\t\t\tthis\r\n\t\t\t    ._moveStart(true, options.noMoveStart || false)\r\n\t\t\t    ._animateZoom(center, zoom, true);\r\n\t\t}, this);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_animateZoom: function (center, zoom, startAnim, noUpdate) {\r\n\t\tif (!this._mapPane) { return; }\r\n\r\n\t\tif (startAnim) {\r\n\t\t\tthis._animatingZoom = true;\r\n\r\n\t\t\t// remember what center/zoom to set after animation\r\n\t\t\tthis._animateToCenter = center;\r\n\t\t\tthis._animateToZoom = zoom;\r\n\r\n\t\t\tDomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\t// @section Other Events\r\n\t\t// @event zoomanim: ZoomAnimEvent\r\n\t\t// Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.\r\n\t\tthis.fire('zoomanim', {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom,\r\n\t\t\tnoUpdate: noUpdate\r\n\t\t});\r\n\r\n\t\tif (!this._tempFireZoomEvent) {\r\n\t\t\tthis._tempFireZoomEvent = this._zoom !== this._animateToZoom;\r\n\t\t}\r\n\r\n\t\tthis._move(this._animateToCenter, this._animateToZoom, undefined, true);\r\n\r\n\t\t// Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693\r\n\t\tsetTimeout(Util.bind(this._onZoomTransitionEnd, this), 250);\r\n\t},\r\n\r\n\t_onZoomTransitionEnd: function () {\r\n\t\tif (!this._animatingZoom) { return; }\r\n\r\n\t\tif (this._mapPane) {\r\n\t\t\tDomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\tthis._animatingZoom = false;\r\n\r\n\t\tthis._move(this._animateToCenter, this._animateToZoom, undefined, true);\r\n\r\n\t\tif (this._tempFireZoomEvent) {\r\n\t\t\tthis.fire('zoom');\r\n\t\t}\r\n\t\tdelete this._tempFireZoomEvent;\r\n\r\n\t\tthis.fire('move');\r\n\r\n\t\tthis._moveEnd(true);\r\n\t}\r\n});\r\n\r\n// @section\r\n\r\n// @factory L.map(id: String, options?: Map options)\r\n// Instantiates a map object given the DOM ID of a `<div>` element\r\n// and optionally an object literal with `Map options`.\r\n//\r\n// @alternative\r\n// @factory L.map(el: HTMLElement, options?: Map options)\r\n// Instantiates a map object given an instance of a `<div>` HTML element\r\n// and optionally an object literal with `Map options`.\r\nexport function createMap(id, options) {\r\n\treturn new Map(id, options);\r\n}\r\n", "\r\nimport {Class} from '../core/Class';\r\nimport {Map} from '../map/Map';\r\nimport * as Util from '../core/Util';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class Control\r\n * @aka L.Control\r\n * @inherits Class\r\n *\r\n * L.Control is a base class for implementing map controls. Handles positioning.\r\n * All other controls extend from this class.\r\n */\r\n\r\nexport var Control = Class.extend({\r\n\t// @section\r\n\t// @aka Control Options\r\n\toptions: {\r\n\t\t// @option position: String = 'topright'\r\n\t\t// The position of the control (one of the map corners). Possible values are `'topleft'`,\r\n\t\t// `'topright'`, `'bottomleft'` or `'bottomright'`\r\n\t\tposition: 'topright'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tUtil.setOptions(this, options);\r\n\t},\r\n\r\n\t/* @section\r\n\t * Classes extending L.Control will inherit the following methods:\r\n\t *\r\n\t * @method getPosition: string\r\n\t * Returns the position of the control.\r\n\t */\r\n\tgetPosition: function () {\r\n\t\treturn this.options.position;\r\n\t},\r\n\r\n\t// @method setPosition(position: string): this\r\n\t// Sets the position of the control.\r\n\tsetPosition: function (position) {\r\n\t\tvar map = this._map;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.removeControl(this);\r\n\t\t}\r\n\r\n\t\tthis.options.position = position;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.addControl(this);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTMLElement that contains the control.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method addTo(map: Map): this\r\n\t// Adds the control to the given map.\r\n\taddTo: function (map) {\r\n\t\tthis.remove();\r\n\t\tthis._map = map;\r\n\r\n\t\tvar container = this._container = this.onAdd(map),\r\n\t\t    pos = this.getPosition(),\r\n\t\t    corner = map._controlCorners[pos];\r\n\r\n\t\tDomUtil.addClass(container, 'leaflet-control');\r\n\r\n\t\tif (pos.indexOf('bottom') !== -1) {\r\n\t\t\tcorner.insertBefore(container, corner.firstChild);\r\n\t\t} else {\r\n\t\t\tcorner.appendChild(container);\r\n\t\t}\r\n\r\n\t\tthis._map.on('unload', this.remove, this);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove: this\r\n\t// Removes the control from the map it is currently active on.\r\n\tremove: function () {\r\n\t\tif (!this._map) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tDomUtil.remove(this._container);\r\n\r\n\t\tif (this.onRemove) {\r\n\t\t\tthis.onRemove(this._map);\r\n\t\t}\r\n\r\n\t\tthis._map.off('unload', this.remove, this);\r\n\t\tthis._map = null;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_refocusOnMap: function (e) {\r\n\t\t// if map exists and event is not a keyboard event\r\n\t\tif (this._map && e && e.screenX > 0 && e.screenY > 0) {\r\n\t\t\tthis._map.getContainer().focus();\r\n\t\t}\r\n\t}\r\n});\r\n\r\nexport var control = function (options) {\r\n\treturn new Control(options);\r\n};\r\n\r\n/* @section Extension methods\r\n * @uninheritable\r\n *\r\n * Every control should extend from `L.Control` and (re-)implement the following methods.\r\n *\r\n * @method onAdd(map: Map): HTMLElement\r\n * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).\r\n *\r\n * @method onRemove(map: Map)\r\n * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).\r\n */\r\n\r\n/* @namespace Map\r\n * @section Methods for Layers and Controls\r\n */\r\nMap.include({\r\n\t// @method addControl(control: Control): this\r\n\t// Adds the given control to the map\r\n\taddControl: function (control) {\r\n\t\tcontrol.addTo(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeControl(control: Control): this\r\n\t// Removes the given control from the map\r\n\tremoveControl: function (control) {\r\n\t\tcontrol.remove();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initControlPos: function () {\r\n\t\tvar corners = this._controlCorners = {},\r\n\t\t    l = 'leaflet-',\r\n\t\t    container = this._controlContainer =\r\n\t\t            DomUtil.create('div', l + 'control-container', this._container);\r\n\r\n\t\tfunction createCorner(vSide, hSide) {\r\n\t\t\tvar className = l + vSide + ' ' + l + hSide;\r\n\r\n\t\t\tcorners[vSide + hSide] = DomUtil.create('div', className, container);\r\n\t\t}\r\n\r\n\t\tcreateCorner('top', 'left');\r\n\t\tcreateCorner('top', 'right');\r\n\t\tcreateCorner('bottom', 'left');\r\n\t\tcreateCorner('bottom', 'right');\r\n\t},\r\n\r\n\t_clearControlPos: function () {\r\n\t\tfor (var i in this._controlCorners) {\r\n\t\t\tDomUtil.remove(this._controlCorners[i]);\r\n\t\t}\r\n\t\tDomUtil.remove(this._controlContainer);\r\n\t\tdelete this._controlCorners;\r\n\t\tdelete this._controlContainer;\r\n\t}\r\n});\r\n", "\r\nimport {Control} from './Control';\r\nimport * as Util from '../core/Util';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class Control.Layers\r\n * @aka L.Control.Layers\r\n * @inherits Control\r\n *\r\n * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](https://leafletjs.com/examples/layers-control/)). Extends `Control`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var baseLayers = {\r\n * \t\"Mapbox\": mapbox,\r\n * \t\"OpenStreetMap\": osm\r\n * };\r\n *\r\n * var overlays = {\r\n * \t\"Marker\": marker,\r\n * \t\"Roads\": roadsLayer\r\n * };\r\n *\r\n * L.control.layers(baseLayers, overlays).addTo(map);\r\n * ```\r\n *\r\n * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:\r\n *\r\n * ```js\r\n * {\r\n *     \"<someName1>\": layer1,\r\n *     \"<someName2>\": layer2\r\n * }\r\n * ```\r\n *\r\n * The layer names can contain HTML, which allows you to add additional styling to the items:\r\n *\r\n * ```js\r\n * {\"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>\": myLayer}\r\n * ```\r\n */\r\n\r\nexport var Layers = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Layers options\r\n\toptions: {\r\n\t\t// @option collapsed: Boolean = true\r\n\t\t// If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.\r\n\t\tcollapsed: true,\r\n\t\tposition: 'topright',\r\n\r\n\t\t// @option autoZIndex: Boolean = true\r\n\t\t// If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.\r\n\t\tautoZIndex: true,\r\n\r\n\t\t// @option hideSingleBase: Boolean = false\r\n\t\t// If `true`, the base layers in the control will be hidden when there is only one.\r\n\t\thideSingleBase: false,\r\n\r\n\t\t// @option sortLayers: Boolean = false\r\n\t\t// Whether to sort the layers. When `false`, layers will keep the order\r\n\t\t// in which they were added to the control.\r\n\t\tsortLayers: false,\r\n\r\n\t\t// @option sortFunction: Function = *\r\n\t\t// A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)\r\n\t\t// that will be used for sorting the layers, when `sortLayers` is `true`.\r\n\t\t// The function receives both the `L.Layer` instances and their names, as in\r\n\t\t// `sortFunction(layerA, layerB, nameA, nameB)`.\r\n\t\t// By default, it sorts layers alphabetically by their name.\r\n\t\tsortFunction: function (layerA, layerB, nameA, nameB) {\r\n\t\t\treturn nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);\r\n\t\t}\r\n\t},\r\n\r\n\tinitialize: function (baseLayers, overlays, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tthis._layers = [];\r\n\t\tthis._lastZIndex = 0;\r\n\t\tthis._handlingClick = false;\r\n\t\tthis._preventClick = false;\r\n\r\n\t\tfor (var i in baseLayers) {\r\n\t\t\tthis._addLayer(baseLayers[i], i);\r\n\t\t}\r\n\r\n\t\tfor (i in overlays) {\r\n\t\t\tthis._addLayer(overlays[i], i, true);\r\n\t\t}\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._initLayout();\r\n\t\tthis._update();\r\n\r\n\t\tthis._map = map;\r\n\t\tmap.on('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\taddTo: function (map) {\r\n\t\tControl.prototype.addTo.call(this, map);\r\n\t\t// Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.\r\n\t\treturn this._expandIfNotCollapsed();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tthis._map.off('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.off('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addBaseLayer(layer: Layer, name: String): this\r\n\t// Adds a base layer (radio button entry) with the given name to the control.\r\n\taddBaseLayer: function (layer, name) {\r\n\t\tthis._addLayer(layer, name);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method addOverlay(layer: Layer, name: String): this\r\n\t// Adds an overlay (checkbox entry) with the given name to the control.\r\n\taddOverlay: function (layer, name) {\r\n\t\tthis._addLayer(layer, name, true);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Remove the given layer from the control.\r\n\tremoveLayer: function (layer) {\r\n\t\tlayer.off('add remove', this._onLayerChange, this);\r\n\r\n\t\tvar obj = this._getLayer(Util.stamp(layer));\r\n\t\tif (obj) {\r\n\t\t\tthis._layers.splice(this._layers.indexOf(obj), 1);\r\n\t\t}\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method expand(): this\r\n\t// Expand the control container if collapsed.\r\n\texpand: function () {\r\n\t\tDomUtil.addClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\tthis._section.style.height = null;\r\n\t\tvar acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);\r\n\t\tif (acceptableHeight < this._section.clientHeight) {\r\n\t\t\tDomUtil.addClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t\tthis._section.style.height = acceptableHeight + 'px';\r\n\t\t} else {\r\n\t\t\tDomUtil.removeClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t}\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method collapse(): this\r\n\t// Collapse the control container if expanded.\r\n\tcollapse: function () {\r\n\t\tDomUtil.removeClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar className = 'leaflet-control-layers',\r\n\t\t    container = this._container = DomUtil.create('div', className),\r\n\t\t    collapsed = this.options.collapsed;\r\n\r\n\t\t// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released\r\n\t\tcontainer.setAttribute('aria-haspopup', true);\r\n\r\n\t\tDomEvent.disableClickPropagation(container);\r\n\t\tDomEvent.disableScrollPropagation(container);\r\n\r\n\t\tvar section = this._section = DomUtil.create('section', className + '-list');\r\n\r\n\t\tif (collapsed) {\r\n\t\t\tthis._map.on('click', this.collapse, this);\r\n\r\n\t\t\tDomEvent.on(container, {\r\n\t\t\t\tmouseenter: this._expandSafely,\r\n\t\t\t\tmouseleave: this.collapse\r\n\t\t\t}, this);\r\n\t\t}\r\n\r\n\t\tvar link = this._layersLink = DomUtil.create('a', className + '-toggle', container);\r\n\t\tlink.href = '#';\r\n\t\tlink.title = 'Layers';\r\n\t\tlink.setAttribute('role', 'button');\r\n\r\n\t\tDomEvent.on(link, {\r\n\t\t\tkeydown: function (e) {\r\n\t\t\t\tif (e.keyCode === 13) {\r\n\t\t\t\t\tthis._expandSafely();\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t// Certain screen readers intercept the key event and instead send a click event\r\n\t\t\tclick: function (e) {\r\n\t\t\t\tDomEvent.preventDefault(e);\r\n\t\t\t\tthis._expandSafely();\r\n\t\t\t}\r\n\t\t}, this);\r\n\r\n\t\tif (!collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\r\n\t\tthis._baseLayersList = DomUtil.create('div', className + '-base', section);\r\n\t\tthis._separator = DomUtil.create('div', className + '-separator', section);\r\n\t\tthis._overlaysList = DomUtil.create('div', className + '-overlays', section);\r\n\r\n\t\tcontainer.appendChild(section);\r\n\t},\r\n\r\n\t_getLayer: function (id) {\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\r\n\t\t\tif (this._layers[i] && Util.stamp(this._layers[i].layer) === id) {\r\n\t\t\t\treturn this._layers[i];\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t_addLayer: function (layer, name, overlay) {\r\n\t\tif (this._map) {\r\n\t\t\tlayer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\tthis._layers.push({\r\n\t\t\tlayer: layer,\r\n\t\t\tname: name,\r\n\t\t\toverlay: overlay\r\n\t\t});\r\n\r\n\t\tif (this.options.sortLayers) {\r\n\t\t\tthis._layers.sort(Util.bind(function (a, b) {\r\n\t\t\t\treturn this.options.sortFunction(a.layer, b.layer, a.name, b.name);\r\n\t\t\t}, this));\r\n\t\t}\r\n\r\n\t\tif (this.options.autoZIndex && layer.setZIndex) {\r\n\t\t\tthis._lastZIndex++;\r\n\t\t\tlayer.setZIndex(this._lastZIndex);\r\n\t\t}\r\n\r\n\t\tthis._expandIfNotCollapsed();\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._container) { return this; }\r\n\r\n\t\tDomUtil.empty(this._baseLayersList);\r\n\t\tDomUtil.empty(this._overlaysList);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tvar baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;\r\n\r\n\t\tfor (i = 0; i < this._layers.length; i++) {\r\n\t\t\tobj = this._layers[i];\r\n\t\t\tthis._addItem(obj);\r\n\t\t\toverlaysPresent = overlaysPresent || obj.overlay;\r\n\t\t\tbaseLayersPresent = baseLayersPresent || !obj.overlay;\r\n\t\t\tbaseLayersCount += !obj.overlay ? 1 : 0;\r\n\t\t}\r\n\r\n\t\t// Hide base layers section if there's only one layer.\r\n\t\tif (this.options.hideSingleBase) {\r\n\t\t\tbaseLayersPresent = baseLayersPresent && baseLayersCount > 1;\r\n\t\t\tthis._baseLayersList.style.display = baseLayersPresent ? '' : 'none';\r\n\t\t}\r\n\r\n\t\tthis._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_onLayerChange: function (e) {\r\n\t\tif (!this._handlingClick) {\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\tvar obj = this._getLayer(Util.stamp(e.target));\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Layer events\r\n\t\t// @event baselayerchange: LayersControlEvent\r\n\t\t// Fired when the base layer is changed through the [layers control](#control-layers).\r\n\t\t// @event overlayadd: LayersControlEvent\r\n\t\t// Fired when an overlay is selected through the [layers control](#control-layers).\r\n\t\t// @event overlayremove: LayersControlEvent\r\n\t\t// Fired when an overlay is deselected through the [layers control](#control-layers).\r\n\t\t// @namespace Control.Layers\r\n\t\tvar type = obj.overlay ?\r\n\t\t\t(e.type === 'add' ? 'overlayadd' : 'overlayremove') :\r\n\t\t\t(e.type === 'add' ? 'baselayerchange' : null);\r\n\r\n\t\tif (type) {\r\n\t\t\tthis._map.fire(type, obj);\r\n\t\t}\r\n\t},\r\n\r\n\t// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)\r\n\t_createRadioElement: function (name, checked) {\r\n\r\n\t\tvar radioHtml = '<input type=\"radio\" class=\"leaflet-control-layers-selector\" name=\"' +\r\n\t\t\t\tname + '\"' + (checked ? ' checked=\"checked\"' : '') + '/>';\r\n\r\n\t\tvar radioFragment = document.createElement('div');\r\n\t\tradioFragment.innerHTML = radioHtml;\r\n\r\n\t\treturn radioFragment.firstChild;\r\n\t},\r\n\r\n\t_addItem: function (obj) {\r\n\t\tvar label = document.createElement('label'),\r\n\t\t    checked = this._map.hasLayer(obj.layer),\r\n\t\t    input;\r\n\r\n\t\tif (obj.overlay) {\r\n\t\t\tinput = document.createElement('input');\r\n\t\t\tinput.type = 'checkbox';\r\n\t\t\tinput.className = 'leaflet-control-layers-selector';\r\n\t\t\tinput.defaultChecked = checked;\r\n\t\t} else {\r\n\t\t\tinput = this._createRadioElement('leaflet-base-layers_' + Util.stamp(this), checked);\r\n\t\t}\r\n\r\n\t\tthis._layerControlInputs.push(input);\r\n\t\tinput.layerId = Util.stamp(obj.layer);\r\n\r\n\t\tDomEvent.on(input, 'click', this._onInputClick, this);\r\n\r\n\t\tvar name = document.createElement('span');\r\n\t\tname.innerHTML = ' ' + obj.name;\r\n\r\n\t\t// Helps from preventing layer control flicker when checkboxes are disabled\r\n\t\t// https://github.com/Leaflet/Leaflet/issues/2771\r\n\t\tvar holder = document.createElement('span');\r\n\r\n\t\tlabel.appendChild(holder);\r\n\t\tholder.appendChild(input);\r\n\t\tholder.appendChild(name);\r\n\r\n\t\tvar container = obj.overlay ? this._overlaysList : this._baseLayersList;\r\n\t\tcontainer.appendChild(label);\r\n\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn label;\r\n\t},\r\n\r\n\t_onInputClick: function () {\r\n\t\t// expanding the control on mobile with a click can cause adding a layer - we don't want this\r\n\t\tif (this._preventClick) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t    input, layer;\r\n\t\tvar addedLayers = [],\r\n\t\t    removedLayers = [];\r\n\r\n\t\tthis._handlingClick = true;\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\r\n\t\t\tif (input.checked) {\r\n\t\t\t\taddedLayers.push(layer);\r\n\t\t\t} else if (!input.checked) {\r\n\t\t\t\tremovedLayers.push(layer);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Bugfix issue 2318: Should remove all old layers before readding new ones\r\n\t\tfor (i = 0; i < removedLayers.length; i++) {\r\n\t\t\tif (this._map.hasLayer(removedLayers[i])) {\r\n\t\t\t\tthis._map.removeLayer(removedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (i = 0; i < addedLayers.length; i++) {\r\n\t\t\tif (!this._map.hasLayer(addedLayers[i])) {\r\n\t\t\t\tthis._map.addLayer(addedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._handlingClick = false;\r\n\r\n\t\tthis._refocusOnMap();\r\n\t},\r\n\r\n\t_checkDisabledLayers: function () {\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t    input,\r\n\t\t    layer,\r\n\t\t    zoom = this._map.getZoom();\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\t\t\tinput.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||\r\n\t\t\t                 (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);\r\n\r\n\t\t}\r\n\t},\r\n\r\n\t_expandIfNotCollapsed: function () {\r\n\t\tif (this._map && !this.options.collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_expandSafely: function () {\r\n\t\tvar section = this._section;\r\n\t\tthis._preventClick = true;\r\n\t\tDomEvent.on(section, 'click', DomEvent.preventDefault);\r\n\t\tthis.expand();\r\n\t\tvar that = this;\r\n\t\tsetTimeout(function () {\r\n\t\t\tDomEvent.off(section, 'click', DomEvent.preventDefault);\r\n\t\t\tthat._preventClick = false;\r\n\t\t});\r\n\t}\r\n\r\n});\r\n\r\n\r\n// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)\r\n// Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.\r\nexport var layers = function (baseLayers, overlays, options) {\r\n\treturn new Layers(baseLayers, overlays, options);\r\n};\r\n", "\r\nimport {Control} from './Control';\r\nimport {Map} from '../map/Map';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport * as DomEvent from '../dom/DomEvent';\r\n\r\n/*\r\n * @class Control.Zoom\r\n * @aka L.Control.Zoom\r\n * @inherits Control\r\n *\r\n * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.\r\n */\r\n\r\nexport var Zoom = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Zoom options\r\n\toptions: {\r\n\t\tposition: 'topleft',\r\n\r\n\t\t// @option zoomInText: String = '<span aria-hidden=\"true\">+</span>'\r\n\t\t// The text set on the 'zoom in' button.\r\n\t\tzoomInText: '<span aria-hidden=\"true\">+</span>',\r\n\r\n\t\t// @option zoomInTitle: String = 'Zoom in'\r\n\t\t// The title set on the 'zoom in' button.\r\n\t\tzoomInTitle: 'Zoom in',\r\n\r\n\t\t// @option zoomOutText: String = '<span aria-hidden=\"true\">&#x2212;</span>'\r\n\t\t// The text set on the 'zoom out' button.\r\n\t\tzoomOutText: '<span aria-hidden=\"true\">&#x2212;</span>',\r\n\r\n\t\t// @option zoomOutTitle: String = 'Zoom out'\r\n\t\t// The title set on the 'zoom out' button.\r\n\t\tzoomOutTitle: 'Zoom out'\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tvar zoomName = 'leaflet-control-zoom',\r\n\t\t    container = DomUtil.create('div', zoomName + ' leaflet-bar'),\r\n\t\t    options = this.options;\r\n\r\n\t\tthis._zoomInButton  = this._createButton(options.zoomInText, options.zoomInTitle,\r\n\t\t        zoomName + '-in',  container, this._zoomIn);\r\n\t\tthis._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,\r\n\t\t        zoomName + '-out', container, this._zoomOut);\r\n\r\n\t\tthis._updateDisabled();\r\n\t\tmap.on('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\r\n\t\treturn container;\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tmap.off('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\t},\r\n\r\n\tdisable: function () {\r\n\t\tthis._disabled = true;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\tenable: function () {\r\n\t\tthis._disabled = false;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_zoomIn: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {\r\n\t\t\tthis._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_zoomOut: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom > this._map.getMinZoom()) {\r\n\t\t\tthis._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_createButton: function (html, title, className, container, fn) {\r\n\t\tvar link = DomUtil.create('a', className, container);\r\n\t\tlink.innerHTML = html;\r\n\t\tlink.href = '#';\r\n\t\tlink.title = title;\r\n\r\n\t\t/*\r\n\t\t * Will force screen readers like VoiceOver to read this as \"Zoom in - button\"\r\n\t\t */\r\n\t\tlink.setAttribute('role', 'button');\r\n\t\tlink.setAttribute('aria-label', title);\r\n\r\n\t\tDomEvent.disableClickPropagation(link);\r\n\t\tDomEvent.on(link, 'click', DomEvent.stop);\r\n\t\tDomEvent.on(link, 'click', fn, this);\r\n\t\tDomEvent.on(link, 'click', this._refocusOnMap, this);\r\n\r\n\t\treturn link;\r\n\t},\r\n\r\n\t_updateDisabled: function () {\r\n\t\tvar map = this._map,\r\n\t\t    className = 'leaflet-disabled';\r\n\r\n\t\tDomUtil.removeClass(this._zoomInButton, className);\r\n\t\tDomUtil.removeClass(this._zoomOutButton, className);\r\n\t\tthis._zoomInButton.setAttribute('aria-disabled', 'false');\r\n\t\tthis._zoomOutButton.setAttribute('aria-disabled', 'false');\r\n\r\n\t\tif (this._disabled || map._zoom === map.getMinZoom()) {\r\n\t\t\tDomUtil.addClass(this._zoomOutButton, className);\r\n\t\t\tthis._zoomOutButton.setAttribute('aria-disabled', 'true');\r\n\t\t}\r\n\t\tif (this._disabled || map._zoom === map.getMaxZoom()) {\r\n\t\t\tDomUtil.addClass(this._zoomInButton, className);\r\n\t\t\tthis._zoomInButton.setAttribute('aria-disabled', 'true');\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option zoomControl: Boolean = true\r\n// Whether a [zoom control](#control-zoom) is added to the map by default.\r\nMap.mergeOptions({\r\n\tzoomControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.zoomControl) {\r\n\t\t// @section Controls\r\n\t\t// @property zoomControl: Control.Zoom\r\n\t\t// The default zoom control (only available if the\r\n\t\t// [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).\r\n\t\tthis.zoomControl = new Zoom();\r\n\t\tthis.addControl(this.zoomControl);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Zoom\r\n// @factory L.control.zoom(options: Control.Zoom options)\r\n// Creates a zoom control\r\nexport var zoom = function (options) {\r\n\treturn new Zoom(options);\r\n};\r\n", "\nimport {Control} from './Control';\nimport * as DomUtil from '../dom/DomUtil';\n\n/*\n * @class Control.Scale\n * @aka L.Control.Scale\n * @inherits Control\n *\n * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.\n *\n * @example\n *\n * ```js\n * L.control.scale().addTo(map);\n * ```\n */\n\nexport var Scale = Control.extend({\n\t// @section\n\t// @aka Control.Scale options\n\toptions: {\n\t\tposition: 'bottomleft',\n\n\t\t// @option maxWidth: Number = 100\n\t\t// Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).\n\t\tmaxWidth: 100,\n\n\t\t// @option metric: Boolean = True\n\t\t// Whether to show the metric scale line (m/km).\n\t\tmetric: true,\n\n\t\t// @option imperial: Boolean = True\n\t\t// Whether to show the imperial scale line (mi/ft).\n\t\timperial: true\n\n\t\t// @option updateWhenIdle: Boolean = false\n\t\t// If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).\n\t},\n\n\tonAdd: function (map) {\n\t\tvar className = 'leaflet-control-scale',\n\t\t    container = DomUtil.create('div', className),\n\t\t    options = this.options;\n\n\t\tthis._addScales(options, className + '-line', container);\n\n\t\tmap.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t\tmap.whenReady(this._update, this);\n\n\t\treturn container;\n\t},\n\n\tonRemove: function (map) {\n\t\tmap.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t},\n\n\t_addScales: function (options, className, container) {\n\t\tif (options.metric) {\n\t\t\tthis._mScale = DomUtil.create('div', className, container);\n\t\t}\n\t\tif (options.imperial) {\n\t\t\tthis._iScale = DomUtil.create('div', className, container);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tvar map = this._map,\n\t\t    y = map.getSize().y / 2;\n\n\t\tvar maxMeters = map.distance(\n\t\t\tmap.containerPointToLatLng([0, y]),\n\t\t\tmap.containerPointToLatLng([this.options.maxWidth, y]));\n\n\t\tthis._updateScales(maxMeters);\n\t},\n\n\t_updateScales: function (maxMeters) {\n\t\tif (this.options.metric && maxMeters) {\n\t\t\tthis._updateMetric(maxMeters);\n\t\t}\n\t\tif (this.options.imperial && maxMeters) {\n\t\t\tthis._updateImperial(maxMeters);\n\t\t}\n\t},\n\n\t_updateMetric: function (maxMeters) {\n\t\tvar meters = this._getRoundNum(maxMeters),\n\t\t    label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';\n\n\t\tthis._updateScale(this._mScale, label, meters / maxMeters);\n\t},\n\n\t_updateImperial: function (maxMeters) {\n\t\tvar maxFeet = maxMeters * 3.2808399,\n\t\t    maxMiles, miles, feet;\n\n\t\tif (maxFeet > 5280) {\n\t\t\tmaxMiles = maxFeet / 5280;\n\t\t\tmiles = this._getRoundNum(maxMiles);\n\t\t\tthis._updateScale(this._iScale, miles + ' mi', miles / maxMiles);\n\n\t\t} else {\n\t\t\tfeet = this._getRoundNum(maxFeet);\n\t\t\tthis._updateScale(this._iScale, feet + ' ft', feet / maxFeet);\n\t\t}\n\t},\n\n\t_updateScale: function (scale, text, ratio) {\n\t\tscale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';\n\t\tscale.innerHTML = text;\n\t},\n\n\t_getRoundNum: function (num) {\n\t\tvar pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),\n\t\t    d = num / pow10;\n\n\t\td = d >= 10 ? 10 :\n\t\t    d >= 5 ? 5 :\n\t\t    d >= 3 ? 3 :\n\t\t    d >= 2 ? 2 : 1;\n\n\t\treturn pow10 * d;\n\t}\n});\n\n\n// @factory L.control.scale(options?: Control.Scale options)\n// Creates an scale control with the given options.\nexport var scale = function (options) {\n\treturn new Scale(options);\n};\n", "\r\nimport {Control} from './Control';\r\nimport {Map} from '../map/Map';\r\nimport * as Util from '../core/Util';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport Browser from '../core/Browser';\r\n\r\nvar ukrainianFlag = '<svg aria-hidden=\"true\" xmlns=\"http://www.w3.org/2000/svg\" width=\"12\" height=\"8\" viewBox=\"0 0 12 8\" class=\"leaflet-attribution-flag\"><path fill=\"#4C7BE1\" d=\"M0 0h12v4H0z\"/><path fill=\"#FFD500\" d=\"M0 4h12v3H0z\"/><path fill=\"#E0BC00\" d=\"M0 7h12v1H0z\"/></svg>';\r\n\r\n\r\n/*\r\n * @class Control.Attribution\r\n * @aka L.Control.Attribution\r\n * @inherits Control\r\n *\r\n * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.\r\n */\r\n\r\nexport var Attribution = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Attribution options\r\n\toptions: {\r\n\t\tposition: 'bottomright',\r\n\r\n\t\t// @option prefix: String|false = 'Leaflet'\r\n\t\t// The HTML text shown before the attributions. Pass `false` to disable.\r\n\t\tprefix: '<a href=\"https://leafletjs.com\" title=\"A JavaScript library for interactive maps\">' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet</a>'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._attributions = {};\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tmap.attributionControl = this;\r\n\t\tthis._container = DomUtil.create('div', 'leaflet-control-attribution');\r\n\t\tDomEvent.disableClickPropagation(this._container);\r\n\r\n\t\t// TODO ugly, refactor\r\n\t\tfor (var i in map._layers) {\r\n\t\t\tif (map._layers[i].getAttribution) {\r\n\t\t\t\tthis.addAttribution(map._layers[i].getAttribution());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._update();\r\n\r\n\t\tmap.on('layeradd', this._addAttribution, this);\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tmap.off('layeradd', this._addAttribution, this);\r\n\t},\r\n\r\n\t_addAttribution: function (ev) {\r\n\t\tif (ev.layer.getAttribution) {\r\n\t\t\tthis.addAttribution(ev.layer.getAttribution());\r\n\t\t\tev.layer.once('remove', function () {\r\n\t\t\t\tthis.removeAttribution(ev.layer.getAttribution());\r\n\t\t\t}, this);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setPrefix(prefix: String|false): this\r\n\t// The HTML text shown before the attributions. Pass `false` to disable.\r\n\tsetPrefix: function (prefix) {\r\n\t\tthis.options.prefix = prefix;\r\n\t\tthis._update();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method addAttribution(text: String): this\r\n\t// Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).\r\n\taddAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (!this._attributions[text]) {\r\n\t\t\tthis._attributions[text] = 0;\r\n\t\t}\r\n\t\tthis._attributions[text]++;\r\n\r\n\t\tthis._update();\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeAttribution(text: String): this\r\n\t// Removes an attribution text.\r\n\tremoveAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (this._attributions[text]) {\r\n\t\t\tthis._attributions[text]--;\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tvar attribs = [];\r\n\r\n\t\tfor (var i in this._attributions) {\r\n\t\t\tif (this._attributions[i]) {\r\n\t\t\t\tattribs.push(i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar prefixAndAttribs = [];\r\n\r\n\t\tif (this.options.prefix) {\r\n\t\t\tprefixAndAttribs.push(this.options.prefix);\r\n\t\t}\r\n\t\tif (attribs.length) {\r\n\t\t\tprefixAndAttribs.push(attribs.join(', '));\r\n\t\t}\r\n\r\n\t\tthis._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden=\"true\">|</span> ');\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option attributionControl: Boolean = true\r\n// Whether a [attribution control](#control-attribution) is added to the map by default.\r\nMap.mergeOptions({\r\n\tattributionControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.attributionControl) {\r\n\t\tnew Attribution().addTo(this);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Attribution\r\n// @factory L.control.attribution(options: Control.Attribution options)\r\n// Creates an attribution control.\r\nexport var attribution = function (options) {\r\n\treturn new Attribution(options);\r\n};\r\n", "import {Control, control} from './Control';\nimport {Layers, layers} from './Control.Layers';\nimport {Zoom, zoom} from './Control.Zoom';\nimport {Scale, scale} from './Control.Scale';\nimport {Attribution, attribution} from './Control.Attribution';\n\nControl.Layers = Layers;\nControl.Zoom = Zoom;\nControl.Scale = Scale;\nControl.Attribution = Attribution;\n\ncontrol.layers = layers;\ncontrol.zoom = zoom;\ncontrol.scale = scale;\ncontrol.attribution = attribution;\n\nexport {Control, control};\n", "import {Class} from './Class';\n\n/*\n\tL.Handler is a base class for handler classes that are used internally to inject\n\tinteraction features like dragging to classes like Map and Marker.\n*/\n\n// @class Handler\n// @aka L.Handler\n// Abstract class for map interaction handlers\n\nexport var Handler = Class.extend({\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\t},\n\n\t// @method enable(): this\n\t// Enables the handler\n\tenable: function () {\n\t\tif (this._enabled) { return this; }\n\n\t\tthis._enabled = true;\n\t\tthis.addHooks();\n\t\treturn this;\n\t},\n\n\t// @method disable(): this\n\t// Disables the handler\n\tdisable: function () {\n\t\tif (!this._enabled) { return this; }\n\n\t\tthis._enabled = false;\n\t\tthis.removeHooks();\n\t\treturn this;\n\t},\n\n\t// @method enabled(): Boolean\n\t// Returns `true` if the handler is enabled\n\tenabled: function () {\n\t\treturn !!this._enabled;\n\t}\n\n\t// @section Extension methods\n\t// Classes inheriting from `Handler` must implement the two following methods:\n\t// @method addHooks()\n\t// Called when the handler is enabled, should add event hooks.\n\t// @method removeHooks()\n\t// Called when the handler is disabled, should remove the event hooks added previously.\n});\n\n// @section There is static function which can be called without instantiating L.Handler:\n// @function addTo(map: Map, name: String): this\n// Adds a new Handler to the given map with the given name.\nHandler.addTo = function (map, name) {\n\tmap.addHandler(name, this);\n\treturn this;\n};\n", "import Browser from './Browser';\nexport {Browser};\n\nexport {Class} from './Class';\n\nimport {Evented} from './Events';\nimport {Events} from './Events';\nexport {Evented};\nexport var Mixin = {Events: Events};\n\nexport {Handler} from './Handler';\n\nimport * as Util from './Util';\nexport {Util};\nexport {extend, bind, stamp, setOptions} from './Util';\n", "import {Evented} from '../core/Events';\r\nimport Browser from '../core/Browser';\r\nimport * as DomEvent from './DomEvent';\r\nimport * as DomUtil from './DomUtil';\r\nimport * as Util from '../core/Util';\r\nimport {Point} from '../geometry/Point';\r\n\r\n/*\r\n * @class Draggable\r\n * @aka L.Draggable\r\n * @inherits Evented\r\n *\r\n * A class for making DOM elements draggable (including touch support).\r\n * Used internally for map and marker dragging. Only works for elements\r\n * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).\r\n *\r\n * @example\r\n * ```js\r\n * var draggable = new L.Draggable(elementToDrag);\r\n * draggable.enable();\r\n * ```\r\n */\r\n\r\nvar START = Browser.touch ? 'touchstart mousedown' : 'mousedown';\r\n\r\nexport var Draggable = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section\r\n\t\t// @aka Draggable options\r\n\t\t// @option clickTolerance: Number = 3\r\n\t\t// The max number of pixels a user can shift the mouse pointer during a click\r\n\t\t// for it to be considered a valid click (as opposed to a mouse drag).\r\n\t\tclickTolerance: 3\r\n\t},\r\n\r\n\t// @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)\r\n\t// Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).\r\n\tinitialize: function (element, dragStartTarget, preventOutline, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._element = element;\r\n\t\tthis._dragStartTarget = dragStartTarget || element;\r\n\t\tthis._preventOutline = preventOutline;\r\n\t},\r\n\r\n\t// @method enable()\r\n\t// Enables the dragging ability\r\n\tenable: function () {\r\n\t\tif (this._enabled) { return; }\r\n\r\n\t\tDomEvent.on(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = true;\r\n\t},\r\n\r\n\t// @method disable()\r\n\t// Disables the dragging ability\r\n\tdisable: function () {\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\t// If we're currently dragging this draggable,\r\n\t\t// disabling it counts as first ending the drag.\r\n\t\tif (Draggable._dragging === this) {\r\n\t\t\tthis.finishDrag(true);\r\n\t\t}\r\n\r\n\t\tDomEvent.off(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = false;\r\n\t\tthis._moved = false;\r\n\t},\r\n\r\n\t_onDown: function (e) {\r\n\t\t// Ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\tthis._moved = false;\r\n\r\n\t\tif (DomUtil.hasClass(this._element, 'leaflet-zoom-anim')) { return; }\r\n\r\n\t\tif (e.touches && e.touches.length !== 1) {\r\n\t\t\t// Finish dragging to avoid conflict with touchZoom\r\n\t\t\tif (Draggable._dragging === this) {\r\n\t\t\t\tthis.finishDrag();\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }\r\n\t\tDraggable._dragging = this;  // Prevent dragging multiple objects at once.\r\n\r\n\t\tif (this._preventOutline) {\r\n\t\t\tDomUtil.preventOutline(this._element);\r\n\t\t}\r\n\r\n\t\tDomUtil.disableImageDrag();\r\n\t\tDomUtil.disableTextSelection();\r\n\r\n\t\tif (this._moving) { return; }\r\n\r\n\t\t// @event down: Event\r\n\t\t// Fired when a drag is about to start.\r\n\t\tthis.fire('down');\r\n\r\n\t\tvar first = e.touches ? e.touches[0] : e,\r\n\t\t    sizedParent = DomUtil.getSizedParentNode(this._element);\r\n\r\n\t\tthis._startPoint = new Point(first.clientX, first.clientY);\r\n\t\tthis._startPos = DomUtil.getPosition(this._element);\r\n\r\n\t\t// Cache the scale, so that we can continuously compensate for it during drag (_onMove).\r\n\t\tthis._parentScale = DomUtil.getScale(sizedParent);\r\n\r\n\t\tvar mouseevent = e.type === 'mousedown';\r\n\t\tDomEvent.on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this);\r\n\t\tDomEvent.on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this);\r\n\t},\r\n\r\n\t_onMove: function (e) {\r\n\t\t// Ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\tif (e.touches && e.touches.length > 1) {\r\n\t\t\tthis._moved = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),\r\n\t\t    offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);\r\n\r\n\t\tif (!offset.x && !offset.y) { return; }\r\n\t\tif (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }\r\n\r\n\t\t// We assume that the parent container's position, border and scale do not change for the duration of the drag.\r\n\t\t// Therefore there is no need to account for the position and border (they are eliminated by the subtraction)\r\n\t\t// and we can use the cached value for the scale.\r\n\t\toffset.x /= this._parentScale.x;\r\n\t\toffset.y /= this._parentScale.y;\r\n\r\n\t\tDomEvent.preventDefault(e);\r\n\r\n\t\tif (!this._moved) {\r\n\t\t\t// @event dragstart: Event\r\n\t\t\t// Fired when a drag starts\r\n\t\t\tthis.fire('dragstart');\r\n\r\n\t\t\tthis._moved = true;\r\n\r\n\t\t\tDomUtil.addClass(document.body, 'leaflet-dragging');\r\n\r\n\t\t\tthis._lastTarget = e.target || e.srcElement;\r\n\t\t\t// IE and Edge do not give the <use> element, so fetch it\r\n\t\t\t// if necessary\r\n\t\t\tif (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {\r\n\t\t\t\tthis._lastTarget = this._lastTarget.correspondingUseElement;\r\n\t\t\t}\r\n\t\t\tDomUtil.addClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t}\r\n\r\n\t\tthis._newPos = this._startPos.add(offset);\r\n\t\tthis._moving = true;\r\n\r\n\t\tthis._lastEvent = e;\r\n\t\tthis._updatePosition();\r\n\t},\r\n\r\n\t_updatePosition: function () {\r\n\t\tvar e = {originalEvent: this._lastEvent};\r\n\r\n\t\t// @event predrag: Event\r\n\t\t// Fired continuously during dragging *before* each corresponding\r\n\t\t// update of the element's position.\r\n\t\tthis.fire('predrag', e);\r\n\t\tDomUtil.setPosition(this._element, this._newPos);\r\n\r\n\t\t// @event drag: Event\r\n\t\t// Fired continuously during dragging.\r\n\t\tthis.fire('drag', e);\r\n\t},\r\n\r\n\t_onUp: function () {\r\n\t\t// Ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (!this._enabled) { return; }\r\n\t\tthis.finishDrag();\r\n\t},\r\n\r\n\tfinishDrag: function (noInertia) {\r\n\t\tDomUtil.removeClass(document.body, 'leaflet-dragging');\r\n\r\n\t\tif (this._lastTarget) {\r\n\t\t\tDomUtil.removeClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t\tthis._lastTarget = null;\r\n\t\t}\r\n\r\n\t\tDomEvent.off(document, 'mousemove touchmove', this._onMove, this);\r\n\t\tDomEvent.off(document, 'mouseup touchend touchcancel', this._onUp, this);\r\n\r\n\t\tDomUtil.enableImageDrag();\r\n\t\tDomUtil.enableTextSelection();\r\n\r\n\t\tvar fireDragend = this._moved && this._moving;\r\n\r\n\t\tthis._moving = false;\r\n\t\tDraggable._dragging = false;\r\n\r\n\t\tif (fireDragend) {\r\n\t\t\t// @event dragend: DragEndEvent\r\n\t\t\t// Fired when the drag ends.\r\n\t\t\tthis.fire('dragend', {\r\n\t\t\t\tnoInertia: noInertia,\r\n\t\t\t\tdistance: this._newPos.distanceTo(this._startPos)\r\n\t\t\t});\r\n\t\t}\r\n\t}\r\n\r\n});\r\n", "import * as LineUtil from './LineUtil';\r\nimport {toLatLng} from '../geo/LatLng';\r\nimport {toPoint} from './Point';\r\nimport {toLatLngBounds} from '../geo/LatLngBounds';\r\n/*\r\n * @namespace PolyUtil\r\n * Various utility functions for polygon geometries.\r\n */\r\n\r\n/* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]\r\n * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).\r\n * Used by Leaflet to only show polygon points that are on the screen or near, increasing\r\n * performance. Note that polygon points needs different algorithm for clipping\r\n * than polyline, so there's a separate method for it.\r\n */\r\nexport function clipPolygon(points, bounds, round) {\r\n\tvar clippedPoints,\r\n\t    edges = [1, 4, 2, 8],\r\n\t    i, j, k,\r\n\t    a, b,\r\n\t    len, edge, p;\r\n\r\n\tfor (i = 0, len = points.length; i < len; i++) {\r\n\t\tpoints[i]._code = LineUtil._getBitCode(points[i], bounds);\r\n\t}\r\n\r\n\t// for each edge (left, bottom, right, top)\r\n\tfor (k = 0; k < 4; k++) {\r\n\t\tedge = edges[k];\r\n\t\tclippedPoints = [];\r\n\r\n\t\tfor (i = 0, len = points.length, j = len - 1; i < len; j = i++) {\r\n\t\t\ta = points[i];\r\n\t\t\tb = points[j];\r\n\r\n\t\t\t// if a is inside the clip window\r\n\t\t\tif (!(a._code & edge)) {\r\n\t\t\t\t// if b is outside the clip window (a->b goes out of screen)\r\n\t\t\t\tif (b._code & edge) {\r\n\t\t\t\t\tp = LineUtil._getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\t\tp._code = LineUtil._getBitCode(p, bounds);\r\n\t\t\t\t\tclippedPoints.push(p);\r\n\t\t\t\t}\r\n\t\t\t\tclippedPoints.push(a);\r\n\r\n\t\t\t// else if b is inside the clip window (a->b enters the screen)\r\n\t\t\t} else if (!(b._code & edge)) {\r\n\t\t\t\tp = LineUtil._getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\tp._code = LineUtil._getBitCode(p, bounds);\r\n\t\t\t\tclippedPoints.push(p);\r\n\t\t\t}\r\n\t\t}\r\n\t\tpoints = clippedPoints;\r\n\t}\r\n\r\n\treturn points;\r\n}\r\n\r\n/* @function polygonCenter(latlngs: LatLng[], crs: CRS): LatLng\r\n * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon.\r\n */\r\nexport function polygonCenter(latlngs, crs) {\r\n\tvar i, j, p1, p2, f, area, x, y, center;\r\n\r\n\tif (!latlngs || latlngs.length === 0) {\r\n\t\tthrow new Error('latlngs not passed');\r\n\t}\r\n\r\n\tif (!LineUtil.isFlat(latlngs)) {\r\n\t\tconsole.warn('latlngs are not flat! Only the first ring will be used');\r\n\t\tlatlngs = latlngs[0];\r\n\t}\r\n\r\n\tvar centroidLatLng = toLatLng([0, 0]);\r\n\r\n\tvar bounds = toLatLngBounds(latlngs);\r\n\tvar areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());\r\n\t// tests showed that below 1700 rounding errors are happening\r\n\tif (areaBounds < 1700) {\r\n\t\t// getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors\r\n\t\tcentroidLatLng = centroid(latlngs);\r\n\t}\r\n\r\n\tvar len = latlngs.length;\r\n\tvar points = [];\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tvar latlng = toLatLng(latlngs[i]);\r\n\t\tpoints.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));\r\n\t}\r\n\r\n\tarea = x = y = 0;\r\n\r\n\t// polygon centroid algorithm;\r\n\tfor (i = 0, j = len - 1; i < len; j = i++) {\r\n\t\tp1 = points[i];\r\n\t\tp2 = points[j];\r\n\r\n\t\tf = p1.y * p2.x - p2.y * p1.x;\r\n\t\tx += (p1.x + p2.x) * f;\r\n\t\ty += (p1.y + p2.y) * f;\r\n\t\tarea += f * 3;\r\n\t}\r\n\r\n\tif (area === 0) {\r\n\t\t// Polygon is so small that all points are on same pixel.\r\n\t\tcenter = points[0];\r\n\t} else {\r\n\t\tcenter = [x / area, y / area];\r\n\t}\r\n\r\n\tvar latlngCenter = crs.unproject(toPoint(center));\r\n\treturn toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);\r\n}\r\n\r\n/* @function centroid(latlngs: LatLng[]): LatLng\r\n * Returns the 'center of mass' of the passed LatLngs.\r\n */\r\nexport function centroid(coords) {\r\n\tvar latSum = 0;\r\n\tvar lngSum = 0;\r\n\tvar len = 0;\r\n\tfor (var i = 0; i < coords.length; i++) {\r\n\t\tvar latlng = toLatLng(coords[i]);\r\n\t\tlatSum += latlng.lat;\r\n\t\tlngSum += latlng.lng;\r\n\t\tlen++;\r\n\t}\r\n\treturn toLatLng([latSum / len, lngSum / len]);\r\n}\r\n", "import {Point, toPoint} from './Point';\r\nimport * as Util from '../core/Util';\r\nimport {toLatLng} from '../geo/LatLng';\r\nimport {centroid} from './PolyUtil';\r\nimport {toLatLngBounds} from '../geo/LatLngBounds';\r\n\r\n\r\n/*\r\n * @namespace LineUtil\r\n *\r\n * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.\r\n */\r\n\r\n// Simplify polyline with vertex reduction and Douglas-Peucker simplification.\r\n// Improves rendering performance dramatically by lessening the number of points to draw.\r\n\r\n// @function simplify(points: Point[], tolerance: Number): Point[]\r\n// Dramatically reduces the number of points in a polyline while retaining\r\n// its shape and returns a new array of simplified points, using the\r\n// [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm).\r\n// Used for a huge performance boost when processing/displaying Leaflet polylines for\r\n// each zoom level and also reducing visual noise. tolerance affects the amount of\r\n// simplification (lesser value means higher quality but slower and with more points).\r\n// Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/).\r\nexport function simplify(points, tolerance) {\r\n\tif (!tolerance || !points.length) {\r\n\t\treturn points.slice();\r\n\t}\r\n\r\n\tvar sqTolerance = tolerance * tolerance;\r\n\r\n\t    // stage 1: vertex reduction\r\n\t    points = _reducePoints(points, sqTolerance);\r\n\r\n\t    // stage 2: Douglas-Peucker simplification\r\n\t    points = _simplifyDP(points, sqTolerance);\r\n\r\n\treturn points;\r\n}\r\n\r\n// @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number\r\n// Returns the distance between point `p` and segment `p1` to `p2`.\r\nexport function pointToSegmentDistance(p, p1, p2) {\r\n\treturn Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));\r\n}\r\n\r\n// @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number\r\n// Returns the closest point from a point `p` on a segment `p1` to `p2`.\r\nexport function closestPointOnSegment(p, p1, p2) {\r\n\treturn _sqClosestPointOnSegment(p, p1, p2);\r\n}\r\n\r\n// Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\r\nfunction _simplifyDP(points, sqTolerance) {\r\n\r\n\tvar len = points.length,\r\n\t    ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,\r\n\t    markers = new ArrayConstructor(len);\r\n\r\n\t    markers[0] = markers[len - 1] = 1;\r\n\r\n\t_simplifyDPStep(points, markers, sqTolerance, 0, len - 1);\r\n\r\n\tvar i,\r\n\t    newPoints = [];\r\n\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tif (markers[i]) {\r\n\t\t\tnewPoints.push(points[i]);\r\n\t\t}\r\n\t}\r\n\r\n\treturn newPoints;\r\n}\r\n\r\nfunction _simplifyDPStep(points, markers, sqTolerance, first, last) {\r\n\r\n\tvar maxSqDist = 0,\r\n\tindex, i, sqDist;\r\n\r\n\tfor (i = first + 1; i <= last - 1; i++) {\r\n\t\tsqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);\r\n\r\n\t\tif (sqDist > maxSqDist) {\r\n\t\t\tindex = i;\r\n\t\t\tmaxSqDist = sqDist;\r\n\t\t}\r\n\t}\r\n\r\n\tif (maxSqDist > sqTolerance) {\r\n\t\tmarkers[index] = 1;\r\n\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, first, index);\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, index, last);\r\n\t}\r\n}\r\n\r\n// reduce points that are too close to each other to a single point\r\nfunction _reducePoints(points, sqTolerance) {\r\n\tvar reducedPoints = [points[0]];\r\n\r\n\tfor (var i = 1, prev = 0, len = points.length; i < len; i++) {\r\n\t\tif (_sqDist(points[i], points[prev]) > sqTolerance) {\r\n\t\t\treducedPoints.push(points[i]);\r\n\t\t\tprev = i;\r\n\t\t}\r\n\t}\r\n\tif (prev < len - 1) {\r\n\t\treducedPoints.push(points[len - 1]);\r\n\t}\r\n\treturn reducedPoints;\r\n}\r\n\r\nvar _lastCode;\r\n\r\n// @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean\r\n// Clips the segment a to b by rectangular bounds with the\r\n// [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)\r\n// (modifying the segment points directly!). Used by Leaflet to only show polyline\r\n// points that are on the screen or near, increasing performance.\r\nexport function clipSegment(a, b, bounds, useLastCode, round) {\r\n\tvar codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),\r\n\t    codeB = _getBitCode(b, bounds),\r\n\r\n\t    codeOut, p, newCode;\r\n\r\n\t    // save 2nd code to avoid calculating it on the next segment\r\n\t    _lastCode = codeB;\r\n\r\n\twhile (true) {\r\n\t\t// if a,b is inside the clip window (trivial accept)\r\n\t\tif (!(codeA | codeB)) {\r\n\t\t\treturn [a, b];\r\n\t\t}\r\n\r\n\t\t// if a,b is outside the clip window (trivial reject)\r\n\t\tif (codeA & codeB) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t// other cases\r\n\t\tcodeOut = codeA || codeB;\r\n\t\tp = _getEdgeIntersection(a, b, codeOut, bounds, round);\r\n\t\tnewCode = _getBitCode(p, bounds);\r\n\r\n\t\tif (codeOut === codeA) {\r\n\t\t\ta = p;\r\n\t\t\tcodeA = newCode;\r\n\t\t} else {\r\n\t\t\tb = p;\r\n\t\t\tcodeB = newCode;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nexport function _getEdgeIntersection(a, b, code, bounds, round) {\r\n\tvar dx = b.x - a.x,\r\n\t    dy = b.y - a.y,\r\n\t    min = bounds.min,\r\n\t    max = bounds.max,\r\n\t    x, y;\r\n\r\n\tif (code & 8) { // top\r\n\t\tx = a.x + dx * (max.y - a.y) / dy;\r\n\t\ty = max.y;\r\n\r\n\t} else if (code & 4) { // bottom\r\n\t\tx = a.x + dx * (min.y - a.y) / dy;\r\n\t\ty = min.y;\r\n\r\n\t} else if (code & 2) { // right\r\n\t\tx = max.x;\r\n\t\ty = a.y + dy * (max.x - a.x) / dx;\r\n\r\n\t} else if (code & 1) { // left\r\n\t\tx = min.x;\r\n\t\ty = a.y + dy * (min.x - a.x) / dx;\r\n\t}\r\n\r\n\treturn new Point(x, y, round);\r\n}\r\n\r\nexport function _getBitCode(p, bounds) {\r\n\tvar code = 0;\r\n\r\n\tif (p.x < bounds.min.x) { // left\r\n\t\tcode |= 1;\r\n\t} else if (p.x > bounds.max.x) { // right\r\n\t\tcode |= 2;\r\n\t}\r\n\r\n\tif (p.y < bounds.min.y) { // bottom\r\n\t\tcode |= 4;\r\n\t} else if (p.y > bounds.max.y) { // top\r\n\t\tcode |= 8;\r\n\t}\r\n\r\n\treturn code;\r\n}\r\n\r\n// square distance (to avoid unnecessary Math.sqrt calls)\r\nfunction _sqDist(p1, p2) {\r\n\tvar dx = p2.x - p1.x,\r\n\t    dy = p2.y - p1.y;\r\n\treturn dx * dx + dy * dy;\r\n}\r\n\r\n// return closest point on segment or distance to that point\r\nexport function _sqClosestPointOnSegment(p, p1, p2, sqDist) {\r\n\tvar x = p1.x,\r\n\t    y = p1.y,\r\n\t    dx = p2.x - x,\r\n\t    dy = p2.y - y,\r\n\t    dot = dx * dx + dy * dy,\r\n\t    t;\r\n\r\n\tif (dot > 0) {\r\n\t\tt = ((p.x - x) * dx + (p.y - y) * dy) / dot;\r\n\r\n\t\tif (t > 1) {\r\n\t\t\tx = p2.x;\r\n\t\t\ty = p2.y;\r\n\t\t} else if (t > 0) {\r\n\t\t\tx += dx * t;\r\n\t\t\ty += dy * t;\r\n\t\t}\r\n\t}\r\n\r\n\tdx = p.x - x;\r\n\tdy = p.y - y;\r\n\r\n\treturn sqDist ? dx * dx + dy * dy : new Point(x, y);\r\n}\r\n\r\n\r\n// @function isFlat(latlngs: LatLng[]): Boolean\r\n// Returns true if `latlngs` is a flat array, false is nested.\r\nexport function isFlat(latlngs) {\r\n\treturn !Util.isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');\r\n}\r\n\r\nexport function _flat(latlngs) {\r\n\tconsole.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');\r\n\treturn isFlat(latlngs);\r\n}\r\n\r\n/* @function polylineCenter(latlngs: LatLng[], crs: CRS): LatLng\r\n * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline.\r\n */\r\nexport function polylineCenter(latlngs, crs) {\r\n\tvar i, halfDist, segDist, dist, p1, p2, ratio, center;\r\n\r\n\tif (!latlngs || latlngs.length === 0) {\r\n\t\tthrow new Error('latlngs not passed');\r\n\t}\r\n\r\n\tif (!isFlat(latlngs)) {\r\n\t\tconsole.warn('latlngs are not flat! Only the first ring will be used');\r\n\t\tlatlngs = latlngs[0];\r\n\t}\r\n\r\n\tvar centroidLatLng = toLatLng([0, 0]);\r\n\r\n\tvar bounds = toLatLngBounds(latlngs);\r\n\tvar areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());\r\n\t// tests showed that below 1700 rounding errors are happening\r\n\tif (areaBounds < 1700) {\r\n\t\t// getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors\r\n\t\tcentroidLatLng = centroid(latlngs);\r\n\t}\r\n\r\n\tvar len = latlngs.length;\r\n\tvar points = [];\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tvar latlng = toLatLng(latlngs[i]);\r\n\t\tpoints.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));\r\n\t}\r\n\r\n\tfor (i = 0, halfDist = 0; i < len - 1; i++) {\r\n\t\thalfDist += points[i].distanceTo(points[i + 1]) / 2;\r\n\t}\r\n\r\n\t// The line is so small in the current view that all points are on the same pixel.\r\n\tif (halfDist === 0) {\r\n\t\tcenter = points[0];\r\n\t} else {\r\n\t\tfor (i = 0, dist = 0; i < len - 1; i++) {\r\n\t\t\tp1 = points[i];\r\n\t\t\tp2 = points[i + 1];\r\n\t\t\tsegDist = p1.distanceTo(p2);\r\n\t\t\tdist += segDist;\r\n\r\n\t\t\tif (dist > halfDist) {\r\n\t\t\t\tratio = (dist - halfDist) / segDist;\r\n\t\t\t\tcenter = [\r\n\t\t\t\t\tp2.x - ratio * (p2.x - p1.x),\r\n\t\t\t\t\tp2.y - ratio * (p2.y - p1.y)\r\n\t\t\t\t];\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvar latlngCenter = crs.unproject(toPoint(center));\r\n\treturn toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);\r\n}\r\n", "import {LatLng} from '../LatLng';\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {Point} from '../../geometry/Point';\r\n\r\n/*\r\n * @namespace Projection\r\n * @section\r\n * Leaflet comes with a set of already defined Projections out of the box:\r\n *\r\n * @projection L.Projection.LonLat\r\n *\r\n * Equirectangular, or Plate Carree projection — the most simple projection,\r\n * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as\r\n * latitude. Also suitable for flat worlds, e.g. game maps. Used by the\r\n * `EPSG:4326` and `Simple` CRS.\r\n */\r\n\r\nexport var LonLat = {\r\n\tproject: function (latlng) {\r\n\t\treturn new Point(latlng.lng, latlng.lat);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\treturn new LatLng(point.y, point.x);\r\n\t},\r\n\r\n\tbounds: new Bounds([-180, -90], [180, 90])\r\n};\r\n", "import {LatLng} from '../LatLng';\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {Point} from '../../geometry/Point';\r\n\r\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.Mercator\r\n *\r\n * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.\r\n */\r\n\r\nexport var Mercator = {\r\n\tR: 6378137,\r\n\tR_MINOR: 6356752.314245179,\r\n\r\n\tbounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t    r = this.R,\r\n\t\t    y = latlng.lat * d,\r\n\t\t    tmp = this.R_MINOR / r,\r\n\t\t    e = Math.sqrt(1 - tmp * tmp),\r\n\t\t    con = e * Math.sin(y);\r\n\r\n\t\tvar ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\ty = -r * Math.log(Math.max(ts, 1E-10));\r\n\r\n\t\treturn new Point(latlng.lng * d * r, y);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI,\r\n\t\t    r = this.R,\r\n\t\t    tmp = this.R_MINOR / r,\r\n\t\t    e = Math.sqrt(1 - tmp * tmp),\r\n\t\t    ts = Math.exp(-point.y / r),\r\n\t\t    phi = Math.PI / 2 - 2 * Math.atan(ts);\r\n\r\n\t\tfor (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {\r\n\t\t\tcon = e * Math.sin(phi);\r\n\t\t\tcon = Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\t\tdphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;\r\n\t\t\tphi += dphi;\r\n\t\t}\r\n\r\n\t\treturn new LatLng(phi * d, point.x * d / r);\r\n\t}\r\n};\r\n", "/*\n * @class Projection\n\n * An object with methods for projecting geographical coordinates of the world onto\n * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection).\n\n * @property bounds: Bounds\n * The bounds (specified in CRS units) where the projection is valid\n\n * @method project(latlng: LatLng): Point\n * Projects geographical coordinates into a 2D point.\n * Only accepts actual `L.LatLng` instances, not arrays.\n\n * @method unproject(point: Point): LatLng\n * The inverse of `project`. Projects a 2D point into a geographical location.\n * Only accepts actual `L.Point` instances, not arrays.\n\n * Note that the projection instances do not inherit from Leaflet's `Class` object,\n * and can't be instantiated. Also, new classes can't inherit from them,\n * and methods can't be added to them with the `include` function.\n\n */\n\nexport {LonLat} from './Projection.LonLat';\nexport {Mercator} from './Projection.Mercator';\nexport {SphericalMercator} from './Projection.SphericalMercator';\n", "import {Earth} from './CRS.Earth';\r\nimport {Mercator} from '../projection/Projection.Mercator';\r\nimport {toTransformation} from '../../geometry/Transformation';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3395\r\n *\r\n * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.\r\n */\r\nexport var EPSG3395 = Util.extend({}, Earth, {\r\n\tcode: 'EPSG:3395',\r\n\tprojection: Mercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * Mercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\r\n", "import {Earth} from './CRS.Earth';\r\nimport {LonLat} from '../projection/Projection.LonLat';\r\nimport {toTransformation} from '../../geometry/Transformation';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG4326\r\n *\r\n * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.\r\n *\r\n * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),\r\n * which is a breaking change from 0.7.x behaviour.  If you are using a `TileLayer`\r\n * with this CRS, ensure that there are two 256x256 pixel tiles covering the\r\n * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),\r\n * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.\r\n */\r\n\r\nexport var EPSG4326 = Util.extend({}, Earth, {\r\n\tcode: 'EPSG:4326',\r\n\tprojection: LonLat,\r\n\ttransformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)\r\n});\r\n", "import {CRS} from './CRS';\nimport {LonLat} from '../projection/Projection.LonLat';\nimport {toTransformation} from '../../geometry/Transformation';\nimport * as Util from '../../core/Util';\n\n/*\n * @namespace CRS\n * @crs L.CRS.Simple\n *\n * A simple CRS that maps longitude and latitude into `x` and `y` directly.\n * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`\n * axis should still be inverted (going from bottom to top). `distance()` returns\n * simple euclidean distance.\n */\n\nexport var Simple = Util.extend({}, CRS, {\n\tprojection: LonLat,\n\ttransformation: toTransformation(1, 0, -1, 0),\n\n\tscale: function (zoom) {\n\t\treturn Math.pow(2, zoom);\n\t},\n\n\tzoom: function (scale) {\n\t\treturn Math.log(scale) / Math.LN2;\n\t},\n\n\tdistance: function (latlng1, latlng2) {\n\t\tvar dx = latlng2.lng - latlng1.lng,\n\t\t    dy = latlng2.lat - latlng1.lat;\n\n\t\treturn Math.sqrt(dx * dx + dy * dy);\n\t},\n\n\tinfinite: true\n});\n", "import {CRS} from './CRS';\nimport {Earth} from './CRS.Earth';\nimport {EPSG3395} from './CRS.EPSG3395';\nimport {EPSG3857, EPSG900913} from './CRS.EPSG3857';\nimport {EPSG4326} from './CRS.EPSG4326';\nimport {Simple} from './CRS.Simple';\n\nCRS.Earth = Earth;\nCRS.EPSG3395 = EPSG3395;\nCRS.EPSG3857 = EPSG3857;\nCRS.EPSG900913 = EPSG900913;\nCRS.EPSG4326 = EPSG4326;\nCRS.Simple = Simple;\n\nexport {CRS};\n", "import {Evented} from '../core/Events';\nimport {Map} from '../map/Map';\nimport * as Util from '../core/Util';\n\n/*\n * @class Layer\n * @inherits Evented\n * @aka L.Layer\n * @aka ILayer\n *\n * A set of methods from the Layer base class that all Leaflet layers use.\n * Inherits all methods, options and events from `L.Evented`.\n *\n * @example\n *\n * ```js\n * var layer = L.marker(latlng).addTo(map);\n * layer.addTo(map);\n * layer.remove();\n * ```\n *\n * @event add: Event\n * Fired after the layer is added to a map\n *\n * @event remove: Event\n * Fired after the layer is removed from a map\n */\n\n\nexport var Layer = Evented.extend({\n\n\t// Classes extending `L.Layer` will inherit the following options:\n\toptions: {\n\t\t// @option pane: String = 'overlayPane'\n\t\t// By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.\n\t\tpane: 'overlayPane',\n\n\t\t// @option attribution: String = null\n\t\t// String to be shown in the attribution control, e.g. \"© OpenStreetMap contributors\". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.\n\t\tattribution: null,\n\n\t\tbubblingMouseEvents: true\n\t},\n\n\t/* @section\n\t * Classes extending `L.Layer` will inherit the following methods:\n\t *\n\t * @method addTo(map: Map|LayerGroup): this\n\t * Adds the layer to the given map or layer group.\n\t */\n\taddTo: function (map) {\n\t\tmap.addLayer(this);\n\t\treturn this;\n\t},\n\n\t// @method remove: this\n\t// Removes the layer from the map it is currently active on.\n\tremove: function () {\n\t\treturn this.removeFrom(this._map || this._mapToAdd);\n\t},\n\n\t// @method removeFrom(map: Map): this\n\t// Removes the layer from the given map\n\t//\n\t// @alternative\n\t// @method removeFrom(group: LayerGroup): this\n\t// Removes the layer from the given `LayerGroup`\n\tremoveFrom: function (obj) {\n\t\tif (obj) {\n\t\t\tobj.removeLayer(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getPane(name? : String): HTMLElement\n\t// Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.\n\tgetPane: function (name) {\n\t\treturn this._map.getPane(name ? (this.options[name] || name) : this.options.pane);\n\t},\n\n\taddInteractiveTarget: function (targetEl) {\n\t\tthis._map._targets[Util.stamp(targetEl)] = this;\n\t\treturn this;\n\t},\n\n\tremoveInteractiveTarget: function (targetEl) {\n\t\tdelete this._map._targets[Util.stamp(targetEl)];\n\t\treturn this;\n\t},\n\n\t// @method getAttribution: String\n\t// Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).\n\tgetAttribution: function () {\n\t\treturn this.options.attribution;\n\t},\n\n\t_layerAdd: function (e) {\n\t\tvar map = e.target;\n\n\t\t// check in case layer gets added and then removed before the map is ready\n\t\tif (!map.hasLayer(this)) { return; }\n\n\t\tthis._map = map;\n\t\tthis._zoomAnimated = map._zoomAnimated;\n\n\t\tif (this.getEvents) {\n\t\t\tvar events = this.getEvents();\n\t\t\tmap.on(events, this);\n\t\t\tthis.once('remove', function () {\n\t\t\t\tmap.off(events, this);\n\t\t\t}, this);\n\t\t}\n\n\t\tthis.onAdd(map);\n\n\t\tthis.fire('add');\n\t\tmap.fire('layeradd', {layer: this});\n\t}\n});\n\n/* @section Extension methods\n * @uninheritable\n *\n * Every layer should extend from `L.Layer` and (re-)implement the following methods.\n *\n * @method onAdd(map: Map): this\n * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).\n *\n * @method onRemove(map: Map): this\n * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).\n *\n * @method getEvents(): Object\n * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.\n *\n * @method getAttribution(): String\n * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.\n *\n * @method beforeAdd(map: Map): this\n * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.\n */\n\n\n/* @namespace Map\n * @section Layer events\n *\n * @event layeradd: LayerEvent\n * Fired when a new layer is added to the map.\n *\n * @event layerremove: LayerEvent\n * Fired when some layer is removed from the map\n *\n * @section Methods for Layers and Controls\n */\nMap.include({\n\t// @method addLayer(layer: Layer): this\n\t// Adds the given layer to the map\n\taddLayer: function (layer) {\n\t\tif (!layer._layerAdd) {\n\t\t\tthrow new Error('The provided object is not a Layer.');\n\t\t}\n\n\t\tvar id = Util.stamp(layer);\n\t\tif (this._layers[id]) { return this; }\n\t\tthis._layers[id] = layer;\n\n\t\tlayer._mapToAdd = this;\n\n\t\tif (layer.beforeAdd) {\n\t\t\tlayer.beforeAdd(this);\n\t\t}\n\n\t\tthis.whenReady(layer._layerAdd, layer);\n\n\t\treturn this;\n\t},\n\n\t// @method removeLayer(layer: Layer): this\n\t// Removes the given layer from the map.\n\tremoveLayer: function (layer) {\n\t\tvar id = Util.stamp(layer);\n\n\t\tif (!this._layers[id]) { return this; }\n\n\t\tif (this._loaded) {\n\t\t\tlayer.onRemove(this);\n\t\t}\n\n\t\tdelete this._layers[id];\n\n\t\tif (this._loaded) {\n\t\t\tthis.fire('layerremove', {layer: layer});\n\t\t\tlayer.fire('remove');\n\t\t}\n\n\t\tlayer._map = layer._mapToAdd = null;\n\n\t\treturn this;\n\t},\n\n\t// @method hasLayer(layer: Layer): Boolean\n\t// Returns `true` if the given layer is currently added to the map\n\thasLayer: function (layer) {\n\t\treturn Util.stamp(layer) in this._layers;\n\t},\n\n\t/* @method eachLayer(fn: Function, context?: Object): this\n\t * Iterates over the layers of the map, optionally specifying context of the iterator function.\n\t * ```\n\t * map.eachLayer(function(layer){\n\t *     layer.bindPopup('Hello');\n\t * });\n\t * ```\n\t */\n\teachLayer: function (method, context) {\n\t\tfor (var i in this._layers) {\n\t\t\tmethod.call(context, this._layers[i]);\n\t\t}\n\t\treturn this;\n\t},\n\n\t_addLayers: function (layers) {\n\t\tlayers = layers ? (Util.isArray(layers) ? layers : [layers]) : [];\n\n\t\tfor (var i = 0, len = layers.length; i < len; i++) {\n\t\t\tthis.addLayer(layers[i]);\n\t\t}\n\t},\n\n\t_addZoomLimit: function (layer) {\n\t\tif (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {\n\t\t\tthis._zoomBoundLayers[Util.stamp(layer)] = layer;\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_removeZoomLimit: function (layer) {\n\t\tvar id = Util.stamp(layer);\n\n\t\tif (this._zoomBoundLayers[id]) {\n\t\t\tdelete this._zoomBoundLayers[id];\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_updateZoomLevels: function () {\n\t\tvar minZoom = Infinity,\n\t\t    maxZoom = -Infinity,\n\t\t    oldZoomSpan = this._getZoomSpan();\n\n\t\tfor (var i in this._zoomBoundLayers) {\n\t\t\tvar options = this._zoomBoundLayers[i].options;\n\n\t\t\tminZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);\n\t\t\tmaxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);\n\t\t}\n\n\t\tthis._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;\n\t\tthis._layersMinZoom = minZoom === Infinity ? undefined : minZoom;\n\n\t\t// @section Map state change events\n\t\t// @event zoomlevelschange: Event\n\t\t// Fired when the number of zoomlevels on the map is changed due\n\t\t// to adding or removing a layer.\n\t\tif (oldZoomSpan !== this._getZoomSpan()) {\n\t\t\tthis.fire('zoomlevelschange');\n\t\t}\n\n\t\tif (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {\n\t\t\tthis.setZoom(this._layersMaxZoom);\n\t\t}\n\t\tif (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {\n\t\t\tthis.setZoom(this._layersMinZoom);\n\t\t}\n\t}\n});\n", "\r\nimport {Layer} from './Layer';\r\nimport * as Util from '../core/Util';\r\n\r\n/*\r\n * @class LayerGroup\r\n * @aka L.LayerGroup\r\n * @inherits Interactive layer\r\n *\r\n * Used to group several layers and handle them as one. If you add it to the map,\r\n * any layers added or removed from the group will be added/removed on the map as\r\n * well. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.layerGroup([marker1, marker2])\r\n * \t.addLayer(polyline)\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nexport var LayerGroup = Layer.extend({\r\n\r\n\tinitialize: function (layers, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tvar i, len;\r\n\r\n\t\tif (layers) {\r\n\t\t\tfor (i = 0, len = layers.length; i < len; i++) {\r\n\t\t\t\tthis.addLayer(layers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addLayer(layer: Layer): this\r\n\t// Adds the given layer to the group.\r\n\taddLayer: function (layer) {\r\n\t\tvar id = this.getLayerId(layer);\r\n\r\n\t\tthis._layers[id] = layer;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._map.addLayer(layer);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Removes the given layer from the group.\r\n\t// @alternative\r\n\t// @method removeLayer(id: Number): this\r\n\t// Removes the layer with the given internal ID from the group.\r\n\tremoveLayer: function (layer) {\r\n\t\tvar id = layer in this._layers ? layer : this.getLayerId(layer);\r\n\r\n\t\tif (this._map && this._layers[id]) {\r\n\t\t\tthis._map.removeLayer(this._layers[id]);\r\n\t\t}\r\n\r\n\t\tdelete this._layers[id];\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method hasLayer(layer: Layer): Boolean\r\n\t// Returns `true` if the given layer is currently added to the group.\r\n\t// @alternative\r\n\t// @method hasLayer(id: Number): Boolean\r\n\t// Returns `true` if the given internal ID is currently added to the group.\r\n\thasLayer: function (layer) {\r\n\t\tvar layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);\r\n\t\treturn layerId in this._layers;\r\n\t},\r\n\r\n\t// @method clearLayers(): this\r\n\t// Removes all the layers from the group.\r\n\tclearLayers: function () {\r\n\t\treturn this.eachLayer(this.removeLayer, this);\r\n\t},\r\n\r\n\t// @method invoke(methodName: String, …): this\r\n\t// Calls `methodName` on every layer contained in this group, passing any\r\n\t// additional parameters. Has no effect if the layers contained do not\r\n\t// implement `methodName`.\r\n\tinvoke: function (methodName) {\r\n\t\tvar args = Array.prototype.slice.call(arguments, 1),\r\n\t\t    i, layer;\r\n\r\n\t\tfor (i in this._layers) {\r\n\t\t\tlayer = this._layers[i];\r\n\r\n\t\t\tif (layer[methodName]) {\r\n\t\t\t\tlayer[methodName].apply(layer, args);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis.eachLayer(map.addLayer, map);\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tthis.eachLayer(map.removeLayer, map);\r\n\t},\r\n\r\n\t// @method eachLayer(fn: Function, context?: Object): this\r\n\t// Iterates over the layers of the group, optionally specifying context of the iterator function.\r\n\t// ```js\r\n\t// group.eachLayer(function (layer) {\r\n\t// \tlayer.bindPopup('Hello');\r\n\t// });\r\n\t// ```\r\n\teachLayer: function (method, context) {\r\n\t\tfor (var i in this._layers) {\r\n\t\t\tmethod.call(context, this._layers[i]);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getLayer(id: Number): Layer\r\n\t// Returns the layer with the given internal ID.\r\n\tgetLayer: function (id) {\r\n\t\treturn this._layers[id];\r\n\t},\r\n\r\n\t// @method getLayers(): Layer[]\r\n\t// Returns an array of all the layers added to the group.\r\n\tgetLayers: function () {\r\n\t\tvar layers = [];\r\n\t\tthis.eachLayer(layers.push, layers);\r\n\t\treturn layers;\r\n\t},\r\n\r\n\t// @method setZIndex(zIndex: Number): this\r\n\t// Calls `setZIndex` on every layer contained in this group, passing the z-index.\r\n\tsetZIndex: function (zIndex) {\r\n\t\treturn this.invoke('setZIndex', zIndex);\r\n\t},\r\n\r\n\t// @method getLayerId(layer: Layer): Number\r\n\t// Returns the internal ID for a layer\r\n\tgetLayerId: function (layer) {\r\n\t\treturn Util.stamp(layer);\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.layerGroup(layers?: Layer[], options?: Object)\r\n// Create a layer group, optionally given an initial set of layers and an `options` object.\r\nexport var layerGroup = function (layers, options) {\r\n\treturn new LayerGroup(layers, options);\r\n};\r\n", "import {LayerGroup} from './LayerGroup';\r\nimport {LatLngBounds} from '../geo/LatLngBounds';\r\n\r\n/*\r\n * @class FeatureGroup\r\n * @aka L.FeatureGroup\r\n * @inherits LayerGroup\r\n *\r\n * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:\r\n *  * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))\r\n *  * Events are propagated to the `FeatureGroup`, so if the group has an event\r\n * handler, it will handle events from any of the layers. This includes mouse events\r\n * and custom events.\r\n *  * Has `layeradd` and `layerremove` events\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.featureGroup([marker1, marker2, polyline])\r\n * \t.bindPopup('Hello world!')\r\n * \t.on('click', function() { alert('Clicked on a member of the group!'); })\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nexport var FeatureGroup = LayerGroup.extend({\r\n\r\n\taddLayer: function (layer) {\r\n\t\tif (this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tlayer.addEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.addLayer.call(this, layer);\r\n\r\n\t\t// @event layeradd: LayerEvent\r\n\t\t// Fired when a layer is added to this `FeatureGroup`\r\n\t\treturn this.fire('layeradd', {layer: layer});\r\n\t},\r\n\r\n\tremoveLayer: function (layer) {\r\n\t\tif (!this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tif (layer in this._layers) {\r\n\t\t\tlayer = this._layers[layer];\r\n\t\t}\r\n\r\n\t\tlayer.removeEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.removeLayer.call(this, layer);\r\n\r\n\t\t// @event layerremove: LayerEvent\r\n\t\t// Fired when a layer is removed from this `FeatureGroup`\r\n\t\treturn this.fire('layerremove', {layer: layer});\r\n\t},\r\n\r\n\t// @method setStyle(style: Path options): this\r\n\t// Sets the given path options to each layer of the group that has a `setStyle` method.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.invoke('setStyle', style);\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer group to the top of all other layers\r\n\tbringToFront: function () {\r\n\t\treturn this.invoke('bringToFront');\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer group to the back of all other layers\r\n\tbringToBack: function () {\r\n\t\treturn this.invoke('bringToBack');\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).\r\n\tgetBounds: function () {\r\n\t\tvar bounds = new LatLngBounds();\r\n\r\n\t\tfor (var id in this._layers) {\r\n\t\t\tvar layer = this._layers[id];\r\n\t\t\tbounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());\r\n\t\t}\r\n\t\treturn bounds;\r\n\t}\r\n});\r\n\r\n// @factory L.featureGroup(layers?: Layer[], options?: Object)\r\n// Create a feature group, optionally given an initial set of layers and an `options` object.\r\nexport var featureGroup = function (layers, options) {\r\n\treturn new FeatureGroup(layers, options);\r\n};\r\n", "import {Class} from '../../core/Class';\r\nimport {setOptions} from '../../core/Util';\r\nimport {toPoint as point} from '../../geometry/Point';\r\nimport Browser from '../../core/Browser';\r\n\r\n/*\r\n * @class Icon\r\n * @aka L.Icon\r\n *\r\n * Represents an icon to provide when creating a marker.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var myIcon = L.icon({\r\n *     iconUrl: 'my-icon.png',\r\n *     iconRetinaUrl: 'my-icon@2x.png',\r\n *     iconSize: [38, 95],\r\n *     iconAnchor: [22, 94],\r\n *     popupAnchor: [-3, -76],\r\n *     shadowUrl: 'my-icon-shadow.png',\r\n *     shadowRetinaUrl: 'my-icon-shadow@2x.png',\r\n *     shadowSize: [68, 95],\r\n *     shadowAnchor: [22, 94]\r\n * });\r\n *\r\n * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);\r\n * ```\r\n *\r\n * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.\r\n *\r\n */\r\n\r\nexport var Icon = Class.extend({\r\n\r\n\t/* @section\r\n\t * @aka Icon options\r\n\t *\r\n\t * @option iconUrl: String = null\r\n\t * **(required)** The URL to the icon image (absolute or relative to your script path).\r\n\t *\r\n\t * @option iconRetinaUrl: String = null\r\n\t * The URL to a retina sized version of the icon image (absolute or relative to your\r\n\t * script path). Used for Retina screen devices.\r\n\t *\r\n\t * @option iconSize: Point = null\r\n\t * Size of the icon image in pixels.\r\n\t *\r\n\t * @option iconAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the icon (relative to its top left corner). The icon\r\n\t * will be aligned so that this point is at the marker's geographical location. Centered\r\n\t * by default if size is specified, also can be set in CSS with negative margins.\r\n\t *\r\n\t * @option popupAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which popups will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option tooltipAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which tooltips will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option shadowUrl: String = null\r\n\t * The URL to the icon shadow image. If not specified, no shadow image will be created.\r\n\t *\r\n\t * @option shadowRetinaUrl: String = null\r\n\t *\r\n\t * @option shadowSize: Point = null\r\n\t * Size of the shadow image in pixels.\r\n\t *\r\n\t * @option shadowAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the shadow (relative to its top left corner) (the same\r\n\t * as iconAnchor if not specified).\r\n\t *\r\n\t * @option className: String = ''\r\n\t * A custom class name to assign to both icon and shadow images. Empty by default.\r\n\t */\r\n\r\n\toptions: {\r\n\t\tpopupAnchor: [0, 0],\r\n\t\ttooltipAnchor: [0, 0],\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the tiles.\r\n\t\t// If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\t// @method createIcon(oldIcon?: HTMLElement): HTMLElement\r\n\t// Called internally when the icon has to be shown, returns a `<img>` HTML element\r\n\t// styled according to the options.\r\n\tcreateIcon: function (oldIcon) {\r\n\t\treturn this._createIcon('icon', oldIcon);\r\n\t},\r\n\r\n\t// @method createShadow(oldIcon?: HTMLElement): HTMLElement\r\n\t// As `createIcon`, but for the shadow beneath it.\r\n\tcreateShadow: function (oldIcon) {\r\n\t\treturn this._createIcon('shadow', oldIcon);\r\n\t},\r\n\r\n\t_createIcon: function (name, oldIcon) {\r\n\t\tvar src = this._getIconUrl(name);\r\n\r\n\t\tif (!src) {\r\n\t\t\tif (name === 'icon') {\r\n\t\t\t\tthrow new Error('iconUrl not set in Icon options (see the docs).');\r\n\t\t\t}\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tvar img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);\r\n\t\tthis._setIconStyles(img, name);\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\timg.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\treturn img;\r\n\t},\r\n\r\n\t_setIconStyles: function (img, name) {\r\n\t\tvar options = this.options;\r\n\t\tvar sizeOption = options[name + 'Size'];\r\n\r\n\t\tif (typeof sizeOption === 'number') {\r\n\t\t\tsizeOption = [sizeOption, sizeOption];\r\n\t\t}\r\n\r\n\t\tvar size = point(sizeOption),\r\n\t\t    anchor = point(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||\r\n\t\t            size && size.divideBy(2, true));\r\n\r\n\t\timg.className = 'leaflet-marker-' + name + ' ' + (options.className || '');\r\n\r\n\t\tif (anchor) {\r\n\t\t\timg.style.marginLeft = (-anchor.x) + 'px';\r\n\t\t\timg.style.marginTop  = (-anchor.y) + 'px';\r\n\t\t}\r\n\r\n\t\tif (size) {\r\n\t\t\timg.style.width  = size.x + 'px';\r\n\t\t\timg.style.height = size.y + 'px';\r\n\t\t}\r\n\t},\r\n\r\n\t_createImg: function (src, el) {\r\n\t\tel = el || document.createElement('img');\r\n\t\tel.src = src;\r\n\t\treturn el;\r\n\t},\r\n\r\n\t_getIconUrl: function (name) {\r\n\t\treturn Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.icon(options: Icon options)\r\n// Creates an icon instance with the given options.\r\nexport function icon(options) {\r\n\treturn new Icon(options);\r\n}\r\n", "import {Icon} from './Icon';\nimport * as DomUtil from '../../dom/DomUtil';\n\n/*\n * @miniclass Icon.Default (Icon)\n * @aka L.Icon.Default\n * @section\n *\n * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when\n * no icon is specified. Points to the blue marker image distributed with Leaflet\n * releases.\n *\n * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`\n * (which is a set of `Icon options`).\n *\n * If you want to _completely_ replace the default icon, override the\n * `L.Marker.prototype.options.icon` with your own icon instead.\n */\n\nexport var IconDefault = Icon.extend({\n\n\toptions: {\n\t\ticonUrl:       'marker-icon.png',\n\t\ticonRetinaUrl: 'marker-icon-2x.png',\n\t\tshadowUrl:     'marker-shadow.png',\n\t\ticonSize:    [25, 41],\n\t\ticonAnchor:  [12, 41],\n\t\tpopupAnchor: [1, -34],\n\t\ttooltipAnchor: [16, -28],\n\t\tshadowSize:  [41, 41]\n\t},\n\n\t_getIconUrl: function (name) {\n\t\tif (typeof IconDefault.imagePath !== 'string') {\t// Deprecated, backwards-compatibility only\n\t\t\tIconDefault.imagePath = this._detectIconPath();\n\t\t}\n\n\t\t// @option imagePath: String\n\t\t// `Icon.Default` will try to auto-detect the location of the\n\t\t// blue icon images. If you are placing these images in a non-standard\n\t\t// way, set this option to point to the right path.\n\t\treturn (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);\n\t},\n\n\t_stripUrl: function (path) {\t// separate function to use in tests\n\t\tvar strip = function (str, re, idx) {\n\t\t\tvar match = re.exec(str);\n\t\t\treturn match && match[idx];\n\t\t};\n\t\tpath = strip(path, /^url\\((['\"])?(.+)\\1\\)$/, 2);\n\t\treturn path && strip(path, /^(.*)marker-icon\\.png$/, 1);\n\t},\n\n\t_detectIconPath: function () {\n\t\tvar el = DomUtil.create('div',  'leaflet-default-icon-path', document.body);\n\t\tvar path = DomUtil.getStyle(el, 'background-image') ||\n\t\t           DomUtil.getStyle(el, 'backgroundImage');\t// IE8\n\n\t\tdocument.body.removeChild(el);\n\t\tpath = this._stripUrl(path);\n\t\tif (path) { return path; }\n\t\tvar link = document.querySelector('link[href$=\"leaflet.css\"]');\n\t\tif (!link) { return ''; }\n\t\treturn link.href.substring(0, link.href.length - 'leaflet.css'.length - 1);\n\t}\n});\n", "import {Handler} from '../../core/Handler';\nimport * as DomUtil from '../../dom/DomUtil';\nimport {Draggable} from '../../dom/Draggable';\nimport {toBounds} from '../../geometry/Bounds';\nimport {toPoint} from '../../geometry/Point';\nimport {requestAnimFrame, cancelAnimFrame} from '../../core/Util';\n\n/*\n * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.\n */\n\n\n/* @namespace Marker\n * @section Interaction handlers\n *\n * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:\n *\n * ```js\n * marker.dragging.disable();\n * ```\n *\n * @property dragging: Handler\n * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).\n */\n\nexport var MarkerDrag = Handler.extend({\n\tinitialize: function (marker) {\n\t\tthis._marker = marker;\n\t},\n\n\taddHooks: function () {\n\t\tvar icon = this._marker._icon;\n\n\t\tif (!this._draggable) {\n\t\t\tthis._draggable = new Draggable(icon, icon, true);\n\t\t}\n\n\t\tthis._draggable.on({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).enable();\n\n\t\tDomUtil.addClass(icon, 'leaflet-marker-draggable');\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._draggable.off({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).disable();\n\n\t\tif (this._marker._icon) {\n\t\t\tDomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');\n\t\t}\n\t},\n\n\tmoved: function () {\n\t\treturn this._draggable && this._draggable._moved;\n\t},\n\n\t_adjustPan: function (e) {\n\t\tvar marker = this._marker,\n\t\t    map = marker._map,\n\t\t    speed = this._marker.options.autoPanSpeed,\n\t\t    padding = this._marker.options.autoPanPadding,\n\t\t    iconPos = DomUtil.getPosition(marker._icon),\n\t\t    bounds = map.getPixelBounds(),\n\t\t    origin = map.getPixelOrigin();\n\n\t\tvar panBounds = toBounds(\n\t\t\tbounds.min._subtract(origin).add(padding),\n\t\t\tbounds.max._subtract(origin).subtract(padding)\n\t\t);\n\n\t\tif (!panBounds.contains(iconPos)) {\n\t\t\t// Compute incremental movement\n\t\t\tvar movement = toPoint(\n\t\t\t\t(Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -\n\t\t\t\t(Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),\n\n\t\t\t\t(Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -\n\t\t\t\t(Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)\n\t\t\t).multiplyBy(speed);\n\n\t\t\tmap.panBy(movement, {animate: false});\n\n\t\t\tthis._draggable._newPos._add(movement);\n\t\t\tthis._draggable._startPos._add(movement);\n\n\t\t\tDomUtil.setPosition(marker._icon, this._draggable._newPos);\n\t\t\tthis._onDrag(e);\n\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDragStart: function () {\n\t\t// @section Dragging events\n\t\t// @event dragstart: Event\n\t\t// Fired when the user starts dragging the marker.\n\n\t\t// @event movestart: Event\n\t\t// Fired when the marker starts moving (because of dragging).\n\n\t\tthis._oldLatLng = this._marker.getLatLng();\n\n\t\t// When using ES6 imports it could not be set when `Popup` was not imported as well\n\t\tthis._marker.closePopup && this._marker.closePopup();\n\n\t\tthis._marker\n\t\t\t.fire('movestart')\n\t\t\t.fire('dragstart');\n\t},\n\n\t_onPreDrag: function (e) {\n\t\tif (this._marker.options.autoPan) {\n\t\t\tcancelAnimFrame(this._panRequest);\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDrag: function (e) {\n\t\tvar marker = this._marker,\n\t\t    shadow = marker._shadow,\n\t\t    iconPos = DomUtil.getPosition(marker._icon),\n\t\t    latlng = marker._map.layerPointToLatLng(iconPos);\n\n\t\t// update shadow position\n\t\tif (shadow) {\n\t\t\tDomUtil.setPosition(shadow, iconPos);\n\t\t}\n\n\t\tmarker._latlng = latlng;\n\t\te.latlng = latlng;\n\t\te.oldLatLng = this._oldLatLng;\n\n\t\t// @event drag: Event\n\t\t// Fired repeatedly while the user drags the marker.\n\t\tmarker\n\t\t    .fire('move', e)\n\t\t    .fire('drag', e);\n\t},\n\n\t_onDragEnd: function (e) {\n\t\t// @event dragend: DragEndEvent\n\t\t// Fired when the user stops dragging the marker.\n\n\t\t cancelAnimFrame(this._panRequest);\n\n\t\t// @event moveend: Event\n\t\t// Fired when the marker stops moving (because of dragging).\n\t\tdelete this._oldLatLng;\n\t\tthis._marker\n\t\t    .fire('moveend')\n\t\t    .fire('dragend', e);\n\t}\n});\n", "import {Layer} from '../Layer';\r\nimport {IconDefault} from './Icon.Default';\r\nimport * as Util from '../../core/Util';\r\nimport {toLatLng as latLng} from '../../geo/LatLng';\r\nimport {toPoint as point} from '../../geometry/Point';\r\nimport * as DomUtil from '../../dom/DomUtil';\r\nimport * as DomEvent from '../../dom/DomEvent';\r\nimport {MarkerDrag} from './Marker.Drag';\r\n\r\n/*\r\n * @class Marker\r\n * @inherits Interactive layer\r\n * @aka L.Marker\r\n * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.marker([50.5, 30.5]).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var Marker = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka Marker options\r\n\toptions: {\r\n\t\t// @option icon: Icon = *\r\n\t\t// Icon instance to use for rendering the marker.\r\n\t\t// See [Icon documentation](#L.Icon) for details on how to customize the marker icon.\r\n\t\t// If not specified, a common instance of `L.Icon.Default` is used.\r\n\t\ticon: new IconDefault(),\r\n\r\n\t\t// Option inherited from \"Interactive layer\" abstract class\r\n\t\tinteractive: true,\r\n\r\n\t\t// @option keyboard: Boolean = true\r\n\t\t// Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.\r\n\t\tkeyboard: true,\r\n\r\n\t\t// @option title: String = ''\r\n\t\t// Text for the browser tooltip that appear on marker hover (no tooltip by default).\r\n\t\t// [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).\r\n\t\ttitle: '',\r\n\r\n\t\t// @option alt: String = 'Marker'\r\n\t\t// Text for the `alt` attribute of the icon image.\r\n\t\t// [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).\r\n\t\talt: 'Marker',\r\n\r\n\t\t// @option zIndexOffset: Number = 0\r\n\t\t// By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).\r\n\t\tzIndexOffset: 0,\r\n\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the marker.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option riseOnHover: Boolean = false\r\n\t\t// If `true`, the marker will get on top of others when you hover the mouse over it.\r\n\t\triseOnHover: false,\r\n\r\n\t\t// @option riseOffset: Number = 250\r\n\t\t// The z-index offset used for the `riseOnHover` feature.\r\n\t\triseOffset: 250,\r\n\r\n\t\t// @option pane: String = 'markerPane'\r\n\t\t// `Map pane` where the markers icon will be added.\r\n\t\tpane: 'markerPane',\r\n\r\n\t\t// @option shadowPane: String = 'shadowPane'\r\n\t\t// `Map pane` where the markers shadow will be added.\r\n\t\tshadowPane: 'shadowPane',\r\n\r\n\t\t// @option bubblingMouseEvents: Boolean = false\r\n\t\t// When `true`, a mouse event on this marker will trigger the same event on the map\r\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\r\n\t\tbubblingMouseEvents: false,\r\n\r\n\t\t// @option autoPanOnFocus: Boolean = true\r\n\t\t// When `true`, the map will pan whenever the marker is focused (via\r\n\t\t// e.g. pressing `tab` on the keyboard) to ensure the marker is\r\n\t\t// visible within the map's bounds\r\n\t\tautoPanOnFocus: true,\r\n\r\n\t\t// @section Draggable marker options\r\n\t\t// @option draggable: Boolean = false\r\n\t\t// Whether the marker is draggable with mouse/touch or not.\r\n\t\tdraggable: false,\r\n\r\n\t\t// @option autoPan: Boolean = false\r\n\t\t// Whether to pan the map when dragging this marker near its edge or not.\r\n\t\tautoPan: false,\r\n\r\n\t\t// @option autoPanPadding: Point = Point(50, 50)\r\n\t\t// Distance (in pixels to the left/right and to the top/bottom) of the\r\n\t\t// map edge to start panning the map.\r\n\t\tautoPanPadding: [50, 50],\r\n\r\n\t\t// @option autoPanSpeed: Number = 10\r\n\t\t// Number of pixels the map should pan by.\r\n\t\tautoPanSpeed: 10\r\n\t},\r\n\r\n\t/* @section\r\n\t *\r\n\t * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:\r\n\t */\r\n\r\n\tinitialize: function (latlng, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\t\tthis._latlng = latLng(latlng);\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.on('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._initIcon();\r\n\t\tthis.update();\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tif (this.dragging && this.dragging.enabled()) {\r\n\t\t\tthis.options.draggable = true;\r\n\t\t\tthis.dragging.removeHooks();\r\n\t\t}\r\n\t\tdelete this.dragging;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.off('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._removeIcon();\r\n\t\tthis._removeShadow();\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\treturn {\r\n\t\t\tzoom: this.update,\r\n\t\t\tviewreset: this.update\r\n\t\t};\r\n\t},\r\n\r\n\t// @method getLatLng: LatLng\r\n\t// Returns the current geographical position of the marker.\r\n\tgetLatLng: function () {\r\n\t\treturn this._latlng;\r\n\t},\r\n\r\n\t// @method setLatLng(latlng: LatLng): this\r\n\t// Changes the marker position to the given point.\r\n\tsetLatLng: function (latlng) {\r\n\t\tvar oldLatLng = this._latlng;\r\n\t\tthis._latlng = latLng(latlng);\r\n\t\tthis.update();\r\n\r\n\t\t// @event move: Event\r\n\t\t// Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.\r\n\t\treturn this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});\r\n\t},\r\n\r\n\t// @method setZIndexOffset(offset: Number): this\r\n\t// Changes the [zIndex offset](#marker-zindexoffset) of the marker.\r\n\tsetZIndexOffset: function (offset) {\r\n\t\tthis.options.zIndexOffset = offset;\r\n\t\treturn this.update();\r\n\t},\r\n\r\n\t// @method getIcon: Icon\r\n\t// Returns the current icon used by the marker\r\n\tgetIcon: function () {\r\n\t\treturn this.options.icon;\r\n\t},\r\n\r\n\t// @method setIcon(icon: Icon): this\r\n\t// Changes the marker icon.\r\n\tsetIcon: function (icon) {\r\n\r\n\t\tthis.options.icon = icon;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._initIcon();\r\n\t\t\tthis.update();\r\n\t\t}\r\n\r\n\t\tif (this._popup) {\r\n\t\t\tthis.bindPopup(this._popup, this._popup.options);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetElement: function () {\r\n\t\treturn this._icon;\r\n\t},\r\n\r\n\tupdate: function () {\r\n\r\n\t\tif (this._icon && this._map) {\r\n\t\t\tvar pos = this._map.latLngToLayerPoint(this._latlng).round();\r\n\t\t\tthis._setPos(pos);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initIcon: function () {\r\n\t\tvar options = this.options,\r\n\t\t    classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');\r\n\r\n\t\tvar icon = options.icon.createIcon(this._icon),\r\n\t\t    addIcon = false;\r\n\r\n\t\t// if we're not reusing the icon, remove the old one and init new one\r\n\t\tif (icon !== this._icon) {\r\n\t\t\tif (this._icon) {\r\n\t\t\t\tthis._removeIcon();\r\n\t\t\t}\r\n\t\t\taddIcon = true;\r\n\r\n\t\t\tif (options.title) {\r\n\t\t\t\ticon.title = options.title;\r\n\t\t\t}\r\n\r\n\t\t\tif (icon.tagName === 'IMG') {\r\n\t\t\t\ticon.alt = options.alt || '';\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tDomUtil.addClass(icon, classToAdd);\r\n\r\n\t\tif (options.keyboard) {\r\n\t\t\ticon.tabIndex = '0';\r\n\t\t\ticon.setAttribute('role', 'button');\r\n\t\t}\r\n\r\n\t\tthis._icon = icon;\r\n\r\n\t\tif (options.riseOnHover) {\r\n\t\t\tthis.on({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tif (this.options.autoPanOnFocus) {\r\n\t\t\tDomEvent.on(icon, 'focus', this._panOnFocus, this);\r\n\t\t}\r\n\r\n\t\tvar newShadow = options.icon.createShadow(this._shadow),\r\n\t\t    addShadow = false;\r\n\r\n\t\tif (newShadow !== this._shadow) {\r\n\t\t\tthis._removeShadow();\r\n\t\t\taddShadow = true;\r\n\t\t}\r\n\r\n\t\tif (newShadow) {\r\n\t\t\tDomUtil.addClass(newShadow, classToAdd);\r\n\t\t\tnewShadow.alt = '';\r\n\t\t}\r\n\t\tthis._shadow = newShadow;\r\n\r\n\r\n\t\tif (options.opacity < 1) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\r\n\t\tif (addIcon) {\r\n\t\t\tthis.getPane().appendChild(this._icon);\r\n\t\t}\r\n\t\tthis._initInteraction();\r\n\t\tif (newShadow && addShadow) {\r\n\t\t\tthis.getPane(options.shadowPane).appendChild(this._shadow);\r\n\t\t}\r\n\t},\r\n\r\n\t_removeIcon: function () {\r\n\t\tif (this.options.riseOnHover) {\r\n\t\t\tthis.off({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tif (this.options.autoPanOnFocus) {\r\n\t\t\tDomEvent.off(this._icon, 'focus', this._panOnFocus, this);\r\n\t\t}\r\n\r\n\t\tDomUtil.remove(this._icon);\r\n\t\tthis.removeInteractiveTarget(this._icon);\r\n\r\n\t\tthis._icon = null;\r\n\t},\r\n\r\n\t_removeShadow: function () {\r\n\t\tif (this._shadow) {\r\n\t\t\tDomUtil.remove(this._shadow);\r\n\t\t}\r\n\t\tthis._shadow = null;\r\n\t},\r\n\r\n\t_setPos: function (pos) {\r\n\r\n\t\tif (this._icon) {\r\n\t\t\tDomUtil.setPosition(this._icon, pos);\r\n\t\t}\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tDomUtil.setPosition(this._shadow, pos);\r\n\t\t}\r\n\r\n\t\tthis._zIndex = pos.y + this.options.zIndexOffset;\r\n\r\n\t\tthis._resetZIndex();\r\n\t},\r\n\r\n\t_updateZIndex: function (offset) {\r\n\t\tif (this._icon) {\r\n\t\t\tthis._icon.style.zIndex = this._zIndex + offset;\r\n\t\t}\r\n\t},\r\n\r\n\t_animateZoom: function (opt) {\r\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();\r\n\r\n\t\tthis._setPos(pos);\r\n\t},\r\n\r\n\t_initInteraction: function () {\r\n\r\n\t\tif (!this.options.interactive) { return; }\r\n\r\n\t\tDomUtil.addClass(this._icon, 'leaflet-interactive');\r\n\r\n\t\tthis.addInteractiveTarget(this._icon);\r\n\r\n\t\tif (MarkerDrag) {\r\n\t\t\tvar draggable = this.options.draggable;\r\n\t\t\tif (this.dragging) {\r\n\t\t\t\tdraggable = this.dragging.enabled();\r\n\t\t\t\tthis.dragging.disable();\r\n\t\t\t}\r\n\r\n\t\t\tthis.dragging = new MarkerDrag(this);\r\n\r\n\t\t\tif (draggable) {\r\n\t\t\t\tthis.dragging.enable();\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Changes the opacity of the marker.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\t\tif (this._map) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tvar opacity = this.options.opacity;\r\n\r\n\t\tif (this._icon) {\r\n\t\t\tDomUtil.setOpacity(this._icon, opacity);\r\n\t\t}\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tDomUtil.setOpacity(this._shadow, opacity);\r\n\t\t}\r\n\t},\r\n\r\n\t_bringToFront: function () {\r\n\t\tthis._updateZIndex(this.options.riseOffset);\r\n\t},\r\n\r\n\t_resetZIndex: function () {\r\n\t\tthis._updateZIndex(0);\r\n\t},\r\n\r\n\t_panOnFocus: function () {\r\n\t\tvar map = this._map;\r\n\t\tif (!map) { return; }\r\n\r\n\t\tvar iconOpts = this.options.icon.options;\r\n\t\tvar size = iconOpts.iconSize ? point(iconOpts.iconSize) : point(0, 0);\r\n\t\tvar anchor = iconOpts.iconAnchor ? point(iconOpts.iconAnchor) : point(0, 0);\r\n\r\n\t\tmap.panInside(this._latlng, {\r\n\t\t\tpaddingTopLeft: anchor,\r\n\t\t\tpaddingBottomRight: size.subtract(anchor)\r\n\t\t});\r\n\t},\r\n\r\n\t_getPopupAnchor: function () {\r\n\t\treturn this.options.icon.options.popupAnchor;\r\n\t},\r\n\r\n\t_getTooltipAnchor: function () {\r\n\t\treturn this.options.icon.options.tooltipAnchor;\r\n\t}\r\n});\r\n\r\n\r\n// factory L.marker(latlng: LatLng, options? : Marker options)\r\n\r\n// @factory L.marker(latlng: LatLng, options? : Marker options)\r\n// Instantiates a Marker object given a geographical point and optionally an options object.\r\nexport function marker(latlng, options) {\r\n\treturn new Marker(latlng, options);\r\n}\r\n", "import {Layer} from '../Layer';\nimport * as Util from '../../core/Util';\n\n/*\n * @class Path\n * @aka L.Path\n * @inherits Interactive layer\n *\n * An abstract class that contains options and constants shared between vector\n * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.\n */\n\nexport var Path = Layer.extend({\n\n\t// @section\n\t// @aka Path options\n\toptions: {\n\t\t// @option stroke: Boolean = true\n\t\t// Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.\n\t\tstroke: true,\n\n\t\t// @option color: String = '#3388ff'\n\t\t// Stroke color\n\t\tcolor: '#3388ff',\n\n\t\t// @option weight: Number = 3\n\t\t// Stroke width in pixels\n\t\tweight: 3,\n\n\t\t// @option opacity: Number = 1.0\n\t\t// Stroke opacity\n\t\topacity: 1,\n\n\t\t// @option lineCap: String= 'round'\n\t\t// A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.\n\t\tlineCap: 'round',\n\n\t\t// @option lineJoin: String = 'round'\n\t\t// A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.\n\t\tlineJoin: 'round',\n\n\t\t// @option dashArray: String = null\n\t\t// A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashArray: null,\n\n\t\t// @option dashOffset: String = null\n\t\t// A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashOffset: null,\n\n\t\t// @option fill: Boolean = depends\n\t\t// Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.\n\t\tfill: false,\n\n\t\t// @option fillColor: String = *\n\t\t// Fill color. Defaults to the value of the [`color`](#path-color) option\n\t\tfillColor: null,\n\n\t\t// @option fillOpacity: Number = 0.2\n\t\t// Fill opacity.\n\t\tfillOpacity: 0.2,\n\n\t\t// @option fillRule: String = 'evenodd'\n\t\t// A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.\n\t\tfillRule: 'evenodd',\n\n\t\t// className: '',\n\n\t\t// Option inherited from \"Interactive layer\" abstract class\n\t\tinteractive: true,\n\n\t\t// @option bubblingMouseEvents: Boolean = true\n\t\t// When `true`, a mouse event on this path will trigger the same event on the map\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\n\t\tbubblingMouseEvents: true\n\t},\n\n\tbeforeAdd: function (map) {\n\t\t// Renderer is set here because we need to call renderer.getEvents\n\t\t// before this.getEvents.\n\t\tthis._renderer = map.getRenderer(this);\n\t},\n\n\tonAdd: function () {\n\t\tthis._renderer._initPath(this);\n\t\tthis._reset();\n\t\tthis._renderer._addPath(this);\n\t},\n\n\tonRemove: function () {\n\t\tthis._renderer._removePath(this);\n\t},\n\n\t// @method redraw(): this\n\t// Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.\n\tredraw: function () {\n\t\tif (this._map) {\n\t\t\tthis._renderer._updatePath(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method setStyle(style: Path options): this\n\t// Changes the appearance of a Path based on the options in the `Path options` object.\n\tsetStyle: function (style) {\n\t\tUtil.setOptions(this, style);\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._updateStyle(this);\n\t\t\tif (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {\n\t\t\t\tthis._updateBounds();\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToFront(): this\n\t// Brings the layer to the top of all path layers.\n\tbringToFront: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToFront(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToBack(): this\n\t// Brings the layer to the bottom of all path layers.\n\tbringToBack: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToBack(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\tgetElement: function () {\n\t\treturn this._path;\n\t},\n\n\t_reset: function () {\n\t\t// defined in child classes\n\t\tthis._project();\n\t\tthis._update();\n\t},\n\n\t_clickTolerance: function () {\n\t\t// used when doing hit detection for Canvas layers\n\t\treturn (this.options.stroke ? this.options.weight / 2 : 0) +\n\t\t  (this._renderer.options.tolerance || 0);\n\t}\n});\n", "import {Path} from './Path';\nimport * as Util from '../../core/Util';\nimport {toLatLng} from '../../geo/LatLng';\nimport {Bounds} from '../../geometry/Bounds';\n\n\n/*\n * @class CircleMarker\n * @aka L.CircleMarker\n * @inherits Path\n *\n * A circle of a fixed size with radius specified in pixels. Extends `Path`.\n */\n\nexport var CircleMarker = Path.extend({\n\n\t// @section\n\t// @aka CircleMarker options\n\toptions: {\n\t\tfill: true,\n\n\t\t// @option radius: Number = 10\n\t\t// Radius of the circle marker, in pixels\n\t\tradius: 10\n\t},\n\n\tinitialize: function (latlng, options) {\n\t\tUtil.setOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis._radius = this.options.radius;\n\t},\n\n\t// @method setLatLng(latLng: LatLng): this\n\t// Sets the position of a circle marker to a new location.\n\tsetLatLng: function (latlng) {\n\t\tvar oldLatLng = this._latlng;\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis.redraw();\n\n\t\t// @event move: Event\n\t\t// Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.\n\t\treturn this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});\n\t},\n\n\t// @method getLatLng(): LatLng\n\t// Returns the current geographical position of the circle marker\n\tgetLatLng: function () {\n\t\treturn this._latlng;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle marker. Units are in pixels.\n\tsetRadius: function (radius) {\n\t\tthis.options.radius = this._radius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of the circle\n\tgetRadius: function () {\n\t\treturn this._radius;\n\t},\n\n\tsetStyle : function (options) {\n\t\tvar radius = options && options.radius || this._radius;\n\t\tPath.prototype.setStyle.call(this, options);\n\t\tthis.setRadius(radius);\n\t\treturn this;\n\t},\n\n\t_project: function () {\n\t\tthis._point = this._map.latLngToLayerPoint(this._latlng);\n\t\tthis._updateBounds();\n\t},\n\n\t_updateBounds: function () {\n\t\tvar r = this._radius,\n\t\t    r2 = this._radiusY || r,\n\t\t    w = this._clickTolerance(),\n\t\t    p = [r + w, r2 + w];\n\t\tthis._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));\n\t},\n\n\t_update: function () {\n\t\tif (this._map) {\n\t\t\tthis._updatePath();\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updateCircle(this);\n\t},\n\n\t_empty: function () {\n\t\treturn this._radius && !this._renderer._bounds.intersects(this._pxBounds);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\treturn p.distanceTo(this._point) <= this._radius + this._clickTolerance();\n\t}\n});\n\n\n// @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)\n// Instantiates a circle marker object given a geographical point, and an optional options object.\nexport function circleMarker(latlng, options) {\n\treturn new CircleMarker(latlng, options);\n}\n", "import {CircleMarker} from './CircleMarker';\nimport {Path} from './Path';\nimport * as Util from '../../core/Util';\nimport {toLatLng} from '../../geo/LatLng';\nimport {LatLngBounds} from '../../geo/LatLngBounds';\nimport {Earth} from '../../geo/crs/CRS.Earth';\n\n\n/*\n * @class Circle\n * @aka L.Circle\n * @inherits CircleMarker\n *\n * A class for drawing circle overlays on a map. Extends `CircleMarker`.\n *\n * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).\n *\n * @example\n *\n * ```js\n * L.circle([50.5, 30.5], {radius: 200}).addTo(map);\n * ```\n */\n\nexport var Circle = CircleMarker.extend({\n\n\tinitialize: function (latlng, options, legacyOptions) {\n\t\tif (typeof options === 'number') {\n\t\t\t// Backwards compatibility with 0.7.x factory (latlng, radius, options?)\n\t\t\toptions = Util.extend({}, legacyOptions, {radius: options});\n\t\t}\n\t\tUtil.setOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\n\t\tif (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }\n\n\t\t// @section\n\t\t// @aka Circle options\n\t\t// @option radius: Number; Radius of the circle, in meters.\n\t\tthis._mRadius = this.options.radius;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle. Units are in meters.\n\tsetRadius: function (radius) {\n\t\tthis._mRadius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of a circle. Units are in meters.\n\tgetRadius: function () {\n\t\treturn this._mRadius;\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\tvar half = [this._radius, this._radiusY || this._radius];\n\n\t\treturn new LatLngBounds(\n\t\t\tthis._map.layerPointToLatLng(this._point.subtract(half)),\n\t\t\tthis._map.layerPointToLatLng(this._point.add(half)));\n\t},\n\n\tsetStyle: Path.prototype.setStyle,\n\n\t_project: function () {\n\n\t\tvar lng = this._latlng.lng,\n\t\t    lat = this._latlng.lat,\n\t\t    map = this._map,\n\t\t    crs = map.options.crs;\n\n\t\tif (crs.distance === Earth.distance) {\n\t\t\tvar d = Math.PI / 180,\n\t\t\t    latR = (this._mRadius / Earth.R) / d,\n\t\t\t    top = map.project([lat + latR, lng]),\n\t\t\t    bottom = map.project([lat - latR, lng]),\n\t\t\t    p = top.add(bottom).divideBy(2),\n\t\t\t    lat2 = map.unproject(p).lat,\n\t\t\t    lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /\n\t\t\t            (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;\n\n\t\t\tif (isNaN(lngR) || lngR === 0) {\n\t\t\t\tlngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425\n\t\t\t}\n\n\t\t\tthis._point = p.subtract(map.getPixelOrigin());\n\t\t\tthis._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;\n\t\t\tthis._radiusY = p.y - top.y;\n\n\t\t} else {\n\t\t\tvar latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));\n\n\t\t\tthis._point = map.latLngToLayerPoint(this._latlng);\n\t\t\tthis._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;\n\t\t}\n\n\t\tthis._updateBounds();\n\t}\n});\n\n// @factory L.circle(latlng: LatLng, options?: Circle options)\n// Instantiates a circle object given a geographical point, and an options object\n// which contains the circle radius.\n// @alternative\n// @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)\n// Obsolete way of instantiating a circle, for compatibility with 0.7.x code.\n// Do not use in new applications or plugins.\nexport function circle(latlng, options, legacyOptions) {\n\treturn new Circle(latlng, options, legacyOptions);\n}\n", "import {Path} from './Path';\nimport * as Util from '../../core/Util';\nimport * as LineUtil from '../../geometry/LineUtil';\nimport {LatLng, toLatLng} from '../../geo/LatLng';\nimport {LatLngBounds} from '../../geo/LatLngBounds';\nimport {Bounds} from '../../geometry/Bounds';\nimport {Point} from '../../geometry/Point';\n\n/*\n * @class Polyline\n * @aka L.Polyline\n * @inherits Path\n *\n * A class for drawing polyline overlays on a map. Extends `Path`.\n *\n * @example\n *\n * ```js\n * // create a red polyline from an array of LatLng points\n * var latlngs = [\n * \t[45.51, -122.68],\n * \t[37.77, -122.43],\n * \t[34.04, -118.2]\n * ];\n *\n * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polyline\n * map.fitBounds(polyline.getBounds());\n * ```\n *\n * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:\n *\n * ```js\n * // create a red polyline from an array of arrays of LatLng points\n * var latlngs = [\n * \t[[45.51, -122.68],\n * \t [37.77, -122.43],\n * \t [34.04, -118.2]],\n * \t[[40.78, -73.91],\n * \t [41.83, -87.62],\n * \t [32.76, -96.72]]\n * ];\n * ```\n */\n\n\nexport var Polyline = Path.extend({\n\n\t// @section\n\t// @aka Polyline options\n\toptions: {\n\t\t// @option smoothFactor: Number = 1.0\n\t\t// How much to simplify the polyline on each zoom level. More means\n\t\t// better performance and smoother look, and less means more accurate representation.\n\t\tsmoothFactor: 1.0,\n\n\t\t// @option noClip: Boolean = false\n\t\t// Disable polyline clipping.\n\t\tnoClip: false\n\t},\n\n\tinitialize: function (latlngs, options) {\n\t\tUtil.setOptions(this, options);\n\t\tthis._setLatLngs(latlngs);\n\t},\n\n\t// @method getLatLngs(): LatLng[]\n\t// Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.\n\tgetLatLngs: function () {\n\t\treturn this._latlngs;\n\t},\n\n\t// @method setLatLngs(latlngs: LatLng[]): this\n\t// Replaces all the points in the polyline with the given array of geographical points.\n\tsetLatLngs: function (latlngs) {\n\t\tthis._setLatLngs(latlngs);\n\t\treturn this.redraw();\n\t},\n\n\t// @method isEmpty(): Boolean\n\t// Returns `true` if the Polyline has no LatLngs.\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length;\n\t},\n\n\t// @method closestLayerPoint(p: Point): Point\n\t// Returns the point closest to `p` on the Polyline.\n\tclosestLayerPoint: function (p) {\n\t\tvar minDistance = Infinity,\n\t\t    minPoint = null,\n\t\t    closest = LineUtil._sqClosestPointOnSegment,\n\t\t    p1, p2;\n\n\t\tfor (var j = 0, jLen = this._parts.length; j < jLen; j++) {\n\t\t\tvar points = this._parts[j];\n\n\t\t\tfor (var i = 1, len = points.length; i < len; i++) {\n\t\t\t\tp1 = points[i - 1];\n\t\t\t\tp2 = points[i];\n\n\t\t\t\tvar sqDist = closest(p, p1, p2, true);\n\n\t\t\t\tif (sqDist < minDistance) {\n\t\t\t\t\tminDistance = sqDist;\n\t\t\t\t\tminPoint = closest(p, p1, p2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (minPoint) {\n\t\t\tminPoint.distance = Math.sqrt(minDistance);\n\t\t}\n\t\treturn minPoint;\n\t},\n\n\t// @method getCenter(): LatLng\n\t// Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\t\treturn LineUtil.polylineCenter(this._defaultShape(), this._map.options.crs);\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\treturn this._bounds;\n\t},\n\n\t// @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this\n\t// Adds a given point to the polyline. By default, adds to the first ring of\n\t// the polyline in case of a multi-polyline, but can be overridden by passing\n\t// a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).\n\taddLatLng: function (latlng, latlngs) {\n\t\tlatlngs = latlngs || this._defaultShape();\n\t\tlatlng = toLatLng(latlng);\n\t\tlatlngs.push(latlng);\n\t\tthis._bounds.extend(latlng);\n\t\treturn this.redraw();\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tthis._bounds = new LatLngBounds();\n\t\tthis._latlngs = this._convertLatLngs(latlngs);\n\t},\n\n\t_defaultShape: function () {\n\t\treturn LineUtil.isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];\n\t},\n\n\t// recursively convert latlngs input into actual LatLng instances; calculate bounds along the way\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = [],\n\t\t    flat = LineUtil.isFlat(latlngs);\n\n\t\tfor (var i = 0, len = latlngs.length; i < len; i++) {\n\t\t\tif (flat) {\n\t\t\t\tresult[i] = toLatLng(latlngs[i]);\n\t\t\t\tthis._bounds.extend(result[i]);\n\t\t\t} else {\n\t\t\t\tresult[i] = this._convertLatLngs(latlngs[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t},\n\n\t_project: function () {\n\t\tvar pxBounds = new Bounds();\n\t\tthis._rings = [];\n\t\tthis._projectLatlngs(this._latlngs, this._rings, pxBounds);\n\n\t\tif (this._bounds.isValid() && pxBounds.isValid()) {\n\t\t\tthis._rawPxBounds = pxBounds;\n\t\t\tthis._updateBounds();\n\t\t}\n\t},\n\n\t_updateBounds: function () {\n\t\tvar w = this._clickTolerance(),\n\t\t    p = new Point(w, w);\n\n\t\tif (!this._rawPxBounds) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._pxBounds = new Bounds([\n\t\t\tthis._rawPxBounds.min.subtract(p),\n\t\t\tthis._rawPxBounds.max.add(p)\n\t\t]);\n\t},\n\n\t// recursively turns latlngs into a set of rings with projected coordinates\n\t_projectLatlngs: function (latlngs, result, projectedBounds) {\n\t\tvar flat = latlngs[0] instanceof LatLng,\n\t\t    len = latlngs.length,\n\t\t    i, ring;\n\n\t\tif (flat) {\n\t\t\tring = [];\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tring[i] = this._map.latLngToLayerPoint(latlngs[i]);\n\t\t\t\tprojectedBounds.extend(ring[i]);\n\t\t\t}\n\t\t\tresult.push(ring);\n\t\t} else {\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tthis._projectLatlngs(latlngs[i], result, projectedBounds);\n\t\t\t}\n\t\t}\n\t},\n\n\t// clip polyline by renderer bounds so that we have less to render for performance\n\t_clipPoints: function () {\n\t\tvar bounds = this._renderer._bounds;\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tvar parts = this._parts,\n\t\t    i, j, k, len, len2, segment, points;\n\n\t\tfor (i = 0, k = 0, len = this._rings.length; i < len; i++) {\n\t\t\tpoints = this._rings[i];\n\n\t\t\tfor (j = 0, len2 = points.length; j < len2 - 1; j++) {\n\t\t\t\tsegment = LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true);\n\n\t\t\t\tif (!segment) { continue; }\n\n\t\t\t\tparts[k] = parts[k] || [];\n\t\t\t\tparts[k].push(segment[0]);\n\n\t\t\t\t// if segment goes out of screen, or it's the last one, it's the end of the line part\n\t\t\t\tif ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {\n\t\t\t\t\tparts[k].push(segment[1]);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\n\t// simplify each clipped part of the polyline for performance\n\t_simplifyPoints: function () {\n\t\tvar parts = this._parts,\n\t\t    tolerance = this.options.smoothFactor;\n\n\t\tfor (var i = 0, len = parts.length; i < len; i++) {\n\t\t\tparts[i] = LineUtil.simplify(parts[i], tolerance);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tif (!this._map) { return; }\n\n\t\tthis._clipPoints();\n\t\tthis._simplifyPoints();\n\t\tthis._updatePath();\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p, closed) {\n\t\tvar i, j, k, len, len2, part,\n\t\t    w = this._clickTolerance();\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// hit detection for polylines\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tif (!closed && (j === 0)) { continue; }\n\n\t\t\t\tif (LineUtil.pointToSegmentDistance(p, part[k], part[j]) <= w) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n});\n\n// @factory L.polyline(latlngs: LatLng[], options?: Polyline options)\n// Instantiates a polyline object given an array of geographical points and\n// optionally an options object. You can create a `Polyline` object with\n// multiple separate lines (`MultiPolyline`) by passing an array of arrays\n// of geographic points.\nexport function polyline(latlngs, options) {\n\treturn new Polyline(latlngs, options);\n}\n\n// Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.\nPolyline._flat = LineUtil._flat;\n", "import {Polyline} from './Polyline';\nimport {LatLng} from '../../geo/LatLng';\nimport * as LineUtil from '../../geometry/LineUtil';\nimport {Point} from '../../geometry/Point';\nimport {Bounds} from '../../geometry/Bounds';\nimport * as PolyUtil from '../../geometry/PolyUtil';\n\n/*\n * @class Polygon\n * @aka L.Polygon\n * @inherits Polyline\n *\n * A class for drawing polygon overlays on a map. Extends `Polyline`.\n *\n * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.\n *\n *\n * @example\n *\n * ```js\n * // create a red polygon from an array of LatLng points\n * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];\n *\n * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polygon\n * map.fitBounds(polygon.getBounds());\n * ```\n *\n * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:\n *\n * ```js\n * var latlngs = [\n *   [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n *   [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n * ];\n * ```\n *\n * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.\n *\n * ```js\n * var latlngs = [\n *   [ // first polygon\n *     [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n *     [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n *   ],\n *   [ // second polygon\n *     [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]\n *   ]\n * ];\n * ```\n */\n\nexport var Polygon = Polyline.extend({\n\n\toptions: {\n\t\tfill: true\n\t},\n\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length || !this._latlngs[0].length;\n\t},\n\n\t// @method getCenter(): LatLng\n\t// Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\t\treturn PolyUtil.polygonCenter(this._defaultShape(), this._map.options.crs);\n\t},\n\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = Polyline.prototype._convertLatLngs.call(this, latlngs),\n\t\t    len = result.length;\n\n\t\t// remove last point if it equals first one\n\t\tif (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {\n\t\t\tresult.pop();\n\t\t}\n\t\treturn result;\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tPolyline.prototype._setLatLngs.call(this, latlngs);\n\t\tif (LineUtil.isFlat(this._latlngs)) {\n\t\t\tthis._latlngs = [this._latlngs];\n\t\t}\n\t},\n\n\t_defaultShape: function () {\n\t\treturn LineUtil.isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];\n\t},\n\n\t_clipPoints: function () {\n\t\t// polygons need a different clipping algorithm so we redefine that\n\n\t\tvar bounds = this._renderer._bounds,\n\t\t    w = this.options.weight,\n\t\t    p = new Point(w, w);\n\n\t\t// increase clip padding by stroke width to avoid stroke on clip edges\n\t\tbounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0, len = this._rings.length, clipped; i < len; i++) {\n\t\t\tclipped = PolyUtil.clipPolygon(this._rings[i], bounds, true);\n\t\t\tif (clipped.length) {\n\t\t\t\tthis._parts.push(clipped);\n\t\t\t}\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this, true);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\tvar inside = false,\n\t\t    part, p1, p2, i, j, k, len, len2;\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// ray casting algorithm for detecting if point is in polygon\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tp1 = part[j];\n\t\t\t\tp2 = part[k];\n\n\t\t\t\tif (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n\t\t\t\t\tinside = !inside;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// also check if it's on polygon stroke\n\t\treturn inside || Polyline.prototype._containsPoint.call(this, p, true);\n\t}\n\n});\n\n\n// @factory L.polygon(latlngs: LatLng[], options?: Polyline options)\nexport function polygon(latlngs, options) {\n\treturn new Polygon(latlngs, options);\n}\n", "import {LayerGroup} from './LayerGroup';\r\nimport {FeatureGroup} from './FeatureGroup';\r\nimport * as Util from '../core/Util';\r\nimport {Marker} from './marker/Marker';\r\nimport {Circle} from './vector/Circle';\r\nimport {CircleMarker} from './vector/CircleMarker';\r\nimport {Polyline} from './vector/Polyline';\r\nimport {Polygon} from './vector/Polygon';\r\nimport {LatLng} from '../geo/LatLng';\r\nimport * as LineUtil from '../geometry/LineUtil';\r\nimport {toLatLng} from '../geo/LatLng';\r\n\r\n\r\n/*\r\n * @class GeoJSON\r\n * @aka L.GeoJSON\r\n * @inherits FeatureGroup\r\n *\r\n * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse\r\n * GeoJSON data and display it on the map. Extends `FeatureGroup`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.geoJSON(data, {\r\n * \tstyle: function (feature) {\r\n * \t\treturn {color: feature.properties.color};\r\n * \t}\r\n * }).bindPopup(function (layer) {\r\n * \treturn layer.feature.properties.description;\r\n * }).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var GeoJSON = FeatureGroup.extend({\r\n\r\n\t/* @section\r\n\t * @aka GeoJSON options\r\n\t *\r\n\t * @option pointToLayer: Function = *\r\n\t * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally\r\n\t * called when data is added, passing the GeoJSON point feature and its `LatLng`.\r\n\t * The default is to spawn a default `Marker`:\r\n\t * ```js\r\n\t * function(geoJsonPoint, latlng) {\r\n\t * \treturn L.marker(latlng);\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option style: Function = *\r\n\t * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,\r\n\t * called internally when data is added.\r\n\t * The default value is to not override any defaults:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn {}\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option onEachFeature: Function = *\r\n\t * A `Function` that will be called once for each created `Feature`, after it has\r\n\t * been created and styled. Useful for attaching events and popups to features.\r\n\t * The default is to do nothing with the newly created layers:\r\n\t * ```js\r\n\t * function (feature, layer) {}\r\n\t * ```\r\n\t *\r\n\t * @option filter: Function = *\r\n\t * A `Function` that will be used to decide whether to include a feature or not.\r\n\t * The default is to include all features:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn true;\r\n\t * }\r\n\t * ```\r\n\t * Note: dynamically changing the `filter` option will have effect only on newly\r\n\t * added data. It will _not_ re-evaluate already included features.\r\n\t *\r\n\t * @option coordsToLatLng: Function = *\r\n\t * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.\r\n\t * The default is the `coordsToLatLng` static method.\r\n\t *\r\n\t * @option markersInheritOptions: Boolean = false\r\n\t * Whether default Markers for \"Point\" type Features inherit from group options.\r\n\t */\r\n\r\n\tinitialize: function (geojson, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tif (geojson) {\r\n\t\t\tthis.addData(geojson);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addData( <GeoJSON> data ): this\r\n\t// Adds a GeoJSON object to the layer.\r\n\taddData: function (geojson) {\r\n\t\tvar features = Util.isArray(geojson) ? geojson : geojson.features,\r\n\t\t    i, len, feature;\r\n\r\n\t\tif (features) {\r\n\t\t\tfor (i = 0, len = features.length; i < len; i++) {\r\n\t\t\t\t// only add this if geometry or geometries are set and not null\r\n\t\t\t\tfeature = features[i];\r\n\t\t\t\tif (feature.geometries || feature.geometry || feature.features || feature.coordinates) {\r\n\t\t\t\t\tthis.addData(feature);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar options = this.options;\r\n\r\n\t\tif (options.filter && !options.filter(geojson)) { return this; }\r\n\r\n\t\tvar layer = geometryToLayer(geojson, options);\r\n\t\tif (!layer) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tlayer.feature = asFeature(geojson);\r\n\r\n\t\tlayer.defaultOptions = layer.options;\r\n\t\tthis.resetStyle(layer);\r\n\r\n\t\tif (options.onEachFeature) {\r\n\t\t\toptions.onEachFeature(geojson, layer);\r\n\t\t}\r\n\r\n\t\treturn this.addLayer(layer);\r\n\t},\r\n\r\n\t// @method resetStyle( <Path> layer? ): this\r\n\t// Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.\r\n\t// If `layer` is omitted, the style of all features in the current layer is reset.\r\n\tresetStyle: function (layer) {\r\n\t\tif (layer === undefined) {\r\n\t\t\treturn this.eachLayer(this.resetStyle, this);\r\n\t\t}\r\n\t\t// reset any custom styles\r\n\t\tlayer.options = Util.extend({}, layer.defaultOptions);\r\n\t\tthis._setLayerStyle(layer, this.options.style);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setStyle( <Function> style ): this\r\n\t// Changes styles of GeoJSON vector layers with the given style function.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.eachLayer(function (layer) {\r\n\t\t\tthis._setLayerStyle(layer, style);\r\n\t\t}, this);\r\n\t},\r\n\r\n\t_setLayerStyle: function (layer, style) {\r\n\t\tif (layer.setStyle) {\r\n\t\t\tif (typeof style === 'function') {\r\n\t\t\t\tstyle = style(layer.feature);\r\n\t\t\t}\r\n\t\t\tlayer.setStyle(style);\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @section\r\n// There are several static functions which can be called without instantiating L.GeoJSON:\r\n\r\n// @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer\r\n// Creates a `Layer` from a given GeoJSON feature. Can use a custom\r\n// [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)\r\n// functions if provided as options.\r\nexport function geometryToLayer(geojson, options) {\r\n\r\n\tvar geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,\r\n\t    coords = geometry ? geometry.coordinates : null,\r\n\t    layers = [],\r\n\t    pointToLayer = options && options.pointToLayer,\r\n\t    _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,\r\n\t    latlng, latlngs, i, len;\r\n\r\n\tif (!coords && !geometry) {\r\n\t\treturn null;\r\n\t}\r\n\r\n\tswitch (geometry.type) {\r\n\tcase 'Point':\r\n\t\tlatlng = _coordsToLatLng(coords);\r\n\t\treturn _pointToLayer(pointToLayer, geojson, latlng, options);\r\n\r\n\tcase 'MultiPoint':\r\n\t\tfor (i = 0, len = coords.length; i < len; i++) {\r\n\t\t\tlatlng = _coordsToLatLng(coords[i]);\r\n\t\t\tlayers.push(_pointToLayer(pointToLayer, geojson, latlng, options));\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tcase 'LineString':\r\n\tcase 'MultiLineString':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);\r\n\t\treturn new Polyline(latlngs, options);\r\n\r\n\tcase 'Polygon':\r\n\tcase 'MultiPolygon':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);\r\n\t\treturn new Polygon(latlngs, options);\r\n\r\n\tcase 'GeometryCollection':\r\n\t\tfor (i = 0, len = geometry.geometries.length; i < len; i++) {\r\n\t\t\tvar geoLayer = geometryToLayer({\r\n\t\t\t\tgeometry: geometry.geometries[i],\r\n\t\t\t\ttype: 'Feature',\r\n\t\t\t\tproperties: geojson.properties\r\n\t\t\t}, options);\r\n\r\n\t\t\tif (geoLayer) {\r\n\t\t\t\tlayers.push(geoLayer);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tcase 'FeatureCollection':\r\n\t\tfor (i = 0, len = geometry.features.length; i < len; i++) {\r\n\t\t\tvar featureLayer = geometryToLayer(geometry.features[i], options);\r\n\r\n\t\t\tif (featureLayer) {\r\n\t\t\t\tlayers.push(featureLayer);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tdefault:\r\n\t\tthrow new Error('Invalid GeoJSON object.');\r\n\t}\r\n}\r\n\r\nfunction _pointToLayer(pointToLayerFn, geojson, latlng, options) {\r\n\treturn pointToLayerFn ?\r\n\t\tpointToLayerFn(geojson, latlng) :\r\n\t\tnew Marker(latlng, options && options.markersInheritOptions && options);\r\n}\r\n\r\n// @function coordsToLatLng(coords: Array): LatLng\r\n// Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)\r\n// or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.\r\nexport function coordsToLatLng(coords) {\r\n\treturn new LatLng(coords[1], coords[0], coords[2]);\r\n}\r\n\r\n// @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array\r\n// Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.\r\n// `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).\r\n// Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.\r\nexport function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {\r\n\tvar latlngs = [];\r\n\r\n\tfor (var i = 0, len = coords.length, latlng; i < len; i++) {\r\n\t\tlatlng = levelsDeep ?\r\n\t\t\tcoordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :\r\n\t\t\t(_coordsToLatLng || coordsToLatLng)(coords[i]);\r\n\r\n\t\tlatlngs.push(latlng);\r\n\t}\r\n\r\n\treturn latlngs;\r\n}\r\n\r\n// @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array\r\n// Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function.\r\nexport function latLngToCoords(latlng, precision) {\r\n\tlatlng = toLatLng(latlng);\r\n\treturn latlng.alt !== undefined ?\r\n\t\t[Util.formatNum(latlng.lng, precision), Util.formatNum(latlng.lat, precision), Util.formatNum(latlng.alt, precision)] :\r\n\t\t[Util.formatNum(latlng.lng, precision), Util.formatNum(latlng.lat, precision)];\r\n}\r\n\r\n// @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array\r\n// Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)\r\n// `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function.\r\nexport function latLngsToCoords(latlngs, levelsDeep, closed, precision) {\r\n\tvar coords = [];\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\t// Check for flat arrays required to ensure unbalanced arrays are correctly converted in recursion\r\n\t\tcoords.push(levelsDeep ?\r\n\t\t\tlatLngsToCoords(latlngs[i], LineUtil.isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) :\r\n\t\t\tlatLngToCoords(latlngs[i], precision));\r\n\t}\r\n\r\n\tif (!levelsDeep && closed && coords.length > 0) {\r\n\t\tcoords.push(coords[0].slice());\r\n\t}\r\n\r\n\treturn coords;\r\n}\r\n\r\nexport function getFeature(layer, newGeometry) {\r\n\treturn layer.feature ?\r\n\t\tUtil.extend({}, layer.feature, {geometry: newGeometry}) :\r\n\t\tasFeature(newGeometry);\r\n}\r\n\r\n// @function asFeature(geojson: Object): Object\r\n// Normalize GeoJSON geometries/features into GeoJSON features.\r\nexport function asFeature(geojson) {\r\n\tif (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {\r\n\t\treturn geojson;\r\n\t}\r\n\r\n\treturn {\r\n\t\ttype: 'Feature',\r\n\t\tproperties: {},\r\n\t\tgeometry: geojson\r\n\t};\r\n}\r\n\r\nvar PointToGeoJSON = {\r\n\ttoGeoJSON: function (precision) {\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'Point',\r\n\t\t\tcoordinates: latLngToCoords(this.getLatLng(), precision)\r\n\t\t});\r\n\t}\r\n};\r\n\r\n// @namespace Marker\r\n// @section Other methods\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).\r\nMarker.include(PointToGeoJSON);\r\n\r\n// @namespace CircleMarker\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).\r\nCircle.include(PointToGeoJSON);\r\nCircleMarker.include(PointToGeoJSON);\r\n\r\n\r\n// @namespace Polyline\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).\r\nPolyline.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar multi = !LineUtil.isFlat(this._latlngs);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'LineString',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n// @namespace Polygon\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).\r\nPolygon.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar holes = !LineUtil.isFlat(this._latlngs),\r\n\t\t    multi = holes && !LineUtil.isFlat(this._latlngs[0]);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);\r\n\r\n\t\tif (!holes) {\r\n\t\t\tcoords = [coords];\r\n\t\t}\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'Polygon',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n\r\n// @namespace LayerGroup\r\nLayerGroup.include({\r\n\ttoMultiPoint: function (precision) {\r\n\t\tvar coords = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tcoords.push(layer.toGeoJSON(precision).geometry.coordinates);\r\n\t\t});\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'MultiPoint',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t},\r\n\r\n\t// @method toGeoJSON(precision?: Number|false): Object\r\n\t// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n\t// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).\r\n\ttoGeoJSON: function (precision) {\r\n\r\n\t\tvar type = this.feature && this.feature.geometry && this.feature.geometry.type;\r\n\r\n\t\tif (type === 'MultiPoint') {\r\n\t\t\treturn this.toMultiPoint(precision);\r\n\t\t}\r\n\r\n\t\tvar isGeometryCollection = type === 'GeometryCollection',\r\n\t\t    jsons = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tif (layer.toGeoJSON) {\r\n\t\t\t\tvar json = layer.toGeoJSON(precision);\r\n\t\t\t\tif (isGeometryCollection) {\r\n\t\t\t\t\tjsons.push(json.geometry);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar feature = asFeature(json);\r\n\t\t\t\t\t// Squash nested feature collections\r\n\t\t\t\t\tif (feature.type === 'FeatureCollection') {\r\n\t\t\t\t\t\tjsons.push.apply(jsons, feature.features);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tjsons.push(feature);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tif (isGeometryCollection) {\r\n\t\t\treturn getFeature(this, {\r\n\t\t\t\tgeometries: jsons,\r\n\t\t\t\ttype: 'GeometryCollection'\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\treturn {\r\n\t\t\ttype: 'FeatureCollection',\r\n\t\t\tfeatures: jsons\r\n\t\t};\r\n\t}\r\n});\r\n\r\n// @namespace GeoJSON\r\n// @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)\r\n// Creates a GeoJSON layer. Optionally accepts an object in\r\n// [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map\r\n// (you can alternatively add it later with `addData` method) and an `options` object.\r\nexport function geoJSON(geojson, options) {\r\n\treturn new GeoJSON(geojson, options);\r\n}\r\n\r\n// Backward compatibility.\r\nexport var geoJson = geoJSON;\r\n", "import {Layer} from './Layer';\r\nimport * as Util from '../core/Util';\r\nimport {toLatLngBounds} from '../geo/LatLngBounds';\r\nimport {Bounds} from '../geometry/Bounds';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class ImageOverlay\r\n * @aka L.ImageOverlay\r\n * @inherits Interactive layer\r\n *\r\n * Used to load and display a single image over specific bounds of the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',\r\n * \timageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];\r\n * L.imageOverlay(imageUrl, imageBounds).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var ImageOverlay = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka ImageOverlay options\r\n\toptions: {\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the image overlay.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option alt: String = ''\r\n\t\t// Text for the `alt` attribute of the image (useful for accessibility).\r\n\t\talt: '',\r\n\r\n\t\t// @option interactive: Boolean = false\r\n\t\t// If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.\r\n\t\tinteractive: false,\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the image.\r\n\t\t// If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false,\r\n\r\n\t\t// @option errorOverlayUrl: String = ''\r\n\t\t// URL to the overlay image to show in place of the overlay that failed to load.\r\n\t\terrorOverlayUrl: '',\r\n\r\n\t\t// @option zIndex: Number = 1\r\n\t\t// The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.\r\n\t\tzIndex: 1,\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom class name to assign to the image. Empty by default.\r\n\t\tclassName: ''\r\n\t},\r\n\r\n\tinitialize: function (url, bounds, options) { // (String, LatLngBounds, Object)\r\n\t\tthis._url = url;\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tUtil.setOptions(this, options);\r\n\t},\r\n\r\n\tonAdd: function () {\r\n\t\tif (!this._image) {\r\n\t\t\tthis._initImage();\r\n\r\n\t\t\tif (this.options.opacity < 1) {\r\n\t\t\t\tthis._updateOpacity();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\tDomUtil.addClass(this._image, 'leaflet-interactive');\r\n\t\t\tthis.addInteractiveTarget(this._image);\r\n\t\t}\r\n\r\n\t\tthis.getPane().appendChild(this._image);\r\n\t\tthis._reset();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tDomUtil.remove(this._image);\r\n\t\tif (this.options.interactive) {\r\n\t\t\tthis.removeInteractiveTarget(this._image);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Sets the opacity of the overlay.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tsetStyle: function (styleOpts) {\r\n\t\tif (styleOpts.opacity) {\r\n\t\t\tthis.setOpacity(styleOpts.opacity);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer to the top of all overlays.\r\n\tbringToFront: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toFront(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer to the bottom of all overlays.\r\n\tbringToBack: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toBack(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setUrl(url: String): this\r\n\t// Changes the URL of the image.\r\n\tsetUrl: function (url) {\r\n\t\tthis._url = url;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._image.src = url;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setBounds(bounds: LatLngBounds): this\r\n\t// Update the bounds that this ImageOverlay covers\r\n\tsetBounds: function (bounds) {\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._reset();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = {\r\n\t\t\tzoom: this._reset,\r\n\t\t\tviewreset: this._reset\r\n\t\t};\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tevents.zoomanim = this._animateZoom;\r\n\t\t}\r\n\r\n\t\treturn events;\r\n\t},\r\n\r\n\t// @method setZIndex(value: Number): this\r\n\t// Changes the [zIndex](#imageoverlay-zindex) of the image overlay.\r\n\tsetZIndex: function (value) {\r\n\t\tthis.options.zIndex = value;\r\n\t\tthis._updateZIndex();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Get the bounds that this ImageOverlay covers\r\n\tgetBounds: function () {\r\n\t\treturn this._bounds;\r\n\t},\r\n\r\n\t// @method getElement(): HTMLElement\r\n\t// Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)\r\n\t// used by this overlay.\r\n\tgetElement: function () {\r\n\t\treturn this._image;\r\n\t},\r\n\r\n\t_initImage: function () {\r\n\t\tvar wasElementSupplied = this._url.tagName === 'IMG';\r\n\t\tvar img = this._image = wasElementSupplied ? this._url : DomUtil.create('img');\r\n\r\n\t\tDomUtil.addClass(img, 'leaflet-image-layer');\r\n\t\tif (this._zoomAnimated) { DomUtil.addClass(img, 'leaflet-zoom-animated'); }\r\n\t\tif (this.options.className) { DomUtil.addClass(img, this.options.className); }\r\n\r\n\t\timg.onselectstart = Util.falseFn;\r\n\t\timg.onmousemove = Util.falseFn;\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the ImageOverlay layer has loaded its image\r\n\t\timg.onload = Util.bind(this.fire, this, 'load');\r\n\t\timg.onerror = Util.bind(this._overlayOnError, this, 'error');\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\timg.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\tif (this.options.zIndex) {\r\n\t\t\tthis._updateZIndex();\r\n\t\t}\r\n\r\n\t\tif (wasElementSupplied) {\r\n\t\t\tthis._url = img.src;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\timg.src = this._url;\r\n\t\timg.alt = this.options.alt;\r\n\t},\r\n\r\n\t_animateZoom: function (e) {\r\n\t\tvar scale = this._map.getZoomScale(e.zoom),\r\n\t\t    offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;\r\n\r\n\t\tDomUtil.setTransform(this._image, offset, scale);\r\n\t},\r\n\r\n\t_reset: function () {\r\n\t\tvar image = this._image,\r\n\t\t    bounds = new Bounds(\r\n\t\t        this._map.latLngToLayerPoint(this._bounds.getNorthWest()),\r\n\t\t        this._map.latLngToLayerPoint(this._bounds.getSouthEast())),\r\n\t\t    size = bounds.getSize();\r\n\r\n\t\tDomUtil.setPosition(image, bounds.min);\r\n\r\n\t\timage.style.width  = size.x + 'px';\r\n\t\timage.style.height = size.y + 'px';\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tDomUtil.setOpacity(this._image, this.options.opacity);\r\n\t},\r\n\r\n\t_updateZIndex: function () {\r\n\t\tif (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {\r\n\t\t\tthis._image.style.zIndex = this.options.zIndex;\r\n\t\t}\r\n\t},\r\n\r\n\t_overlayOnError: function () {\r\n\t\t// @event error: Event\r\n\t\t// Fired when the ImageOverlay layer fails to load its image\r\n\t\tthis.fire('error');\r\n\r\n\t\tvar errorUrl = this.options.errorOverlayUrl;\r\n\t\tif (errorUrl && this._url !== errorUrl) {\r\n\t\t\tthis._url = errorUrl;\r\n\t\t\tthis._image.src = errorUrl;\r\n\t\t}\r\n\t},\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the center of the ImageOverlay.\r\n\tgetCenter: function () {\r\n\t\treturn this._bounds.getCenter();\r\n\t}\r\n});\r\n\r\n// @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)\r\n// Instantiates an image overlay object given the URL of the image and the\r\n// geographical bounds it is tied to.\r\nexport var imageOverlay = function (url, bounds, options) {\r\n\treturn new ImageOverlay(url, bounds, options);\r\n};\r\n", "import {ImageOverlay} from './ImageOverlay';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport * as Util from '../core/Util';\r\n\r\n/*\r\n * @class VideoOverlay\r\n * @aka L.VideoOverlay\r\n * @inherits ImageOverlay\r\n *\r\n * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.\r\n *\r\n * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)\r\n * HTML5 element.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',\r\n * \tvideoBounds = [[ 32, -130], [ 13, -100]];\r\n * L.videoOverlay(videoUrl, videoBounds ).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var VideoOverlay = ImageOverlay.extend({\r\n\r\n\t// @section\r\n\t// @aka VideoOverlay options\r\n\toptions: {\r\n\t\t// @option autoplay: Boolean = true\r\n\t\t// Whether the video starts playing automatically when loaded.\r\n\t\t// On some browsers autoplay will only work with `muted: true`\r\n\t\tautoplay: true,\r\n\r\n\t\t// @option loop: Boolean = true\r\n\t\t// Whether the video will loop back to the beginning when played.\r\n\t\tloop: true,\r\n\r\n\t\t// @option keepAspectRatio: Boolean = true\r\n\t\t// Whether the video will save aspect ratio after the projection.\r\n\t\t// Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)\r\n\t\tkeepAspectRatio: true,\r\n\r\n\t\t// @option muted: Boolean = false\r\n\t\t// Whether the video starts on mute when loaded.\r\n\t\tmuted: false,\r\n\r\n\t\t// @option playsInline: Boolean = true\r\n\t\t// Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.\r\n\t\tplaysInline: true\r\n\t},\r\n\r\n\t_initImage: function () {\r\n\t\tvar wasElementSupplied = this._url.tagName === 'VIDEO';\r\n\t\tvar vid = this._image = wasElementSupplied ? this._url : DomUtil.create('video');\r\n\r\n\t\tDomUtil.addClass(vid, 'leaflet-image-layer');\r\n\t\tif (this._zoomAnimated) { DomUtil.addClass(vid, 'leaflet-zoom-animated'); }\r\n\t\tif (this.options.className) { DomUtil.addClass(vid, this.options.className); }\r\n\r\n\t\tvid.onselectstart = Util.falseFn;\r\n\t\tvid.onmousemove = Util.falseFn;\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the video has finished loading the first frame\r\n\t\tvid.onloadeddata = Util.bind(this.fire, this, 'load');\r\n\r\n\t\tif (wasElementSupplied) {\r\n\t\t\tvar sourceElements = vid.getElementsByTagName('source');\r\n\t\t\tvar sources = [];\r\n\t\t\tfor (var j = 0; j < sourceElements.length; j++) {\r\n\t\t\t\tsources.push(sourceElements[j].src);\r\n\t\t\t}\r\n\r\n\t\t\tthis._url = (sourceElements.length > 0) ? sources : [vid.src];\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!Util.isArray(this._url)) { this._url = [this._url]; }\r\n\r\n\t\tif (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {\r\n\t\t\tvid.style['objectFit'] = 'fill';\r\n\t\t}\r\n\t\tvid.autoplay = !!this.options.autoplay;\r\n\t\tvid.loop = !!this.options.loop;\r\n\t\tvid.muted = !!this.options.muted;\r\n\t\tvid.playsInline = !!this.options.playsInline;\r\n\t\tfor (var i = 0; i < this._url.length; i++) {\r\n\t\t\tvar source = DomUtil.create('source');\r\n\t\t\tsource.src = this._url[i];\r\n\t\t\tvid.appendChild(source);\r\n\t\t}\r\n\t}\r\n\r\n\t// @method getElement(): HTMLVideoElement\r\n\t// Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)\r\n\t// used by this overlay.\r\n});\r\n\r\n\r\n// @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)\r\n// Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the\r\n// geographical bounds it is tied to.\r\n\r\nexport function videoOverlay(video, bounds, options) {\r\n\treturn new VideoOverlay(video, bounds, options);\r\n}\r\n", "import {ImageOverlay} from './ImageOverlay';\nimport * as DomUtil from '../dom/DomUtil';\nimport * as Util from '../core/Util';\n\n/*\n * @class SVGOverlay\n * @aka L.SVGOverlay\n * @inherits ImageOverlay\n *\n * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.\n *\n * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.\n *\n * @example\n *\n * ```js\n * var svgElement = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n * svgElement.setAttribute('xmlns', \"http://www.w3.org/2000/svg\");\n * svgElement.setAttribute('viewBox', \"0 0 200 200\");\n * svgElement.innerHTML = '<rect width=\"200\" height=\"200\"/><rect x=\"75\" y=\"23\" width=\"50\" height=\"50\" style=\"fill:red\"/><rect x=\"75\" y=\"123\" width=\"50\" height=\"50\" style=\"fill:#0013ff\"/>';\n * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];\n * L.svgOverlay(svgElement, svgElementBounds).addTo(map);\n * ```\n */\n\nexport var SVGOverlay = ImageOverlay.extend({\n\t_initImage: function () {\n\t\tvar el = this._image = this._url;\n\n\t\tDomUtil.addClass(el, 'leaflet-image-layer');\n\t\tif (this._zoomAnimated) { DomUtil.addClass(el, 'leaflet-zoom-animated'); }\n\t\tif (this.options.className) { DomUtil.addClass(el, this.options.className); }\n\n\t\tel.onselectstart = Util.falseFn;\n\t\tel.onmousemove = Util.falseFn;\n\t}\n\n\t// @method getElement(): SVGElement\n\t// Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)\n\t// used by this overlay.\n});\n\n\n// @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)\n// Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.\n// A viewBox attribute is required on the SVG element to zoom in and out properly.\n\nexport function svgOverlay(el, bounds, options) {\n\treturn new SVGOverlay(el, bounds, options);\n}\n", "import {Map} from '../map/Map';\r\nimport {Layer} from './Layer';\r\nimport {FeatureGroup} from './FeatureGroup';\r\nimport * as Util from '../core/Util';\r\nimport {toLatLng, LatLng} from '../geo/LatLng';\r\nimport {toPoint} from '../geometry/Point';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class DivOverlay\r\n * @inherits Interactive layer\r\n * @aka L.DivOverlay\r\n * Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.\r\n */\r\n\r\n// @namespace DivOverlay\r\nexport var DivOverlay = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka DivOverlay options\r\n\toptions: {\r\n\t\t// @option interactive: Boolean = false\r\n\t\t// If true, the popup/tooltip will listen to the mouse events.\r\n\t\tinteractive: false,\r\n\r\n\t\t// @option offset: Point = Point(0, 0)\r\n\t\t// The offset of the overlay position.\r\n\t\toffset: [0, 0],\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom CSS class name to assign to the overlay.\r\n\t\tclassName: '',\r\n\r\n\t\t// @option pane: String = undefined\r\n\t\t// `Map pane` where the overlay will be added.\r\n\t\tpane: undefined,\r\n\r\n\t\t// @option content: String|HTMLElement|Function = ''\r\n\t\t// Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be\r\n\t\t// passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.\r\n\t\tcontent: ''\r\n\t},\r\n\r\n\tinitialize: function (options, source) {\r\n\t\tif (options && (options instanceof LatLng || Util.isArray(options))) {\r\n\t\t\tthis._latlng = toLatLng(options);\r\n\t\t\tUtil.setOptions(this, source);\r\n\t\t} else {\r\n\t\t\tUtil.setOptions(this, options);\r\n\t\t\tthis._source = source;\r\n\t\t}\r\n\t\tif (this.options.content) {\r\n\t\t\tthis._content = this.options.content;\r\n\t\t}\r\n\t},\r\n\r\n\t// @method openOn(map: Map): this\r\n\t// Adds the overlay to the map.\r\n\t// Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.\r\n\topenOn: function (map) {\r\n\t\tmap = arguments.length ? map : this._source._map; // experimental, not the part of public api\r\n\t\tif (!map.hasLayer(this)) {\r\n\t\t\tmap.addLayer(this);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method close(): this\r\n\t// Closes the overlay.\r\n\t// Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`\r\n\t// and `layer.closePopup()`/`.closeTooltip()`.\r\n\tclose: function () {\r\n\t\tif (this._map) {\r\n\t\t\tthis._map.removeLayer(this);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method toggle(layer?: Layer): this\r\n\t// Opens or closes the overlay bound to layer depending on its current state.\r\n\t// Argument may be omitted only for overlay bound to layer.\r\n\t// Alternative to `layer.togglePopup()`/`.toggleTooltip()`.\r\n\ttoggle: function (layer) {\r\n\t\tif (this._map) {\r\n\t\t\tthis.close();\r\n\t\t} else {\r\n\t\t\tif (arguments.length) {\r\n\t\t\t\tthis._source = layer;\r\n\t\t\t} else {\r\n\t\t\t\tlayer = this._source;\r\n\t\t\t}\r\n\t\t\tthis._prepareOpen();\r\n\r\n\t\t\t// open the overlay on the map\r\n\t\t\tthis.openOn(layer._map);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._zoomAnimated = map._zoomAnimated;\r\n\r\n\t\tif (!this._container) {\r\n\t\t\tthis._initLayout();\r\n\t\t}\r\n\r\n\t\tif (map._fadeAnimated) {\r\n\t\t\tDomUtil.setOpacity(this._container, 0);\r\n\t\t}\r\n\r\n\t\tclearTimeout(this._removeTimeout);\r\n\t\tthis.getPane().appendChild(this._container);\r\n\t\tthis.update();\r\n\r\n\t\tif (map._fadeAnimated) {\r\n\t\t\tDomUtil.setOpacity(this._container, 1);\r\n\t\t}\r\n\r\n\t\tthis.bringToFront();\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\tDomUtil.addClass(this._container, 'leaflet-interactive');\r\n\t\t\tthis.addInteractiveTarget(this._container);\r\n\t\t}\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tif (map._fadeAnimated) {\r\n\t\t\tDomUtil.setOpacity(this._container, 0);\r\n\t\t\tthis._removeTimeout = setTimeout(Util.bind(DomUtil.remove, undefined, this._container), 200);\r\n\t\t} else {\r\n\t\t\tDomUtil.remove(this._container);\r\n\t\t}\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\tDomUtil.removeClass(this._container, 'leaflet-interactive');\r\n\t\t\tthis.removeInteractiveTarget(this._container);\r\n\t\t}\r\n\t},\r\n\r\n\t// @namespace DivOverlay\r\n\t// @method getLatLng: LatLng\r\n\t// Returns the geographical point of the overlay.\r\n\tgetLatLng: function () {\r\n\t\treturn this._latlng;\r\n\t},\r\n\r\n\t// @method setLatLng(latlng: LatLng): this\r\n\t// Sets the geographical point where the overlay will open.\r\n\tsetLatLng: function (latlng) {\r\n\t\tthis._latlng = toLatLng(latlng);\r\n\t\tif (this._map) {\r\n\t\t\tthis._updatePosition();\r\n\t\t\tthis._adjustPan();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getContent: String|HTMLElement\r\n\t// Returns the content of the overlay.\r\n\tgetContent: function () {\r\n\t\treturn this._content;\r\n\t},\r\n\r\n\t// @method setContent(htmlContent: String|HTMLElement|Function): this\r\n\t// Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.\r\n\t// The function should return a `String` or `HTMLElement` to be used in the overlay.\r\n\tsetContent: function (content) {\r\n\t\tthis._content = content;\r\n\t\tthis.update();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getElement: String|HTMLElement\r\n\t// Returns the HTML container of the overlay.\r\n\tgetElement: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method update: null\r\n\t// Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.\r\n\tupdate: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tthis._container.style.visibility = 'hidden';\r\n\r\n\t\tthis._updateContent();\r\n\t\tthis._updateLayout();\r\n\t\tthis._updatePosition();\r\n\r\n\t\tthis._container.style.visibility = '';\r\n\r\n\t\tthis._adjustPan();\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = {\r\n\t\t\tzoom: this._updatePosition,\r\n\t\t\tviewreset: this._updatePosition\r\n\t\t};\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tevents.zoomanim = this._animateZoom;\r\n\t\t}\r\n\t\treturn events;\r\n\t},\r\n\r\n\t// @method isOpen: Boolean\r\n\t// Returns `true` when the overlay is visible on the map.\r\n\tisOpen: function () {\r\n\t\treturn !!this._map && this._map.hasLayer(this);\r\n\t},\r\n\r\n\t// @method bringToFront: this\r\n\t// Brings this overlay in front of other overlays (in the same map pane).\r\n\tbringToFront: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toFront(this._container);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToBack: this\r\n\t// Brings this overlay to the back of other overlays (in the same map pane).\r\n\tbringToBack: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toBack(this._container);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)\r\n\t_prepareOpen: function (latlng) {\r\n\t\tvar source = this._source;\r\n\t\tif (!source._map) { return false; }\r\n\r\n\t\tif (source instanceof FeatureGroup) {\r\n\t\t\tsource = null;\r\n\t\t\tvar layers = this._source._layers;\r\n\t\t\tfor (var id in layers) {\r\n\t\t\t\tif (layers[id]._map) {\r\n\t\t\t\t\tsource = layers[id];\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!source) { return false; } // Unable to get source layer.\r\n\r\n\t\t\t// set overlay source to this layer\r\n\t\t\tthis._source = source;\r\n\t\t}\r\n\r\n\t\tif (!latlng) {\r\n\t\t\tif (source.getCenter) {\r\n\t\t\t\tlatlng = source.getCenter();\r\n\t\t\t} else if (source.getLatLng) {\r\n\t\t\t\tlatlng = source.getLatLng();\r\n\t\t\t} else if (source.getBounds) {\r\n\t\t\t\tlatlng = source.getBounds().getCenter();\r\n\t\t\t} else {\r\n\t\t\t\tthrow new Error('Unable to get source layer LatLng.');\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.setLatLng(latlng);\r\n\r\n\t\tif (this._map) {\r\n\t\t\t// update the overlay (content, layout, etc...)\r\n\t\t\tthis.update();\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_updateContent: function () {\r\n\t\tif (!this._content) { return; }\r\n\r\n\t\tvar node = this._contentNode;\r\n\t\tvar content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;\r\n\r\n\t\tif (typeof content === 'string') {\r\n\t\t\tnode.innerHTML = content;\r\n\t\t} else {\r\n\t\t\twhile (node.hasChildNodes()) {\r\n\t\t\t\tnode.removeChild(node.firstChild);\r\n\t\t\t}\r\n\t\t\tnode.appendChild(content);\r\n\t\t}\r\n\r\n\t\t// @namespace DivOverlay\r\n\t\t// @section DivOverlay events\r\n\t\t// @event contentupdate: Event\r\n\t\t// Fired when the content of the overlay is updated\r\n\t\tthis.fire('contentupdate');\r\n\t},\r\n\r\n\t_updatePosition: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tvar pos = this._map.latLngToLayerPoint(this._latlng),\r\n\t\t    offset = toPoint(this.options.offset),\r\n\t\t    anchor = this._getAnchor();\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tDomUtil.setPosition(this._container, pos.add(anchor));\r\n\t\t} else {\r\n\t\t\toffset = offset.add(pos).add(anchor);\r\n\t\t}\r\n\r\n\t\tvar bottom = this._containerBottom = -offset.y,\r\n\t\t    left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;\r\n\r\n\t\t// bottom position the overlay in case the height of the overlay changes (images loading etc)\r\n\t\tthis._container.style.bottom = bottom + 'px';\r\n\t\tthis._container.style.left = left + 'px';\r\n\t},\r\n\r\n\t_getAnchor: function () {\r\n\t\treturn [0, 0];\r\n\t}\r\n\r\n});\r\n\r\nMap.include({\r\n\t_initOverlay: function (OverlayClass, content, latlng, options) {\r\n\t\tvar overlay = content;\r\n\t\tif (!(overlay instanceof OverlayClass)) {\r\n\t\t\toverlay = new OverlayClass(options).setContent(content);\r\n\t\t}\r\n\t\tif (latlng) {\r\n\t\t\toverlay.setLatLng(latlng);\r\n\t\t}\r\n\t\treturn overlay;\r\n\t}\r\n});\r\n\r\n\r\nLayer.include({\r\n\t_initOverlay: function (OverlayClass, old, content, options) {\r\n\t\tvar overlay = content;\r\n\t\tif (overlay instanceof OverlayClass) {\r\n\t\t\tUtil.setOptions(overlay, options);\r\n\t\t\toverlay._source = this;\r\n\t\t} else {\r\n\t\t\toverlay = (old && !options) ? old : new OverlayClass(options, this);\r\n\t\t\toverlay.setContent(content);\r\n\t\t}\r\n\t\treturn overlay;\r\n\t}\r\n});\r\n", "import {DivOverlay} from './DivOverlay';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport {Point, toPoint} from '../geometry/Point';\r\nimport {Map} from '../map/Map';\r\nimport {Layer} from './Layer';\r\nimport {Path} from './vector/Path';\r\nimport {FeatureGroup} from './FeatureGroup';\r\n\r\n/*\r\n * @class Popup\r\n * @inherits DivOverlay\r\n * @aka L.Popup\r\n * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to\r\n * open popups while making sure that only one popup is open at one time\r\n * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.\r\n *\r\n * @example\r\n *\r\n * If you want to just bind a popup to marker click and then open it, it's really easy:\r\n *\r\n * ```js\r\n * marker.bindPopup(popupContent).openPopup();\r\n * ```\r\n * Path overlays like polylines also have a `bindPopup` method.\r\n *\r\n * A popup can be also standalone:\r\n *\r\n * ```js\r\n * var popup = L.popup()\r\n * \t.setLatLng(latlng)\r\n * \t.setContent('<p>Hello world!<br />This is a nice popup.</p>')\r\n * \t.openOn(map);\r\n * ```\r\n * or\r\n * ```js\r\n * var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>')\r\n * \t.openOn(map);\r\n * ```\r\n */\r\n\r\n\r\n// @namespace Popup\r\nexport var Popup = DivOverlay.extend({\r\n\r\n\t// @section\r\n\t// @aka Popup options\r\n\toptions: {\r\n\t\t// @option pane: String = 'popupPane'\r\n\t\t// `Map pane` where the popup will be added.\r\n\t\tpane: 'popupPane',\r\n\r\n\t\t// @option offset: Point = Point(0, 7)\r\n\t\t// The offset of the popup position.\r\n\t\toffset: [0, 7],\r\n\r\n\t\t// @option maxWidth: Number = 300\r\n\t\t// Max width of the popup, in pixels.\r\n\t\tmaxWidth: 300,\r\n\r\n\t\t// @option minWidth: Number = 50\r\n\t\t// Min width of the popup, in pixels.\r\n\t\tminWidth: 50,\r\n\r\n\t\t// @option maxHeight: Number = null\r\n\t\t// If set, creates a scrollable container of the given height\r\n\t\t// inside a popup if its content exceeds it.\r\n\t\t// The scrollable container can be styled using the\r\n\t\t// `leaflet-popup-scrolled` CSS class selector.\r\n\t\tmaxHeight: null,\r\n\r\n\t\t// @option autoPan: Boolean = true\r\n\t\t// Set it to `false` if you don't want the map to do panning animation\r\n\t\t// to fit the opened popup.\r\n\t\tautoPan: true,\r\n\r\n\t\t// @option autoPanPaddingTopLeft: Point = null\r\n\t\t// The margin between the popup and the top left corner of the map\r\n\t\t// view after autopanning was performed.\r\n\t\tautoPanPaddingTopLeft: null,\r\n\r\n\t\t// @option autoPanPaddingBottomRight: Point = null\r\n\t\t// The margin between the popup and the bottom right corner of the map\r\n\t\t// view after autopanning was performed.\r\n\t\tautoPanPaddingBottomRight: null,\r\n\r\n\t\t// @option autoPanPadding: Point = Point(5, 5)\r\n\t\t// Equivalent of setting both top left and bottom right autopan padding to the same value.\r\n\t\tautoPanPadding: [5, 5],\r\n\r\n\t\t// @option keepInView: Boolean = false\r\n\t\t// Set it to `true` if you want to prevent users from panning the popup\r\n\t\t// off of the screen while it is open.\r\n\t\tkeepInView: false,\r\n\r\n\t\t// @option closeButton: Boolean = true\r\n\t\t// Controls the presence of a close button in the popup.\r\n\t\tcloseButton: true,\r\n\r\n\t\t// @option autoClose: Boolean = true\r\n\t\t// Set it to `false` if you want to override the default behavior of\r\n\t\t// the popup closing when another popup is opened.\r\n\t\tautoClose: true,\r\n\r\n\t\t// @option closeOnEscapeKey: Boolean = true\r\n\t\t// Set it to `false` if you want to override the default behavior of\r\n\t\t// the ESC key for closing of the popup.\r\n\t\tcloseOnEscapeKey: true,\r\n\r\n\t\t// @option closeOnClick: Boolean = *\r\n\t\t// Set it if you want to override the default behavior of the popup closing when user clicks\r\n\t\t// on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom CSS class name to assign to the popup.\r\n\t\tclassName: ''\r\n\t},\r\n\r\n\t// @namespace Popup\r\n\t// @method openOn(map: Map): this\r\n\t// Alternative to `map.openPopup(popup)`.\r\n\t// Adds the popup to the map and closes the previous one.\r\n\topenOn: function (map) {\r\n\t\tmap = arguments.length ? map : this._source._map; // experimental, not the part of public api\r\n\r\n\t\tif (!map.hasLayer(this) && map._popup && map._popup.options.autoClose) {\r\n\t\t\tmap.removeLayer(map._popup);\r\n\t\t}\r\n\t\tmap._popup = this;\r\n\r\n\t\treturn DivOverlay.prototype.openOn.call(this, map);\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tDivOverlay.prototype.onAdd.call(this, map);\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Popup events\r\n\t\t// @event popupopen: PopupEvent\r\n\t\t// Fired when a popup is opened in the map\r\n\t\tmap.fire('popupopen', {popup: this});\r\n\r\n\t\tif (this._source) {\r\n\t\t\t// @namespace Layer\r\n\t\t\t// @section Popup events\r\n\t\t\t// @event popupopen: PopupEvent\r\n\t\t\t// Fired when a popup bound to this layer is opened\r\n\t\t\tthis._source.fire('popupopen', {popup: this}, true);\r\n\t\t\t// For non-path layers, we toggle the popup when clicking\r\n\t\t\t// again the layer, so prevent the map to reopen it.\r\n\t\t\tif (!(this._source instanceof Path)) {\r\n\t\t\t\tthis._source.on('preclick', DomEvent.stopPropagation);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tDivOverlay.prototype.onRemove.call(this, map);\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Popup events\r\n\t\t// @event popupclose: PopupEvent\r\n\t\t// Fired when a popup in the map is closed\r\n\t\tmap.fire('popupclose', {popup: this});\r\n\r\n\t\tif (this._source) {\r\n\t\t\t// @namespace Layer\r\n\t\t\t// @section Popup events\r\n\t\t\t// @event popupclose: PopupEvent\r\n\t\t\t// Fired when a popup bound to this layer is closed\r\n\t\t\tthis._source.fire('popupclose', {popup: this}, true);\r\n\t\t\tif (!(this._source instanceof Path)) {\r\n\t\t\t\tthis._source.off('preclick', DomEvent.stopPropagation);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = DivOverlay.prototype.getEvents.call(this);\r\n\r\n\t\tif (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {\r\n\t\t\tevents.preclick = this.close;\r\n\t\t}\r\n\r\n\t\tif (this.options.keepInView) {\r\n\t\t\tevents.moveend = this._adjustPan;\r\n\t\t}\r\n\r\n\t\treturn events;\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar prefix = 'leaflet-popup',\r\n\t\t    container = this._container = DomUtil.create('div',\r\n\t\t\tprefix + ' ' + (this.options.className || '') +\r\n\t\t\t' leaflet-zoom-animated');\r\n\r\n\t\tvar wrapper = this._wrapper = DomUtil.create('div', prefix + '-content-wrapper', container);\r\n\t\tthis._contentNode = DomUtil.create('div', prefix + '-content', wrapper);\r\n\r\n\t\tDomEvent.disableClickPropagation(container);\r\n\t\tDomEvent.disableScrollPropagation(this._contentNode);\r\n\t\tDomEvent.on(container, 'contextmenu', DomEvent.stopPropagation);\r\n\r\n\t\tthis._tipContainer = DomUtil.create('div', prefix + '-tip-container', container);\r\n\t\tthis._tip = DomUtil.create('div', prefix + '-tip', this._tipContainer);\r\n\r\n\t\tif (this.options.closeButton) {\r\n\t\t\tvar closeButton = this._closeButton = DomUtil.create('a', prefix + '-close-button', container);\r\n\t\t\tcloseButton.setAttribute('role', 'button'); // overrides the implicit role=link of <a> elements #7399\r\n\t\t\tcloseButton.setAttribute('aria-label', 'Close popup');\r\n\t\t\tcloseButton.href = '#close';\r\n\t\t\tcloseButton.innerHTML = '<span aria-hidden=\"true\">&#215;</span>';\r\n\r\n\t\t\tDomEvent.on(closeButton, 'click', function (ev) {\r\n\t\t\t\tDomEvent.preventDefault(ev);\r\n\t\t\t\tthis.close();\r\n\t\t\t}, this);\r\n\t\t}\r\n\t},\r\n\r\n\t_updateLayout: function () {\r\n\t\tvar container = this._contentNode,\r\n\t\t    style = container.style;\r\n\r\n\t\tstyle.width = '';\r\n\t\tstyle.whiteSpace = 'nowrap';\r\n\r\n\t\tvar width = container.offsetWidth;\r\n\t\twidth = Math.min(width, this.options.maxWidth);\r\n\t\twidth = Math.max(width, this.options.minWidth);\r\n\r\n\t\tstyle.width = (width + 1) + 'px';\r\n\t\tstyle.whiteSpace = '';\r\n\r\n\t\tstyle.height = '';\r\n\r\n\t\tvar height = container.offsetHeight,\r\n\t\t    maxHeight = this.options.maxHeight,\r\n\t\t    scrolledClass = 'leaflet-popup-scrolled';\r\n\r\n\t\tif (maxHeight && height > maxHeight) {\r\n\t\t\tstyle.height = maxHeight + 'px';\r\n\t\t\tDomUtil.addClass(container, scrolledClass);\r\n\t\t} else {\r\n\t\t\tDomUtil.removeClass(container, scrolledClass);\r\n\t\t}\r\n\r\n\t\tthis._containerWidth = this._container.offsetWidth;\r\n\t},\r\n\r\n\t_animateZoom: function (e) {\r\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),\r\n\t\t    anchor = this._getAnchor();\r\n\t\tDomUtil.setPosition(this._container, pos.add(anchor));\r\n\t},\r\n\r\n\t_adjustPan: function () {\r\n\t\tif (!this.options.autoPan) { return; }\r\n\t\tif (this._map._panAnim) { this._map._panAnim.stop(); }\r\n\r\n\t\t// We can endlessly recurse if keepInView is set and the view resets.\r\n\t\t// Let's guard against that by exiting early if we're responding to our own autopan.\r\n\t\tif (this._autopanning) {\r\n\t\t\tthis._autopanning = false;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar map = this._map,\r\n\t\t    marginBottom = parseInt(DomUtil.getStyle(this._container, 'marginBottom'), 10) || 0,\r\n\t\t    containerHeight = this._container.offsetHeight + marginBottom,\r\n\t\t    containerWidth = this._containerWidth,\r\n\t\t    layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);\r\n\r\n\t\tlayerPos._add(DomUtil.getPosition(this._container));\r\n\r\n\t\tvar containerPos = map.layerPointToContainerPoint(layerPos),\r\n\t\t    padding = toPoint(this.options.autoPanPadding),\r\n\t\t    paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),\r\n\t\t    paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),\r\n\t\t    size = map.getSize(),\r\n\t\t    dx = 0,\r\n\t\t    dy = 0;\r\n\r\n\t\tif (containerPos.x + containerWidth + paddingBR.x > size.x) { // right\r\n\t\t\tdx = containerPos.x + containerWidth - size.x + paddingBR.x;\r\n\t\t}\r\n\t\tif (containerPos.x - dx - paddingTL.x < 0) { // left\r\n\t\t\tdx = containerPos.x - paddingTL.x;\r\n\t\t}\r\n\t\tif (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom\r\n\t\t\tdy = containerPos.y + containerHeight - size.y + paddingBR.y;\r\n\t\t}\r\n\t\tif (containerPos.y - dy - paddingTL.y < 0) { // top\r\n\t\t\tdy = containerPos.y - paddingTL.y;\r\n\t\t}\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Popup events\r\n\t\t// @event autopanstart: Event\r\n\t\t// Fired when the map starts autopanning when opening a popup.\r\n\t\tif (dx || dy) {\r\n\t\t\t// Track that we're autopanning, as this function will be re-ran on moveend\r\n\t\t\tif (this.options.keepInView) {\r\n\t\t\t\tthis._autopanning = true;\r\n\t\t\t}\r\n\r\n\t\t\tmap\r\n\t\t\t    .fire('autopanstart')\r\n\t\t\t    .panBy([dx, dy]);\r\n\t\t}\r\n\t},\r\n\r\n\t_getAnchor: function () {\r\n\t\t// Where should we anchor the popup on the source layer?\r\n\t\treturn toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);\r\n\t}\r\n\r\n});\r\n\r\n// @namespace Popup\r\n// @factory L.popup(options?: Popup options, source?: Layer)\r\n// Instantiates a `Popup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.\r\n// @alternative\r\n// @factory L.popup(latlng: LatLng, options?: Popup options)\r\n// Instantiates a `Popup` object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location.\r\nexport var popup = function (options, source) {\r\n\treturn new Popup(options, source);\r\n};\r\n\r\n\r\n/* @namespace Map\r\n * @section Interaction Options\r\n * @option closePopupOnClick: Boolean = true\r\n * Set it to `false` if you don't want popups to close when user clicks the map.\r\n */\r\nMap.mergeOptions({\r\n\tclosePopupOnClick: true\r\n});\r\n\r\n\r\n// @namespace Map\r\n// @section Methods for Layers and Controls\r\nMap.include({\r\n\t// @method openPopup(popup: Popup): this\r\n\t// Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).\r\n\t// @alternative\r\n\t// @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this\r\n\t// Creates a popup with the specified content and options and opens it in the given point on a map.\r\n\topenPopup: function (popup, latlng, options) {\r\n\t\tthis._initOverlay(Popup, popup, latlng, options)\r\n\t\t  .openOn(this);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method closePopup(popup?: Popup): this\r\n\t// Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).\r\n\tclosePopup: function (popup) {\r\n\t\tpopup = arguments.length ? popup : this._popup;\r\n\t\tif (popup) {\r\n\t\t\tpopup.close();\r\n\t\t}\r\n\t\treturn this;\r\n\t}\r\n});\r\n\r\n/*\r\n * @namespace Layer\r\n * @section Popup methods example\r\n *\r\n * All layers share a set of methods convenient for binding popups to it.\r\n *\r\n * ```js\r\n * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);\r\n * layer.openPopup();\r\n * layer.closePopup();\r\n * ```\r\n *\r\n * Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened.\r\n */\r\n\r\n// @section Popup methods\r\nLayer.include({\r\n\r\n\t// @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this\r\n\t// Binds a popup to the layer with the passed `content` and sets up the\r\n\t// necessary event listeners. If a `Function` is passed it will receive\r\n\t// the layer as the first argument and should return a `String` or `HTMLElement`.\r\n\tbindPopup: function (content, options) {\r\n\t\tthis._popup = this._initOverlay(Popup, this._popup, content, options);\r\n\t\tif (!this._popupHandlersAdded) {\r\n\t\t\tthis.on({\r\n\t\t\t\tclick: this._openPopup,\r\n\t\t\t\tkeypress: this._onKeyPress,\r\n\t\t\t\tremove: this.closePopup,\r\n\t\t\t\tmove: this._movePopup\r\n\t\t\t});\r\n\t\t\tthis._popupHandlersAdded = true;\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method unbindPopup(): this\r\n\t// Removes the popup previously bound with `bindPopup`.\r\n\tunbindPopup: function () {\r\n\t\tif (this._popup) {\r\n\t\t\tthis.off({\r\n\t\t\t\tclick: this._openPopup,\r\n\t\t\t\tkeypress: this._onKeyPress,\r\n\t\t\t\tremove: this.closePopup,\r\n\t\t\t\tmove: this._movePopup\r\n\t\t\t});\r\n\t\t\tthis._popupHandlersAdded = false;\r\n\t\t\tthis._popup = null;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method openPopup(latlng?: LatLng): this\r\n\t// Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.\r\n\topenPopup: function (latlng) {\r\n\t\tif (this._popup) {\r\n\t\t\tif (!(this instanceof FeatureGroup)) {\r\n\t\t\t\tthis._popup._source = this;\r\n\t\t\t}\r\n\t\t\tif (this._popup._prepareOpen(latlng || this._latlng)) {\r\n\t\t\t\t// open the popup on the map\r\n\t\t\t\tthis._popup.openOn(this._map);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method closePopup(): this\r\n\t// Closes the popup bound to this layer if it is open.\r\n\tclosePopup: function () {\r\n\t\tif (this._popup) {\r\n\t\t\tthis._popup.close();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method togglePopup(): this\r\n\t// Opens or closes the popup bound to this layer depending on its current state.\r\n\ttogglePopup: function () {\r\n\t\tif (this._popup) {\r\n\t\t\tthis._popup.toggle(this);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method isPopupOpen(): boolean\r\n\t// Returns `true` if the popup bound to this layer is currently open.\r\n\tisPopupOpen: function () {\r\n\t\treturn (this._popup ? this._popup.isOpen() : false);\r\n\t},\r\n\r\n\t// @method setPopupContent(content: String|HTMLElement|Popup): this\r\n\t// Sets the content of the popup bound to this layer.\r\n\tsetPopupContent: function (content) {\r\n\t\tif (this._popup) {\r\n\t\t\tthis._popup.setContent(content);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getPopup(): Popup\r\n\t// Returns the popup bound to this layer.\r\n\tgetPopup: function () {\r\n\t\treturn this._popup;\r\n\t},\r\n\r\n\t_openPopup: function (e) {\r\n\t\tif (!this._popup || !this._map) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t// prevent map click\r\n\t\tDomEvent.stop(e);\r\n\r\n\t\tvar target = e.layer || e.target;\r\n\t\tif (this._popup._source === target && !(target instanceof Path)) {\r\n\t\t\t// treat it like a marker and figure out\r\n\t\t\t// if we should toggle it open/closed\r\n\t\t\tif (this._map.hasLayer(this._popup)) {\r\n\t\t\t\tthis.closePopup();\r\n\t\t\t} else {\r\n\t\t\t\tthis.openPopup(e.latlng);\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tthis._popup._source = target;\r\n\t\tthis.openPopup(e.latlng);\r\n\t},\r\n\r\n\t_movePopup: function (e) {\r\n\t\tthis._popup.setLatLng(e.latlng);\r\n\t},\r\n\r\n\t_onKeyPress: function (e) {\r\n\t\tif (e.originalEvent.keyCode === 13) {\r\n\t\t\tthis._openPopup(e);\r\n\t\t}\r\n\t}\r\n});\r\n", "import {DivOverlay} from './DivOverlay';\nimport {toPoint} from '../geometry/Point';\nimport {Map} from '../map/Map';\nimport {Layer} from './Layer';\nimport * as DomUtil from '../dom/DomUtil';\nimport * as DomEvent from '../dom/DomEvent';\nimport * as Util from '../core/Util';\nimport {FeatureGroup} from './FeatureGroup';\n\n/*\n * @class Tooltip\n * @inherits DivOverlay\n * @aka L.Tooltip\n * Used to display small texts on top of map layers.\n *\n * @example\n * If you want to just bind a tooltip to marker:\n *\n * ```js\n * marker.bindTooltip(\"my tooltip text\").openTooltip();\n * ```\n * Path overlays like polylines also have a `bindTooltip` method.\n *\n * A tooltip can be also standalone:\n *\n * ```js\n * var tooltip = L.tooltip()\n * \t.setLatLng(latlng)\n * \t.setContent('Hello world!<br />This is a nice tooltip.')\n * \t.addTo(map);\n * ```\n * or\n * ```js\n * var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})\n * \t.addTo(map);\n * ```\n *\n *\n * Note about tooltip offset. Leaflet takes two options in consideration\n * for computing tooltip offsetting:\n * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.\n *   Add a positive x offset to move the tooltip to the right, and a positive y offset to\n *   move it to the bottom. Negatives will move to the left and top.\n * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You\n *   should adapt this value if you use a custom icon.\n */\n\n\n// @namespace Tooltip\nexport var Tooltip = DivOverlay.extend({\n\n\t// @section\n\t// @aka Tooltip options\n\toptions: {\n\t\t// @option pane: String = 'tooltipPane'\n\t\t// `Map pane` where the tooltip will be added.\n\t\tpane: 'tooltipPane',\n\n\t\t// @option offset: Point = Point(0, 0)\n\t\t// Optional offset of the tooltip position.\n\t\toffset: [0, 0],\n\n\t\t// @option direction: String = 'auto'\n\t\t// Direction where to open the tooltip. Possible values are: `right`, `left`,\n\t\t// `top`, `bottom`, `center`, `auto`.\n\t\t// `auto` will dynamically switch between `right` and `left` according to the tooltip\n\t\t// position on the map.\n\t\tdirection: 'auto',\n\n\t\t// @option permanent: Boolean = false\n\t\t// Whether to open the tooltip permanently or only on mouseover.\n\t\tpermanent: false,\n\n\t\t// @option sticky: Boolean = false\n\t\t// If true, the tooltip will follow the mouse instead of being fixed at the feature center.\n\t\tsticky: false,\n\n\t\t// @option opacity: Number = 0.9\n\t\t// Tooltip container opacity.\n\t\topacity: 0.9\n\t},\n\n\tonAdd: function (map) {\n\t\tDivOverlay.prototype.onAdd.call(this, map);\n\t\tthis.setOpacity(this.options.opacity);\n\n\t\t// @namespace Map\n\t\t// @section Tooltip events\n\t\t// @event tooltipopen: TooltipEvent\n\t\t// Fired when a tooltip is opened in the map.\n\t\tmap.fire('tooltipopen', {tooltip: this});\n\n\t\tif (this._source) {\n\t\t\tthis.addEventParent(this._source);\n\n\t\t\t// @namespace Layer\n\t\t\t// @section Tooltip events\n\t\t\t// @event tooltipopen: TooltipEvent\n\t\t\t// Fired when a tooltip bound to this layer is opened.\n\t\t\tthis._source.fire('tooltipopen', {tooltip: this}, true);\n\t\t}\n\t},\n\n\tonRemove: function (map) {\n\t\tDivOverlay.prototype.onRemove.call(this, map);\n\n\t\t// @namespace Map\n\t\t// @section Tooltip events\n\t\t// @event tooltipclose: TooltipEvent\n\t\t// Fired when a tooltip in the map is closed.\n\t\tmap.fire('tooltipclose', {tooltip: this});\n\n\t\tif (this._source) {\n\t\t\tthis.removeEventParent(this._source);\n\n\t\t\t// @namespace Layer\n\t\t\t// @section Tooltip events\n\t\t\t// @event tooltipclose: TooltipEvent\n\t\t\t// Fired when a tooltip bound to this layer is closed.\n\t\t\tthis._source.fire('tooltipclose', {tooltip: this}, true);\n\t\t}\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = DivOverlay.prototype.getEvents.call(this);\n\n\t\tif (!this.options.permanent) {\n\t\t\tevents.preclick = this.close;\n\t\t}\n\n\t\treturn events;\n\t},\n\n\t_initLayout: function () {\n\t\tvar prefix = 'leaflet-tooltip',\n\t\t    className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');\n\n\t\tthis._contentNode = this._container = DomUtil.create('div', className);\n\n\t\tthis._container.setAttribute('role', 'tooltip');\n\t\tthis._container.setAttribute('id', 'leaflet-tooltip-' + Util.stamp(this));\n\t},\n\n\t_updateLayout: function () {},\n\n\t_adjustPan: function () {},\n\n\t_setPosition: function (pos) {\n\t\tvar subX, subY,\n\t\t    map = this._map,\n\t\t    container = this._container,\n\t\t    centerPoint = map.latLngToContainerPoint(map.getCenter()),\n\t\t    tooltipPoint = map.layerPointToContainerPoint(pos),\n\t\t    direction = this.options.direction,\n\t\t    tooltipWidth = container.offsetWidth,\n\t\t    tooltipHeight = container.offsetHeight,\n\t\t    offset = toPoint(this.options.offset),\n\t\t    anchor = this._getAnchor();\n\n\t\tif (direction === 'top') {\n\t\t\tsubX = tooltipWidth / 2;\n\t\t\tsubY = tooltipHeight;\n\t\t} else if (direction === 'bottom') {\n\t\t\tsubX = tooltipWidth / 2;\n\t\t\tsubY = 0;\n\t\t} else if (direction === 'center') {\n\t\t\tsubX = tooltipWidth / 2;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else if (direction === 'right') {\n\t\t\tsubX = 0;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else if (direction === 'left') {\n\t\t\tsubX = tooltipWidth;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else if (tooltipPoint.x < centerPoint.x) {\n\t\t\tdirection = 'right';\n\t\t\tsubX = 0;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else {\n\t\t\tdirection = 'left';\n\t\t\tsubX = tooltipWidth + (offset.x + anchor.x) * 2;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t}\n\n\t\tpos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);\n\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-right');\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-left');\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-top');\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-bottom');\n\t\tDomUtil.addClass(container, 'leaflet-tooltip-' + direction);\n\t\tDomUtil.setPosition(container, pos);\n\t},\n\n\t_updatePosition: function () {\n\t\tvar pos = this._map.latLngToLayerPoint(this._latlng);\n\t\tthis._setPosition(pos);\n\t},\n\n\tsetOpacity: function (opacity) {\n\t\tthis.options.opacity = opacity;\n\n\t\tif (this._container) {\n\t\t\tDomUtil.setOpacity(this._container, opacity);\n\t\t}\n\t},\n\n\t_animateZoom: function (e) {\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);\n\t\tthis._setPosition(pos);\n\t},\n\n\t_getAnchor: function () {\n\t\t// Where should we anchor the tooltip on the source layer?\n\t\treturn toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);\n\t}\n\n});\n\n// @namespace Tooltip\n// @factory L.tooltip(options?: Tooltip options, source?: Layer)\n// Instantiates a `Tooltip` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers.\n// @alternative\n// @factory L.tooltip(latlng: LatLng, options?: Tooltip options)\n// Instantiates a `Tooltip` object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location.\nexport var tooltip = function (options, source) {\n\treturn new Tooltip(options, source);\n};\n\n// @namespace Map\n// @section Methods for Layers and Controls\nMap.include({\n\n\t// @method openTooltip(tooltip: Tooltip): this\n\t// Opens the specified tooltip.\n\t// @alternative\n\t// @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this\n\t// Creates a tooltip with the specified content and options and open it.\n\topenTooltip: function (tooltip, latlng, options) {\n\t\tthis._initOverlay(Tooltip, tooltip, latlng, options)\n\t\t  .openOn(this);\n\n\t\treturn this;\n\t},\n\n\t// @method closeTooltip(tooltip: Tooltip): this\n\t// Closes the tooltip given as parameter.\n\tcloseTooltip: function (tooltip) {\n\t\ttooltip.close();\n\t\treturn this;\n\t}\n\n});\n\n/*\n * @namespace Layer\n * @section Tooltip methods example\n *\n * All layers share a set of methods convenient for binding tooltips to it.\n *\n * ```js\n * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);\n * layer.openTooltip();\n * layer.closeTooltip();\n * ```\n */\n\n// @section Tooltip methods\nLayer.include({\n\n\t// @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this\n\t// Binds a tooltip to the layer with the passed `content` and sets up the\n\t// necessary event listeners. If a `Function` is passed it will receive\n\t// the layer as the first argument and should return a `String` or `HTMLElement`.\n\tbindTooltip: function (content, options) {\n\n\t\tif (this._tooltip && this.isTooltipOpen()) {\n\t\t\tthis.unbindTooltip();\n\t\t}\n\n\t\tthis._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);\n\t\tthis._initTooltipInteractions();\n\n\t\tif (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {\n\t\t\tthis.openTooltip();\n\t\t}\n\n\t\treturn this;\n\t},\n\n\t// @method unbindTooltip(): this\n\t// Removes the tooltip previously bound with `bindTooltip`.\n\tunbindTooltip: function () {\n\t\tif (this._tooltip) {\n\t\t\tthis._initTooltipInteractions(true);\n\t\t\tthis.closeTooltip();\n\t\t\tthis._tooltip = null;\n\t\t}\n\t\treturn this;\n\t},\n\n\t_initTooltipInteractions: function (remove) {\n\t\tif (!remove && this._tooltipHandlersAdded) { return; }\n\t\tvar onOff = remove ? 'off' : 'on',\n\t\t    events = {\n\t\t\tremove: this.closeTooltip,\n\t\t\tmove: this._moveTooltip\n\t\t    };\n\t\tif (!this._tooltip.options.permanent) {\n\t\t\tevents.mouseover = this._openTooltip;\n\t\t\tevents.mouseout = this.closeTooltip;\n\t\t\tevents.click = this._openTooltip;\n\t\t\tif (this._map) {\n\t\t\t\tthis._addFocusListeners();\n\t\t\t} else {\n\t\t\t\tevents.add = this._addFocusListeners;\n\t\t\t}\n\t\t} else {\n\t\t\tevents.add = this._openTooltip;\n\t\t}\n\t\tif (this._tooltip.options.sticky) {\n\t\t\tevents.mousemove = this._moveTooltip;\n\t\t}\n\t\tthis[onOff](events);\n\t\tthis._tooltipHandlersAdded = !remove;\n\t},\n\n\t// @method openTooltip(latlng?: LatLng): this\n\t// Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.\n\topenTooltip: function (latlng) {\n\t\tif (this._tooltip) {\n\t\t\tif (!(this instanceof FeatureGroup)) {\n\t\t\t\tthis._tooltip._source = this;\n\t\t\t}\n\t\t\tif (this._tooltip._prepareOpen(latlng)) {\n\t\t\t\t// open the tooltip on the map\n\t\t\t\tthis._tooltip.openOn(this._map);\n\n\t\t\t\tif (this.getElement) {\n\t\t\t\t\tthis._setAriaDescribedByOnLayer(this);\n\t\t\t\t} else if (this.eachLayer) {\n\t\t\t\t\tthis.eachLayer(this._setAriaDescribedByOnLayer, this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method closeTooltip(): this\n\t// Closes the tooltip bound to this layer if it is open.\n\tcloseTooltip: function () {\n\t\tif (this._tooltip) {\n\t\t\treturn this._tooltip.close();\n\t\t}\n\t},\n\n\t// @method toggleTooltip(): this\n\t// Opens or closes the tooltip bound to this layer depending on its current state.\n\ttoggleTooltip: function () {\n\t\tif (this._tooltip) {\n\t\t\tthis._tooltip.toggle(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method isTooltipOpen(): boolean\n\t// Returns `true` if the tooltip bound to this layer is currently open.\n\tisTooltipOpen: function () {\n\t\treturn this._tooltip.isOpen();\n\t},\n\n\t// @method setTooltipContent(content: String|HTMLElement|Tooltip): this\n\t// Sets the content of the tooltip bound to this layer.\n\tsetTooltipContent: function (content) {\n\t\tif (this._tooltip) {\n\t\t\tthis._tooltip.setContent(content);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getTooltip(): Tooltip\n\t// Returns the tooltip bound to this layer.\n\tgetTooltip: function () {\n\t\treturn this._tooltip;\n\t},\n\n\t_addFocusListeners: function () {\n\t\tif (this.getElement) {\n\t\t\tthis._addFocusListenersOnLayer(this);\n\t\t} else if (this.eachLayer) {\n\t\t\tthis.eachLayer(this._addFocusListenersOnLayer, this);\n\t\t}\n\t},\n\n\t_addFocusListenersOnLayer: function (layer) {\n\t\tvar el = typeof layer.getElement === 'function' && layer.getElement();\n\t\tif (el) {\n\t\t\tDomEvent.on(el, 'focus', function () {\n\t\t\t\tthis._tooltip._source = layer;\n\t\t\t\tthis.openTooltip();\n\t\t\t}, this);\n\t\t\tDomEvent.on(el, 'blur', this.closeTooltip, this);\n\t\t}\n\t},\n\n\t_setAriaDescribedByOnLayer: function (layer) {\n\t\tvar el = typeof layer.getElement === 'function' && layer.getElement();\n\t\tif (el) {\n\t\t\tel.setAttribute('aria-describedby', this._tooltip._container.id);\n\t\t}\n\t},\n\n\n\t_openTooltip: function (e) {\n\t\tif (!this._tooltip || !this._map) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If the map is moving, we will show the tooltip after it's done.\n\t\tif (this._map.dragging && this._map.dragging.moving() && !this._openOnceFlag) {\n\t\t\tthis._openOnceFlag = true;\n\t\t\tvar that = this;\n\t\t\tthis._map.once('moveend', function () {\n\t\t\t\tthat._openOnceFlag = false;\n\t\t\t\tthat._openTooltip(e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._tooltip._source = e.layer || e.target;\n\n\t\tthis.openTooltip(this._tooltip.options.sticky ? e.latlng : undefined);\n\t},\n\n\t_moveTooltip: function (e) {\n\t\tvar latlng = e.latlng, containerPoint, layerPoint;\n\t\tif (this._tooltip.options.sticky && e.originalEvent) {\n\t\t\tcontainerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);\n\t\t\tlayerPoint = this._map.containerPointToLayerPoint(containerPoint);\n\t\t\tlatlng = this._map.layerPointToLatLng(layerPoint);\n\t\t}\n\t\tthis._tooltip.setLatLng(latlng);\n\t}\n});\n", "import {Icon} from './Icon';\nimport {toPoint as point} from '../../geometry/Point';\nimport {empty} from '../../dom/DomUtil';\n\n/*\n * @class DivIcon\n * @aka L.DivIcon\n * @inherits Icon\n *\n * Represents a lightweight icon for markers that uses a simple `<div>`\n * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.\n *\n * @example\n * ```js\n * var myIcon = L.divIcon({className: 'my-div-icon'});\n * // you can set .my-div-icon styles in CSS\n *\n * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);\n * ```\n *\n * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.\n */\n\nexport var DivIcon = Icon.extend({\n\toptions: {\n\t\t// @section\n\t\t// @aka DivIcon options\n\t\ticonSize: [12, 12], // also can be set through CSS\n\n\t\t// iconAnchor: (Point),\n\t\t// popupAnchor: (Point),\n\n\t\t// @option html: String|HTMLElement = ''\n\t\t// Custom HTML code to put inside the div element, empty by default. Alternatively,\n\t\t// an instance of `HTMLElement`.\n\t\thtml: false,\n\n\t\t// @option bgPos: Point = [0, 0]\n\t\t// Optional relative position of the background, in pixels\n\t\tbgPos: null,\n\n\t\tclassName: 'leaflet-div-icon'\n\t},\n\n\tcreateIcon: function (oldIcon) {\n\t\tvar div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),\n\t\t    options = this.options;\n\n\t\tif (options.html instanceof Element) {\n\t\t\tempty(div);\n\t\t\tdiv.appendChild(options.html);\n\t\t} else {\n\t\t\tdiv.innerHTML = options.html !== false ? options.html : '';\n\t\t}\n\n\t\tif (options.bgPos) {\n\t\t\tvar bgPos = point(options.bgPos);\n\t\t\tdiv.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';\n\t\t}\n\t\tthis._setIconStyles(div, 'icon');\n\n\t\treturn div;\n\t},\n\n\tcreateShadow: function () {\n\t\treturn null;\n\t}\n});\n\n// @factory L.divIcon(options: DivIcon options)\n// Creates a `DivIcon` instance with the given options.\nexport function divIcon(options) {\n\treturn new DivIcon(options);\n}\n", "import {Icon} from './Icon';\nexport {icon} from './Icon';\nimport {IconDefault} from './Icon.Default';\nIcon.Default = IconDefault;\nexport {Icon};\n\nexport {DivIcon, divIcon} from './DivIcon';\nexport {Marker, marker} from './Marker';\n", "import {Layer} from '../Layer';\nimport Browser from '../../core/Browser';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport {Point} from '../../geometry/Point';\nimport {Bounds} from '../../geometry/Bounds';\nimport {LatLngBounds, toLatLngBounds as latLngBounds} from '../../geo/LatLngBounds';\n\n/*\n * @class GridLayer\n * @inherits Layer\n * @aka L.GridLayer\n *\n * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.\n * GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you.\n *\n *\n * @section Synchronous usage\n * @example\n *\n * To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile.\n *\n * ```js\n * var CanvasLayer = L.GridLayer.extend({\n *     createTile: function(coords){\n *         // create a <canvas> element for drawing\n *         var tile = L.DomUtil.create('canvas', 'leaflet-tile');\n *\n *         // setup tile width and height according to the options\n *         var size = this.getTileSize();\n *         tile.width = size.x;\n *         tile.height = size.y;\n *\n *         // get a canvas context and draw something on it using coords.x, coords.y and coords.z\n *         var ctx = tile.getContext('2d');\n *\n *         // return the tile so it can be rendered on screen\n *         return tile;\n *     }\n * });\n * ```\n *\n * @section Asynchronous usage\n * @example\n *\n * Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback.\n *\n * ```js\n * var CanvasLayer = L.GridLayer.extend({\n *     createTile: function(coords, done){\n *         var error;\n *\n *         // create a <canvas> element for drawing\n *         var tile = L.DomUtil.create('canvas', 'leaflet-tile');\n *\n *         // setup tile width and height according to the options\n *         var size = this.getTileSize();\n *         tile.width = size.x;\n *         tile.height = size.y;\n *\n *         // draw something asynchronously and pass the tile to the done() callback\n *         setTimeout(function() {\n *             done(error, tile);\n *         }, 1000);\n *\n *         return tile;\n *     }\n * });\n * ```\n *\n * @section\n */\n\n\nexport var GridLayer = Layer.extend({\n\n\t// @section\n\t// @aka GridLayer options\n\toptions: {\n\t\t// @option tileSize: Number|Point = 256\n\t\t// Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.\n\t\ttileSize: 256,\n\n\t\t// @option opacity: Number = 1.0\n\t\t// Opacity of the tiles. Can be used in the `createTile()` function.\n\t\topacity: 1,\n\n\t\t// @option updateWhenIdle: Boolean = (depends)\n\t\t// Load new tiles only when panning ends.\n\t\t// `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.\n\t\t// `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the\n\t\t// [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.\n\t\tupdateWhenIdle: Browser.mobile,\n\n\t\t// @option updateWhenZooming: Boolean = true\n\t\t// By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.\n\t\tupdateWhenZooming: true,\n\n\t\t// @option updateInterval: Number = 200\n\t\t// Tiles will not update more than once every `updateInterval` milliseconds when panning.\n\t\tupdateInterval: 200,\n\n\t\t// @option zIndex: Number = 1\n\t\t// The explicit zIndex of the tile layer.\n\t\tzIndex: 1,\n\n\t\t// @option bounds: LatLngBounds = undefined\n\t\t// If set, tiles will only be loaded inside the set `LatLngBounds`.\n\t\tbounds: null,\n\n\t\t// @option minZoom: Number = 0\n\t\t// The minimum zoom level down to which this layer will be displayed (inclusive).\n\t\tminZoom: 0,\n\n\t\t// @option maxZoom: Number = undefined\n\t\t// The maximum zoom level up to which this layer will be displayed (inclusive).\n\t\tmaxZoom: undefined,\n\n\t\t// @option maxNativeZoom: Number = undefined\n\t\t// Maximum zoom number the tile source has available. If it is specified,\n\t\t// the tiles on all zoom levels higher than `maxNativeZoom` will be loaded\n\t\t// from `maxNativeZoom` level and auto-scaled.\n\t\tmaxNativeZoom: undefined,\n\n\t\t// @option minNativeZoom: Number = undefined\n\t\t// Minimum zoom number the tile source has available. If it is specified,\n\t\t// the tiles on all zoom levels lower than `minNativeZoom` will be loaded\n\t\t// from `minNativeZoom` level and auto-scaled.\n\t\tminNativeZoom: undefined,\n\n\t\t// @option noWrap: Boolean = false\n\t\t// Whether the layer is wrapped around the antimeridian. If `true`, the\n\t\t// GridLayer will only be displayed once at low zoom levels. Has no\n\t\t// effect when the [map CRS](#map-crs) doesn't wrap around. Can be used\n\t\t// in combination with [`bounds`](#gridlayer-bounds) to prevent requesting\n\t\t// tiles outside the CRS limits.\n\t\tnoWrap: false,\n\n\t\t// @option pane: String = 'tilePane'\n\t\t// `Map pane` where the grid layer will be added.\n\t\tpane: 'tilePane',\n\n\t\t// @option className: String = ''\n\t\t// A custom class name to assign to the tile layer. Empty by default.\n\t\tclassName: '',\n\n\t\t// @option keepBuffer: Number = 2\n\t\t// When panning the map, keep this many rows and columns of tiles before unloading them.\n\t\tkeepBuffer: 2\n\t},\n\n\tinitialize: function (options) {\n\t\tUtil.setOptions(this, options);\n\t},\n\n\tonAdd: function () {\n\t\tthis._initContainer();\n\n\t\tthis._levels = {};\n\t\tthis._tiles = {};\n\n\t\tthis._resetView(); // implicit _update() call\n\t},\n\n\tbeforeAdd: function (map) {\n\t\tmap._addZoomLimit(this);\n\t},\n\n\tonRemove: function (map) {\n\t\tthis._removeAllTiles();\n\t\tDomUtil.remove(this._container);\n\t\tmap._removeZoomLimit(this);\n\t\tthis._container = null;\n\t\tthis._tileZoom = undefined;\n\t},\n\n\t// @method bringToFront: this\n\t// Brings the tile layer to the top of all tile layers.\n\tbringToFront: function () {\n\t\tif (this._map) {\n\t\t\tDomUtil.toFront(this._container);\n\t\t\tthis._setAutoZIndex(Math.max);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToBack: this\n\t// Brings the tile layer to the bottom of all tile layers.\n\tbringToBack: function () {\n\t\tif (this._map) {\n\t\t\tDomUtil.toBack(this._container);\n\t\t\tthis._setAutoZIndex(Math.min);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getContainer: HTMLElement\n\t// Returns the HTML element that contains the tiles for this layer.\n\tgetContainer: function () {\n\t\treturn this._container;\n\t},\n\n\t// @method setOpacity(opacity: Number): this\n\t// Changes the [opacity](#gridlayer-opacity) of the grid layer.\n\tsetOpacity: function (opacity) {\n\t\tthis.options.opacity = opacity;\n\t\tthis._updateOpacity();\n\t\treturn this;\n\t},\n\n\t// @method setZIndex(zIndex: Number): this\n\t// Changes the [zIndex](#gridlayer-zindex) of the grid layer.\n\tsetZIndex: function (zIndex) {\n\t\tthis.options.zIndex = zIndex;\n\t\tthis._updateZIndex();\n\n\t\treturn this;\n\t},\n\n\t// @method isLoading: Boolean\n\t// Returns `true` if any tile in the grid layer has not finished loading.\n\tisLoading: function () {\n\t\treturn this._loading;\n\t},\n\n\t// @method redraw: this\n\t// Causes the layer to clear all the tiles and request them again.\n\tredraw: function () {\n\t\tif (this._map) {\n\t\t\tthis._removeAllTiles();\n\t\t\tvar tileZoom = this._clampZoom(this._map.getZoom());\n\t\t\tif (tileZoom !== this._tileZoom) {\n\t\t\t\tthis._tileZoom = tileZoom;\n\t\t\t\tthis._updateLevels();\n\t\t\t}\n\t\t\tthis._update();\n\t\t}\n\t\treturn this;\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = {\n\t\t\tviewprereset: this._invalidateAll,\n\t\t\tviewreset: this._resetView,\n\t\t\tzoom: this._resetView,\n\t\t\tmoveend: this._onMoveEnd\n\t\t};\n\n\t\tif (!this.options.updateWhenIdle) {\n\t\t\t// update tiles on move, but not more often than once per given interval\n\t\t\tif (!this._onMove) {\n\t\t\t\tthis._onMove = Util.throttle(this._onMoveEnd, this.options.updateInterval, this);\n\t\t\t}\n\n\t\t\tevents.move = this._onMove;\n\t\t}\n\n\t\tif (this._zoomAnimated) {\n\t\t\tevents.zoomanim = this._animateZoom;\n\t\t}\n\n\t\treturn events;\n\t},\n\n\t// @section Extension methods\n\t// Layers extending `GridLayer` shall reimplement the following method.\n\t// @method createTile(coords: Object, done?: Function): HTMLElement\n\t// Called only internally, must be overridden by classes extending `GridLayer`.\n\t// Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback\n\t// is specified, it must be called when the tile has finished loading and drawing.\n\tcreateTile: function () {\n\t\treturn document.createElement('div');\n\t},\n\n\t// @section\n\t// @method getTileSize: Point\n\t// Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.\n\tgetTileSize: function () {\n\t\tvar s = this.options.tileSize;\n\t\treturn s instanceof Point ? s : new Point(s, s);\n\t},\n\n\t_updateZIndex: function () {\n\t\tif (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {\n\t\t\tthis._container.style.zIndex = this.options.zIndex;\n\t\t}\n\t},\n\n\t_setAutoZIndex: function (compare) {\n\t\t// go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)\n\n\t\tvar layers = this.getPane().children,\n\t\t    edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min\n\n\t\tfor (var i = 0, len = layers.length, zIndex; i < len; i++) {\n\n\t\t\tzIndex = layers[i].style.zIndex;\n\n\t\t\tif (layers[i] !== this._container && zIndex) {\n\t\t\t\tedgeZIndex = compare(edgeZIndex, +zIndex);\n\t\t\t}\n\t\t}\n\n\t\tif (isFinite(edgeZIndex)) {\n\t\t\tthis.options.zIndex = edgeZIndex + compare(-1, 1);\n\t\t\tthis._updateZIndex();\n\t\t}\n\t},\n\n\t_updateOpacity: function () {\n\t\tif (!this._map) { return; }\n\n\t\t// IE doesn't inherit filter opacity properly, so we're forced to set it on tiles\n\t\tif (Browser.ielt9) { return; }\n\n\t\tDomUtil.setOpacity(this._container, this.options.opacity);\n\n\t\tvar now = +new Date(),\n\t\t    nextFrame = false,\n\t\t    willPrune = false;\n\n\t\tfor (var key in this._tiles) {\n\t\t\tvar tile = this._tiles[key];\n\t\t\tif (!tile.current || !tile.loaded) { continue; }\n\n\t\t\tvar fade = Math.min(1, (now - tile.loaded) / 200);\n\n\t\t\tDomUtil.setOpacity(tile.el, fade);\n\t\t\tif (fade < 1) {\n\t\t\t\tnextFrame = true;\n\t\t\t} else {\n\t\t\t\tif (tile.active) {\n\t\t\t\t\twillPrune = true;\n\t\t\t\t} else {\n\t\t\t\t\tthis._onOpaqueTile(tile);\n\t\t\t\t}\n\t\t\t\ttile.active = true;\n\t\t\t}\n\t\t}\n\n\t\tif (willPrune && !this._noPrune) { this._pruneTiles(); }\n\n\t\tif (nextFrame) {\n\t\t\tUtil.cancelAnimFrame(this._fadeFrame);\n\t\t\tthis._fadeFrame = Util.requestAnimFrame(this._updateOpacity, this);\n\t\t}\n\t},\n\n\t_onOpaqueTile: Util.falseFn,\n\n\t_initContainer: function () {\n\t\tif (this._container) { return; }\n\n\t\tthis._container = DomUtil.create('div', 'leaflet-layer ' + (this.options.className || ''));\n\t\tthis._updateZIndex();\n\n\t\tif (this.options.opacity < 1) {\n\t\t\tthis._updateOpacity();\n\t\t}\n\n\t\tthis.getPane().appendChild(this._container);\n\t},\n\n\t_updateLevels: function () {\n\n\t\tvar zoom = this._tileZoom,\n\t\t    maxZoom = this.options.maxZoom;\n\n\t\tif (zoom === undefined) { return undefined; }\n\n\t\tfor (var z in this._levels) {\n\t\t\tz = Number(z);\n\t\t\tif (this._levels[z].el.children.length || z === zoom) {\n\t\t\t\tthis._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);\n\t\t\t\tthis._onUpdateLevel(z);\n\t\t\t} else {\n\t\t\t\tDomUtil.remove(this._levels[z].el);\n\t\t\t\tthis._removeTilesAtZoom(z);\n\t\t\t\tthis._onRemoveLevel(z);\n\t\t\t\tdelete this._levels[z];\n\t\t\t}\n\t\t}\n\n\t\tvar level = this._levels[zoom],\n\t\t    map = this._map;\n\n\t\tif (!level) {\n\t\t\tlevel = this._levels[zoom] = {};\n\n\t\t\tlevel.el = DomUtil.create('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);\n\t\t\tlevel.el.style.zIndex = maxZoom;\n\n\t\t\tlevel.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();\n\t\t\tlevel.zoom = zoom;\n\n\t\t\tthis._setZoomTransform(level, map.getCenter(), map.getZoom());\n\n\t\t\t// force the browser to consider the newly added element for transition\n\t\t\tUtil.falseFn(level.el.offsetWidth);\n\n\t\t\tthis._onCreateLevel(level);\n\t\t}\n\n\t\tthis._level = level;\n\n\t\treturn level;\n\t},\n\n\t_onUpdateLevel: Util.falseFn,\n\n\t_onRemoveLevel: Util.falseFn,\n\n\t_onCreateLevel: Util.falseFn,\n\n\t_pruneTiles: function () {\n\t\tif (!this._map) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar key, tile;\n\n\t\tvar zoom = this._map.getZoom();\n\t\tif (zoom > this.options.maxZoom ||\n\t\t\tzoom < this.options.minZoom) {\n\t\t\tthis._removeAllTiles();\n\t\t\treturn;\n\t\t}\n\n\t\tfor (key in this._tiles) {\n\t\t\ttile = this._tiles[key];\n\t\t\ttile.retain = tile.current;\n\t\t}\n\n\t\tfor (key in this._tiles) {\n\t\t\ttile = this._tiles[key];\n\t\t\tif (tile.current && !tile.active) {\n\t\t\t\tvar coords = tile.coords;\n\t\t\t\tif (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {\n\t\t\t\t\tthis._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (key in this._tiles) {\n\t\t\tif (!this._tiles[key].retain) {\n\t\t\t\tthis._removeTile(key);\n\t\t\t}\n\t\t}\n\t},\n\n\t_removeTilesAtZoom: function (zoom) {\n\t\tfor (var key in this._tiles) {\n\t\t\tif (this._tiles[key].coords.z !== zoom) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._removeTile(key);\n\t\t}\n\t},\n\n\t_removeAllTiles: function () {\n\t\tfor (var key in this._tiles) {\n\t\t\tthis._removeTile(key);\n\t\t}\n\t},\n\n\t_invalidateAll: function () {\n\t\tfor (var z in this._levels) {\n\t\t\tDomUtil.remove(this._levels[z].el);\n\t\t\tthis._onRemoveLevel(Number(z));\n\t\t\tdelete this._levels[z];\n\t\t}\n\t\tthis._removeAllTiles();\n\n\t\tthis._tileZoom = undefined;\n\t},\n\n\t_retainParent: function (x, y, z, minZoom) {\n\t\tvar x2 = Math.floor(x / 2),\n\t\t    y2 = Math.floor(y / 2),\n\t\t    z2 = z - 1,\n\t\t    coords2 = new Point(+x2, +y2);\n\t\tcoords2.z = +z2;\n\n\t\tvar key = this._tileCoordsToKey(coords2),\n\t\t    tile = this._tiles[key];\n\n\t\tif (tile && tile.active) {\n\t\t\ttile.retain = true;\n\t\t\treturn true;\n\n\t\t} else if (tile && tile.loaded) {\n\t\t\ttile.retain = true;\n\t\t}\n\n\t\tif (z2 > minZoom) {\n\t\t\treturn this._retainParent(x2, y2, z2, minZoom);\n\t\t}\n\n\t\treturn false;\n\t},\n\n\t_retainChildren: function (x, y, z, maxZoom) {\n\n\t\tfor (var i = 2 * x; i < 2 * x + 2; i++) {\n\t\t\tfor (var j = 2 * y; j < 2 * y + 2; j++) {\n\n\t\t\t\tvar coords = new Point(i, j);\n\t\t\t\tcoords.z = z + 1;\n\n\t\t\t\tvar key = this._tileCoordsToKey(coords),\n\t\t\t\t    tile = this._tiles[key];\n\n\t\t\t\tif (tile && tile.active) {\n\t\t\t\t\ttile.retain = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\t} else if (tile && tile.loaded) {\n\t\t\t\t\ttile.retain = true;\n\t\t\t\t}\n\n\t\t\t\tif (z + 1 < maxZoom) {\n\t\t\t\t\tthis._retainChildren(i, j, z + 1, maxZoom);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\n\t_resetView: function (e) {\n\t\tvar animating = e && (e.pinch || e.flyTo);\n\t\tthis._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);\n\t},\n\n\t_animateZoom: function (e) {\n\t\tthis._setView(e.center, e.zoom, true, e.noUpdate);\n\t},\n\n\t_clampZoom: function (zoom) {\n\t\tvar options = this.options;\n\n\t\tif (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {\n\t\t\treturn options.minNativeZoom;\n\t\t}\n\n\t\tif (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {\n\t\t\treturn options.maxNativeZoom;\n\t\t}\n\n\t\treturn zoom;\n\t},\n\n\t_setView: function (center, zoom, noPrune, noUpdate) {\n\t\tvar tileZoom = Math.round(zoom);\n\t\tif ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||\n\t\t    (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {\n\t\t\ttileZoom = undefined;\n\t\t} else {\n\t\t\ttileZoom = this._clampZoom(tileZoom);\n\t\t}\n\n\t\tvar tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);\n\n\t\tif (!noUpdate || tileZoomChanged) {\n\n\t\t\tthis._tileZoom = tileZoom;\n\n\t\t\tif (this._abortLoading) {\n\t\t\t\tthis._abortLoading();\n\t\t\t}\n\n\t\t\tthis._updateLevels();\n\t\t\tthis._resetGrid();\n\n\t\t\tif (tileZoom !== undefined) {\n\t\t\t\tthis._update(center);\n\t\t\t}\n\n\t\t\tif (!noPrune) {\n\t\t\t\tthis._pruneTiles();\n\t\t\t}\n\n\t\t\t// Flag to prevent _updateOpacity from pruning tiles during\n\t\t\t// a zoom anim or a pinch gesture\n\t\t\tthis._noPrune = !!noPrune;\n\t\t}\n\n\t\tthis._setZoomTransforms(center, zoom);\n\t},\n\n\t_setZoomTransforms: function (center, zoom) {\n\t\tfor (var i in this._levels) {\n\t\t\tthis._setZoomTransform(this._levels[i], center, zoom);\n\t\t}\n\t},\n\n\t_setZoomTransform: function (level, center, zoom) {\n\t\tvar scale = this._map.getZoomScale(zoom, level.zoom),\n\t\t    translate = level.origin.multiplyBy(scale)\n\t\t        .subtract(this._map._getNewPixelOrigin(center, zoom)).round();\n\n\t\tif (Browser.any3d) {\n\t\t\tDomUtil.setTransform(level.el, translate, scale);\n\t\t} else {\n\t\t\tDomUtil.setPosition(level.el, translate);\n\t\t}\n\t},\n\n\t_resetGrid: function () {\n\t\tvar map = this._map,\n\t\t    crs = map.options.crs,\n\t\t    tileSize = this._tileSize = this.getTileSize(),\n\t\t    tileZoom = this._tileZoom;\n\n\t\tvar bounds = this._map.getPixelWorldBounds(this._tileZoom);\n\t\tif (bounds) {\n\t\t\tthis._globalTileRange = this._pxBoundsToTileRange(bounds);\n\t\t}\n\n\t\tthis._wrapX = crs.wrapLng && !this.options.noWrap && [\n\t\t\tMath.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),\n\t\t\tMath.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)\n\t\t];\n\t\tthis._wrapY = crs.wrapLat && !this.options.noWrap && [\n\t\t\tMath.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),\n\t\t\tMath.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)\n\t\t];\n\t},\n\n\t_onMoveEnd: function () {\n\t\tif (!this._map || this._map._animatingZoom) { return; }\n\n\t\tthis._update();\n\t},\n\n\t_getTiledPixelBounds: function (center) {\n\t\tvar map = this._map,\n\t\t    mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),\n\t\t    scale = map.getZoomScale(mapZoom, this._tileZoom),\n\t\t    pixelCenter = map.project(center, this._tileZoom).floor(),\n\t\t    halfSize = map.getSize().divideBy(scale * 2);\n\n\t\treturn new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));\n\t},\n\n\t// Private method to load tiles in the grid's active zoom level according to map bounds\n\t_update: function (center) {\n\t\tvar map = this._map;\n\t\tif (!map) { return; }\n\t\tvar zoom = this._clampZoom(map.getZoom());\n\n\t\tif (center === undefined) { center = map.getCenter(); }\n\t\tif (this._tileZoom === undefined) { return; }\t// if out of minzoom/maxzoom\n\n\t\tvar pixelBounds = this._getTiledPixelBounds(center),\n\t\t    tileRange = this._pxBoundsToTileRange(pixelBounds),\n\t\t    tileCenter = tileRange.getCenter(),\n\t\t    queue = [],\n\t\t    margin = this.options.keepBuffer,\n\t\t    noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),\n\t\t                              tileRange.getTopRight().add([margin, -margin]));\n\n\t\t// Sanity check: panic if the tile range contains Infinity somewhere.\n\t\tif (!(isFinite(tileRange.min.x) &&\n\t\t      isFinite(tileRange.min.y) &&\n\t\t      isFinite(tileRange.max.x) &&\n\t\t      isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }\n\n\t\tfor (var key in this._tiles) {\n\t\t\tvar c = this._tiles[key].coords;\n\t\t\tif (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {\n\t\t\t\tthis._tiles[key].current = false;\n\t\t\t}\n\t\t}\n\n\t\t// _update just loads more tiles. If the tile zoom level differs too much\n\t\t// from the map's, let _setView reset levels and prune old tiles.\n\t\tif (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }\n\n\t\t// create a queue of coordinates to load tiles from\n\t\tfor (var j = tileRange.min.y; j <= tileRange.max.y; j++) {\n\t\t\tfor (var i = tileRange.min.x; i <= tileRange.max.x; i++) {\n\t\t\t\tvar coords = new Point(i, j);\n\t\t\t\tcoords.z = this._tileZoom;\n\n\t\t\t\tif (!this._isValidTile(coords)) { continue; }\n\n\t\t\t\tvar tile = this._tiles[this._tileCoordsToKey(coords)];\n\t\t\t\tif (tile) {\n\t\t\t\t\ttile.current = true;\n\t\t\t\t} else {\n\t\t\t\t\tqueue.push(coords);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// sort tile queue to load tiles in order of their distance to center\n\t\tqueue.sort(function (a, b) {\n\t\t\treturn a.distanceTo(tileCenter) - b.distanceTo(tileCenter);\n\t\t});\n\n\t\tif (queue.length !== 0) {\n\t\t\t// if it's the first batch of tiles to load\n\t\t\tif (!this._loading) {\n\t\t\t\tthis._loading = true;\n\t\t\t\t// @event loading: Event\n\t\t\t\t// Fired when the grid layer starts loading tiles.\n\t\t\t\tthis.fire('loading');\n\t\t\t}\n\n\t\t\t// create DOM fragment to append tiles in one batch\n\t\t\tvar fragment = document.createDocumentFragment();\n\n\t\t\tfor (i = 0; i < queue.length; i++) {\n\t\t\t\tthis._addTile(queue[i], fragment);\n\t\t\t}\n\n\t\t\tthis._level.el.appendChild(fragment);\n\t\t}\n\t},\n\n\t_isValidTile: function (coords) {\n\t\tvar crs = this._map.options.crs;\n\n\t\tif (!crs.infinite) {\n\t\t\t// don't load tile if it's out of bounds and not wrapped\n\t\t\tvar bounds = this._globalTileRange;\n\t\t\tif ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||\n\t\t\t    (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }\n\t\t}\n\n\t\tif (!this.options.bounds) { return true; }\n\n\t\t// don't load tile if it doesn't intersect the bounds in options\n\t\tvar tileBounds = this._tileCoordsToBounds(coords);\n\t\treturn latLngBounds(this.options.bounds).overlaps(tileBounds);\n\t},\n\n\t_keyToBounds: function (key) {\n\t\treturn this._tileCoordsToBounds(this._keyToTileCoords(key));\n\t},\n\n\t_tileCoordsToNwSe: function (coords) {\n\t\tvar map = this._map,\n\t\t    tileSize = this.getTileSize(),\n\t\t    nwPoint = coords.scaleBy(tileSize),\n\t\t    sePoint = nwPoint.add(tileSize),\n\t\t    nw = map.unproject(nwPoint, coords.z),\n\t\t    se = map.unproject(sePoint, coords.z);\n\t\treturn [nw, se];\n\t},\n\n\t// converts tile coordinates to its geographical bounds\n\t_tileCoordsToBounds: function (coords) {\n\t\tvar bp = this._tileCoordsToNwSe(coords),\n\t\t    bounds = new LatLngBounds(bp[0], bp[1]);\n\n\t\tif (!this.options.noWrap) {\n\t\t\tbounds = this._map.wrapLatLngBounds(bounds);\n\t\t}\n\t\treturn bounds;\n\t},\n\t// converts tile coordinates to key for the tile cache\n\t_tileCoordsToKey: function (coords) {\n\t\treturn coords.x + ':' + coords.y + ':' + coords.z;\n\t},\n\n\t// converts tile cache key to coordinates\n\t_keyToTileCoords: function (key) {\n\t\tvar k = key.split(':'),\n\t\t    coords = new Point(+k[0], +k[1]);\n\t\tcoords.z = +k[2];\n\t\treturn coords;\n\t},\n\n\t_removeTile: function (key) {\n\t\tvar tile = this._tiles[key];\n\t\tif (!tile) { return; }\n\n\t\tDomUtil.remove(tile.el);\n\n\t\tdelete this._tiles[key];\n\n\t\t// @event tileunload: TileEvent\n\t\t// Fired when a tile is removed (e.g. when a tile goes off the screen).\n\t\tthis.fire('tileunload', {\n\t\t\ttile: tile.el,\n\t\t\tcoords: this._keyToTileCoords(key)\n\t\t});\n\t},\n\n\t_initTile: function (tile) {\n\t\tDomUtil.addClass(tile, 'leaflet-tile');\n\n\t\tvar tileSize = this.getTileSize();\n\t\ttile.style.width = tileSize.x + 'px';\n\t\ttile.style.height = tileSize.y + 'px';\n\n\t\ttile.onselectstart = Util.falseFn;\n\t\ttile.onmousemove = Util.falseFn;\n\n\t\t// update opacity on tiles in IE7-8 because of filter inheritance problems\n\t\tif (Browser.ielt9 && this.options.opacity < 1) {\n\t\t\tDomUtil.setOpacity(tile, this.options.opacity);\n\t\t}\n\t},\n\n\t_addTile: function (coords, container) {\n\t\tvar tilePos = this._getTilePos(coords),\n\t\t    key = this._tileCoordsToKey(coords);\n\n\t\tvar tile = this.createTile(this._wrapCoords(coords), Util.bind(this._tileReady, this, coords));\n\n\t\tthis._initTile(tile);\n\n\t\t// if createTile is defined with a second argument (\"done\" callback),\n\t\t// we know that tile is async and will be ready later; otherwise\n\t\tif (this.createTile.length < 2) {\n\t\t\t// mark tile as ready, but delay one frame for opacity animation to happen\n\t\t\tUtil.requestAnimFrame(Util.bind(this._tileReady, this, coords, null, tile));\n\t\t}\n\n\t\tDomUtil.setPosition(tile, tilePos);\n\n\t\t// save tile in cache\n\t\tthis._tiles[key] = {\n\t\t\tel: tile,\n\t\t\tcoords: coords,\n\t\t\tcurrent: true\n\t\t};\n\n\t\tcontainer.appendChild(tile);\n\t\t// @event tileloadstart: TileEvent\n\t\t// Fired when a tile is requested and starts loading.\n\t\tthis.fire('tileloadstart', {\n\t\t\ttile: tile,\n\t\t\tcoords: coords\n\t\t});\n\t},\n\n\t_tileReady: function (coords, err, tile) {\n\t\tif (err) {\n\t\t\t// @event tileerror: TileErrorEvent\n\t\t\t// Fired when there is an error loading a tile.\n\t\t\tthis.fire('tileerror', {\n\t\t\t\terror: err,\n\t\t\t\ttile: tile,\n\t\t\t\tcoords: coords\n\t\t\t});\n\t\t}\n\n\t\tvar key = this._tileCoordsToKey(coords);\n\n\t\ttile = this._tiles[key];\n\t\tif (!tile) { return; }\n\n\t\ttile.loaded = +new Date();\n\t\tif (this._map._fadeAnimated) {\n\t\t\tDomUtil.setOpacity(tile.el, 0);\n\t\t\tUtil.cancelAnimFrame(this._fadeFrame);\n\t\t\tthis._fadeFrame = Util.requestAnimFrame(this._updateOpacity, this);\n\t\t} else {\n\t\t\ttile.active = true;\n\t\t\tthis._pruneTiles();\n\t\t}\n\n\t\tif (!err) {\n\t\t\tDomUtil.addClass(tile.el, 'leaflet-tile-loaded');\n\n\t\t\t// @event tileload: TileEvent\n\t\t\t// Fired when a tile loads.\n\t\t\tthis.fire('tileload', {\n\t\t\t\ttile: tile.el,\n\t\t\t\tcoords: coords\n\t\t\t});\n\t\t}\n\n\t\tif (this._noTilesToLoad()) {\n\t\t\tthis._loading = false;\n\t\t\t// @event load: Event\n\t\t\t// Fired when the grid layer loaded all visible tiles.\n\t\t\tthis.fire('load');\n\n\t\t\tif (Browser.ielt9 || !this._map._fadeAnimated) {\n\t\t\t\tUtil.requestAnimFrame(this._pruneTiles, this);\n\t\t\t} else {\n\t\t\t\t// Wait a bit more than 0.2 secs (the duration of the tile fade-in)\n\t\t\t\t// to trigger a pruning.\n\t\t\t\tsetTimeout(Util.bind(this._pruneTiles, this), 250);\n\t\t\t}\n\t\t}\n\t},\n\n\t_getTilePos: function (coords) {\n\t\treturn coords.scaleBy(this.getTileSize()).subtract(this._level.origin);\n\t},\n\n\t_wrapCoords: function (coords) {\n\t\tvar newCoords = new Point(\n\t\t\tthis._wrapX ? Util.wrapNum(coords.x, this._wrapX) : coords.x,\n\t\t\tthis._wrapY ? Util.wrapNum(coords.y, this._wrapY) : coords.y);\n\t\tnewCoords.z = coords.z;\n\t\treturn newCoords;\n\t},\n\n\t_pxBoundsToTileRange: function (bounds) {\n\t\tvar tileSize = this.getTileSize();\n\t\treturn new Bounds(\n\t\t\tbounds.min.unscaleBy(tileSize).floor(),\n\t\t\tbounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));\n\t},\n\n\t_noTilesToLoad: function () {\n\t\tfor (var key in this._tiles) {\n\t\t\tif (!this._tiles[key].loaded) { return false; }\n\t\t}\n\t\treturn true;\n\t}\n});\n\n// @factory L.gridLayer(options?: GridLayer options)\n// Creates a new instance of GridLayer with the supplied options.\nexport function gridLayer(options) {\n\treturn new GridLayer(options);\n}\n", "import {GridLayer} from './GridLayer';\r\nimport Browser from '../../core/Browser';\r\nimport * as Util from '../../core/Util';\r\nimport * as DomEvent from '../../dom/DomEvent';\r\nimport * as DomUtil from '../../dom/DomUtil';\r\n\r\n\r\n/*\r\n * @class TileLayer\r\n * @inherits GridLayer\r\n * @aka L.TileLayer\r\n * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: '&copy; <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors'}).addTo(map);\n * ```\r\n *\r\n * @section URL template\r\n * @example\r\n *\r\n * A string of the following form:\r\n *\r\n * ```\r\n * 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'\r\n * ```\r\n *\r\n * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add \"&commat;2x\" to the URL to load retina tiles.\r\n *\r\n * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:\r\n *\r\n * ```\r\n * L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});\r\n * ```\r\n */\r\n\r\n\r\nexport var TileLayer = GridLayer.extend({\r\n\r\n\t// @section\r\n\t// @aka TileLayer options\r\n\toptions: {\r\n\t\t// @option minZoom: Number = 0\r\n\t\t// The minimum zoom level down to which this layer will be displayed (inclusive).\r\n\t\tminZoom: 0,\r\n\r\n\t\t// @option maxZoom: Number = 18\r\n\t\t// The maximum zoom level up to which this layer will be displayed (inclusive).\r\n\t\tmaxZoom: 18,\r\n\r\n\t\t// @option subdomains: String|String[] = 'abc'\r\n\t\t// Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.\r\n\t\tsubdomains: 'abc',\r\n\r\n\t\t// @option errorTileUrl: String = ''\r\n\t\t// URL to the tile image to show in place of the tile that failed to load.\r\n\t\terrorTileUrl: '',\r\n\r\n\t\t// @option zoomOffset: Number = 0\r\n\t\t// The zoom number used in tile URLs will be offset with this value.\r\n\t\tzoomOffset: 0,\r\n\r\n\t\t// @option tms: Boolean = false\r\n\t\t// If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).\r\n\t\ttms: false,\r\n\r\n\t\t// @option zoomReverse: Boolean = false\r\n\t\t// If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)\r\n\t\tzoomReverse: false,\r\n\r\n\t\t// @option detectRetina: Boolean = false\r\n\t\t// If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.\r\n\t\tdetectRetina: false,\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the tiles.\r\n\t\t// If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false,\r\n\r\n\t\t// @option referrerPolicy: Boolean|String = false\r\n\t\t// Whether the referrerPolicy attribute will be added to the tiles.\r\n\t\t// If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.\r\n\t\t// This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer\r\n\t\t// (e.g. to validate an API token).\r\n\t\t// Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.\r\n\t\treferrerPolicy: false\r\n\t},\r\n\r\n\tinitialize: function (url, options) {\r\n\r\n\t\tthis._url = url;\r\n\r\n\t\toptions = Util.setOptions(this, options);\r\n\r\n\t\t// detecting retina displays, adjusting tileSize and zoom levels\r\n\t\tif (options.detectRetina && Browser.retina && options.maxZoom > 0) {\r\n\r\n\t\t\toptions.tileSize = Math.floor(options.tileSize / 2);\r\n\r\n\t\t\tif (!options.zoomReverse) {\r\n\t\t\t\toptions.zoomOffset++;\r\n\t\t\t\toptions.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);\r\n\t\t\t} else {\r\n\t\t\t\toptions.zoomOffset--;\r\n\t\t\t\toptions.minZoom = Math.min(options.maxZoom, options.minZoom + 1);\r\n\t\t\t}\r\n\r\n\t\t\toptions.minZoom = Math.max(0, options.minZoom);\r\n\t\t} else if (!options.zoomReverse) {\r\n\t\t\t// make sure maxZoom is gte minZoom\r\n\t\t\toptions.maxZoom = Math.max(options.minZoom, options.maxZoom);\r\n\t\t} else {\r\n\t\t\t// make sure minZoom is lte maxZoom\r\n\t\t\toptions.minZoom = Math.min(options.maxZoom, options.minZoom);\r\n\t\t}\r\n\r\n\t\tif (typeof options.subdomains === 'string') {\r\n\t\t\toptions.subdomains = options.subdomains.split('');\r\n\t\t}\r\n\r\n\t\tthis.on('tileunload', this._onTileRemove);\r\n\t},\r\n\r\n\t// @method setUrl(url: String, noRedraw?: Boolean): this\r\n\t// Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).\r\n\t// If the URL does not change, the layer will not be redrawn unless\r\n\t// the noRedraw parameter is set to false.\r\n\tsetUrl: function (url, noRedraw) {\r\n\t\tif (this._url === url && noRedraw === undefined) {\r\n\t\t\tnoRedraw = true;\r\n\t\t}\r\n\r\n\t\tthis._url = url;\r\n\r\n\t\tif (!noRedraw) {\r\n\t\t\tthis.redraw();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method createTile(coords: Object, done?: Function): HTMLElement\r\n\t// Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)\r\n\t// to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`\r\n\t// callback is called when the tile has been loaded.\r\n\tcreateTile: function (coords, done) {\r\n\t\tvar tile = document.createElement('img');\r\n\r\n\t\tDomEvent.on(tile, 'load', Util.bind(this._tileOnLoad, this, done, tile));\r\n\t\tDomEvent.on(tile, 'error', Util.bind(this._tileOnError, this, done, tile));\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\ttile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\t// for this new option we follow the documented behavior\r\n\t\t// more closely by only setting the property when string\r\n\t\tif (typeof this.options.referrerPolicy === 'string') {\r\n\t\t\ttile.referrerPolicy = this.options.referrerPolicy;\r\n\t\t}\r\n\r\n\t\t// The alt attribute is set to the empty string,\r\n\t\t// allowing screen readers to ignore the decorative image tiles.\r\n\t\t// https://www.w3.org/WAI/tutorials/images/decorative/\r\n\t\t// https://www.w3.org/TR/html-aria/#el-img-empty-alt\r\n\t\ttile.alt = '';\r\n\r\n\t\ttile.src = this.getTileUrl(coords);\r\n\r\n\t\treturn tile;\r\n\t},\r\n\r\n\t// @section Extension methods\r\n\t// @uninheritable\r\n\t// Layers extending `TileLayer` might reimplement the following method.\r\n\t// @method getTileUrl(coords: Object): String\r\n\t// Called only internally, returns the URL for a tile given its coordinates.\r\n\t// Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.\r\n\tgetTileUrl: function (coords) {\r\n\t\tvar data = {\r\n\t\t\tr: Browser.retina ? '@2x' : '',\r\n\t\t\ts: this._getSubdomain(coords),\r\n\t\t\tx: coords.x,\r\n\t\t\ty: coords.y,\r\n\t\t\tz: this._getZoomForUrl()\r\n\t\t};\r\n\t\tif (this._map && !this._map.options.crs.infinite) {\r\n\t\t\tvar invertedY = this._globalTileRange.max.y - coords.y;\r\n\t\t\tif (this.options.tms) {\r\n\t\t\t\tdata['y'] = invertedY;\r\n\t\t\t}\r\n\t\t\tdata['-y'] = invertedY;\r\n\t\t}\r\n\r\n\t\treturn Util.template(this._url, Util.extend(data, this.options));\r\n\t},\r\n\r\n\t_tileOnLoad: function (done, tile) {\r\n\t\t// For https://github.com/Leaflet/Leaflet/issues/3332\r\n\t\tif (Browser.ielt9) {\r\n\t\t\tsetTimeout(Util.bind(done, this, null, tile), 0);\r\n\t\t} else {\r\n\t\t\tdone(null, tile);\r\n\t\t}\r\n\t},\r\n\r\n\t_tileOnError: function (done, tile, e) {\r\n\t\tvar errorUrl = this.options.errorTileUrl;\r\n\t\tif (errorUrl && tile.getAttribute('src') !== errorUrl) {\r\n\t\t\ttile.src = errorUrl;\r\n\t\t}\r\n\t\tdone(e, tile);\r\n\t},\r\n\r\n\t_onTileRemove: function (e) {\r\n\t\te.tile.onload = null;\r\n\t},\r\n\r\n\t_getZoomForUrl: function () {\r\n\t\tvar zoom = this._tileZoom,\r\n\t\tmaxZoom = this.options.maxZoom,\r\n\t\tzoomReverse = this.options.zoomReverse,\r\n\t\tzoomOffset = this.options.zoomOffset;\r\n\r\n\t\tif (zoomReverse) {\r\n\t\t\tzoom = maxZoom - zoom;\r\n\t\t}\r\n\r\n\t\treturn zoom + zoomOffset;\r\n\t},\r\n\r\n\t_getSubdomain: function (tilePoint) {\r\n\t\tvar index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;\r\n\t\treturn this.options.subdomains[index];\r\n\t},\r\n\r\n\t// stops loading all tiles in the background layer\r\n\t_abortLoading: function () {\r\n\t\tvar i, tile;\r\n\t\tfor (i in this._tiles) {\r\n\t\t\tif (this._tiles[i].coords.z !== this._tileZoom) {\r\n\t\t\t\ttile = this._tiles[i].el;\r\n\r\n\t\t\t\ttile.onload = Util.falseFn;\r\n\t\t\t\ttile.onerror = Util.falseFn;\r\n\r\n\t\t\t\tif (!tile.complete) {\r\n\t\t\t\t\ttile.src = Util.emptyImageUrl;\r\n\t\t\t\t\tvar coords = this._tiles[i].coords;\r\n\t\t\t\t\tDomUtil.remove(tile);\r\n\t\t\t\t\tdelete this._tiles[i];\r\n\t\t\t\t\t// @event tileabort: TileEvent\r\n\t\t\t\t\t// Fired when a tile was loading but is now not wanted.\r\n\t\t\t\t\tthis.fire('tileabort', {\r\n\t\t\t\t\t\ttile: tile,\r\n\t\t\t\t\t\tcoords: coords\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t_removeTile: function (key) {\r\n\t\tvar tile = this._tiles[key];\r\n\t\tif (!tile) { return; }\r\n\r\n\t\t// Cancels any pending http requests associated with the tile\r\n\t\ttile.el.setAttribute('src', Util.emptyImageUrl);\r\n\r\n\t\treturn GridLayer.prototype._removeTile.call(this, key);\r\n\t},\r\n\r\n\t_tileReady: function (coords, err, tile) {\r\n\t\tif (!this._map || (tile && tile.getAttribute('src') === Util.emptyImageUrl)) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\treturn GridLayer.prototype._tileReady.call(this, coords, err, tile);\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)\r\n// Instantiates a tile layer object given a `URL template` and optionally an options object.\r\n\r\nexport function tileLayer(url, options) {\r\n\treturn new TileLayer(url, options);\r\n}\r\n", "import {TileLayer} from './TileLayer';\r\nimport {extend, setOptions, getParamString} from '../../core/Util';\r\nimport Browser from '../../core/Browser';\r\nimport {EPSG4326} from '../../geo/crs/CRS.EPSG4326';\r\nimport {toBounds} from '../../geometry/Bounds';\r\n\r\n/*\r\n * @class TileLayer.WMS\r\n * @inherits TileLayer\r\n * @aka L.TileLayer.WMS\r\n * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var nexrad = L.tileLayer.wms(\"http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi\", {\r\n * \tlayers: 'nexrad-n0r-900913',\r\n * \tformat: 'image/png',\r\n * \ttransparent: true,\r\n * \tattribution: \"Weather data © 2012 IEM Nexrad\"\r\n * });\r\n * ```\r\n */\r\n\r\nexport var TileLayerWMS = TileLayer.extend({\r\n\r\n\t// @section\r\n\t// @aka TileLayer.WMS options\r\n\t// If any custom options not documented here are used, they will be sent to the\r\n\t// WMS server as extra parameters in each request URL. This can be useful for\r\n\t// [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).\r\n\tdefaultWmsParams: {\r\n\t\tservice: 'WMS',\r\n\t\trequest: 'GetMap',\r\n\r\n\t\t// @option layers: String = ''\r\n\t\t// **(required)** Comma-separated list of WMS layers to show.\r\n\t\tlayers: '',\r\n\r\n\t\t// @option styles: String = ''\r\n\t\t// Comma-separated list of WMS styles.\r\n\t\tstyles: '',\r\n\r\n\t\t// @option format: String = 'image/jpeg'\r\n\t\t// WMS image format (use `'image/png'` for layers with transparency).\r\n\t\tformat: 'image/jpeg',\r\n\r\n\t\t// @option transparent: Boolean = false\r\n\t\t// If `true`, the WMS service will return images with transparency.\r\n\t\ttransparent: false,\r\n\r\n\t\t// @option version: String = '1.1.1'\r\n\t\t// Version of the WMS service to use\r\n\t\tversion: '1.1.1'\r\n\t},\r\n\r\n\toptions: {\r\n\t\t// @option crs: CRS = null\r\n\t\t// Coordinate Reference System to use for the WMS requests, defaults to\r\n\t\t// map CRS. Don't change this if you're not sure what it means.\r\n\t\tcrs: null,\r\n\r\n\t\t// @option uppercase: Boolean = false\r\n\t\t// If `true`, WMS request parameter keys will be uppercase.\r\n\t\tuppercase: false\r\n\t},\r\n\r\n\tinitialize: function (url, options) {\r\n\r\n\t\tthis._url = url;\r\n\r\n\t\tvar wmsParams = extend({}, this.defaultWmsParams);\r\n\r\n\t\t// all keys that are not TileLayer options go to WMS params\r\n\t\tfor (var i in options) {\r\n\t\t\tif (!(i in this.options)) {\r\n\t\t\t\twmsParams[i] = options[i];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\toptions = setOptions(this, options);\r\n\r\n\t\tvar realRetina = options.detectRetina && Browser.retina ? 2 : 1;\r\n\t\tvar tileSize = this.getTileSize();\r\n\t\twmsParams.width = tileSize.x * realRetina;\r\n\t\twmsParams.height = tileSize.y * realRetina;\r\n\r\n\t\tthis.wmsParams = wmsParams;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\r\n\t\tthis._crs = this.options.crs || map.options.crs;\r\n\t\tthis._wmsVersion = parseFloat(this.wmsParams.version);\r\n\r\n\t\tvar projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';\r\n\t\tthis.wmsParams[projectionKey] = this._crs.code;\r\n\r\n\t\tTileLayer.prototype.onAdd.call(this, map);\r\n\t},\r\n\r\n\tgetTileUrl: function (coords) {\r\n\r\n\t\tvar tileBounds = this._tileCoordsToNwSe(coords),\r\n\t\t    crs = this._crs,\r\n\t\t    bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),\r\n\t\t    min = bounds.min,\r\n\t\t    max = bounds.max,\r\n\t\t    bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?\r\n\t\t    [min.y, min.x, max.y, max.x] :\r\n\t\t    [min.x, min.y, max.x, max.y]).join(','),\r\n\t\t    url = TileLayer.prototype.getTileUrl.call(this, coords);\r\n\t\treturn url +\r\n\t\t\tgetParamString(this.wmsParams, url, this.options.uppercase) +\r\n\t\t\t(this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;\r\n\t},\r\n\r\n\t// @method setParams(params: Object, noRedraw?: Boolean): this\r\n\t// Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).\r\n\tsetParams: function (params, noRedraw) {\r\n\r\n\t\textend(this.wmsParams, params);\r\n\r\n\t\tif (!noRedraw) {\r\n\t\t\tthis.redraw();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)\r\n// Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.\r\nexport function tileLayerWMS(url, options) {\r\n\treturn new TileLayerWMS(url, options);\r\n}\r\n", "export {GridLayer, gridLayer} from './GridLayer';\nimport {TileLayer, tileLayer} from './TileLayer';\nimport {TileLayerWMS, tileLayerWMS} from './TileLayer.WMS';\nTileLayer.WMS = TileLayerWMS;\ntileLayer.wms = tileLayerWMS;\nexport {TileLayer, tileLayer};\n", "import {Layer} from '../Layer';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as Util from '../../core/Util';\nimport Browser from '../../core/Browser';\nimport {Bounds} from '../../geometry/Bounds';\n\n\n\n/*\n * @class Renderer\n * @inherits Layer\n * @aka L.Renderer\n *\n * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the\n * DOM container of the renderer, its bounds, and its zoom animation.\n *\n * A `Renderer` works as an implicit layer group for all `Path`s - the renderer\n * itself can be added or removed to the map. All paths use a renderer, which can\n * be implicit (the map will decide the type of renderer and use it automatically)\n * or explicit (using the [`renderer`](#path-renderer) option of the path).\n *\n * Do not use this class directly, use `SVG` and `Canvas` instead.\n *\n * @event update: Event\n * Fired when the renderer updates its bounds, center and zoom, for example when\n * its map has moved\n */\n\nexport var Renderer = Layer.extend({\n\n\t// @section\n\t// @aka Renderer options\n\toptions: {\n\t\t// @option padding: Number = 0.1\n\t\t// How much to extend the clip area around the map view (relative to its size)\n\t\t// e.g. 0.1 would be 10% of map view in each direction\n\t\tpadding: 0.1\n\t},\n\n\tinitialize: function (options) {\n\t\tUtil.setOptions(this, options);\n\t\tUtil.stamp(this);\n\t\tthis._layers = this._layers || {};\n\t},\n\n\tonAdd: function () {\n\t\tif (!this._container) {\n\t\t\tthis._initContainer(); // defined by renderer implementations\n\n\t\t\t// always keep transform-origin as 0 0\n\t\t\tDomUtil.addClass(this._container, 'leaflet-zoom-animated');\n\t\t}\n\n\t\tthis.getPane().appendChild(this._container);\n\t\tthis._update();\n\t\tthis.on('update', this._updatePaths, this);\n\t},\n\n\tonRemove: function () {\n\t\tthis.off('update', this._updatePaths, this);\n\t\tthis._destroyContainer();\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = {\n\t\t\tviewreset: this._reset,\n\t\t\tzoom: this._onZoom,\n\t\t\tmoveend: this._update,\n\t\t\tzoomend: this._onZoomEnd\n\t\t};\n\t\tif (this._zoomAnimated) {\n\t\t\tevents.zoomanim = this._onAnimZoom;\n\t\t}\n\t\treturn events;\n\t},\n\n\t_onAnimZoom: function (ev) {\n\t\tthis._updateTransform(ev.center, ev.zoom);\n\t},\n\n\t_onZoom: function () {\n\t\tthis._updateTransform(this._map.getCenter(), this._map.getZoom());\n\t},\n\n\t_updateTransform: function (center, zoom) {\n\t\tvar scale = this._map.getZoomScale(zoom, this._zoom),\n\t\t    viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),\n\t\t    currentCenterPoint = this._map.project(this._center, zoom),\n\n\t\t    topLeftOffset = viewHalf.multiplyBy(-scale).add(currentCenterPoint)\n\t\t\t\t  .subtract(this._map._getNewPixelOrigin(center, zoom));\n\n\t\tif (Browser.any3d) {\n\t\t\tDomUtil.setTransform(this._container, topLeftOffset, scale);\n\t\t} else {\n\t\t\tDomUtil.setPosition(this._container, topLeftOffset);\n\t\t}\n\t},\n\n\t_reset: function () {\n\t\tthis._update();\n\t\tthis._updateTransform(this._center, this._zoom);\n\n\t\tfor (var id in this._layers) {\n\t\t\tthis._layers[id]._reset();\n\t\t}\n\t},\n\n\t_onZoomEnd: function () {\n\t\tfor (var id in this._layers) {\n\t\t\tthis._layers[id]._project();\n\t\t}\n\t},\n\n\t_updatePaths: function () {\n\t\tfor (var id in this._layers) {\n\t\t\tthis._layers[id]._update();\n\t\t}\n\t},\n\n\t_update: function () {\n\t\t// Update pixel bounds of renderer container (for positioning/sizing/clipping later)\n\t\t// Subclasses are responsible of firing the 'update' event.\n\t\tvar p = this.options.padding,\n\t\t    size = this._map.getSize(),\n\t\t    min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();\n\n\t\tthis._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());\n\n\t\tthis._center = this._map.getCenter();\n\t\tthis._zoom = this._map.getZoom();\n\t}\n});\n", "import {Renderer} from './Renderer';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as DomEvent from '../../dom/DomEvent';\nimport Browser from '../../core/Browser';\nimport * as Util from '../../core/Util';\nimport {Bounds} from '../../geometry/Bounds';\n\n/*\n * @class Canvas\n * @inherits Renderer\n * @aka L.Canvas\n *\n * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).\n * Inherits `Renderer`.\n *\n * Due to [technical limitations](https://caniuse.com/canvas), Canvas is not\n * available in all web browsers, notably IE8, and overlapping geometries might\n * not display properly in some edge cases.\n *\n * @example\n *\n * Use Canvas by default for all paths in the map:\n *\n * ```js\n * var map = L.map('map', {\n * \trenderer: L.canvas()\n * });\n * ```\n *\n * Use a Canvas renderer with extra padding for specific vector geometries:\n *\n * ```js\n * var map = L.map('map');\n * var myRenderer = L.canvas({ padding: 0.5 });\n * var line = L.polyline( coordinates, { renderer: myRenderer } );\n * var circle = L.circle( center, { renderer: myRenderer } );\n * ```\n */\n\nexport var Canvas = Renderer.extend({\n\n\t// @section\n\t// @aka Canvas options\n\toptions: {\n\t\t// @option tolerance: Number = 0\n\t\t// How much to extend the click tolerance around a path/object on the map.\n\t\ttolerance: 0\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = Renderer.prototype.getEvents.call(this);\n\t\tevents.viewprereset = this._onViewPreReset;\n\t\treturn events;\n\t},\n\n\t_onViewPreReset: function () {\n\t\t// Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once\n\t\tthis._postponeUpdatePaths = true;\n\t},\n\n\tonAdd: function () {\n\t\tRenderer.prototype.onAdd.call(this);\n\n\t\t// Redraw vectors since canvas is cleared upon removal,\n\t\t// in case of removing the renderer itself from the map.\n\t\tthis._draw();\n\t},\n\n\t_initContainer: function () {\n\t\tvar container = this._container = document.createElement('canvas');\n\n\t\tDomEvent.on(container, 'mousemove', this._onMouseMove, this);\n\t\tDomEvent.on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);\n\t\tDomEvent.on(container, 'mouseout', this._handleMouseOut, this);\n\t\tcontainer['_leaflet_disable_events'] = true;\n\n\t\tthis._ctx = container.getContext('2d');\n\t},\n\n\t_destroyContainer: function () {\n\t\tUtil.cancelAnimFrame(this._redrawRequest);\n\t\tdelete this._ctx;\n\t\tDomUtil.remove(this._container);\n\t\tDomEvent.off(this._container);\n\t\tdelete this._container;\n\t},\n\n\t_updatePaths: function () {\n\t\tif (this._postponeUpdatePaths) { return; }\n\n\t\tvar layer;\n\t\tthis._redrawBounds = null;\n\t\tfor (var id in this._layers) {\n\t\t\tlayer = this._layers[id];\n\t\t\tlayer._update();\n\t\t}\n\t\tthis._redraw();\n\t},\n\n\t_update: function () {\n\t\tif (this._map._animatingZoom && this._bounds) { return; }\n\n\t\tRenderer.prototype._update.call(this);\n\n\t\tvar b = this._bounds,\n\t\t    container = this._container,\n\t\t    size = b.getSize(),\n\t\t    m = Browser.retina ? 2 : 1;\n\n\t\tDomUtil.setPosition(container, b.min);\n\n\t\t// set canvas size (also clearing it); use double size on retina\n\t\tcontainer.width = m * size.x;\n\t\tcontainer.height = m * size.y;\n\t\tcontainer.style.width = size.x + 'px';\n\t\tcontainer.style.height = size.y + 'px';\n\n\t\tif (Browser.retina) {\n\t\t\tthis._ctx.scale(2, 2);\n\t\t}\n\n\t\t// translate so we use the same path coordinates after canvas element moves\n\t\tthis._ctx.translate(-b.min.x, -b.min.y);\n\n\t\t// Tell paths to redraw themselves\n\t\tthis.fire('update');\n\t},\n\n\t_reset: function () {\n\t\tRenderer.prototype._reset.call(this);\n\n\t\tif (this._postponeUpdatePaths) {\n\t\t\tthis._postponeUpdatePaths = false;\n\t\t\tthis._updatePaths();\n\t\t}\n\t},\n\n\t_initPath: function (layer) {\n\t\tthis._updateDashArray(layer);\n\t\tthis._layers[Util.stamp(layer)] = layer;\n\n\t\tvar order = layer._order = {\n\t\t\tlayer: layer,\n\t\t\tprev: this._drawLast,\n\t\t\tnext: null\n\t\t};\n\t\tif (this._drawLast) { this._drawLast.next = order; }\n\t\tthis._drawLast = order;\n\t\tthis._drawFirst = this._drawFirst || this._drawLast;\n\t},\n\n\t_addPath: function (layer) {\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_removePath: function (layer) {\n\t\tvar order = layer._order;\n\t\tvar next = order.next;\n\t\tvar prev = order.prev;\n\n\t\tif (next) {\n\t\t\tnext.prev = prev;\n\t\t} else {\n\t\t\tthis._drawLast = prev;\n\t\t}\n\t\tif (prev) {\n\t\t\tprev.next = next;\n\t\t} else {\n\t\t\tthis._drawFirst = next;\n\t\t}\n\n\t\tdelete layer._order;\n\n\t\tdelete this._layers[Util.stamp(layer)];\n\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_updatePath: function (layer) {\n\t\t// Redraw the union of the layer's old pixel\n\t\t// bounds and the new pixel bounds.\n\t\tthis._extendRedrawBounds(layer);\n\t\tlayer._project();\n\t\tlayer._update();\n\t\t// The redraw will extend the redraw bounds\n\t\t// with the new pixel bounds.\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_updateStyle: function (layer) {\n\t\tthis._updateDashArray(layer);\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_updateDashArray: function (layer) {\n\t\tif (typeof layer.options.dashArray === 'string') {\n\t\t\tvar parts = layer.options.dashArray.split(/[, ]+/),\n\t\t\t    dashArray = [],\n\t\t\t    dashValue,\n\t\t\t    i;\n\t\t\tfor (i = 0; i < parts.length; i++) {\n\t\t\t\tdashValue = Number(parts[i]);\n\t\t\t\t// Ignore dash array containing invalid lengths\n\t\t\t\tif (isNaN(dashValue)) { return; }\n\t\t\t\tdashArray.push(dashValue);\n\t\t\t}\n\t\t\tlayer.options._dashArray = dashArray;\n\t\t} else {\n\t\t\tlayer.options._dashArray = layer.options.dashArray;\n\t\t}\n\t},\n\n\t_requestRedraw: function (layer) {\n\t\tif (!this._map) { return; }\n\n\t\tthis._extendRedrawBounds(layer);\n\t\tthis._redrawRequest = this._redrawRequest || Util.requestAnimFrame(this._redraw, this);\n\t},\n\n\t_extendRedrawBounds: function (layer) {\n\t\tif (layer._pxBounds) {\n\t\t\tvar padding = (layer.options.weight || 0) + 1;\n\t\t\tthis._redrawBounds = this._redrawBounds || new Bounds();\n\t\t\tthis._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));\n\t\t\tthis._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));\n\t\t}\n\t},\n\n\t_redraw: function () {\n\t\tthis._redrawRequest = null;\n\n\t\tif (this._redrawBounds) {\n\t\t\tthis._redrawBounds.min._floor();\n\t\t\tthis._redrawBounds.max._ceil();\n\t\t}\n\n\t\tthis._clear(); // clear layers in redraw bounds\n\t\tthis._draw(); // draw layers\n\n\t\tthis._redrawBounds = null;\n\t},\n\n\t_clear: function () {\n\t\tvar bounds = this._redrawBounds;\n\t\tif (bounds) {\n\t\t\tvar size = bounds.getSize();\n\t\t\tthis._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);\n\t\t} else {\n\t\t\tthis._ctx.save();\n\t\t\tthis._ctx.setTransform(1, 0, 0, 1, 0, 0);\n\t\t\tthis._ctx.clearRect(0, 0, this._container.width, this._container.height);\n\t\t\tthis._ctx.restore();\n\t\t}\n\t},\n\n\t_draw: function () {\n\t\tvar layer, bounds = this._redrawBounds;\n\t\tthis._ctx.save();\n\t\tif (bounds) {\n\t\t\tvar size = bounds.getSize();\n\t\t\tthis._ctx.beginPath();\n\t\t\tthis._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);\n\t\t\tthis._ctx.clip();\n\t\t}\n\n\t\tthis._drawing = true;\n\n\t\tfor (var order = this._drawFirst; order; order = order.next) {\n\t\t\tlayer = order.layer;\n\t\t\tif (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {\n\t\t\t\tlayer._updatePath();\n\t\t\t}\n\t\t}\n\n\t\tthis._drawing = false;\n\n\t\tthis._ctx.restore();  // Restore state before clipping.\n\t},\n\n\t_updatePoly: function (layer, closed) {\n\t\tif (!this._drawing) { return; }\n\n\t\tvar i, j, len2, p,\n\t\t    parts = layer._parts,\n\t\t    len = parts.length,\n\t\t    ctx = this._ctx;\n\n\t\tif (!len) { return; }\n\n\t\tctx.beginPath();\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tfor (j = 0, len2 = parts[i].length; j < len2; j++) {\n\t\t\t\tp = parts[i][j];\n\t\t\t\tctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);\n\t\t\t}\n\t\t\tif (closed) {\n\t\t\t\tctx.closePath();\n\t\t\t}\n\t\t}\n\n\t\tthis._fillStroke(ctx, layer);\n\n\t\t// TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature\n\t},\n\n\t_updateCircle: function (layer) {\n\n\t\tif (!this._drawing || layer._empty()) { return; }\n\n\t\tvar p = layer._point,\n\t\t    ctx = this._ctx,\n\t\t    r = Math.max(Math.round(layer._radius), 1),\n\t\t    s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;\n\n\t\tif (s !== 1) {\n\t\t\tctx.save();\n\t\t\tctx.scale(1, s);\n\t\t}\n\n\t\tctx.beginPath();\n\t\tctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);\n\n\t\tif (s !== 1) {\n\t\t\tctx.restore();\n\t\t}\n\n\t\tthis._fillStroke(ctx, layer);\n\t},\n\n\t_fillStroke: function (ctx, layer) {\n\t\tvar options = layer.options;\n\n\t\tif (options.fill) {\n\t\t\tctx.globalAlpha = options.fillOpacity;\n\t\t\tctx.fillStyle = options.fillColor || options.color;\n\t\t\tctx.fill(options.fillRule || 'evenodd');\n\t\t}\n\n\t\tif (options.stroke && options.weight !== 0) {\n\t\t\tif (ctx.setLineDash) {\n\t\t\t\tctx.setLineDash(layer.options && layer.options._dashArray || []);\n\t\t\t}\n\t\t\tctx.globalAlpha = options.opacity;\n\t\t\tctx.lineWidth = options.weight;\n\t\t\tctx.strokeStyle = options.color;\n\t\t\tctx.lineCap = options.lineCap;\n\t\t\tctx.lineJoin = options.lineJoin;\n\t\t\tctx.stroke();\n\t\t}\n\t},\n\n\t// Canvas obviously doesn't have mouse events for individual drawn objects,\n\t// so we emulate that by calculating what's under the mouse on mousemove/click manually\n\n\t_onClick: function (e) {\n\t\tvar point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;\n\n\t\tfor (var order = this._drawFirst; order; order = order.next) {\n\t\t\tlayer = order.layer;\n\t\t\tif (layer.options.interactive && layer._containsPoint(point)) {\n\t\t\t\tif (!(e.type === 'click' || e.type === 'preclick') || !this._map._draggableMoved(layer)) {\n\t\t\t\t\tclickedLayer = layer;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis._fireEvent(clickedLayer ? [clickedLayer] : false, e);\n\t},\n\n\t_onMouseMove: function (e) {\n\t\tif (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }\n\n\t\tvar point = this._map.mouseEventToLayerPoint(e);\n\t\tthis._handleMouseHover(e, point);\n\t},\n\n\n\t_handleMouseOut: function (e) {\n\t\tvar layer = this._hoveredLayer;\n\t\tif (layer) {\n\t\t\t// if we're leaving the layer, fire mouseout\n\t\t\tDomUtil.removeClass(this._container, 'leaflet-interactive');\n\t\t\tthis._fireEvent([layer], e, 'mouseout');\n\t\t\tthis._hoveredLayer = null;\n\t\t\tthis._mouseHoverThrottled = false;\n\t\t}\n\t},\n\n\t_handleMouseHover: function (e, point) {\n\t\tif (this._mouseHoverThrottled) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar layer, candidateHoveredLayer;\n\n\t\tfor (var order = this._drawFirst; order; order = order.next) {\n\t\t\tlayer = order.layer;\n\t\t\tif (layer.options.interactive && layer._containsPoint(point)) {\n\t\t\t\tcandidateHoveredLayer = layer;\n\t\t\t}\n\t\t}\n\n\t\tif (candidateHoveredLayer !== this._hoveredLayer) {\n\t\t\tthis._handleMouseOut(e);\n\n\t\t\tif (candidateHoveredLayer) {\n\t\t\t\tDomUtil.addClass(this._container, 'leaflet-interactive'); // change cursor\n\t\t\t\tthis._fireEvent([candidateHoveredLayer], e, 'mouseover');\n\t\t\t\tthis._hoveredLayer = candidateHoveredLayer;\n\t\t\t}\n\t\t}\n\n\t\tthis._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);\n\n\t\tthis._mouseHoverThrottled = true;\n\t\tsetTimeout(Util.bind(function () {\n\t\t\tthis._mouseHoverThrottled = false;\n\t\t}, this), 32);\n\t},\n\n\t_fireEvent: function (layers, e, type) {\n\t\tthis._map._fireDOMEvent(e, type || e.type, layers);\n\t},\n\n\t_bringToFront: function (layer) {\n\t\tvar order = layer._order;\n\n\t\tif (!order) { return; }\n\n\t\tvar next = order.next;\n\t\tvar prev = order.prev;\n\n\t\tif (next) {\n\t\t\tnext.prev = prev;\n\t\t} else {\n\t\t\t// Already last\n\t\t\treturn;\n\t\t}\n\t\tif (prev) {\n\t\t\tprev.next = next;\n\t\t} else if (next) {\n\t\t\t// Update first entry unless this is the\n\t\t\t// single entry\n\t\t\tthis._drawFirst = next;\n\t\t}\n\n\t\torder.prev = this._drawLast;\n\t\tthis._drawLast.next = order;\n\n\t\torder.next = null;\n\t\tthis._drawLast = order;\n\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_bringToBack: function (layer) {\n\t\tvar order = layer._order;\n\n\t\tif (!order) { return; }\n\n\t\tvar next = order.next;\n\t\tvar prev = order.prev;\n\n\t\tif (prev) {\n\t\t\tprev.next = next;\n\t\t} else {\n\t\t\t// Already first\n\t\t\treturn;\n\t\t}\n\t\tif (next) {\n\t\t\tnext.prev = prev;\n\t\t} else if (prev) {\n\t\t\t// Update last entry unless this is the\n\t\t\t// single entry\n\t\t\tthis._drawLast = prev;\n\t\t}\n\n\t\torder.prev = null;\n\n\t\torder.next = this._drawFirst;\n\t\tthis._drawFirst.prev = order;\n\t\tthis._drawFirst = order;\n\n\t\tthis._requestRedraw(layer);\n\t}\n});\n\n// @factory L.canvas(options?: Renderer options)\n// Creates a Canvas renderer with the given options.\nexport function canvas(options) {\n\treturn Browser.canvas ? new Canvas(options) : null;\n}\n", "import * as DomUtil from '../../dom/DomUtil';\nimport * as Util from '../../core/Util';\nimport {Renderer} from './Renderer';\n\n/*\n * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!\n */\n\n\nexport var vmlCreate = (function () {\n\ttry {\n\t\tdocument.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');\n\t\treturn function (name) {\n\t\t\treturn document.createElement('<lvml:' + name + ' class=\"lvml\">');\n\t\t};\n\t} catch (e) {\n\t\t// Do not return fn from catch block so `e` can be garbage collected\n\t\t// See https://github.com/Leaflet/Leaflet/pull/7279\n\t}\n\treturn function (name) {\n\t\treturn document.createElement('<' + name + ' xmlns=\"urn:schemas-microsoft.com:vml\" class=\"lvml\">');\n\t};\n})();\n\n\n/*\n * @class SVG\n *\n *\n * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility\n * with old versions of Internet Explorer.\n */\n\n// mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences\nexport var vmlMixin = {\n\n\t_initContainer: function () {\n\t\tthis._container = DomUtil.create('div', 'leaflet-vml-container');\n\t},\n\n\t_update: function () {\n\t\tif (this._map._animatingZoom) { return; }\n\t\tRenderer.prototype._update.call(this);\n\t\tthis.fire('update');\n\t},\n\n\t_initPath: function (layer) {\n\t\tvar container = layer._container = vmlCreate('shape');\n\n\t\tDomUtil.addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));\n\n\t\tcontainer.coordsize = '1 1';\n\n\t\tlayer._path = vmlCreate('path');\n\t\tcontainer.appendChild(layer._path);\n\n\t\tthis._updateStyle(layer);\n\t\tthis._layers[Util.stamp(layer)] = layer;\n\t},\n\n\t_addPath: function (layer) {\n\t\tvar container = layer._container;\n\t\tthis._container.appendChild(container);\n\n\t\tif (layer.options.interactive) {\n\t\t\tlayer.addInteractiveTarget(container);\n\t\t}\n\t},\n\n\t_removePath: function (layer) {\n\t\tvar container = layer._container;\n\t\tDomUtil.remove(container);\n\t\tlayer.removeInteractiveTarget(container);\n\t\tdelete this._layers[Util.stamp(layer)];\n\t},\n\n\t_updateStyle: function (layer) {\n\t\tvar stroke = layer._stroke,\n\t\t    fill = layer._fill,\n\t\t    options = layer.options,\n\t\t    container = layer._container;\n\n\t\tcontainer.stroked = !!options.stroke;\n\t\tcontainer.filled = !!options.fill;\n\n\t\tif (options.stroke) {\n\t\t\tif (!stroke) {\n\t\t\t\tstroke = layer._stroke = vmlCreate('stroke');\n\t\t\t}\n\t\t\tcontainer.appendChild(stroke);\n\t\t\tstroke.weight = options.weight + 'px';\n\t\t\tstroke.color = options.color;\n\t\t\tstroke.opacity = options.opacity;\n\n\t\t\tif (options.dashArray) {\n\t\t\t\tstroke.dashStyle = Util.isArray(options.dashArray) ?\n\t\t\t\t    options.dashArray.join(' ') :\n\t\t\t\t    options.dashArray.replace(/( *, *)/g, ' ');\n\t\t\t} else {\n\t\t\t\tstroke.dashStyle = '';\n\t\t\t}\n\t\t\tstroke.endcap = options.lineCap.replace('butt', 'flat');\n\t\t\tstroke.joinstyle = options.lineJoin;\n\n\t\t} else if (stroke) {\n\t\t\tcontainer.removeChild(stroke);\n\t\t\tlayer._stroke = null;\n\t\t}\n\n\t\tif (options.fill) {\n\t\t\tif (!fill) {\n\t\t\t\tfill = layer._fill = vmlCreate('fill');\n\t\t\t}\n\t\t\tcontainer.appendChild(fill);\n\t\t\tfill.color = options.fillColor || options.color;\n\t\t\tfill.opacity = options.fillOpacity;\n\n\t\t} else if (fill) {\n\t\t\tcontainer.removeChild(fill);\n\t\t\tlayer._fill = null;\n\t\t}\n\t},\n\n\t_updateCircle: function (layer) {\n\t\tvar p = layer._point.round(),\n\t\t    r = Math.round(layer._radius),\n\t\t    r2 = Math.round(layer._radiusY || r);\n\n\t\tthis._setPath(layer, layer._empty() ? 'M0 0' :\n\t\t\t'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));\n\t},\n\n\t_setPath: function (layer, path) {\n\t\tlayer._path.v = path;\n\t},\n\n\t_bringToFront: function (layer) {\n\t\tDomUtil.toFront(layer._container);\n\t},\n\n\t_bringToBack: function (layer) {\n\t\tDomUtil.toBack(layer._container);\n\t}\n};\n", "import {Renderer} from './Renderer';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as DomEvent from '../../dom/DomEvent';\nimport Browser from '../../core/Browser';\nimport {stamp} from '../../core/Util';\nimport {svgCreate, pointsToPath} from './SVG.Util';\nexport {pointsToPath};\nimport {vmlMixin, vmlCreate} from './SVG.VML';\n\nexport var create = Browser.vml ? vmlCreate : svgCreate;\n\n/*\n * @class SVG\n * @inherits Renderer\n * @aka L.SVG\n *\n * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).\n * Inherits `Renderer`.\n *\n * Due to [technical limitations](https://caniuse.com/svg), SVG is not\n * available in all web browsers, notably Android 2.x and 3.x.\n *\n * Although SVG is not available on IE7 and IE8, these browsers support\n * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)\n * (a now deprecated technology), and the SVG renderer will fall back to VML in\n * this case.\n *\n * @example\n *\n * Use SVG by default for all paths in the map:\n *\n * ```js\n * var map = L.map('map', {\n * \trenderer: L.svg()\n * });\n * ```\n *\n * Use a SVG renderer with extra padding for specific vector geometries:\n *\n * ```js\n * var map = L.map('map');\n * var myRenderer = L.svg({ padding: 0.5 });\n * var line = L.polyline( coordinates, { renderer: myRenderer } );\n * var circle = L.circle( center, { renderer: myRenderer } );\n * ```\n */\n\nexport var SVG = Renderer.extend({\n\n\t_initContainer: function () {\n\t\tthis._container = create('svg');\n\n\t\t// makes it possible to click through svg root; we'll reset it back in individual paths\n\t\tthis._container.setAttribute('pointer-events', 'none');\n\n\t\tthis._rootGroup = create('g');\n\t\tthis._container.appendChild(this._rootGroup);\n\t},\n\n\t_destroyContainer: function () {\n\t\tDomUtil.remove(this._container);\n\t\tDomEvent.off(this._container);\n\t\tdelete this._container;\n\t\tdelete this._rootGroup;\n\t\tdelete this._svgSize;\n\t},\n\n\t_update: function () {\n\t\tif (this._map._animatingZoom && this._bounds) { return; }\n\n\t\tRenderer.prototype._update.call(this);\n\n\t\tvar b = this._bounds,\n\t\t    size = b.getSize(),\n\t\t    container = this._container;\n\n\t\t// set size of svg-container if changed\n\t\tif (!this._svgSize || !this._svgSize.equals(size)) {\n\t\t\tthis._svgSize = size;\n\t\t\tcontainer.setAttribute('width', size.x);\n\t\t\tcontainer.setAttribute('height', size.y);\n\t\t}\n\n\t\t// movement: update container viewBox so that we don't have to change coordinates of individual layers\n\t\tDomUtil.setPosition(container, b.min);\n\t\tcontainer.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));\n\n\t\tthis.fire('update');\n\t},\n\n\t// methods below are called by vector layers implementations\n\n\t_initPath: function (layer) {\n\t\tvar path = layer._path = create('path');\n\n\t\t// @namespace Path\n\t\t// @option className: String = null\n\t\t// Custom class name set on an element. Only for SVG renderer.\n\t\tif (layer.options.className) {\n\t\t\tDomUtil.addClass(path, layer.options.className);\n\t\t}\n\n\t\tif (layer.options.interactive) {\n\t\t\tDomUtil.addClass(path, 'leaflet-interactive');\n\t\t}\n\n\t\tthis._updateStyle(layer);\n\t\tthis._layers[stamp(layer)] = layer;\n\t},\n\n\t_addPath: function (layer) {\n\t\tif (!this._rootGroup) { this._initContainer(); }\n\t\tthis._rootGroup.appendChild(layer._path);\n\t\tlayer.addInteractiveTarget(layer._path);\n\t},\n\n\t_removePath: function (layer) {\n\t\tDomUtil.remove(layer._path);\n\t\tlayer.removeInteractiveTarget(layer._path);\n\t\tdelete this._layers[stamp(layer)];\n\t},\n\n\t_updatePath: function (layer) {\n\t\tlayer._project();\n\t\tlayer._update();\n\t},\n\n\t_updateStyle: function (layer) {\n\t\tvar path = layer._path,\n\t\t    options = layer.options;\n\n\t\tif (!path) { return; }\n\n\t\tif (options.stroke) {\n\t\t\tpath.setAttribute('stroke', options.color);\n\t\t\tpath.setAttribute('stroke-opacity', options.opacity);\n\t\t\tpath.setAttribute('stroke-width', options.weight);\n\t\t\tpath.setAttribute('stroke-linecap', options.lineCap);\n\t\t\tpath.setAttribute('stroke-linejoin', options.lineJoin);\n\n\t\t\tif (options.dashArray) {\n\t\t\t\tpath.setAttribute('stroke-dasharray', options.dashArray);\n\t\t\t} else {\n\t\t\t\tpath.removeAttribute('stroke-dasharray');\n\t\t\t}\n\n\t\t\tif (options.dashOffset) {\n\t\t\t\tpath.setAttribute('stroke-dashoffset', options.dashOffset);\n\t\t\t} else {\n\t\t\t\tpath.removeAttribute('stroke-dashoffset');\n\t\t\t}\n\t\t} else {\n\t\t\tpath.setAttribute('stroke', 'none');\n\t\t}\n\n\t\tif (options.fill) {\n\t\t\tpath.setAttribute('fill', options.fillColor || options.color);\n\t\t\tpath.setAttribute('fill-opacity', options.fillOpacity);\n\t\t\tpath.setAttribute('fill-rule', options.fillRule || 'evenodd');\n\t\t} else {\n\t\t\tpath.setAttribute('fill', 'none');\n\t\t}\n\t},\n\n\t_updatePoly: function (layer, closed) {\n\t\tthis._setPath(layer, pointsToPath(layer._parts, closed));\n\t},\n\n\t_updateCircle: function (layer) {\n\t\tvar p = layer._point,\n\t\t    r = Math.max(Math.round(layer._radius), 1),\n\t\t    r2 = Math.max(Math.round(layer._radiusY), 1) || r,\n\t\t    arc = 'a' + r + ',' + r2 + ' 0 1,0 ';\n\n\t\t// drawing a circle with two half-arcs\n\t\tvar d = layer._empty() ? 'M0 0' :\n\t\t\t'M' + (p.x - r) + ',' + p.y +\n\t\t\tarc + (r * 2) + ',0 ' +\n\t\t\tarc + (-r * 2) + ',0 ';\n\n\t\tthis._setPath(layer, d);\n\t},\n\n\t_setPath: function (layer, path) {\n\t\tlayer._path.setAttribute('d', path);\n\t},\n\n\t// SVG does not have the concept of zIndex so we resort to changing the DOM order of elements\n\t_bringToFront: function (layer) {\n\t\tDomUtil.toFront(layer._path);\n\t},\n\n\t_bringToBack: function (layer) {\n\t\tDomUtil.toBack(layer._path);\n\t}\n});\n\nif (Browser.vml) {\n\tSVG.include(vmlMixin);\n}\n\n// @namespace SVG\n// @factory L.svg(options?: Renderer options)\n// Creates a SVG renderer with the given options.\nexport function svg(options) {\n\treturn Browser.svg || Browser.vml ? new SVG(options) : null;\n}\n", "import {Map} from '../../map/Map';\nimport {canvas} from './Canvas';\nimport {svg} from './SVG';\n\nMap.include({\n\t// @namespace Map; @method getRenderer(layer: Path): Renderer\n\t// Returns the instance of `Renderer` that should be used to render the given\n\t// `Path`. It will ensure that the `renderer` options of the map and paths\n\t// are respected, and that the renderers do exist on the map.\n\tgetRenderer: function (layer) {\n\t\t// @namespace Path; @option renderer: Renderer\n\t\t// Use this specific instance of `Renderer` for this path. Takes\n\t\t// precedence over the map's [default renderer](#map-renderer).\n\t\tvar renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;\n\n\t\tif (!renderer) {\n\t\t\trenderer = this._renderer = this._createRenderer();\n\t\t}\n\n\t\tif (!this.hasLayer(renderer)) {\n\t\t\tthis.addLayer(renderer);\n\t\t}\n\t\treturn renderer;\n\t},\n\n\t_getPaneRenderer: function (name) {\n\t\tif (name === 'overlayPane' || name === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar renderer = this._paneRenderers[name];\n\t\tif (renderer === undefined) {\n\t\t\trenderer = this._createRenderer({pane: name});\n\t\t\tthis._paneRenderers[name] = renderer;\n\t\t}\n\t\treturn renderer;\n\t},\n\n\t_createRenderer: function (options) {\n\t\t// @namespace Map; @option preferCanvas: Boolean = false\n\t\t// Whether `Path`s should be rendered on a `Canvas` renderer.\n\t\t// By default, all `Path`s are rendered in a `SVG` renderer.\n\t\treturn (this.options.preferCanvas && canvas(options)) || svg(options);\n\t}\n});\n", "import {Polygon} from './Polygon';\nimport {toLatLngBounds} from '../../geo/LatLngBounds';\n\n/*\n * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.\n */\n\n/*\n * @class Rectangle\n * @aka L.Rectangle\n * @inherits Polygon\n *\n * A class for drawing rectangle overlays on a map. Extends `Polygon`.\n *\n * @example\n *\n * ```js\n * // define rectangle geographical bounds\n * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];\n *\n * // create an orange rectangle\n * L.rectangle(bounds, {color: \"#ff7800\", weight: 1}).addTo(map);\n *\n * // zoom the map to the rectangle bounds\n * map.fitBounds(bounds);\n * ```\n *\n */\n\n\nexport var Rectangle = Polygon.extend({\n\tinitialize: function (latLngBounds, options) {\n\t\tPolygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);\n\t},\n\n\t// @method setBounds(latLngBounds: LatLngBounds): this\n\t// Redraws the rectangle with the passed bounds.\n\tsetBounds: function (latLngBounds) {\n\t\treturn this.setLatLngs(this._boundsToLatLngs(latLngBounds));\n\t},\n\n\t_boundsToLatLngs: function (latLngBounds) {\n\t\tlatLngBounds = toLatLngBounds(latLngBounds);\n\t\treturn [\n\t\t\tlatLngBounds.getSouthWest(),\n\t\t\tlatLngBounds.getNorthWest(),\n\t\t\tlatLngBounds.getNorthEast(),\n\t\t\tlatLngBounds.getSouthEast()\n\t\t];\n\t}\n});\n\n\n// @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)\nexport function rectangle(latLngBounds, options) {\n\treturn new Rectangle(latLngBounds, options);\n}\n", "export {Renderer} from './Renderer';\nexport {Canvas, canvas} from './Canvas';\nimport {SVG, create, pointsToPath, svg} from './SVG';\nSVG.create = create;\nSVG.pointsToPath = pointsToPath;\nexport {SVG, svg};\nimport './Renderer.getRenderer';\t// This is a bit of a hack, but needed because circular dependencies\n\nexport {Path} from './Path';\nexport {CircleMarker, circleMarker} from './CircleMarker';\nexport {Circle, circle} from './Circle';\nexport {Polyline, polyline} from './Polyline';\nexport {Polygon, polygon} from './Polygon';\nexport {Rectangle, rectangle} from './Rectangle';\n", "export {Layer} from './Layer';\nexport {LayerGroup, layerGroup} from './LayerGroup';\nexport {FeatureGroup, featureGroup} from './FeatureGroup';\nimport {GeoJSON, geoJSON, geoJson, geometryToLayer, coordsToLatLng, coordsToLatLngs, latLngToCoords, latLngsToCoords, getFeature, asFeature} from './GeoJSON';\nGeoJSON.geometryToLayer = geometryToLayer;\nGeoJSON.coordsToLatLng = coordsToLatLng;\nGeoJSON.coordsToLatLngs = coordsToLatLngs;\nGeoJSON.latLngToCoords = latLngToCoords;\nGeoJSON.latLngsToCoords = latLngsToCoords;\nGeoJSON.getFeature = getFeature;\nGeoJSON.asFeature = asFeature;\nexport {GeoJSON, geoJSON, geoJson};\n\nexport {ImageOverlay, imageOverlay} from './ImageOverlay';\nexport {VideoOverlay, videoOverlay} from './VideoOverlay';\nexport {SVGOverlay, svgOverlay} from './SVGOverlay';\n\nexport {DivOverlay} from './DivOverlay';\nexport {Popup, popup} from './Popup';\nexport {Tooltip, tooltip} from './Tooltip';\n\nexport * from './marker/index';\nexport * from './tile/index';\nexport * from './vector/index';\n", "import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as DomEvent from '../../dom/DomEvent';\nimport {LatLngBounds} from '../../geo/LatLngBounds';\nimport {Bounds} from '../../geometry/Bounds';\n\n/*\n * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map\n * (zoom to a selected bounding box), enabled by default.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @option boxZoom: Boolean = true\n\t// Whether the map can be zoomed to a rectangular area specified by\n\t// dragging the mouse while pressing the shift key.\n\tboxZoom: true\n});\n\nexport var BoxZoom = Handler.extend({\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\t\tthis._container = map._container;\n\t\tthis._pane = map._panes.overlayPane;\n\t\tthis._resetStateTimeout = 0;\n\t\tmap.on('unload', this._destroy, this);\n\t},\n\n\taddHooks: function () {\n\t\tDomEvent.on(this._container, 'mousedown', this._onMouseDown, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tDomEvent.off(this._container, 'mousedown', this._onMouseDown, this);\n\t},\n\n\tmoved: function () {\n\t\treturn this._moved;\n\t},\n\n\t_destroy: function () {\n\t\tDomUtil.remove(this._pane);\n\t\tdelete this._pane;\n\t},\n\n\t_resetState: function () {\n\t\tthis._resetStateTimeout = 0;\n\t\tthis._moved = false;\n\t},\n\n\t_clearDeferredResetState: function () {\n\t\tif (this._resetStateTimeout !== 0) {\n\t\t\tclearTimeout(this._resetStateTimeout);\n\t\t\tthis._resetStateTimeout = 0;\n\t\t}\n\t},\n\n\t_onMouseDown: function (e) {\n\t\tif (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }\n\n\t\t// Clear the deferred resetState if it hasn't executed yet, otherwise it\n\t\t// will interrupt the interaction and orphan a box element in the container.\n\t\tthis._clearDeferredResetState();\n\t\tthis._resetState();\n\n\t\tDomUtil.disableTextSelection();\n\t\tDomUtil.disableImageDrag();\n\n\t\tthis._startPoint = this._map.mouseEventToContainerPoint(e);\n\n\t\tDomEvent.on(document, {\n\t\t\tcontextmenu: DomEvent.stop,\n\t\t\tmousemove: this._onMouseMove,\n\t\t\tmouseup: this._onMouseUp,\n\t\t\tkeydown: this._onKeyDown\n\t\t}, this);\n\t},\n\n\t_onMouseMove: function (e) {\n\t\tif (!this._moved) {\n\t\t\tthis._moved = true;\n\n\t\t\tthis._box = DomUtil.create('div', 'leaflet-zoom-box', this._container);\n\t\t\tDomUtil.addClass(this._container, 'leaflet-crosshair');\n\n\t\t\tthis._map.fire('boxzoomstart');\n\t\t}\n\n\t\tthis._point = this._map.mouseEventToContainerPoint(e);\n\n\t\tvar bounds = new Bounds(this._point, this._startPoint),\n\t\t    size = bounds.getSize();\n\n\t\tDomUtil.setPosition(this._box, bounds.min);\n\n\t\tthis._box.style.width  = size.x + 'px';\n\t\tthis._box.style.height = size.y + 'px';\n\t},\n\n\t_finish: function () {\n\t\tif (this._moved) {\n\t\t\tDomUtil.remove(this._box);\n\t\t\tDomUtil.removeClass(this._container, 'leaflet-crosshair');\n\t\t}\n\n\t\tDomUtil.enableTextSelection();\n\t\tDomUtil.enableImageDrag();\n\n\t\tDomEvent.off(document, {\n\t\t\tcontextmenu: DomEvent.stop,\n\t\t\tmousemove: this._onMouseMove,\n\t\t\tmouseup: this._onMouseUp,\n\t\t\tkeydown: this._onKeyDown\n\t\t}, this);\n\t},\n\n\t_onMouseUp: function (e) {\n\t\tif ((e.which !== 1) && (e.button !== 1)) { return; }\n\n\t\tthis._finish();\n\n\t\tif (!this._moved) { return; }\n\t\t// Postpone to next JS tick so internal click event handling\n\t\t// still see it as \"moved\".\n\t\tthis._clearDeferredResetState();\n\t\tthis._resetStateTimeout = setTimeout(Util.bind(this._resetState, this), 0);\n\n\t\tvar bounds = new LatLngBounds(\n\t\t        this._map.containerPointToLatLng(this._startPoint),\n\t\t        this._map.containerPointToLatLng(this._point));\n\n\t\tthis._map\n\t\t\t.fitBounds(bounds)\n\t\t\t.fire('boxzoomend', {boxZoomBounds: bounds});\n\t},\n\n\t_onKeyDown: function (e) {\n\t\tif (e.keyCode === 27) {\n\t\t\tthis._finish();\n\t\t\tthis._clearDeferredResetState();\n\t\t\tthis._resetState();\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property boxZoom: Handler\n// Box (shift-drag with mouse) zoom handler.\nMap.addInitHook('addHandler', 'boxZoom', BoxZoom);\n", "import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\n\n/*\n * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.\n */\n\n// @namespace Map\n// @section Interaction Options\n\nMap.mergeOptions({\n\t// @option doubleClickZoom: Boolean|String = true\n\t// Whether the map can be zoomed in by double clicking on it and\n\t// zoomed out by double clicking while holding shift. If passed\n\t// `'center'`, double-click zoom will zoom to the center of the\n\t//  view regardless of where the mouse was.\n\tdoubleClickZoom: true\n});\n\nexport var DoubleClickZoom = Handler.extend({\n\taddHooks: function () {\n\t\tthis._map.on('dblclick', this._onDoubleClick, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._map.off('dblclick', this._onDoubleClick, this);\n\t},\n\n\t_onDoubleClick: function (e) {\n\t\tvar map = this._map,\n\t\t    oldZoom = map.getZoom(),\n\t\t    delta = map.options.zoomDelta,\n\t\t    zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;\n\n\t\tif (map.options.doubleClickZoom === 'center') {\n\t\t\tmap.setZoom(zoom);\n\t\t} else {\n\t\t\tmap.setZoomAround(e.containerPoint, zoom);\n\t\t}\n\t}\n});\n\n// @section Handlers\n//\n// Map properties include interaction handlers that allow you to control\n// interaction behavior in runtime, enabling or disabling certain features such\n// as dragging or touch zoom (see `Handler` methods). For example:\n//\n// ```js\n// map.doubleClickZoom.disable();\n// ```\n//\n// @property doubleClickZoom: Handler\n// Double click zoom handler.\nMap.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);\n", "import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport {Draggable} from '../../dom/Draggable';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport {toLatLngBounds as latLngBounds} from '../../geo/LatLngBounds';\nimport {toBounds} from '../../geometry/Bounds';\n\n/*\n * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @option dragging: Boolean = true\n\t// Whether the map is draggable with mouse/touch or not.\n\tdragging: true,\n\n\t// @section Panning Inertia Options\n\t// @option inertia: Boolean = *\n\t// If enabled, panning of the map will have an inertia effect where\n\t// the map builds momentum while dragging and continues moving in\n\t// the same direction for some time. Feels especially nice on touch\n\t// devices. Enabled by default.\n\tinertia: true,\n\n\t// @option inertiaDeceleration: Number = 3000\n\t// The rate with which the inertial movement slows down, in pixels/second².\n\tinertiaDeceleration: 3400, // px/s^2\n\n\t// @option inertiaMaxSpeed: Number = Infinity\n\t// Max speed of the inertial movement, in pixels/second.\n\tinertiaMaxSpeed: Infinity, // px/s\n\n\t// @option easeLinearity: Number = 0.2\n\teaseLinearity: 0.2,\n\n\t// TODO refactor, move to CRS\n\t// @option worldCopyJump: Boolean = false\n\t// With this option enabled, the map tracks when you pan to another \"copy\"\n\t// of the world and seamlessly jumps to the original one so that all overlays\n\t// like markers and vector layers are still visible.\n\tworldCopyJump: false,\n\n\t// @option maxBoundsViscosity: Number = 0.0\n\t// If `maxBounds` is set, this option will control how solid the bounds\n\t// are when dragging the map around. The default value of `0.0` allows the\n\t// user to drag outside the bounds at normal speed, higher values will\n\t// slow down map dragging outside bounds, and `1.0` makes the bounds fully\n\t// solid, preventing the user from dragging outside the bounds.\n\tmaxBoundsViscosity: 0.0\n});\n\nexport var Drag = Handler.extend({\n\taddHooks: function () {\n\t\tif (!this._draggable) {\n\t\t\tvar map = this._map;\n\n\t\t\tthis._draggable = new Draggable(map._mapPane, map._container);\n\n\t\t\tthis._draggable.on({\n\t\t\t\tdragstart: this._onDragStart,\n\t\t\t\tdrag: this._onDrag,\n\t\t\t\tdragend: this._onDragEnd\n\t\t\t}, this);\n\n\t\t\tthis._draggable.on('predrag', this._onPreDragLimit, this);\n\t\t\tif (map.options.worldCopyJump) {\n\t\t\t\tthis._draggable.on('predrag', this._onPreDragWrap, this);\n\t\t\t\tmap.on('zoomend', this._onZoomEnd, this);\n\n\t\t\t\tmap.whenReady(this._onZoomEnd, this);\n\t\t\t}\n\t\t}\n\t\tDomUtil.addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');\n\t\tthis._draggable.enable();\n\t\tthis._positions = [];\n\t\tthis._times = [];\n\t},\n\n\tremoveHooks: function () {\n\t\tDomUtil.removeClass(this._map._container, 'leaflet-grab');\n\t\tDomUtil.removeClass(this._map._container, 'leaflet-touch-drag');\n\t\tthis._draggable.disable();\n\t},\n\n\tmoved: function () {\n\t\treturn this._draggable && this._draggable._moved;\n\t},\n\n\tmoving: function () {\n\t\treturn this._draggable && this._draggable._moving;\n\t},\n\n\t_onDragStart: function () {\n\t\tvar map = this._map;\n\n\t\tmap._stop();\n\t\tif (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {\n\t\t\tvar bounds = latLngBounds(this._map.options.maxBounds);\n\n\t\t\tthis._offsetLimit = toBounds(\n\t\t\t\tthis._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),\n\t\t\t\tthis._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)\n\t\t\t\t\t.add(this._map.getSize()));\n\n\t\t\tthis._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));\n\t\t} else {\n\t\t\tthis._offsetLimit = null;\n\t\t}\n\n\t\tmap\n\t\t    .fire('movestart')\n\t\t    .fire('dragstart');\n\n\t\tif (map.options.inertia) {\n\t\t\tthis._positions = [];\n\t\t\tthis._times = [];\n\t\t}\n\t},\n\n\t_onDrag: function (e) {\n\t\tif (this._map.options.inertia) {\n\t\t\tvar time = this._lastTime = +new Date(),\n\t\t\t    pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;\n\n\t\t\tthis._positions.push(pos);\n\t\t\tthis._times.push(time);\n\n\t\t\tthis._prunePositions(time);\n\t\t}\n\n\t\tthis._map\n\t\t    .fire('move', e)\n\t\t    .fire('drag', e);\n\t},\n\n\t_prunePositions: function (time) {\n\t\twhile (this._positions.length > 1 && time - this._times[0] > 50) {\n\t\t\tthis._positions.shift();\n\t\t\tthis._times.shift();\n\t\t}\n\t},\n\n\t_onZoomEnd: function () {\n\t\tvar pxCenter = this._map.getSize().divideBy(2),\n\t\t    pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);\n\n\t\tthis._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;\n\t\tthis._worldWidth = this._map.getPixelWorldBounds().getSize().x;\n\t},\n\n\t_viscousLimit: function (value, threshold) {\n\t\treturn value - (value - threshold) * this._viscosity;\n\t},\n\n\t_onPreDragLimit: function () {\n\t\tif (!this._viscosity || !this._offsetLimit) { return; }\n\n\t\tvar offset = this._draggable._newPos.subtract(this._draggable._startPos);\n\n\t\tvar limit = this._offsetLimit;\n\t\tif (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }\n\t\tif (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }\n\t\tif (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }\n\t\tif (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }\n\n\t\tthis._draggable._newPos = this._draggable._startPos.add(offset);\n\t},\n\n\t_onPreDragWrap: function () {\n\t\t// TODO refactor to be able to adjust map pane position after zoom\n\t\tvar worldWidth = this._worldWidth,\n\t\t    halfWidth = Math.round(worldWidth / 2),\n\t\t    dx = this._initialWorldOffset,\n\t\t    x = this._draggable._newPos.x,\n\t\t    newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,\n\t\t    newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,\n\t\t    newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;\n\n\t\tthis._draggable._absPos = this._draggable._newPos.clone();\n\t\tthis._draggable._newPos.x = newX;\n\t},\n\n\t_onDragEnd: function (e) {\n\t\tvar map = this._map,\n\t\t    options = map.options,\n\n\t\t    noInertia = !options.inertia || e.noInertia || this._times.length < 2;\n\n\t\tmap.fire('dragend', e);\n\n\t\tif (noInertia) {\n\t\t\tmap.fire('moveend');\n\n\t\t} else {\n\t\t\tthis._prunePositions(+new Date());\n\n\t\t\tvar direction = this._lastPos.subtract(this._positions[0]),\n\t\t\t    duration = (this._lastTime - this._times[0]) / 1000,\n\t\t\t    ease = options.easeLinearity,\n\n\t\t\t    speedVector = direction.multiplyBy(ease / duration),\n\t\t\t    speed = speedVector.distanceTo([0, 0]),\n\n\t\t\t    limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),\n\t\t\t    limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),\n\n\t\t\t    decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),\n\t\t\t    offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();\n\n\t\t\tif (!offset.x && !offset.y) {\n\t\t\t\tmap.fire('moveend');\n\n\t\t\t} else {\n\t\t\t\toffset = map._limitOffset(offset, map.options.maxBounds);\n\n\t\t\t\tUtil.requestAnimFrame(function () {\n\t\t\t\t\tmap.panBy(offset, {\n\t\t\t\t\t\tduration: decelerationDuration,\n\t\t\t\t\t\teaseLinearity: ease,\n\t\t\t\t\t\tnoMoveStart: true,\n\t\t\t\t\t\tanimate: true\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property dragging: Handler\n// Map dragging handler (by both mouse and touch).\nMap.addInitHook('addHandler', 'dragging', Drag);\n", "import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport {on, off, stop} from '../../dom/DomEvent';\nimport {toPoint} from '../../geometry/Point';\n\n\n/*\n * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.\n */\n\n// @namespace Map\n// @section Keyboard Navigation Options\nMap.mergeOptions({\n\t// @option keyboard: Boolean = true\n\t// Makes the map focusable and allows users to navigate the map with keyboard\n\t// arrows and `+`/`-` keys.\n\tkeyboard: true,\n\n\t// @option keyboardPanDelta: Number = 80\n\t// Amount of pixels to pan when pressing an arrow key.\n\tkeyboardPanDelta: 80\n});\n\nexport var Keyboard = Handler.extend({\n\n\tkeyCodes: {\n\t\tleft:    [37],\n\t\tright:   [39],\n\t\tdown:    [40],\n\t\tup:      [38],\n\t\tzoomIn:  [187, 107, 61, 171],\n\t\tzoomOut: [189, 109, 54, 173]\n\t},\n\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\n\t\tthis._setPanDelta(map.options.keyboardPanDelta);\n\t\tthis._setZoomDelta(map.options.zoomDelta);\n\t},\n\n\taddHooks: function () {\n\t\tvar container = this._map._container;\n\n\t\t// make the container focusable by tabbing\n\t\tif (container.tabIndex <= 0) {\n\t\t\tcontainer.tabIndex = '0';\n\t\t}\n\n\t\ton(container, {\n\t\t\tfocus: this._onFocus,\n\t\t\tblur: this._onBlur,\n\t\t\tmousedown: this._onMouseDown\n\t\t}, this);\n\n\t\tthis._map.on({\n\t\t\tfocus: this._addHooks,\n\t\t\tblur: this._removeHooks\n\t\t}, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._removeHooks();\n\n\t\toff(this._map._container, {\n\t\t\tfocus: this._onFocus,\n\t\t\tblur: this._onBlur,\n\t\t\tmousedown: this._onMouseDown\n\t\t}, this);\n\n\t\tthis._map.off({\n\t\t\tfocus: this._addHooks,\n\t\t\tblur: this._removeHooks\n\t\t}, this);\n\t},\n\n\t_onMouseDown: function () {\n\t\tif (this._focused) { return; }\n\n\t\tvar body = document.body,\n\t\t    docEl = document.documentElement,\n\t\t    top = body.scrollTop || docEl.scrollTop,\n\t\t    left = body.scrollLeft || docEl.scrollLeft;\n\n\t\tthis._map._container.focus();\n\n\t\twindow.scrollTo(left, top);\n\t},\n\n\t_onFocus: function () {\n\t\tthis._focused = true;\n\t\tthis._map.fire('focus');\n\t},\n\n\t_onBlur: function () {\n\t\tthis._focused = false;\n\t\tthis._map.fire('blur');\n\t},\n\n\t_setPanDelta: function (panDelta) {\n\t\tvar keys = this._panKeys = {},\n\t\t    codes = this.keyCodes,\n\t\t    i, len;\n\n\t\tfor (i = 0, len = codes.left.length; i < len; i++) {\n\t\t\tkeys[codes.left[i]] = [-1 * panDelta, 0];\n\t\t}\n\t\tfor (i = 0, len = codes.right.length; i < len; i++) {\n\t\t\tkeys[codes.right[i]] = [panDelta, 0];\n\t\t}\n\t\tfor (i = 0, len = codes.down.length; i < len; i++) {\n\t\t\tkeys[codes.down[i]] = [0, panDelta];\n\t\t}\n\t\tfor (i = 0, len = codes.up.length; i < len; i++) {\n\t\t\tkeys[codes.up[i]] = [0, -1 * panDelta];\n\t\t}\n\t},\n\n\t_setZoomDelta: function (zoomDelta) {\n\t\tvar keys = this._zoomKeys = {},\n\t\t    codes = this.keyCodes,\n\t\t    i, len;\n\n\t\tfor (i = 0, len = codes.zoomIn.length; i < len; i++) {\n\t\t\tkeys[codes.zoomIn[i]] = zoomDelta;\n\t\t}\n\t\tfor (i = 0, len = codes.zoomOut.length; i < len; i++) {\n\t\t\tkeys[codes.zoomOut[i]] = -zoomDelta;\n\t\t}\n\t},\n\n\t_addHooks: function () {\n\t\ton(document, 'keydown', this._onKeyDown, this);\n\t},\n\n\t_removeHooks: function () {\n\t\toff(document, 'keydown', this._onKeyDown, this);\n\t},\n\n\t_onKeyDown: function (e) {\n\t\tif (e.altKey || e.ctrlKey || e.metaKey) { return; }\n\n\t\tvar key = e.keyCode,\n\t\t    map = this._map,\n\t\t    offset;\n\n\t\tif (key in this._panKeys) {\n\t\t\tif (!map._panAnim || !map._panAnim._inProgress) {\n\t\t\t\toffset = this._panKeys[key];\n\t\t\t\tif (e.shiftKey) {\n\t\t\t\t\toffset = toPoint(offset).multiplyBy(3);\n\t\t\t\t}\n\n\t\t\t\tif (map.options.maxBounds) {\n\t\t\t\t\toffset = map._limitOffset(toPoint(offset), map.options.maxBounds);\n\t\t\t\t}\n\n\t\t\t\tif (map.options.worldCopyJump) {\n\t\t\t\t\tvar newLatLng = map.wrapLatLng(map.unproject(map.project(map.getCenter()).add(offset)));\n\t\t\t\t\tmap.panTo(newLatLng);\n\t\t\t\t} else {\n\t\t\t\t\tmap.panBy(offset);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (key in this._zoomKeys) {\n\t\t\tmap.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);\n\n\t\t} else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {\n\t\t\tmap.closePopup();\n\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\n\t\tstop(e);\n\t}\n});\n\n// @section Handlers\n// @section Handlers\n// @property keyboard: Handler\n// Keyboard navigation handler.\nMap.addInitHook('addHandler', 'keyboard', Keyboard);\n", "import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as DomEvent from '../../dom/DomEvent';\nimport * as Util from '../../core/Util';\n\n/*\n * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @section Mouse wheel options\n\t// @option scrollWheelZoom: Boolean|String = true\n\t// Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,\n\t// it will zoom to the center of the view regardless of where the mouse was.\n\tscrollWheelZoom: true,\n\n\t// @option wheelDebounceTime: Number = 40\n\t// Limits the rate at which a wheel can fire (in milliseconds). By default\n\t// user can't zoom via wheel more often than once per 40 ms.\n\twheelDebounceTime: 40,\n\n\t// @option wheelPxPerZoomLevel: Number = 60\n\t// How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))\n\t// mean a change of one full zoom level. Smaller values will make wheel-zooming\n\t// faster (and vice versa).\n\twheelPxPerZoomLevel: 60\n});\n\nexport var ScrollWheelZoom = Handler.extend({\n\taddHooks: function () {\n\t\tDomEvent.on(this._map._container, 'wheel', this._onWheelScroll, this);\n\n\t\tthis._delta = 0;\n\t},\n\n\tremoveHooks: function () {\n\t\tDomEvent.off(this._map._container, 'wheel', this._onWheelScroll, this);\n\t},\n\n\t_onWheelScroll: function (e) {\n\t\tvar delta = DomEvent.getWheelDelta(e);\n\n\t\tvar debounce = this._map.options.wheelDebounceTime;\n\n\t\tthis._delta += delta;\n\t\tthis._lastMousePos = this._map.mouseEventToContainerPoint(e);\n\n\t\tif (!this._startTime) {\n\t\t\tthis._startTime = +new Date();\n\t\t}\n\n\t\tvar left = Math.max(debounce - (+new Date() - this._startTime), 0);\n\n\t\tclearTimeout(this._timer);\n\t\tthis._timer = setTimeout(Util.bind(this._performZoom, this), left);\n\n\t\tDomEvent.stop(e);\n\t},\n\n\t_performZoom: function () {\n\t\tvar map = this._map,\n\t\t    zoom = map.getZoom(),\n\t\t    snap = this._map.options.zoomSnap || 0;\n\n\t\tmap._stop(); // stop panning and fly animations if any\n\n\t\t// map the delta with a sigmoid function to -4..4 range leaning on -1..1\n\t\tvar d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),\n\t\t    d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,\n\t\t    d4 = snap ? Math.ceil(d3 / snap) * snap : d3,\n\t\t    delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;\n\n\t\tthis._delta = 0;\n\t\tthis._startTime = null;\n\n\t\tif (!delta) { return; }\n\n\t\tif (map.options.scrollWheelZoom === 'center') {\n\t\t\tmap.setZoom(zoom + delta);\n\t\t} else {\n\t\t\tmap.setZoomAround(this._lastMousePos, zoom + delta);\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property scrollWheelZoom: Handler\n// Scroll wheel zoom handler.\nMap.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);\n", "import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as DomEvent from '../../dom/DomEvent';\nimport {Point} from '../../geometry/Point';\nimport * as Util from '../../core/Util';\nimport Browser from '../../core/Browser';\n\n/*\n * L.Map.TapHold is used to simulate `contextmenu` event on long hold,\n * which otherwise is not fired by mobile Safari.\n */\n\nvar tapHoldDelay = 600;\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @section Touch interaction options\n\t// @option tapHold: Boolean\n\t// Enables simulation of `contextmenu` event, default is `true` for mobile Safari.\n\ttapHold: Browser.touchNative && Browser.safari && Browser.mobile,\n\n\t// @option tapTolerance: Number = 15\n\t// The max number of pixels a user can shift his finger during touch\n\t// for it to be considered a valid tap.\n\ttapTolerance: 15\n});\n\nexport var TapHold = Handler.extend({\n\taddHooks: function () {\n\t\tDomEvent.on(this._map._container, 'touchstart', this._onDown, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tDomEvent.off(this._map._container, 'touchstart', this._onDown, this);\n\t},\n\n\t_onDown: function (e) {\n\t\tclearTimeout(this._holdTimeout);\n\t\tif (e.touches.length !== 1) { return; }\n\n\t\tvar first = e.touches[0];\n\t\tthis._startPos = this._newPos = new Point(first.clientX, first.clientY);\n\n\t\tthis._holdTimeout = setTimeout(Util.bind(function () {\n\t\t\tthis._cancel();\n\t\t\tif (!this._isTapValid()) { return; }\n\n\t\t\t// prevent simulated mouse events https://w3c.github.io/touch-events/#mouse-events\n\t\t\tDomEvent.on(document, 'touchend', DomEvent.preventDefault);\n\t\t\tDomEvent.on(document, 'touchend touchcancel', this._cancelClickPrevent);\n\t\t\tthis._simulateEvent('contextmenu', first);\n\t\t}, this), tapHoldDelay);\n\n\t\tDomEvent.on(document, 'touchend touchcancel contextmenu', this._cancel, this);\n\t\tDomEvent.on(document, 'touchmove', this._onMove, this);\n\t},\n\n\t_cancelClickPrevent: function cancelClickPrevent() {\n\t\tDomEvent.off(document, 'touchend', DomEvent.preventDefault);\n\t\tDomEvent.off(document, 'touchend touchcancel', cancelClickPrevent);\n\t},\n\n\t_cancel: function () {\n\t\tclearTimeout(this._holdTimeout);\n\t\tDomEvent.off(document, 'touchend touchcancel contextmenu', this._cancel, this);\n\t\tDomEvent.off(document, 'touchmove', this._onMove, this);\n\t},\n\n\t_onMove: function (e) {\n\t\tvar first = e.touches[0];\n\t\tthis._newPos = new Point(first.clientX, first.clientY);\n\t},\n\n\t_isTapValid: function () {\n\t\treturn this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;\n\t},\n\n\t_simulateEvent: function (type, e) {\n\t\tvar simulatedEvent = new MouseEvent(type, {\n\t\t\tbubbles: true,\n\t\t\tcancelable: true,\n\t\t\tview: window,\n\t\t\t// detail: 1,\n\t\t\tscreenX: e.screenX,\n\t\t\tscreenY: e.screenY,\n\t\t\tclientX: e.clientX,\n\t\t\tclientY: e.clientY,\n\t\t\t// button: 2,\n\t\t\t// buttons: 2\n\t\t});\n\n\t\tsimulatedEvent._simulated = true;\n\n\t\te.target.dispatchEvent(simulatedEvent);\n\t}\n});\n\n// @section Handlers\n// @property tapHold: Handler\n// Long tap handler to simulate `contextmenu` event (useful in mobile Safari).\nMap.addInitHook('addHandler', 'tapHold', TapHold);\n", "import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as DomEvent from '../../dom/DomEvent';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport Browser from '../../core/Browser';\n\n/*\n * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @section Touch interaction options\n\t// @option touchZoom: Boolean|String = *\n\t// Whether the map can be zoomed by touch-dragging with two fingers. If\n\t// passed `'center'`, it will zoom to the center of the view regardless of\n\t// where the touch events (fingers) were. Enabled for touch-capable web\n\t// browsers.\n\ttouchZoom: Browser.touch,\n\n\t// @option bounceAtZoomLimits: Boolean = true\n\t// Set it to false if you don't want the map to zoom beyond min/max zoom\n\t// and then bounce back when pinch-zooming.\n\tbounceAtZoomLimits: true\n});\n\nexport var TouchZoom = Handler.extend({\n\taddHooks: function () {\n\t\tDomUtil.addClass(this._map._container, 'leaflet-touch-zoom');\n\t\tDomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tDomUtil.removeClass(this._map._container, 'leaflet-touch-zoom');\n\t\tDomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);\n\t},\n\n\t_onTouchStart: function (e) {\n\t\tvar map = this._map;\n\t\tif (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }\n\n\t\tvar p1 = map.mouseEventToContainerPoint(e.touches[0]),\n\t\t    p2 = map.mouseEventToContainerPoint(e.touches[1]);\n\n\t\tthis._centerPoint = map.getSize()._divideBy(2);\n\t\tthis._startLatLng = map.containerPointToLatLng(this._centerPoint);\n\t\tif (map.options.touchZoom !== 'center') {\n\t\t\tthis._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));\n\t\t}\n\n\t\tthis._startDist = p1.distanceTo(p2);\n\t\tthis._startZoom = map.getZoom();\n\n\t\tthis._moved = false;\n\t\tthis._zooming = true;\n\n\t\tmap._stop();\n\n\t\tDomEvent.on(document, 'touchmove', this._onTouchMove, this);\n\t\tDomEvent.on(document, 'touchend touchcancel', this._onTouchEnd, this);\n\n\t\tDomEvent.preventDefault(e);\n\t},\n\n\t_onTouchMove: function (e) {\n\t\tif (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }\n\n\t\tvar map = this._map,\n\t\t    p1 = map.mouseEventToContainerPoint(e.touches[0]),\n\t\t    p2 = map.mouseEventToContainerPoint(e.touches[1]),\n\t\t    scale = p1.distanceTo(p2) / this._startDist;\n\n\t\tthis._zoom = map.getScaleZoom(scale, this._startZoom);\n\n\t\tif (!map.options.bounceAtZoomLimits && (\n\t\t\t(this._zoom < map.getMinZoom() && scale < 1) ||\n\t\t\t(this._zoom > map.getMaxZoom() && scale > 1))) {\n\t\t\tthis._zoom = map._limitZoom(this._zoom);\n\t\t}\n\n\t\tif (map.options.touchZoom === 'center') {\n\t\t\tthis._center = this._startLatLng;\n\t\t\tif (scale === 1) { return; }\n\t\t} else {\n\t\t\t// Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng\n\t\t\tvar delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);\n\t\t\tif (scale === 1 && delta.x === 0 && delta.y === 0) { return; }\n\t\t\tthis._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);\n\t\t}\n\n\t\tif (!this._moved) {\n\t\t\tmap._moveStart(true, false);\n\t\t\tthis._moved = true;\n\t\t}\n\n\t\tUtil.cancelAnimFrame(this._animRequest);\n\n\t\tvar moveFn = Util.bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}, undefined);\n\t\tthis._animRequest = Util.requestAnimFrame(moveFn, this, true);\n\n\t\tDomEvent.preventDefault(e);\n\t},\n\n\t_onTouchEnd: function () {\n\t\tif (!this._moved || !this._zooming) {\n\t\t\tthis._zooming = false;\n\t\t\treturn;\n\t\t}\n\n\t\tthis._zooming = false;\n\t\tUtil.cancelAnimFrame(this._animRequest);\n\n\t\tDomEvent.off(document, 'touchmove', this._onTouchMove, this);\n\t\tDomEvent.off(document, 'touchend touchcancel', this._onTouchEnd, this);\n\n\t\t// Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.\n\t\tif (this._map.options.zoomAnimation) {\n\t\t\tthis._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);\n\t\t} else {\n\t\t\tthis._map._resetView(this._center, this._map._limitZoom(this._zoom));\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property touchZoom: Handler\n// Touch zoom handler.\nMap.addInitHook('addHandler', 'touchZoom', TouchZoom);\n", "import {Map} from './Map';\nimport {BoxZoom} from './handler/Map.BoxZoom';\nMap.BoxZoom = BoxZoom;\nimport {DoubleClickZoom} from './handler/Map.DoubleClickZoom';\nMap.DoubleClickZoom = DoubleClickZoom;\nimport {Drag} from './handler/Map.Drag';\nMap.Drag = Drag;\nimport {Keyboard} from './handler/Map.Keyboard';\nMap.Keyboard = Keyboard;\nimport {ScrollWheelZoom} from './handler/Map.ScrollWheelZoom';\nMap.ScrollWheelZoom = ScrollWheelZoom;\nimport {TapHold} from './handler/Map.TapHold';\nMap.TapHold = TapHold;\nimport {TouchZoom} from './handler/Map.TouchZoom';\nMap.TouchZoom = TouchZoom;\n\nexport {Map, createMap as map} from './Map';\n", "/**\n * leaflet plugin for plain image map projection\n * @copyright 2016- commenthol\n * @license MIT\n */\n/* globals define */\n/* eslint no-var:off */\n\n;(function (factory) {\n  var L\n  if (typeof define === 'function' && define.amd) {\n    // AMD\n    define(['leaflet'], factory)\n  } else if (typeof module !== 'undefined') {\n    // Node/CommonJS\n    L = require('leaflet')\n    module.exports = factory(L)\n  } else {\n    // Browser globals\n    if (typeof window.L === 'undefined') {\n      throw new Error('Leaflet must be loaded first')\n    }\n    factory(window.L)\n  }\n}(function (L) {\n  /**\n   * L.RasterCoords\n   * @param {L.map} map - the map used\n   * @param {Array} imgsize - [ width, height ] image dimensions\n   * @param {Number} [tilesize] - tilesize in pixels. Default=256\n   * @param {Boolean} setmaxbounds - automatically set map max bounds. Default=true\n   */\n  L.RasterCoords = function (map, imgsize, tilesize, setmaxbounds = true) {\n    this.map = map\n    this.width = imgsize[0]\n    this.height = imgsize[1]\n    this.tilesize = tilesize || 256\n    this.zoom = this.zoomLevel()\n    if (setmaxbounds && this.width && this.height) {\n      this.setMaxBounds()\n    }\n  }\n\n  L.RasterCoords.prototype = {\n    /**\n     * calculate accurate zoom level for the given image size\n     */\n    zoomLevel: function () {\n      return Math.ceil(\n        Math.log(\n          Math.max(this.width, this.height) /\n          this.tilesize\n        ) / Math.log(2)\n      )\n    },\n    /**\n     * unproject `coords` to the raster coordinates used by the raster image projection\n     * @param {Array} coords - [ x, y ]\n     * @return {L.LatLng} - internal coordinates\n     */\n    unproject: function (coords) {\n      return this.map.unproject(coords, this.zoom)\n    },\n    /**\n     * project `coords` back to image coordinates\n     * @param {Array} coords - [ x, y ]\n     * @return {L.LatLng} - image coordinates\n     */\n    project: function (coords) {\n      return this.map.project(coords, this.zoom)\n    },\n    /**\n     * get the max bounds of the image\n     */\n    getMaxBounds: function () {\n      var southWest = this.unproject([0, this.height])\n      var northEast = this.unproject([this.width, 0])\n      return new L.LatLngBounds(southWest, northEast)\n    },\n    /**\n     * sets the max bounds on map\n     */\n    setMaxBounds: function () {\n      var bounds = this.getMaxBounds()\n      this.map.setMaxBounds(bounds)\n    }\n  }\n\n  return L.RasterCoords\n}))\n; // eslint-disable-line semi\n", "/**\n * EvEmitter v1.1.0\n * Lil' event emitter\n * MIT License\n */\n\n/* jshint unused: true, undef: true, strict: true */\n\n( function( global, factory ) {\n  // universal module definition\n  /* jshint strict: false */ /* globals define, module, window */\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD - RequireJS\n    define( factory );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS - Browserify, Webpack\n    module.exports = factory();\n  } else {\n    // Browser globals\n    global.EvEmitter = factory();\n  }\n\n}( typeof window != 'undefined' ? window : this, function() {\n\n\"use strict\";\n\nfunction EvEmitter() {}\n\nvar proto = EvEmitter.prototype;\n\nproto.on = function( eventName, listener ) {\n  if ( !eventName || !listener ) {\n    return;\n  }\n  // set events hash\n  var events = this._events = this._events || {};\n  // set listeners array\n  var listeners = events[ eventName ] = events[ eventName ] || [];\n  // only add once\n  if ( listeners.indexOf( listener ) == -1 ) {\n    listeners.push( listener );\n  }\n\n  return this;\n};\n\nproto.once = function( eventName, listener ) {\n  if ( !eventName || !listener ) {\n    return;\n  }\n  // add event\n  this.on( eventName, listener );\n  // set once flag\n  // set onceEvents hash\n  var onceEvents = this._onceEvents = this._onceEvents || {};\n  // set onceListeners object\n  var onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {};\n  // set flag\n  onceListeners[ listener ] = true;\n\n  return this;\n};\n\nproto.off = function( eventName, listener ) {\n  var listeners = this._events && this._events[ eventName ];\n  if ( !listeners || !listeners.length ) {\n    return;\n  }\n  var index = listeners.indexOf( listener );\n  if ( index != -1 ) {\n    listeners.splice( index, 1 );\n  }\n\n  return this;\n};\n\nproto.emitEvent = function( eventName, args ) {\n  var listeners = this._events && this._events[ eventName ];\n  if ( !listeners || !listeners.length ) {\n    return;\n  }\n  // copy over to avoid interference if .off() in listener\n  listeners = listeners.slice(0);\n  args = args || [];\n  // once stuff\n  var onceListeners = this._onceEvents && this._onceEvents[ eventName ];\n\n  for ( var i=0; i < listeners.length; i++ ) {\n    var listener = listeners[i]\n    var isOnce = onceListeners && onceListeners[ listener ];\n    if ( isOnce ) {\n      // remove listener\n      // remove before trigger to prevent recursion\n      this.off( eventName, listener );\n      // unset once flag\n      delete onceListeners[ listener ];\n    }\n    // trigger listener\n    listener.apply( this, args );\n  }\n\n  return this;\n};\n\nproto.allOff = function() {\n  delete this._events;\n  delete this._onceEvents;\n};\n\nreturn EvEmitter;\n\n}));\n", "/*!\n * getSize v2.0.3\n * measure size of elements\n * MIT license\n */\n\n/* jshint browser: true, strict: true, undef: true, unused: true */\n/* globals console: false */\n\n( function( window, factory ) {\n  /* jshint strict: false */ /* globals define, module */\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( factory );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory();\n  } else {\n    // browser global\n    window.getSize = factory();\n  }\n\n})( window, function factory() {\n'use strict';\n\n// -------------------------- helpers -------------------------- //\n\n// get a number from a string, not a percentage\nfunction getStyleSize( value ) {\n  var num = parseFloat( value );\n  // not a percent like '100%', and a number\n  var isValid = value.indexOf('%') == -1 && !isNaN( num );\n  return isValid && num;\n}\n\nfunction noop() {}\n\nvar logError = typeof console == 'undefined' ? noop :\n  function( message ) {\n    console.error( message );\n  };\n\n// -------------------------- measurements -------------------------- //\n\nvar measurements = [\n  'paddingLeft',\n  'paddingRight',\n  'paddingTop',\n  'paddingBottom',\n  'marginLeft',\n  'marginRight',\n  'marginTop',\n  'marginBottom',\n  'borderLeftWidth',\n  'borderRightWidth',\n  'borderTopWidth',\n  'borderBottomWidth'\n];\n\nvar measurementsLength = measurements.length;\n\nfunction getZeroSize() {\n  var size = {\n    width: 0,\n    height: 0,\n    innerWidth: 0,\n    innerHeight: 0,\n    outerWidth: 0,\n    outerHeight: 0\n  };\n  for ( var i=0; i < measurementsLength; i++ ) {\n    var measurement = measurements[i];\n    size[ measurement ] = 0;\n  }\n  return size;\n}\n\n// -------------------------- getStyle -------------------------- //\n\n/**\n * getStyle, get style of element, check for Firefox bug\n * https://bugzilla.mozilla.org/show_bug.cgi?id=548397\n */\nfunction getStyle( elem ) {\n  var style = getComputedStyle( elem );\n  if ( !style ) {\n    logError( 'Style returned ' + style +\n      '. Are you running this code in a hidden iframe on Firefox? ' +\n      'See https://bit.ly/getsizebug1' );\n  }\n  return style;\n}\n\n// -------------------------- setup -------------------------- //\n\nvar isSetup = false;\n\nvar isBoxSizeOuter;\n\n/**\n * setup\n * check isBoxSizerOuter\n * do on first getSize() rather than on page load for Firefox bug\n */\nfunction setup() {\n  // setup once\n  if ( isSetup ) {\n    return;\n  }\n  isSetup = true;\n\n  // -------------------------- box sizing -------------------------- //\n\n  /**\n   * Chrome & Safari measure the outer-width on style.width on border-box elems\n   * IE11 & Firefox<29 measures the inner-width\n   */\n  var div = document.createElement('div');\n  div.style.width = '200px';\n  div.style.padding = '1px 2px 3px 4px';\n  div.style.borderStyle = 'solid';\n  div.style.borderWidth = '1px 2px 3px 4px';\n  div.style.boxSizing = 'border-box';\n\n  var body = document.body || document.documentElement;\n  body.appendChild( div );\n  var style = getStyle( div );\n  // round value for browser zoom. desandro/masonry#928\n  isBoxSizeOuter = Math.round( getStyleSize( style.width ) ) == 200;\n  getSize.isBoxSizeOuter = isBoxSizeOuter;\n\n  body.removeChild( div );\n}\n\n// -------------------------- getSize -------------------------- //\n\nfunction getSize( elem ) {\n  setup();\n\n  // use querySeletor if elem is string\n  if ( typeof elem == 'string' ) {\n    elem = document.querySelector( elem );\n  }\n\n  // do not proceed on non-objects\n  if ( !elem || typeof elem != 'object' || !elem.nodeType ) {\n    return;\n  }\n\n  var style = getStyle( elem );\n\n  // if hidden, everything is 0\n  if ( style.display == 'none' ) {\n    return getZeroSize();\n  }\n\n  var size = {};\n  size.width = elem.offsetWidth;\n  size.height = elem.offsetHeight;\n\n  var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box';\n\n  // get all measurements\n  for ( var i=0; i < measurementsLength; i++ ) {\n    var measurement = measurements[i];\n    var value = style[ measurement ];\n    var num = parseFloat( value );\n    // any 'auto', 'medium' value will be 0\n    size[ measurement ] = !isNaN( num ) ? num : 0;\n  }\n\n  var paddingWidth = size.paddingLeft + size.paddingRight;\n  var paddingHeight = size.paddingTop + size.paddingBottom;\n  var marginWidth = size.marginLeft + size.marginRight;\n  var marginHeight = size.marginTop + size.marginBottom;\n  var borderWidth = size.borderLeftWidth + size.borderRightWidth;\n  var borderHeight = size.borderTopWidth + size.borderBottomWidth;\n\n  var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;\n\n  // overwrite width and height if we can get it from style\n  var styleWidth = getStyleSize( style.width );\n  if ( styleWidth !== false ) {\n    size.width = styleWidth +\n      // add padding and border unless it's already including it\n      ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );\n  }\n\n  var styleHeight = getStyleSize( style.height );\n  if ( styleHeight !== false ) {\n    size.height = styleHeight +\n      // add padding and border unless it's already including it\n      ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );\n  }\n\n  size.innerWidth = size.width - ( paddingWidth + borderWidth );\n  size.innerHeight = size.height - ( paddingHeight + borderHeight );\n\n  size.outerWidth = size.width + marginWidth;\n  size.outerHeight = size.height + marginHeight;\n\n  return size;\n}\n\nreturn getSize;\n\n});\n", "/**\n * matchesSelector v2.0.2\n * matchesSelector( element, '.selector' )\n * MIT license\n */\n\n/*jshint browser: true, strict: true, undef: true, unused: true */\n\n( function( window, factory ) {\n  /*global define: false, module: false */\n  'use strict';\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( factory );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory();\n  } else {\n    // browser global\n    window.matchesSelector = factory();\n  }\n\n}( window, function factory() {\n  'use strict';\n\n  var matchesMethod = ( function() {\n    var ElemProto = window.Element.prototype;\n    // check for the standard method name first\n    if ( ElemProto.matches ) {\n      return 'matches';\n    }\n    // check un-prefixed\n    if ( ElemProto.matchesSelector ) {\n      return 'matchesSelector';\n    }\n    // check vendor prefixes\n    var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];\n\n    for ( var i=0; i < prefixes.length; i++ ) {\n      var prefix = prefixes[i];\n      var method = prefix + 'MatchesSelector';\n      if ( ElemProto[ method ] ) {\n        return method;\n      }\n    }\n  })();\n\n  return function matchesSelector( elem, selector ) {\n    return elem[ matchesMethod ]( selector );\n  };\n\n}));\n", "/**\n * Fizzy UI utils v2.0.7\n * MIT license\n */\n\n/*jshint browser: true, undef: true, unused: true, strict: true */\n\n( function( window, factory ) {\n  // universal module definition\n  /*jshint strict: false */ /*globals define, module, require */\n\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      'desandro-matches-selector/matches-selector'\n    ], function( matchesSelector ) {\n      return factory( window, matchesSelector );\n    });\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n      window,\n      require('desandro-matches-selector')\n    );\n  } else {\n    // browser global\n    window.fizzyUIUtils = factory(\n      window,\n      window.matchesSelector\n    );\n  }\n\n}( window, function factory( window, matchesSelector ) {\n\n'use strict';\n\nvar utils = {};\n\n// ----- extend ----- //\n\n// extends objects\nutils.extend = function( a, b ) {\n  for ( var prop in b ) {\n    a[ prop ] = b[ prop ];\n  }\n  return a;\n};\n\n// ----- modulo ----- //\n\nutils.modulo = function( num, div ) {\n  return ( ( num % div ) + div ) % div;\n};\n\n// ----- makeArray ----- //\n\nvar arraySlice = Array.prototype.slice;\n\n// turn element or nodeList into an array\nutils.makeArray = function( obj ) {\n  if ( Array.isArray( obj ) ) {\n    // use object if already an array\n    return obj;\n  }\n  // return empty array if undefined or null. #6\n  if ( obj === null || obj === undefined ) {\n    return [];\n  }\n\n  var isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';\n  if ( isArrayLike ) {\n    // convert nodeList to array\n    return arraySlice.call( obj );\n  }\n\n  // array of single index\n  return [ obj ];\n};\n\n// ----- removeFrom ----- //\n\nutils.removeFrom = function( ary, obj ) {\n  var index = ary.indexOf( obj );\n  if ( index != -1 ) {\n    ary.splice( index, 1 );\n  }\n};\n\n// ----- getParent ----- //\n\nutils.getParent = function( elem, selector ) {\n  while ( elem.parentNode && elem != document.body ) {\n    elem = elem.parentNode;\n    if ( matchesSelector( elem, selector ) ) {\n      return elem;\n    }\n  }\n};\n\n// ----- getQueryElement ----- //\n\n// use element as selector string\nutils.getQueryElement = function( elem ) {\n  if ( typeof elem == 'string' ) {\n    return document.querySelector( elem );\n  }\n  return elem;\n};\n\n// ----- handleEvent ----- //\n\n// enable .ontype to trigger from .addEventListener( elem, 'type' )\nutils.handleEvent = function( event ) {\n  var method = 'on' + event.type;\n  if ( this[ method ] ) {\n    this[ method ]( event );\n  }\n};\n\n// ----- filterFindElements ----- //\n\nutils.filterFindElements = function( elems, selector ) {\n  // make array of elems\n  elems = utils.makeArray( elems );\n  var ffElems = [];\n\n  elems.forEach( function( elem ) {\n    // check that elem is an actual element\n    if ( !( elem instanceof HTMLElement ) ) {\n      return;\n    }\n    // add elem if no selector\n    if ( !selector ) {\n      ffElems.push( elem );\n      return;\n    }\n    // filter & find items if we have a selector\n    // filter\n    if ( matchesSelector( elem, selector ) ) {\n      ffElems.push( elem );\n    }\n    // find children\n    var childElems = elem.querySelectorAll( selector );\n    // concat childElems to filterFound array\n    for ( var i=0; i < childElems.length; i++ ) {\n      ffElems.push( childElems[i] );\n    }\n  });\n\n  return ffElems;\n};\n\n// ----- debounceMethod ----- //\n\nutils.debounceMethod = function( _class, methodName, threshold ) {\n  threshold = threshold || 100;\n  // original method\n  var method = _class.prototype[ methodName ];\n  var timeoutName = methodName + 'Timeout';\n\n  _class.prototype[ methodName ] = function() {\n    var timeout = this[ timeoutName ];\n    clearTimeout( timeout );\n\n    var args = arguments;\n    var _this = this;\n    this[ timeoutName ] = setTimeout( function() {\n      method.apply( _this, args );\n      delete _this[ timeoutName ];\n    }, threshold );\n  };\n};\n\n// ----- docReady ----- //\n\nutils.docReady = function( callback ) {\n  var readyState = document.readyState;\n  if ( readyState == 'complete' || readyState == 'interactive' ) {\n    // do async to allow for other scripts to run. metafizzy/flickity#441\n    setTimeout( callback );\n  } else {\n    document.addEventListener( 'DOMContentLoaded', callback );\n  }\n};\n\n// ----- htmlInit ----- //\n\n// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/\nutils.toDashed = function( str ) {\n  return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {\n    return $1 + '-' + $2;\n  }).toLowerCase();\n};\n\nvar console = window.console;\n/**\n * allow user to initialize classes via [data-namespace] or .js-namespace class\n * htmlInit( Widget, 'widgetName' )\n * options are parsed from data-namespace-options\n */\nutils.htmlInit = function( WidgetClass, namespace ) {\n  utils.docReady( function() {\n    var dashedNamespace = utils.toDashed( namespace );\n    var dataAttr = 'data-' + dashedNamespace;\n    var dataAttrElems = document.querySelectorAll( '[' + dataAttr + ']' );\n    var jsDashElems = document.querySelectorAll( '.js-' + dashedNamespace );\n    var elems = utils.makeArray( dataAttrElems )\n      .concat( utils.makeArray( jsDashElems ) );\n    var dataOptionsAttr = dataAttr + '-options';\n    var jQuery = window.jQuery;\n\n    elems.forEach( function( elem ) {\n      var attr = elem.getAttribute( dataAttr ) ||\n        elem.getAttribute( dataOptionsAttr );\n      var options;\n      try {\n        options = attr && JSON.parse( attr );\n      } catch ( error ) {\n        // log error, do not initialize\n        if ( console ) {\n          console.error( 'Error parsing ' + dataAttr + ' on ' + elem.className +\n          ': ' + error );\n        }\n        return;\n      }\n      // initialize\n      var instance = new WidgetClass( elem, options );\n      // make available via $().data('namespace')\n      if ( jQuery ) {\n        jQuery.data( elem, namespace, instance );\n      }\n    });\n\n  });\n};\n\n// -----  ----- //\n\nreturn utils;\n\n}));\n", "// Flickity.Cell\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      'get-size/get-size',\n    ], function( getSize ) {\n      return factory( window, getSize );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('get-size')\n    );\n  } else {\n    // browser global\n    window.Flickity = window.Flickity || {};\n    window.Flickity.Cell = factory(\n        window,\n        window.getSize\n    );\n  }\n\n}( window, function factory( window, getSize ) {\n\n'use strict';\n\nfunction Cell( elem, parent ) {\n  this.element = elem;\n  this.parent = parent;\n\n  this.create();\n}\n\nvar proto = Cell.prototype;\n\nproto.create = function() {\n  this.element.style.position = 'absolute';\n  this.element.setAttribute( 'aria-hidden', 'true' );\n  this.x = 0;\n  this.shift = 0;\n  this.element.style[ this.parent.originSide ] = 0;\n};\n\nproto.destroy = function() {\n  // reset style\n  this.unselect();\n  this.element.style.position = '';\n  var side = this.parent.originSide;\n  this.element.style[ side ] = '';\n  this.element.style.transform = '';\n  this.element.removeAttribute('aria-hidden');\n};\n\nproto.getSize = function() {\n  this.size = getSize( this.element );\n};\n\nproto.setPosition = function( x ) {\n  this.x = x;\n  this.updateTarget();\n  this.renderPosition( x );\n};\n\n// setDefaultTarget v1 method, backwards compatibility, remove in v3\nproto.updateTarget = proto.setDefaultTarget = function() {\n  var marginProperty = this.parent.originSide == 'left' ? 'marginLeft' : 'marginRight';\n  this.target = this.x + this.size[ marginProperty ] +\n    this.size.width * this.parent.cellAlign;\n};\n\nproto.renderPosition = function( x ) {\n  // render position of cell with in slider\n  var sideOffset = this.parent.originSide === 'left' ? 1 : -1;\n\n  var adjustedX = this.parent.options.percentPosition ?\n    x * sideOffset * ( this.parent.size.innerWidth / this.size.width ) :\n    x * sideOffset;\n\n  this.element.style.transform = 'translateX(' +\n    this.parent.getPositionValue( adjustedX ) + ')';\n};\n\nproto.select = function() {\n  this.element.classList.add('is-selected');\n  this.element.removeAttribute('aria-hidden');\n};\n\nproto.unselect = function() {\n  this.element.classList.remove('is-selected');\n  this.element.setAttribute( 'aria-hidden', 'true' );\n};\n\n/**\n * @param {Integer} shift - 0, 1, or -1\n */\nproto.wrapShift = function( shift ) {\n  this.shift = shift;\n  this.renderPosition( this.x + this.parent.slideableWidth * shift );\n};\n\nproto.remove = function() {\n  this.element.parentNode.removeChild( this.element );\n};\n\nreturn Cell;\n\n} ) );\n", "// slide\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( factory );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory();\n  } else {\n    // browser global\n    window.Flickity = window.Flickity || {};\n    window.Flickity.Slide = factory();\n  }\n\n}( window, function factory() {\n'use strict';\n\nfunction Slide( parent ) {\n  this.parent = parent;\n  this.isOriginLeft = parent.originSide == 'left';\n  this.cells = [];\n  this.outerWidth = 0;\n  this.height = 0;\n}\n\nvar proto = Slide.prototype;\n\nproto.addCell = function( cell ) {\n  this.cells.push( cell );\n  this.outerWidth += cell.size.outerWidth;\n  this.height = Math.max( cell.size.outerHeight, this.height );\n  // first cell stuff\n  if ( this.cells.length == 1 ) {\n    this.x = cell.x; // x comes from first cell\n    var beginMargin = this.isOriginLeft ? 'marginLeft' : 'marginRight';\n    this.firstMargin = cell.size[ beginMargin ];\n  }\n};\n\nproto.updateTarget = function() {\n  var endMargin = this.isOriginLeft ? 'marginRight' : 'marginLeft';\n  var lastCell = this.getLastCell();\n  var lastMargin = lastCell ? lastCell.size[ endMargin ] : 0;\n  var slideWidth = this.outerWidth - ( this.firstMargin + lastMargin );\n  this.target = this.x + this.firstMargin + slideWidth * this.parent.cellAlign;\n};\n\nproto.getLastCell = function() {\n  return this.cells[ this.cells.length - 1 ];\n};\n\nproto.select = function() {\n  this.cells.forEach( function( cell ) {\n    cell.select();\n  } );\n};\n\nproto.unselect = function() {\n  this.cells.forEach( function( cell ) {\n    cell.unselect();\n  } );\n};\n\nproto.getCellElements = function() {\n  return this.cells.map( function( cell ) {\n    return cell.element;\n  } );\n};\n\nreturn Slide;\n\n} ) );\n", "// animate\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      'fizzy-ui-utils/utils',\n    ], function( utils ) {\n      return factory( window, utils );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('fizzy-ui-utils')\n    );\n  } else {\n    // browser global\n    window.Flickity = window.Flickity || {};\n    window.Flickity.animatePrototype = factory(\n        window,\n        window.fizzyUIUtils\n    );\n  }\n\n}( window, function factory( window, utils ) {\n\n'use strict';\n\n// -------------------------- animate -------------------------- //\n\nvar proto = {};\n\nproto.startAnimation = function() {\n  if ( this.isAnimating ) {\n    return;\n  }\n\n  this.isAnimating = true;\n  this.restingFrames = 0;\n  this.animate();\n};\n\nproto.animate = function() {\n  this.applyDragForce();\n  this.applySelectedAttraction();\n\n  var previousX = this.x;\n\n  this.integratePhysics();\n  this.positionSlider();\n  this.settle( previousX );\n  // animate next frame\n  if ( this.isAnimating ) {\n    var _this = this;\n    requestAnimationFrame( function animateFrame() {\n      _this.animate();\n    } );\n  }\n};\n\nproto.positionSlider = function() {\n  var x = this.x;\n  // wrap position around\n  if ( this.options.wrapAround && this.cells.length > 1 ) {\n    x = utils.modulo( x, this.slideableWidth );\n    x -= this.slideableWidth;\n    this.shiftWrapCells( x );\n  }\n\n  this.setTranslateX( x, this.isAnimating );\n  this.dispatchScrollEvent();\n};\n\nproto.setTranslateX = function( x, is3d ) {\n  x += this.cursorPosition;\n  // reverse if right-to-left and using transform\n  x = this.options.rightToLeft ? -x : x;\n  var translateX = this.getPositionValue( x );\n  // use 3D transforms for hardware acceleration on iOS\n  // but use 2D when settled, for better font-rendering\n  this.slider.style.transform = is3d ?\n    'translate3d(' + translateX + ',0,0)' : 'translateX(' + translateX + ')';\n};\n\nproto.dispatchScrollEvent = function() {\n  var firstSlide = this.slides[0];\n  if ( !firstSlide ) {\n    return;\n  }\n  var positionX = -this.x - firstSlide.target;\n  var progress = positionX / this.slidesWidth;\n  this.dispatchEvent( 'scroll', null, [ progress, positionX ] );\n};\n\nproto.positionSliderAtSelected = function() {\n  if ( !this.cells.length ) {\n    return;\n  }\n  this.x = -this.selectedSlide.target;\n  this.velocity = 0; // stop wobble\n  this.positionSlider();\n};\n\nproto.getPositionValue = function( position ) {\n  if ( this.options.percentPosition ) {\n    // percent position, round to 2 digits, like 12.34%\n    return ( Math.round( ( position / this.size.innerWidth ) * 10000 ) * 0.01 ) + '%';\n  } else {\n    // pixel positioning\n    return Math.round( position ) + 'px';\n  }\n};\n\nproto.settle = function( previousX ) {\n  // keep track of frames where x hasn't moved\n  var isResting = !this.isPointerDown &&\n      Math.round( this.x * 100 ) == Math.round( previousX * 100 );\n  if ( isResting ) {\n    this.restingFrames++;\n  }\n  // stop animating if resting for 3 or more frames\n  if ( this.restingFrames > 2 ) {\n    this.isAnimating = false;\n    delete this.isFreeScrolling;\n    // render position with translateX when settled\n    this.positionSlider();\n    this.dispatchEvent( 'settle', null, [ this.selectedIndex ] );\n  }\n};\n\nproto.shiftWrapCells = function( x ) {\n  // shift before cells\n  var beforeGap = this.cursorPosition + x;\n  this._shiftCells( this.beforeShiftCells, beforeGap, -1 );\n  // shift after cells\n  var afterGap = this.size.innerWidth - ( x + this.slideableWidth + this.cursorPosition );\n  this._shiftCells( this.afterShiftCells, afterGap, 1 );\n};\n\nproto._shiftCells = function( cells, gap, shift ) {\n  for ( var i = 0; i < cells.length; i++ ) {\n    var cell = cells[i];\n    var cellShift = gap > 0 ? shift : 0;\n    cell.wrapShift( cellShift );\n    gap -= cell.size.outerWidth;\n  }\n};\n\nproto._unshiftCells = function( cells ) {\n  if ( !cells || !cells.length ) {\n    return;\n  }\n  for ( var i = 0; i < cells.length; i++ ) {\n    cells[i].wrapShift( 0 );\n  }\n};\n\n// -------------------------- physics -------------------------- //\n\nproto.integratePhysics = function() {\n  this.x += this.velocity;\n  this.velocity *= this.getFrictionFactor();\n};\n\nproto.applyForce = function( force ) {\n  this.velocity += force;\n};\n\nproto.getFrictionFactor = function() {\n  return 1 - this.options[ this.isFreeScrolling ? 'freeScrollFriction' : 'friction' ];\n};\n\nproto.getRestingPosition = function() {\n  // my thanks to Steven Wittens, who simplified this math greatly\n  return this.x + this.velocity / ( 1 - this.getFrictionFactor() );\n};\n\nproto.applyDragForce = function() {\n  if ( !this.isDraggable || !this.isPointerDown ) {\n    return;\n  }\n  // change the position to drag position by applying force\n  var dragVelocity = this.dragX - this.x;\n  var dragForce = dragVelocity - this.velocity;\n  this.applyForce( dragForce );\n};\n\nproto.applySelectedAttraction = function() {\n  // do not attract if pointer down or no slides\n  var dragDown = this.isDraggable && this.isPointerDown;\n  if ( dragDown || this.isFreeScrolling || !this.slides.length ) {\n    return;\n  }\n  var distance = this.selectedSlide.target * -1 - this.x;\n  var force = distance * this.options.selectedAttraction;\n  this.applyForce( force );\n};\n\nreturn proto;\n\n} ) );\n", "// Flickity main\n/* eslint-disable max-params */\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      'ev-emitter/ev-emitter',\n      'get-size/get-size',\n      'fizzy-ui-utils/utils',\n      './cell',\n      './slide',\n      './animate',\n    ], function( EvEmitter, getSize, utils, Cell, Slide, animatePrototype ) {\n      return factory( window, EvEmitter, getSize, utils, Cell, Slide, animatePrototype );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('ev-emitter'),\n        require('get-size'),\n        require('fizzy-ui-utils'),\n        require('./cell'),\n        require('./slide'),\n        require('./animate')\n    );\n  } else {\n    // browser global\n    var _Flickity = window.Flickity;\n\n    window.Flickity = factory(\n        window,\n        window.EvEmitter,\n        window.getSize,\n        window.fizzyUIUtils,\n        _Flickity.Cell,\n        _Flickity.Slide,\n        _Flickity.animatePrototype\n    );\n  }\n\n}( window, function factory( window, EvEmitter, getSize,\n    utils, Cell, Slide, animatePrototype ) {\n\n/* eslint-enable max-params */\n'use strict';\n\n// vars\nvar jQuery = window.jQuery;\nvar getComputedStyle = window.getComputedStyle;\nvar console = window.console;\n\nfunction moveElements( elems, toElem ) {\n  elems = utils.makeArray( elems );\n  while ( elems.length ) {\n    toElem.appendChild( elems.shift() );\n  }\n}\n\n// -------------------------- Flickity -------------------------- //\n\n// globally unique identifiers\nvar GUID = 0;\n// internal store of all Flickity intances\nvar instances = {};\n\nfunction Flickity( element, options ) {\n  var queryElement = utils.getQueryElement( element );\n  if ( !queryElement ) {\n    if ( console ) {\n      console.error( 'Bad element for Flickity: ' + ( queryElement || element ) );\n    }\n    return;\n  }\n  this.element = queryElement;\n  // do not initialize twice on same element\n  if ( this.element.flickityGUID ) {\n    var instance = instances[ this.element.flickityGUID ];\n    if ( instance ) instance.option( options );\n    return instance;\n  }\n\n  // add jQuery\n  if ( jQuery ) {\n    this.$element = jQuery( this.element );\n  }\n  // options\n  this.options = utils.extend( {}, this.constructor.defaults );\n  this.option( options );\n\n  // kick things off\n  this._create();\n}\n\nFlickity.defaults = {\n  accessibility: true,\n  // adaptiveHeight: false,\n  cellAlign: 'center',\n  // cellSelector: undefined,\n  // contain: false,\n  freeScrollFriction: 0.075, // friction when free-scrolling\n  friction: 0.28, // friction when selecting\n  namespaceJQueryEvents: true,\n  // initialIndex: 0,\n  percentPosition: true,\n  resize: true,\n  selectedAttraction: 0.025,\n  setGallerySize: true,\n  // watchCSS: false,\n  // wrapAround: false\n};\n\n// hash of methods triggered on _create()\nFlickity.createMethods = [];\n\nvar proto = Flickity.prototype;\n// inherit EventEmitter\nutils.extend( proto, EvEmitter.prototype );\n\nproto._create = function() {\n  // add id for Flickity.data\n  var id = this.guid = ++GUID;\n  this.element.flickityGUID = id; // expando\n  instances[ id ] = this; // associate via id\n  // initial properties\n  this.selectedIndex = 0;\n  // how many frames slider has been in same position\n  this.restingFrames = 0;\n  // initial physics properties\n  this.x = 0;\n  this.velocity = 0;\n  this.originSide = this.options.rightToLeft ? 'right' : 'left';\n  // create viewport & slider\n  this.viewport = document.createElement('div');\n  this.viewport.className = 'flickity-viewport';\n  this._createSlider();\n\n  if ( this.options.resize || this.options.watchCSS ) {\n    window.addEventListener( 'resize', this );\n  }\n\n  // add listeners from on option\n  for ( var eventName in this.options.on ) {\n    var listener = this.options.on[ eventName ];\n    this.on( eventName, listener );\n  }\n\n  Flickity.createMethods.forEach( function( method ) {\n    this[ method ]();\n  }, this );\n\n  if ( this.options.watchCSS ) {\n    this.watchCSS();\n  } else {\n    this.activate();\n  }\n\n};\n\n/**\n * set options\n * @param {Object} opts - options to extend\n */\nproto.option = function( opts ) {\n  utils.extend( this.options, opts );\n};\n\nproto.activate = function() {\n  if ( this.isActive ) {\n    return;\n  }\n  this.isActive = true;\n  this.element.classList.add('flickity-enabled');\n  if ( this.options.rightToLeft ) {\n    this.element.classList.add('flickity-rtl');\n  }\n\n  this.getSize();\n  // move initial cell elements so they can be loaded as cells\n  var cellElems = this._filterFindCellElements( this.element.children );\n  moveElements( cellElems, this.slider );\n  this.viewport.appendChild( this.slider );\n  this.element.appendChild( this.viewport );\n  // get cells from children\n  this.reloadCells();\n\n  if ( this.options.accessibility ) {\n    // allow element to focusable\n    this.element.tabIndex = 0;\n    // listen for key presses\n    this.element.addEventListener( 'keydown', this );\n  }\n\n  this.emitEvent('activate');\n  this.selectInitialIndex();\n  // flag for initial activation, for using initialIndex\n  this.isInitActivated = true;\n  // ready event. #493\n  this.dispatchEvent('ready');\n};\n\n// slider positions the cells\nproto._createSlider = function() {\n  // slider element does all the positioning\n  var slider = document.createElement('div');\n  slider.className = 'flickity-slider';\n  slider.style[ this.originSide ] = 0;\n  this.slider = slider;\n};\n\nproto._filterFindCellElements = function( elems ) {\n  return utils.filterFindElements( elems, this.options.cellSelector );\n};\n\n// goes through all children\nproto.reloadCells = function() {\n  // collection of item elements\n  this.cells = this._makeCells( this.slider.children );\n  this.positionCells();\n  this._getWrapShiftCells();\n  this.setGallerySize();\n};\n\n/**\n * turn elements into Flickity.Cells\n * @param {[Array, NodeList, HTMLElement]} elems - elements to make into cells\n * @returns {Array} items - collection of new Flickity Cells\n */\nproto._makeCells = function( elems ) {\n  var cellElems = this._filterFindCellElements( elems );\n\n  // create new Flickity for collection\n  var cells = cellElems.map( function( cellElem ) {\n    return new Cell( cellElem, this );\n  }, this );\n\n  return cells;\n};\n\nproto.getLastCell = function() {\n  return this.cells[ this.cells.length - 1 ];\n};\n\nproto.getLastSlide = function() {\n  return this.slides[ this.slides.length - 1 ];\n};\n\n// positions all cells\nproto.positionCells = function() {\n  // size all cells\n  this._sizeCells( this.cells );\n  // position all cells\n  this._positionCells( 0 );\n};\n\n/**\n * position certain cells\n * @param {Integer} index - which cell to start with\n */\nproto._positionCells = function( index ) {\n  index = index || 0;\n  // also measure maxCellHeight\n  // start 0 if positioning all cells\n  this.maxCellHeight = index ? this.maxCellHeight || 0 : 0;\n  var cellX = 0;\n  // get cellX\n  if ( index > 0 ) {\n    var startCell = this.cells[ index - 1 ];\n    cellX = startCell.x + startCell.size.outerWidth;\n  }\n  var len = this.cells.length;\n  for ( var i = index; i < len; i++ ) {\n    var cell = this.cells[i];\n    cell.setPosition( cellX );\n    cellX += cell.size.outerWidth;\n    this.maxCellHeight = Math.max( cell.size.outerHeight, this.maxCellHeight );\n  }\n  // keep track of cellX for wrap-around\n  this.slideableWidth = cellX;\n  // slides\n  this.updateSlides();\n  // contain slides target\n  this._containSlides();\n  // update slidesWidth\n  this.slidesWidth = len ? this.getLastSlide().target - this.slides[0].target : 0;\n};\n\n/**\n * cell.getSize() on multiple cells\n * @param {Array} cells - cells to size\n */\nproto._sizeCells = function( cells ) {\n  cells.forEach( function( cell ) {\n    cell.getSize();\n  } );\n};\n\n// --------------------------  -------------------------- //\n\nproto.updateSlides = function() {\n  this.slides = [];\n  if ( !this.cells.length ) {\n    return;\n  }\n\n  var slide = new Slide( this );\n  this.slides.push( slide );\n  var isOriginLeft = this.originSide == 'left';\n  var nextMargin = isOriginLeft ? 'marginRight' : 'marginLeft';\n\n  var canCellFit = this._getCanCellFit();\n\n  this.cells.forEach( function( cell, i ) {\n    // just add cell if first cell in slide\n    if ( !slide.cells.length ) {\n      slide.addCell( cell );\n      return;\n    }\n\n    var slideWidth = ( slide.outerWidth - slide.firstMargin ) +\n      ( cell.size.outerWidth - cell.size[ nextMargin ] );\n\n    if ( canCellFit.call( this, i, slideWidth ) ) {\n      slide.addCell( cell );\n    } else {\n      // doesn't fit, new slide\n      slide.updateTarget();\n\n      slide = new Slide( this );\n      this.slides.push( slide );\n      slide.addCell( cell );\n    }\n  }, this );\n  // last slide\n  slide.updateTarget();\n  // update .selectedSlide\n  this.updateSelectedSlide();\n};\n\nproto._getCanCellFit = function() {\n  var groupCells = this.options.groupCells;\n  if ( !groupCells ) {\n    return function() {\n      return false;\n    };\n  } else if ( typeof groupCells == 'number' ) {\n    // group by number. 3 -> [0,1,2], [3,4,5], ...\n    var number = parseInt( groupCells, 10 );\n    return function( i ) {\n      return ( i % number ) !== 0;\n    };\n  }\n  // default, group by width of slide\n  // parse '75%\n  var percentMatch = typeof groupCells == 'string' &&\n    groupCells.match( /^(\\d+)%$/ );\n  var percent = percentMatch ? parseInt( percentMatch[1], 10 ) / 100 : 1;\n  return function( i, slideWidth ) {\n    /* eslint-disable-next-line no-invalid-this */\n    return slideWidth <= ( this.size.innerWidth + 1 ) * percent;\n  };\n};\n\n// alias _init for jQuery plugin .flickity()\nproto._init =\nproto.reposition = function() {\n  this.positionCells();\n  this.positionSliderAtSelected();\n};\n\nproto.getSize = function() {\n  this.size = getSize( this.element );\n  this.setCellAlign();\n  this.cursorPosition = this.size.innerWidth * this.cellAlign;\n};\n\nvar cellAlignShorthands = {\n  // cell align, then based on origin side\n  center: {\n    left: 0.5,\n    right: 0.5,\n  },\n  left: {\n    left: 0,\n    right: 1,\n  },\n  right: {\n    right: 0,\n    left: 1,\n  },\n};\n\nproto.setCellAlign = function() {\n  var shorthand = cellAlignShorthands[ this.options.cellAlign ];\n  this.cellAlign = shorthand ? shorthand[ this.originSide ] : this.options.cellAlign;\n};\n\nproto.setGallerySize = function() {\n  if ( this.options.setGallerySize ) {\n    var height = this.options.adaptiveHeight && this.selectedSlide ?\n      this.selectedSlide.height : this.maxCellHeight;\n    this.viewport.style.height = height + 'px';\n  }\n};\n\nproto._getWrapShiftCells = function() {\n  // only for wrap-around\n  if ( !this.options.wrapAround ) {\n    return;\n  }\n  // unshift previous cells\n  this._unshiftCells( this.beforeShiftCells );\n  this._unshiftCells( this.afterShiftCells );\n  // get before cells\n  // initial gap\n  var gapX = this.cursorPosition;\n  var cellIndex = this.cells.length - 1;\n  this.beforeShiftCells = this._getGapCells( gapX, cellIndex, -1 );\n  // get after cells\n  // ending gap between last cell and end of gallery viewport\n  gapX = this.size.innerWidth - this.cursorPosition;\n  // start cloning at first cell, working forwards\n  this.afterShiftCells = this._getGapCells( gapX, 0, 1 );\n};\n\nproto._getGapCells = function( gapX, cellIndex, increment ) {\n  // keep adding cells until the cover the initial gap\n  var cells = [];\n  while ( gapX > 0 ) {\n    var cell = this.cells[ cellIndex ];\n    if ( !cell ) {\n      break;\n    }\n    cells.push( cell );\n    cellIndex += increment;\n    gapX -= cell.size.outerWidth;\n  }\n  return cells;\n};\n\n// ----- contain ----- //\n\n// contain cell targets so no excess sliding\nproto._containSlides = function() {\n  if ( !this.options.contain || this.options.wrapAround || !this.cells.length ) {\n    return;\n  }\n  var isRightToLeft = this.options.rightToLeft;\n  var beginMargin = isRightToLeft ? 'marginRight' : 'marginLeft';\n  var endMargin = isRightToLeft ? 'marginLeft' : 'marginRight';\n  var contentWidth = this.slideableWidth - this.getLastCell().size[ endMargin ];\n  // content is less than gallery size\n  var isContentSmaller = contentWidth < this.size.innerWidth;\n  // bounds\n  var beginBound = this.cursorPosition + this.cells[0].size[ beginMargin ];\n  var endBound = contentWidth - this.size.innerWidth * ( 1 - this.cellAlign );\n  // contain each cell target\n  this.slides.forEach( function( slide ) {\n    if ( isContentSmaller ) {\n      // all cells fit inside gallery\n      slide.target = contentWidth * this.cellAlign;\n    } else {\n      // contain to bounds\n      slide.target = Math.max( slide.target, beginBound );\n      slide.target = Math.min( slide.target, endBound );\n    }\n  }, this );\n};\n\n// -----  ----- //\n\n/**\n * emits events via eventEmitter and jQuery events\n * @param {String} type - name of event\n * @param {Event} event - original event\n * @param {Array} args - extra arguments\n */\nproto.dispatchEvent = function( type, event, args ) {\n  var emitArgs = event ? [ event ].concat( args ) : args;\n  this.emitEvent( type, emitArgs );\n\n  if ( jQuery && this.$element ) {\n    // default trigger with type if no event\n    type += this.options.namespaceJQueryEvents ? '.flickity' : '';\n    var $event = type;\n    if ( event ) {\n      // create jQuery event\n      var jQEvent = new jQuery.Event( event );\n      jQEvent.type = type;\n      $event = jQEvent;\n    }\n    this.$element.trigger( $event, args );\n  }\n};\n\n// -------------------------- select -------------------------- //\n\n/**\n * @param {Integer} index - index of the slide\n * @param {Boolean} isWrap - will wrap-around to last/first if at the end\n * @param {Boolean} isInstant - will immediately set position at selected cell\n */\nproto.select = function( index, isWrap, isInstant ) {\n  if ( !this.isActive ) {\n    return;\n  }\n  index = parseInt( index, 10 );\n  this._wrapSelect( index );\n\n  if ( this.options.wrapAround || isWrap ) {\n    index = utils.modulo( index, this.slides.length );\n  }\n  // bail if invalid index\n  if ( !this.slides[ index ] ) {\n    return;\n  }\n  var prevIndex = this.selectedIndex;\n  this.selectedIndex = index;\n  this.updateSelectedSlide();\n  if ( isInstant ) {\n    this.positionSliderAtSelected();\n  } else {\n    this.startAnimation();\n  }\n  if ( this.options.adaptiveHeight ) {\n    this.setGallerySize();\n  }\n  // events\n  this.dispatchEvent( 'select', null, [ index ] );\n  // change event if new index\n  if ( index != prevIndex ) {\n    this.dispatchEvent( 'change', null, [ index ] );\n  }\n  // old v1 event name, remove in v3\n  this.dispatchEvent('cellSelect');\n};\n\n// wraps position for wrapAround, to move to closest slide. #113\nproto._wrapSelect = function( index ) {\n  var len = this.slides.length;\n  var isWrapping = this.options.wrapAround && len > 1;\n  if ( !isWrapping ) {\n    return index;\n  }\n  var wrapIndex = utils.modulo( index, len );\n  // go to shortest\n  var delta = Math.abs( wrapIndex - this.selectedIndex );\n  var backWrapDelta = Math.abs( ( wrapIndex + len ) - this.selectedIndex );\n  var forewardWrapDelta = Math.abs( ( wrapIndex - len ) - this.selectedIndex );\n  if ( !this.isDragSelect && backWrapDelta < delta ) {\n    index += len;\n  } else if ( !this.isDragSelect && forewardWrapDelta < delta ) {\n    index -= len;\n  }\n  // wrap position so slider is within normal area\n  if ( index < 0 ) {\n    this.x -= this.slideableWidth;\n  } else if ( index >= len ) {\n    this.x += this.slideableWidth;\n  }\n};\n\nproto.previous = function( isWrap, isInstant ) {\n  this.select( this.selectedIndex - 1, isWrap, isInstant );\n};\n\nproto.next = function( isWrap, isInstant ) {\n  this.select( this.selectedIndex + 1, isWrap, isInstant );\n};\n\nproto.updateSelectedSlide = function() {\n  var slide = this.slides[ this.selectedIndex ];\n  // selectedIndex could be outside of slides, if triggered before resize()\n  if ( !slide ) {\n    return;\n  }\n  // unselect previous selected slide\n  this.unselectSelectedSlide();\n  // update new selected slide\n  this.selectedSlide = slide;\n  slide.select();\n  this.selectedCells = slide.cells;\n  this.selectedElements = slide.getCellElements();\n  // HACK: selectedCell & selectedElement is first cell in slide, backwards compatibility\n  // Remove in v3?\n  this.selectedCell = slide.cells[0];\n  this.selectedElement = this.selectedElements[0];\n};\n\nproto.unselectSelectedSlide = function() {\n  if ( this.selectedSlide ) {\n    this.selectedSlide.unselect();\n  }\n};\n\nproto.selectInitialIndex = function() {\n  var initialIndex = this.options.initialIndex;\n  // already activated, select previous selectedIndex\n  if ( this.isInitActivated ) {\n    this.select( this.selectedIndex, false, true );\n    return;\n  }\n  // select with selector string\n  if ( initialIndex && typeof initialIndex == 'string' ) {\n    var cell = this.queryCell( initialIndex );\n    if ( cell ) {\n      this.selectCell( initialIndex, false, true );\n      return;\n    }\n  }\n\n  var index = 0;\n  // select with number\n  if ( initialIndex && this.slides[ initialIndex ] ) {\n    index = initialIndex;\n  }\n  // select instantly\n  this.select( index, false, true );\n};\n\n/**\n * select slide from number or cell element\n * @param {[Element, Number]} value - zero-based index or element to select\n * @param {Boolean} isWrap - enables wrapping around for extra index\n * @param {Boolean} isInstant - disables slide animation\n */\nproto.selectCell = function( value, isWrap, isInstant ) {\n  // get cell\n  var cell = this.queryCell( value );\n  if ( !cell ) {\n    return;\n  }\n\n  var index = this.getCellSlideIndex( cell );\n  this.select( index, isWrap, isInstant );\n};\n\nproto.getCellSlideIndex = function( cell ) {\n  // get index of slides that has cell\n  for ( var i = 0; i < this.slides.length; i++ ) {\n    var slide = this.slides[i];\n    var index = slide.cells.indexOf( cell );\n    if ( index != -1 ) {\n      return i;\n    }\n  }\n};\n\n// -------------------------- get cells -------------------------- //\n\n/**\n * get Flickity.Cell, given an Element\n * @param {Element} elem - matching cell element\n * @returns {Flickity.Cell} cell - matching cell\n */\nproto.getCell = function( elem ) {\n  // loop through cells to get the one that matches\n  for ( var i = 0; i < this.cells.length; i++ ) {\n    var cell = this.cells[i];\n    if ( cell.element == elem ) {\n      return cell;\n    }\n  }\n};\n\n/**\n * get collection of Flickity.Cells, given Elements\n * @param {[Element, Array, NodeList]} elems - multiple elements\n * @returns {Array} cells - Flickity.Cells\n */\nproto.getCells = function( elems ) {\n  elems = utils.makeArray( elems );\n  var cells = [];\n  elems.forEach( function( elem ) {\n    var cell = this.getCell( elem );\n    if ( cell ) {\n      cells.push( cell );\n    }\n  }, this );\n  return cells;\n};\n\n/**\n * get cell elements\n * @returns {Array} cellElems\n */\nproto.getCellElements = function() {\n  return this.cells.map( function( cell ) {\n    return cell.element;\n  } );\n};\n\n/**\n * get parent cell from an element\n * @param {Element} elem - child element\n * @returns {Flickit.Cell} cell - parent cell\n */\nproto.getParentCell = function( elem ) {\n  // first check if elem is cell\n  var cell = this.getCell( elem );\n  if ( cell ) {\n    return cell;\n  }\n  // try to get parent cell elem\n  elem = utils.getParent( elem, '.flickity-slider > *' );\n  return this.getCell( elem );\n};\n\n/**\n * get cells adjacent to a slide\n * @param {Integer} adjCount - number of adjacent slides\n * @param {Integer} index - index of slide to start\n * @returns {Array} cells - array of Flickity.Cells\n */\nproto.getAdjacentCellElements = function( adjCount, index ) {\n  if ( !adjCount ) {\n    return this.selectedSlide.getCellElements();\n  }\n  index = index === undefined ? this.selectedIndex : index;\n\n  var len = this.slides.length;\n  if ( 1 + ( adjCount * 2 ) >= len ) {\n    return this.getCellElements();\n  }\n\n  var cellElems = [];\n  for ( var i = index - adjCount; i <= index + adjCount; i++ ) {\n    var slideIndex = this.options.wrapAround ? utils.modulo( i, len ) : i;\n    var slide = this.slides[ slideIndex ];\n    if ( slide ) {\n      cellElems = cellElems.concat( slide.getCellElements() );\n    }\n  }\n  return cellElems;\n};\n\n/**\n * select slide from number or cell element\n * @param {[Element, String, Number]} selector - element, selector string, or index\n * @returns {Flickity.Cell} - matching cell\n */\nproto.queryCell = function( selector ) {\n  if ( typeof selector == 'number' ) {\n    // use number as index\n    return this.cells[ selector ];\n  }\n  if ( typeof selector == 'string' ) {\n    // do not select invalid selectors from hash: #123, #/. #791\n    if ( selector.match( /^[#.]?[\\d/]/ ) ) {\n      return;\n    }\n    // use string as selector, get element\n    selector = this.element.querySelector( selector );\n  }\n  // get cell from element\n  return this.getCell( selector );\n};\n\n// -------------------------- events -------------------------- //\n\nproto.uiChange = function() {\n  this.emitEvent('uiChange');\n};\n\n// keep focus on element when child UI elements are clicked\nproto.childUIPointerDown = function( event ) {\n  // HACK iOS does not allow touch events to bubble up?!\n  if ( event.type != 'touchstart' ) {\n    event.preventDefault();\n  }\n  this.focus();\n};\n\n// ----- resize ----- //\n\nproto.onresize = function() {\n  this.watchCSS();\n  this.resize();\n};\n\nutils.debounceMethod( Flickity, 'onresize', 150 );\n\nproto.resize = function() {\n  // #1177 disable resize behavior when animating or dragging for iOS 15\n  if ( !this.isActive || this.isAnimating || this.isDragging ) {\n    return;\n  }\n  this.getSize();\n  // wrap values\n  if ( this.options.wrapAround ) {\n    this.x = utils.modulo( this.x, this.slideableWidth );\n  }\n  this.positionCells();\n  this._getWrapShiftCells();\n  this.setGallerySize();\n  this.emitEvent('resize');\n  // update selected index for group slides, instant\n  // TODO: position can be lost between groups of various numbers\n  var selectedElement = this.selectedElements && this.selectedElements[0];\n  this.selectCell( selectedElement, false, true );\n};\n\n// watches the :after property, activates/deactivates\nproto.watchCSS = function() {\n  var watchOption = this.options.watchCSS;\n  if ( !watchOption ) {\n    return;\n  }\n\n  var afterContent = getComputedStyle( this.element, ':after' ).content;\n  // activate if :after { content: 'flickity' }\n  if ( afterContent.indexOf('flickity') != -1 ) {\n    this.activate();\n  } else {\n    this.deactivate();\n  }\n};\n\n// ----- keydown ----- //\n\n// go previous/next if left/right keys pressed\nproto.onkeydown = function( event ) {\n  // only work if element is in focus\n  var isNotFocused = document.activeElement && document.activeElement != this.element;\n  if ( !this.options.accessibility || isNotFocused ) {\n    return;\n  }\n\n  var handler = Flickity.keyboardHandlers[ event.keyCode ];\n  if ( handler ) {\n    handler.call( this );\n  }\n};\n\nFlickity.keyboardHandlers = {\n  // left arrow\n  37: function() {\n    var leftMethod = this.options.rightToLeft ? 'next' : 'previous';\n    this.uiChange();\n    this[ leftMethod ]();\n  },\n  // right arrow\n  39: function() {\n    var rightMethod = this.options.rightToLeft ? 'previous' : 'next';\n    this.uiChange();\n    this[ rightMethod ]();\n  },\n};\n\n// ----- focus ----- //\n\nproto.focus = function() {\n  // TODO remove scrollTo once focus options gets more support\n  // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus ...\n  //    #Browser_compatibility\n  var prevScrollY = window.pageYOffset;\n  this.element.focus({ preventScroll: true });\n  // hack to fix scroll jump after focus, #76\n  if ( window.pageYOffset != prevScrollY ) {\n    window.scrollTo( window.pageXOffset, prevScrollY );\n  }\n};\n\n// -------------------------- destroy -------------------------- //\n\n// deactivate all Flickity functionality, but keep stuff available\nproto.deactivate = function() {\n  if ( !this.isActive ) {\n    return;\n  }\n  this.element.classList.remove('flickity-enabled');\n  this.element.classList.remove('flickity-rtl');\n  this.unselectSelectedSlide();\n  // destroy cells\n  this.cells.forEach( function( cell ) {\n    cell.destroy();\n  } );\n  this.element.removeChild( this.viewport );\n  // move child elements back into element\n  moveElements( this.slider.children, this.element );\n  if ( this.options.accessibility ) {\n    this.element.removeAttribute('tabIndex');\n    this.element.removeEventListener( 'keydown', this );\n  }\n  // set flags\n  this.isActive = false;\n  this.emitEvent('deactivate');\n};\n\nproto.destroy = function() {\n  this.deactivate();\n  window.removeEventListener( 'resize', this );\n  this.allOff();\n  this.emitEvent('destroy');\n  if ( jQuery && this.$element ) {\n    jQuery.removeData( this.element, 'flickity' );\n  }\n  delete this.element.flickityGUID;\n  delete instances[ this.guid ];\n};\n\n// -------------------------- prototype -------------------------- //\n\nutils.extend( proto, animatePrototype );\n\n// -------------------------- extras -------------------------- //\n\n/**\n * get Flickity instance from element\n * @param {[Element, String]} elem - element or selector string\n * @returns {Flickity} - Flickity instance\n */\nFlickity.data = function( elem ) {\n  elem = utils.getQueryElement( elem );\n  var id = elem && elem.flickityGUID;\n  return id && instances[ id ];\n};\n\nutils.htmlInit( Flickity, 'flickity' );\n\nif ( jQuery && jQuery.bridget ) {\n  jQuery.bridget( 'flickity', Flickity );\n}\n\n// set internal jQuery, for Webpack + jQuery v3, #478\nFlickity.setJQuery = function( jq ) {\n  jQuery = jq;\n};\n\nFlickity.Cell = Cell;\nFlickity.Slide = Slide;\n\nreturn Flickity;\n\n} ) );\n", "/*!\n * Unipointer v2.4.0\n * base class for doing one thing with pointer event\n * MIT license\n */\n\n/*jshint browser: true, undef: true, unused: true, strict: true */\n\n( function( window, factory ) {\n  // universal module definition\n  /* jshint strict: false */ /*global define, module, require */\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      'ev-emitter/ev-emitter'\n    ], function( EvEmitter ) {\n      return factory( window, EvEmitter );\n    });\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n      window,\n      require('ev-emitter')\n    );\n  } else {\n    // browser global\n    window.Unipointer = factory(\n      window,\n      window.EvEmitter\n    );\n  }\n\n}( window, function factory( window, EvEmitter ) {\n\n'use strict';\n\nfunction noop() {}\n\nfunction Unipointer() {}\n\n// inherit EvEmitter\nvar proto = Unipointer.prototype = Object.create( EvEmitter.prototype );\n\nproto.bindStartEvent = function( elem ) {\n  this._bindStartEvent( elem, true );\n};\n\nproto.unbindStartEvent = function( elem ) {\n  this._bindStartEvent( elem, false );\n};\n\n/**\n * Add or remove start event\n * @param {Boolean} isAdd - remove if falsey\n */\nproto._bindStartEvent = function( elem, isAdd ) {\n  // munge isAdd, default to true\n  isAdd = isAdd === undefined ? true : isAdd;\n  var bindMethod = isAdd ? 'addEventListener' : 'removeEventListener';\n\n  // default to mouse events\n  var startEvent = 'mousedown';\n  if ( 'ontouchstart' in window ) {\n    // HACK prefer Touch Events as you can preventDefault on touchstart to\n    // disable scroll in iOS & mobile Chrome metafizzy/flickity#1177\n    startEvent = 'touchstart';\n  } else if ( window.PointerEvent ) {\n    // Pointer Events\n    startEvent = 'pointerdown';\n  }\n  elem[ bindMethod ]( startEvent, this );\n};\n\n// trigger handler methods for events\nproto.handleEvent = function( event ) {\n  var method = 'on' + event.type;\n  if ( this[ method ] ) {\n    this[ method ]( event );\n  }\n};\n\n// returns the touch that we're keeping track of\nproto.getTouch = function( touches ) {\n  for ( var i=0; i < touches.length; i++ ) {\n    var touch = touches[i];\n    if ( touch.identifier == this.pointerIdentifier ) {\n      return touch;\n    }\n  }\n};\n\n// ----- start event ----- //\n\nproto.onmousedown = function( event ) {\n  // dismiss clicks from right or middle buttons\n  var button = event.button;\n  if ( button && ( button !== 0 && button !== 1 ) ) {\n    return;\n  }\n  this._pointerDown( event, event );\n};\n\nproto.ontouchstart = function( event ) {\n  this._pointerDown( event, event.changedTouches[0] );\n};\n\nproto.onpointerdown = function( event ) {\n  this._pointerDown( event, event );\n};\n\n/**\n * pointer start\n * @param {Event} event\n * @param {Event or Touch} pointer\n */\nproto._pointerDown = function( event, pointer ) {\n  // dismiss right click and other pointers\n  // button = 0 is okay, 1-4 not\n  if ( event.button || this.isPointerDown ) {\n    return;\n  }\n\n  this.isPointerDown = true;\n  // save pointer identifier to match up touch events\n  this.pointerIdentifier = pointer.pointerId !== undefined ?\n    // pointerId for pointer events, touch.indentifier for touch events\n    pointer.pointerId : pointer.identifier;\n\n  this.pointerDown( event, pointer );\n};\n\nproto.pointerDown = function( event, pointer ) {\n  this._bindPostStartEvents( event );\n  this.emitEvent( 'pointerDown', [ event, pointer ] );\n};\n\n// hash of events to be bound after start event\nvar postStartEvents = {\n  mousedown: [ 'mousemove', 'mouseup' ],\n  touchstart: [ 'touchmove', 'touchend', 'touchcancel' ],\n  pointerdown: [ 'pointermove', 'pointerup', 'pointercancel' ],\n};\n\nproto._bindPostStartEvents = function( event ) {\n  if ( !event ) {\n    return;\n  }\n  // get proper events to match start event\n  var events = postStartEvents[ event.type ];\n  // bind events to node\n  events.forEach( function( eventName ) {\n    window.addEventListener( eventName, this );\n  }, this );\n  // save these arguments\n  this._boundPointerEvents = events;\n};\n\nproto._unbindPostStartEvents = function() {\n  // check for _boundEvents, in case dragEnd triggered twice (old IE8 bug)\n  if ( !this._boundPointerEvents ) {\n    return;\n  }\n  this._boundPointerEvents.forEach( function( eventName ) {\n    window.removeEventListener( eventName, this );\n  }, this );\n\n  delete this._boundPointerEvents;\n};\n\n// ----- move event ----- //\n\nproto.onmousemove = function( event ) {\n  this._pointerMove( event, event );\n};\n\nproto.onpointermove = function( event ) {\n  if ( event.pointerId == this.pointerIdentifier ) {\n    this._pointerMove( event, event );\n  }\n};\n\nproto.ontouchmove = function( event ) {\n  var touch = this.getTouch( event.changedTouches );\n  if ( touch ) {\n    this._pointerMove( event, touch );\n  }\n};\n\n/**\n * pointer move\n * @param {Event} event\n * @param {Event or Touch} pointer\n * @private\n */\nproto._pointerMove = function( event, pointer ) {\n  this.pointerMove( event, pointer );\n};\n\n// public\nproto.pointerMove = function( event, pointer ) {\n  this.emitEvent( 'pointerMove', [ event, pointer ] );\n};\n\n// ----- end event ----- //\n\n\nproto.onmouseup = function( event ) {\n  this._pointerUp( event, event );\n};\n\nproto.onpointerup = function( event ) {\n  if ( event.pointerId == this.pointerIdentifier ) {\n    this._pointerUp( event, event );\n  }\n};\n\nproto.ontouchend = function( event ) {\n  var touch = this.getTouch( event.changedTouches );\n  if ( touch ) {\n    this._pointerUp( event, touch );\n  }\n};\n\n/**\n * pointer up\n * @param {Event} event\n * @param {Event or Touch} pointer\n * @private\n */\nproto._pointerUp = function( event, pointer ) {\n  this._pointerDone();\n  this.pointerUp( event, pointer );\n};\n\n// public\nproto.pointerUp = function( event, pointer ) {\n  this.emitEvent( 'pointerUp', [ event, pointer ] );\n};\n\n// ----- pointer done ----- //\n\n// triggered on pointer up & pointer cancel\nproto._pointerDone = function() {\n  this._pointerReset();\n  this._unbindPostStartEvents();\n  this.pointerDone();\n};\n\nproto._pointerReset = function() {\n  // reset properties\n  this.isPointerDown = false;\n  delete this.pointerIdentifier;\n};\n\nproto.pointerDone = noop;\n\n// ----- pointer cancel ----- //\n\nproto.onpointercancel = function( event ) {\n  if ( event.pointerId == this.pointerIdentifier ) {\n    this._pointerCancel( event, event );\n  }\n};\n\nproto.ontouchcancel = function( event ) {\n  var touch = this.getTouch( event.changedTouches );\n  if ( touch ) {\n    this._pointerCancel( event, touch );\n  }\n};\n\n/**\n * pointer cancel\n * @param {Event} event\n * @param {Event or Touch} pointer\n * @private\n */\nproto._pointerCancel = function( event, pointer ) {\n  this._pointerDone();\n  this.pointerCancel( event, pointer );\n};\n\n// public\nproto.pointerCancel = function( event, pointer ) {\n  this.emitEvent( 'pointerCancel', [ event, pointer ] );\n};\n\n// -----  ----- //\n\n// utility function for getting x/y coords from event\nUnipointer.getPointerPoint = function( pointer ) {\n  return {\n    x: pointer.pageX,\n    y: pointer.pageY\n  };\n};\n\n// -----  ----- //\n\nreturn Unipointer;\n\n}));\n", "/*!\n * Unidragger v2.4.0\n * Draggable base class\n * MIT license\n */\n\n/*jshint browser: true, unused: true, undef: true, strict: true */\n\n( function( window, factory ) {\n  // universal module definition\n  /*jshint strict: false */ /*globals define, module, require */\n\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      'unipointer/unipointer'\n    ], function( Unipointer ) {\n      return factory( window, Unipointer );\n    });\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n      window,\n      require('unipointer')\n    );\n  } else {\n    // browser global\n    window.Unidragger = factory(\n      window,\n      window.Unipointer\n    );\n  }\n\n}( window, function factory( window, Unipointer ) {\n\n'use strict';\n\n// -------------------------- Unidragger -------------------------- //\n\nfunction Unidragger() {}\n\n// inherit Unipointer & EvEmitter\nvar proto = Unidragger.prototype = Object.create( Unipointer.prototype );\n\n// ----- bind start ----- //\n\nproto.bindHandles = function() {\n  this._bindHandles( true );\n};\n\nproto.unbindHandles = function() {\n  this._bindHandles( false );\n};\n\n/**\n * Add or remove start event\n * @param {Boolean} isAdd\n */\nproto._bindHandles = function( isAdd ) {\n  // munge isAdd, default to true\n  isAdd = isAdd === undefined ? true : isAdd;\n  // bind each handle\n  var bindMethod = isAdd ? 'addEventListener' : 'removeEventListener';\n  var touchAction = isAdd ? this._touchActionValue : '';\n  for ( var i=0; i < this.handles.length; i++ ) {\n    var handle = this.handles[i];\n    this._bindStartEvent( handle, isAdd );\n    handle[ bindMethod ]( 'click', this );\n    // touch-action: none to override browser touch gestures. metafizzy/flickity#540\n    if ( window.PointerEvent ) {\n      handle.style.touchAction = touchAction;\n    }\n  }\n};\n\n// prototype so it can be overwriteable by Flickity\nproto._touchActionValue = 'none';\n\n// ----- start event ----- //\n\n/**\n * pointer start\n * @param {Event} event\n * @param {Event or Touch} pointer\n */\nproto.pointerDown = function( event, pointer ) {\n  var isOkay = this.okayPointerDown( event );\n  if ( !isOkay ) {\n    return;\n  }\n  // track start event position\n  // Safari 9 overrides pageX and pageY. These values needs to be copied. flickity#842\n  this.pointerDownPointer = {\n    pageX: pointer.pageX,\n    pageY: pointer.pageY,\n  };\n\n  event.preventDefault();\n  this.pointerDownBlur();\n  // bind move and end events\n  this._bindPostStartEvents( event );\n  this.emitEvent( 'pointerDown', [ event, pointer ] );\n};\n\n// nodes that have text fields\nvar cursorNodes = {\n  TEXTAREA: true,\n  INPUT: true,\n  SELECT: true,\n  OPTION: true,\n};\n\n// input types that do not have text fields\nvar clickTypes = {\n  radio: true,\n  checkbox: true,\n  button: true,\n  submit: true,\n  image: true,\n  file: true,\n};\n\n// dismiss inputs with text fields. flickity#403, flickity#404\nproto.okayPointerDown = function( event ) {\n  var isCursorNode = cursorNodes[ event.target.nodeName ];\n  var isClickType = clickTypes[ event.target.type ];\n  var isOkay = !isCursorNode || isClickType;\n  if ( !isOkay ) {\n    this._pointerReset();\n  }\n  return isOkay;\n};\n\n// kludge to blur previously focused input\nproto.pointerDownBlur = function() {\n  var focused = document.activeElement;\n  // do not blur body for IE10, metafizzy/flickity#117\n  var canBlur = focused && focused.blur && focused != document.body;\n  if ( canBlur ) {\n    focused.blur();\n  }\n};\n\n// ----- move event ----- //\n\n/**\n * drag move\n * @param {Event} event\n * @param {Event or Touch} pointer\n */\nproto.pointerMove = function( event, pointer ) {\n  var moveVector = this._dragPointerMove( event, pointer );\n  this.emitEvent( 'pointerMove', [ event, pointer, moveVector ] );\n  this._dragMove( event, pointer, moveVector );\n};\n\n// base pointer move logic\nproto._dragPointerMove = function( event, pointer ) {\n  var moveVector = {\n    x: pointer.pageX - this.pointerDownPointer.pageX,\n    y: pointer.pageY - this.pointerDownPointer.pageY\n  };\n  // start drag if pointer has moved far enough to start drag\n  if ( !this.isDragging && this.hasDragStarted( moveVector ) ) {\n    this._dragStart( event, pointer );\n  }\n  return moveVector;\n};\n\n// condition if pointer has moved far enough to start drag\nproto.hasDragStarted = function( moveVector ) {\n  return Math.abs( moveVector.x ) > 3 || Math.abs( moveVector.y ) > 3;\n};\n\n// ----- end event ----- //\n\n/**\n * pointer up\n * @param {Event} event\n * @param {Event or Touch} pointer\n */\nproto.pointerUp = function( event, pointer ) {\n  this.emitEvent( 'pointerUp', [ event, pointer ] );\n  this._dragPointerUp( event, pointer );\n};\n\nproto._dragPointerUp = function( event, pointer ) {\n  if ( this.isDragging ) {\n    this._dragEnd( event, pointer );\n  } else {\n    // pointer didn't move enough for drag to start\n    this._staticClick( event, pointer );\n  }\n};\n\n// -------------------------- drag -------------------------- //\n\n// dragStart\nproto._dragStart = function( event, pointer ) {\n  this.isDragging = true;\n  // prevent clicks\n  this.isPreventingClicks = true;\n  this.dragStart( event, pointer );\n};\n\nproto.dragStart = function( event, pointer ) {\n  this.emitEvent( 'dragStart', [ event, pointer ] );\n};\n\n// dragMove\nproto._dragMove = function( event, pointer, moveVector ) {\n  // do not drag if not dragging yet\n  if ( !this.isDragging ) {\n    return;\n  }\n\n  this.dragMove( event, pointer, moveVector );\n};\n\nproto.dragMove = function( event, pointer, moveVector ) {\n  event.preventDefault();\n  this.emitEvent( 'dragMove', [ event, pointer, moveVector ] );\n};\n\n// dragEnd\nproto._dragEnd = function( event, pointer ) {\n  // set flags\n  this.isDragging = false;\n  // re-enable clicking async\n  setTimeout( function() {\n    delete this.isPreventingClicks;\n  }.bind( this ) );\n\n  this.dragEnd( event, pointer );\n};\n\nproto.dragEnd = function( event, pointer ) {\n  this.emitEvent( 'dragEnd', [ event, pointer ] );\n};\n\n// ----- onclick ----- //\n\n// handle all clicks and prevent clicks when dragging\nproto.onclick = function( event ) {\n  if ( this.isPreventingClicks ) {\n    event.preventDefault();\n  }\n};\n\n// ----- staticClick ----- //\n\n// triggered after pointer down & up with no/tiny movement\nproto._staticClick = function( event, pointer ) {\n  // ignore emulated mouse up clicks\n  if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) {\n    return;\n  }\n\n  this.staticClick( event, pointer );\n\n  // set flag for emulated clicks 300ms after touchend\n  if ( event.type != 'mouseup' ) {\n    this.isIgnoringMouseUp = true;\n    // reset flag after 300ms\n    setTimeout( function() {\n      delete this.isIgnoringMouseUp;\n    }.bind( this ), 400 );\n  }\n};\n\nproto.staticClick = function( event, pointer ) {\n  this.emitEvent( 'staticClick', [ event, pointer ] );\n};\n\n// ----- utils ----- //\n\nUnidragger.getPointerPoint = Unipointer.getPointerPoint;\n\n// -----  ----- //\n\nreturn Unidragger;\n\n}));\n", "// drag\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      './flickity',\n      'unidragger/unidragger',\n      'fizzy-ui-utils/utils',\n    ], function( Flickity, Unidragger, utils ) {\n      return factory( window, Flickity, Unidragger, utils );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('./flickity'),\n        require('unidragger'),\n        require('fizzy-ui-utils')\n    );\n  } else {\n    // browser global\n    window.Flickity = factory(\n        window,\n        window.Flickity,\n        window.Unidragger,\n        window.fizzyUIUtils\n    );\n  }\n\n}( window, function factory( window, Flickity, Unidragger, utils ) {\n\n'use strict';\n\n// ----- defaults ----- //\n\nutils.extend( Flickity.defaults, {\n  draggable: '>1',\n  dragThreshold: 3,\n} );\n\n// ----- create ----- //\n\nFlickity.createMethods.push('_createDrag');\n\n// -------------------------- drag prototype -------------------------- //\n\nvar proto = Flickity.prototype;\nutils.extend( proto, Unidragger.prototype );\nproto._touchActionValue = 'pan-y';\n\n// --------------------------  -------------------------- //\n\nproto._createDrag = function() {\n  this.on( 'activate', this.onActivateDrag );\n  this.on( 'uiChange', this._uiChangeDrag );\n  this.on( 'deactivate', this.onDeactivateDrag );\n  this.on( 'cellChange', this.updateDraggable );\n  // TODO updateDraggable on resize? if groupCells & slides change\n};\n\nproto.onActivateDrag = function() {\n  this.handles = [ this.viewport ];\n  this.bindHandles();\n  this.updateDraggable();\n};\n\nproto.onDeactivateDrag = function() {\n  this.unbindHandles();\n  this.element.classList.remove('is-draggable');\n};\n\nproto.updateDraggable = function() {\n  // disable dragging if less than 2 slides. #278\n  if ( this.options.draggable == '>1' ) {\n    this.isDraggable = this.slides.length > 1;\n  } else {\n    this.isDraggable = this.options.draggable;\n  }\n  if ( this.isDraggable ) {\n    this.element.classList.add('is-draggable');\n  } else {\n    this.element.classList.remove('is-draggable');\n  }\n};\n\n// backwards compatibility\nproto.bindDrag = function() {\n  this.options.draggable = true;\n  this.updateDraggable();\n};\n\nproto.unbindDrag = function() {\n  this.options.draggable = false;\n  this.updateDraggable();\n};\n\nproto._uiChangeDrag = function() {\n  delete this.isFreeScrolling;\n};\n\n// -------------------------- pointer events -------------------------- //\n\nproto.pointerDown = function( event, pointer ) {\n  if ( !this.isDraggable ) {\n    this._pointerDownDefault( event, pointer );\n    return;\n  }\n  var isOkay = this.okayPointerDown( event );\n  if ( !isOkay ) {\n    return;\n  }\n\n  this._pointerDownPreventDefault( event );\n  this.pointerDownFocus( event );\n  // blur\n  if ( document.activeElement != this.element ) {\n    // do not blur if already focused\n    this.pointerDownBlur();\n  }\n\n  // stop if it was moving\n  this.dragX = this.x;\n  this.viewport.classList.add('is-pointer-down');\n  // track scrolling\n  this.pointerDownScroll = getScrollPosition();\n  window.addEventListener( 'scroll', this );\n\n  this._pointerDownDefault( event, pointer );\n};\n\n// default pointerDown logic, used for staticClick\nproto._pointerDownDefault = function( event, pointer ) {\n  // track start event position\n  // Safari 9 overrides pageX and pageY. These values needs to be copied. #779\n  this.pointerDownPointer = {\n    pageX: pointer.pageX,\n    pageY: pointer.pageY,\n  };\n  // bind move and end events\n  this._bindPostStartEvents( event );\n  this.dispatchEvent( 'pointerDown', event, [ pointer ] );\n};\n\nvar focusNodes = {\n  INPUT: true,\n  TEXTAREA: true,\n  SELECT: true,\n};\n\nproto.pointerDownFocus = function( event ) {\n  var isFocusNode = focusNodes[ event.target.nodeName ];\n  if ( !isFocusNode ) {\n    this.focus();\n  }\n};\n\nproto._pointerDownPreventDefault = function( event ) {\n  var isTouchStart = event.type == 'touchstart';\n  var isTouchPointer = event.pointerType == 'touch';\n  var isFocusNode = focusNodes[ event.target.nodeName ];\n  if ( !isTouchStart && !isTouchPointer && !isFocusNode ) {\n    event.preventDefault();\n  }\n};\n\n// ----- move ----- //\n\nproto.hasDragStarted = function( moveVector ) {\n  return Math.abs( moveVector.x ) > this.options.dragThreshold;\n};\n\n// ----- up ----- //\n\nproto.pointerUp = function( event, pointer ) {\n  delete this.isTouchScrolling;\n  this.viewport.classList.remove('is-pointer-down');\n  this.dispatchEvent( 'pointerUp', event, [ pointer ] );\n  this._dragPointerUp( event, pointer );\n};\n\nproto.pointerDone = function() {\n  window.removeEventListener( 'scroll', this );\n  delete this.pointerDownScroll;\n};\n\n// -------------------------- dragging -------------------------- //\n\nproto.dragStart = function( event, pointer ) {\n  if ( !this.isDraggable ) {\n    return;\n  }\n  this.dragStartPosition = this.x;\n  this.startAnimation();\n  window.removeEventListener( 'scroll', this );\n  this.dispatchEvent( 'dragStart', event, [ pointer ] );\n};\n\nproto.pointerMove = function( event, pointer ) {\n  var moveVector = this._dragPointerMove( event, pointer );\n  this.dispatchEvent( 'pointerMove', event, [ pointer, moveVector ] );\n  this._dragMove( event, pointer, moveVector );\n};\n\nproto.dragMove = function( event, pointer, moveVector ) {\n  if ( !this.isDraggable ) {\n    return;\n  }\n  event.preventDefault();\n\n  this.previousDragX = this.dragX;\n  // reverse if right-to-left\n  var direction = this.options.rightToLeft ? -1 : 1;\n  if ( this.options.wrapAround ) {\n    // wrap around move. #589\n    moveVector.x %= this.slideableWidth;\n  }\n  var dragX = this.dragStartPosition + moveVector.x * direction;\n\n  if ( !this.options.wrapAround && this.slides.length ) {\n    // slow drag\n    var originBound = Math.max( -this.slides[0].target, this.dragStartPosition );\n    dragX = dragX > originBound ? ( dragX + originBound ) * 0.5 : dragX;\n    var endBound = Math.min( -this.getLastSlide().target, this.dragStartPosition );\n    dragX = dragX < endBound ? ( dragX + endBound ) * 0.5 : dragX;\n  }\n\n  this.dragX = dragX;\n\n  this.dragMoveTime = new Date();\n  this.dispatchEvent( 'dragMove', event, [ pointer, moveVector ] );\n};\n\nproto.dragEnd = function( event, pointer ) {\n  if ( !this.isDraggable ) {\n    return;\n  }\n  if ( this.options.freeScroll ) {\n    this.isFreeScrolling = true;\n  }\n  // set selectedIndex based on where flick will end up\n  var index = this.dragEndRestingSelect();\n\n  if ( this.options.freeScroll && !this.options.wrapAround ) {\n    // if free-scroll & not wrap around\n    // do not free-scroll if going outside of bounding slides\n    // so bounding slides can attract slider, and keep it in bounds\n    var restingX = this.getRestingPosition();\n    this.isFreeScrolling = -restingX > this.slides[0].target &&\n      -restingX < this.getLastSlide().target;\n  } else if ( !this.options.freeScroll && index == this.selectedIndex ) {\n    // boost selection if selected index has not changed\n    index += this.dragEndBoostSelect();\n  }\n  delete this.previousDragX;\n  // apply selection\n  // TODO refactor this, selecting here feels weird\n  // HACK, set flag so dragging stays in correct direction\n  this.isDragSelect = this.options.wrapAround;\n  this.select( index );\n  delete this.isDragSelect;\n  this.dispatchEvent( 'dragEnd', event, [ pointer ] );\n};\n\nproto.dragEndRestingSelect = function() {\n  var restingX = this.getRestingPosition();\n  // how far away from selected slide\n  var distance = Math.abs( this.getSlideDistance( -restingX, this.selectedIndex ) );\n  // get closet resting going up and going down\n  var positiveResting = this._getClosestResting( restingX, distance, 1 );\n  var negativeResting = this._getClosestResting( restingX, distance, -1 );\n  // use closer resting for wrap-around\n  var index = positiveResting.distance < negativeResting.distance ?\n    positiveResting.index : negativeResting.index;\n  return index;\n};\n\n/**\n * given resting X and distance to selected cell\n * get the distance and index of the closest cell\n * @param {Number} restingX - estimated post-flick resting position\n * @param {Number} distance - distance to selected cell\n * @param {Integer} increment - +1 or -1, going up or down\n * @returns {Object} - { distance: {Number}, index: {Integer} }\n */\nproto._getClosestResting = function( restingX, distance, increment ) {\n  var index = this.selectedIndex;\n  var minDistance = Infinity;\n  var condition = this.options.contain && !this.options.wrapAround ?\n    // if contain, keep going if distance is equal to minDistance\n    function( dist, minDist ) {\n      return dist <= minDist;\n    } : function( dist, minDist ) {\n      return dist < minDist;\n    };\n  while ( condition( distance, minDistance ) ) {\n    // measure distance to next cell\n    index += increment;\n    minDistance = distance;\n    distance = this.getSlideDistance( -restingX, index );\n    if ( distance === null ) {\n      break;\n    }\n    distance = Math.abs( distance );\n  }\n  return {\n    distance: minDistance,\n    // selected was previous index\n    index: index - increment,\n  };\n};\n\n/**\n * measure distance between x and a slide target\n * @param {Number} x - horizontal position\n * @param {Integer} index - slide index\n * @returns {Number} - slide distance\n */\nproto.getSlideDistance = function( x, index ) {\n  var len = this.slides.length;\n  // wrap around if at least 2 slides\n  var isWrapAround = this.options.wrapAround && len > 1;\n  var slideIndex = isWrapAround ? utils.modulo( index, len ) : index;\n  var slide = this.slides[ slideIndex ];\n  if ( !slide ) {\n    return null;\n  }\n  // add distance for wrap-around slides\n  var wrap = isWrapAround ? this.slideableWidth * Math.floor( index/len ) : 0;\n  return x - ( slide.target + wrap );\n};\n\nproto.dragEndBoostSelect = function() {\n  // do not boost if no previousDragX or dragMoveTime\n  if ( this.previousDragX === undefined || !this.dragMoveTime ||\n    // or if drag was held for 100 ms\n    new Date() - this.dragMoveTime > 100 ) {\n    return 0;\n  }\n\n  var distance = this.getSlideDistance( -this.dragX, this.selectedIndex );\n  var delta = this.previousDragX - this.dragX;\n  if ( distance > 0 && delta > 0 ) {\n    // boost to next if moving towards the right, and positive velocity\n    return 1;\n  } else if ( distance < 0 && delta < 0 ) {\n    // boost to previous if moving towards the left, and negative velocity\n    return -1;\n  }\n  return 0;\n};\n\n// ----- staticClick ----- //\n\nproto.staticClick = function( event, pointer ) {\n  // get clickedCell, if cell was clicked\n  var clickedCell = this.getParentCell( event.target );\n  var cellElem = clickedCell && clickedCell.element;\n  var cellIndex = clickedCell && this.cells.indexOf( clickedCell );\n  this.dispatchEvent( 'staticClick', event, [ pointer, cellElem, cellIndex ] );\n};\n\n// ----- scroll ----- //\n\nproto.onscroll = function() {\n  var scroll = getScrollPosition();\n  var scrollMoveX = this.pointerDownScroll.x - scroll.x;\n  var scrollMoveY = this.pointerDownScroll.y - scroll.y;\n  // cancel click/tap if scroll is too much\n  if ( Math.abs( scrollMoveX ) > 3 || Math.abs( scrollMoveY ) > 3 ) {\n    this._pointerDone();\n  }\n};\n\n// ----- utils ----- //\n\nfunction getScrollPosition() {\n  return {\n    x: window.pageXOffset,\n    y: window.pageYOffset,\n  };\n}\n\n// -----  ----- //\n\nreturn Flickity;\n\n} ) );\n", "// prev/next buttons\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      './flickity',\n      'unipointer/unipointer',\n      'fizzy-ui-utils/utils',\n    ], function( Flickity, Unipointer, utils ) {\n      return factory( window, Flickity, Unipointer, utils );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('./flickity'),\n        require('unipointer'),\n        require('fizzy-ui-utils')\n    );\n  } else {\n    // browser global\n    factory(\n        window,\n        window.Flickity,\n        window.Unipointer,\n        window.fizzyUIUtils\n    );\n  }\n\n}( window, function factory( window, Flickity, Unipointer, utils ) {\n'use strict';\n\nvar svgURI = 'http://www.w3.org/2000/svg';\n\n// -------------------------- PrevNextButton -------------------------- //\n\nfunction PrevNextButton( direction, parent ) {\n  this.direction = direction;\n  this.parent = parent;\n  this._create();\n}\n\nPrevNextButton.prototype = Object.create( Unipointer.prototype );\n\nPrevNextButton.prototype._create = function() {\n  // properties\n  this.isEnabled = true;\n  this.isPrevious = this.direction == -1;\n  var leftDirection = this.parent.options.rightToLeft ? 1 : -1;\n  this.isLeft = this.direction == leftDirection;\n\n  var element = this.element = document.createElement('button');\n  element.className = 'flickity-button flickity-prev-next-button';\n  element.className += this.isPrevious ? ' previous' : ' next';\n  // prevent button from submitting form http://stackoverflow.com/a/10836076/182183\n  element.setAttribute( 'type', 'button' );\n  // init as disabled\n  this.disable();\n\n  element.setAttribute( 'aria-label', this.isPrevious ? 'Previous' : 'Next' );\n\n  // create arrow\n  var svg = this.createSVG();\n  element.appendChild( svg );\n  // events\n  this.parent.on( 'select', this.update.bind( this ) );\n  this.on( 'pointerDown', this.parent.childUIPointerDown.bind( this.parent ) );\n};\n\nPrevNextButton.prototype.activate = function() {\n  this.bindStartEvent( this.element );\n  this.element.addEventListener( 'click', this );\n  // add to DOM\n  this.parent.element.appendChild( this.element );\n};\n\nPrevNextButton.prototype.deactivate = function() {\n  // remove from DOM\n  this.parent.element.removeChild( this.element );\n  // click events\n  this.unbindStartEvent( this.element );\n  this.element.removeEventListener( 'click', this );\n};\n\nPrevNextButton.prototype.createSVG = function() {\n  var svg = document.createElementNS( svgURI, 'svg' );\n  svg.setAttribute( 'class', 'flickity-button-icon' );\n  svg.setAttribute( 'viewBox', '0 0 100 100' );\n  var path = document.createElementNS( svgURI, 'path' );\n  var pathMovements = getArrowMovements( this.parent.options.arrowShape );\n  path.setAttribute( 'd', pathMovements );\n  path.setAttribute( 'class', 'arrow' );\n  // rotate arrow\n  if ( !this.isLeft ) {\n    path.setAttribute( 'transform', 'translate(100, 100) rotate(180) ' );\n  }\n  svg.appendChild( path );\n  return svg;\n};\n\n// get SVG path movmement\nfunction getArrowMovements( shape ) {\n  // use shape as movement if string\n  if ( typeof shape == 'string' ) {\n    return shape;\n  }\n  // create movement string\n  return 'M ' + shape.x0 + ',50' +\n    ' L ' + shape.x1 + ',' + ( shape.y1 + 50 ) +\n    ' L ' + shape.x2 + ',' + ( shape.y2 + 50 ) +\n    ' L ' + shape.x3 + ',50 ' +\n    ' L ' + shape.x2 + ',' + ( 50 - shape.y2 ) +\n    ' L ' + shape.x1 + ',' + ( 50 - shape.y1 ) +\n    ' Z';\n}\n\nPrevNextButton.prototype.handleEvent = utils.handleEvent;\n\nPrevNextButton.prototype.onclick = function() {\n  if ( !this.isEnabled ) {\n    return;\n  }\n  this.parent.uiChange();\n  var method = this.isPrevious ? 'previous' : 'next';\n  this.parent[ method ]();\n};\n\n// -----  ----- //\n\nPrevNextButton.prototype.enable = function() {\n  if ( this.isEnabled ) {\n    return;\n  }\n  this.element.disabled = false;\n  this.isEnabled = true;\n};\n\nPrevNextButton.prototype.disable = function() {\n  if ( !this.isEnabled ) {\n    return;\n  }\n  this.element.disabled = true;\n  this.isEnabled = false;\n};\n\nPrevNextButton.prototype.update = function() {\n  // index of first or last slide, if previous or next\n  var slides = this.parent.slides;\n  // enable is wrapAround and at least 2 slides\n  if ( this.parent.options.wrapAround && slides.length > 1 ) {\n    this.enable();\n    return;\n  }\n  var lastIndex = slides.length ? slides.length - 1 : 0;\n  var boundIndex = this.isPrevious ? 0 : lastIndex;\n  var method = this.parent.selectedIndex == boundIndex ? 'disable' : 'enable';\n  this[ method ]();\n};\n\nPrevNextButton.prototype.destroy = function() {\n  this.deactivate();\n  this.allOff();\n};\n\n// -------------------------- Flickity prototype -------------------------- //\n\nutils.extend( Flickity.defaults, {\n  prevNextButtons: true,\n  arrowShape: {\n    x0: 10,\n    x1: 60, y1: 50,\n    x2: 70, y2: 40,\n    x3: 30,\n  },\n} );\n\nFlickity.createMethods.push('_createPrevNextButtons');\nvar proto = Flickity.prototype;\n\nproto._createPrevNextButtons = function() {\n  if ( !this.options.prevNextButtons ) {\n    return;\n  }\n\n  this.prevButton = new PrevNextButton( -1, this );\n  this.nextButton = new PrevNextButton( 1, this );\n\n  this.on( 'activate', this.activatePrevNextButtons );\n};\n\nproto.activatePrevNextButtons = function() {\n  this.prevButton.activate();\n  this.nextButton.activate();\n  this.on( 'deactivate', this.deactivatePrevNextButtons );\n};\n\nproto.deactivatePrevNextButtons = function() {\n  this.prevButton.deactivate();\n  this.nextButton.deactivate();\n  this.off( 'deactivate', this.deactivatePrevNextButtons );\n};\n\n// --------------------------  -------------------------- //\n\nFlickity.PrevNextButton = PrevNextButton;\n\nreturn Flickity;\n\n} ) );\n", "// page dots\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      './flickity',\n      'unipointer/unipointer',\n      'fizzy-ui-utils/utils',\n    ], function( Flickity, Unipointer, utils ) {\n      return factory( window, Flickity, Unipointer, utils );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('./flickity'),\n        require('unipointer'),\n        require('fizzy-ui-utils')\n    );\n  } else {\n    // browser global\n    factory(\n        window,\n        window.Flickity,\n        window.Unipointer,\n        window.fizzyUIUtils\n    );\n  }\n\n}( window, function factory( window, Flickity, Unipointer, utils ) {\n\n// -------------------------- PageDots -------------------------- //\n\n'use strict';\n\nfunction PageDots( parent ) {\n  this.parent = parent;\n  this._create();\n}\n\nPageDots.prototype = Object.create( Unipointer.prototype );\n\nPageDots.prototype._create = function() {\n  // create holder element\n  this.holder = document.createElement('ol');\n  this.holder.className = 'flickity-page-dots';\n  // create dots, array of elements\n  this.dots = [];\n  // events\n  this.handleClick = this.onClick.bind( this );\n  this.on( 'pointerDown', this.parent.childUIPointerDown.bind( this.parent ) );\n};\n\nPageDots.prototype.activate = function() {\n  this.setDots();\n  this.holder.addEventListener( 'click', this.handleClick );\n  this.bindStartEvent( this.holder );\n  // add to DOM\n  this.parent.element.appendChild( this.holder );\n};\n\nPageDots.prototype.deactivate = function() {\n  this.holder.removeEventListener( 'click', this.handleClick );\n  this.unbindStartEvent( this.holder );\n  // remove from DOM\n  this.parent.element.removeChild( this.holder );\n};\n\nPageDots.prototype.setDots = function() {\n  // get difference between number of slides and number of dots\n  var delta = this.parent.slides.length - this.dots.length;\n  if ( delta > 0 ) {\n    this.addDots( delta );\n  } else if ( delta < 0 ) {\n    this.removeDots( -delta );\n  }\n};\n\nPageDots.prototype.addDots = function( count ) {\n  var fragment = document.createDocumentFragment();\n  var newDots = [];\n  var length = this.dots.length;\n  var max = length + count;\n\n  for ( var i = length; i < max; i++ ) {\n    var dot = document.createElement('li');\n    dot.className = 'dot';\n    dot.setAttribute( 'aria-label', 'Page dot ' + ( i + 1 ) );\n    fragment.appendChild( dot );\n    newDots.push( dot );\n  }\n\n  this.holder.appendChild( fragment );\n  this.dots = this.dots.concat( newDots );\n};\n\nPageDots.prototype.removeDots = function( count ) {\n  // remove from this.dots collection\n  var removeDots = this.dots.splice( this.dots.length - count, count );\n  // remove from DOM\n  removeDots.forEach( function( dot ) {\n    this.holder.removeChild( dot );\n  }, this );\n};\n\nPageDots.prototype.updateSelected = function() {\n  // remove selected class on previous\n  if ( this.selectedDot ) {\n    this.selectedDot.className = 'dot';\n    this.selectedDot.removeAttribute('aria-current');\n  }\n  // don't proceed if no dots\n  if ( !this.dots.length ) {\n    return;\n  }\n  this.selectedDot = this.dots[ this.parent.selectedIndex ];\n  this.selectedDot.className = 'dot is-selected';\n  this.selectedDot.setAttribute( 'aria-current', 'step' );\n};\n\nPageDots.prototype.onTap = // old method name, backwards-compatible\nPageDots.prototype.onClick = function( event ) {\n  var target = event.target;\n  // only care about dot clicks\n  if ( target.nodeName != 'LI' ) {\n    return;\n  }\n\n  this.parent.uiChange();\n  var index = this.dots.indexOf( target );\n  this.parent.select( index );\n};\n\nPageDots.prototype.destroy = function() {\n  this.deactivate();\n  this.allOff();\n};\n\nFlickity.PageDots = PageDots;\n\n// -------------------------- Flickity -------------------------- //\n\nutils.extend( Flickity.defaults, {\n  pageDots: true,\n} );\n\nFlickity.createMethods.push('_createPageDots');\n\nvar proto = Flickity.prototype;\n\nproto._createPageDots = function() {\n  if ( !this.options.pageDots ) {\n    return;\n  }\n  this.pageDots = new PageDots( this );\n  // events\n  this.on( 'activate', this.activatePageDots );\n  this.on( 'select', this.updateSelectedPageDots );\n  this.on( 'cellChange', this.updatePageDots );\n  this.on( 'resize', this.updatePageDots );\n  this.on( 'deactivate', this.deactivatePageDots );\n};\n\nproto.activatePageDots = function() {\n  this.pageDots.activate();\n};\n\nproto.updateSelectedPageDots = function() {\n  this.pageDots.updateSelected();\n};\n\nproto.updatePageDots = function() {\n  this.pageDots.setDots();\n};\n\nproto.deactivatePageDots = function() {\n  this.pageDots.deactivate();\n};\n\n// -----  ----- //\n\nFlickity.PageDots = PageDots;\n\nreturn Flickity;\n\n} ) );\n", "// player & autoPlay\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      'ev-emitter/ev-emitter',\n      'fizzy-ui-utils/utils',\n      './flickity',\n    ], function( EvEmitter, utils, Flickity ) {\n      return factory( EvEmitter, utils, Flickity );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        require('ev-emitter'),\n        require('fizzy-ui-utils'),\n        require('./flickity')\n    );\n  } else {\n    // browser global\n    factory(\n        window.EvEmitter,\n        window.fizzyUIUtils,\n        window.Flickity\n    );\n  }\n\n}( window, function factory( EvEmitter, utils, Flickity ) {\n\n'use strict';\n\n// -------------------------- Player -------------------------- //\n\nfunction Player( parent ) {\n  this.parent = parent;\n  this.state = 'stopped';\n  // visibility change event handler\n  this.onVisibilityChange = this.visibilityChange.bind( this );\n  this.onVisibilityPlay = this.visibilityPlay.bind( this );\n}\n\nPlayer.prototype = Object.create( EvEmitter.prototype );\n\n// start play\nPlayer.prototype.play = function() {\n  if ( this.state == 'playing' ) {\n    return;\n  }\n  // do not play if page is hidden, start playing when page is visible\n  var isPageHidden = document.hidden;\n  if ( isPageHidden ) {\n    document.addEventListener( 'visibilitychange', this.onVisibilityPlay );\n    return;\n  }\n\n  this.state = 'playing';\n  // listen to visibility change\n  document.addEventListener( 'visibilitychange', this.onVisibilityChange );\n  // start ticking\n  this.tick();\n};\n\nPlayer.prototype.tick = function() {\n  // do not tick if not playing\n  if ( this.state != 'playing' ) {\n    return;\n  }\n\n  var time = this.parent.options.autoPlay;\n  // default to 3 seconds\n  time = typeof time == 'number' ? time : 3000;\n  var _this = this;\n  // HACK: reset ticks if stopped and started within interval\n  this.clear();\n  this.timeout = setTimeout( function() {\n    _this.parent.next( true );\n    _this.tick();\n  }, time );\n};\n\nPlayer.prototype.stop = function() {\n  this.state = 'stopped';\n  this.clear();\n  // remove visibility change event\n  document.removeEventListener( 'visibilitychange', this.onVisibilityChange );\n};\n\nPlayer.prototype.clear = function() {\n  clearTimeout( this.timeout );\n};\n\nPlayer.prototype.pause = function() {\n  if ( this.state == 'playing' ) {\n    this.state = 'paused';\n    this.clear();\n  }\n};\n\nPlayer.prototype.unpause = function() {\n  // re-start play if paused\n  if ( this.state == 'paused' ) {\n    this.play();\n  }\n};\n\n// pause if page visibility is hidden, unpause if visible\nPlayer.prototype.visibilityChange = function() {\n  var isPageHidden = document.hidden;\n  this[ isPageHidden ? 'pause' : 'unpause' ]();\n};\n\nPlayer.prototype.visibilityPlay = function() {\n  this.play();\n  document.removeEventListener( 'visibilitychange', this.onVisibilityPlay );\n};\n\n// -------------------------- Flickity -------------------------- //\n\nutils.extend( Flickity.defaults, {\n  pauseAutoPlayOnHover: true,\n} );\n\nFlickity.createMethods.push('_createPlayer');\nvar proto = Flickity.prototype;\n\nproto._createPlayer = function() {\n  this.player = new Player( this );\n\n  this.on( 'activate', this.activatePlayer );\n  this.on( 'uiChange', this.stopPlayer );\n  this.on( 'pointerDown', this.stopPlayer );\n  this.on( 'deactivate', this.deactivatePlayer );\n};\n\nproto.activatePlayer = function() {\n  if ( !this.options.autoPlay ) {\n    return;\n  }\n  this.player.play();\n  this.element.addEventListener( 'mouseenter', this );\n};\n\n// Player API, don't hate the ... thanks I know where the door is\n\nproto.playPlayer = function() {\n  this.player.play();\n};\n\nproto.stopPlayer = function() {\n  this.player.stop();\n};\n\nproto.pausePlayer = function() {\n  this.player.pause();\n};\n\nproto.unpausePlayer = function() {\n  this.player.unpause();\n};\n\nproto.deactivatePlayer = function() {\n  this.player.stop();\n  this.element.removeEventListener( 'mouseenter', this );\n};\n\n// ----- mouseenter/leave ----- //\n\n// pause auto-play on hover\nproto.onmouseenter = function() {\n  if ( !this.options.pauseAutoPlayOnHover ) {\n    return;\n  }\n  this.player.pause();\n  this.element.addEventListener( 'mouseleave', this );\n};\n\n// resume auto-play on hover off\nproto.onmouseleave = function() {\n  this.player.unpause();\n  this.element.removeEventListener( 'mouseleave', this );\n};\n\n// -----  ----- //\n\nFlickity.Player = Player;\n\nreturn Flickity;\n\n} ) );\n", "// add, remove cell\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      './flickity',\n      'fizzy-ui-utils/utils',\n    ], function( Flickity, utils ) {\n      return factory( window, Flickity, utils );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('./flickity'),\n        require('fizzy-ui-utils')\n    );\n  } else {\n    // browser global\n    factory(\n        window,\n        window.Flickity,\n        window.fizzyUIUtils\n    );\n  }\n\n}( window, function factory( window, Flickity, utils ) {\n\n'use strict';\n\n// append cells to a document fragment\nfunction getCellsFragment( cells ) {\n  var fragment = document.createDocumentFragment();\n  cells.forEach( function( cell ) {\n    fragment.appendChild( cell.element );\n  } );\n  return fragment;\n}\n\n// -------------------------- add/remove cell prototype -------------------------- //\n\nvar proto = Flickity.prototype;\n\n/**\n * Insert, prepend, or append cells\n * @param {[Element, Array, NodeList]} elems - Elements to insert\n * @param {Integer} index - Zero-based number to insert\n */\nproto.insert = function( elems, index ) {\n  var cells = this._makeCells( elems );\n  if ( !cells || !cells.length ) {\n    return;\n  }\n  var len = this.cells.length;\n  // default to append\n  index = index === undefined ? len : index;\n  // add cells with document fragment\n  var fragment = getCellsFragment( cells );\n  // append to slider\n  var isAppend = index == len;\n  if ( isAppend ) {\n    this.slider.appendChild( fragment );\n  } else {\n    var insertCellElement = this.cells[ index ].element;\n    this.slider.insertBefore( fragment, insertCellElement );\n  }\n  // add to this.cells\n  if ( index === 0 ) {\n    // prepend, add to start\n    this.cells = cells.concat( this.cells );\n  } else if ( isAppend ) {\n    // append, add to end\n    this.cells = this.cells.concat( cells );\n  } else {\n    // insert in this.cells\n    var endCells = this.cells.splice( index, len - index );\n    this.cells = this.cells.concat( cells ).concat( endCells );\n  }\n\n  this._sizeCells( cells );\n  this.cellChange( index, true );\n};\n\nproto.append = function( elems ) {\n  this.insert( elems, this.cells.length );\n};\n\nproto.prepend = function( elems ) {\n  this.insert( elems, 0 );\n};\n\n/**\n * Remove cells\n * @param {[Element, Array, NodeList]} elems - ELements to remove\n */\nproto.remove = function( elems ) {\n  var cells = this.getCells( elems );\n  if ( !cells || !cells.length ) {\n    return;\n  }\n\n  var minCellIndex = this.cells.length - 1;\n  // remove cells from collection & DOM\n  cells.forEach( function( cell ) {\n    cell.remove();\n    var index = this.cells.indexOf( cell );\n    minCellIndex = Math.min( index, minCellIndex );\n    utils.removeFrom( this.cells, cell );\n  }, this );\n\n  this.cellChange( minCellIndex, true );\n};\n\n/**\n * logic to be run after a cell's size changes\n * @param {Element} elem - cell's element\n */\nproto.cellSizeChange = function( elem ) {\n  var cell = this.getCell( elem );\n  if ( !cell ) {\n    return;\n  }\n  cell.getSize();\n\n  var index = this.cells.indexOf( cell );\n  this.cellChange( index );\n};\n\n/**\n * logic any time a cell is changed: added, removed, or size changed\n * @param {Integer} changedCellIndex - index of the changed cell, optional\n * @param {Boolean} isPositioningSlider - Positions slider after selection\n */\nproto.cellChange = function( changedCellIndex, isPositioningSlider ) {\n  var prevSelectedElem = this.selectedElement;\n  this._positionCells( changedCellIndex );\n  this._getWrapShiftCells();\n  this.setGallerySize();\n  // update selectedIndex\n  // try to maintain position & select previous selected element\n  var cell = this.getCell( prevSelectedElem );\n  if ( cell ) {\n    this.selectedIndex = this.getCellSlideIndex( cell );\n  }\n  this.selectedIndex = Math.min( this.slides.length - 1, this.selectedIndex );\n\n  this.emitEvent( 'cellChange', [ changedCellIndex ] );\n  // position slider\n  this.select( this.selectedIndex );\n  // do not position slider after lazy load\n  if ( isPositioningSlider ) {\n    this.positionSliderAtSelected();\n  }\n};\n\n// -----  ----- //\n\nreturn Flickity;\n\n} ) );\n", "// lazyload\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      './flickity',\n      'fizzy-ui-utils/utils',\n    ], function( Flickity, utils ) {\n      return factory( window, Flickity, utils );\n    } );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        window,\n        require('./flickity'),\n        require('fizzy-ui-utils')\n    );\n  } else {\n    // browser global\n    factory(\n        window,\n        window.Flickity,\n        window.fizzyUIUtils\n    );\n  }\n\n}( window, function factory( window, Flickity, utils ) {\n'use strict';\n\nFlickity.createMethods.push('_createLazyload');\nvar proto = Flickity.prototype;\n\nproto._createLazyload = function() {\n  this.on( 'select', this.lazyLoad );\n};\n\nproto.lazyLoad = function() {\n  var lazyLoad = this.options.lazyLoad;\n  if ( !lazyLoad ) {\n    return;\n  }\n  // get adjacent cells, use lazyLoad option for adjacent count\n  var adjCount = typeof lazyLoad == 'number' ? lazyLoad : 0;\n  var cellElems = this.getAdjacentCellElements( adjCount );\n  // get lazy images in those cells\n  var lazyImages = [];\n  cellElems.forEach( function( cellElem ) {\n    var lazyCellImages = getCellLazyImages( cellElem );\n    lazyImages = lazyImages.concat( lazyCellImages );\n  } );\n  // load lazy images\n  lazyImages.forEach( function( img ) {\n    new LazyLoader( img, this );\n  }, this );\n};\n\nfunction getCellLazyImages( cellElem ) {\n  // check if cell element is lazy image\n  if ( cellElem.nodeName == 'IMG' ) {\n    var lazyloadAttr = cellElem.getAttribute('data-flickity-lazyload');\n    var srcAttr = cellElem.getAttribute('data-flickity-lazyload-src');\n    var srcsetAttr = cellElem.getAttribute('data-flickity-lazyload-srcset');\n    if ( lazyloadAttr || srcAttr || srcsetAttr ) {\n      return [ cellElem ];\n    }\n  }\n  // select lazy images in cell\n  var lazySelector = 'img[data-flickity-lazyload], ' +\n    'img[data-flickity-lazyload-src], img[data-flickity-lazyload-srcset]';\n  var imgs = cellElem.querySelectorAll( lazySelector );\n  return utils.makeArray( imgs );\n}\n\n// -------------------------- LazyLoader -------------------------- //\n\n/**\n * class to handle loading images\n * @param {Image} img - Image element\n * @param {Flickity} flickity - Flickity instance\n */\nfunction LazyLoader( img, flickity ) {\n  this.img = img;\n  this.flickity = flickity;\n  this.load();\n}\n\nLazyLoader.prototype.handleEvent = utils.handleEvent;\n\nLazyLoader.prototype.load = function() {\n  this.img.addEventListener( 'load', this );\n  this.img.addEventListener( 'error', this );\n  // get src & srcset\n  var src = this.img.getAttribute('data-flickity-lazyload') ||\n    this.img.getAttribute('data-flickity-lazyload-src');\n  var srcset = this.img.getAttribute('data-flickity-lazyload-srcset');\n  // set src & serset\n  this.img.src = src;\n  if ( srcset ) {\n    this.img.setAttribute( 'srcset', srcset );\n  }\n  // remove attr\n  this.img.removeAttribute('data-flickity-lazyload');\n  this.img.removeAttribute('data-flickity-lazyload-src');\n  this.img.removeAttribute('data-flickity-lazyload-srcset');\n};\n\nLazyLoader.prototype.onload = function( event ) {\n  this.complete( event, 'flickity-lazyloaded' );\n};\n\nLazyLoader.prototype.onerror = function( event ) {\n  this.complete( event, 'flickity-lazyerror' );\n};\n\nLazyLoader.prototype.complete = function( event, className ) {\n  // unbind events\n  this.img.removeEventListener( 'load', this );\n  this.img.removeEventListener( 'error', this );\n\n  var cell = this.flickity.getParentCell( this.img );\n  var cellElem = cell && cell.element;\n  this.flickity.cellSizeChange( cellElem );\n\n  this.img.classList.add( className );\n  this.flickity.dispatchEvent( 'lazyLoad', event, cellElem );\n};\n\n// -----  ----- //\n\nFlickity.LazyLoader = LazyLoader;\n\nreturn Flickity;\n\n} ) );\n", "/*!\n * Flickity v2.3.0\n * Touch, responsive, flickable carousels\n *\n * Licensed GPLv3 for open source use\n * or Flickity Commercial License for commercial use\n *\n * https://flickity.metafizzy.co\n * Copyright 2015-2021 Metafizzy\n */\n\n( function( window, factory ) {\n  // universal module definition\n  if ( typeof define == 'function' && define.amd ) {\n    // AMD\n    define( [\n      './flickity',\n      './drag',\n      './prev-next-button',\n      './page-dots',\n      './player',\n      './add-remove-cell',\n      './lazyload',\n    ], factory );\n  } else if ( typeof module == 'object' && module.exports ) {\n    // CommonJS\n    module.exports = factory(\n        require('./flickity'),\n        require('./drag'),\n        require('./prev-next-button'),\n        require('./page-dots'),\n        require('./player'),\n        require('./add-remove-cell'),\n        require('./lazyload')\n    );\n  }\n\n} )( window, function factory( Flickity ) {\n  return Flickity;\n} );\n", "/*\nTurbo 7.3.0\nCopyright \u00A9 2023 37signals LLC\n */\n(function () {\n    if (window.Reflect === undefined ||\n        window.customElements === undefined ||\n        window.customElements.polyfillWrapFlushCallback) {\n        return;\n    }\n    const BuiltInHTMLElement = HTMLElement;\n    const wrapperForTheName = {\n        HTMLElement: function HTMLElement() {\n            return Reflect.construct(BuiltInHTMLElement, [], this.constructor);\n        },\n    };\n    window.HTMLElement = wrapperForTheName[\"HTMLElement\"];\n    HTMLElement.prototype = BuiltInHTMLElement.prototype;\n    HTMLElement.prototype.constructor = HTMLElement;\n    Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);\n})();\n\n/**\n * The MIT License (MIT)\n * \n * Copyright (c) 2019 Javan Makhmali\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 deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * 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 FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n(function(prototype) {\n  if (typeof prototype.requestSubmit == \"function\") return\n\n  prototype.requestSubmit = function(submitter) {\n    if (submitter) {\n      validateSubmitter(submitter, this);\n      submitter.click();\n    } else {\n      submitter = document.createElement(\"input\");\n      submitter.type = \"submit\";\n      submitter.hidden = true;\n      this.appendChild(submitter);\n      submitter.click();\n      this.removeChild(submitter);\n    }\n  };\n\n  function validateSubmitter(submitter, form) {\n    submitter instanceof HTMLElement || raise(TypeError, \"parameter 1 is not of type 'HTMLElement'\");\n    submitter.type == \"submit\" || raise(TypeError, \"The specified element is not a submit button\");\n    submitter.form == form || raise(DOMException, \"The specified element is not owned by this form element\", \"NotFoundError\");\n  }\n\n  function raise(errorConstructor, message, name) {\n    throw new errorConstructor(\"Failed to execute 'requestSubmit' on 'HTMLFormElement': \" + message + \".\", name)\n  }\n})(HTMLFormElement.prototype);\n\nconst submittersByForm = new WeakMap();\nfunction findSubmitterFromClickTarget(target) {\n    const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;\n    const candidate = element ? element.closest(\"input, button\") : null;\n    return (candidate === null || candidate === void 0 ? void 0 : candidate.type) == \"submit\" ? candidate : null;\n}\nfunction clickCaptured(event) {\n    const submitter = findSubmitterFromClickTarget(event.target);\n    if (submitter && submitter.form) {\n        submittersByForm.set(submitter.form, submitter);\n    }\n}\n(function () {\n    if (\"submitter\" in Event.prototype)\n        return;\n    let prototype = window.Event.prototype;\n    if (\"SubmitEvent\" in window && /Apple Computer/.test(navigator.vendor)) {\n        prototype = window.SubmitEvent.prototype;\n    }\n    else if (\"SubmitEvent\" in window) {\n        return;\n    }\n    addEventListener(\"click\", clickCaptured, true);\n    Object.defineProperty(prototype, \"submitter\", {\n        get() {\n            if (this.type == \"submit\" && this.target instanceof HTMLFormElement) {\n                return submittersByForm.get(this.target);\n            }\n        },\n    });\n})();\n\nvar FrameLoadingStyle;\n(function (FrameLoadingStyle) {\n    FrameLoadingStyle[\"eager\"] = \"eager\";\n    FrameLoadingStyle[\"lazy\"] = \"lazy\";\n})(FrameLoadingStyle || (FrameLoadingStyle = {}));\nclass FrameElement extends HTMLElement {\n    static get observedAttributes() {\n        return [\"disabled\", \"complete\", \"loading\", \"src\"];\n    }\n    constructor() {\n        super();\n        this.loaded = Promise.resolve();\n        this.delegate = new FrameElement.delegateConstructor(this);\n    }\n    connectedCallback() {\n        this.delegate.connect();\n    }\n    disconnectedCallback() {\n        this.delegate.disconnect();\n    }\n    reload() {\n        return this.delegate.sourceURLReloaded();\n    }\n    attributeChangedCallback(name) {\n        if (name == \"loading\") {\n            this.delegate.loadingStyleChanged();\n        }\n        else if (name == \"complete\") {\n            this.delegate.completeChanged();\n        }\n        else if (name == \"src\") {\n            this.delegate.sourceURLChanged();\n        }\n        else {\n            this.delegate.disabledChanged();\n        }\n    }\n    get src() {\n        return this.getAttribute(\"src\");\n    }\n    set src(value) {\n        if (value) {\n            this.setAttribute(\"src\", value);\n        }\n        else {\n            this.removeAttribute(\"src\");\n        }\n    }\n    get loading() {\n        return frameLoadingStyleFromString(this.getAttribute(\"loading\") || \"\");\n    }\n    set loading(value) {\n        if (value) {\n            this.setAttribute(\"loading\", value);\n        }\n        else {\n            this.removeAttribute(\"loading\");\n        }\n    }\n    get disabled() {\n        return this.hasAttribute(\"disabled\");\n    }\n    set disabled(value) {\n        if (value) {\n            this.setAttribute(\"disabled\", \"\");\n        }\n        else {\n            this.removeAttribute(\"disabled\");\n        }\n    }\n    get autoscroll() {\n        return this.hasAttribute(\"autoscroll\");\n    }\n    set autoscroll(value) {\n        if (value) {\n            this.setAttribute(\"autoscroll\", \"\");\n        }\n        else {\n            this.removeAttribute(\"autoscroll\");\n        }\n    }\n    get complete() {\n        return !this.delegate.isLoading;\n    }\n    get isActive() {\n        return this.ownerDocument === document && !this.isPreview;\n    }\n    get isPreview() {\n        var _a, _b;\n        return (_b = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.documentElement) === null || _b === void 0 ? void 0 : _b.hasAttribute(\"data-turbo-preview\");\n    }\n}\nfunction frameLoadingStyleFromString(style) {\n    switch (style.toLowerCase()) {\n        case \"lazy\":\n            return FrameLoadingStyle.lazy;\n        default:\n            return FrameLoadingStyle.eager;\n    }\n}\n\nfunction expandURL(locatable) {\n    return new URL(locatable.toString(), document.baseURI);\n}\nfunction getAnchor(url) {\n    let anchorMatch;\n    if (url.hash) {\n        return url.hash.slice(1);\n    }\n    else if ((anchorMatch = url.href.match(/#(.*)$/))) {\n        return anchorMatch[1];\n    }\n}\nfunction getAction(form, submitter) {\n    const action = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formaction\")) || form.getAttribute(\"action\") || form.action;\n    return expandURL(action);\n}\nfunction getExtension(url) {\n    return (getLastPathComponent(url).match(/\\.[^.]*$/) || [])[0] || \"\";\n}\nfunction isHTML(url) {\n    return !!getExtension(url).match(/^(?:|\\.(?:htm|html|xhtml|php))$/);\n}\nfunction isPrefixedBy(baseURL, url) {\n    const prefix = getPrefix(url);\n    return baseURL.href === expandURL(prefix).href || baseURL.href.startsWith(prefix);\n}\nfunction locationIsVisitable(location, rootLocation) {\n    return isPrefixedBy(location, rootLocation) && isHTML(location);\n}\nfunction getRequestURL(url) {\n    const anchor = getAnchor(url);\n    return anchor != null ? url.href.slice(0, -(anchor.length + 1)) : url.href;\n}\nfunction toCacheKey(url) {\n    return getRequestURL(url);\n}\nfunction urlsAreEqual(left, right) {\n    return expandURL(left).href == expandURL(right).href;\n}\nfunction getPathComponents(url) {\n    return url.pathname.split(\"/\").slice(1);\n}\nfunction getLastPathComponent(url) {\n    return getPathComponents(url).slice(-1)[0];\n}\nfunction getPrefix(url) {\n    return addTrailingSlash(url.origin + url.pathname);\n}\nfunction addTrailingSlash(value) {\n    return value.endsWith(\"/\") ? value : value + \"/\";\n}\n\nclass FetchResponse {\n    constructor(response) {\n        this.response = response;\n    }\n    get succeeded() {\n        return this.response.ok;\n    }\n    get failed() {\n        return !this.succeeded;\n    }\n    get clientError() {\n        return this.statusCode >= 400 && this.statusCode <= 499;\n    }\n    get serverError() {\n        return this.statusCode >= 500 && this.statusCode <= 599;\n    }\n    get redirected() {\n        return this.response.redirected;\n    }\n    get location() {\n        return expandURL(this.response.url);\n    }\n    get isHTML() {\n        return this.contentType && this.contentType.match(/^(?:text\\/([^\\s;,]+\\b)?html|application\\/xhtml\\+xml)\\b/);\n    }\n    get statusCode() {\n        return this.response.status;\n    }\n    get contentType() {\n        return this.header(\"Content-Type\");\n    }\n    get responseText() {\n        return this.response.clone().text();\n    }\n    get responseHTML() {\n        if (this.isHTML) {\n            return this.response.clone().text();\n        }\n        else {\n            return Promise.resolve(undefined);\n        }\n    }\n    header(name) {\n        return this.response.headers.get(name);\n    }\n}\n\nfunction activateScriptElement(element) {\n    if (element.getAttribute(\"data-turbo-eval\") == \"false\") {\n        return element;\n    }\n    else {\n        const createdScriptElement = document.createElement(\"script\");\n        const cspNonce = getMetaContent(\"csp-nonce\");\n        if (cspNonce) {\n            createdScriptElement.nonce = cspNonce;\n        }\n        createdScriptElement.textContent = element.textContent;\n        createdScriptElement.async = false;\n        copyElementAttributes(createdScriptElement, element);\n        return createdScriptElement;\n    }\n}\nfunction copyElementAttributes(destinationElement, sourceElement) {\n    for (const { name, value } of sourceElement.attributes) {\n        destinationElement.setAttribute(name, value);\n    }\n}\nfunction createDocumentFragment(html) {\n    const template = document.createElement(\"template\");\n    template.innerHTML = html;\n    return template.content;\n}\nfunction dispatch(eventName, { target, cancelable, detail } = {}) {\n    const event = new CustomEvent(eventName, {\n        cancelable,\n        bubbles: true,\n        composed: true,\n        detail,\n    });\n    if (target && target.isConnected) {\n        target.dispatchEvent(event);\n    }\n    else {\n        document.documentElement.dispatchEvent(event);\n    }\n    return event;\n}\nfunction nextAnimationFrame() {\n    return new Promise((resolve) => requestAnimationFrame(() => resolve()));\n}\nfunction nextEventLoopTick() {\n    return new Promise((resolve) => setTimeout(() => resolve(), 0));\n}\nfunction nextMicrotask() {\n    return Promise.resolve();\n}\nfunction parseHTMLDocument(html = \"\") {\n    return new DOMParser().parseFromString(html, \"text/html\");\n}\nfunction unindent(strings, ...values) {\n    const lines = interpolate(strings, values).replace(/^\\n/, \"\").split(\"\\n\");\n    const match = lines[0].match(/^\\s+/);\n    const indent = match ? match[0].length : 0;\n    return lines.map((line) => line.slice(indent)).join(\"\\n\");\n}\nfunction interpolate(strings, values) {\n    return strings.reduce((result, string, i) => {\n        const value = values[i] == undefined ? \"\" : values[i];\n        return result + string + value;\n    }, \"\");\n}\nfunction uuid() {\n    return Array.from({ length: 36 })\n        .map((_, i) => {\n        if (i == 8 || i == 13 || i == 18 || i == 23) {\n            return \"-\";\n        }\n        else if (i == 14) {\n            return \"4\";\n        }\n        else if (i == 19) {\n            return (Math.floor(Math.random() * 4) + 8).toString(16);\n        }\n        else {\n            return Math.floor(Math.random() * 15).toString(16);\n        }\n    })\n        .join(\"\");\n}\nfunction getAttribute(attributeName, ...elements) {\n    for (const value of elements.map((element) => element === null || element === void 0 ? void 0 : element.getAttribute(attributeName))) {\n        if (typeof value == \"string\")\n            return value;\n    }\n    return null;\n}\nfunction hasAttribute(attributeName, ...elements) {\n    return elements.some((element) => element && element.hasAttribute(attributeName));\n}\nfunction markAsBusy(...elements) {\n    for (const element of elements) {\n        if (element.localName == \"turbo-frame\") {\n            element.setAttribute(\"busy\", \"\");\n        }\n        element.setAttribute(\"aria-busy\", \"true\");\n    }\n}\nfunction clearBusyState(...elements) {\n    for (const element of elements) {\n        if (element.localName == \"turbo-frame\") {\n            element.removeAttribute(\"busy\");\n        }\n        element.removeAttribute(\"aria-busy\");\n    }\n}\nfunction waitForLoad(element, timeoutInMilliseconds = 2000) {\n    return new Promise((resolve) => {\n        const onComplete = () => {\n            element.removeEventListener(\"error\", onComplete);\n            element.removeEventListener(\"load\", onComplete);\n            resolve();\n        };\n        element.addEventListener(\"load\", onComplete, { once: true });\n        element.addEventListener(\"error\", onComplete, { once: true });\n        setTimeout(resolve, timeoutInMilliseconds);\n    });\n}\nfunction getHistoryMethodForAction(action) {\n    switch (action) {\n        case \"replace\":\n            return history.replaceState;\n        case \"advance\":\n        case \"restore\":\n            return history.pushState;\n    }\n}\nfunction isAction(action) {\n    return action == \"advance\" || action == \"replace\" || action == \"restore\";\n}\nfunction getVisitAction(...elements) {\n    const action = getAttribute(\"data-turbo-action\", ...elements);\n    return isAction(action) ? action : null;\n}\nfunction getMetaElement(name) {\n    return document.querySelector(`meta[name=\"${name}\"]`);\n}\nfunction getMetaContent(name) {\n    const element = getMetaElement(name);\n    return element && element.content;\n}\nfunction setMetaContent(name, content) {\n    let element = getMetaElement(name);\n    if (!element) {\n        element = document.createElement(\"meta\");\n        element.setAttribute(\"name\", name);\n        document.head.appendChild(element);\n    }\n    element.setAttribute(\"content\", content);\n    return element;\n}\nfunction findClosestRecursively(element, selector) {\n    var _a;\n    if (element instanceof Element) {\n        return (element.closest(selector) ||\n            findClosestRecursively(element.assignedSlot || ((_a = element.getRootNode()) === null || _a === void 0 ? void 0 : _a.host), selector));\n    }\n}\n\nvar FetchMethod;\n(function (FetchMethod) {\n    FetchMethod[FetchMethod[\"get\"] = 0] = \"get\";\n    FetchMethod[FetchMethod[\"post\"] = 1] = \"post\";\n    FetchMethod[FetchMethod[\"put\"] = 2] = \"put\";\n    FetchMethod[FetchMethod[\"patch\"] = 3] = \"patch\";\n    FetchMethod[FetchMethod[\"delete\"] = 4] = \"delete\";\n})(FetchMethod || (FetchMethod = {}));\nfunction fetchMethodFromString(method) {\n    switch (method.toLowerCase()) {\n        case \"get\":\n            return FetchMethod.get;\n        case \"post\":\n            return FetchMethod.post;\n        case \"put\":\n            return FetchMethod.put;\n        case \"patch\":\n            return FetchMethod.patch;\n        case \"delete\":\n            return FetchMethod.delete;\n    }\n}\nclass FetchRequest {\n    constructor(delegate, method, location, body = new URLSearchParams(), target = null) {\n        this.abortController = new AbortController();\n        this.resolveRequestPromise = (_value) => { };\n        this.delegate = delegate;\n        this.method = method;\n        this.headers = this.defaultHeaders;\n        this.body = body;\n        this.url = location;\n        this.target = target;\n    }\n    get location() {\n        return this.url;\n    }\n    get params() {\n        return this.url.searchParams;\n    }\n    get entries() {\n        return this.body ? Array.from(this.body.entries()) : [];\n    }\n    cancel() {\n        this.abortController.abort();\n    }\n    async perform() {\n        const { fetchOptions } = this;\n        this.delegate.prepareRequest(this);\n        await this.allowRequestToBeIntercepted(fetchOptions);\n        try {\n            this.delegate.requestStarted(this);\n            const response = await fetch(this.url.href, fetchOptions);\n            return await this.receive(response);\n        }\n        catch (error) {\n            if (error.name !== \"AbortError\") {\n                if (this.willDelegateErrorHandling(error)) {\n                    this.delegate.requestErrored(this, error);\n                }\n                throw error;\n            }\n        }\n        finally {\n            this.delegate.requestFinished(this);\n        }\n    }\n    async receive(response) {\n        const fetchResponse = new FetchResponse(response);\n        const event = dispatch(\"turbo:before-fetch-response\", {\n            cancelable: true,\n            detail: { fetchResponse },\n            target: this.target,\n        });\n        if (event.defaultPrevented) {\n            this.delegate.requestPreventedHandlingResponse(this, fetchResponse);\n        }\n        else if (fetchResponse.succeeded) {\n            this.delegate.requestSucceededWithResponse(this, fetchResponse);\n        }\n        else {\n            this.delegate.requestFailedWithResponse(this, fetchResponse);\n        }\n        return fetchResponse;\n    }\n    get fetchOptions() {\n        var _a;\n        return {\n            method: FetchMethod[this.method].toUpperCase(),\n            credentials: \"same-origin\",\n            headers: this.headers,\n            redirect: \"follow\",\n            body: this.isSafe ? null : this.body,\n            signal: this.abortSignal,\n            referrer: (_a = this.delegate.referrer) === null || _a === void 0 ? void 0 : _a.href,\n        };\n    }\n    get defaultHeaders() {\n        return {\n            Accept: \"text/html, application/xhtml+xml\",\n        };\n    }\n    get isSafe() {\n        return this.method === FetchMethod.get;\n    }\n    get abortSignal() {\n        return this.abortController.signal;\n    }\n    acceptResponseType(mimeType) {\n        this.headers[\"Accept\"] = [mimeType, this.headers[\"Accept\"]].join(\", \");\n    }\n    async allowRequestToBeIntercepted(fetchOptions) {\n        const requestInterception = new Promise((resolve) => (this.resolveRequestPromise = resolve));\n        const event = dispatch(\"turbo:before-fetch-request\", {\n            cancelable: true,\n            detail: {\n                fetchOptions,\n                url: this.url,\n                resume: this.resolveRequestPromise,\n            },\n            target: this.target,\n        });\n        if (event.defaultPrevented)\n            await requestInterception;\n    }\n    willDelegateErrorHandling(error) {\n        const event = dispatch(\"turbo:fetch-request-error\", {\n            target: this.target,\n            cancelable: true,\n            detail: { request: this, error: error },\n        });\n        return !event.defaultPrevented;\n    }\n}\n\nclass AppearanceObserver {\n    constructor(delegate, element) {\n        this.started = false;\n        this.intersect = (entries) => {\n            const lastEntry = entries.slice(-1)[0];\n            if (lastEntry === null || lastEntry === void 0 ? void 0 : lastEntry.isIntersecting) {\n                this.delegate.elementAppearedInViewport(this.element);\n            }\n        };\n        this.delegate = delegate;\n        this.element = element;\n        this.intersectionObserver = new IntersectionObserver(this.intersect);\n    }\n    start() {\n        if (!this.started) {\n            this.started = true;\n            this.intersectionObserver.observe(this.element);\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.started = false;\n            this.intersectionObserver.unobserve(this.element);\n        }\n    }\n}\n\nclass StreamMessage {\n    static wrap(message) {\n        if (typeof message == \"string\") {\n            return new this(createDocumentFragment(message));\n        }\n        else {\n            return message;\n        }\n    }\n    constructor(fragment) {\n        this.fragment = importStreamElements(fragment);\n    }\n}\nStreamMessage.contentType = \"text/vnd.turbo-stream.html\";\nfunction importStreamElements(fragment) {\n    for (const element of fragment.querySelectorAll(\"turbo-stream\")) {\n        const streamElement = document.importNode(element, true);\n        for (const inertScriptElement of streamElement.templateElement.content.querySelectorAll(\"script\")) {\n            inertScriptElement.replaceWith(activateScriptElement(inertScriptElement));\n        }\n        element.replaceWith(streamElement);\n    }\n    return fragment;\n}\n\nvar FormSubmissionState;\n(function (FormSubmissionState) {\n    FormSubmissionState[FormSubmissionState[\"initialized\"] = 0] = \"initialized\";\n    FormSubmissionState[FormSubmissionState[\"requesting\"] = 1] = \"requesting\";\n    FormSubmissionState[FormSubmissionState[\"waiting\"] = 2] = \"waiting\";\n    FormSubmissionState[FormSubmissionState[\"receiving\"] = 3] = \"receiving\";\n    FormSubmissionState[FormSubmissionState[\"stopping\"] = 4] = \"stopping\";\n    FormSubmissionState[FormSubmissionState[\"stopped\"] = 5] = \"stopped\";\n})(FormSubmissionState || (FormSubmissionState = {}));\nvar FormEnctype;\n(function (FormEnctype) {\n    FormEnctype[\"urlEncoded\"] = \"application/x-www-form-urlencoded\";\n    FormEnctype[\"multipart\"] = \"multipart/form-data\";\n    FormEnctype[\"plain\"] = \"text/plain\";\n})(FormEnctype || (FormEnctype = {}));\nfunction formEnctypeFromString(encoding) {\n    switch (encoding.toLowerCase()) {\n        case FormEnctype.multipart:\n            return FormEnctype.multipart;\n        case FormEnctype.plain:\n            return FormEnctype.plain;\n        default:\n            return FormEnctype.urlEncoded;\n    }\n}\nclass FormSubmission {\n    static confirmMethod(message, _element, _submitter) {\n        return Promise.resolve(confirm(message));\n    }\n    constructor(delegate, formElement, submitter, mustRedirect = false) {\n        this.state = FormSubmissionState.initialized;\n        this.delegate = delegate;\n        this.formElement = formElement;\n        this.submitter = submitter;\n        this.formData = buildFormData(formElement, submitter);\n        this.location = expandURL(this.action);\n        if (this.method == FetchMethod.get) {\n            mergeFormDataEntries(this.location, [...this.body.entries()]);\n        }\n        this.fetchRequest = new FetchRequest(this, this.method, this.location, this.body, this.formElement);\n        this.mustRedirect = mustRedirect;\n    }\n    get method() {\n        var _a;\n        const method = ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"formmethod\")) || this.formElement.getAttribute(\"method\") || \"\";\n        return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get;\n    }\n    get action() {\n        var _a;\n        const formElementAction = typeof this.formElement.action === \"string\" ? this.formElement.action : null;\n        if ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.hasAttribute(\"formaction\")) {\n            return this.submitter.getAttribute(\"formaction\") || \"\";\n        }\n        else {\n            return this.formElement.getAttribute(\"action\") || formElementAction || \"\";\n        }\n    }\n    get body() {\n        if (this.enctype == FormEnctype.urlEncoded || this.method == FetchMethod.get) {\n            return new URLSearchParams(this.stringFormData);\n        }\n        else {\n            return this.formData;\n        }\n    }\n    get enctype() {\n        var _a;\n        return formEnctypeFromString(((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"formenctype\")) || this.formElement.enctype);\n    }\n    get isSafe() {\n        return this.fetchRequest.isSafe;\n    }\n    get stringFormData() {\n        return [...this.formData].reduce((entries, [name, value]) => {\n            return entries.concat(typeof value == \"string\" ? [[name, value]] : []);\n        }, []);\n    }\n    async start() {\n        const { initialized, requesting } = FormSubmissionState;\n        const confirmationMessage = getAttribute(\"data-turbo-confirm\", this.submitter, this.formElement);\n        if (typeof confirmationMessage === \"string\") {\n            const answer = await FormSubmission.confirmMethod(confirmationMessage, this.formElement, this.submitter);\n            if (!answer) {\n                return;\n            }\n        }\n        if (this.state == initialized) {\n            this.state = requesting;\n            return this.fetchRequest.perform();\n        }\n    }\n    stop() {\n        const { stopping, stopped } = FormSubmissionState;\n        if (this.state != stopping && this.state != stopped) {\n            this.state = stopping;\n            this.fetchRequest.cancel();\n            return true;\n        }\n    }\n    prepareRequest(request) {\n        if (!request.isSafe) {\n            const token = getCookieValue(getMetaContent(\"csrf-param\")) || getMetaContent(\"csrf-token\");\n            if (token) {\n                request.headers[\"X-CSRF-Token\"] = token;\n            }\n        }\n        if (this.requestAcceptsTurboStreamResponse(request)) {\n            request.acceptResponseType(StreamMessage.contentType);\n        }\n    }\n    requestStarted(_request) {\n        var _a;\n        this.state = FormSubmissionState.waiting;\n        (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.setAttribute(\"disabled\", \"\");\n        this.setSubmitsWith();\n        dispatch(\"turbo:submit-start\", {\n            target: this.formElement,\n            detail: { formSubmission: this },\n        });\n        this.delegate.formSubmissionStarted(this);\n    }\n    requestPreventedHandlingResponse(request, response) {\n        this.result = { success: response.succeeded, fetchResponse: response };\n    }\n    requestSucceededWithResponse(request, response) {\n        if (response.clientError || response.serverError) {\n            this.delegate.formSubmissionFailedWithResponse(this, response);\n        }\n        else if (this.requestMustRedirect(request) && responseSucceededWithoutRedirect(response)) {\n            const error = new Error(\"Form responses must redirect to another location\");\n            this.delegate.formSubmissionErrored(this, error);\n        }\n        else {\n            this.state = FormSubmissionState.receiving;\n            this.result = { success: true, fetchResponse: response };\n            this.delegate.formSubmissionSucceededWithResponse(this, response);\n        }\n    }\n    requestFailedWithResponse(request, response) {\n        this.result = { success: false, fetchResponse: response };\n        this.delegate.formSubmissionFailedWithResponse(this, response);\n    }\n    requestErrored(request, error) {\n        this.result = { success: false, error };\n        this.delegate.formSubmissionErrored(this, error);\n    }\n    requestFinished(_request) {\n        var _a;\n        this.state = FormSubmissionState.stopped;\n        (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.removeAttribute(\"disabled\");\n        this.resetSubmitterText();\n        dispatch(\"turbo:submit-end\", {\n            target: this.formElement,\n            detail: Object.assign({ formSubmission: this }, this.result),\n        });\n        this.delegate.formSubmissionFinished(this);\n    }\n    setSubmitsWith() {\n        if (!this.submitter || !this.submitsWith)\n            return;\n        if (this.submitter.matches(\"button\")) {\n            this.originalSubmitText = this.submitter.innerHTML;\n            this.submitter.innerHTML = this.submitsWith;\n        }\n        else if (this.submitter.matches(\"input\")) {\n            const input = this.submitter;\n            this.originalSubmitText = input.value;\n            input.value = this.submitsWith;\n        }\n    }\n    resetSubmitterText() {\n        if (!this.submitter || !this.originalSubmitText)\n            return;\n        if (this.submitter.matches(\"button\")) {\n            this.submitter.innerHTML = this.originalSubmitText;\n        }\n        else if (this.submitter.matches(\"input\")) {\n            const input = this.submitter;\n            input.value = this.originalSubmitText;\n        }\n    }\n    requestMustRedirect(request) {\n        return !request.isSafe && this.mustRedirect;\n    }\n    requestAcceptsTurboStreamResponse(request) {\n        return !request.isSafe || hasAttribute(\"data-turbo-stream\", this.submitter, this.formElement);\n    }\n    get submitsWith() {\n        var _a;\n        return (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute(\"data-turbo-submits-with\");\n    }\n}\nfunction buildFormData(formElement, submitter) {\n    const formData = new FormData(formElement);\n    const name = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"name\");\n    const value = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"value\");\n    if (name) {\n        formData.append(name, value || \"\");\n    }\n    return formData;\n}\nfunction getCookieValue(cookieName) {\n    if (cookieName != null) {\n        const cookies = document.cookie ? document.cookie.split(\"; \") : [];\n        const cookie = cookies.find((cookie) => cookie.startsWith(cookieName));\n        if (cookie) {\n            const value = cookie.split(\"=\").slice(1).join(\"=\");\n            return value ? decodeURIComponent(value) : undefined;\n        }\n    }\n}\nfunction responseSucceededWithoutRedirect(response) {\n    return response.statusCode == 200 && !response.redirected;\n}\nfunction mergeFormDataEntries(url, entries) {\n    const searchParams = new URLSearchParams();\n    for (const [name, value] of entries) {\n        if (value instanceof File)\n            continue;\n        searchParams.append(name, value);\n    }\n    url.search = searchParams.toString();\n    return url;\n}\n\nclass Snapshot {\n    constructor(element) {\n        this.element = element;\n    }\n    get activeElement() {\n        return this.element.ownerDocument.activeElement;\n    }\n    get children() {\n        return [...this.element.children];\n    }\n    hasAnchor(anchor) {\n        return this.getElementForAnchor(anchor) != null;\n    }\n    getElementForAnchor(anchor) {\n        return anchor ? this.element.querySelector(`[id='${anchor}'], a[name='${anchor}']`) : null;\n    }\n    get isConnected() {\n        return this.element.isConnected;\n    }\n    get firstAutofocusableElement() {\n        const inertDisabledOrHidden = \"[inert], :disabled, [hidden], details:not([open]), dialog:not([open])\";\n        for (const element of this.element.querySelectorAll(\"[autofocus]\")) {\n            if (element.closest(inertDisabledOrHidden) == null)\n                return element;\n            else\n                continue;\n        }\n        return null;\n    }\n    get permanentElements() {\n        return queryPermanentElementsAll(this.element);\n    }\n    getPermanentElementById(id) {\n        return getPermanentElementById(this.element, id);\n    }\n    getPermanentElementMapForSnapshot(snapshot) {\n        const permanentElementMap = {};\n        for (const currentPermanentElement of this.permanentElements) {\n            const { id } = currentPermanentElement;\n            const newPermanentElement = snapshot.getPermanentElementById(id);\n            if (newPermanentElement) {\n                permanentElementMap[id] = [currentPermanentElement, newPermanentElement];\n            }\n        }\n        return permanentElementMap;\n    }\n}\nfunction getPermanentElementById(node, id) {\n    return node.querySelector(`#${id}[data-turbo-permanent]`);\n}\nfunction queryPermanentElementsAll(node) {\n    return node.querySelectorAll(\"[id][data-turbo-permanent]\");\n}\n\nclass FormSubmitObserver {\n    constructor(delegate, eventTarget) {\n        this.started = false;\n        this.submitCaptured = () => {\n            this.eventTarget.removeEventListener(\"submit\", this.submitBubbled, false);\n            this.eventTarget.addEventListener(\"submit\", this.submitBubbled, false);\n        };\n        this.submitBubbled = ((event) => {\n            if (!event.defaultPrevented) {\n                const form = event.target instanceof HTMLFormElement ? event.target : undefined;\n                const submitter = event.submitter || undefined;\n                if (form &&\n                    submissionDoesNotDismissDialog(form, submitter) &&\n                    submissionDoesNotTargetIFrame(form, submitter) &&\n                    this.delegate.willSubmitForm(form, submitter)) {\n                    event.preventDefault();\n                    event.stopImmediatePropagation();\n                    this.delegate.formSubmitted(form, submitter);\n                }\n            }\n        });\n        this.delegate = delegate;\n        this.eventTarget = eventTarget;\n    }\n    start() {\n        if (!this.started) {\n            this.eventTarget.addEventListener(\"submit\", this.submitCaptured, true);\n            this.started = true;\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.eventTarget.removeEventListener(\"submit\", this.submitCaptured, true);\n            this.started = false;\n        }\n    }\n}\nfunction submissionDoesNotDismissDialog(form, submitter) {\n    const method = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formmethod\")) || form.getAttribute(\"method\");\n    return method != \"dialog\";\n}\nfunction submissionDoesNotTargetIFrame(form, submitter) {\n    if ((submitter === null || submitter === void 0 ? void 0 : submitter.hasAttribute(\"formtarget\")) || form.hasAttribute(\"target\")) {\n        const target = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"formtarget\")) || form.target;\n        for (const element of document.getElementsByName(target)) {\n            if (element instanceof HTMLIFrameElement)\n                return false;\n        }\n        return true;\n    }\n    else {\n        return true;\n    }\n}\n\nclass View {\n    constructor(delegate, element) {\n        this.resolveRenderPromise = (_value) => { };\n        this.resolveInterceptionPromise = (_value) => { };\n        this.delegate = delegate;\n        this.element = element;\n    }\n    scrollToAnchor(anchor) {\n        const element = this.snapshot.getElementForAnchor(anchor);\n        if (element) {\n            this.scrollToElement(element);\n            this.focusElement(element);\n        }\n        else {\n            this.scrollToPosition({ x: 0, y: 0 });\n        }\n    }\n    scrollToAnchorFromLocation(location) {\n        this.scrollToAnchor(getAnchor(location));\n    }\n    scrollToElement(element) {\n        element.scrollIntoView();\n    }\n    focusElement(element) {\n        if (element instanceof HTMLElement) {\n            if (element.hasAttribute(\"tabindex\")) {\n                element.focus();\n            }\n            else {\n                element.setAttribute(\"tabindex\", \"-1\");\n                element.focus();\n                element.removeAttribute(\"tabindex\");\n            }\n        }\n    }\n    scrollToPosition({ x, y }) {\n        this.scrollRoot.scrollTo(x, y);\n    }\n    scrollToTop() {\n        this.scrollToPosition({ x: 0, y: 0 });\n    }\n    get scrollRoot() {\n        return window;\n    }\n    async render(renderer) {\n        const { isPreview, shouldRender, newSnapshot: snapshot } = renderer;\n        if (shouldRender) {\n            try {\n                this.renderPromise = new Promise((resolve) => (this.resolveRenderPromise = resolve));\n                this.renderer = renderer;\n                await this.prepareToRenderSnapshot(renderer);\n                const renderInterception = new Promise((resolve) => (this.resolveInterceptionPromise = resolve));\n                const options = { resume: this.resolveInterceptionPromise, render: this.renderer.renderElement };\n                const immediateRender = this.delegate.allowsImmediateRender(snapshot, options);\n                if (!immediateRender)\n                    await renderInterception;\n                await this.renderSnapshot(renderer);\n                this.delegate.viewRenderedSnapshot(snapshot, isPreview);\n                this.delegate.preloadOnLoadLinksForView(this.element);\n                this.finishRenderingSnapshot(renderer);\n            }\n            finally {\n                delete this.renderer;\n                this.resolveRenderPromise(undefined);\n                delete this.renderPromise;\n            }\n        }\n        else {\n            this.invalidate(renderer.reloadReason);\n        }\n    }\n    invalidate(reason) {\n        this.delegate.viewInvalidated(reason);\n    }\n    async prepareToRenderSnapshot(renderer) {\n        this.markAsPreview(renderer.isPreview);\n        await renderer.prepareToRender();\n    }\n    markAsPreview(isPreview) {\n        if (isPreview) {\n            this.element.setAttribute(\"data-turbo-preview\", \"\");\n        }\n        else {\n            this.element.removeAttribute(\"data-turbo-preview\");\n        }\n    }\n    async renderSnapshot(renderer) {\n        await renderer.render();\n    }\n    finishRenderingSnapshot(renderer) {\n        renderer.finishRendering();\n    }\n}\n\nclass FrameView extends View {\n    missing() {\n        this.element.innerHTML = `<strong class=\"turbo-frame-error\">Content missing</strong>`;\n    }\n    get snapshot() {\n        return new Snapshot(this.element);\n    }\n}\n\nclass LinkInterceptor {\n    constructor(delegate, element) {\n        this.clickBubbled = (event) => {\n            if (this.respondsToEventTarget(event.target)) {\n                this.clickEvent = event;\n            }\n            else {\n                delete this.clickEvent;\n            }\n        };\n        this.linkClicked = ((event) => {\n            if (this.clickEvent && this.respondsToEventTarget(event.target) && event.target instanceof Element) {\n                if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) {\n                    this.clickEvent.preventDefault();\n                    event.preventDefault();\n                    this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent);\n                }\n            }\n            delete this.clickEvent;\n        });\n        this.willVisit = ((_event) => {\n            delete this.clickEvent;\n        });\n        this.delegate = delegate;\n        this.element = element;\n    }\n    start() {\n        this.element.addEventListener(\"click\", this.clickBubbled);\n        document.addEventListener(\"turbo:click\", this.linkClicked);\n        document.addEventListener(\"turbo:before-visit\", this.willVisit);\n    }\n    stop() {\n        this.element.removeEventListener(\"click\", this.clickBubbled);\n        document.removeEventListener(\"turbo:click\", this.linkClicked);\n        document.removeEventListener(\"turbo:before-visit\", this.willVisit);\n    }\n    respondsToEventTarget(target) {\n        const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;\n        return element && element.closest(\"turbo-frame, html\") == this.element;\n    }\n}\n\nclass LinkClickObserver {\n    constructor(delegate, eventTarget) {\n        this.started = false;\n        this.clickCaptured = () => {\n            this.eventTarget.removeEventListener(\"click\", this.clickBubbled, false);\n            this.eventTarget.addEventListener(\"click\", this.clickBubbled, false);\n        };\n        this.clickBubbled = (event) => {\n            if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) {\n                const target = (event.composedPath && event.composedPath()[0]) || event.target;\n                const link = this.findLinkFromClickTarget(target);\n                if (link && doesNotTargetIFrame(link)) {\n                    const location = this.getLocationForLink(link);\n                    if (this.delegate.willFollowLinkToLocation(link, location, event)) {\n                        event.preventDefault();\n                        this.delegate.followedLinkToLocation(link, location);\n                    }\n                }\n            }\n        };\n        this.delegate = delegate;\n        this.eventTarget = eventTarget;\n    }\n    start() {\n        if (!this.started) {\n            this.eventTarget.addEventListener(\"click\", this.clickCaptured, true);\n            this.started = true;\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.eventTarget.removeEventListener(\"click\", this.clickCaptured, true);\n            this.started = false;\n        }\n    }\n    clickEventIsSignificant(event) {\n        return !((event.target && event.target.isContentEditable) ||\n            event.defaultPrevented ||\n            event.which > 1 ||\n            event.altKey ||\n            event.ctrlKey ||\n            event.metaKey ||\n            event.shiftKey);\n    }\n    findLinkFromClickTarget(target) {\n        return findClosestRecursively(target, \"a[href]:not([target^=_]):not([download])\");\n    }\n    getLocationForLink(link) {\n        return expandURL(link.getAttribute(\"href\") || \"\");\n    }\n}\nfunction doesNotTargetIFrame(anchor) {\n    if (anchor.hasAttribute(\"target\")) {\n        for (const element of document.getElementsByName(anchor.target)) {\n            if (element instanceof HTMLIFrameElement)\n                return false;\n        }\n        return true;\n    }\n    else {\n        return true;\n    }\n}\n\nclass FormLinkClickObserver {\n    constructor(delegate, element) {\n        this.delegate = delegate;\n        this.linkInterceptor = new LinkClickObserver(this, element);\n    }\n    start() {\n        this.linkInterceptor.start();\n    }\n    stop() {\n        this.linkInterceptor.stop();\n    }\n    willFollowLinkToLocation(link, location, originalEvent) {\n        return (this.delegate.willSubmitFormLinkToLocation(link, location, originalEvent) &&\n            link.hasAttribute(\"data-turbo-method\"));\n    }\n    followedLinkToLocation(link, location) {\n        const form = document.createElement(\"form\");\n        const type = \"hidden\";\n        for (const [name, value] of location.searchParams) {\n            form.append(Object.assign(document.createElement(\"input\"), { type, name, value }));\n        }\n        const action = Object.assign(location, { search: \"\" });\n        form.setAttribute(\"data-turbo\", \"true\");\n        form.setAttribute(\"action\", action.href);\n        form.setAttribute(\"hidden\", \"\");\n        const method = link.getAttribute(\"data-turbo-method\");\n        if (method)\n            form.setAttribute(\"method\", method);\n        const turboFrame = link.getAttribute(\"data-turbo-frame\");\n        if (turboFrame)\n            form.setAttribute(\"data-turbo-frame\", turboFrame);\n        const turboAction = getVisitAction(link);\n        if (turboAction)\n            form.setAttribute(\"data-turbo-action\", turboAction);\n        const turboConfirm = link.getAttribute(\"data-turbo-confirm\");\n        if (turboConfirm)\n            form.setAttribute(\"data-turbo-confirm\", turboConfirm);\n        const turboStream = link.hasAttribute(\"data-turbo-stream\");\n        if (turboStream)\n            form.setAttribute(\"data-turbo-stream\", \"\");\n        this.delegate.submittedFormLinkToLocation(link, location, form);\n        document.body.appendChild(form);\n        form.addEventListener(\"turbo:submit-end\", () => form.remove(), { once: true });\n        requestAnimationFrame(() => form.requestSubmit());\n    }\n}\n\nclass Bardo {\n    static async preservingPermanentElements(delegate, permanentElementMap, callback) {\n        const bardo = new this(delegate, permanentElementMap);\n        bardo.enter();\n        await callback();\n        bardo.leave();\n    }\n    constructor(delegate, permanentElementMap) {\n        this.delegate = delegate;\n        this.permanentElementMap = permanentElementMap;\n    }\n    enter() {\n        for (const id in this.permanentElementMap) {\n            const [currentPermanentElement, newPermanentElement] = this.permanentElementMap[id];\n            this.delegate.enteringBardo(currentPermanentElement, newPermanentElement);\n            this.replaceNewPermanentElementWithPlaceholder(newPermanentElement);\n        }\n    }\n    leave() {\n        for (const id in this.permanentElementMap) {\n            const [currentPermanentElement] = this.permanentElementMap[id];\n            this.replaceCurrentPermanentElementWithClone(currentPermanentElement);\n            this.replacePlaceholderWithPermanentElement(currentPermanentElement);\n            this.delegate.leavingBardo(currentPermanentElement);\n        }\n    }\n    replaceNewPermanentElementWithPlaceholder(permanentElement) {\n        const placeholder = createPlaceholderForPermanentElement(permanentElement);\n        permanentElement.replaceWith(placeholder);\n    }\n    replaceCurrentPermanentElementWithClone(permanentElement) {\n        const clone = permanentElement.cloneNode(true);\n        permanentElement.replaceWith(clone);\n    }\n    replacePlaceholderWithPermanentElement(permanentElement) {\n        const placeholder = this.getPlaceholderById(permanentElement.id);\n        placeholder === null || placeholder === void 0 ? void 0 : placeholder.replaceWith(permanentElement);\n    }\n    getPlaceholderById(id) {\n        return this.placeholders.find((element) => element.content == id);\n    }\n    get placeholders() {\n        return [...document.querySelectorAll(\"meta[name=turbo-permanent-placeholder][content]\")];\n    }\n}\nfunction createPlaceholderForPermanentElement(permanentElement) {\n    const element = document.createElement(\"meta\");\n    element.setAttribute(\"name\", \"turbo-permanent-placeholder\");\n    element.setAttribute(\"content\", permanentElement.id);\n    return element;\n}\n\nclass Renderer {\n    constructor(currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {\n        this.activeElement = null;\n        this.currentSnapshot = currentSnapshot;\n        this.newSnapshot = newSnapshot;\n        this.isPreview = isPreview;\n        this.willRender = willRender;\n        this.renderElement = renderElement;\n        this.promise = new Promise((resolve, reject) => (this.resolvingFunctions = { resolve, reject }));\n    }\n    get shouldRender() {\n        return true;\n    }\n    get reloadReason() {\n        return;\n    }\n    prepareToRender() {\n        return;\n    }\n    finishRendering() {\n        if (this.resolvingFunctions) {\n            this.resolvingFunctions.resolve();\n            delete this.resolvingFunctions;\n        }\n    }\n    async preservingPermanentElements(callback) {\n        await Bardo.preservingPermanentElements(this, this.permanentElementMap, callback);\n    }\n    focusFirstAutofocusableElement() {\n        const element = this.connectedSnapshot.firstAutofocusableElement;\n        if (elementIsFocusable(element)) {\n            element.focus();\n        }\n    }\n    enteringBardo(currentPermanentElement) {\n        if (this.activeElement)\n            return;\n        if (currentPermanentElement.contains(this.currentSnapshot.activeElement)) {\n            this.activeElement = this.currentSnapshot.activeElement;\n        }\n    }\n    leavingBardo(currentPermanentElement) {\n        if (currentPermanentElement.contains(this.activeElement) && this.activeElement instanceof HTMLElement) {\n            this.activeElement.focus();\n            this.activeElement = null;\n        }\n    }\n    get connectedSnapshot() {\n        return this.newSnapshot.isConnected ? this.newSnapshot : this.currentSnapshot;\n    }\n    get currentElement() {\n        return this.currentSnapshot.element;\n    }\n    get newElement() {\n        return this.newSnapshot.element;\n    }\n    get permanentElementMap() {\n        return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot);\n    }\n}\nfunction elementIsFocusable(element) {\n    return element && typeof element.focus == \"function\";\n}\n\nclass FrameRenderer extends Renderer {\n    static renderElement(currentElement, newElement) {\n        var _a;\n        const destinationRange = document.createRange();\n        destinationRange.selectNodeContents(currentElement);\n        destinationRange.deleteContents();\n        const frameElement = newElement;\n        const sourceRange = (_a = frameElement.ownerDocument) === null || _a === void 0 ? void 0 : _a.createRange();\n        if (sourceRange) {\n            sourceRange.selectNodeContents(frameElement);\n            currentElement.appendChild(sourceRange.extractContents());\n        }\n    }\n    constructor(delegate, currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {\n        super(currentSnapshot, newSnapshot, renderElement, isPreview, willRender);\n        this.delegate = delegate;\n    }\n    get shouldRender() {\n        return true;\n    }\n    async render() {\n        await nextAnimationFrame();\n        this.preservingPermanentElements(() => {\n            this.loadFrameElement();\n        });\n        this.scrollFrameIntoView();\n        await nextAnimationFrame();\n        this.focusFirstAutofocusableElement();\n        await nextAnimationFrame();\n        this.activateScriptElements();\n    }\n    loadFrameElement() {\n        this.delegate.willRenderFrame(this.currentElement, this.newElement);\n        this.renderElement(this.currentElement, this.newElement);\n    }\n    scrollFrameIntoView() {\n        if (this.currentElement.autoscroll || this.newElement.autoscroll) {\n            const element = this.currentElement.firstElementChild;\n            const block = readScrollLogicalPosition(this.currentElement.getAttribute(\"data-autoscroll-block\"), \"end\");\n            const behavior = readScrollBehavior(this.currentElement.getAttribute(\"data-autoscroll-behavior\"), \"auto\");\n            if (element) {\n                element.scrollIntoView({ block, behavior });\n                return true;\n            }\n        }\n        return false;\n    }\n    activateScriptElements() {\n        for (const inertScriptElement of this.newScriptElements) {\n            const activatedScriptElement = activateScriptElement(inertScriptElement);\n            inertScriptElement.replaceWith(activatedScriptElement);\n        }\n    }\n    get newScriptElements() {\n        return this.currentElement.querySelectorAll(\"script\");\n    }\n}\nfunction readScrollLogicalPosition(value, defaultValue) {\n    if (value == \"end\" || value == \"start\" || value == \"center\" || value == \"nearest\") {\n        return value;\n    }\n    else {\n        return defaultValue;\n    }\n}\nfunction readScrollBehavior(value, defaultValue) {\n    if (value == \"auto\" || value == \"smooth\") {\n        return value;\n    }\n    else {\n        return defaultValue;\n    }\n}\n\nclass ProgressBar {\n    static get defaultCSS() {\n        return unindent `\n      .turbo-progress-bar {\n        position: fixed;\n        display: block;\n        top: 0;\n        left: 0;\n        height: 3px;\n        background: #0076ff;\n        z-index: 2147483647;\n        transition:\n          width ${ProgressBar.animationDuration}ms ease-out,\n          opacity ${ProgressBar.animationDuration / 2}ms ${ProgressBar.animationDuration / 2}ms ease-in;\n        transform: translate3d(0, 0, 0);\n      }\n    `;\n    }\n    constructor() {\n        this.hiding = false;\n        this.value = 0;\n        this.visible = false;\n        this.trickle = () => {\n            this.setValue(this.value + Math.random() / 100);\n        };\n        this.stylesheetElement = this.createStylesheetElement();\n        this.progressElement = this.createProgressElement();\n        this.installStylesheetElement();\n        this.setValue(0);\n    }\n    show() {\n        if (!this.visible) {\n            this.visible = true;\n            this.installProgressElement();\n            this.startTrickling();\n        }\n    }\n    hide() {\n        if (this.visible && !this.hiding) {\n            this.hiding = true;\n            this.fadeProgressElement(() => {\n                this.uninstallProgressElement();\n                this.stopTrickling();\n                this.visible = false;\n                this.hiding = false;\n            });\n        }\n    }\n    setValue(value) {\n        this.value = value;\n        this.refresh();\n    }\n    installStylesheetElement() {\n        document.head.insertBefore(this.stylesheetElement, document.head.firstChild);\n    }\n    installProgressElement() {\n        this.progressElement.style.width = \"0\";\n        this.progressElement.style.opacity = \"1\";\n        document.documentElement.insertBefore(this.progressElement, document.body);\n        this.refresh();\n    }\n    fadeProgressElement(callback) {\n        this.progressElement.style.opacity = \"0\";\n        setTimeout(callback, ProgressBar.animationDuration * 1.5);\n    }\n    uninstallProgressElement() {\n        if (this.progressElement.parentNode) {\n            document.documentElement.removeChild(this.progressElement);\n        }\n    }\n    startTrickling() {\n        if (!this.trickleInterval) {\n            this.trickleInterval = window.setInterval(this.trickle, ProgressBar.animationDuration);\n        }\n    }\n    stopTrickling() {\n        window.clearInterval(this.trickleInterval);\n        delete this.trickleInterval;\n    }\n    refresh() {\n        requestAnimationFrame(() => {\n            this.progressElement.style.width = `${10 + this.value * 90}%`;\n        });\n    }\n    createStylesheetElement() {\n        const element = document.createElement(\"style\");\n        element.type = \"text/css\";\n        element.textContent = ProgressBar.defaultCSS;\n        if (this.cspNonce) {\n            element.nonce = this.cspNonce;\n        }\n        return element;\n    }\n    createProgressElement() {\n        const element = document.createElement(\"div\");\n        element.className = \"turbo-progress-bar\";\n        return element;\n    }\n    get cspNonce() {\n        return getMetaContent(\"csp-nonce\");\n    }\n}\nProgressBar.animationDuration = 300;\n\nclass HeadSnapshot extends Snapshot {\n    constructor() {\n        super(...arguments);\n        this.detailsByOuterHTML = this.children\n            .filter((element) => !elementIsNoscript(element))\n            .map((element) => elementWithoutNonce(element))\n            .reduce((result, element) => {\n            const { outerHTML } = element;\n            const details = outerHTML in result\n                ? result[outerHTML]\n                : {\n                    type: elementType(element),\n                    tracked: elementIsTracked(element),\n                    elements: [],\n                };\n            return Object.assign(Object.assign({}, result), { [outerHTML]: Object.assign(Object.assign({}, details), { elements: [...details.elements, element] }) });\n        }, {});\n    }\n    get trackedElementSignature() {\n        return Object.keys(this.detailsByOuterHTML)\n            .filter((outerHTML) => this.detailsByOuterHTML[outerHTML].tracked)\n            .join(\"\");\n    }\n    getScriptElementsNotInSnapshot(snapshot) {\n        return this.getElementsMatchingTypeNotInSnapshot(\"script\", snapshot);\n    }\n    getStylesheetElementsNotInSnapshot(snapshot) {\n        return this.getElementsMatchingTypeNotInSnapshot(\"stylesheet\", snapshot);\n    }\n    getElementsMatchingTypeNotInSnapshot(matchedType, snapshot) {\n        return Object.keys(this.detailsByOuterHTML)\n            .filter((outerHTML) => !(outerHTML in snapshot.detailsByOuterHTML))\n            .map((outerHTML) => this.detailsByOuterHTML[outerHTML])\n            .filter(({ type }) => type == matchedType)\n            .map(({ elements: [element] }) => element);\n    }\n    get provisionalElements() {\n        return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n            const { type, tracked, elements } = this.detailsByOuterHTML[outerHTML];\n            if (type == null && !tracked) {\n                return [...result, ...elements];\n            }\n            else if (elements.length > 1) {\n                return [...result, ...elements.slice(1)];\n            }\n            else {\n                return result;\n            }\n        }, []);\n    }\n    getMetaValue(name) {\n        const element = this.findMetaElementByName(name);\n        return element ? element.getAttribute(\"content\") : null;\n    }\n    findMetaElementByName(name) {\n        return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n            const { elements: [element], } = this.detailsByOuterHTML[outerHTML];\n            return elementIsMetaElementWithName(element, name) ? element : result;\n        }, undefined);\n    }\n}\nfunction elementType(element) {\n    if (elementIsScript(element)) {\n        return \"script\";\n    }\n    else if (elementIsStylesheet(element)) {\n        return \"stylesheet\";\n    }\n}\nfunction elementIsTracked(element) {\n    return element.getAttribute(\"data-turbo-track\") == \"reload\";\n}\nfunction elementIsScript(element) {\n    const tagName = element.localName;\n    return tagName == \"script\";\n}\nfunction elementIsNoscript(element) {\n    const tagName = element.localName;\n    return tagName == \"noscript\";\n}\nfunction elementIsStylesheet(element) {\n    const tagName = element.localName;\n    return tagName == \"style\" || (tagName == \"link\" && element.getAttribute(\"rel\") == \"stylesheet\");\n}\nfunction elementIsMetaElementWithName(element, name) {\n    const tagName = element.localName;\n    return tagName == \"meta\" && element.getAttribute(\"name\") == name;\n}\nfunction elementWithoutNonce(element) {\n    if (element.hasAttribute(\"nonce\")) {\n        element.setAttribute(\"nonce\", \"\");\n    }\n    return element;\n}\n\nclass PageSnapshot extends Snapshot {\n    static fromHTMLString(html = \"\") {\n        return this.fromDocument(parseHTMLDocument(html));\n    }\n    static fromElement(element) {\n        return this.fromDocument(element.ownerDocument);\n    }\n    static fromDocument({ head, body }) {\n        return new this(body, new HeadSnapshot(head));\n    }\n    constructor(element, headSnapshot) {\n        super(element);\n        this.headSnapshot = headSnapshot;\n    }\n    clone() {\n        const clonedElement = this.element.cloneNode(true);\n        const selectElements = this.element.querySelectorAll(\"select\");\n        const clonedSelectElements = clonedElement.querySelectorAll(\"select\");\n        for (const [index, source] of selectElements.entries()) {\n            const clone = clonedSelectElements[index];\n            for (const option of clone.selectedOptions)\n                option.selected = false;\n            for (const option of source.selectedOptions)\n                clone.options[option.index].selected = true;\n        }\n        for (const clonedPasswordInput of clonedElement.querySelectorAll('input[type=\"password\"]')) {\n            clonedPasswordInput.value = \"\";\n        }\n        return new PageSnapshot(clonedElement, this.headSnapshot);\n    }\n    get headElement() {\n        return this.headSnapshot.element;\n    }\n    get rootLocation() {\n        var _a;\n        const root = (_a = this.getSetting(\"root\")) !== null && _a !== void 0 ? _a : \"/\";\n        return expandURL(root);\n    }\n    get cacheControlValue() {\n        return this.getSetting(\"cache-control\");\n    }\n    get isPreviewable() {\n        return this.cacheControlValue != \"no-preview\";\n    }\n    get isCacheable() {\n        return this.cacheControlValue != \"no-cache\";\n    }\n    get isVisitable() {\n        return this.getSetting(\"visit-control\") != \"reload\";\n    }\n    getSetting(name) {\n        return this.headSnapshot.getMetaValue(`turbo-${name}`);\n    }\n}\n\nvar TimingMetric;\n(function (TimingMetric) {\n    TimingMetric[\"visitStart\"] = \"visitStart\";\n    TimingMetric[\"requestStart\"] = \"requestStart\";\n    TimingMetric[\"requestEnd\"] = \"requestEnd\";\n    TimingMetric[\"visitEnd\"] = \"visitEnd\";\n})(TimingMetric || (TimingMetric = {}));\nvar VisitState;\n(function (VisitState) {\n    VisitState[\"initialized\"] = \"initialized\";\n    VisitState[\"started\"] = \"started\";\n    VisitState[\"canceled\"] = \"canceled\";\n    VisitState[\"failed\"] = \"failed\";\n    VisitState[\"completed\"] = \"completed\";\n})(VisitState || (VisitState = {}));\nconst defaultOptions = {\n    action: \"advance\",\n    historyChanged: false,\n    visitCachedSnapshot: () => { },\n    willRender: true,\n    updateHistory: true,\n    shouldCacheSnapshot: true,\n    acceptsStreamResponse: false,\n};\nvar SystemStatusCode;\n(function (SystemStatusCode) {\n    SystemStatusCode[SystemStatusCode[\"networkFailure\"] = 0] = \"networkFailure\";\n    SystemStatusCode[SystemStatusCode[\"timeoutFailure\"] = -1] = \"timeoutFailure\";\n    SystemStatusCode[SystemStatusCode[\"contentTypeMismatch\"] = -2] = \"contentTypeMismatch\";\n})(SystemStatusCode || (SystemStatusCode = {}));\nclass Visit {\n    constructor(delegate, location, restorationIdentifier, options = {}) {\n        this.identifier = uuid();\n        this.timingMetrics = {};\n        this.followedRedirect = false;\n        this.historyChanged = false;\n        this.scrolled = false;\n        this.shouldCacheSnapshot = true;\n        this.acceptsStreamResponse = false;\n        this.snapshotCached = false;\n        this.state = VisitState.initialized;\n        this.delegate = delegate;\n        this.location = location;\n        this.restorationIdentifier = restorationIdentifier || uuid();\n        const { action, historyChanged, referrer, snapshot, snapshotHTML, response, visitCachedSnapshot, willRender, updateHistory, shouldCacheSnapshot, acceptsStreamResponse, } = Object.assign(Object.assign({}, defaultOptions), options);\n        this.action = action;\n        this.historyChanged = historyChanged;\n        this.referrer = referrer;\n        this.snapshot = snapshot;\n        this.snapshotHTML = snapshotHTML;\n        this.response = response;\n        this.isSamePage = this.delegate.locationWithActionIsSamePage(this.location, this.action);\n        this.visitCachedSnapshot = visitCachedSnapshot;\n        this.willRender = willRender;\n        this.updateHistory = updateHistory;\n        this.scrolled = !willRender;\n        this.shouldCacheSnapshot = shouldCacheSnapshot;\n        this.acceptsStreamResponse = acceptsStreamResponse;\n    }\n    get adapter() {\n        return this.delegate.adapter;\n    }\n    get view() {\n        return this.delegate.view;\n    }\n    get history() {\n        return this.delegate.history;\n    }\n    get restorationData() {\n        return this.history.getRestorationDataForIdentifier(this.restorationIdentifier);\n    }\n    get silent() {\n        return this.isSamePage;\n    }\n    start() {\n        if (this.state == VisitState.initialized) {\n            this.recordTimingMetric(TimingMetric.visitStart);\n            this.state = VisitState.started;\n            this.adapter.visitStarted(this);\n            this.delegate.visitStarted(this);\n        }\n    }\n    cancel() {\n        if (this.state == VisitState.started) {\n            if (this.request) {\n                this.request.cancel();\n            }\n            this.cancelRender();\n            this.state = VisitState.canceled;\n        }\n    }\n    complete() {\n        if (this.state == VisitState.started) {\n            this.recordTimingMetric(TimingMetric.visitEnd);\n            this.state = VisitState.completed;\n            this.followRedirect();\n            if (!this.followedRedirect) {\n                this.adapter.visitCompleted(this);\n                this.delegate.visitCompleted(this);\n            }\n        }\n    }\n    fail() {\n        if (this.state == VisitState.started) {\n            this.state = VisitState.failed;\n            this.adapter.visitFailed(this);\n        }\n    }\n    changeHistory() {\n        var _a;\n        if (!this.historyChanged && this.updateHistory) {\n            const actionForHistory = this.location.href === ((_a = this.referrer) === null || _a === void 0 ? void 0 : _a.href) ? \"replace\" : this.action;\n            const method = getHistoryMethodForAction(actionForHistory);\n            this.history.update(method, this.location, this.restorationIdentifier);\n            this.historyChanged = true;\n        }\n    }\n    issueRequest() {\n        if (this.hasPreloadedResponse()) {\n            this.simulateRequest();\n        }\n        else if (this.shouldIssueRequest() && !this.request) {\n            this.request = new FetchRequest(this, FetchMethod.get, this.location);\n            this.request.perform();\n        }\n    }\n    simulateRequest() {\n        if (this.response) {\n            this.startRequest();\n            this.recordResponse();\n            this.finishRequest();\n        }\n    }\n    startRequest() {\n        this.recordTimingMetric(TimingMetric.requestStart);\n        this.adapter.visitRequestStarted(this);\n    }\n    recordResponse(response = this.response) {\n        this.response = response;\n        if (response) {\n            const { statusCode } = response;\n            if (isSuccessful(statusCode)) {\n                this.adapter.visitRequestCompleted(this);\n            }\n            else {\n                this.adapter.visitRequestFailedWithStatusCode(this, statusCode);\n            }\n        }\n    }\n    finishRequest() {\n        this.recordTimingMetric(TimingMetric.requestEnd);\n        this.adapter.visitRequestFinished(this);\n    }\n    loadResponse() {\n        if (this.response) {\n            const { statusCode, responseHTML } = this.response;\n            this.render(async () => {\n                if (this.shouldCacheSnapshot)\n                    this.cacheSnapshot();\n                if (this.view.renderPromise)\n                    await this.view.renderPromise;\n                if (isSuccessful(statusCode) && responseHTML != null) {\n                    await this.view.renderPage(PageSnapshot.fromHTMLString(responseHTML), false, this.willRender, this);\n                    this.performScroll();\n                    this.adapter.visitRendered(this);\n                    this.complete();\n                }\n                else {\n                    await this.view.renderError(PageSnapshot.fromHTMLString(responseHTML), this);\n                    this.adapter.visitRendered(this);\n                    this.fail();\n                }\n            });\n        }\n    }\n    getCachedSnapshot() {\n        const snapshot = this.view.getCachedSnapshotForLocation(this.location) || this.getPreloadedSnapshot();\n        if (snapshot && (!getAnchor(this.location) || snapshot.hasAnchor(getAnchor(this.location)))) {\n            if (this.action == \"restore\" || snapshot.isPreviewable) {\n                return snapshot;\n            }\n        }\n    }\n    getPreloadedSnapshot() {\n        if (this.snapshotHTML) {\n            return PageSnapshot.fromHTMLString(this.snapshotHTML);\n        }\n    }\n    hasCachedSnapshot() {\n        return this.getCachedSnapshot() != null;\n    }\n    loadCachedSnapshot() {\n        const snapshot = this.getCachedSnapshot();\n        if (snapshot) {\n            const isPreview = this.shouldIssueRequest();\n            this.render(async () => {\n                this.cacheSnapshot();\n                if (this.isSamePage) {\n                    this.adapter.visitRendered(this);\n                }\n                else {\n                    if (this.view.renderPromise)\n                        await this.view.renderPromise;\n                    await this.view.renderPage(snapshot, isPreview, this.willRender, this);\n                    this.performScroll();\n                    this.adapter.visitRendered(this);\n                    if (!isPreview) {\n                        this.complete();\n                    }\n                }\n            });\n        }\n    }\n    followRedirect() {\n        var _a;\n        if (this.redirectedToLocation && !this.followedRedirect && ((_a = this.response) === null || _a === void 0 ? void 0 : _a.redirected)) {\n            this.adapter.visitProposedToLocation(this.redirectedToLocation, {\n                action: \"replace\",\n                response: this.response,\n                shouldCacheSnapshot: false,\n                willRender: false,\n            });\n            this.followedRedirect = true;\n        }\n    }\n    goToSamePageAnchor() {\n        if (this.isSamePage) {\n            this.render(async () => {\n                this.cacheSnapshot();\n                this.performScroll();\n                this.changeHistory();\n                this.adapter.visitRendered(this);\n            });\n        }\n    }\n    prepareRequest(request) {\n        if (this.acceptsStreamResponse) {\n            request.acceptResponseType(StreamMessage.contentType);\n        }\n    }\n    requestStarted() {\n        this.startRequest();\n    }\n    requestPreventedHandlingResponse(_request, _response) { }\n    async requestSucceededWithResponse(request, response) {\n        const responseHTML = await response.responseHTML;\n        const { redirected, statusCode } = response;\n        if (responseHTML == undefined) {\n            this.recordResponse({\n                statusCode: SystemStatusCode.contentTypeMismatch,\n                redirected,\n            });\n        }\n        else {\n            this.redirectedToLocation = response.redirected ? response.location : undefined;\n            this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n        }\n    }\n    async requestFailedWithResponse(request, response) {\n        const responseHTML = await response.responseHTML;\n        const { redirected, statusCode } = response;\n        if (responseHTML == undefined) {\n            this.recordResponse({\n                statusCode: SystemStatusCode.contentTypeMismatch,\n                redirected,\n            });\n        }\n        else {\n            this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n        }\n    }\n    requestErrored(_request, _error) {\n        this.recordResponse({\n            statusCode: SystemStatusCode.networkFailure,\n            redirected: false,\n        });\n    }\n    requestFinished() {\n        this.finishRequest();\n    }\n    performScroll() {\n        if (!this.scrolled && !this.view.forceReloaded) {\n            if (this.action == \"restore\") {\n                this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop();\n            }\n            else {\n                this.scrollToAnchor() || this.view.scrollToTop();\n            }\n            if (this.isSamePage) {\n                this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation, this.location);\n            }\n            this.scrolled = true;\n        }\n    }\n    scrollToRestoredPosition() {\n        const { scrollPosition } = this.restorationData;\n        if (scrollPosition) {\n            this.view.scrollToPosition(scrollPosition);\n            return true;\n        }\n    }\n    scrollToAnchor() {\n        const anchor = getAnchor(this.location);\n        if (anchor != null) {\n            this.view.scrollToAnchor(anchor);\n            return true;\n        }\n    }\n    recordTimingMetric(metric) {\n        this.timingMetrics[metric] = new Date().getTime();\n    }\n    getTimingMetrics() {\n        return Object.assign({}, this.timingMetrics);\n    }\n    getHistoryMethodForAction(action) {\n        switch (action) {\n            case \"replace\":\n                return history.replaceState;\n            case \"advance\":\n            case \"restore\":\n                return history.pushState;\n        }\n    }\n    hasPreloadedResponse() {\n        return typeof this.response == \"object\";\n    }\n    shouldIssueRequest() {\n        if (this.isSamePage) {\n            return false;\n        }\n        else if (this.action == \"restore\") {\n            return !this.hasCachedSnapshot();\n        }\n        else {\n            return this.willRender;\n        }\n    }\n    cacheSnapshot() {\n        if (!this.snapshotCached) {\n            this.view.cacheSnapshot(this.snapshot).then((snapshot) => snapshot && this.visitCachedSnapshot(snapshot));\n            this.snapshotCached = true;\n        }\n    }\n    async render(callback) {\n        this.cancelRender();\n        await new Promise((resolve) => {\n            this.frame = requestAnimationFrame(() => resolve());\n        });\n        await callback();\n        delete this.frame;\n    }\n    cancelRender() {\n        if (this.frame) {\n            cancelAnimationFrame(this.frame);\n            delete this.frame;\n        }\n    }\n}\nfunction isSuccessful(statusCode) {\n    return statusCode >= 200 && statusCode < 300;\n}\n\nclass BrowserAdapter {\n    constructor(session) {\n        this.progressBar = new ProgressBar();\n        this.showProgressBar = () => {\n            this.progressBar.show();\n        };\n        this.session = session;\n    }\n    visitProposedToLocation(location, options) {\n        this.navigator.startVisit(location, (options === null || options === void 0 ? void 0 : options.restorationIdentifier) || uuid(), options);\n    }\n    visitStarted(visit) {\n        this.location = visit.location;\n        visit.loadCachedSnapshot();\n        visit.issueRequest();\n        visit.goToSamePageAnchor();\n    }\n    visitRequestStarted(visit) {\n        this.progressBar.setValue(0);\n        if (visit.hasCachedSnapshot() || visit.action != \"restore\") {\n            this.showVisitProgressBarAfterDelay();\n        }\n        else {\n            this.showProgressBar();\n        }\n    }\n    visitRequestCompleted(visit) {\n        visit.loadResponse();\n    }\n    visitRequestFailedWithStatusCode(visit, statusCode) {\n        switch (statusCode) {\n            case SystemStatusCode.networkFailure:\n            case SystemStatusCode.timeoutFailure:\n            case SystemStatusCode.contentTypeMismatch:\n                return this.reload({\n                    reason: \"request_failed\",\n                    context: {\n                        statusCode,\n                    },\n                });\n            default:\n                return visit.loadResponse();\n        }\n    }\n    visitRequestFinished(_visit) {\n        this.progressBar.setValue(1);\n        this.hideVisitProgressBar();\n    }\n    visitCompleted(_visit) { }\n    pageInvalidated(reason) {\n        this.reload(reason);\n    }\n    visitFailed(_visit) { }\n    visitRendered(_visit) { }\n    formSubmissionStarted(_formSubmission) {\n        this.progressBar.setValue(0);\n        this.showFormProgressBarAfterDelay();\n    }\n    formSubmissionFinished(_formSubmission) {\n        this.progressBar.setValue(1);\n        this.hideFormProgressBar();\n    }\n    showVisitProgressBarAfterDelay() {\n        this.visitProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n    }\n    hideVisitProgressBar() {\n        this.progressBar.hide();\n        if (this.visitProgressBarTimeout != null) {\n            window.clearTimeout(this.visitProgressBarTimeout);\n            delete this.visitProgressBarTimeout;\n        }\n    }\n    showFormProgressBarAfterDelay() {\n        if (this.formProgressBarTimeout == null) {\n            this.formProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n        }\n    }\n    hideFormProgressBar() {\n        this.progressBar.hide();\n        if (this.formProgressBarTimeout != null) {\n            window.clearTimeout(this.formProgressBarTimeout);\n            delete this.formProgressBarTimeout;\n        }\n    }\n    reload(reason) {\n        var _a;\n        dispatch(\"turbo:reload\", { detail: reason });\n        window.location.href = ((_a = this.location) === null || _a === void 0 ? void 0 : _a.toString()) || window.location.href;\n    }\n    get navigator() {\n        return this.session.navigator;\n    }\n}\n\nclass CacheObserver {\n    constructor() {\n        this.selector = \"[data-turbo-temporary]\";\n        this.deprecatedSelector = \"[data-turbo-cache=false]\";\n        this.started = false;\n        this.removeTemporaryElements = ((_event) => {\n            for (const element of this.temporaryElements) {\n                element.remove();\n            }\n        });\n    }\n    start() {\n        if (!this.started) {\n            this.started = true;\n            addEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.started = false;\n            removeEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n        }\n    }\n    get temporaryElements() {\n        return [...document.querySelectorAll(this.selector), ...this.temporaryElementsWithDeprecation];\n    }\n    get temporaryElementsWithDeprecation() {\n        const elements = document.querySelectorAll(this.deprecatedSelector);\n        if (elements.length) {\n            console.warn(`The ${this.deprecatedSelector} selector is deprecated and will be removed in a future version. Use ${this.selector} instead.`);\n        }\n        return [...elements];\n    }\n}\n\nclass FrameRedirector {\n    constructor(session, element) {\n        this.session = session;\n        this.element = element;\n        this.linkInterceptor = new LinkInterceptor(this, element);\n        this.formSubmitObserver = new FormSubmitObserver(this, element);\n    }\n    start() {\n        this.linkInterceptor.start();\n        this.formSubmitObserver.start();\n    }\n    stop() {\n        this.linkInterceptor.stop();\n        this.formSubmitObserver.stop();\n    }\n    shouldInterceptLinkClick(element, _location, _event) {\n        return this.shouldRedirect(element);\n    }\n    linkClickIntercepted(element, url, event) {\n        const frame = this.findFrameElement(element);\n        if (frame) {\n            frame.delegate.linkClickIntercepted(element, url, event);\n        }\n    }\n    willSubmitForm(element, submitter) {\n        return (element.closest(\"turbo-frame\") == null &&\n            this.shouldSubmit(element, submitter) &&\n            this.shouldRedirect(element, submitter));\n    }\n    formSubmitted(element, submitter) {\n        const frame = this.findFrameElement(element, submitter);\n        if (frame) {\n            frame.delegate.formSubmitted(element, submitter);\n        }\n    }\n    shouldSubmit(form, submitter) {\n        var _a;\n        const action = getAction(form, submitter);\n        const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n        const rootLocation = expandURL((_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : \"/\");\n        return this.shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation);\n    }\n    shouldRedirect(element, submitter) {\n        const isNavigatable = element instanceof HTMLFormElement\n            ? this.session.submissionIsNavigatable(element, submitter)\n            : this.session.elementIsNavigatable(element);\n        if (isNavigatable) {\n            const frame = this.findFrameElement(element, submitter);\n            return frame ? frame != element.closest(\"turbo-frame\") : false;\n        }\n        else {\n            return false;\n        }\n    }\n    findFrameElement(element, submitter) {\n        const id = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute(\"data-turbo-frame\")) || element.getAttribute(\"data-turbo-frame\");\n        if (id && id != \"_top\") {\n            const frame = this.element.querySelector(`#${id}:not([disabled])`);\n            if (frame instanceof FrameElement) {\n                return frame;\n            }\n        }\n    }\n}\n\nclass History {\n    constructor(delegate) {\n        this.restorationIdentifier = uuid();\n        this.restorationData = {};\n        this.started = false;\n        this.pageLoaded = false;\n        this.onPopState = (event) => {\n            if (this.shouldHandlePopState()) {\n                const { turbo } = event.state || {};\n                if (turbo) {\n                    this.location = new URL(window.location.href);\n                    const { restorationIdentifier } = turbo;\n                    this.restorationIdentifier = restorationIdentifier;\n                    this.delegate.historyPoppedToLocationWithRestorationIdentifier(this.location, restorationIdentifier);\n                }\n            }\n        };\n        this.onPageLoad = async (_event) => {\n            await nextMicrotask();\n            this.pageLoaded = true;\n        };\n        this.delegate = delegate;\n    }\n    start() {\n        if (!this.started) {\n            addEventListener(\"popstate\", this.onPopState, false);\n            addEventListener(\"load\", this.onPageLoad, false);\n            this.started = true;\n            this.replace(new URL(window.location.href));\n        }\n    }\n    stop() {\n        if (this.started) {\n            removeEventListener(\"popstate\", this.onPopState, false);\n            removeEventListener(\"load\", this.onPageLoad, false);\n            this.started = false;\n        }\n    }\n    push(location, restorationIdentifier) {\n        this.update(history.pushState, location, restorationIdentifier);\n    }\n    replace(location, restorationIdentifier) {\n        this.update(history.replaceState, location, restorationIdentifier);\n    }\n    update(method, location, restorationIdentifier = uuid()) {\n        const state = { turbo: { restorationIdentifier } };\n        method.call(history, state, \"\", location.href);\n        this.location = location;\n        this.restorationIdentifier = restorationIdentifier;\n    }\n    getRestorationDataForIdentifier(restorationIdentifier) {\n        return this.restorationData[restorationIdentifier] || {};\n    }\n    updateRestorationData(additionalData) {\n        const { restorationIdentifier } = this;\n        const restorationData = this.restorationData[restorationIdentifier];\n        this.restorationData[restorationIdentifier] = Object.assign(Object.assign({}, restorationData), additionalData);\n    }\n    assumeControlOfScrollRestoration() {\n        var _a;\n        if (!this.previousScrollRestoration) {\n            this.previousScrollRestoration = (_a = history.scrollRestoration) !== null && _a !== void 0 ? _a : \"auto\";\n            history.scrollRestoration = \"manual\";\n        }\n    }\n    relinquishControlOfScrollRestoration() {\n        if (this.previousScrollRestoration) {\n            history.scrollRestoration = this.previousScrollRestoration;\n            delete this.previousScrollRestoration;\n        }\n    }\n    shouldHandlePopState() {\n        return this.pageIsLoaded();\n    }\n    pageIsLoaded() {\n        return this.pageLoaded || document.readyState == \"complete\";\n    }\n}\n\nclass Navigator {\n    constructor(delegate) {\n        this.delegate = delegate;\n    }\n    proposeVisit(location, options = {}) {\n        if (this.delegate.allowsVisitingLocationWithAction(location, options.action)) {\n            if (locationIsVisitable(location, this.view.snapshot.rootLocation)) {\n                this.delegate.visitProposedToLocation(location, options);\n            }\n            else {\n                window.location.href = location.toString();\n            }\n        }\n    }\n    startVisit(locatable, restorationIdentifier, options = {}) {\n        this.stop();\n        this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, Object.assign({ referrer: this.location }, options));\n        this.currentVisit.start();\n    }\n    submitForm(form, submitter) {\n        this.stop();\n        this.formSubmission = new FormSubmission(this, form, submitter, true);\n        this.formSubmission.start();\n    }\n    stop() {\n        if (this.formSubmission) {\n            this.formSubmission.stop();\n            delete this.formSubmission;\n        }\n        if (this.currentVisit) {\n            this.currentVisit.cancel();\n            delete this.currentVisit;\n        }\n    }\n    get adapter() {\n        return this.delegate.adapter;\n    }\n    get view() {\n        return this.delegate.view;\n    }\n    get history() {\n        return this.delegate.history;\n    }\n    formSubmissionStarted(formSubmission) {\n        if (typeof this.adapter.formSubmissionStarted === \"function\") {\n            this.adapter.formSubmissionStarted(formSubmission);\n        }\n    }\n    async formSubmissionSucceededWithResponse(formSubmission, fetchResponse) {\n        if (formSubmission == this.formSubmission) {\n            const responseHTML = await fetchResponse.responseHTML;\n            if (responseHTML) {\n                const shouldCacheSnapshot = formSubmission.isSafe;\n                if (!shouldCacheSnapshot) {\n                    this.view.clearSnapshotCache();\n                }\n                const { statusCode, redirected } = fetchResponse;\n                const action = this.getActionForFormSubmission(formSubmission);\n                const visitOptions = {\n                    action,\n                    shouldCacheSnapshot,\n                    response: { statusCode, responseHTML, redirected },\n                };\n                this.proposeVisit(fetchResponse.location, visitOptions);\n            }\n        }\n    }\n    async formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n        const responseHTML = await fetchResponse.responseHTML;\n        if (responseHTML) {\n            const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n            if (fetchResponse.serverError) {\n                await this.view.renderError(snapshot, this.currentVisit);\n            }\n            else {\n                await this.view.renderPage(snapshot, false, true, this.currentVisit);\n            }\n            this.view.scrollToTop();\n            this.view.clearSnapshotCache();\n        }\n    }\n    formSubmissionErrored(formSubmission, error) {\n        console.error(error);\n    }\n    formSubmissionFinished(formSubmission) {\n        if (typeof this.adapter.formSubmissionFinished === \"function\") {\n            this.adapter.formSubmissionFinished(formSubmission);\n        }\n    }\n    visitStarted(visit) {\n        this.delegate.visitStarted(visit);\n    }\n    visitCompleted(visit) {\n        this.delegate.visitCompleted(visit);\n    }\n    locationWithActionIsSamePage(location, action) {\n        const anchor = getAnchor(location);\n        const currentAnchor = getAnchor(this.view.lastRenderedLocation);\n        const isRestorationToTop = action === \"restore\" && typeof anchor === \"undefined\";\n        return (action !== \"replace\" &&\n            getRequestURL(location) === getRequestURL(this.view.lastRenderedLocation) &&\n            (isRestorationToTop || (anchor != null && anchor !== currentAnchor)));\n    }\n    visitScrolledToSamePageLocation(oldURL, newURL) {\n        this.delegate.visitScrolledToSamePageLocation(oldURL, newURL);\n    }\n    get location() {\n        return this.history.location;\n    }\n    get restorationIdentifier() {\n        return this.history.restorationIdentifier;\n    }\n    getActionForFormSubmission({ submitter, formElement }) {\n        return getVisitAction(submitter, formElement) || \"advance\";\n    }\n}\n\nvar PageStage;\n(function (PageStage) {\n    PageStage[PageStage[\"initial\"] = 0] = \"initial\";\n    PageStage[PageStage[\"loading\"] = 1] = \"loading\";\n    PageStage[PageStage[\"interactive\"] = 2] = \"interactive\";\n    PageStage[PageStage[\"complete\"] = 3] = \"complete\";\n})(PageStage || (PageStage = {}));\nclass PageObserver {\n    constructor(delegate) {\n        this.stage = PageStage.initial;\n        this.started = false;\n        this.interpretReadyState = () => {\n            const { readyState } = this;\n            if (readyState == \"interactive\") {\n                this.pageIsInteractive();\n            }\n            else if (readyState == \"complete\") {\n                this.pageIsComplete();\n            }\n        };\n        this.pageWillUnload = () => {\n            this.delegate.pageWillUnload();\n        };\n        this.delegate = delegate;\n    }\n    start() {\n        if (!this.started) {\n            if (this.stage == PageStage.initial) {\n                this.stage = PageStage.loading;\n            }\n            document.addEventListener(\"readystatechange\", this.interpretReadyState, false);\n            addEventListener(\"pagehide\", this.pageWillUnload, false);\n            this.started = true;\n        }\n    }\n    stop() {\n        if (this.started) {\n            document.removeEventListener(\"readystatechange\", this.interpretReadyState, false);\n            removeEventListener(\"pagehide\", this.pageWillUnload, false);\n            this.started = false;\n        }\n    }\n    pageIsInteractive() {\n        if (this.stage == PageStage.loading) {\n            this.stage = PageStage.interactive;\n            this.delegate.pageBecameInteractive();\n        }\n    }\n    pageIsComplete() {\n        this.pageIsInteractive();\n        if (this.stage == PageStage.interactive) {\n            this.stage = PageStage.complete;\n            this.delegate.pageLoaded();\n        }\n    }\n    get readyState() {\n        return document.readyState;\n    }\n}\n\nclass ScrollObserver {\n    constructor(delegate) {\n        this.started = false;\n        this.onScroll = () => {\n            this.updatePosition({ x: window.pageXOffset, y: window.pageYOffset });\n        };\n        this.delegate = delegate;\n    }\n    start() {\n        if (!this.started) {\n            addEventListener(\"scroll\", this.onScroll, false);\n            this.onScroll();\n            this.started = true;\n        }\n    }\n    stop() {\n        if (this.started) {\n            removeEventListener(\"scroll\", this.onScroll, false);\n            this.started = false;\n        }\n    }\n    updatePosition(position) {\n        this.delegate.scrollPositionChanged(position);\n    }\n}\n\nclass StreamMessageRenderer {\n    render({ fragment }) {\n        Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), () => document.documentElement.appendChild(fragment));\n    }\n    enteringBardo(currentPermanentElement, newPermanentElement) {\n        newPermanentElement.replaceWith(currentPermanentElement.cloneNode(true));\n    }\n    leavingBardo() { }\n}\nfunction getPermanentElementMapForFragment(fragment) {\n    const permanentElementsInDocument = queryPermanentElementsAll(document.documentElement);\n    const permanentElementMap = {};\n    for (const permanentElementInDocument of permanentElementsInDocument) {\n        const { id } = permanentElementInDocument;\n        for (const streamElement of fragment.querySelectorAll(\"turbo-stream\")) {\n            const elementInStream = getPermanentElementById(streamElement.templateElement.content, id);\n            if (elementInStream) {\n                permanentElementMap[id] = [permanentElementInDocument, elementInStream];\n            }\n        }\n    }\n    return permanentElementMap;\n}\n\nclass StreamObserver {\n    constructor(delegate) {\n        this.sources = new Set();\n        this.started = false;\n        this.inspectFetchResponse = ((event) => {\n            const response = fetchResponseFromEvent(event);\n            if (response && fetchResponseIsStream(response)) {\n                event.preventDefault();\n                this.receiveMessageResponse(response);\n            }\n        });\n        this.receiveMessageEvent = (event) => {\n            if (this.started && typeof event.data == \"string\") {\n                this.receiveMessageHTML(event.data);\n            }\n        };\n        this.delegate = delegate;\n    }\n    start() {\n        if (!this.started) {\n            this.started = true;\n            addEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.started = false;\n            removeEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n        }\n    }\n    connectStreamSource(source) {\n        if (!this.streamSourceIsConnected(source)) {\n            this.sources.add(source);\n            source.addEventListener(\"message\", this.receiveMessageEvent, false);\n        }\n    }\n    disconnectStreamSource(source) {\n        if (this.streamSourceIsConnected(source)) {\n            this.sources.delete(source);\n            source.removeEventListener(\"message\", this.receiveMessageEvent, false);\n        }\n    }\n    streamSourceIsConnected(source) {\n        return this.sources.has(source);\n    }\n    async receiveMessageResponse(response) {\n        const html = await response.responseHTML;\n        if (html) {\n            this.receiveMessageHTML(html);\n        }\n    }\n    receiveMessageHTML(html) {\n        this.delegate.receivedMessageFromStream(StreamMessage.wrap(html));\n    }\n}\nfunction fetchResponseFromEvent(event) {\n    var _a;\n    const fetchResponse = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.fetchResponse;\n    if (fetchResponse instanceof FetchResponse) {\n        return fetchResponse;\n    }\n}\nfunction fetchResponseIsStream(response) {\n    var _a;\n    const contentType = (_a = response.contentType) !== null && _a !== void 0 ? _a : \"\";\n    return contentType.startsWith(StreamMessage.contentType);\n}\n\nclass ErrorRenderer extends Renderer {\n    static renderElement(currentElement, newElement) {\n        const { documentElement, body } = document;\n        documentElement.replaceChild(newElement, body);\n    }\n    async render() {\n        this.replaceHeadAndBody();\n        this.activateScriptElements();\n    }\n    replaceHeadAndBody() {\n        const { documentElement, head } = document;\n        documentElement.replaceChild(this.newHead, head);\n        this.renderElement(this.currentElement, this.newElement);\n    }\n    activateScriptElements() {\n        for (const replaceableElement of this.scriptElements) {\n            const parentNode = replaceableElement.parentNode;\n            if (parentNode) {\n                const element = activateScriptElement(replaceableElement);\n                parentNode.replaceChild(element, replaceableElement);\n            }\n        }\n    }\n    get newHead() {\n        return this.newSnapshot.headSnapshot.element;\n    }\n    get scriptElements() {\n        return document.documentElement.querySelectorAll(\"script\");\n    }\n}\n\nclass PageRenderer extends Renderer {\n    static renderElement(currentElement, newElement) {\n        if (document.body && newElement instanceof HTMLBodyElement) {\n            document.body.replaceWith(newElement);\n        }\n        else {\n            document.documentElement.appendChild(newElement);\n        }\n    }\n    get shouldRender() {\n        return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical;\n    }\n    get reloadReason() {\n        if (!this.newSnapshot.isVisitable) {\n            return {\n                reason: \"turbo_visit_control_is_reload\",\n            };\n        }\n        if (!this.trackedElementsAreIdentical) {\n            return {\n                reason: \"tracked_element_mismatch\",\n            };\n        }\n    }\n    async prepareToRender() {\n        await this.mergeHead();\n    }\n    async render() {\n        if (this.willRender) {\n            await this.replaceBody();\n        }\n    }\n    finishRendering() {\n        super.finishRendering();\n        if (!this.isPreview) {\n            this.focusFirstAutofocusableElement();\n        }\n    }\n    get currentHeadSnapshot() {\n        return this.currentSnapshot.headSnapshot;\n    }\n    get newHeadSnapshot() {\n        return this.newSnapshot.headSnapshot;\n    }\n    get newElement() {\n        return this.newSnapshot.element;\n    }\n    async mergeHead() {\n        const mergedHeadElements = this.mergeProvisionalElements();\n        const newStylesheetElements = this.copyNewHeadStylesheetElements();\n        this.copyNewHeadScriptElements();\n        await mergedHeadElements;\n        await newStylesheetElements;\n    }\n    async replaceBody() {\n        await this.preservingPermanentElements(async () => {\n            this.activateNewBody();\n            await this.assignNewBody();\n        });\n    }\n    get trackedElementsAreIdentical() {\n        return this.currentHeadSnapshot.trackedElementSignature == this.newHeadSnapshot.trackedElementSignature;\n    }\n    async copyNewHeadStylesheetElements() {\n        const loadingElements = [];\n        for (const element of this.newHeadStylesheetElements) {\n            loadingElements.push(waitForLoad(element));\n            document.head.appendChild(element);\n        }\n        await Promise.all(loadingElements);\n    }\n    copyNewHeadScriptElements() {\n        for (const element of this.newHeadScriptElements) {\n            document.head.appendChild(activateScriptElement(element));\n        }\n    }\n    async mergeProvisionalElements() {\n        const newHeadElements = [...this.newHeadProvisionalElements];\n        for (const element of this.currentHeadProvisionalElements) {\n            if (!this.isCurrentElementInElementList(element, newHeadElements)) {\n                document.head.removeChild(element);\n            }\n        }\n        for (const element of newHeadElements) {\n            document.head.appendChild(element);\n        }\n    }\n    isCurrentElementInElementList(element, elementList) {\n        for (const [index, newElement] of elementList.entries()) {\n            if (element.tagName == \"TITLE\") {\n                if (newElement.tagName != \"TITLE\") {\n                    continue;\n                }\n                if (element.innerHTML == newElement.innerHTML) {\n                    elementList.splice(index, 1);\n                    return true;\n                }\n            }\n            if (newElement.isEqualNode(element)) {\n                elementList.splice(index, 1);\n                return true;\n            }\n        }\n        return false;\n    }\n    removeCurrentHeadProvisionalElements() {\n        for (const element of this.currentHeadProvisionalElements) {\n            document.head.removeChild(element);\n        }\n    }\n    copyNewHeadProvisionalElements() {\n        for (const element of this.newHeadProvisionalElements) {\n            document.head.appendChild(element);\n        }\n    }\n    activateNewBody() {\n        document.adoptNode(this.newElement);\n        this.activateNewBodyScriptElements();\n    }\n    activateNewBodyScriptElements() {\n        for (const inertScriptElement of this.newBodyScriptElements) {\n            const activatedScriptElement = activateScriptElement(inertScriptElement);\n            inertScriptElement.replaceWith(activatedScriptElement);\n        }\n    }\n    async assignNewBody() {\n        await this.renderElement(this.currentElement, this.newElement);\n    }\n    get newHeadStylesheetElements() {\n        return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot);\n    }\n    get newHeadScriptElements() {\n        return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot);\n    }\n    get currentHeadProvisionalElements() {\n        return this.currentHeadSnapshot.provisionalElements;\n    }\n    get newHeadProvisionalElements() {\n        return this.newHeadSnapshot.provisionalElements;\n    }\n    get newBodyScriptElements() {\n        return this.newElement.querySelectorAll(\"script\");\n    }\n}\n\nclass SnapshotCache {\n    constructor(size) {\n        this.keys = [];\n        this.snapshots = {};\n        this.size = size;\n    }\n    has(location) {\n        return toCacheKey(location) in this.snapshots;\n    }\n    get(location) {\n        if (this.has(location)) {\n            const snapshot = this.read(location);\n            this.touch(location);\n            return snapshot;\n        }\n    }\n    put(location, snapshot) {\n        this.write(location, snapshot);\n        this.touch(location);\n        return snapshot;\n    }\n    clear() {\n        this.snapshots = {};\n    }\n    read(location) {\n        return this.snapshots[toCacheKey(location)];\n    }\n    write(location, snapshot) {\n        this.snapshots[toCacheKey(location)] = snapshot;\n    }\n    touch(location) {\n        const key = toCacheKey(location);\n        const index = this.keys.indexOf(key);\n        if (index > -1)\n            this.keys.splice(index, 1);\n        this.keys.unshift(key);\n        this.trim();\n    }\n    trim() {\n        for (const key of this.keys.splice(this.size)) {\n            delete this.snapshots[key];\n        }\n    }\n}\n\nclass PageView extends View {\n    constructor() {\n        super(...arguments);\n        this.snapshotCache = new SnapshotCache(10);\n        this.lastRenderedLocation = new URL(location.href);\n        this.forceReloaded = false;\n    }\n    renderPage(snapshot, isPreview = false, willRender = true, visit) {\n        const renderer = new PageRenderer(this.snapshot, snapshot, PageRenderer.renderElement, isPreview, willRender);\n        if (!renderer.shouldRender) {\n            this.forceReloaded = true;\n        }\n        else {\n            visit === null || visit === void 0 ? void 0 : visit.changeHistory();\n        }\n        return this.render(renderer);\n    }\n    renderError(snapshot, visit) {\n        visit === null || visit === void 0 ? void 0 : visit.changeHistory();\n        const renderer = new ErrorRenderer(this.snapshot, snapshot, ErrorRenderer.renderElement, false);\n        return this.render(renderer);\n    }\n    clearSnapshotCache() {\n        this.snapshotCache.clear();\n    }\n    async cacheSnapshot(snapshot = this.snapshot) {\n        if (snapshot.isCacheable) {\n            this.delegate.viewWillCacheSnapshot();\n            const { lastRenderedLocation: location } = this;\n            await nextEventLoopTick();\n            const cachedSnapshot = snapshot.clone();\n            this.snapshotCache.put(location, cachedSnapshot);\n            return cachedSnapshot;\n        }\n    }\n    getCachedSnapshotForLocation(location) {\n        return this.snapshotCache.get(location);\n    }\n    get snapshot() {\n        return PageSnapshot.fromElement(this.element);\n    }\n}\n\nclass Preloader {\n    constructor(delegate) {\n        this.selector = \"a[data-turbo-preload]\";\n        this.delegate = delegate;\n    }\n    get snapshotCache() {\n        return this.delegate.navigator.view.snapshotCache;\n    }\n    start() {\n        if (document.readyState === \"loading\") {\n            return document.addEventListener(\"DOMContentLoaded\", () => {\n                this.preloadOnLoadLinksForView(document.body);\n            });\n        }\n        else {\n            this.preloadOnLoadLinksForView(document.body);\n        }\n    }\n    preloadOnLoadLinksForView(element) {\n        for (const link of element.querySelectorAll(this.selector)) {\n            this.preloadURL(link);\n        }\n    }\n    async preloadURL(link) {\n        const location = new URL(link.href);\n        if (this.snapshotCache.has(location)) {\n            return;\n        }\n        try {\n            const response = await fetch(location.toString(), { headers: { \"VND.PREFETCH\": \"true\", Accept: \"text/html\" } });\n            const responseText = await response.text();\n            const snapshot = PageSnapshot.fromHTMLString(responseText);\n            this.snapshotCache.put(location, snapshot);\n        }\n        catch (_) {\n        }\n    }\n}\n\nclass Session {\n    constructor() {\n        this.navigator = new Navigator(this);\n        this.history = new History(this);\n        this.preloader = new Preloader(this);\n        this.view = new PageView(this, document.documentElement);\n        this.adapter = new BrowserAdapter(this);\n        this.pageObserver = new PageObserver(this);\n        this.cacheObserver = new CacheObserver();\n        this.linkClickObserver = new LinkClickObserver(this, window);\n        this.formSubmitObserver = new FormSubmitObserver(this, document);\n        this.scrollObserver = new ScrollObserver(this);\n        this.streamObserver = new StreamObserver(this);\n        this.formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement);\n        this.frameRedirector = new FrameRedirector(this, document.documentElement);\n        this.streamMessageRenderer = new StreamMessageRenderer();\n        this.drive = true;\n        this.enabled = true;\n        this.progressBarDelay = 500;\n        this.started = false;\n        this.formMode = \"on\";\n    }\n    start() {\n        if (!this.started) {\n            this.pageObserver.start();\n            this.cacheObserver.start();\n            this.formLinkClickObserver.start();\n            this.linkClickObserver.start();\n            this.formSubmitObserver.start();\n            this.scrollObserver.start();\n            this.streamObserver.start();\n            this.frameRedirector.start();\n            this.history.start();\n            this.preloader.start();\n            this.started = true;\n            this.enabled = true;\n        }\n    }\n    disable() {\n        this.enabled = false;\n    }\n    stop() {\n        if (this.started) {\n            this.pageObserver.stop();\n            this.cacheObserver.stop();\n            this.formLinkClickObserver.stop();\n            this.linkClickObserver.stop();\n            this.formSubmitObserver.stop();\n            this.scrollObserver.stop();\n            this.streamObserver.stop();\n            this.frameRedirector.stop();\n            this.history.stop();\n            this.started = false;\n        }\n    }\n    registerAdapter(adapter) {\n        this.adapter = adapter;\n    }\n    visit(location, options = {}) {\n        const frameElement = options.frame ? document.getElementById(options.frame) : null;\n        if (frameElement instanceof FrameElement) {\n            frameElement.src = location.toString();\n            frameElement.loaded;\n        }\n        else {\n            this.navigator.proposeVisit(expandURL(location), options);\n        }\n    }\n    connectStreamSource(source) {\n        this.streamObserver.connectStreamSource(source);\n    }\n    disconnectStreamSource(source) {\n        this.streamObserver.disconnectStreamSource(source);\n    }\n    renderStreamMessage(message) {\n        this.streamMessageRenderer.render(StreamMessage.wrap(message));\n    }\n    clearCache() {\n        this.view.clearSnapshotCache();\n    }\n    setProgressBarDelay(delay) {\n        this.progressBarDelay = delay;\n    }\n    setFormMode(mode) {\n        this.formMode = mode;\n    }\n    get location() {\n        return this.history.location;\n    }\n    get restorationIdentifier() {\n        return this.history.restorationIdentifier;\n    }\n    historyPoppedToLocationWithRestorationIdentifier(location, restorationIdentifier) {\n        if (this.enabled) {\n            this.navigator.startVisit(location, restorationIdentifier, {\n                action: \"restore\",\n                historyChanged: true,\n            });\n        }\n        else {\n            this.adapter.pageInvalidated({\n                reason: \"turbo_disabled\",\n            });\n        }\n    }\n    scrollPositionChanged(position) {\n        this.history.updateRestorationData({ scrollPosition: position });\n    }\n    willSubmitFormLinkToLocation(link, location) {\n        return this.elementIsNavigatable(link) && locationIsVisitable(location, this.snapshot.rootLocation);\n    }\n    submittedFormLinkToLocation() { }\n    willFollowLinkToLocation(link, location, event) {\n        return (this.elementIsNavigatable(link) &&\n            locationIsVisitable(location, this.snapshot.rootLocation) &&\n            this.applicationAllowsFollowingLinkToLocation(link, location, event));\n    }\n    followedLinkToLocation(link, location) {\n        const action = this.getActionForLink(link);\n        const acceptsStreamResponse = link.hasAttribute(\"data-turbo-stream\");\n        this.visit(location.href, { action, acceptsStreamResponse });\n    }\n    allowsVisitingLocationWithAction(location, action) {\n        return this.locationWithActionIsSamePage(location, action) || this.applicationAllowsVisitingLocation(location);\n    }\n    visitProposedToLocation(location, options) {\n        extendURLWithDeprecatedProperties(location);\n        this.adapter.visitProposedToLocation(location, options);\n    }\n    visitStarted(visit) {\n        if (!visit.acceptsStreamResponse) {\n            markAsBusy(document.documentElement);\n        }\n        extendURLWithDeprecatedProperties(visit.location);\n        if (!visit.silent) {\n            this.notifyApplicationAfterVisitingLocation(visit.location, visit.action);\n        }\n    }\n    visitCompleted(visit) {\n        clearBusyState(document.documentElement);\n        this.notifyApplicationAfterPageLoad(visit.getTimingMetrics());\n    }\n    locationWithActionIsSamePage(location, action) {\n        return this.navigator.locationWithActionIsSamePage(location, action);\n    }\n    visitScrolledToSamePageLocation(oldURL, newURL) {\n        this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL);\n    }\n    willSubmitForm(form, submitter) {\n        const action = getAction(form, submitter);\n        return (this.submissionIsNavigatable(form, submitter) &&\n            locationIsVisitable(expandURL(action), this.snapshot.rootLocation));\n    }\n    formSubmitted(form, submitter) {\n        this.navigator.submitForm(form, submitter);\n    }\n    pageBecameInteractive() {\n        this.view.lastRenderedLocation = this.location;\n        this.notifyApplicationAfterPageLoad();\n    }\n    pageLoaded() {\n        this.history.assumeControlOfScrollRestoration();\n    }\n    pageWillUnload() {\n        this.history.relinquishControlOfScrollRestoration();\n    }\n    receivedMessageFromStream(message) {\n        this.renderStreamMessage(message);\n    }\n    viewWillCacheSnapshot() {\n        var _a;\n        if (!((_a = this.navigator.currentVisit) === null || _a === void 0 ? void 0 : _a.silent)) {\n            this.notifyApplicationBeforeCachingSnapshot();\n        }\n    }\n    allowsImmediateRender({ element }, options) {\n        const event = this.notifyApplicationBeforeRender(element, options);\n        const { defaultPrevented, detail: { render }, } = event;\n        if (this.view.renderer && render) {\n            this.view.renderer.renderElement = render;\n        }\n        return !defaultPrevented;\n    }\n    viewRenderedSnapshot(_snapshot, _isPreview) {\n        this.view.lastRenderedLocation = this.history.location;\n        this.notifyApplicationAfterRender();\n    }\n    preloadOnLoadLinksForView(element) {\n        this.preloader.preloadOnLoadLinksForView(element);\n    }\n    viewInvalidated(reason) {\n        this.adapter.pageInvalidated(reason);\n    }\n    frameLoaded(frame) {\n        this.notifyApplicationAfterFrameLoad(frame);\n    }\n    frameRendered(fetchResponse, frame) {\n        this.notifyApplicationAfterFrameRender(fetchResponse, frame);\n    }\n    applicationAllowsFollowingLinkToLocation(link, location, ev) {\n        const event = this.notifyApplicationAfterClickingLinkToLocation(link, location, ev);\n        return !event.defaultPrevented;\n    }\n    applicationAllowsVisitingLocation(location) {\n        const event = this.notifyApplicationBeforeVisitingLocation(location);\n        return !event.defaultPrevented;\n    }\n    notifyApplicationAfterClickingLinkToLocation(link, location, event) {\n        return dispatch(\"turbo:click\", {\n            target: link,\n            detail: { url: location.href, originalEvent: event },\n            cancelable: true,\n        });\n    }\n    notifyApplicationBeforeVisitingLocation(location) {\n        return dispatch(\"turbo:before-visit\", {\n            detail: { url: location.href },\n            cancelable: true,\n        });\n    }\n    notifyApplicationAfterVisitingLocation(location, action) {\n        return dispatch(\"turbo:visit\", { detail: { url: location.href, action } });\n    }\n    notifyApplicationBeforeCachingSnapshot() {\n        return dispatch(\"turbo:before-cache\");\n    }\n    notifyApplicationBeforeRender(newBody, options) {\n        return dispatch(\"turbo:before-render\", {\n            detail: Object.assign({ newBody }, options),\n            cancelable: true,\n        });\n    }\n    notifyApplicationAfterRender() {\n        return dispatch(\"turbo:render\");\n    }\n    notifyApplicationAfterPageLoad(timing = {}) {\n        return dispatch(\"turbo:load\", {\n            detail: { url: this.location.href, timing },\n        });\n    }\n    notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL) {\n        dispatchEvent(new HashChangeEvent(\"hashchange\", {\n            oldURL: oldURL.toString(),\n            newURL: newURL.toString(),\n        }));\n    }\n    notifyApplicationAfterFrameLoad(frame) {\n        return dispatch(\"turbo:frame-load\", { target: frame });\n    }\n    notifyApplicationAfterFrameRender(fetchResponse, frame) {\n        return dispatch(\"turbo:frame-render\", {\n            detail: { fetchResponse },\n            target: frame,\n            cancelable: true,\n        });\n    }\n    submissionIsNavigatable(form, submitter) {\n        if (this.formMode == \"off\") {\n            return false;\n        }\n        else {\n            const submitterIsNavigatable = submitter ? this.elementIsNavigatable(submitter) : true;\n            if (this.formMode == \"optin\") {\n                return submitterIsNavigatable && form.closest('[data-turbo=\"true\"]') != null;\n            }\n            else {\n                return submitterIsNavigatable && this.elementIsNavigatable(form);\n            }\n        }\n    }\n    elementIsNavigatable(element) {\n        const container = findClosestRecursively(element, \"[data-turbo]\");\n        const withinFrame = findClosestRecursively(element, \"turbo-frame\");\n        if (this.drive || withinFrame) {\n            if (container) {\n                return container.getAttribute(\"data-turbo\") != \"false\";\n            }\n            else {\n                return true;\n            }\n        }\n        else {\n            if (container) {\n                return container.getAttribute(\"data-turbo\") == \"true\";\n            }\n            else {\n                return false;\n            }\n        }\n    }\n    getActionForLink(link) {\n        return getVisitAction(link) || \"advance\";\n    }\n    get snapshot() {\n        return this.view.snapshot;\n    }\n}\nfunction extendURLWithDeprecatedProperties(url) {\n    Object.defineProperties(url, deprecatedLocationPropertyDescriptors);\n}\nconst deprecatedLocationPropertyDescriptors = {\n    absoluteURL: {\n        get() {\n            return this.toString();\n        },\n    },\n};\n\nclass Cache {\n    constructor(session) {\n        this.session = session;\n    }\n    clear() {\n        this.session.clearCache();\n    }\n    resetCacheControl() {\n        this.setCacheControl(\"\");\n    }\n    exemptPageFromCache() {\n        this.setCacheControl(\"no-cache\");\n    }\n    exemptPageFromPreview() {\n        this.setCacheControl(\"no-preview\");\n    }\n    setCacheControl(value) {\n        setMetaContent(\"turbo-cache-control\", value);\n    }\n}\n\nconst StreamActions = {\n    after() {\n        this.targetElements.forEach((e) => { var _a; return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e.nextSibling); });\n    },\n    append() {\n        this.removeDuplicateTargetChildren();\n        this.targetElements.forEach((e) => e.append(this.templateContent));\n    },\n    before() {\n        this.targetElements.forEach((e) => { var _a; return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e); });\n    },\n    prepend() {\n        this.removeDuplicateTargetChildren();\n        this.targetElements.forEach((e) => e.prepend(this.templateContent));\n    },\n    remove() {\n        this.targetElements.forEach((e) => e.remove());\n    },\n    replace() {\n        this.targetElements.forEach((e) => e.replaceWith(this.templateContent));\n    },\n    update() {\n        this.targetElements.forEach((targetElement) => {\n            targetElement.innerHTML = \"\";\n            targetElement.append(this.templateContent);\n        });\n    },\n};\n\nconst session = new Session();\nconst cache = new Cache(session);\nconst { navigator: navigator$1 } = session;\nfunction start() {\n    session.start();\n}\nfunction registerAdapter(adapter) {\n    session.registerAdapter(adapter);\n}\nfunction visit(location, options) {\n    session.visit(location, options);\n}\nfunction connectStreamSource(source) {\n    session.connectStreamSource(source);\n}\nfunction disconnectStreamSource(source) {\n    session.disconnectStreamSource(source);\n}\nfunction renderStreamMessage(message) {\n    session.renderStreamMessage(message);\n}\nfunction clearCache() {\n    console.warn(\"Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`\");\n    session.clearCache();\n}\nfunction setProgressBarDelay(delay) {\n    session.setProgressBarDelay(delay);\n}\nfunction setConfirmMethod(confirmMethod) {\n    FormSubmission.confirmMethod = confirmMethod;\n}\nfunction setFormMode(mode) {\n    session.setFormMode(mode);\n}\n\nvar Turbo = /*#__PURE__*/Object.freeze({\n    __proto__: null,\n    navigator: navigator$1,\n    session: session,\n    cache: cache,\n    PageRenderer: PageRenderer,\n    PageSnapshot: PageSnapshot,\n    FrameRenderer: FrameRenderer,\n    start: start,\n    registerAdapter: registerAdapter,\n    visit: visit,\n    connectStreamSource: connectStreamSource,\n    disconnectStreamSource: disconnectStreamSource,\n    renderStreamMessage: renderStreamMessage,\n    clearCache: clearCache,\n    setProgressBarDelay: setProgressBarDelay,\n    setConfirmMethod: setConfirmMethod,\n    setFormMode: setFormMode,\n    StreamActions: StreamActions\n});\n\nclass TurboFrameMissingError extends Error {\n}\n\nclass FrameController {\n    constructor(element) {\n        this.fetchResponseLoaded = (_fetchResponse) => { };\n        this.currentFetchRequest = null;\n        this.resolveVisitPromise = () => { };\n        this.connected = false;\n        this.hasBeenLoaded = false;\n        this.ignoredAttributes = new Set();\n        this.action = null;\n        this.visitCachedSnapshot = ({ element }) => {\n            const frame = element.querySelector(\"#\" + this.element.id);\n            if (frame && this.previousFrameElement) {\n                frame.replaceChildren(...this.previousFrameElement.children);\n            }\n            delete this.previousFrameElement;\n        };\n        this.element = element;\n        this.view = new FrameView(this, this.element);\n        this.appearanceObserver = new AppearanceObserver(this, this.element);\n        this.formLinkClickObserver = new FormLinkClickObserver(this, this.element);\n        this.linkInterceptor = new LinkInterceptor(this, this.element);\n        this.restorationIdentifier = uuid();\n        this.formSubmitObserver = new FormSubmitObserver(this, this.element);\n    }\n    connect() {\n        if (!this.connected) {\n            this.connected = true;\n            if (this.loadingStyle == FrameLoadingStyle.lazy) {\n                this.appearanceObserver.start();\n            }\n            else {\n                this.loadSourceURL();\n            }\n            this.formLinkClickObserver.start();\n            this.linkInterceptor.start();\n            this.formSubmitObserver.start();\n        }\n    }\n    disconnect() {\n        if (this.connected) {\n            this.connected = false;\n            this.appearanceObserver.stop();\n            this.formLinkClickObserver.stop();\n            this.linkInterceptor.stop();\n            this.formSubmitObserver.stop();\n        }\n    }\n    disabledChanged() {\n        if (this.loadingStyle == FrameLoadingStyle.eager) {\n            this.loadSourceURL();\n        }\n    }\n    sourceURLChanged() {\n        if (this.isIgnoringChangesTo(\"src\"))\n            return;\n        if (this.element.isConnected) {\n            this.complete = false;\n        }\n        if (this.loadingStyle == FrameLoadingStyle.eager || this.hasBeenLoaded) {\n            this.loadSourceURL();\n        }\n    }\n    sourceURLReloaded() {\n        const { src } = this.element;\n        this.ignoringChangesToAttribute(\"complete\", () => {\n            this.element.removeAttribute(\"complete\");\n        });\n        this.element.src = null;\n        this.element.src = src;\n        return this.element.loaded;\n    }\n    completeChanged() {\n        if (this.isIgnoringChangesTo(\"complete\"))\n            return;\n        this.loadSourceURL();\n    }\n    loadingStyleChanged() {\n        if (this.loadingStyle == FrameLoadingStyle.lazy) {\n            this.appearanceObserver.start();\n        }\n        else {\n            this.appearanceObserver.stop();\n            this.loadSourceURL();\n        }\n    }\n    async loadSourceURL() {\n        if (this.enabled && this.isActive && !this.complete && this.sourceURL) {\n            this.element.loaded = this.visit(expandURL(this.sourceURL));\n            this.appearanceObserver.stop();\n            await this.element.loaded;\n            this.hasBeenLoaded = true;\n        }\n    }\n    async loadResponse(fetchResponse) {\n        if (fetchResponse.redirected || (fetchResponse.succeeded && fetchResponse.isHTML)) {\n            this.sourceURL = fetchResponse.response.url;\n        }\n        try {\n            const html = await fetchResponse.responseHTML;\n            if (html) {\n                const document = parseHTMLDocument(html);\n                const pageSnapshot = PageSnapshot.fromDocument(document);\n                if (pageSnapshot.isVisitable) {\n                    await this.loadFrameResponse(fetchResponse, document);\n                }\n                else {\n                    await this.handleUnvisitableFrameResponse(fetchResponse);\n                }\n            }\n        }\n        finally {\n            this.fetchResponseLoaded = () => { };\n        }\n    }\n    elementAppearedInViewport(element) {\n        this.proposeVisitIfNavigatedWithAction(element, element);\n        this.loadSourceURL();\n    }\n    willSubmitFormLinkToLocation(link) {\n        return this.shouldInterceptNavigation(link);\n    }\n    submittedFormLinkToLocation(link, _location, form) {\n        const frame = this.findFrameElement(link);\n        if (frame)\n            form.setAttribute(\"data-turbo-frame\", frame.id);\n    }\n    shouldInterceptLinkClick(element, _location, _event) {\n        return this.shouldInterceptNavigation(element);\n    }\n    linkClickIntercepted(element, location) {\n        this.navigateFrame(element, location);\n    }\n    willSubmitForm(element, submitter) {\n        return element.closest(\"turbo-frame\") == this.element && this.shouldInterceptNavigation(element, submitter);\n    }\n    formSubmitted(element, submitter) {\n        if (this.formSubmission) {\n            this.formSubmission.stop();\n        }\n        this.formSubmission = new FormSubmission(this, element, submitter);\n        const { fetchRequest } = this.formSubmission;\n        this.prepareRequest(fetchRequest);\n        this.formSubmission.start();\n    }\n    prepareRequest(request) {\n        var _a;\n        request.headers[\"Turbo-Frame\"] = this.id;\n        if ((_a = this.currentNavigationElement) === null || _a === void 0 ? void 0 : _a.hasAttribute(\"data-turbo-stream\")) {\n            request.acceptResponseType(StreamMessage.contentType);\n        }\n    }\n    requestStarted(_request) {\n        markAsBusy(this.element);\n    }\n    requestPreventedHandlingResponse(_request, _response) {\n        this.resolveVisitPromise();\n    }\n    async requestSucceededWithResponse(request, response) {\n        await this.loadResponse(response);\n        this.resolveVisitPromise();\n    }\n    async requestFailedWithResponse(request, response) {\n        await this.loadResponse(response);\n        this.resolveVisitPromise();\n    }\n    requestErrored(request, error) {\n        console.error(error);\n        this.resolveVisitPromise();\n    }\n    requestFinished(_request) {\n        clearBusyState(this.element);\n    }\n    formSubmissionStarted({ formElement }) {\n        markAsBusy(formElement, this.findFrameElement(formElement));\n    }\n    formSubmissionSucceededWithResponse(formSubmission, response) {\n        const frame = this.findFrameElement(formSubmission.formElement, formSubmission.submitter);\n        frame.delegate.proposeVisitIfNavigatedWithAction(frame, formSubmission.formElement, formSubmission.submitter);\n        frame.delegate.loadResponse(response);\n        if (!formSubmission.isSafe) {\n            session.clearCache();\n        }\n    }\n    formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n        this.element.delegate.loadResponse(fetchResponse);\n        session.clearCache();\n    }\n    formSubmissionErrored(formSubmission, error) {\n        console.error(error);\n    }\n    formSubmissionFinished({ formElement }) {\n        clearBusyState(formElement, this.findFrameElement(formElement));\n    }\n    allowsImmediateRender({ element: newFrame }, options) {\n        const event = dispatch(\"turbo:before-frame-render\", {\n            target: this.element,\n            detail: Object.assign({ newFrame }, options),\n            cancelable: true,\n        });\n        const { defaultPrevented, detail: { render }, } = event;\n        if (this.view.renderer && render) {\n            this.view.renderer.renderElement = render;\n        }\n        return !defaultPrevented;\n    }\n    viewRenderedSnapshot(_snapshot, _isPreview) { }\n    preloadOnLoadLinksForView(element) {\n        session.preloadOnLoadLinksForView(element);\n    }\n    viewInvalidated() { }\n    willRenderFrame(currentElement, _newElement) {\n        this.previousFrameElement = currentElement.cloneNode(true);\n    }\n    async loadFrameResponse(fetchResponse, document) {\n        const newFrameElement = await this.extractForeignFrameElement(document.body);\n        if (newFrameElement) {\n            const snapshot = new Snapshot(newFrameElement);\n            const renderer = new FrameRenderer(this, this.view.snapshot, snapshot, FrameRenderer.renderElement, false, false);\n            if (this.view.renderPromise)\n                await this.view.renderPromise;\n            this.changeHistory();\n            await this.view.render(renderer);\n            this.complete = true;\n            session.frameRendered(fetchResponse, this.element);\n            session.frameLoaded(this.element);\n            this.fetchResponseLoaded(fetchResponse);\n        }\n        else if (this.willHandleFrameMissingFromResponse(fetchResponse)) {\n            this.handleFrameMissingFromResponse(fetchResponse);\n        }\n    }\n    async visit(url) {\n        var _a;\n        const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams(), this.element);\n        (_a = this.currentFetchRequest) === null || _a === void 0 ? void 0 : _a.cancel();\n        this.currentFetchRequest = request;\n        return new Promise((resolve) => {\n            this.resolveVisitPromise = () => {\n                this.resolveVisitPromise = () => { };\n                this.currentFetchRequest = null;\n                resolve();\n            };\n            request.perform();\n        });\n    }\n    navigateFrame(element, url, submitter) {\n        const frame = this.findFrameElement(element, submitter);\n        frame.delegate.proposeVisitIfNavigatedWithAction(frame, element, submitter);\n        this.withCurrentNavigationElement(element, () => {\n            frame.src = url;\n        });\n    }\n    proposeVisitIfNavigatedWithAction(frame, element, submitter) {\n        this.action = getVisitAction(submitter, element, frame);\n        if (this.action) {\n            const pageSnapshot = PageSnapshot.fromElement(frame).clone();\n            const { visitCachedSnapshot } = frame.delegate;\n            frame.delegate.fetchResponseLoaded = (fetchResponse) => {\n                if (frame.src) {\n                    const { statusCode, redirected } = fetchResponse;\n                    const responseHTML = frame.ownerDocument.documentElement.outerHTML;\n                    const response = { statusCode, redirected, responseHTML };\n                    const options = {\n                        response,\n                        visitCachedSnapshot,\n                        willRender: false,\n                        updateHistory: false,\n                        restorationIdentifier: this.restorationIdentifier,\n                        snapshot: pageSnapshot,\n                    };\n                    if (this.action)\n                        options.action = this.action;\n                    session.visit(frame.src, options);\n                }\n            };\n        }\n    }\n    changeHistory() {\n        if (this.action) {\n            const method = getHistoryMethodForAction(this.action);\n            session.history.update(method, expandURL(this.element.src || \"\"), this.restorationIdentifier);\n        }\n    }\n    async handleUnvisitableFrameResponse(fetchResponse) {\n        console.warn(`The response (${fetchResponse.statusCode}) from <turbo-frame id=\"${this.element.id}\"> is performing a full page visit due to turbo-visit-control.`);\n        await this.visitResponse(fetchResponse.response);\n    }\n    willHandleFrameMissingFromResponse(fetchResponse) {\n        this.element.setAttribute(\"complete\", \"\");\n        const response = fetchResponse.response;\n        const visit = async (url, options = {}) => {\n            if (url instanceof Response) {\n                this.visitResponse(url);\n            }\n            else {\n                session.visit(url, options);\n            }\n        };\n        const event = dispatch(\"turbo:frame-missing\", {\n            target: this.element,\n            detail: { response, visit },\n            cancelable: true,\n        });\n        return !event.defaultPrevented;\n    }\n    handleFrameMissingFromResponse(fetchResponse) {\n        this.view.missing();\n        this.throwFrameMissingError(fetchResponse);\n    }\n    throwFrameMissingError(fetchResponse) {\n        const message = `The response (${fetchResponse.statusCode}) did not contain the expected <turbo-frame id=\"${this.element.id}\"> and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;\n        throw new TurboFrameMissingError(message);\n    }\n    async visitResponse(response) {\n        const wrapped = new FetchResponse(response);\n        const responseHTML = await wrapped.responseHTML;\n        const { location, redirected, statusCode } = wrapped;\n        return session.visit(location, { response: { redirected, statusCode, responseHTML } });\n    }\n    findFrameElement(element, submitter) {\n        var _a;\n        const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n        return (_a = getFrameElementById(id)) !== null && _a !== void 0 ? _a : this.element;\n    }\n    async extractForeignFrameElement(container) {\n        let element;\n        const id = CSS.escape(this.id);\n        try {\n            element = activateElement(container.querySelector(`turbo-frame#${id}`), this.sourceURL);\n            if (element) {\n                return element;\n            }\n            element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.sourceURL);\n            if (element) {\n                await element.loaded;\n                return await this.extractForeignFrameElement(element);\n            }\n        }\n        catch (error) {\n            console.error(error);\n            return new FrameElement();\n        }\n        return null;\n    }\n    formActionIsVisitable(form, submitter) {\n        const action = getAction(form, submitter);\n        return locationIsVisitable(expandURL(action), this.rootLocation);\n    }\n    shouldInterceptNavigation(element, submitter) {\n        const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n        if (element instanceof HTMLFormElement && !this.formActionIsVisitable(element, submitter)) {\n            return false;\n        }\n        if (!this.enabled || id == \"_top\") {\n            return false;\n        }\n        if (id) {\n            const frameElement = getFrameElementById(id);\n            if (frameElement) {\n                return !frameElement.disabled;\n            }\n        }\n        if (!session.elementIsNavigatable(element)) {\n            return false;\n        }\n        if (submitter && !session.elementIsNavigatable(submitter)) {\n            return false;\n        }\n        return true;\n    }\n    get id() {\n        return this.element.id;\n    }\n    get enabled() {\n        return !this.element.disabled;\n    }\n    get sourceURL() {\n        if (this.element.src) {\n            return this.element.src;\n        }\n    }\n    set sourceURL(sourceURL) {\n        this.ignoringChangesToAttribute(\"src\", () => {\n            this.element.src = sourceURL !== null && sourceURL !== void 0 ? sourceURL : null;\n        });\n    }\n    get loadingStyle() {\n        return this.element.loading;\n    }\n    get isLoading() {\n        return this.formSubmission !== undefined || this.resolveVisitPromise() !== undefined;\n    }\n    get complete() {\n        return this.element.hasAttribute(\"complete\");\n    }\n    set complete(value) {\n        this.ignoringChangesToAttribute(\"complete\", () => {\n            if (value) {\n                this.element.setAttribute(\"complete\", \"\");\n            }\n            else {\n                this.element.removeAttribute(\"complete\");\n            }\n        });\n    }\n    get isActive() {\n        return this.element.isActive && this.connected;\n    }\n    get rootLocation() {\n        var _a;\n        const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n        const root = (_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : \"/\";\n        return expandURL(root);\n    }\n    isIgnoringChangesTo(attributeName) {\n        return this.ignoredAttributes.has(attributeName);\n    }\n    ignoringChangesToAttribute(attributeName, callback) {\n        this.ignoredAttributes.add(attributeName);\n        callback();\n        this.ignoredAttributes.delete(attributeName);\n    }\n    withCurrentNavigationElement(element, callback) {\n        this.currentNavigationElement = element;\n        callback();\n        delete this.currentNavigationElement;\n    }\n}\nfunction getFrameElementById(id) {\n    if (id != null) {\n        const element = document.getElementById(id);\n        if (element instanceof FrameElement) {\n            return element;\n        }\n    }\n}\nfunction activateElement(element, currentURL) {\n    if (element) {\n        const src = element.getAttribute(\"src\");\n        if (src != null && currentURL != null && urlsAreEqual(src, currentURL)) {\n            throw new Error(`Matching <turbo-frame id=\"${element.id}\"> element has a source URL which references itself`);\n        }\n        if (element.ownerDocument !== document) {\n            element = document.importNode(element, true);\n        }\n        if (element instanceof FrameElement) {\n            element.connectedCallback();\n            element.disconnectedCallback();\n            return element;\n        }\n    }\n}\n\nclass StreamElement extends HTMLElement {\n    static async renderElement(newElement) {\n        await newElement.performAction();\n    }\n    async connectedCallback() {\n        try {\n            await this.render();\n        }\n        catch (error) {\n            console.error(error);\n        }\n        finally {\n            this.disconnect();\n        }\n    }\n    async render() {\n        var _a;\n        return ((_a = this.renderPromise) !== null && _a !== void 0 ? _a : (this.renderPromise = (async () => {\n            const event = this.beforeRenderEvent;\n            if (this.dispatchEvent(event)) {\n                await nextAnimationFrame();\n                await event.detail.render(this);\n            }\n        })()));\n    }\n    disconnect() {\n        try {\n            this.remove();\n        }\n        catch (_a) { }\n    }\n    removeDuplicateTargetChildren() {\n        this.duplicateChildren.forEach((c) => c.remove());\n    }\n    get duplicateChildren() {\n        var _a;\n        const existingChildren = this.targetElements.flatMap((e) => [...e.children]).filter((c) => !!c.id);\n        const newChildrenIds = [...(((_a = this.templateContent) === null || _a === void 0 ? void 0 : _a.children) || [])].filter((c) => !!c.id).map((c) => c.id);\n        return existingChildren.filter((c) => newChildrenIds.includes(c.id));\n    }\n    get performAction() {\n        if (this.action) {\n            const actionFunction = StreamActions[this.action];\n            if (actionFunction) {\n                return actionFunction;\n            }\n            this.raise(\"unknown action\");\n        }\n        this.raise(\"action attribute is missing\");\n    }\n    get targetElements() {\n        if (this.target) {\n            return this.targetElementsById;\n        }\n        else if (this.targets) {\n            return this.targetElementsByQuery;\n        }\n        else {\n            this.raise(\"target or targets attribute is missing\");\n        }\n    }\n    get templateContent() {\n        return this.templateElement.content.cloneNode(true);\n    }\n    get templateElement() {\n        if (this.firstElementChild === null) {\n            const template = this.ownerDocument.createElement(\"template\");\n            this.appendChild(template);\n            return template;\n        }\n        else if (this.firstElementChild instanceof HTMLTemplateElement) {\n            return this.firstElementChild;\n        }\n        this.raise(\"first child element must be a <template> element\");\n    }\n    get action() {\n        return this.getAttribute(\"action\");\n    }\n    get target() {\n        return this.getAttribute(\"target\");\n    }\n    get targets() {\n        return this.getAttribute(\"targets\");\n    }\n    raise(message) {\n        throw new Error(`${this.description}: ${message}`);\n    }\n    get description() {\n        var _a, _b;\n        return (_b = ((_a = this.outerHTML.match(/<[^>]+>/)) !== null && _a !== void 0 ? _a : [])[0]) !== null && _b !== void 0 ? _b : \"<turbo-stream>\";\n    }\n    get beforeRenderEvent() {\n        return new CustomEvent(\"turbo:before-stream-render\", {\n            bubbles: true,\n            cancelable: true,\n            detail: { newStream: this, render: StreamElement.renderElement },\n        });\n    }\n    get targetElementsById() {\n        var _a;\n        const element = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.getElementById(this.target);\n        if (element !== null) {\n            return [element];\n        }\n        else {\n            return [];\n        }\n    }\n    get targetElementsByQuery() {\n        var _a;\n        const elements = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.querySelectorAll(this.targets);\n        if (elements.length !== 0) {\n            return Array.prototype.slice.call(elements);\n        }\n        else {\n            return [];\n        }\n    }\n}\n\nclass StreamSourceElement extends HTMLElement {\n    constructor() {\n        super(...arguments);\n        this.streamSource = null;\n    }\n    connectedCallback() {\n        this.streamSource = this.src.match(/^ws{1,2}:/) ? new WebSocket(this.src) : new EventSource(this.src);\n        connectStreamSource(this.streamSource);\n    }\n    disconnectedCallback() {\n        if (this.streamSource) {\n            disconnectStreamSource(this.streamSource);\n        }\n    }\n    get src() {\n        return this.getAttribute(\"src\") || \"\";\n    }\n}\n\nFrameElement.delegateConstructor = FrameController;\nif (customElements.get(\"turbo-frame\") === undefined) {\n    customElements.define(\"turbo-frame\", FrameElement);\n}\nif (customElements.get(\"turbo-stream\") === undefined) {\n    customElements.define(\"turbo-stream\", StreamElement);\n}\nif (customElements.get(\"turbo-stream-source\") === undefined) {\n    customElements.define(\"turbo-stream-source\", StreamSourceElement);\n}\n\n(() => {\n    let element = document.currentScript;\n    if (!element)\n        return;\n    if (element.hasAttribute(\"data-turbo-suppress-warning\"))\n        return;\n    element = element.parentElement;\n    while (element) {\n        if (element == document.body) {\n            return console.warn(unindent `\n        You are loading Turbo from a <script> element inside the <body> element. This is probably not what you meant to do!\n\n        Load your application\u2019s JavaScript bundle inside the <head> element instead. <script> elements in <body> are evaluated with each page change.\n\n        For more information, see: https://turbo.hotwired.dev/handbook/building#working-with-script-elements\n\n        \u2014\u2014\n        Suppress this warning by adding a \"data-turbo-suppress-warning\" attribute to: %s\n      `, element.outerHTML);\n        }\n        element = element.parentElement;\n    }\n})();\n\nwindow.Turbo = Turbo;\nstart();\n\nexport { FrameElement, FrameLoadingStyle, FrameRenderer, PageRenderer, PageSnapshot, StreamActions, StreamElement, StreamSourceElement, cache, clearCache, connectStreamSource, disconnectStreamSource, navigator$1 as navigator, registerAdapter, renderStreamMessage, session, setConfirmMethod, setFormMode, setProgressBarDelay, start, visit };\n", "let consumer\n\nexport async function getConsumer() {\n  return consumer || setConsumer(createConsumer().then(setConsumer))\n}\n\nexport function setConsumer(newConsumer) {\n  return consumer = newConsumer\n}\n\nexport async function createConsumer() {\n  const { createConsumer } = await import(/* webpackChunkName: \"actioncable\" */ \"@rails/actioncable/src\")\n  return createConsumer()\n}\n\nexport async function subscribeTo(channel, mixin) {\n  const { subscriptions } = await getConsumer()\n  return subscriptions.create(channel, mixin)\n}\n", "// Based on https://github.com/nathan7/snakeize\n//\n// This software is released under the MIT license:\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// 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, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\nexport default function walk (obj) {\n    if (!obj || typeof obj !== 'object') return obj;\n    if (obj instanceof Date || obj instanceof RegExp) return obj;\n    if (Array.isArray(obj)) return obj.map(walk);\n    return Object.keys(obj).reduce(function (acc, key) {\n        var camel = key[0].toLowerCase() + key.slice(1).replace(/([A-Z]+)/g, function (m, x) {\n            return '_' + x.toLowerCase();\n        });\n        acc[camel] = walk(obj[key]);\n        return acc;\n    }, {});\n};", "import { connectStreamSource, disconnectStreamSource } from \"@hotwired/turbo\"\nimport { subscribeTo } from \"./cable\"\nimport snakeize from \"./snakeize\"\n\nclass TurboCableStreamSourceElement extends HTMLElement {\n  async connectedCallback() {\n    connectStreamSource(this)\n    this.subscription = await subscribeTo(this.channel, {\n      received: this.dispatchMessageEvent.bind(this),\n      connected: this.subscriptionConnected.bind(this),\n      disconnected: this.subscriptionDisconnected.bind(this)\n    })\n  }\n\n  disconnectedCallback() {\n    disconnectStreamSource(this)\n    if (this.subscription) this.subscription.unsubscribe()\n  }\n\n  dispatchMessageEvent(data) {\n    const event = new MessageEvent(\"message\", { data })\n    return this.dispatchEvent(event)\n  }\n\n  subscriptionConnected() {\n    this.setAttribute(\"connected\", \"\")\n  }\n\n  subscriptionDisconnected() {\n    this.removeAttribute(\"connected\")\n  }\n\n  get channel() {\n    const channel = this.getAttribute(\"channel\")\n    const signed_stream_name = this.getAttribute(\"signed-stream-name\")\n    return { channel, signed_stream_name, ...snakeize({ ...this.dataset }) }\n  }\n}\n\n\nif (customElements.get(\"turbo-cable-stream-source\") === undefined) {\n  customElements.define(\"turbo-cable-stream-source\", TurboCableStreamSourceElement)\n}\n", "export function encodeMethodIntoRequestBody(event) {\n  if (event.target instanceof HTMLFormElement) {\n    const { target: form, detail: { fetchOptions } } = event\n\n    form.addEventListener(\"turbo:submit-start\", ({ detail: { formSubmission: { submitter } } }) => {\n      const body = isBodyInit(fetchOptions.body) ? fetchOptions.body : new URLSearchParams()\n      const method = determineFetchMethod(submitter, body, form)\n\n      if (!/get/i.test(method)) {\n        if (/post/i.test(method)) {\n          body.delete(\"_method\")\n        } else {\n          body.set(\"_method\", method)\n        }\n\n        fetchOptions.method = \"post\"\n      }\n    }, { once: true })\n  }\n}\n\nfunction determineFetchMethod(submitter, body, form) {\n  const formMethod = determineFormMethod(submitter)\n  const overrideMethod = body.get(\"_method\")\n  const method = form.getAttribute(\"method\") || \"get\"\n\n  if (typeof formMethod == \"string\") {\n    return formMethod\n  } else if (typeof overrideMethod == \"string\") {\n    return overrideMethod\n  } else {\n    return method\n  }\n}\n\nfunction determineFormMethod(submitter) {\n  if (submitter instanceof HTMLButtonElement || submitter instanceof HTMLInputElement) {\n    if (submitter.hasAttribute(\"formmethod\")) {\n      return submitter.formMethod\n    } else {\n      return null\n    }\n  } else {\n    return null\n  }\n}\n\nfunction isBodyInit(body) {\n  return body instanceof FormData || body instanceof URLSearchParams\n}\n", "import \"./cable_stream_source_element\"\n\nimport * as Turbo from \"@hotwired/turbo\"\nexport { Turbo }\n\nimport * as cable from \"./cable\"\nexport { cable }\n\nimport { encodeMethodIntoRequestBody } from \"./fetch_requests\"\n\naddEventListener(\"turbo:before-fetch-request\", encodeMethodIntoRequestBody)\n", "/*\nStimulus 3.2.1\nCopyright \u00A9 2023 Basecamp, LLC\n */\nclass EventListener {\n    constructor(eventTarget, eventName, eventOptions) {\n        this.eventTarget = eventTarget;\n        this.eventName = eventName;\n        this.eventOptions = eventOptions;\n        this.unorderedBindings = new Set();\n    }\n    connect() {\n        this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);\n    }\n    disconnect() {\n        this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);\n    }\n    bindingConnected(binding) {\n        this.unorderedBindings.add(binding);\n    }\n    bindingDisconnected(binding) {\n        this.unorderedBindings.delete(binding);\n    }\n    handleEvent(event) {\n        const extendedEvent = extendEvent(event);\n        for (const binding of this.bindings) {\n            if (extendedEvent.immediatePropagationStopped) {\n                break;\n            }\n            else {\n                binding.handleEvent(extendedEvent);\n            }\n        }\n    }\n    hasBindings() {\n        return this.unorderedBindings.size > 0;\n    }\n    get bindings() {\n        return Array.from(this.unorderedBindings).sort((left, right) => {\n            const leftIndex = left.index, rightIndex = right.index;\n            return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;\n        });\n    }\n}\nfunction extendEvent(event) {\n    if (\"immediatePropagationStopped\" in event) {\n        return event;\n    }\n    else {\n        const { stopImmediatePropagation } = event;\n        return Object.assign(event, {\n            immediatePropagationStopped: false,\n            stopImmediatePropagation() {\n                this.immediatePropagationStopped = true;\n                stopImmediatePropagation.call(this);\n            },\n        });\n    }\n}\n\nclass Dispatcher {\n    constructor(application) {\n        this.application = application;\n        this.eventListenerMaps = new Map();\n        this.started = false;\n    }\n    start() {\n        if (!this.started) {\n            this.started = true;\n            this.eventListeners.forEach((eventListener) => eventListener.connect());\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.started = false;\n            this.eventListeners.forEach((eventListener) => eventListener.disconnect());\n        }\n    }\n    get eventListeners() {\n        return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n    }\n    bindingConnected(binding) {\n        this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n    }\n    bindingDisconnected(binding, clearEventListeners = false) {\n        this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n        if (clearEventListeners)\n            this.clearEventListenersForBinding(binding);\n    }\n    handleError(error, message, detail = {}) {\n        this.application.handleError(error, `Error ${message}`, detail);\n    }\n    clearEventListenersForBinding(binding) {\n        const eventListener = this.fetchEventListenerForBinding(binding);\n        if (!eventListener.hasBindings()) {\n            eventListener.disconnect();\n            this.removeMappedEventListenerFor(binding);\n        }\n    }\n    removeMappedEventListenerFor(binding) {\n        const { eventTarget, eventName, eventOptions } = binding;\n        const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n        const cacheKey = this.cacheKey(eventName, eventOptions);\n        eventListenerMap.delete(cacheKey);\n        if (eventListenerMap.size == 0)\n            this.eventListenerMaps.delete(eventTarget);\n    }\n    fetchEventListenerForBinding(binding) {\n        const { eventTarget, eventName, eventOptions } = binding;\n        return this.fetchEventListener(eventTarget, eventName, eventOptions);\n    }\n    fetchEventListener(eventTarget, eventName, eventOptions) {\n        const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n        const cacheKey = this.cacheKey(eventName, eventOptions);\n        let eventListener = eventListenerMap.get(cacheKey);\n        if (!eventListener) {\n            eventListener = this.createEventListener(eventTarget, eventName, eventOptions);\n            eventListenerMap.set(cacheKey, eventListener);\n        }\n        return eventListener;\n    }\n    createEventListener(eventTarget, eventName, eventOptions) {\n        const eventListener = new EventListener(eventTarget, eventName, eventOptions);\n        if (this.started) {\n            eventListener.connect();\n        }\n        return eventListener;\n    }\n    fetchEventListenerMapForEventTarget(eventTarget) {\n        let eventListenerMap = this.eventListenerMaps.get(eventTarget);\n        if (!eventListenerMap) {\n            eventListenerMap = new Map();\n            this.eventListenerMaps.set(eventTarget, eventListenerMap);\n        }\n        return eventListenerMap;\n    }\n    cacheKey(eventName, eventOptions) {\n        const parts = [eventName];\n        Object.keys(eventOptions)\n            .sort()\n            .forEach((key) => {\n            parts.push(`${eventOptions[key] ? \"\" : \"!\"}${key}`);\n        });\n        return parts.join(\":\");\n    }\n}\n\nconst defaultActionDescriptorFilters = {\n    stop({ event, value }) {\n        if (value)\n            event.stopPropagation();\n        return true;\n    },\n    prevent({ event, value }) {\n        if (value)\n            event.preventDefault();\n        return true;\n    },\n    self({ event, value, element }) {\n        if (value) {\n            return element === event.target;\n        }\n        else {\n            return true;\n        }\n    },\n};\nconst descriptorPattern = /^(?:(?:([^.]+?)\\+)?(.+?)(?:\\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;\nfunction parseActionDescriptorString(descriptorString) {\n    const source = descriptorString.trim();\n    const matches = source.match(descriptorPattern) || [];\n    let eventName = matches[2];\n    let keyFilter = matches[3];\n    if (keyFilter && ![\"keydown\", \"keyup\", \"keypress\"].includes(eventName)) {\n        eventName += `.${keyFilter}`;\n        keyFilter = \"\";\n    }\n    return {\n        eventTarget: parseEventTarget(matches[4]),\n        eventName,\n        eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},\n        identifier: matches[5],\n        methodName: matches[6],\n        keyFilter: matches[1] || keyFilter,\n    };\n}\nfunction parseEventTarget(eventTargetName) {\n    if (eventTargetName == \"window\") {\n        return window;\n    }\n    else if (eventTargetName == \"document\") {\n        return document;\n    }\n}\nfunction parseEventOptions(eventOptions) {\n    return eventOptions\n        .split(\":\")\n        .reduce((options, token) => Object.assign(options, { [token.replace(/^!/, \"\")]: !/^!/.test(token) }), {});\n}\nfunction stringifyEventTarget(eventTarget) {\n    if (eventTarget == window) {\n        return \"window\";\n    }\n    else if (eventTarget == document) {\n        return \"document\";\n    }\n}\n\nfunction camelize(value) {\n    return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n}\nfunction namespaceCamelize(value) {\n    return camelize(value.replace(/--/g, \"-\").replace(/__/g, \"_\"));\n}\nfunction capitalize(value) {\n    return value.charAt(0).toUpperCase() + value.slice(1);\n}\nfunction dasherize(value) {\n    return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);\n}\nfunction tokenize(value) {\n    return value.match(/[^\\s]+/g) || [];\n}\n\nfunction isSomething(object) {\n    return object !== null && object !== undefined;\n}\nfunction hasProperty(object, property) {\n    return Object.prototype.hasOwnProperty.call(object, property);\n}\n\nconst allModifiers = [\"meta\", \"ctrl\", \"alt\", \"shift\"];\nclass Action {\n    constructor(element, index, descriptor, schema) {\n        this.element = element;\n        this.index = index;\n        this.eventTarget = descriptor.eventTarget || element;\n        this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n        this.eventOptions = descriptor.eventOptions || {};\n        this.identifier = descriptor.identifier || error(\"missing identifier\");\n        this.methodName = descriptor.methodName || error(\"missing method name\");\n        this.keyFilter = descriptor.keyFilter || \"\";\n        this.schema = schema;\n    }\n    static forToken(token, schema) {\n        return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);\n    }\n    toString() {\n        const eventFilter = this.keyFilter ? `.${this.keyFilter}` : \"\";\n        const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n        return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;\n    }\n    shouldIgnoreKeyboardEvent(event) {\n        if (!this.keyFilter) {\n            return false;\n        }\n        const filters = this.keyFilter.split(\"+\");\n        if (this.keyFilterDissatisfied(event, filters)) {\n            return true;\n        }\n        const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0];\n        if (!standardFilter) {\n            return false;\n        }\n        if (!hasProperty(this.keyMappings, standardFilter)) {\n            error(`contains unknown key filter: ${this.keyFilter}`);\n        }\n        return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();\n    }\n    shouldIgnoreMouseEvent(event) {\n        if (!this.keyFilter) {\n            return false;\n        }\n        const filters = [this.keyFilter];\n        if (this.keyFilterDissatisfied(event, filters)) {\n            return true;\n        }\n        return false;\n    }\n    get params() {\n        const params = {};\n        const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, \"i\");\n        for (const { name, value } of Array.from(this.element.attributes)) {\n            const match = name.match(pattern);\n            const key = match && match[1];\n            if (key) {\n                params[camelize(key)] = typecast(value);\n            }\n        }\n        return params;\n    }\n    get eventTargetName() {\n        return stringifyEventTarget(this.eventTarget);\n    }\n    get keyMappings() {\n        return this.schema.keyMappings;\n    }\n    keyFilterDissatisfied(event, filters) {\n        const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier));\n        return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;\n    }\n}\nconst defaultEventNames = {\n    a: () => \"click\",\n    button: () => \"click\",\n    form: () => \"submit\",\n    details: () => \"toggle\",\n    input: (e) => (e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\"),\n    select: () => \"change\",\n    textarea: () => \"input\",\n};\nfunction getDefaultEventNameForElement(element) {\n    const tagName = element.tagName.toLowerCase();\n    if (tagName in defaultEventNames) {\n        return defaultEventNames[tagName](element);\n    }\n}\nfunction error(message) {\n    throw new Error(message);\n}\nfunction typecast(value) {\n    try {\n        return JSON.parse(value);\n    }\n    catch (o_O) {\n        return value;\n    }\n}\n\nclass Binding {\n    constructor(context, action) {\n        this.context = context;\n        this.action = action;\n    }\n    get index() {\n        return this.action.index;\n    }\n    get eventTarget() {\n        return this.action.eventTarget;\n    }\n    get eventOptions() {\n        return this.action.eventOptions;\n    }\n    get identifier() {\n        return this.context.identifier;\n    }\n    handleEvent(event) {\n        const actionEvent = this.prepareActionEvent(event);\n        if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {\n            this.invokeWithEvent(actionEvent);\n        }\n    }\n    get eventName() {\n        return this.action.eventName;\n    }\n    get method() {\n        const method = this.controller[this.methodName];\n        if (typeof method == \"function\") {\n            return method;\n        }\n        throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n    }\n    applyEventModifiers(event) {\n        const { element } = this.action;\n        const { actionDescriptorFilters } = this.context.application;\n        const { controller } = this.context;\n        let passes = true;\n        for (const [name, value] of Object.entries(this.eventOptions)) {\n            if (name in actionDescriptorFilters) {\n                const filter = actionDescriptorFilters[name];\n                passes = passes && filter({ name, value, event, element, controller });\n            }\n            else {\n                continue;\n            }\n        }\n        return passes;\n    }\n    prepareActionEvent(event) {\n        return Object.assign(event, { params: this.action.params });\n    }\n    invokeWithEvent(event) {\n        const { target, currentTarget } = event;\n        try {\n            this.method.call(this.controller, event);\n            this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });\n        }\n        catch (error) {\n            const { identifier, controller, element, index } = this;\n            const detail = { identifier, controller, element, index, event };\n            this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n        }\n    }\n    willBeInvokedByEvent(event) {\n        const eventTarget = event.target;\n        if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {\n            return false;\n        }\n        if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {\n            return false;\n        }\n        if (this.element === eventTarget) {\n            return true;\n        }\n        else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n            return this.scope.containsElement(eventTarget);\n        }\n        else {\n            return this.scope.containsElement(this.action.element);\n        }\n    }\n    get controller() {\n        return this.context.controller;\n    }\n    get methodName() {\n        return this.action.methodName;\n    }\n    get element() {\n        return this.scope.element;\n    }\n    get scope() {\n        return this.context.scope;\n    }\n}\n\nclass ElementObserver {\n    constructor(element, delegate) {\n        this.mutationObserverInit = { attributes: true, childList: true, subtree: true };\n        this.element = element;\n        this.started = false;\n        this.delegate = delegate;\n        this.elements = new Set();\n        this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n    }\n    start() {\n        if (!this.started) {\n            this.started = true;\n            this.mutationObserver.observe(this.element, this.mutationObserverInit);\n            this.refresh();\n        }\n    }\n    pause(callback) {\n        if (this.started) {\n            this.mutationObserver.disconnect();\n            this.started = false;\n        }\n        callback();\n        if (!this.started) {\n            this.mutationObserver.observe(this.element, this.mutationObserverInit);\n            this.started = true;\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.mutationObserver.takeRecords();\n            this.mutationObserver.disconnect();\n            this.started = false;\n        }\n    }\n    refresh() {\n        if (this.started) {\n            const matches = new Set(this.matchElementsInTree());\n            for (const element of Array.from(this.elements)) {\n                if (!matches.has(element)) {\n                    this.removeElement(element);\n                }\n            }\n            for (const element of Array.from(matches)) {\n                this.addElement(element);\n            }\n        }\n    }\n    processMutations(mutations) {\n        if (this.started) {\n            for (const mutation of mutations) {\n                this.processMutation(mutation);\n            }\n        }\n    }\n    processMutation(mutation) {\n        if (mutation.type == \"attributes\") {\n            this.processAttributeChange(mutation.target, mutation.attributeName);\n        }\n        else if (mutation.type == \"childList\") {\n            this.processRemovedNodes(mutation.removedNodes);\n            this.processAddedNodes(mutation.addedNodes);\n        }\n    }\n    processAttributeChange(element, attributeName) {\n        if (this.elements.has(element)) {\n            if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n                this.delegate.elementAttributeChanged(element, attributeName);\n            }\n            else {\n                this.removeElement(element);\n            }\n        }\n        else if (this.matchElement(element)) {\n            this.addElement(element);\n        }\n    }\n    processRemovedNodes(nodes) {\n        for (const node of Array.from(nodes)) {\n            const element = this.elementFromNode(node);\n            if (element) {\n                this.processTree(element, this.removeElement);\n            }\n        }\n    }\n    processAddedNodes(nodes) {\n        for (const node of Array.from(nodes)) {\n            const element = this.elementFromNode(node);\n            if (element && this.elementIsActive(element)) {\n                this.processTree(element, this.addElement);\n            }\n        }\n    }\n    matchElement(element) {\n        return this.delegate.matchElement(element);\n    }\n    matchElementsInTree(tree = this.element) {\n        return this.delegate.matchElementsInTree(tree);\n    }\n    processTree(tree, processor) {\n        for (const element of this.matchElementsInTree(tree)) {\n            processor.call(this, element);\n        }\n    }\n    elementFromNode(node) {\n        if (node.nodeType == Node.ELEMENT_NODE) {\n            return node;\n        }\n    }\n    elementIsActive(element) {\n        if (element.isConnected != this.element.isConnected) {\n            return false;\n        }\n        else {\n            return this.element.contains(element);\n        }\n    }\n    addElement(element) {\n        if (!this.elements.has(element)) {\n            if (this.elementIsActive(element)) {\n                this.elements.add(element);\n                if (this.delegate.elementMatched) {\n                    this.delegate.elementMatched(element);\n                }\n            }\n        }\n    }\n    removeElement(element) {\n        if (this.elements.has(element)) {\n            this.elements.delete(element);\n            if (this.delegate.elementUnmatched) {\n                this.delegate.elementUnmatched(element);\n            }\n        }\n    }\n}\n\nclass AttributeObserver {\n    constructor(element, attributeName, delegate) {\n        this.attributeName = attributeName;\n        this.delegate = delegate;\n        this.elementObserver = new ElementObserver(element, this);\n    }\n    get element() {\n        return this.elementObserver.element;\n    }\n    get selector() {\n        return `[${this.attributeName}]`;\n    }\n    start() {\n        this.elementObserver.start();\n    }\n    pause(callback) {\n        this.elementObserver.pause(callback);\n    }\n    stop() {\n        this.elementObserver.stop();\n    }\n    refresh() {\n        this.elementObserver.refresh();\n    }\n    get started() {\n        return this.elementObserver.started;\n    }\n    matchElement(element) {\n        return element.hasAttribute(this.attributeName);\n    }\n    matchElementsInTree(tree) {\n        const match = this.matchElement(tree) ? [tree] : [];\n        const matches = Array.from(tree.querySelectorAll(this.selector));\n        return match.concat(matches);\n    }\n    elementMatched(element) {\n        if (this.delegate.elementMatchedAttribute) {\n            this.delegate.elementMatchedAttribute(element, this.attributeName);\n        }\n    }\n    elementUnmatched(element) {\n        if (this.delegate.elementUnmatchedAttribute) {\n            this.delegate.elementUnmatchedAttribute(element, this.attributeName);\n        }\n    }\n    elementAttributeChanged(element, attributeName) {\n        if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {\n            this.delegate.elementAttributeValueChanged(element, attributeName);\n        }\n    }\n}\n\nfunction add(map, key, value) {\n    fetch(map, key).add(value);\n}\nfunction del(map, key, value) {\n    fetch(map, key).delete(value);\n    prune(map, key);\n}\nfunction fetch(map, key) {\n    let values = map.get(key);\n    if (!values) {\n        values = new Set();\n        map.set(key, values);\n    }\n    return values;\n}\nfunction prune(map, key) {\n    const values = map.get(key);\n    if (values != null && values.size == 0) {\n        map.delete(key);\n    }\n}\n\nclass Multimap {\n    constructor() {\n        this.valuesByKey = new Map();\n    }\n    get keys() {\n        return Array.from(this.valuesByKey.keys());\n    }\n    get values() {\n        const sets = Array.from(this.valuesByKey.values());\n        return sets.reduce((values, set) => values.concat(Array.from(set)), []);\n    }\n    get size() {\n        const sets = Array.from(this.valuesByKey.values());\n        return sets.reduce((size, set) => size + set.size, 0);\n    }\n    add(key, value) {\n        add(this.valuesByKey, key, value);\n    }\n    delete(key, value) {\n        del(this.valuesByKey, key, value);\n    }\n    has(key, value) {\n        const values = this.valuesByKey.get(key);\n        return values != null && values.has(value);\n    }\n    hasKey(key) {\n        return this.valuesByKey.has(key);\n    }\n    hasValue(value) {\n        const sets = Array.from(this.valuesByKey.values());\n        return sets.some((set) => set.has(value));\n    }\n    getValuesForKey(key) {\n        const values = this.valuesByKey.get(key);\n        return values ? Array.from(values) : [];\n    }\n    getKeysForValue(value) {\n        return Array.from(this.valuesByKey)\n            .filter(([_key, values]) => values.has(value))\n            .map(([key, _values]) => key);\n    }\n}\n\nclass IndexedMultimap extends Multimap {\n    constructor() {\n        super();\n        this.keysByValue = new Map();\n    }\n    get values() {\n        return Array.from(this.keysByValue.keys());\n    }\n    add(key, value) {\n        super.add(key, value);\n        add(this.keysByValue, value, key);\n    }\n    delete(key, value) {\n        super.delete(key, value);\n        del(this.keysByValue, value, key);\n    }\n    hasValue(value) {\n        return this.keysByValue.has(value);\n    }\n    getKeysForValue(value) {\n        const set = this.keysByValue.get(value);\n        return set ? Array.from(set) : [];\n    }\n}\n\nclass SelectorObserver {\n    constructor(element, selector, delegate, details) {\n        this._selector = selector;\n        this.details = details;\n        this.elementObserver = new ElementObserver(element, this);\n        this.delegate = delegate;\n        this.matchesByElement = new Multimap();\n    }\n    get started() {\n        return this.elementObserver.started;\n    }\n    get selector() {\n        return this._selector;\n    }\n    set selector(selector) {\n        this._selector = selector;\n        this.refresh();\n    }\n    start() {\n        this.elementObserver.start();\n    }\n    pause(callback) {\n        this.elementObserver.pause(callback);\n    }\n    stop() {\n        this.elementObserver.stop();\n    }\n    refresh() {\n        this.elementObserver.refresh();\n    }\n    get element() {\n        return this.elementObserver.element;\n    }\n    matchElement(element) {\n        const { selector } = this;\n        if (selector) {\n            const matches = element.matches(selector);\n            if (this.delegate.selectorMatchElement) {\n                return matches && this.delegate.selectorMatchElement(element, this.details);\n            }\n            return matches;\n        }\n        else {\n            return false;\n        }\n    }\n    matchElementsInTree(tree) {\n        const { selector } = this;\n        if (selector) {\n            const match = this.matchElement(tree) ? [tree] : [];\n            const matches = Array.from(tree.querySelectorAll(selector)).filter((match) => this.matchElement(match));\n            return match.concat(matches);\n        }\n        else {\n            return [];\n        }\n    }\n    elementMatched(element) {\n        const { selector } = this;\n        if (selector) {\n            this.selectorMatched(element, selector);\n        }\n    }\n    elementUnmatched(element) {\n        const selectors = this.matchesByElement.getKeysForValue(element);\n        for (const selector of selectors) {\n            this.selectorUnmatched(element, selector);\n        }\n    }\n    elementAttributeChanged(element, _attributeName) {\n        const { selector } = this;\n        if (selector) {\n            const matches = this.matchElement(element);\n            const matchedBefore = this.matchesByElement.has(selector, element);\n            if (matches && !matchedBefore) {\n                this.selectorMatched(element, selector);\n            }\n            else if (!matches && matchedBefore) {\n                this.selectorUnmatched(element, selector);\n            }\n        }\n    }\n    selectorMatched(element, selector) {\n        this.delegate.selectorMatched(element, selector, this.details);\n        this.matchesByElement.add(selector, element);\n    }\n    selectorUnmatched(element, selector) {\n        this.delegate.selectorUnmatched(element, selector, this.details);\n        this.matchesByElement.delete(selector, element);\n    }\n}\n\nclass StringMapObserver {\n    constructor(element, delegate) {\n        this.element = element;\n        this.delegate = delegate;\n        this.started = false;\n        this.stringMap = new Map();\n        this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n    }\n    start() {\n        if (!this.started) {\n            this.started = true;\n            this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });\n            this.refresh();\n        }\n    }\n    stop() {\n        if (this.started) {\n            this.mutationObserver.takeRecords();\n            this.mutationObserver.disconnect();\n            this.started = false;\n        }\n    }\n    refresh() {\n        if (this.started) {\n            for (const attributeName of this.knownAttributeNames) {\n                this.refreshAttribute(attributeName, null);\n            }\n        }\n    }\n    processMutations(mutations) {\n        if (this.started) {\n            for (const mutation of mutations) {\n                this.processMutation(mutation);\n            }\n        }\n    }\n    processMutation(mutation) {\n        const attributeName = mutation.attributeName;\n        if (attributeName) {\n            this.refreshAttribute(attributeName, mutation.oldValue);\n        }\n    }\n    refreshAttribute(attributeName, oldValue) {\n        const key = this.delegate.getStringMapKeyForAttribute(attributeName);\n        if (key != null) {\n            if (!this.stringMap.has(attributeName)) {\n                this.stringMapKeyAdded(key, attributeName);\n            }\n            const value = this.element.getAttribute(attributeName);\n            if (this.stringMap.get(attributeName) != value) {\n                this.stringMapValueChanged(value, key, oldValue);\n            }\n            if (value == null) {\n                const oldValue = this.stringMap.get(attributeName);\n                this.stringMap.delete(attributeName);\n                if (oldValue)\n                    this.stringMapKeyRemoved(key, attributeName, oldValue);\n            }\n            else {\n                this.stringMap.set(attributeName, value);\n            }\n        }\n    }\n    stringMapKeyAdded(key, attributeName) {\n        if (this.delegate.stringMapKeyAdded) {\n            this.delegate.stringMapKeyAdded(key, attributeName);\n        }\n    }\n    stringMapValueChanged(value, key, oldValue) {\n        if (this.delegate.stringMapValueChanged) {\n            this.delegate.stringMapValueChanged(value, key, oldValue);\n        }\n    }\n    stringMapKeyRemoved(key, attributeName, oldValue) {\n        if (this.delegate.stringMapKeyRemoved) {\n            this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);\n        }\n    }\n    get knownAttributeNames() {\n        return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));\n    }\n    get currentAttributeNames() {\n        return Array.from(this.element.attributes).map((attribute) => attribute.name);\n    }\n    get recordedAttributeNames() {\n        return Array.from(this.stringMap.keys());\n    }\n}\n\nclass TokenListObserver {\n    constructor(element, attributeName, delegate) {\n        this.attributeObserver = new AttributeObserver(element, attributeName, this);\n        this.delegate = delegate;\n        this.tokensByElement = new Multimap();\n    }\n    get started() {\n        return this.attributeObserver.started;\n    }\n    start() {\n        this.attributeObserver.start();\n    }\n    pause(callback) {\n        this.attributeObserver.pause(callback);\n    }\n    stop() {\n        this.attributeObserver.stop();\n    }\n    refresh() {\n        this.attributeObserver.refresh();\n    }\n    get element() {\n        return this.attributeObserver.element;\n    }\n    get attributeName() {\n        return this.attributeObserver.attributeName;\n    }\n    elementMatchedAttribute(element) {\n        this.tokensMatched(this.readTokensForElement(element));\n    }\n    elementAttributeValueChanged(element) {\n        const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);\n        this.tokensUnmatched(unmatchedTokens);\n        this.tokensMatched(matchedTokens);\n    }\n    elementUnmatchedAttribute(element) {\n        this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n    }\n    tokensMatched(tokens) {\n        tokens.forEach((token) => this.tokenMatched(token));\n    }\n    tokensUnmatched(tokens) {\n        tokens.forEach((token) => this.tokenUnmatched(token));\n    }\n    tokenMatched(token) {\n        this.delegate.tokenMatched(token);\n        this.tokensByElement.add(token.element, token);\n    }\n    tokenUnmatched(token) {\n        this.delegate.tokenUnmatched(token);\n        this.tokensByElement.delete(token.element, token);\n    }\n    refreshTokensForElement(element) {\n        const previousTokens = this.tokensByElement.getValuesForKey(element);\n        const currentTokens = this.readTokensForElement(element);\n        const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));\n        if (firstDifferingIndex == -1) {\n            return [[], []];\n        }\n        else {\n            return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];\n        }\n    }\n    readTokensForElement(element) {\n        const attributeName = this.attributeName;\n        const tokenString = element.getAttribute(attributeName) || \"\";\n        return parseTokenString(tokenString, element, attributeName);\n    }\n}\nfunction parseTokenString(tokenString, element, attributeName) {\n    return tokenString\n        .trim()\n        .split(/\\s+/)\n        .filter((content) => content.length)\n        .map((content, index) => ({ element, attributeName, content, index }));\n}\nfunction zip(left, right) {\n    const length = Math.max(left.length, right.length);\n    return Array.from({ length }, (_, index) => [left[index], right[index]]);\n}\nfunction tokensAreEqual(left, right) {\n    return left && right && left.index == right.index && left.content == right.content;\n}\n\nclass ValueListObserver {\n    constructor(element, attributeName, delegate) {\n        this.tokenListObserver = new TokenListObserver(element, attributeName, this);\n        this.delegate = delegate;\n        this.parseResultsByToken = new WeakMap();\n        this.valuesByTokenByElement = new WeakMap();\n    }\n    get started() {\n        return this.tokenListObserver.started;\n    }\n    start() {\n        this.tokenListObserver.start();\n    }\n    stop() {\n        this.tokenListObserver.stop();\n    }\n    refresh() {\n        this.tokenListObserver.refresh();\n    }\n    get element() {\n        return this.tokenListObserver.element;\n    }\n    get attributeName() {\n        return this.tokenListObserver.attributeName;\n    }\n    tokenMatched(token) {\n        const { element } = token;\n        const { value } = this.fetchParseResultForToken(token);\n        if (value) {\n            this.fetchValuesByTokenForElement(element).set(token, value);\n            this.delegate.elementMatchedValue(element, value);\n        }\n    }\n    tokenUnmatched(token) {\n        const { element } = token;\n        const { value } = this.fetchParseResultForToken(token);\n        if (value) {\n            this.fetchValuesByTokenForElement(element).delete(token);\n            this.delegate.elementUnmatchedValue(element, value);\n        }\n    }\n    fetchParseResultForToken(token) {\n        let parseResult = this.parseResultsByToken.get(token);\n        if (!parseResult) {\n            parseResult = this.parseToken(token);\n            this.parseResultsByToken.set(token, parseResult);\n        }\n        return parseResult;\n    }\n    fetchValuesByTokenForElement(element) {\n        let valuesByToken = this.valuesByTokenByElement.get(element);\n        if (!valuesByToken) {\n            valuesByToken = new Map();\n            this.valuesByTokenByElement.set(element, valuesByToken);\n        }\n        return valuesByToken;\n    }\n    parseToken(token) {\n        try {\n            const value = this.delegate.parseValueForToken(token);\n            return { value };\n        }\n        catch (error) {\n            return { error };\n        }\n    }\n}\n\nclass BindingObserver {\n    constructor(context, delegate) {\n        this.context = context;\n        this.delegate = delegate;\n        this.bindingsByAction = new Map();\n    }\n    start() {\n        if (!this.valueListObserver) {\n            this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);\n            this.valueListObserver.start();\n        }\n    }\n    stop() {\n        if (this.valueListObserver) {\n            this.valueListObserver.stop();\n            delete this.valueListObserver;\n            this.disconnectAllActions();\n        }\n    }\n    get element() {\n        return this.context.element;\n    }\n    get identifier() {\n        return this.context.identifier;\n    }\n    get actionAttribute() {\n        return this.schema.actionAttribute;\n    }\n    get schema() {\n        return this.context.schema;\n    }\n    get bindings() {\n        return Array.from(this.bindingsByAction.values());\n    }\n    connectAction(action) {\n        const binding = new Binding(this.context, action);\n        this.bindingsByAction.set(action, binding);\n        this.delegate.bindingConnected(binding);\n    }\n    disconnectAction(action) {\n        const binding = this.bindingsByAction.get(action);\n        if (binding) {\n            this.bindingsByAction.delete(action);\n            this.delegate.bindingDisconnected(binding);\n        }\n    }\n    disconnectAllActions() {\n        this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true));\n        this.bindingsByAction.clear();\n    }\n    parseValueForToken(token) {\n        const action = Action.forToken(token, this.schema);\n        if (action.identifier == this.identifier) {\n            return action;\n        }\n    }\n    elementMatchedValue(element, action) {\n        this.connectAction(action);\n    }\n    elementUnmatchedValue(element, action) {\n        this.disconnectAction(action);\n    }\n}\n\nclass ValueObserver {\n    constructor(context, receiver) {\n        this.context = context;\n        this.receiver = receiver;\n        this.stringMapObserver = new StringMapObserver(this.element, this);\n        this.valueDescriptorMap = this.controller.valueDescriptorMap;\n    }\n    start() {\n        this.stringMapObserver.start();\n        this.invokeChangedCallbacksForDefaultValues();\n    }\n    stop() {\n        this.stringMapObserver.stop();\n    }\n    get element() {\n        return this.context.element;\n    }\n    get controller() {\n        return this.context.controller;\n    }\n    getStringMapKeyForAttribute(attributeName) {\n        if (attributeName in this.valueDescriptorMap) {\n            return this.valueDescriptorMap[attributeName].name;\n        }\n    }\n    stringMapKeyAdded(key, attributeName) {\n        const descriptor = this.valueDescriptorMap[attributeName];\n        if (!this.hasValue(key)) {\n            this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n        }\n    }\n    stringMapValueChanged(value, name, oldValue) {\n        const descriptor = this.valueDescriptorNameMap[name];\n        if (value === null)\n            return;\n        if (oldValue === null) {\n            oldValue = descriptor.writer(descriptor.defaultValue);\n        }\n        this.invokeChangedCallback(name, value, oldValue);\n    }\n    stringMapKeyRemoved(key, attributeName, oldValue) {\n        const descriptor = this.valueDescriptorNameMap[key];\n        if (this.hasValue(key)) {\n            this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);\n        }\n        else {\n            this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n        }\n    }\n    invokeChangedCallbacksForDefaultValues() {\n        for (const { key, name, defaultValue, writer } of this.valueDescriptors) {\n            if (defaultValue != undefined && !this.controller.data.has(key)) {\n                this.invokeChangedCallback(name, writer(defaultValue), undefined);\n            }\n        }\n    }\n    invokeChangedCallback(name, rawValue, rawOldValue) {\n        const changedMethodName = `${name}Changed`;\n        const changedMethod = this.receiver[changedMethodName];\n        if (typeof changedMethod == \"function\") {\n            const descriptor = this.valueDescriptorNameMap[name];\n            try {\n                const value = descriptor.reader(rawValue);\n                let oldValue = rawOldValue;\n                if (rawOldValue) {\n                    oldValue = descriptor.reader(rawOldValue);\n                }\n                changedMethod.call(this.receiver, value, oldValue);\n            }\n            catch (error) {\n                if (error instanceof TypeError) {\n                    error.message = `Stimulus Value \"${this.context.identifier}.${descriptor.name}\" - ${error.message}`;\n                }\n                throw error;\n            }\n        }\n    }\n    get valueDescriptors() {\n        const { valueDescriptorMap } = this;\n        return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]);\n    }\n    get valueDescriptorNameMap() {\n        const descriptors = {};\n        Object.keys(this.valueDescriptorMap).forEach((key) => {\n            const descriptor = this.valueDescriptorMap[key];\n            descriptors[descriptor.name] = descriptor;\n        });\n        return descriptors;\n    }\n    hasValue(attributeName) {\n        const descriptor = this.valueDescriptorNameMap[attributeName];\n        const hasMethodName = `has${capitalize(descriptor.name)}`;\n        return this.receiver[hasMethodName];\n    }\n}\n\nclass TargetObserver {\n    constructor(context, delegate) {\n        this.context = context;\n        this.delegate = delegate;\n        this.targetsByName = new Multimap();\n    }\n    start() {\n        if (!this.tokenListObserver) {\n            this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);\n            this.tokenListObserver.start();\n        }\n    }\n    stop() {\n        if (this.tokenListObserver) {\n            this.disconnectAllTargets();\n            this.tokenListObserver.stop();\n            delete this.tokenListObserver;\n        }\n    }\n    tokenMatched({ element, content: name }) {\n        if (this.scope.containsElement(element)) {\n            this.connectTarget(element, name);\n        }\n    }\n    tokenUnmatched({ element, content: name }) {\n        this.disconnectTarget(element, name);\n    }\n    connectTarget(element, name) {\n        var _a;\n        if (!this.targetsByName.has(name, element)) {\n            this.targetsByName.add(name, element);\n            (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));\n        }\n    }\n    disconnectTarget(element, name) {\n        var _a;\n        if (this.targetsByName.has(name, element)) {\n            this.targetsByName.delete(name, element);\n            (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));\n        }\n    }\n    disconnectAllTargets() {\n        for (const name of this.targetsByName.keys) {\n            for (const element of this.targetsByName.getValuesForKey(name)) {\n                this.disconnectTarget(element, name);\n            }\n        }\n    }\n    get attributeName() {\n        return `data-${this.context.identifier}-target`;\n    }\n    get element() {\n        return this.context.element;\n    }\n    get scope() {\n        return this.context.scope;\n    }\n}\n\nfunction readInheritableStaticArrayValues(constructor, propertyName) {\n    const ancestors = getAncestorsForConstructor(constructor);\n    return Array.from(ancestors.reduce((values, constructor) => {\n        getOwnStaticArrayValues(constructor, propertyName).forEach((name) => values.add(name));\n        return values;\n    }, new Set()));\n}\nfunction readInheritableStaticObjectPairs(constructor, propertyName) {\n    const ancestors = getAncestorsForConstructor(constructor);\n    return ancestors.reduce((pairs, constructor) => {\n        pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));\n        return pairs;\n    }, []);\n}\nfunction getAncestorsForConstructor(constructor) {\n    const ancestors = [];\n    while (constructor) {\n        ancestors.push(constructor);\n        constructor = Object.getPrototypeOf(constructor);\n    }\n    return ancestors.reverse();\n}\nfunction getOwnStaticArrayValues(constructor, propertyName) {\n    const definition = constructor[propertyName];\n    return Array.isArray(definition) ? definition : [];\n}\nfunction getOwnStaticObjectPairs(constructor, propertyName) {\n    const definition = constructor[propertyName];\n    return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : [];\n}\n\nclass OutletObserver {\n    constructor(context, delegate) {\n        this.started = false;\n        this.context = context;\n        this.delegate = delegate;\n        this.outletsByName = new Multimap();\n        this.outletElementsByName = new Multimap();\n        this.selectorObserverMap = new Map();\n        this.attributeObserverMap = new Map();\n    }\n    start() {\n        if (!this.started) {\n            this.outletDefinitions.forEach((outletName) => {\n                this.setupSelectorObserverForOutlet(outletName);\n                this.setupAttributeObserverForOutlet(outletName);\n            });\n            this.started = true;\n            this.dependentContexts.forEach((context) => context.refresh());\n        }\n    }\n    refresh() {\n        this.selectorObserverMap.forEach((observer) => observer.refresh());\n        this.attributeObserverMap.forEach((observer) => observer.refresh());\n    }\n    stop() {\n        if (this.started) {\n            this.started = false;\n            this.disconnectAllOutlets();\n            this.stopSelectorObservers();\n            this.stopAttributeObservers();\n        }\n    }\n    stopSelectorObservers() {\n        if (this.selectorObserverMap.size > 0) {\n            this.selectorObserverMap.forEach((observer) => observer.stop());\n            this.selectorObserverMap.clear();\n        }\n    }\n    stopAttributeObservers() {\n        if (this.attributeObserverMap.size > 0) {\n            this.attributeObserverMap.forEach((observer) => observer.stop());\n            this.attributeObserverMap.clear();\n        }\n    }\n    selectorMatched(element, _selector, { outletName }) {\n        const outlet = this.getOutlet(element, outletName);\n        if (outlet) {\n            this.connectOutlet(outlet, element, outletName);\n        }\n    }\n    selectorUnmatched(element, _selector, { outletName }) {\n        const outlet = this.getOutletFromMap(element, outletName);\n        if (outlet) {\n            this.disconnectOutlet(outlet, element, outletName);\n        }\n    }\n    selectorMatchElement(element, { outletName }) {\n        const selector = this.selector(outletName);\n        const hasOutlet = this.hasOutlet(element, outletName);\n        const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);\n        if (selector) {\n            return hasOutlet && hasOutletController && element.matches(selector);\n        }\n        else {\n            return false;\n        }\n    }\n    elementMatchedAttribute(_element, attributeName) {\n        const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n        if (outletName) {\n            this.updateSelectorObserverForOutlet(outletName);\n        }\n    }\n    elementAttributeValueChanged(_element, attributeName) {\n        const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n        if (outletName) {\n            this.updateSelectorObserverForOutlet(outletName);\n        }\n    }\n    elementUnmatchedAttribute(_element, attributeName) {\n        const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n        if (outletName) {\n            this.updateSelectorObserverForOutlet(outletName);\n        }\n    }\n    connectOutlet(outlet, element, outletName) {\n        var _a;\n        if (!this.outletElementsByName.has(outletName, element)) {\n            this.outletsByName.add(outletName, outlet);\n            this.outletElementsByName.add(outletName, element);\n            (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));\n        }\n    }\n    disconnectOutlet(outlet, element, outletName) {\n        var _a;\n        if (this.outletElementsByName.has(outletName, element)) {\n            this.outletsByName.delete(outletName, outlet);\n            this.outletElementsByName.delete(outletName, element);\n            (_a = this.selectorObserverMap\n                .get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));\n        }\n    }\n    disconnectAllOutlets() {\n        for (const outletName of this.outletElementsByName.keys) {\n            for (const element of this.outletElementsByName.getValuesForKey(outletName)) {\n                for (const outlet of this.outletsByName.getValuesForKey(outletName)) {\n                    this.disconnectOutlet(outlet, element, outletName);\n                }\n            }\n        }\n    }\n    updateSelectorObserverForOutlet(outletName) {\n        const observer = this.selectorObserverMap.get(outletName);\n        if (observer) {\n            observer.selector = this.selector(outletName);\n        }\n    }\n    setupSelectorObserverForOutlet(outletName) {\n        const selector = this.selector(outletName);\n        const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName });\n        this.selectorObserverMap.set(outletName, selectorObserver);\n        selectorObserver.start();\n    }\n    setupAttributeObserverForOutlet(outletName) {\n        const attributeName = this.attributeNameForOutletName(outletName);\n        const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);\n        this.attributeObserverMap.set(outletName, attributeObserver);\n        attributeObserver.start();\n    }\n    selector(outletName) {\n        return this.scope.outlets.getSelectorForOutletName(outletName);\n    }\n    attributeNameForOutletName(outletName) {\n        return this.scope.schema.outletAttributeForScope(this.identifier, outletName);\n    }\n    getOutletNameFromOutletAttributeName(attributeName) {\n        return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName);\n    }\n    get outletDependencies() {\n        const dependencies = new Multimap();\n        this.router.modules.forEach((module) => {\n            const constructor = module.definition.controllerConstructor;\n            const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n            outlets.forEach((outlet) => dependencies.add(outlet, module.identifier));\n        });\n        return dependencies;\n    }\n    get outletDefinitions() {\n        return this.outletDependencies.getKeysForValue(this.identifier);\n    }\n    get dependentControllerIdentifiers() {\n        return this.outletDependencies.getValuesForKey(this.identifier);\n    }\n    get dependentContexts() {\n        const identifiers = this.dependentControllerIdentifiers;\n        return this.router.contexts.filter((context) => identifiers.includes(context.identifier));\n    }\n    hasOutlet(element, outletName) {\n        return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);\n    }\n    getOutlet(element, outletName) {\n        return this.application.getControllerForElementAndIdentifier(element, outletName);\n    }\n    getOutletFromMap(element, outletName) {\n        return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element);\n    }\n    get scope() {\n        return this.context.scope;\n    }\n    get schema() {\n        return this.context.schema;\n    }\n    get identifier() {\n        return this.context.identifier;\n    }\n    get application() {\n        return this.context.application;\n    }\n    get router() {\n        return this.application.router;\n    }\n}\n\nclass Context {\n    constructor(module, scope) {\n        this.logDebugActivity = (functionName, detail = {}) => {\n            const { identifier, controller, element } = this;\n            detail = Object.assign({ identifier, controller, element }, detail);\n            this.application.logDebugActivity(this.identifier, functionName, detail);\n        };\n        this.module = module;\n        this.scope = scope;\n        this.controller = new module.controllerConstructor(this);\n        this.bindingObserver = new BindingObserver(this, this.dispatcher);\n        this.valueObserver = new ValueObserver(this, this.controller);\n        this.targetObserver = new TargetObserver(this, this);\n        this.outletObserver = new OutletObserver(this, this);\n        try {\n            this.controller.initialize();\n            this.logDebugActivity(\"initialize\");\n        }\n        catch (error) {\n            this.handleError(error, \"initializing controller\");\n        }\n    }\n    connect() {\n        this.bindingObserver.start();\n        this.valueObserver.start();\n        this.targetObserver.start();\n        this.outletObserver.start();\n        try {\n            this.controller.connect();\n            this.logDebugActivity(\"connect\");\n        }\n        catch (error) {\n            this.handleError(error, \"connecting controller\");\n        }\n    }\n    refresh() {\n        this.outletObserver.refresh();\n    }\n    disconnect() {\n        try {\n            this.controller.disconnect();\n            this.logDebugActivity(\"disconnect\");\n        }\n        catch (error) {\n            this.handleError(error, \"disconnecting controller\");\n        }\n        this.outletObserver.stop();\n        this.targetObserver.stop();\n        this.valueObserver.stop();\n        this.bindingObserver.stop();\n    }\n    get application() {\n        return this.module.application;\n    }\n    get identifier() {\n        return this.module.identifier;\n    }\n    get schema() {\n        return this.application.schema;\n    }\n    get dispatcher() {\n        return this.application.dispatcher;\n    }\n    get element() {\n        return this.scope.element;\n    }\n    get parentElement() {\n        return this.element.parentElement;\n    }\n    handleError(error, message, detail = {}) {\n        const { identifier, controller, element } = this;\n        detail = Object.assign({ identifier, controller, element }, detail);\n        this.application.handleError(error, `Error ${message}`, detail);\n    }\n    targetConnected(element, name) {\n        this.invokeControllerMethod(`${name}TargetConnected`, element);\n    }\n    targetDisconnected(element, name) {\n        this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n    }\n    outletConnected(outlet, element, name) {\n        this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);\n    }\n    outletDisconnected(outlet, element, name) {\n        this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);\n    }\n    invokeControllerMethod(methodName, ...args) {\n        const controller = this.controller;\n        if (typeof controller[methodName] == \"function\") {\n            controller[methodName](...args);\n        }\n    }\n}\n\nfunction bless(constructor) {\n    return shadow(constructor, getBlessedProperties(constructor));\n}\nfunction shadow(constructor, properties) {\n    const shadowConstructor = extend(constructor);\n    const shadowProperties = getShadowProperties(constructor.prototype, properties);\n    Object.defineProperties(shadowConstructor.prototype, shadowProperties);\n    return shadowConstructor;\n}\nfunction getBlessedProperties(constructor) {\n    const blessings = readInheritableStaticArrayValues(constructor, \"blessings\");\n    return blessings.reduce((blessedProperties, blessing) => {\n        const properties = blessing(constructor);\n        for (const key in properties) {\n            const descriptor = blessedProperties[key] || {};\n            blessedProperties[key] = Object.assign(descriptor, properties[key]);\n        }\n        return blessedProperties;\n    }, {});\n}\nfunction getShadowProperties(prototype, properties) {\n    return getOwnKeys(properties).reduce((shadowProperties, key) => {\n        const descriptor = getShadowedDescriptor(prototype, properties, key);\n        if (descriptor) {\n            Object.assign(shadowProperties, { [key]: descriptor });\n        }\n        return shadowProperties;\n    }, {});\n}\nfunction getShadowedDescriptor(prototype, properties, key) {\n    const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);\n    const shadowedByValue = shadowingDescriptor && \"value\" in shadowingDescriptor;\n    if (!shadowedByValue) {\n        const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;\n        if (shadowingDescriptor) {\n            descriptor.get = shadowingDescriptor.get || descriptor.get;\n            descriptor.set = shadowingDescriptor.set || descriptor.set;\n        }\n        return descriptor;\n    }\n}\nconst getOwnKeys = (() => {\n    if (typeof Object.getOwnPropertySymbols == \"function\") {\n        return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];\n    }\n    else {\n        return Object.getOwnPropertyNames;\n    }\n})();\nconst extend = (() => {\n    function extendWithReflect(constructor) {\n        function extended() {\n            return Reflect.construct(constructor, arguments, new.target);\n        }\n        extended.prototype = Object.create(constructor.prototype, {\n            constructor: { value: extended },\n        });\n        Reflect.setPrototypeOf(extended, constructor);\n        return extended;\n    }\n    function testReflectExtension() {\n        const a = function () {\n            this.a.call(this);\n        };\n        const b = extendWithReflect(a);\n        b.prototype.a = function () { };\n        return new b();\n    }\n    try {\n        testReflectExtension();\n        return extendWithReflect;\n    }\n    catch (error) {\n        return (constructor) => class extended extends constructor {\n        };\n    }\n})();\n\nfunction blessDefinition(definition) {\n    return {\n        identifier: definition.identifier,\n        controllerConstructor: bless(definition.controllerConstructor),\n    };\n}\n\nclass Module {\n    constructor(application, definition) {\n        this.application = application;\n        this.definition = blessDefinition(definition);\n        this.contextsByScope = new WeakMap();\n        this.connectedContexts = new Set();\n    }\n    get identifier() {\n        return this.definition.identifier;\n    }\n    get controllerConstructor() {\n        return this.definition.controllerConstructor;\n    }\n    get contexts() {\n        return Array.from(this.connectedContexts);\n    }\n    connectContextForScope(scope) {\n        const context = this.fetchContextForScope(scope);\n        this.connectedContexts.add(context);\n        context.connect();\n    }\n    disconnectContextForScope(scope) {\n        const context = this.contextsByScope.get(scope);\n        if (context) {\n            this.connectedContexts.delete(context);\n            context.disconnect();\n        }\n    }\n    fetchContextForScope(scope) {\n        let context = this.contextsByScope.get(scope);\n        if (!context) {\n            context = new Context(this, scope);\n            this.contextsByScope.set(scope, context);\n        }\n        return context;\n    }\n}\n\nclass ClassMap {\n    constructor(scope) {\n        this.scope = scope;\n    }\n    has(name) {\n        return this.data.has(this.getDataKey(name));\n    }\n    get(name) {\n        return this.getAll(name)[0];\n    }\n    getAll(name) {\n        const tokenString = this.data.get(this.getDataKey(name)) || \"\";\n        return tokenize(tokenString);\n    }\n    getAttributeName(name) {\n        return this.data.getAttributeNameForKey(this.getDataKey(name));\n    }\n    getDataKey(name) {\n        return `${name}-class`;\n    }\n    get data() {\n        return this.scope.data;\n    }\n}\n\nclass DataMap {\n    constructor(scope) {\n        this.scope = scope;\n    }\n    get element() {\n        return this.scope.element;\n    }\n    get identifier() {\n        return this.scope.identifier;\n    }\n    get(key) {\n        const name = this.getAttributeNameForKey(key);\n        return this.element.getAttribute(name);\n    }\n    set(key, value) {\n        const name = this.getAttributeNameForKey(key);\n        this.element.setAttribute(name, value);\n        return this.get(key);\n    }\n    has(key) {\n        const name = this.getAttributeNameForKey(key);\n        return this.element.hasAttribute(name);\n    }\n    delete(key) {\n        if (this.has(key)) {\n            const name = this.getAttributeNameForKey(key);\n            this.element.removeAttribute(name);\n            return true;\n        }\n        else {\n            return false;\n        }\n    }\n    getAttributeNameForKey(key) {\n        return `data-${this.identifier}-${dasherize(key)}`;\n    }\n}\n\nclass Guide {\n    constructor(logger) {\n        this.warnedKeysByObject = new WeakMap();\n        this.logger = logger;\n    }\n    warn(object, key, message) {\n        let warnedKeys = this.warnedKeysByObject.get(object);\n        if (!warnedKeys) {\n            warnedKeys = new Set();\n            this.warnedKeysByObject.set(object, warnedKeys);\n        }\n        if (!warnedKeys.has(key)) {\n            warnedKeys.add(key);\n            this.logger.warn(message, object);\n        }\n    }\n}\n\nfunction attributeValueContainsToken(attributeName, token) {\n    return `[${attributeName}~=\"${token}\"]`;\n}\n\nclass TargetSet {\n    constructor(scope) {\n        this.scope = scope;\n    }\n    get element() {\n        return this.scope.element;\n    }\n    get identifier() {\n        return this.scope.identifier;\n    }\n    get schema() {\n        return this.scope.schema;\n    }\n    has(targetName) {\n        return this.find(targetName) != null;\n    }\n    find(...targetNames) {\n        return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);\n    }\n    findAll(...targetNames) {\n        return targetNames.reduce((targets, targetName) => [\n            ...targets,\n            ...this.findAllTargets(targetName),\n            ...this.findAllLegacyTargets(targetName),\n        ], []);\n    }\n    findTarget(targetName) {\n        const selector = this.getSelectorForTargetName(targetName);\n        return this.scope.findElement(selector);\n    }\n    findAllTargets(targetName) {\n        const selector = this.getSelectorForTargetName(targetName);\n        return this.scope.findAllElements(selector);\n    }\n    getSelectorForTargetName(targetName) {\n        const attributeName = this.schema.targetAttributeForScope(this.identifier);\n        return attributeValueContainsToken(attributeName, targetName);\n    }\n    findLegacyTarget(targetName) {\n        const selector = this.getLegacySelectorForTargetName(targetName);\n        return this.deprecate(this.scope.findElement(selector), targetName);\n    }\n    findAllLegacyTargets(targetName) {\n        const selector = this.getLegacySelectorForTargetName(targetName);\n        return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName));\n    }\n    getLegacySelectorForTargetName(targetName) {\n        const targetDescriptor = `${this.identifier}.${targetName}`;\n        return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);\n    }\n    deprecate(element, targetName) {\n        if (element) {\n            const { identifier } = this;\n            const attributeName = this.schema.targetAttribute;\n            const revisedAttributeName = this.schema.targetAttributeForScope(identifier);\n            this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}=\"${identifier}.${targetName}\" with ${revisedAttributeName}=\"${targetName}\". ` +\n                `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);\n        }\n        return element;\n    }\n    get guide() {\n        return this.scope.guide;\n    }\n}\n\nclass OutletSet {\n    constructor(scope, controllerElement) {\n        this.scope = scope;\n        this.controllerElement = controllerElement;\n    }\n    get element() {\n        return this.scope.element;\n    }\n    get identifier() {\n        return this.scope.identifier;\n    }\n    get schema() {\n        return this.scope.schema;\n    }\n    has(outletName) {\n        return this.find(outletName) != null;\n    }\n    find(...outletNames) {\n        return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);\n    }\n    findAll(...outletNames) {\n        return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);\n    }\n    getSelectorForOutletName(outletName) {\n        const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);\n        return this.controllerElement.getAttribute(attributeName);\n    }\n    findOutlet(outletName) {\n        const selector = this.getSelectorForOutletName(outletName);\n        if (selector)\n            return this.findElement(selector, outletName);\n    }\n    findAllOutlets(outletName) {\n        const selector = this.getSelectorForOutletName(outletName);\n        return selector ? this.findAllElements(selector, outletName) : [];\n    }\n    findElement(selector, outletName) {\n        const elements = this.scope.queryElements(selector);\n        return elements.filter((element) => this.matchesElement(element, selector, outletName))[0];\n    }\n    findAllElements(selector, outletName) {\n        const elements = this.scope.queryElements(selector);\n        return elements.filter((element) => this.matchesElement(element, selector, outletName));\n    }\n    matchesElement(element, selector, outletName) {\n        const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || \"\";\n        return element.matches(selector) && controllerAttribute.split(\" \").includes(outletName);\n    }\n}\n\nclass Scope {\n    constructor(schema, element, identifier, logger) {\n        this.targets = new TargetSet(this);\n        this.classes = new ClassMap(this);\n        this.data = new DataMap(this);\n        this.containsElement = (element) => {\n            return element.closest(this.controllerSelector) === this.element;\n        };\n        this.schema = schema;\n        this.element = element;\n        this.identifier = identifier;\n        this.guide = new Guide(logger);\n        this.outlets = new OutletSet(this.documentScope, element);\n    }\n    findElement(selector) {\n        return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);\n    }\n    findAllElements(selector) {\n        return [\n            ...(this.element.matches(selector) ? [this.element] : []),\n            ...this.queryElements(selector).filter(this.containsElement),\n        ];\n    }\n    queryElements(selector) {\n        return Array.from(this.element.querySelectorAll(selector));\n    }\n    get controllerSelector() {\n        return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n    }\n    get isDocumentScope() {\n        return this.element === document.documentElement;\n    }\n    get documentScope() {\n        return this.isDocumentScope\n            ? this\n            : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);\n    }\n}\n\nclass ScopeObserver {\n    constructor(element, schema, delegate) {\n        this.element = element;\n        this.schema = schema;\n        this.delegate = delegate;\n        this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);\n        this.scopesByIdentifierByElement = new WeakMap();\n        this.scopeReferenceCounts = new WeakMap();\n    }\n    start() {\n        this.valueListObserver.start();\n    }\n    stop() {\n        this.valueListObserver.stop();\n    }\n    get controllerAttribute() {\n        return this.schema.controllerAttribute;\n    }\n    parseValueForToken(token) {\n        const { element, content: identifier } = token;\n        return this.parseValueForElementAndIdentifier(element, identifier);\n    }\n    parseValueForElementAndIdentifier(element, identifier) {\n        const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n        let scope = scopesByIdentifier.get(identifier);\n        if (!scope) {\n            scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n            scopesByIdentifier.set(identifier, scope);\n        }\n        return scope;\n    }\n    elementMatchedValue(element, value) {\n        const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n        this.scopeReferenceCounts.set(value, referenceCount);\n        if (referenceCount == 1) {\n            this.delegate.scopeConnected(value);\n        }\n    }\n    elementUnmatchedValue(element, value) {\n        const referenceCount = this.scopeReferenceCounts.get(value);\n        if (referenceCount) {\n            this.scopeReferenceCounts.set(value, referenceCount - 1);\n            if (referenceCount == 1) {\n                this.delegate.scopeDisconnected(value);\n            }\n        }\n    }\n    fetchScopesByIdentifierForElement(element) {\n        let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n        if (!scopesByIdentifier) {\n            scopesByIdentifier = new Map();\n            this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n        }\n        return scopesByIdentifier;\n    }\n}\n\nclass Router {\n    constructor(application) {\n        this.application = application;\n        this.scopeObserver = new ScopeObserver(this.element, this.schema, this);\n        this.scopesByIdentifier = new Multimap();\n        this.modulesByIdentifier = new Map();\n    }\n    get element() {\n        return this.application.element;\n    }\n    get schema() {\n        return this.application.schema;\n    }\n    get logger() {\n        return this.application.logger;\n    }\n    get controllerAttribute() {\n        return this.schema.controllerAttribute;\n    }\n    get modules() {\n        return Array.from(this.modulesByIdentifier.values());\n    }\n    get contexts() {\n        return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);\n    }\n    start() {\n        this.scopeObserver.start();\n    }\n    stop() {\n        this.scopeObserver.stop();\n    }\n    loadDefinition(definition) {\n        this.unloadIdentifier(definition.identifier);\n        const module = new Module(this.application, definition);\n        this.connectModule(module);\n        const afterLoad = definition.controllerConstructor.afterLoad;\n        if (afterLoad) {\n            afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);\n        }\n    }\n    unloadIdentifier(identifier) {\n        const module = this.modulesByIdentifier.get(identifier);\n        if (module) {\n            this.disconnectModule(module);\n        }\n    }\n    getContextForElementAndIdentifier(element, identifier) {\n        const module = this.modulesByIdentifier.get(identifier);\n        if (module) {\n            return module.contexts.find((context) => context.element == element);\n        }\n    }\n    proposeToConnectScopeForElementAndIdentifier(element, identifier) {\n        const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);\n        if (scope) {\n            this.scopeObserver.elementMatchedValue(scope.element, scope);\n        }\n        else {\n            console.error(`Couldn't find or create scope for identifier: \"${identifier}\" and element:`, element);\n        }\n    }\n    handleError(error, message, detail) {\n        this.application.handleError(error, message, detail);\n    }\n    createScopeForElementAndIdentifier(element, identifier) {\n        return new Scope(this.schema, element, identifier, this.logger);\n    }\n    scopeConnected(scope) {\n        this.scopesByIdentifier.add(scope.identifier, scope);\n        const module = this.modulesByIdentifier.get(scope.identifier);\n        if (module) {\n            module.connectContextForScope(scope);\n        }\n    }\n    scopeDisconnected(scope) {\n        this.scopesByIdentifier.delete(scope.identifier, scope);\n        const module = this.modulesByIdentifier.get(scope.identifier);\n        if (module) {\n            module.disconnectContextForScope(scope);\n        }\n    }\n    connectModule(module) {\n        this.modulesByIdentifier.set(module.identifier, module);\n        const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n        scopes.forEach((scope) => module.connectContextForScope(scope));\n    }\n    disconnectModule(module) {\n        this.modulesByIdentifier.delete(module.identifier);\n        const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n        scopes.forEach((scope) => module.disconnectContextForScope(scope));\n    }\n}\n\nconst defaultSchema = {\n    controllerAttribute: \"data-controller\",\n    actionAttribute: \"data-action\",\n    targetAttribute: \"data-target\",\n    targetAttributeForScope: (identifier) => `data-${identifier}-target`,\n    outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,\n    keyMappings: Object.assign(Object.assign({ enter: \"Enter\", tab: \"Tab\", esc: \"Escape\", space: \" \", up: \"ArrowUp\", down: \"ArrowDown\", left: \"ArrowLeft\", right: \"ArrowRight\", home: \"Home\", end: \"End\", page_up: \"PageUp\", page_down: \"PageDown\" }, objectFromEntries(\"abcdefghijklmnopqrstuvwxyz\".split(\"\").map((c) => [c, c]))), objectFromEntries(\"0123456789\".split(\"\").map((n) => [n, n]))),\n};\nfunction objectFromEntries(array) {\n    return array.reduce((memo, [k, v]) => (Object.assign(Object.assign({}, memo), { [k]: v })), {});\n}\n\nclass Application {\n    constructor(element = document.documentElement, schema = defaultSchema) {\n        this.logger = console;\n        this.debug = false;\n        this.logDebugActivity = (identifier, functionName, detail = {}) => {\n            if (this.debug) {\n                this.logFormattedMessage(identifier, functionName, detail);\n            }\n        };\n        this.element = element;\n        this.schema = schema;\n        this.dispatcher = new Dispatcher(this);\n        this.router = new Router(this);\n        this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);\n    }\n    static start(element, schema) {\n        const application = new this(element, schema);\n        application.start();\n        return application;\n    }\n    async start() {\n        await domReady();\n        this.logDebugActivity(\"application\", \"starting\");\n        this.dispatcher.start();\n        this.router.start();\n        this.logDebugActivity(\"application\", \"start\");\n    }\n    stop() {\n        this.logDebugActivity(\"application\", \"stopping\");\n        this.dispatcher.stop();\n        this.router.stop();\n        this.logDebugActivity(\"application\", \"stop\");\n    }\n    register(identifier, controllerConstructor) {\n        this.load({ identifier, controllerConstructor });\n    }\n    registerActionOption(name, filter) {\n        this.actionDescriptorFilters[name] = filter;\n    }\n    load(head, ...rest) {\n        const definitions = Array.isArray(head) ? head : [head, ...rest];\n        definitions.forEach((definition) => {\n            if (definition.controllerConstructor.shouldLoad) {\n                this.router.loadDefinition(definition);\n            }\n        });\n    }\n    unload(head, ...rest) {\n        const identifiers = Array.isArray(head) ? head : [head, ...rest];\n        identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier));\n    }\n    get controllers() {\n        return this.router.contexts.map((context) => context.controller);\n    }\n    getControllerForElementAndIdentifier(element, identifier) {\n        const context = this.router.getContextForElementAndIdentifier(element, identifier);\n        return context ? context.controller : null;\n    }\n    handleError(error, message, detail) {\n        var _a;\n        this.logger.error(`%s\\n\\n%o\\n\\n%o`, message, error, detail);\n        (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, \"\", 0, 0, error);\n    }\n    logFormattedMessage(identifier, functionName, detail = {}) {\n        detail = Object.assign({ application: this }, detail);\n        this.logger.groupCollapsed(`${identifier} #${functionName}`);\n        this.logger.log(\"details:\", Object.assign({}, detail));\n        this.logger.groupEnd();\n    }\n}\nfunction domReady() {\n    return new Promise((resolve) => {\n        if (document.readyState == \"loading\") {\n            document.addEventListener(\"DOMContentLoaded\", () => resolve());\n        }\n        else {\n            resolve();\n        }\n    });\n}\n\nfunction ClassPropertiesBlessing(constructor) {\n    const classes = readInheritableStaticArrayValues(constructor, \"classes\");\n    return classes.reduce((properties, classDefinition) => {\n        return Object.assign(properties, propertiesForClassDefinition(classDefinition));\n    }, {});\n}\nfunction propertiesForClassDefinition(key) {\n    return {\n        [`${key}Class`]: {\n            get() {\n                const { classes } = this;\n                if (classes.has(key)) {\n                    return classes.get(key);\n                }\n                else {\n                    const attribute = classes.getAttributeName(key);\n                    throw new Error(`Missing attribute \"${attribute}\"`);\n                }\n            },\n        },\n        [`${key}Classes`]: {\n            get() {\n                return this.classes.getAll(key);\n            },\n        },\n        [`has${capitalize(key)}Class`]: {\n            get() {\n                return this.classes.has(key);\n            },\n        },\n    };\n}\n\nfunction OutletPropertiesBlessing(constructor) {\n    const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n    return outlets.reduce((properties, outletDefinition) => {\n        return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));\n    }, {});\n}\nfunction getOutletController(controller, element, identifier) {\n    return controller.application.getControllerForElementAndIdentifier(element, identifier);\n}\nfunction getControllerAndEnsureConnectedScope(controller, element, outletName) {\n    let outletController = getOutletController(controller, element, outletName);\n    if (outletController)\n        return outletController;\n    controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);\n    outletController = getOutletController(controller, element, outletName);\n    if (outletController)\n        return outletController;\n}\nfunction propertiesForOutletDefinition(name) {\n    const camelizedName = namespaceCamelize(name);\n    return {\n        [`${camelizedName}Outlet`]: {\n            get() {\n                const outletElement = this.outlets.find(name);\n                const selector = this.outlets.getSelectorForOutletName(name);\n                if (outletElement) {\n                    const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n                    if (outletController)\n                        return outletController;\n                    throw new Error(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`);\n                }\n                throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n            },\n        },\n        [`${camelizedName}Outlets`]: {\n            get() {\n                const outlets = this.outlets.findAll(name);\n                if (outlets.length > 0) {\n                    return outlets\n                        .map((outletElement) => {\n                        const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n                        if (outletController)\n                            return outletController;\n                        console.warn(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`, outletElement);\n                    })\n                        .filter((controller) => controller);\n                }\n                return [];\n            },\n        },\n        [`${camelizedName}OutletElement`]: {\n            get() {\n                const outletElement = this.outlets.find(name);\n                const selector = this.outlets.getSelectorForOutletName(name);\n                if (outletElement) {\n                    return outletElement;\n                }\n                else {\n                    throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n                }\n            },\n        },\n        [`${camelizedName}OutletElements`]: {\n            get() {\n                return this.outlets.findAll(name);\n            },\n        },\n        [`has${capitalize(camelizedName)}Outlet`]: {\n            get() {\n                return this.outlets.has(name);\n            },\n        },\n    };\n}\n\nfunction TargetPropertiesBlessing(constructor) {\n    const targets = readInheritableStaticArrayValues(constructor, \"targets\");\n    return targets.reduce((properties, targetDefinition) => {\n        return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));\n    }, {});\n}\nfunction propertiesForTargetDefinition(name) {\n    return {\n        [`${name}Target`]: {\n            get() {\n                const target = this.targets.find(name);\n                if (target) {\n                    return target;\n                }\n                else {\n                    throw new Error(`Missing target element \"${name}\" for \"${this.identifier}\" controller`);\n                }\n            },\n        },\n        [`${name}Targets`]: {\n            get() {\n                return this.targets.findAll(name);\n            },\n        },\n        [`has${capitalize(name)}Target`]: {\n            get() {\n                return this.targets.has(name);\n            },\n        },\n    };\n}\n\nfunction ValuePropertiesBlessing(constructor) {\n    const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, \"values\");\n    const propertyDescriptorMap = {\n        valueDescriptorMap: {\n            get() {\n                return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {\n                    const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);\n                    const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n                    return Object.assign(result, { [attributeName]: valueDescriptor });\n                }, {});\n            },\n        },\n    };\n    return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n        return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n    }, propertyDescriptorMap);\n}\nfunction propertiesForValueDefinitionPair(valueDefinitionPair, controller) {\n    const definition = parseValueDefinitionPair(valueDefinitionPair, controller);\n    const { key, name, reader: read, writer: write } = definition;\n    return {\n        [name]: {\n            get() {\n                const value = this.data.get(key);\n                if (value !== null) {\n                    return read(value);\n                }\n                else {\n                    return definition.defaultValue;\n                }\n            },\n            set(value) {\n                if (value === undefined) {\n                    this.data.delete(key);\n                }\n                else {\n                    this.data.set(key, write(value));\n                }\n            },\n        },\n        [`has${capitalize(name)}`]: {\n            get() {\n                return this.data.has(key) || definition.hasCustomDefaultValue;\n            },\n        },\n    };\n}\nfunction parseValueDefinitionPair([token, typeDefinition], controller) {\n    return valueDescriptorForTokenAndTypeDefinition({\n        controller,\n        token,\n        typeDefinition,\n    });\n}\nfunction parseValueTypeConstant(constant) {\n    switch (constant) {\n        case Array:\n            return \"array\";\n        case Boolean:\n            return \"boolean\";\n        case Number:\n            return \"number\";\n        case Object:\n            return \"object\";\n        case String:\n            return \"string\";\n    }\n}\nfunction parseValueTypeDefault(defaultValue) {\n    switch (typeof defaultValue) {\n        case \"boolean\":\n            return \"boolean\";\n        case \"number\":\n            return \"number\";\n        case \"string\":\n            return \"string\";\n    }\n    if (Array.isArray(defaultValue))\n        return \"array\";\n    if (Object.prototype.toString.call(defaultValue) === \"[object Object]\")\n        return \"object\";\n}\nfunction parseValueTypeObject(payload) {\n    const { controller, token, typeObject } = payload;\n    const hasType = isSomething(typeObject.type);\n    const hasDefault = isSomething(typeObject.default);\n    const fullObject = hasType && hasDefault;\n    const onlyType = hasType && !hasDefault;\n    const onlyDefault = !hasType && hasDefault;\n    const typeFromObject = parseValueTypeConstant(typeObject.type);\n    const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);\n    if (onlyType)\n        return typeFromObject;\n    if (onlyDefault)\n        return typeFromDefaultValue;\n    if (typeFromObject !== typeFromDefaultValue) {\n        const propertyPath = controller ? `${controller}.${token}` : token;\n        throw new Error(`The specified default value for the Stimulus Value \"${propertyPath}\" must match the defined type \"${typeFromObject}\". The provided default value of \"${typeObject.default}\" is of type \"${typeFromDefaultValue}\".`);\n    }\n    if (fullObject)\n        return typeFromObject;\n}\nfunction parseValueTypeDefinition(payload) {\n    const { controller, token, typeDefinition } = payload;\n    const typeObject = { controller, token, typeObject: typeDefinition };\n    const typeFromObject = parseValueTypeObject(typeObject);\n    const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n    const typeFromConstant = parseValueTypeConstant(typeDefinition);\n    const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n    if (type)\n        return type;\n    const propertyPath = controller ? `${controller}.${typeDefinition}` : token;\n    throw new Error(`Unknown value type \"${propertyPath}\" for \"${token}\" value`);\n}\nfunction defaultValueForDefinition(typeDefinition) {\n    const constant = parseValueTypeConstant(typeDefinition);\n    if (constant)\n        return defaultValuesByType[constant];\n    const hasDefault = hasProperty(typeDefinition, \"default\");\n    const hasType = hasProperty(typeDefinition, \"type\");\n    const typeObject = typeDefinition;\n    if (hasDefault)\n        return typeObject.default;\n    if (hasType) {\n        const { type } = typeObject;\n        const constantFromType = parseValueTypeConstant(type);\n        if (constantFromType)\n            return defaultValuesByType[constantFromType];\n    }\n    return typeDefinition;\n}\nfunction valueDescriptorForTokenAndTypeDefinition(payload) {\n    const { token, typeDefinition } = payload;\n    const key = `${dasherize(token)}-value`;\n    const type = parseValueTypeDefinition(payload);\n    return {\n        type,\n        key,\n        name: camelize(key),\n        get defaultValue() {\n            return defaultValueForDefinition(typeDefinition);\n        },\n        get hasCustomDefaultValue() {\n            return parseValueTypeDefault(typeDefinition) !== undefined;\n        },\n        reader: readers[type],\n        writer: writers[type] || writers.default,\n    };\n}\nconst defaultValuesByType = {\n    get array() {\n        return [];\n    },\n    boolean: false,\n    number: 0,\n    get object() {\n        return {};\n    },\n    string: \"\",\n};\nconst readers = {\n    array(value) {\n        const array = JSON.parse(value);\n        if (!Array.isArray(array)) {\n            throw new TypeError(`expected value of type \"array\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(array)}\"`);\n        }\n        return array;\n    },\n    boolean(value) {\n        return !(value == \"0\" || String(value).toLowerCase() == \"false\");\n    },\n    number(value) {\n        return Number(value.replace(/_/g, \"\"));\n    },\n    object(value) {\n        const object = JSON.parse(value);\n        if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n            throw new TypeError(`expected value of type \"object\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(object)}\"`);\n        }\n        return object;\n    },\n    string(value) {\n        return value;\n    },\n};\nconst writers = {\n    default: writeString,\n    array: writeJSON,\n    object: writeJSON,\n};\nfunction writeJSON(value) {\n    return JSON.stringify(value);\n}\nfunction writeString(value) {\n    return `${value}`;\n}\n\nclass Controller {\n    constructor(context) {\n        this.context = context;\n    }\n    static get shouldLoad() {\n        return true;\n    }\n    static afterLoad(_identifier, _application) {\n        return;\n    }\n    get application() {\n        return this.context.application;\n    }\n    get scope() {\n        return this.context.scope;\n    }\n    get element() {\n        return this.scope.element;\n    }\n    get identifier() {\n        return this.scope.identifier;\n    }\n    get targets() {\n        return this.scope.targets;\n    }\n    get outlets() {\n        return this.scope.outlets;\n    }\n    get classes() {\n        return this.scope.classes;\n    }\n    get data() {\n        return this.scope.data;\n    }\n    initialize() {\n    }\n    connect() {\n    }\n    disconnect() {\n    }\n    dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true, } = {}) {\n        const type = prefix ? `${prefix}:${eventName}` : eventName;\n        const event = new CustomEvent(type, { detail, bubbles, cancelable });\n        target.dispatchEvent(event);\n        return event;\n    }\n}\nController.blessings = [\n    ClassPropertiesBlessing,\n    TargetPropertiesBlessing,\n    ValuePropertiesBlessing,\n    OutletPropertiesBlessing,\n];\nController.targets = [];\nController.outlets = [];\nController.values = {};\n\nexport { Application, AttributeObserver, Context, Controller, ElementObserver, IndexedMultimap, Multimap, SelectorObserver, StringMapObserver, TokenListObserver, ValueListObserver, add, defaultSchema, del, fetch, prune };\n", "import { Application } from \"@hotwired/stimulus\"\n\nconst application = Application.start()\n\n// Configure Stimulus development experience\napplication.debug = false\nwindow.Stimulus   = application\n\nexport { application }\n", "const chars =\n    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~';\nconst decode83 = (str, start, end) => {\n    let value = 0;\n    while (start < end) {\n        value = value * 83 + chars.indexOf(str[start++]);\n    }\n    return value;\n};\n\nconst pow = Math.pow;\nconst PI = Math.PI;\n\nconst d = 3294.6;\nconst e = 269.025;\nconst sRGBToLinear = (value) =>\n    value > 10.31475 ? pow(value / e + 0.052132, 2.4) : value / d;\n\nconst linearTosRGB = (v) =>\n    ~~(v > 0.00001227 ? e * pow(v, 0.416666) - 13.025 : v * d + 1);\n\n// linear -> sRGB is by far the hottest part of decoding (3 conversions per\n// output pixel). The curve only depends on the linear value, so it is sampled\n// once over [0, 1] at module load into a lookup table and reused for every\n// pixel. Values outside [0, 1] clamp to the 0/255 ends like the exact formula.\nconst LUT_SIZE = 4096;\nconst sRGBLookup = new Uint8ClampedArray(LUT_SIZE + 1);\nfor (let i = 0; i <= LUT_SIZE; i++) {\n    sRGBLookup[i] = linearTosRGB(i / LUT_SIZE);\n}\nconst fastLinearTosRGB = (v) =>\n    v <= 0 ? 0 : v >= 1 ? 255 : sRGBLookup[(v * LUT_SIZE + 0.5) | 0];\n\nconst signSqr = (x) => (x < 0 ? -1 : 1) * x * x;\n\n/**\n * Fast approximate cosine implementation\n * Based on FTrig https://github.com/netcell/FTrig\n */\nconst fastCos = (x) => {\n    for (x += PI / 2; x > PI; ) {\n        x -= PI * 2;\n    }\n    const cos = 1.27323954 * x - 0.405284735 * signSqr(x);\n    return 0.225 * (signSqr(cos) - cos) + cos;\n};\n\n/**\n * Extracts average color from BlurHash image\n * @param {string} blurHash BlurHash image string\n * @returns {[number, number, number]}\n */\nexport function getBlurHashAverageColor(blurHash) {\n    const val = decode83(blurHash, 2, 6);\n    return [val >> 16, (val >> 8) & 255, val & 255];\n}\n\n/**\n * Decodes BlurHash image\n * @param {string} blurHash BlurHash image string\n * @param {number} width Output image width\n * @param {number} height Output image height\n * @param {?number} punch\n * @returns {Uint8ClampedArray}\n */\nexport function decodeBlurHash(blurHash, width, height, punch) {\n    const sizeFlag = decode83(blurHash, 0, 1);\n    const numX = (sizeFlag % 9) + 1;\n    const numY = ~~(sizeFlag / 9) + 1;\n    const size = numX * numY;\n\n    let i, j, x, y, r, g, b, basis, basisY, colorIndex, pixelIndex, value;\n\n    const maximumValue = ((decode83(blurHash, 1, 2) + 1) / 13446) * (punch | 1);\n\n    const colors = new Float64Array(size * 3);\n\n    const averageColor = getBlurHashAverageColor(blurHash);\n    for (i = 0; i < 3; i++) {\n        colors[i] = sRGBToLinear(averageColor[i]);\n    }\n\n    for (i = 1; i < size; i++) {\n        value = decode83(blurHash, 4 + i * 2, 6 + i * 2);\n        colors[i * 3] = signSqr(~~(value / 361) - 9) * maximumValue;\n        colors[i * 3 + 1] = signSqr((~~(value / 19) % 19) - 9) * maximumValue;\n        colors[i * 3 + 2] = signSqr((value % 19) - 9) * maximumValue;\n    }\n\n    const cosinesY = new Float64Array(numY * height);\n    const cosinesX = new Float64Array(numX * width);\n    for (j = 0; j < numY; j++) {\n        for (y = 0; y < height; y++) {\n            cosinesY[j * height + y] = fastCos((PI * y * j) / height);\n        }\n    }\n    for (i = 0; i < numX; i++) {\n        for (x = 0; x < width; x++) {\n            cosinesX[i * width + x] = fastCos((PI * x * i) / width);\n        }\n    }\n\n    const bytesPerRow = width * 4;\n    const pixels = new Uint8ClampedArray(bytesPerRow * height);\n\n    // The inverse transform is separable, so it is computed in two passes per\n    // row: first collapse the Y basis into per-X-basis color sums (`u`), then\n    // collapse the X basis for each pixel. This turns the inner work from\n    // O(numX * numY) per pixel into O(numX) per pixel.\n    const u = new Float64Array(numX * 3);\n    for (y = 0; y < height; y++) {\n        for (i = 0; i < numX; i++) {\n            r = g = b = 0;\n            for (j = 0; j < numY; j++) {\n                basisY = cosinesY[j * height + y];\n                colorIndex = (i + j * numX) * 3;\n                r += colors[colorIndex] * basisY;\n                g += colors[colorIndex + 1] * basisY;\n                b += colors[colorIndex + 2] * basisY;\n            }\n            u[i * 3] = r;\n            u[i * 3 + 1] = g;\n            u[i * 3 + 2] = b;\n        }\n        for (x = 0; x < width; x++) {\n            r = g = b = 0;\n            for (i = 0; i < numX; i++) {\n                basis = cosinesX[i * width + x];\n                colorIndex = i * 3;\n                r += u[colorIndex] * basis;\n                g += u[colorIndex + 1] * basis;\n                b += u[colorIndex + 2] * basis;\n            }\n\n            pixelIndex = 4 * x + y * bytesPerRow;\n            pixels[pixelIndex] = fastLinearTosRGB(r);\n            pixels[pixelIndex + 1] = fastLinearTosRGB(g);\n            pixels[pixelIndex + 2] = fastLinearTosRGB(b);\n            pixels[pixelIndex + 3] = 255; // alpha\n        }\n    }\n    return pixels;\n}\n", "import { Controller } from \"@hotwired/stimulus\"\nimport { decodeBlurHash } from \"fast-blurhash\";\n\nexport default class extends Controller {\n  static values = { blurhash: String };\n\n  connect() {\n    if (this.hasBlurhashValue) {\n      this.processBlurhash();\n    }\n  }\n\n  disconnect() {\n  }\n\n  processBlurhash() {\n    const pixels = decodeBlurHash(this.blurhashValue, 3, 3);\n    const bottom = pixels.slice(28, 31);\n\n    if (this.isTooLight(...bottom)) {\n      this.element.classList.add(\"is-light\");\n    }\n  }\n\n  isTooLight(r, g, b, a) {\n    const hsp = Math.sqrt(\n      0.299 * (r * r) +\n      0.587 * (g * g) +\n      0.114 * (b * b)\n    );\n\n    return hsp > 175;\n  }\n}\n", "// This file is auto-generated by ./bin/rails stimulus:manifest:update\n// Run that command whenever you add a new controller or create them with\n// ./bin/rails generate stimulus controllerName\n\nimport { application } from \"./application\"\n\nimport LightnessController from \"./lightness_controller\"\napplication.register(\"lightness\", LightnessController)\n", "import \"./filters_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./brand_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./button_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./button_group_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./section_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./tile_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./actions_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./content_editor_component.css\"\nimport { Editor } from '@tiptap/core';\nimport FloatingMenu from '@tiptap/extension-floating-menu';\nimport Link from '@tiptap/extension-link';\n// import Placeholder from '@tiptap/extension-placeholder';\nimport StarterKit from '@tiptap/starter-kit';\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\nimport { TableOfContents } from './extensions/table_of_contents.js'\nimport PromptsBlock from './extensions/prompts_block.js';\nimport ImageBlock from './extensions/image_block.js';\n\nexport class Controller extends BaseController {\n  static classes = [\"active\", \"empty\"];\n  static targets = [\"editorContent\", \"editorJson\", \"floatingMenu\", \"hiddenPromptsButton\", \"hiddenImageButton\", \"hiddenLinkButton\", \"contentInserter\", \"linkInserter\"];\n  static values = {\n    placeholder: String\n  };\n\n  connect() {\n    this.editor = new Editor({\n      element: this.editorContentTarget,\n      extensions: [\n        StarterKit.configure({\n          heading: {\n            levels: [2, 3, 4],\n          }\n        }),\n        // Placeholder.configure({\n        //   emptyEditorClass: this.emptyClass,\n        //   placeholder: this.placeholderValue,\n        // }),\n        Link.configure({\n          openOnClick: false,\n          HTMLAttributes: {\n            'data-action': 'admin--form--content-editor#selectLink',\n            target: null,\n          },\n        }),\n        TableOfContents,\n        this.hasFloatingMenuTarget ? FloatingMenu.configure({\n          element: this.floatingMenuTarget,\n        }) : null,\n        ImageBlock,\n        PromptsBlock,\n      ],\n      content: this.contentJson,\n    });\n\n    this.editor.on(\"update\", () => this.updateContent());\n    this.editor.on(\"selectionUpdate\", (e) => this.updateSelection(e));\n    this.updateContent();\n  }\n\n  disconnect() {\n    this.editor.off(\"update\", () => this.updateContent());\n    this.editor.off(\"selectionUpdate\", () => this.updateSelection());\n    this.editor.destroy();\n    this.editor = null;\n  }\n\n  focus() {\n    this.editor.chain().focus().run();\n  }\n\n  updateContent() {\n    this.editorJsonTarget.value = JSON.stringify(this.editor.getJSON());\n  }\n\n  updateSelection(e) {\n    const buttons = [\n      { key: 'bold' },\n      { key: 'italic' },\n      { key: 'strike' },\n      { key: 'code' },\n      { key: 'link' },\n      { key: 'paragraph' },\n      { key: 'h1', command: 'heading', params: { level: 1 } },\n      { key: 'h2', command: 'heading', params: { level: 2 } },\n      { key: 'h3', command: 'heading', params: { level: 3 } },\n      { key: 'h4', command: 'heading', params: { level: 4 } },\n      { key: 'h5', command: 'heading', params: { level: 5 } },\n      { key: 'h6', command: 'heading', params: { level: 6 } },\n      { key: 'bulletList' },\n      { key: 'orderedList' },\n      { key: 'codeBlock' },\n      { key: 'blockquote' },\n    ];\n\n    buttons.forEach(b => {\n      const button = this.element.querySelector('button.' + b.key);\n\n      if (!button) return;\n\n      const active = this.editor.isActive(b.command || b.key, b.params || {});\n\n      button.classList.toggle(this.activeClass, active);\n    });\n  }\n\n  toggleBold(e) {\n    this.editor.chain().focus().toggleBold().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('bold'))\n  }\n\n  toggleItalic(e) {\n    this.editor.chain().focus().toggleItalic().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('italic'))\n  }\n\n  toggleStrike(e) {\n    this.editor.chain().focus().toggleStrike().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('strike'))\n  }\n\n  toggleCode(e) {\n    this.editor.chain().focus().toggleCode().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('code'))\n  }\n\n  selectLink() {\n    this.editor.commands.extendMarkRange('link');\n  }\n\n  toggleLink(e) {\n    this.selectLink();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('link'))\n\n    const attributes = this.editor.getAttributes('link');\n    attributes.text = this.currentlySelectedText();\n\n    const url = this.hiddenLinkButtonTarget.dataset.basePath;\n    this.hiddenLinkButtonTarget.href = url + '&' + this.linkParams(attributes);\n    this.hiddenLinkButtonTarget.click();\n  }\n\n  linkParams(attributes) {\n    const linkAttributes = Object.fromEntries(\n      Object.entries(attributes).map(([k, v]) => [`link[${k}]`, v])\n    );\n    return new URLSearchParams(linkAttributes).toString();\n  }\n\n  currentlySelectedText() {\n    const state = this.editor.state;\n    const text = state.doc.textBetween(state.selection.from, state.selection.to);\n\n    return text;\n  }\n\n  linkInserterTargetConnected(t) {\n    const params = JSON.parse(t.dataset.params);\n\n    this.editor.chain().focus().setLink({\n      href: params.href,\n      target: params.target,\n      title: params.title,\n    }).run();\n\n    t.parentNode.removeChild(t);\n  }\n\n  unsetAllMarks() {\n    this.editor.chain().focus().unsetAllMarks().run();\n  }\n\n  clearNodes() {\n    this.editor.chain().focus().clearNodes().run();\n  }\n\n  setParagraph(e) {\n    this.editor.chain().focus().setParagraph().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('paragraph'))\n  }\n\n  toggleHeading(e) {\n    const level = parseInt(e.target.dataset.level, 10);\n    this.editor.chain().focus().toggleHeading({ level: level }).run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('heading', { level: level }))\n  }\n\n  toggleBulletList(e) {\n    this.editor.chain().focus().toggleBulletList().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('bulletList'))\n  }\n\n  toggleOrderedList(e) {\n    this.editor.chain().focus().toggleOrderedList().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('orderedList'))\n  }\n\n  toggleCodeBlock(e) {\n    this.editor.chain().focus().toggleCodeBlock().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('codeBlock'))\n  }\n\n  toggleBlockquote(e) {\n    this.editor.chain().focus().toggleBlockquote().run();\n    e.target.classList.toggle(this.activeClass, this.editor.isActive('blockquote'))\n  }\n\n  setHorizontalRule() {\n    this.editor.chain().focus().setHorizontalRule().run();\n  }\n\n  setHardBreak() {\n    this.editor.chain().focus().setHardBreak().run();\n  }\n\n  undo() {\n    this.editor.chain().focus().undo().run();\n  }\n\n  redo() {\n    this.editor.chain().focus().redo().run();\n  }\n\n  togglePrompts(e) {\n    const params = e.target.closest(\"button\").dataset.params;\n    const url = this.hiddenPromptsButtonTarget.dataset.basePath;\n    this.hiddenPromptsButtonTarget.href = url + (params ? '&' + params : '');\n    this.hiddenPromptsButtonTarget.click();\n  }\n\n  contentInserterTargetConnected(t) {\n    const content = t.innerHTML;\n    this.editor.commands.insertContent(content);\n    t.parentNode.removeChild(t);\n  }\n\n  toggleImage(e) {\n    const params = e.target.closest(\"button\").dataset.params;\n    const url = this.hiddenImageButtonTarget.dataset.basePath;\n    this.hiddenImageButtonTarget.href = url + (params ? '&' + params : '');\n    this.hiddenImageButtonTarget.click();\n  }\n\n  get contentJson() {\n    const { value } = this.editorJsonTarget;\n\n    if (value == \"\") {\n      return \"\";\n    } else {\n      return JSON.parse(value);\n    }\n  }\n}\n", "// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n  this.content = content;\n}\n\nOrderedMap.prototype = {\n  constructor: OrderedMap,\n\n  find: function(key) {\n    for (var i = 0; i < this.content.length; i += 2)\n      if (this.content[i] === key) return i\n    return -1\n  },\n\n  // :: (string) \u2192 ?any\n  // Retrieve the value stored under `key`, or return undefined when\n  // no such key exists.\n  get: function(key) {\n    var found = this.find(key);\n    return found == -1 ? undefined : this.content[found + 1]\n  },\n\n  // :: (string, any, ?string) \u2192 OrderedMap\n  // Create a new map by replacing the value of `key` with a new\n  // value, or adding a binding to the end of the map. If `newKey` is\n  // given, the key of the binding will be replaced with that key.\n  update: function(key, value, newKey) {\n    var self = newKey && newKey != key ? this.remove(newKey) : this;\n    var found = self.find(key), content = self.content.slice();\n    if (found == -1) {\n      content.push(newKey || key, value);\n    } else {\n      content[found + 1] = value;\n      if (newKey) content[found] = newKey;\n    }\n    return new OrderedMap(content)\n  },\n\n  // :: (string) \u2192 OrderedMap\n  // Return a map with the given key removed, if it existed.\n  remove: function(key) {\n    var found = this.find(key);\n    if (found == -1) return this\n    var content = this.content.slice();\n    content.splice(found, 2);\n    return new OrderedMap(content)\n  },\n\n  // :: (string, any) \u2192 OrderedMap\n  // Add a new key to the start of the map.\n  addToStart: function(key, value) {\n    return new OrderedMap([key, value].concat(this.remove(key).content))\n  },\n\n  // :: (string, any) \u2192 OrderedMap\n  // Add a new key to the end of the map.\n  addToEnd: function(key, value) {\n    var content = this.remove(key).content.slice();\n    content.push(key, value);\n    return new OrderedMap(content)\n  },\n\n  // :: (string, string, any) \u2192 OrderedMap\n  // Add a key after the given key. If `place` is not found, the new\n  // key is added to the end.\n  addBefore: function(place, key, value) {\n    var without = this.remove(key), content = without.content.slice();\n    var found = without.find(place);\n    content.splice(found == -1 ? content.length : found, 0, key, value);\n    return new OrderedMap(content)\n  },\n\n  // :: ((key: string, value: any))\n  // Call the given function for each key/value pair in the map, in\n  // order.\n  forEach: function(f) {\n    for (var i = 0; i < this.content.length; i += 2)\n      f(this.content[i], this.content[i + 1]);\n  },\n\n  // :: (union<Object, OrderedMap>) \u2192 OrderedMap\n  // Create a new map by prepending the keys in this map that don't\n  // appear in `map` before the keys in `map`.\n  prepend: function(map) {\n    map = OrderedMap.from(map);\n    if (!map.size) return this\n    return new OrderedMap(map.content.concat(this.subtract(map).content))\n  },\n\n  // :: (union<Object, OrderedMap>) \u2192 OrderedMap\n  // Create a new map by appending the keys in this map that don't\n  // appear in `map` after the keys in `map`.\n  append: function(map) {\n    map = OrderedMap.from(map);\n    if (!map.size) return this\n    return new OrderedMap(this.subtract(map).content.concat(map.content))\n  },\n\n  // :: (union<Object, OrderedMap>) \u2192 OrderedMap\n  // Create a map containing all the keys in this map that don't\n  // appear in `map`.\n  subtract: function(map) {\n    var result = this;\n    map = OrderedMap.from(map);\n    for (var i = 0; i < map.content.length; i += 2)\n      result = result.remove(map.content[i]);\n    return result\n  },\n\n  // :: () \u2192 Object\n  // Turn ordered map into a plain object.\n  toObject: function() {\n    var result = {};\n    this.forEach(function(key, value) { result[key] = value; });\n    return result\n  },\n\n  // :: number\n  // The amount of keys in this map.\n  get size() {\n    return this.content.length >> 1\n  }\n};\n\n// :: (?union<Object, OrderedMap>) \u2192 OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n  if (value instanceof OrderedMap) return value\n  var content = [];\n  if (value) for (var prop in value) content.push(prop, value[prop]);\n  return new OrderedMap(content)\n};\n\nexport default OrderedMap;\n", "import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n    for (let i = 0;; i++) {\n        if (i == a.childCount || i == b.childCount)\n            return a.childCount == b.childCount ? null : pos;\n        let childA = a.child(i), childB = b.child(i);\n        if (childA == childB) {\n            pos += childA.nodeSize;\n            continue;\n        }\n        if (!childA.sameMarkup(childB))\n            return pos;\n        if (childA.isText && childA.text != childB.text) {\n            let tA = childA.text, tB = childB.text, j = 0;\n            for (; tA[j] == tB[j]; j++)\n                pos++;\n            if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j)))\n                pos--;\n            return pos;\n        }\n        if (childA.content.size || childB.content.size) {\n            let inner = findDiffStart(childA.content, childB.content, pos + 1);\n            if (inner != null)\n                return inner;\n        }\n        pos += childA.nodeSize;\n    }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n    for (let iA = a.childCount, iB = b.childCount;;) {\n        if (iA == 0 || iB == 0)\n            return iA == iB ? null : { a: posA, b: posB };\n        let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n        if (childA == childB) {\n            posA -= size;\n            posB -= size;\n            continue;\n        }\n        if (!childA.sameMarkup(childB))\n            return { a: posA, b: posB };\n        if (childA.isText && childA.text != childB.text) {\n            let tA = childA.text, tB = childB.text, iA = tA.length, iB = tB.length;\n            while (iA > 0 && iB > 0 && tA[iA - 1] == tB[iB - 1]) {\n                iA--;\n                iB--;\n                posA--;\n                posB--;\n            }\n            if (iA && iB && iA < tA.length && surrogateHigh(tA.charCodeAt(iA - 1)) && surrogateLow(tA.charCodeAt(iA))) {\n                posA++;\n                posB++;\n            }\n            return { a: posA, b: posB };\n        }\n        if (childA.content.size || childB.content.size) {\n            let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n            if (inner)\n                return inner;\n        }\n        posA -= size;\n        posB -= size;\n    }\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The child nodes in this fragment.\n    */\n    content, size) {\n        this.content = content;\n        this.size = size || 0;\n        if (size == null)\n            for (let i = 0; i < content.length; i++)\n                this.size += content[i].nodeSize;\n    }\n    /**\n    Invoke a callback for all descendant nodes between the given two\n    positions (relative to start of this fragment). Doesn't descend\n    into a node when the callback returns `false`.\n    */\n    nodesBetween(from, to, f, nodeStart = 0, parent) {\n        for (let i = 0, pos = 0; pos < to; i++) {\n            let child = this.content[i], end = pos + child.nodeSize;\n            if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n                let start = pos + 1;\n                child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n            }\n            pos = end;\n        }\n    }\n    /**\n    Call the given callback for every descendant node. `pos` will be\n    relative to the start of the fragment. The callback may return\n    `false` to prevent traversal of a given node's children.\n    */\n    descendants(f) {\n        this.nodesBetween(0, this.size, f);\n    }\n    /**\n    Extract the text between `from` and `to`. See the same method on\n    [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n    */\n    textBetween(from, to, blockSeparator, leafText) {\n        let text = \"\", first = true;\n        this.nodesBetween(from, to, (node, pos) => {\n            let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n                : !node.isLeaf ? \"\"\n                    : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n                        : node.type.spec.leafText ? node.type.spec.leafText(node)\n                            : \"\";\n            if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n                if (first)\n                    first = false;\n                else\n                    text += blockSeparator;\n            }\n            text += nodeText;\n        }, 0);\n        return text;\n    }\n    /**\n    Create a new fragment containing the combined content of this\n    fragment and the other.\n    */\n    append(other) {\n        if (!other.size)\n            return this;\n        if (!this.size)\n            return other;\n        let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n        if (last.isText && last.sameMarkup(first)) {\n            content[content.length - 1] = last.withText(last.text + first.text);\n            i = 1;\n        }\n        for (; i < other.content.length; i++)\n            content.push(other.content[i]);\n        return new Fragment(content, this.size + other.size);\n    }\n    /**\n    Cut out the sub-fragment between the two given positions.\n    */\n    cut(from, to = this.size) {\n        if (from == 0 && to == this.size)\n            return this;\n        let result = [], size = 0;\n        if (to > from)\n            for (let i = 0, pos = 0; pos < to; i++) {\n                let child = this.content[i], end = pos + child.nodeSize;\n                if (end > from) {\n                    if (pos < from || end > to) {\n                        if (child.isText)\n                            child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n                        else\n                            child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n                    }\n                    result.push(child);\n                    size += child.nodeSize;\n                }\n                pos = end;\n            }\n        return new Fragment(result, size);\n    }\n    /**\n    @internal\n    */\n    cutByIndex(from, to) {\n        if (from == to)\n            return Fragment.empty;\n        if (from == 0 && to == this.content.length)\n            return this;\n        return new Fragment(this.content.slice(from, to));\n    }\n    /**\n    Create a new fragment in which the node at the given index is\n    replaced by the given node.\n    */\n    replaceChild(index, node) {\n        let current = this.content[index];\n        if (current == node)\n            return this;\n        let copy = this.content.slice();\n        let size = this.size + node.nodeSize - current.nodeSize;\n        copy[index] = node;\n        return new Fragment(copy, size);\n    }\n    /**\n    Create a new fragment by prepending the given node to this\n    fragment.\n    */\n    addToStart(node) {\n        return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n    }\n    /**\n    Create a new fragment by appending the given node to this\n    fragment.\n    */\n    addToEnd(node) {\n        return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n    }\n    /**\n    Compare this fragment to another one.\n    */\n    eq(other) {\n        if (this.content.length != other.content.length)\n            return false;\n        for (let i = 0; i < this.content.length; i++)\n            if (!this.content[i].eq(other.content[i]))\n                return false;\n        return true;\n    }\n    /**\n    The first child of the fragment, or `null` if it is empty.\n    */\n    get firstChild() { return this.content.length ? this.content[0] : null; }\n    /**\n    The last child of the fragment, or `null` if it is empty.\n    */\n    get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n    /**\n    The number of child nodes in this fragment.\n    */\n    get childCount() { return this.content.length; }\n    /**\n    Get the child node at the given index. Raise an error when the\n    index is out of range.\n    */\n    child(index) {\n        let found = this.content[index];\n        if (!found)\n            throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n        return found;\n    }\n    /**\n    Get the child node at the given index, if it exists.\n    */\n    maybeChild(index) {\n        return this.content[index] || null;\n    }\n    /**\n    Call `f` for every child node, passing the node, its offset\n    into this parent node, and its index.\n    */\n    forEach(f) {\n        for (let i = 0, p = 0; i < this.content.length; i++) {\n            let child = this.content[i];\n            f(child, p, i);\n            p += child.nodeSize;\n        }\n    }\n    /**\n    Find the first position at which this fragment and another\n    fragment differ, or `null` if they are the same.\n    */\n    findDiffStart(other, pos = 0) {\n        return findDiffStart(this, other, pos);\n    }\n    /**\n    Find the first position, searching from the end, at which this\n    fragment and the given fragment differ, or `null` if they are\n    the same. Since this position will not be the same in both\n    nodes, an object with two separate positions is returned.\n    */\n    findDiffEnd(other, pos = this.size, otherPos = other.size) {\n        return findDiffEnd(this, other, pos, otherPos);\n    }\n    /**\n    Find the index and inner offset corresponding to a given relative\n    position in this fragment. The result object will be reused\n    (overwritten) the next time the function is called. @internal\n    */\n    findIndex(pos) {\n        if (pos == 0)\n            return retIndex(0, pos);\n        if (pos == this.size)\n            return retIndex(this.content.length, pos);\n        if (pos > this.size || pos < 0)\n            throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n        for (let i = 0, curPos = 0;; i++) {\n            let cur = this.child(i), end = curPos + cur.nodeSize;\n            if (end >= pos) {\n                if (end == pos)\n                    return retIndex(i + 1, end);\n                return retIndex(i, curPos);\n            }\n            curPos = end;\n        }\n    }\n    /**\n    Return a debugging string that describes this fragment.\n    */\n    toString() { return \"<\" + this.toStringInner() + \">\"; }\n    /**\n    @internal\n    */\n    toStringInner() { return this.content.join(\", \"); }\n    /**\n    Create a JSON-serializeable representation of this fragment.\n    */\n    toJSON() {\n        return this.content.length ? this.content.map(n => n.toJSON()) : null;\n    }\n    /**\n    Deserialize a fragment from its JSON representation.\n    */\n    static fromJSON(schema, value) {\n        if (!value)\n            return Fragment.empty;\n        if (!Array.isArray(value))\n            throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n        return Fragment.fromArray(value.map(schema.nodeFromJSON));\n    }\n    /**\n    Build a fragment from an array of nodes. Ensures that adjacent\n    text nodes with the same marks are joined together.\n    */\n    static fromArray(array) {\n        if (!array.length)\n            return Fragment.empty;\n        let joined, size = 0;\n        for (let i = 0; i < array.length; i++) {\n            let node = array[i];\n            size += node.nodeSize;\n            if (i && node.isText && array[i - 1].sameMarkup(node)) {\n                if (!joined)\n                    joined = array.slice(0, i);\n                joined[joined.length - 1] = node\n                    .withText(joined[joined.length - 1].text + node.text);\n            }\n            else if (joined) {\n                joined.push(node);\n            }\n        }\n        return new Fragment(joined || array, size);\n    }\n    /**\n    Create a fragment from something that can be interpreted as a\n    set of nodes. For `null`, it returns the empty fragment. For a\n    fragment, the fragment itself. For a node or array of nodes, a\n    fragment containing those nodes.\n    */\n    static from(nodes) {\n        if (!nodes)\n            return Fragment.empty;\n        if (nodes instanceof Fragment)\n            return nodes;\n        if (Array.isArray(nodes))\n            return this.fromArray(nodes);\n        if (nodes.attrs)\n            return new Fragment([nodes], nodes.nodeSize);\n        throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n            (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n    }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n    found.index = index;\n    found.offset = offset;\n    return found;\n}\n\nfunction compareDeep(a, b) {\n    if (a === b)\n        return true;\n    if (!(a && typeof a == \"object\") ||\n        !(b && typeof b == \"object\"))\n        return false;\n    let array = Array.isArray(a);\n    if (Array.isArray(b) != array)\n        return false;\n    if (array) {\n        if (a.length != b.length)\n            return false;\n        for (let i = 0; i < a.length; i++)\n            if (!compareDeep(a[i], b[i]))\n                return false;\n    }\n    else {\n        for (let p in a)\n            if (!(p in b) || !compareDeep(a[p], b[p]))\n                return false;\n        for (let p in b)\n            if (!(p in a))\n                return false;\n    }\n    return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The type of this mark.\n    */\n    type, \n    /**\n    The attributes associated with this mark.\n    */\n    attrs) {\n        this.type = type;\n        this.attrs = attrs;\n    }\n    /**\n    Given a set of marks, create a new set which contains this one as\n    well, in the right position. If this mark is already in the set,\n    the set itself is returned. If any marks that are set to be\n    [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n    those are replaced by this one.\n    */\n    addToSet(set) {\n        let copy, placed = false;\n        for (let i = 0; i < set.length; i++) {\n            let other = set[i];\n            if (this.eq(other))\n                return set;\n            if (this.type.excludes(other.type)) {\n                if (!copy)\n                    copy = set.slice(0, i);\n            }\n            else if (other.type.excludes(this.type)) {\n                return set;\n            }\n            else {\n                if (!placed && other.type.rank > this.type.rank) {\n                    if (!copy)\n                        copy = set.slice(0, i);\n                    copy.push(this);\n                    placed = true;\n                }\n                if (copy)\n                    copy.push(other);\n            }\n        }\n        if (!copy)\n            copy = set.slice();\n        if (!placed)\n            copy.push(this);\n        return copy;\n    }\n    /**\n    Remove this mark from the given set, returning a new set. If this\n    mark is not in the set, the set itself is returned.\n    */\n    removeFromSet(set) {\n        for (let i = 0; i < set.length; i++)\n            if (this.eq(set[i]))\n                return set.slice(0, i).concat(set.slice(i + 1));\n        return set;\n    }\n    /**\n    Test whether this mark is in the given set of marks.\n    */\n    isInSet(set) {\n        for (let i = 0; i < set.length; i++)\n            if (this.eq(set[i]))\n                return true;\n        return false;\n    }\n    /**\n    Test whether this mark has the same type and attributes as\n    another mark.\n    */\n    eq(other) {\n        return this == other ||\n            (this.type == other.type && compareDeep(this.attrs, other.attrs));\n    }\n    /**\n    Convert this mark to a JSON-serializeable representation.\n    */\n    toJSON() {\n        let obj = { type: this.type.name };\n        for (let _ in this.attrs) {\n            obj.attrs = this.attrs;\n            break;\n        }\n        return obj;\n    }\n    /**\n    Deserialize a mark from JSON.\n    */\n    static fromJSON(schema, json) {\n        if (!json)\n            throw new RangeError(\"Invalid input for Mark.fromJSON\");\n        let type = schema.marks[json.type];\n        if (!type)\n            throw new RangeError(`There is no mark type ${json.type} in this schema`);\n        let mark = type.create(json.attrs);\n        return mark;\n    }\n    /**\n    Test whether two sets of marks are identical.\n    */\n    static sameSet(a, b) {\n        if (a == b)\n            return true;\n        if (a.length != b.length)\n            return false;\n        for (let i = 0; i < a.length; i++)\n            if (!a[i].eq(b[i]))\n                return false;\n        return true;\n    }\n    /**\n    Create a properly sorted mark set from null, a single mark, or an\n    unsorted array of marks.\n    */\n    static setFrom(marks) {\n        if (!marks || Array.isArray(marks) && marks.length == 0)\n            return Mark.none;\n        if (marks instanceof Mark)\n            return [marks];\n        let copy = marks.slice();\n        copy.sort((a, b) => a.type.rank - b.type.rank);\n        return copy;\n    }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are \u2018open\u2019 (cut through).\n*/\nclass Slice {\n    /**\n    Create a slice. When specifying a non-zero open depth, you must\n    make sure that there are nodes of at least that depth at the\n    appropriate side of the fragment\u2014i.e. if the fragment is an\n    empty paragraph node, `openStart` and `openEnd` can't be greater\n    than 1.\n    \n    It is not necessary for the content of open nodes to conform to\n    the schema's content constraints, though it should be a valid\n    start/end/middle for such a node, depending on which sides are\n    open.\n    */\n    constructor(\n    /**\n    The slice's content.\n    */\n    content, \n    /**\n    The open depth at the start of the fragment.\n    */\n    openStart, \n    /**\n    The open depth at the end.\n    */\n    openEnd) {\n        this.content = content;\n        this.openStart = openStart;\n        this.openEnd = openEnd;\n    }\n    /**\n    The size this slice would add when inserted into a document.\n    */\n    get size() {\n        return this.content.size - this.openStart - this.openEnd;\n    }\n    /**\n    @internal\n    */\n    insertAt(pos, fragment) {\n        let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1);\n        return content && new Slice(content, this.openStart, this.openEnd);\n    }\n    /**\n    @internal\n    */\n    removeBetween(from, to) {\n        return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n    }\n    /**\n    Tests whether this slice is equal to another slice.\n    */\n    eq(other) {\n        return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n    }\n    /**\n    @internal\n    */\n    toString() {\n        return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n    }\n    /**\n    Convert a slice to a JSON-serializable representation.\n    */\n    toJSON() {\n        if (!this.content.size)\n            return null;\n        let json = { content: this.content.toJSON() };\n        if (this.openStart > 0)\n            json.openStart = this.openStart;\n        if (this.openEnd > 0)\n            json.openEnd = this.openEnd;\n        return json;\n    }\n    /**\n    Deserialize a slice from its JSON representation.\n    */\n    static fromJSON(schema, json) {\n        if (!json)\n            return Slice.empty;\n        let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n        if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n            throw new RangeError(\"Invalid input for Slice.fromJSON\");\n        return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n    }\n    /**\n    Create a slice from a fragment by taking the maximum possible\n    open value on both side of the fragment.\n    */\n    static maxOpen(fragment, openIsolating = true) {\n        let openStart = 0, openEnd = 0;\n        for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n            openStart++;\n        for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n            openEnd++;\n        return new Slice(fragment, openStart, openEnd);\n    }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n    let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n    let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n    if (offset == from || child.isText) {\n        if (offsetTo != to && !content.child(indexTo).isText)\n            throw new RangeError(\"Removing non-flat range\");\n        return content.cut(0, from).append(content.cut(to));\n    }\n    if (index != indexTo)\n        throw new RangeError(\"Removing non-flat range\");\n    return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, openStart, openEnd, parent) {\n    let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n    if (offset == dist || child.isText) {\n        if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert))\n            return null;\n        return content.cut(0, dist).append(insert).append(content.cut(dist));\n    }\n    let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child);\n    return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n    if (slice.openStart > $from.depth)\n        throw new ReplaceError(\"Inserted content deeper than insertion position\");\n    if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n        throw new ReplaceError(\"Inconsistent open depths\");\n    return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n    let index = $from.index(depth), node = $from.node(depth);\n    if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n        let inner = replaceOuter($from, $to, slice, depth + 1);\n        return node.copy(node.content.replaceChild(index, inner));\n    }\n    else if (!slice.content.size) {\n        return close(node, replaceTwoWay($from, $to, depth));\n    }\n    else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n        let parent = $from.parent, content = parent.content;\n        return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n    }\n    else {\n        let { start, end } = prepareSliceForReplace(slice, $from);\n        return close(node, replaceThreeWay($from, start, end, $to, depth));\n    }\n}\nfunction checkJoin(main, sub) {\n    if (!sub.type.compatibleContent(main.type))\n        throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n    let node = $before.node(depth);\n    checkJoin(node, $after.node(depth));\n    return node;\n}\nfunction addNode(child, target) {\n    let last = target.length - 1;\n    if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n        target[last] = child.withText(target[last].text + child.text);\n    else\n        target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n    let node = ($end || $start).node(depth);\n    let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n    if ($start) {\n        startIndex = $start.index(depth);\n        if ($start.depth > depth) {\n            startIndex++;\n        }\n        else if ($start.textOffset) {\n            addNode($start.nodeAfter, target);\n            startIndex++;\n        }\n    }\n    for (let i = startIndex; i < endIndex; i++)\n        addNode(node.child(i), target);\n    if ($end && $end.depth == depth && $end.textOffset)\n        addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n    if (!node.type.validContent(content))\n        throw new ReplaceError(\"Invalid content for node \" + node.type.name);\n    return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n    let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n    let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n    let content = [];\n    addRange(null, $from, depth, content);\n    if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n        checkJoin(openStart, openEnd);\n        addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n    }\n    else {\n        if (openStart)\n            addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n        addRange($start, $end, depth, content);\n        if (openEnd)\n            addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n    }\n    addRange($to, null, depth, content);\n    return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n    let content = [];\n    addRange(null, $from, depth, content);\n    if ($from.depth > depth) {\n        let type = joinable($from, $to, depth + 1);\n        addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n    }\n    addRange($to, null, depth, content);\n    return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n    let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n    let node = parent.copy(slice.content);\n    for (let i = extra - 1; i >= 0; i--)\n        node = $along.node(i).copy(Fragment.from(node));\n    return { start: node.resolveNoCache(slice.openStart + extra),\n        end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The position that was resolved.\n    */\n    pos, \n    /**\n    @internal\n    */\n    path, \n    /**\n    The offset this position has into its parent node.\n    */\n    parentOffset) {\n        this.pos = pos;\n        this.path = path;\n        this.parentOffset = parentOffset;\n        this.depth = path.length / 3 - 1;\n    }\n    /**\n    @internal\n    */\n    resolveDepth(val) {\n        if (val == null)\n            return this.depth;\n        if (val < 0)\n            return this.depth + val;\n        return val;\n    }\n    /**\n    The parent node that the position points into. Note that even if\n    a position points into a text node, that node is not considered\n    the parent\u2014text nodes are \u2018flat\u2019 in this model, and have no content.\n    */\n    get parent() { return this.node(this.depth); }\n    /**\n    The root node in which the position was resolved.\n    */\n    get doc() { return this.node(0); }\n    /**\n    The ancestor node at the given level. `p.node(p.depth)` is the\n    same as `p.parent`.\n    */\n    node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n    /**\n    The index into the ancestor at the given level. If this points\n    at the 3rd node in the 2nd paragraph on the top level, for\n    example, `p.index(0)` is 1 and `p.index(1)` is 2.\n    */\n    index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n    /**\n    The index pointing after this position into the ancestor at the\n    given level.\n    */\n    indexAfter(depth) {\n        depth = this.resolveDepth(depth);\n        return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n    }\n    /**\n    The (absolute) position at the start of the node at the given\n    level.\n    */\n    start(depth) {\n        depth = this.resolveDepth(depth);\n        return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n    }\n    /**\n    The (absolute) position at the end of the node at the given\n    level.\n    */\n    end(depth) {\n        depth = this.resolveDepth(depth);\n        return this.start(depth) + this.node(depth).content.size;\n    }\n    /**\n    The (absolute) position directly before the wrapping node at the\n    given level, or, when `depth` is `this.depth + 1`, the original\n    position.\n    */\n    before(depth) {\n        depth = this.resolveDepth(depth);\n        if (!depth)\n            throw new RangeError(\"There is no position before the top-level node\");\n        return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n    }\n    /**\n    The (absolute) position directly after the wrapping node at the\n    given level, or the original position when `depth` is `this.depth + 1`.\n    */\n    after(depth) {\n        depth = this.resolveDepth(depth);\n        if (!depth)\n            throw new RangeError(\"There is no position after the top-level node\");\n        return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n    }\n    /**\n    When this position points into a text node, this returns the\n    distance between the position and the start of the text node.\n    Will be zero for positions that point between nodes.\n    */\n    get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n    /**\n    Get the node directly after the position, if any. If the position\n    points into a text node, only the part of that node after the\n    position is returned.\n    */\n    get nodeAfter() {\n        let parent = this.parent, index = this.index(this.depth);\n        if (index == parent.childCount)\n            return null;\n        let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n        return dOff ? parent.child(index).cut(dOff) : child;\n    }\n    /**\n    Get the node directly before the position, if any. If the\n    position points into a text node, only the part of that node\n    before the position is returned.\n    */\n    get nodeBefore() {\n        let index = this.index(this.depth);\n        let dOff = this.pos - this.path[this.path.length - 1];\n        if (dOff)\n            return this.parent.child(index).cut(0, dOff);\n        return index == 0 ? null : this.parent.child(index - 1);\n    }\n    /**\n    Get the position at the given index in the parent node at the\n    given depth (which defaults to `this.depth`).\n    */\n    posAtIndex(index, depth) {\n        depth = this.resolveDepth(depth);\n        let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n        for (let i = 0; i < index; i++)\n            pos += node.child(i).nodeSize;\n        return pos;\n    }\n    /**\n    Get the marks at this position, factoring in the surrounding\n    marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n    position is at the start of a non-empty node, the marks of the\n    node after it (if any) are returned.\n    */\n    marks() {\n        let parent = this.parent, index = this.index();\n        // In an empty parent, return the empty array\n        if (parent.content.size == 0)\n            return Mark.none;\n        // When inside a text node, just return the text node's marks\n        if (this.textOffset)\n            return parent.child(index).marks;\n        let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n        // If the `after` flag is true of there is no node before, make\n        // the node after this position the main reference.\n        if (!main) {\n            let tmp = main;\n            main = other;\n            other = tmp;\n        }\n        // Use all marks in the main node, except those that have\n        // `inclusive` set to false and are not present in the other node.\n        let marks = main.marks;\n        for (var i = 0; i < marks.length; i++)\n            if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n                marks = marks[i--].removeFromSet(marks);\n        return marks;\n    }\n    /**\n    Get the marks after the current position, if any, except those\n    that are non-inclusive and not present at position `$end`. This\n    is mostly useful for getting the set of marks to preserve after a\n    deletion. Will return `null` if this position is at the end of\n    its parent node or its parent node isn't a textblock (in which\n    case no marks should be preserved).\n    */\n    marksAcross($end) {\n        let after = this.parent.maybeChild(this.index());\n        if (!after || !after.isInline)\n            return null;\n        let marks = after.marks, next = $end.parent.maybeChild($end.index());\n        for (var i = 0; i < marks.length; i++)\n            if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n                marks = marks[i--].removeFromSet(marks);\n        return marks;\n    }\n    /**\n    The depth up to which this position and the given (non-resolved)\n    position share the same parent nodes.\n    */\n    sharedDepth(pos) {\n        for (let depth = this.depth; depth > 0; depth--)\n            if (this.start(depth) <= pos && this.end(depth) >= pos)\n                return depth;\n        return 0;\n    }\n    /**\n    Returns a range based on the place where this position and the\n    given position diverge around block content. If both point into\n    the same textblock, for example, a range around that textblock\n    will be returned. If they point into different blocks, the range\n    around those blocks in their shared ancestor is returned. You can\n    pass in an optional predicate that will be called with a parent\n    node to see if a range into that parent is acceptable.\n    */\n    blockRange(other = this, pred) {\n        if (other.pos < this.pos)\n            return other.blockRange(this);\n        for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n            if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n                return new NodeRange(this, other, d);\n        return null;\n    }\n    /**\n    Query whether the given position shares the same parent node.\n    */\n    sameParent(other) {\n        return this.pos - this.parentOffset == other.pos - other.parentOffset;\n    }\n    /**\n    Return the greater of this and the given position.\n    */\n    max(other) {\n        return other.pos > this.pos ? other : this;\n    }\n    /**\n    Return the smaller of this and the given position.\n    */\n    min(other) {\n        return other.pos < this.pos ? other : this;\n    }\n    /**\n    @internal\n    */\n    toString() {\n        let str = \"\";\n        for (let i = 1; i <= this.depth; i++)\n            str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n        return str + \":\" + this.parentOffset;\n    }\n    /**\n    @internal\n    */\n    static resolve(doc, pos) {\n        if (!(pos >= 0 && pos <= doc.content.size))\n            throw new RangeError(\"Position \" + pos + \" out of range\");\n        let path = [];\n        let start = 0, parentOffset = pos;\n        for (let node = doc;;) {\n            let { index, offset } = node.content.findIndex(parentOffset);\n            let rem = parentOffset - offset;\n            path.push(node, index, start + offset);\n            if (!rem)\n                break;\n            node = node.child(index);\n            if (node.isText)\n                break;\n            parentOffset = rem - 1;\n            start += offset + 1;\n        }\n        return new ResolvedPos(pos, path, parentOffset);\n    }\n    /**\n    @internal\n    */\n    static resolveCached(doc, pos) {\n        let cache = resolveCache.get(doc);\n        if (cache) {\n            for (let i = 0; i < cache.elts.length; i++) {\n                let elt = cache.elts[i];\n                if (elt.pos == pos)\n                    return elt;\n            }\n        }\n        else {\n            resolveCache.set(doc, cache = new ResolveCache);\n        }\n        let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n        cache.i = (cache.i + 1) % resolveCacheSize;\n        return result;\n    }\n}\nclass ResolveCache {\n    constructor() {\n        this.elts = [];\n        this.i = 0;\n    }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n    /**\n    Construct a node range. `$from` and `$to` should point into the\n    same node until at least the given `depth`, since a node range\n    denotes an adjacent set of nodes in a single parent node.\n    */\n    constructor(\n    /**\n    A resolved position along the start of the content. May have a\n    `depth` greater than this object's `depth` property, since\n    these are the positions that were used to compute the range,\n    not re-resolved positions directly at its boundaries.\n    */\n    $from, \n    /**\n    A position along the end of the content. See\n    caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n    */\n    $to, \n    /**\n    The depth of the node that this range points into.\n    */\n    depth) {\n        this.$from = $from;\n        this.$to = $to;\n        this.depth = depth;\n    }\n    /**\n    The position at the start of the range.\n    */\n    get start() { return this.$from.before(this.depth + 1); }\n    /**\n    The position at the end of the range.\n    */\n    get end() { return this.$to.after(this.depth + 1); }\n    /**\n    The parent node that the range points into.\n    */\n    get parent() { return this.$from.node(this.depth); }\n    /**\n    The start index of the range in the parent node.\n    */\n    get startIndex() { return this.$from.index(this.depth); }\n    /**\n    The end index of the range in the parent node.\n    */\n    get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](https://prosemirror.net/docs/guide/#doc) for more information.\n*/\nclass Node {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The type of node that this is.\n    */\n    type, \n    /**\n    An object mapping attribute names to values. The kind of\n    attributes allowed and required are\n    [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n    */\n    attrs, \n    // A fragment holding the node's children.\n    content, \n    /**\n    The marks (things like whether it is emphasized or part of a\n    link) applied to this node.\n    */\n    marks = Mark.none) {\n        this.type = type;\n        this.attrs = attrs;\n        this.marks = marks;\n        this.content = content || Fragment.empty;\n    }\n    /**\n    The array of this node's child nodes.\n    */\n    get children() { return this.content.content; }\n    /**\n    The size of this node, as defined by the integer-based [indexing\n    scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the\n    amount of characters. For other leaf nodes, it is one. For\n    non-leaf nodes, it is the size of the content plus two (the\n    start and end token).\n    */\n    get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n    /**\n    The number of children that the node has.\n    */\n    get childCount() { return this.content.childCount; }\n    /**\n    Get the child node at the given index. Raises an error when the\n    index is out of range.\n    */\n    child(index) { return this.content.child(index); }\n    /**\n    Get the child node at the given index, if it exists.\n    */\n    maybeChild(index) { return this.content.maybeChild(index); }\n    /**\n    Call `f` for every child node, passing the node, its offset\n    into this parent node, and its index.\n    */\n    forEach(f) { this.content.forEach(f); }\n    /**\n    Invoke a callback for all descendant nodes recursively overlapping\n    the given two positions that are relative to start of this\n    node's content. This includes all ancestors of the nodes\n    containing the two positions. The callback is invoked with the\n    node, its position relative to the original node (method receiver),\n    its parent node, and its child index. When the callback returns\n    false for a given node, that node's children will not be\n    recursed over. The last parameter can be used to specify a\n    starting position to count from.\n    */\n    nodesBetween(from, to, f, startPos = 0) {\n        this.content.nodesBetween(from, to, f, startPos, this);\n    }\n    /**\n    Call the given callback for every descendant node. Doesn't\n    descend into a node when the callback returns `false`.\n    */\n    descendants(f) {\n        this.nodesBetween(0, this.content.size, f);\n    }\n    /**\n    Concatenates all the text nodes found in this fragment and its\n    children.\n    */\n    get textContent() {\n        return (this.isLeaf && this.type.spec.leafText)\n            ? this.type.spec.leafText(this)\n            : this.textBetween(0, this.content.size, \"\");\n    }\n    /**\n    Get all text between positions `from` and `to`. When\n    `blockSeparator` is given, it will be inserted to separate text\n    from different block nodes. If `leafText` is given, it'll be\n    inserted for every non-text leaf node encountered, otherwise\n    [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.\n    */\n    textBetween(from, to, blockSeparator, leafText) {\n        return this.content.textBetween(from, to, blockSeparator, leafText);\n    }\n    /**\n    Returns this node's first child, or `null` if there are no\n    children.\n    */\n    get firstChild() { return this.content.firstChild; }\n    /**\n    Returns this node's last child, or `null` if there are no\n    children.\n    */\n    get lastChild() { return this.content.lastChild; }\n    /**\n    Test whether two nodes represent the same piece of document.\n    */\n    eq(other) {\n        return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n    }\n    /**\n    Compare the markup (type, attributes, and marks) of this node to\n    those of another. Returns `true` if both have the same markup.\n    */\n    sameMarkup(other) {\n        return this.hasMarkup(other.type, other.attrs, other.marks);\n    }\n    /**\n    Check whether this node's markup correspond to the given type,\n    attributes, and marks.\n    */\n    hasMarkup(type, attrs, marks) {\n        return this.type == type &&\n            compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n            Mark.sameSet(this.marks, marks || Mark.none);\n    }\n    /**\n    Create a new node with the same markup as this node, containing\n    the given content (or empty, if no content is given).\n    */\n    copy(content = null) {\n        if (content == this.content)\n            return this;\n        return new Node(this.type, this.attrs, content, this.marks);\n    }\n    /**\n    Create a copy of this node, with the given set of marks instead\n    of the node's own marks.\n    */\n    mark(marks) {\n        return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n    }\n    /**\n    Create a copy of this node with only the content between the\n    given positions. If `to` is not given, it defaults to the end of\n    the node.\n    */\n    cut(from, to = this.content.size) {\n        if (from == 0 && to == this.content.size)\n            return this;\n        return this.copy(this.content.cut(from, to));\n    }\n    /**\n    Cut out the part of the document between the given positions, and\n    return it as a `Slice` object.\n    */\n    slice(from, to = this.content.size, includeParents = false) {\n        if (from == to)\n            return Slice.empty;\n        let $from = this.resolve(from), $to = this.resolve(to);\n        let depth = includeParents ? 0 : $from.sharedDepth(to);\n        let start = $from.start(depth), node = $from.node(depth);\n        let content = node.content.cut($from.pos - start, $to.pos - start);\n        return new Slice(content, $from.depth - depth, $to.depth - depth);\n    }\n    /**\n    Replace the part of the document between the given positions with\n    the given slice. The slice must 'fit', meaning its open sides\n    must be able to connect to the surrounding content, and its\n    content nodes must be valid children for the node they are placed\n    into. If any of this is violated, an error of type\n    [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n    */\n    replace(from, to, slice) {\n        return replace(this.resolve(from), this.resolve(to), slice);\n    }\n    /**\n    Find the node directly after the given position.\n    */\n    nodeAt(pos) {\n        for (let node = this;;) {\n            let { index, offset } = node.content.findIndex(pos);\n            node = node.maybeChild(index);\n            if (!node)\n                return null;\n            if (offset == pos || node.isText)\n                return node;\n            pos -= offset + 1;\n        }\n    }\n    /**\n    Find the (direct) child node after the given offset, if any,\n    and return it along with its index and offset relative to this\n    node.\n    */\n    childAfter(pos) {\n        let { index, offset } = this.content.findIndex(pos);\n        return { node: this.content.maybeChild(index), index, offset };\n    }\n    /**\n    Find the (direct) child node before the given offset, if any,\n    and return it along with its index and offset relative to this\n    node.\n    */\n    childBefore(pos) {\n        if (pos == 0)\n            return { node: null, index: 0, offset: 0 };\n        let { index, offset } = this.content.findIndex(pos);\n        if (offset < pos)\n            return { node: this.content.child(index), index, offset };\n        let node = this.content.child(index - 1);\n        return { node, index: index - 1, offset: offset - node.nodeSize };\n    }\n    /**\n    Resolve the given position in the document, returning an\n    [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n    */\n    resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n    /**\n    @internal\n    */\n    resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n    /**\n    Test whether a given mark or mark type occurs in this document\n    between the two given positions.\n    */\n    rangeHasMark(from, to, type) {\n        let found = false;\n        if (to > from)\n            this.nodesBetween(from, to, node => {\n                if (type.isInSet(node.marks))\n                    found = true;\n                return !found;\n            });\n        return found;\n    }\n    /**\n    True when this is a block (non-inline node)\n    */\n    get isBlock() { return this.type.isBlock; }\n    /**\n    True when this is a textblock node, a block node with inline\n    content.\n    */\n    get isTextblock() { return this.type.isTextblock; }\n    /**\n    True when this node allows inline content.\n    */\n    get inlineContent() { return this.type.inlineContent; }\n    /**\n    True when this is an inline node (a text node or a node that can\n    appear among text).\n    */\n    get isInline() { return this.type.isInline; }\n    /**\n    True when this is a text node.\n    */\n    get isText() { return this.type.isText; }\n    /**\n    True when this is a leaf node.\n    */\n    get isLeaf() { return this.type.isLeaf; }\n    /**\n    True when this is an atom, i.e. when it does not have directly\n    editable content. This is usually the same as `isLeaf`, but can\n    be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n    on a node's spec (typically used when the node is displayed as\n    an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n    */\n    get isAtom() { return this.type.isAtom; }\n    /**\n    Return a string representation of this node for debugging\n    purposes.\n    */\n    toString() {\n        if (this.type.spec.toDebugString)\n            return this.type.spec.toDebugString(this);\n        let name = this.type.name;\n        if (this.content.size)\n            name += \"(\" + this.content.toStringInner() + \")\";\n        return wrapMarks(this.marks, name);\n    }\n    /**\n    Get the content match in this node at the given index.\n    */\n    contentMatchAt(index) {\n        let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n        if (!match)\n            throw new Error(\"Called contentMatchAt on a node with invalid content\");\n        return match;\n    }\n    /**\n    Test whether replacing the range between `from` and `to` (by\n    child index) with the given replacement fragment (which defaults\n    to the empty fragment) would leave the node's content valid. You\n    can optionally pass `start` and `end` indices into the\n    replacement fragment.\n    */\n    canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n        let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n        let two = one && one.matchFragment(this.content, to);\n        if (!two || !two.validEnd)\n            return false;\n        for (let i = start; i < end; i++)\n            if (!this.type.allowsMarks(replacement.child(i).marks))\n                return false;\n        return true;\n    }\n    /**\n    Test whether replacing the range `from` to `to` (by index) with\n    a node of the given type would leave the node's content valid.\n    */\n    canReplaceWith(from, to, type, marks) {\n        if (marks && !this.type.allowsMarks(marks))\n            return false;\n        let start = this.contentMatchAt(from).matchType(type);\n        let end = start && start.matchFragment(this.content, to);\n        return end ? end.validEnd : false;\n    }\n    /**\n    Test whether the given node's content could be appended to this\n    node. If that node is empty, this will only return true if there\n    is at least one node type that can appear in both nodes (to avoid\n    merging completely incompatible nodes).\n    */\n    canAppend(other) {\n        if (other.content.size)\n            return this.canReplace(this.childCount, this.childCount, other.content);\n        else\n            return this.type.compatibleContent(other.type);\n    }\n    /**\n    Check whether this node and its descendants conform to the\n    schema, and raise an exception when they do not.\n    */\n    check() {\n        this.type.checkContent(this.content);\n        checkAttrs(this.type.attrs, this.attrs, \"node\", this.type.name);\n        let copy = Mark.none;\n        for (let i = 0; i < this.marks.length; i++) {\n            let mark = this.marks[i];\n            checkAttrs(mark.type.attrs, mark.attrs, \"mark\", mark.type.name);\n            copy = mark.addToSet(copy);\n        }\n        if (!Mark.sameSet(copy, this.marks))\n            throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n        this.content.forEach(node => node.check());\n    }\n    /**\n    Return a JSON-serializeable representation of this node.\n    */\n    toJSON() {\n        let obj = { type: this.type.name };\n        for (let _ in this.attrs) {\n            obj.attrs = this.attrs;\n            break;\n        }\n        if (this.content.size)\n            obj.content = this.content.toJSON();\n        if (this.marks.length)\n            obj.marks = this.marks.map(n => n.toJSON());\n        return obj;\n    }\n    /**\n    Deserialize a node from its JSON representation.\n    */\n    static fromJSON(schema, json) {\n        if (!json)\n            throw new RangeError(\"Invalid input for Node.fromJSON\");\n        let marks = undefined;\n        if (json.marks) {\n            if (!Array.isArray(json.marks))\n                throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n            marks = json.marks.map(schema.markFromJSON);\n        }\n        if (json.type == \"text\") {\n            if (typeof json.text != \"string\")\n                throw new RangeError(\"Invalid text node in JSON\");\n            return schema.text(json.text, marks);\n        }\n        let content = Fragment.fromJSON(schema, json.content);\n        let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n        return node;\n    }\n}\nNode.prototype.text = undefined;\n// V8 can leak big strings if you take a slice from them and hang on\n// to the slice (https://issues.chromium.org/issues/41480525). If it\n// looks like we're on V8 (by stack trace pattern), use such strings\n// as index to an object first to intern them to avoid leaking memory\n// in, for example, inverted steps stored in history. (#1609)\nconst v8InternHack = (() => {\n    let { stack } = new Error(\"/\");\n    if (!stack || !/\\n\\s*at\\s/.test(stack))\n        return s => s;\n    let obj = Object.create(null);\n    return s => { obj[s]; return s; };\n})();\nclass TextNode extends Node {\n    /**\n    @internal\n    */\n    constructor(type, attrs, content, marks) {\n        super(type, attrs, null, marks);\n        if (!content)\n            throw new RangeError(\"Empty text nodes are not allowed\");\n        this.text = content;\n    }\n    toString() {\n        if (this.type.spec.toDebugString)\n            return this.type.spec.toDebugString(this);\n        return wrapMarks(this.marks, JSON.stringify(this.text));\n    }\n    get textContent() { return this.text; }\n    textBetween(from, to) { return v8InternHack(this.text.slice(from, to)); }\n    get nodeSize() { return this.text.length; }\n    mark(marks) {\n        return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n    }\n    withText(text) {\n        if (text == this.text)\n            return this;\n        return new TextNode(this.type, this.attrs, text, this.marks);\n    }\n    cut(from = 0, to = this.text.length) {\n        if (from == 0 && to == this.text.length)\n            return this;\n        return this.withText(v8InternHack(this.text.slice(from, to)));\n    }\n    eq(other) {\n        return this.sameMarkup(other) && this.text == other.text;\n    }\n    toJSON() {\n        let base = super.toJSON();\n        base.text = this.text;\n        return base;\n    }\n}\nfunction wrapMarks(marks, str) {\n    for (let i = marks.length - 1; i >= 0; i--)\n        str = marks[i].type.name + \"(\" + str + \")\";\n    return str;\n}\nfunction checkAttrs(attrs, values, type, name) {\n    for (let attr in values)\n        if (!(attr in attrs))\n            throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`);\n    for (let attr in attrs) {\n        if (attrs[attr].validate)\n            attrs[attr].validate(values[attr]);\n    }\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    True when this match state represents a valid end of the node.\n    */\n    validEnd) {\n        this.validEnd = validEnd;\n        /**\n        @internal\n        */\n        this.next = [];\n        /**\n        @internal\n        */\n        this.wrapCache = [];\n    }\n    /**\n    @internal\n    */\n    static parse(string, nodeTypes) {\n        let stream = new TokenStream(string, nodeTypes);\n        if (stream.next == null)\n            return ContentMatch.empty;\n        let expr = parseExpr(stream);\n        if (stream.next)\n            stream.err(\"Unexpected trailing text\");\n        let match = dfa(nfa(expr));\n        checkForDeadEnds(match, stream);\n        return match;\n    }\n    /**\n    Match a node type, returning a match after that node if\n    successful.\n    */\n    matchType(type) {\n        for (let i = 0; i < this.next.length; i++)\n            if (this.next[i].type == type)\n                return this.next[i].next;\n        return null;\n    }\n    /**\n    Try to match a fragment. Returns the resulting match when\n    successful.\n    */\n    matchFragment(frag, start = 0, end = frag.childCount) {\n        let cur = this;\n        for (let i = start; cur && i < end; i++)\n            cur = cur.matchType(frag.child(i).type);\n        return cur;\n    }\n    /**\n    @internal\n    */\n    get inlineContent() {\n        return this.next.length != 0 && this.next[0].type.isInline;\n    }\n    /**\n    Get the first matching node type at this match position that can\n    be generated.\n    */\n    get defaultType() {\n        for (let i = 0; i < this.next.length; i++) {\n            let { type } = this.next[i];\n            if (!(type.isText || type.hasRequiredAttrs()))\n                return type;\n        }\n        return null;\n    }\n    /**\n    @internal\n    */\n    compatible(other) {\n        for (let i = 0; i < this.next.length; i++)\n            for (let j = 0; j < other.next.length; j++)\n                if (this.next[i].type == other.next[j].type)\n                    return true;\n        return false;\n    }\n    /**\n    Try to match the given fragment, and if that fails, see if it can\n    be made to match by inserting nodes in front of it. When\n    successful, return a fragment of inserted nodes (which may be\n    empty if nothing had to be inserted). When `toEnd` is true, only\n    return a fragment if the resulting match goes to the end of the\n    content expression.\n    */\n    fillBefore(after, toEnd = false, startIndex = 0) {\n        let seen = [this];\n        function search(match, types) {\n            let finished = match.matchFragment(after, startIndex);\n            if (finished && (!toEnd || finished.validEnd))\n                return Fragment.from(types.map(tp => tp.createAndFill()));\n            for (let i = 0; i < match.next.length; i++) {\n                let { type, next } = match.next[i];\n                if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n                    seen.push(next);\n                    let found = search(next, types.concat(type));\n                    if (found)\n                        return found;\n                }\n            }\n            return null;\n        }\n        return search(this, []);\n    }\n    /**\n    Find a set of wrapping node types that would allow a node of the\n    given type to appear at this position. The result may be empty\n    (when it fits directly) and will be null when no such wrapping\n    exists.\n    */\n    findWrapping(target) {\n        for (let i = 0; i < this.wrapCache.length; i += 2)\n            if (this.wrapCache[i] == target)\n                return this.wrapCache[i + 1];\n        let computed = this.computeWrapping(target);\n        this.wrapCache.push(target, computed);\n        return computed;\n    }\n    /**\n    @internal\n    */\n    computeWrapping(target) {\n        let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n        while (active.length) {\n            let current = active.shift(), match = current.match;\n            if (match.matchType(target)) {\n                let result = [];\n                for (let obj = current; obj.type; obj = obj.via)\n                    result.push(obj.type);\n                return result.reverse();\n            }\n            for (let i = 0; i < match.next.length; i++) {\n                let { type, next } = match.next[i];\n                if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n                    active.push({ match: type.contentMatch, type, via: current });\n                    seen[type.name] = true;\n                }\n            }\n        }\n        return null;\n    }\n    /**\n    The number of outgoing edges this node has in the finite\n    automaton that describes the content expression.\n    */\n    get edgeCount() {\n        return this.next.length;\n    }\n    /**\n    Get the _n_\u200Bth outgoing edge from this node in the finite\n    automaton that describes the content expression.\n    */\n    edge(n) {\n        if (n >= this.next.length)\n            throw new RangeError(`There's no ${n}th edge in this content match`);\n        return this.next[n];\n    }\n    /**\n    @internal\n    */\n    toString() {\n        let seen = [];\n        function scan(m) {\n            seen.push(m);\n            for (let i = 0; i < m.next.length; i++)\n                if (seen.indexOf(m.next[i].next) == -1)\n                    scan(m.next[i].next);\n        }\n        scan(this);\n        return seen.map((m, i) => {\n            let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n            for (let i = 0; i < m.next.length; i++)\n                out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n            return out;\n        }).join(\"\\n\");\n    }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n    constructor(string, nodeTypes) {\n        this.string = string;\n        this.nodeTypes = nodeTypes;\n        this.inline = null;\n        this.pos = 0;\n        this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n        if (this.tokens[this.tokens.length - 1] == \"\")\n            this.tokens.pop();\n        if (this.tokens[0] == \"\")\n            this.tokens.shift();\n    }\n    get next() { return this.tokens[this.pos]; }\n    eat(tok) { return this.next == tok && (this.pos++ || true); }\n    err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n    let exprs = [];\n    do {\n        exprs.push(parseExprSeq(stream));\n    } while (stream.eat(\"|\"));\n    return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n    let exprs = [];\n    do {\n        exprs.push(parseExprSubscript(stream));\n    } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n    return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n    let expr = parseExprAtom(stream);\n    for (;;) {\n        if (stream.eat(\"+\"))\n            expr = { type: \"plus\", expr };\n        else if (stream.eat(\"*\"))\n            expr = { type: \"star\", expr };\n        else if (stream.eat(\"?\"))\n            expr = { type: \"opt\", expr };\n        else if (stream.eat(\"{\"))\n            expr = parseExprRange(stream, expr);\n        else\n            break;\n    }\n    return expr;\n}\nfunction parseNum(stream) {\n    if (/\\D/.test(stream.next))\n        stream.err(\"Expected number, got '\" + stream.next + \"'\");\n    let result = Number(stream.next);\n    stream.pos++;\n    return result;\n}\nfunction parseExprRange(stream, expr) {\n    let min = parseNum(stream), max = min;\n    if (stream.eat(\",\")) {\n        if (stream.next != \"}\")\n            max = parseNum(stream);\n        else\n            max = -1;\n    }\n    if (!stream.eat(\"}\"))\n        stream.err(\"Unclosed braced range\");\n    return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n    let types = stream.nodeTypes, type = types[name];\n    if (type)\n        return [type];\n    let result = [];\n    for (let typeName in types) {\n        let type = types[typeName];\n        if (type.isInGroup(name))\n            result.push(type);\n    }\n    if (result.length == 0)\n        stream.err(\"No node type or group '\" + name + \"' found\");\n    return result;\n}\nfunction parseExprAtom(stream) {\n    if (stream.eat(\"(\")) {\n        let expr = parseExpr(stream);\n        if (!stream.eat(\")\"))\n            stream.err(\"Missing closing paren\");\n        return expr;\n    }\n    else if (!/\\W/.test(stream.next)) {\n        let exprs = resolveName(stream, stream.next).map(type => {\n            if (stream.inline == null)\n                stream.inline = type.isInline;\n            else if (stream.inline != type.isInline)\n                stream.err(\"Mixing inline and block content\");\n            return { type: \"name\", value: type };\n        });\n        stream.pos++;\n        return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n    }\n    else {\n        stream.err(\"Unexpected token '\" + stream.next + \"'\");\n    }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n    let nfa = [[]];\n    connect(compile(expr, 0), node());\n    return nfa;\n    function node() { return nfa.push([]) - 1; }\n    function edge(from, to, term) {\n        let edge = { term, to };\n        nfa[from].push(edge);\n        return edge;\n    }\n    function connect(edges, to) {\n        edges.forEach(edge => edge.to = to);\n    }\n    function compile(expr, from) {\n        if (expr.type == \"choice\") {\n            return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n        }\n        else if (expr.type == \"seq\") {\n            for (let i = 0;; i++) {\n                let next = compile(expr.exprs[i], from);\n                if (i == expr.exprs.length - 1)\n                    return next;\n                connect(next, from = node());\n            }\n        }\n        else if (expr.type == \"star\") {\n            let loop = node();\n            edge(from, loop);\n            connect(compile(expr.expr, loop), loop);\n            return [edge(loop)];\n        }\n        else if (expr.type == \"plus\") {\n            let loop = node();\n            connect(compile(expr.expr, from), loop);\n            connect(compile(expr.expr, loop), loop);\n            return [edge(loop)];\n        }\n        else if (expr.type == \"opt\") {\n            return [edge(from)].concat(compile(expr.expr, from));\n        }\n        else if (expr.type == \"range\") {\n            let cur = from;\n            for (let i = 0; i < expr.min; i++) {\n                let next = node();\n                connect(compile(expr.expr, cur), next);\n                cur = next;\n            }\n            if (expr.max == -1) {\n                connect(compile(expr.expr, cur), cur);\n            }\n            else {\n                for (let i = expr.min; i < expr.max; i++) {\n                    let next = node();\n                    edge(cur, next);\n                    connect(compile(expr.expr, cur), next);\n                    cur = next;\n                }\n            }\n            return [edge(cur)];\n        }\n        else if (expr.type == \"name\") {\n            return [edge(from, undefined, expr.value)];\n        }\n        else {\n            throw new Error(\"Unknown expr type\");\n        }\n    }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n    let result = [];\n    scan(node);\n    return result.sort(cmp);\n    function scan(node) {\n        let edges = nfa[node];\n        if (edges.length == 1 && !edges[0].term)\n            return scan(edges[0].to);\n        result.push(node);\n        for (let i = 0; i < edges.length; i++) {\n            let { term, to } = edges[i];\n            if (!term && result.indexOf(to) == -1)\n                scan(to);\n        }\n    }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n    let labeled = Object.create(null);\n    return explore(nullFrom(nfa, 0));\n    function explore(states) {\n        let out = [];\n        states.forEach(node => {\n            nfa[node].forEach(({ term, to }) => {\n                if (!term)\n                    return;\n                let set;\n                for (let i = 0; i < out.length; i++)\n                    if (out[i][0] == term)\n                        set = out[i][1];\n                nullFrom(nfa, to).forEach(node => {\n                    if (!set)\n                        out.push([term, set = []]);\n                    if (set.indexOf(node) == -1)\n                        set.push(node);\n                });\n            });\n        });\n        let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n        for (let i = 0; i < out.length; i++) {\n            let states = out[i][1].sort(cmp);\n            state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n        }\n        return state;\n    }\n}\nfunction checkForDeadEnds(match, stream) {\n    for (let i = 0, work = [match]; i < work.length; i++) {\n        let state = work[i], dead = !state.validEnd, nodes = [];\n        for (let j = 0; j < state.next.length; j++) {\n            let { type, next } = state.next[j];\n            nodes.push(type.name);\n            if (dead && !(type.isText || type.hasRequiredAttrs()))\n                dead = false;\n            if (work.indexOf(next) == -1)\n                work.push(next);\n        }\n        if (dead)\n            stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n    }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n    let defaults = Object.create(null);\n    for (let attrName in attrs) {\n        let attr = attrs[attrName];\n        if (!attr.hasDefault)\n            return null;\n        defaults[attrName] = attr.default;\n    }\n    return defaults;\n}\nfunction computeAttrs(attrs, value) {\n    let built = Object.create(null);\n    for (let name in attrs) {\n        let attr = attrs[name];\n        let given = value && value[name];\n        if (given === undefined) {\n            if (attr.hasDefault)\n                given = attr.default;\n            else\n                throw new RangeError(\"No value supplied for attribute \" + name);\n        }\n        else if (attr.validate) {\n            attr.validate(given);\n        }\n        built[name] = given;\n    }\n    return built;\n}\nfunction initAttrs(typeName, attrs) {\n    let result = Object.create(null);\n    if (attrs)\n        for (let name in attrs)\n            result[name] = new Attribute(typeName, name, attrs[name]);\n    return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The name the node type has in this schema.\n    */\n    name, \n    /**\n    A link back to the `Schema` the node type belongs to.\n    */\n    schema, \n    /**\n    The spec that this type is based on\n    */\n    spec) {\n        this.name = name;\n        this.schema = schema;\n        this.spec = spec;\n        /**\n        The set of marks allowed in this node. `null` means all marks\n        are allowed.\n        */\n        this.markSet = null;\n        this.groups = spec.group ? spec.group.split(\" \") : [];\n        this.attrs = initAttrs(name, spec.attrs);\n        this.defaultAttrs = defaultAttrs(this.attrs);\n        this.contentMatch = null;\n        this.inlineContent = null;\n        this.isBlock = !(spec.inline || name == \"text\");\n        this.isText = name == \"text\";\n    }\n    /**\n    True if this is an inline type.\n    */\n    get isInline() { return !this.isBlock; }\n    /**\n    True if this is a textblock type, a block that contains inline\n    content.\n    */\n    get isTextblock() { return this.isBlock && this.inlineContent; }\n    /**\n    True for node types that allow no content.\n    */\n    get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n    /**\n    True when this node is an atom, i.e. when it does not have\n    directly editable content.\n    */\n    get isAtom() { return this.isLeaf || !!this.spec.atom; }\n    /**\n    Return true when this node type is part of the given\n    [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n    */\n    isInGroup(group) {\n        return this.groups.indexOf(group) > -1;\n    }\n    /**\n    The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n    */\n    get whitespace() {\n        return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n    }\n    /**\n    Tells you whether this node type has any required attributes.\n    */\n    hasRequiredAttrs() {\n        for (let n in this.attrs)\n            if (this.attrs[n].isRequired)\n                return true;\n        return false;\n    }\n    /**\n    Indicates whether this node allows some of the same content as\n    the given node type.\n    */\n    compatibleContent(other) {\n        return this == other || this.contentMatch.compatible(other.contentMatch);\n    }\n    /**\n    @internal\n    */\n    computeAttrs(attrs) {\n        if (!attrs && this.defaultAttrs)\n            return this.defaultAttrs;\n        else\n            return computeAttrs(this.attrs, attrs);\n    }\n    /**\n    Create a `Node` of this type. The given attributes are\n    checked and defaulted (you can pass `null` to use the type's\n    defaults entirely, if no required attributes exist). `content`\n    may be a `Fragment`, a node, an array of nodes, or\n    `null`. Similarly `marks` may be `null` to default to the empty\n    set of marks.\n    */\n    create(attrs = null, content, marks) {\n        if (this.isText)\n            throw new Error(\"NodeType.create can't construct text nodes\");\n        return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n    }\n    /**\n    Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n    against the node type's content restrictions, and throw an error\n    if it doesn't match.\n    */\n    createChecked(attrs = null, content, marks) {\n        content = Fragment.from(content);\n        this.checkContent(content);\n        return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n    }\n    /**\n    Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n    necessary to add nodes to the start or end of the given fragment\n    to make it fit the node. If no fitting wrapping can be found,\n    return null. Note that, due to the fact that required nodes can\n    always be created, this will always succeed if you pass null or\n    `Fragment.empty` as content.\n    */\n    createAndFill(attrs = null, content, marks) {\n        attrs = this.computeAttrs(attrs);\n        content = Fragment.from(content);\n        if (content.size) {\n            let before = this.contentMatch.fillBefore(content);\n            if (!before)\n                return null;\n            content = before.append(content);\n        }\n        let matched = this.contentMatch.matchFragment(content);\n        let after = matched && matched.fillBefore(Fragment.empty, true);\n        if (!after)\n            return null;\n        return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n    }\n    /**\n    Returns true if the given fragment is valid content for this node\n    type.\n    */\n    validContent(content) {\n        let result = this.contentMatch.matchFragment(content);\n        if (!result || !result.validEnd)\n            return false;\n        for (let i = 0; i < content.childCount; i++)\n            if (!this.allowsMarks(content.child(i).marks))\n                return false;\n        return true;\n    }\n    /**\n    Throws a RangeError if the given fragment is not valid content for this\n    node type.\n    @internal\n    */\n    checkContent(content) {\n        if (!this.validContent(content))\n            throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n    }\n    /**\n    @internal no longer useful, but called by old prosemirror-view versions\n    */\n    checkAttrs(attrs) { }\n    /**\n    Check whether the given mark type is allowed in this node.\n    */\n    allowsMarkType(markType) {\n        return this.markSet == null || this.markSet.indexOf(markType) > -1;\n    }\n    /**\n    Test whether the given set of marks are allowed in this node.\n    */\n    allowsMarks(marks) {\n        if (this.markSet == null)\n            return true;\n        for (let i = 0; i < marks.length; i++)\n            if (!this.allowsMarkType(marks[i].type))\n                return false;\n        return true;\n    }\n    /**\n    Removes the marks that are not allowed in this node from the given set.\n    */\n    allowedMarks(marks) {\n        if (this.markSet == null)\n            return marks;\n        let copy;\n        for (let i = 0; i < marks.length; i++) {\n            if (!this.allowsMarkType(marks[i].type)) {\n                if (!copy)\n                    copy = marks.slice(0, i);\n            }\n            else if (copy) {\n                copy.push(marks[i]);\n            }\n        }\n        return !copy ? marks : copy.length ? copy : Mark.none;\n    }\n    /**\n    @internal\n    */\n    static compile(nodes, schema) {\n        let result = Object.create(null);\n        nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n        let topType = schema.spec.topNode || \"doc\";\n        if (!result[topType])\n            throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n        if (!result.text)\n            throw new RangeError(\"Every schema needs a 'text' type\");\n        for (let _ in result.text.attrs)\n            throw new RangeError(\"The text node type should not have attributes\");\n        return result;\n    }\n}\nfunction validateType(typeName, attrName, type) {\n    let types = type.split(\"|\");\n    return (value) => {\n        let name = value === null ? \"null\" : typeof value;\n        if (types.indexOf(name) < 0)\n            throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n    };\n}\n// Attribute descriptors\nclass Attribute {\n    constructor(typeName, attrName, options) {\n        this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n        this.default = options.default;\n        this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n    }\n    get isRequired() {\n        return !this.hasDefault;\n    }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The name of the mark type.\n    */\n    name, \n    /**\n    @internal\n    */\n    rank, \n    /**\n    The schema that this mark type instance is part of.\n    */\n    schema, \n    /**\n    The spec on which the type is based.\n    */\n    spec) {\n        this.name = name;\n        this.rank = rank;\n        this.schema = schema;\n        this.spec = spec;\n        this.attrs = initAttrs(name, spec.attrs);\n        this.excluded = null;\n        let defaults = defaultAttrs(this.attrs);\n        this.instance = defaults ? new Mark(this, defaults) : null;\n    }\n    /**\n    Create a mark of this type. `attrs` may be `null` or an object\n    containing only some of the mark's attributes. The others, if\n    they have defaults, will be added.\n    */\n    create(attrs = null) {\n        if (!attrs && this.instance)\n            return this.instance;\n        return new Mark(this, computeAttrs(this.attrs, attrs));\n    }\n    /**\n    @internal\n    */\n    static compile(marks, schema) {\n        let result = Object.create(null), rank = 0;\n        marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n        return result;\n    }\n    /**\n    When there is a mark of this type in the given set, a new set\n    without it is returned. Otherwise, the input set is returned.\n    */\n    removeFromSet(set) {\n        for (var i = 0; i < set.length; i++)\n            if (set[i].type == this) {\n                set = set.slice(0, i).concat(set.slice(i + 1));\n                i--;\n            }\n        return set;\n    }\n    /**\n    Tests whether there is a mark of this type in the given set.\n    */\n    isInSet(set) {\n        for (let i = 0; i < set.length; i++)\n            if (set[i].type == this)\n                return set[i];\n    }\n    /**\n    Queries whether a given mark type is\n    [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n    */\n    excludes(other) {\n        return this.excluded.indexOf(other) > -1;\n    }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n    /**\n    Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n    */\n    constructor(spec) {\n        /**\n        The [linebreak\n        replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n        in this schema, if any.\n        */\n        this.linebreakReplacement = null;\n        /**\n        An object for storing whatever values modules may want to\n        compute and cache per schema. (If you want to store something\n        in it, try to use property names unlikely to clash.)\n        */\n        this.cached = Object.create(null);\n        let instanceSpec = this.spec = {};\n        for (let prop in spec)\n            instanceSpec[prop] = spec[prop];\n        instanceSpec.nodes = OrderedMap.from(spec.nodes),\n            instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n            this.nodes = NodeType.compile(this.spec.nodes, this);\n        this.marks = MarkType.compile(this.spec.marks, this);\n        let contentExprCache = Object.create(null);\n        for (let prop in this.nodes) {\n            if (prop in this.marks)\n                throw new RangeError(prop + \" can not be both a node and a mark\");\n            let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n            type.contentMatch = contentExprCache[contentExpr] ||\n                (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n            type.inlineContent = type.contentMatch.inlineContent;\n            if (type.spec.linebreakReplacement) {\n                if (this.linebreakReplacement)\n                    throw new RangeError(\"Multiple linebreak nodes defined\");\n                if (!type.isInline || !type.isLeaf)\n                    throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n                this.linebreakReplacement = type;\n            }\n            type.markSet = markExpr == \"_\" ? null :\n                markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n                    markExpr == \"\" || !type.inlineContent ? [] : null;\n        }\n        for (let prop in this.marks) {\n            let type = this.marks[prop], excl = type.spec.excludes;\n            type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n        }\n        this.nodeFromJSON = json => Node.fromJSON(this, json);\n        this.markFromJSON = json => Mark.fromJSON(this, json);\n        this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n        this.cached.wrappings = Object.create(null);\n    }\n    /**\n    Create a node in this schema. The `type` may be a string or a\n    `NodeType` instance. Attributes will be extended with defaults,\n    `content` may be a `Fragment`, `null`, a `Node`, or an array of\n    nodes.\n    */\n    node(type, attrs = null, content, marks) {\n        if (typeof type == \"string\")\n            type = this.nodeType(type);\n        else if (!(type instanceof NodeType))\n            throw new RangeError(\"Invalid node type: \" + type);\n        else if (type.schema != this)\n            throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n        return type.createChecked(attrs, content, marks);\n    }\n    /**\n    Create a text node in the schema. Empty text nodes are not\n    allowed.\n    */\n    text(text, marks) {\n        let type = this.nodes.text;\n        return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n    }\n    /**\n    Create a mark with the given type and attributes.\n    */\n    mark(type, attrs) {\n        if (typeof type == \"string\")\n            type = this.marks[type];\n        return type.create(attrs);\n    }\n    /**\n    @internal\n    */\n    nodeType(name) {\n        let found = this.nodes[name];\n        if (!found)\n            throw new RangeError(\"Unknown node type: \" + name);\n        return found;\n    }\n}\nfunction gatherMarks(schema, marks) {\n    let found = [];\n    for (let i = 0; i < marks.length; i++) {\n        let name = marks[i], mark = schema.marks[name], ok = mark;\n        if (mark) {\n            found.push(mark);\n        }\n        else {\n            for (let prop in schema.marks) {\n                let mark = schema.marks[prop];\n                if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n                    found.push(ok = mark);\n            }\n        }\n        if (!ok)\n            throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n    }\n    return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n    /**\n    Create a parser that targets the given schema, using the given\n    parsing rules.\n    */\n    constructor(\n    /**\n    The schema into which the parser parses.\n    */\n    schema, \n    /**\n    The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n    uses, in order of precedence.\n    */\n    rules) {\n        this.schema = schema;\n        this.rules = rules;\n        /**\n        @internal\n        */\n        this.tags = [];\n        /**\n        @internal\n        */\n        this.styles = [];\n        let matchedStyles = this.matchedStyles = [];\n        rules.forEach(rule => {\n            if (isTagRule(rule)) {\n                this.tags.push(rule);\n            }\n            else if (isStyleRule(rule)) {\n                let prop = /[^=]*/.exec(rule.style)[0];\n                if (matchedStyles.indexOf(prop) < 0)\n                    matchedStyles.push(prop);\n                this.styles.push(rule);\n            }\n        });\n        // Only normalize list elements when lists in the schema can't directly contain themselves\n        this.normalizeLists = !this.tags.some(r => {\n            if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n                return false;\n            let node = schema.nodes[r.node];\n            return node.contentMatch.matchType(node);\n        });\n    }\n    /**\n    Parse a document from the content of a DOM node.\n    */\n    parse(dom, options = {}) {\n        let context = new ParseContext(this, options, false);\n        context.addAll(dom, Mark.none, options.from, options.to);\n        return context.finish();\n    }\n    /**\n    Parses the content of the given DOM node, like\n    [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n    options. But unlike that method, which produces a whole node,\n    this one returns a slice that is open at the sides, meaning that\n    the schema constraints aren't applied to the start of nodes to\n    the left of the input and the end of nodes at the end.\n    */\n    parseSlice(dom, options = {}) {\n        let context = new ParseContext(this, options, true);\n        context.addAll(dom, Mark.none, options.from, options.to);\n        return Slice.maxOpen(context.finish());\n    }\n    /**\n    @internal\n    */\n    matchTag(dom, context, after) {\n        for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n            let rule = this.tags[i];\n            if (matches(dom, rule.tag) &&\n                (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n                (!rule.context || context.matchesContext(rule.context))) {\n                if (rule.getAttrs) {\n                    let result = rule.getAttrs(dom);\n                    if (result === false)\n                        continue;\n                    rule.attrs = result || undefined;\n                }\n                return rule;\n            }\n        }\n    }\n    /**\n    @internal\n    */\n    matchStyle(prop, value, context, after) {\n        for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n            let rule = this.styles[i], style = rule.style;\n            if (style.indexOf(prop) != 0 ||\n                rule.context && !context.matchesContext(rule.context) ||\n                // Test that the style string either precisely matches the prop,\n                // or has an '=' sign after the prop, followed by the given\n                // value.\n                style.length > prop.length &&\n                    (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n                continue;\n            if (rule.getAttrs) {\n                let result = rule.getAttrs(value);\n                if (result === false)\n                    continue;\n                rule.attrs = result || undefined;\n            }\n            return rule;\n        }\n    }\n    /**\n    @internal\n    */\n    static schemaRules(schema) {\n        let result = [];\n        function insert(rule) {\n            let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n            for (; i < result.length; i++) {\n                let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n                if (nextPriority < priority)\n                    break;\n            }\n            result.splice(i, 0, rule);\n        }\n        for (let name in schema.marks) {\n            let rules = schema.marks[name].spec.parseDOM;\n            if (rules)\n                rules.forEach(rule => {\n                    insert(rule = copy(rule));\n                    if (!(rule.mark || rule.ignore || rule.clearMark))\n                        rule.mark = name;\n                });\n        }\n        for (let name in schema.nodes) {\n            let rules = schema.nodes[name].spec.parseDOM;\n            if (rules)\n                rules.forEach(rule => {\n                    insert(rule = copy(rule));\n                    if (!(rule.node || rule.ignore || rule.mark))\n                        rule.node = name;\n                });\n        }\n        return result;\n    }\n    /**\n    Construct a DOM parser using the parsing rules listed in a\n    schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n    [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).\n    */\n    static fromSchema(schema) {\n        return schema.cached.domParser ||\n            (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n    }\n}\nconst blockTags = {\n    address: true, article: true, aside: true, blockquote: true, body: true, canvas: true,\n    dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n    footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n    h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n    output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n    head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n    if (preserveWhitespace != null)\n        return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n            (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n    return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n    constructor(type, attrs, marks, solid, match, options) {\n        this.type = type;\n        this.attrs = attrs;\n        this.marks = marks;\n        this.solid = solid;\n        this.options = options;\n        this.content = [];\n        // Marks applied to the node's children\n        this.activeMarks = Mark.none;\n        this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n    }\n    findWrapping(node) {\n        if (!this.match) {\n            if (!this.type)\n                return [];\n            let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n            if (fill) {\n                this.match = this.type.contentMatch.matchFragment(fill);\n            }\n            else {\n                let start = this.type.contentMatch, wrap;\n                if (wrap = start.findWrapping(node.type)) {\n                    this.match = start;\n                    return wrap;\n                }\n                else {\n                    return null;\n                }\n            }\n        }\n        return this.match.findWrapping(node.type);\n    }\n    finish(openEnd) {\n        if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n            let last = this.content[this.content.length - 1], m;\n            if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n                let text = last;\n                if (last.text.length == m[0].length)\n                    this.content.pop();\n                else\n                    this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n            }\n        }\n        let content = Fragment.from(this.content);\n        if (!openEnd && this.match)\n            content = content.append(this.match.fillBefore(Fragment.empty, true));\n        return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n    }\n    inlineContext(node) {\n        if (this.type)\n            return this.type.inlineContent;\n        if (this.content.length)\n            return this.content[0].isInline;\n        return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n    }\n}\nclass ParseContext {\n    constructor(\n    // The parser we are using.\n    parser, \n    // The options passed to this parse.\n    options, isOpen) {\n        this.parser = parser;\n        this.options = options;\n        this.isOpen = isOpen;\n        this.open = 0;\n        this.localPreserveWS = false;\n        let topNode = options.topNode, topContext;\n        let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n        if (topNode)\n            topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n        else if (isOpen)\n            topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n        else\n            topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n        this.nodes = [topContext];\n        this.find = options.findPositions;\n        this.needsBlock = false;\n    }\n    get top() {\n        return this.nodes[this.open];\n    }\n    // Add a DOM node to the content. Text is inserted as text node,\n    // otherwise, the node is passed to `addElement` or, if it has a\n    // `style` attribute, `addElementWithStyles`.\n    addDOM(dom, marks) {\n        if (dom.nodeType == 3)\n            this.addTextNode(dom, marks);\n        else if (dom.nodeType == 1)\n            this.addElement(dom, marks);\n    }\n    addTextNode(dom, marks) {\n        let value = dom.nodeValue;\n        let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n            : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n        let { schema } = this.parser;\n        if (preserveWS === \"full\" ||\n            top.inlineContext(dom) ||\n            /[^ \\t\\r\\n\\u000c]/.test(value)) {\n            if (!preserveWS) {\n                value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n                // If this starts with whitespace, and there is no node before it, or\n                // a hard break, or a text node that ends with whitespace, strip the\n                // leading space.\n                if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n                    let nodeBefore = top.content[top.content.length - 1];\n                    let domNodeBefore = dom.previousSibling;\n                    if (!nodeBefore ||\n                        (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n                        (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n                        value = value.slice(1);\n                }\n            }\n            else if (preserveWS === \"full\") {\n                value = value.replace(/\\r\\n?/g, \"\\n\");\n            }\n            else if (schema.linebreakReplacement && /[\\r\\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {\n                let lines = value.split(/\\r?\\n|\\r/);\n                for (let i = 0; i < lines.length; i++) {\n                    if (i)\n                        this.insertNode(schema.linebreakReplacement.create(), marks, true);\n                    if (lines[i])\n                        this.insertNode(schema.text(lines[i]), marks, !/\\S/.test(lines[i]));\n                }\n                value = \"\";\n            }\n            else {\n                value = value.replace(/\\r?\\n|\\r/g, \" \");\n            }\n            if (value)\n                this.insertNode(schema.text(value), marks, !/\\S/.test(value));\n            this.findInText(dom);\n        }\n        else {\n            this.findInside(dom);\n        }\n    }\n    // Try to find a handler for the given tag and use that to parse. If\n    // none is found, the element's content nodes are added directly.\n    addElement(dom, marks, matchAfter) {\n        let outerWS = this.localPreserveWS, top = this.top;\n        if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n            this.localPreserveWS = true;\n        let name = dom.nodeName.toLowerCase(), ruleID;\n        if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n            normalizeList(dom);\n        let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n            (ruleID = this.parser.matchTag(dom, this, matchAfter));\n        out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n            this.findInside(dom);\n            this.ignoreFallback(dom, marks);\n        }\n        else if (!rule || rule.skip || rule.closeParent) {\n            if (rule && rule.closeParent)\n                this.open = Math.max(0, this.open - 1);\n            else if (rule && rule.skip.nodeType)\n                dom = rule.skip;\n            let sync, oldNeedsBlock = this.needsBlock;\n            if (blockTags.hasOwnProperty(name)) {\n                if (top.content.length && top.content[0].isInline && this.open) {\n                    this.open--;\n                    top = this.top;\n                }\n                sync = true;\n                if (!top.type)\n                    this.needsBlock = true;\n            }\n            else if (!dom.firstChild) {\n                this.leafFallback(dom, marks);\n                break out;\n            }\n            let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n            if (innerMarks)\n                this.addAll(dom, innerMarks);\n            if (sync)\n                this.sync(top);\n            this.needsBlock = oldNeedsBlock;\n        }\n        else {\n            let innerMarks = this.readStyles(dom, marks);\n            if (innerMarks)\n                this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n        }\n        this.localPreserveWS = outerWS;\n    }\n    // Called for leaf DOM nodes that would otherwise be ignored\n    leafFallback(dom, marks) {\n        if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n            this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n    }\n    // Called for ignored nodes\n    ignoreFallback(dom, marks) {\n        // Ignored BR nodes should at least create an inline context\n        if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n            this.findPlace(this.parser.schema.text(\"-\"), marks, true);\n    }\n    // Run any style parser associated with the node's styles. Either\n    // return an updated array of marks, or null to indicate some of the\n    // styles had a rule with `ignore` set.\n    readStyles(dom, marks) {\n        let styles = dom.style;\n        // Because many properties will only show up in 'normalized' form\n        // in `style.item` (i.e. text-decoration becomes\n        // text-decoration-line, text-decoration-color, etc), we directly\n        // query the styles mentioned in our rules instead of iterating\n        // over the items.\n        if (styles && styles.length)\n            for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n                let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n                if (value)\n                    for (let after = undefined;;) {\n                        let rule = this.parser.matchStyle(name, value, this, after);\n                        if (!rule)\n                            break;\n                        if (rule.ignore)\n                            return null;\n                        if (rule.clearMark)\n                            marks = marks.filter(m => !rule.clearMark(m));\n                        else\n                            marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n                        if (rule.consuming === false)\n                            after = rule;\n                        else\n                            break;\n                    }\n            }\n        return marks;\n    }\n    // Look up a handler for the given node. If none are found, return\n    // false. Otherwise, apply it, use its return value to drive the way\n    // the node's content is wrapped, and return true.\n    addElementByRule(dom, rule, marks, continueAfter) {\n        let sync, nodeType;\n        if (rule.node) {\n            nodeType = this.parser.schema.nodes[rule.node];\n            if (!nodeType.isLeaf) {\n                let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n                if (inner) {\n                    sync = true;\n                    marks = inner;\n                }\n            }\n            else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == \"BR\")) {\n                this.leafFallback(dom, marks);\n            }\n        }\n        else {\n            let markType = this.parser.schema.marks[rule.mark];\n            marks = marks.concat(markType.create(rule.attrs));\n        }\n        let startIn = this.top;\n        if (nodeType && nodeType.isLeaf) {\n            this.findInside(dom);\n        }\n        else if (continueAfter) {\n            this.addElement(dom, marks, continueAfter);\n        }\n        else if (rule.getContent) {\n            this.findInside(dom);\n            rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks, false));\n        }\n        else {\n            let contentDOM = dom;\n            if (typeof rule.contentElement == \"string\")\n                contentDOM = dom.querySelector(rule.contentElement);\n            else if (typeof rule.contentElement == \"function\")\n                contentDOM = rule.contentElement(dom);\n            else if (rule.contentElement)\n                contentDOM = rule.contentElement;\n            this.findAround(dom, contentDOM, true);\n            this.addAll(contentDOM, marks);\n            this.findAround(dom, contentDOM, false);\n        }\n        if (sync && this.sync(startIn))\n            this.open--;\n    }\n    // Add all child nodes between `startIndex` and `endIndex` (or the\n    // whole node, if not given). If `sync` is passed, use it to\n    // synchronize after every block element.\n    addAll(parent, marks, startIndex, endIndex) {\n        let index = startIndex || 0;\n        for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n            this.findAtPoint(parent, index);\n            this.addDOM(dom, marks);\n        }\n        this.findAtPoint(parent, index);\n    }\n    // Try to find a way to fit the given node type into the current\n    // context. May add intermediate wrappers and/or leave non-solid\n    // nodes that we're in.\n    findPlace(node, marks, cautious) {\n        let route, sync;\n        for (let depth = this.open, penalty = 0; depth >= 0; depth--) {\n            let cx = this.nodes[depth];\n            let found = cx.findWrapping(node);\n            if (found && (!route || route.length > found.length + penalty)) {\n                route = found;\n                sync = cx;\n                if (!found.length)\n                    break;\n            }\n            if (cx.solid) {\n                if (cautious)\n                    break;\n                penalty += 2;\n            }\n        }\n        if (!route)\n            return null;\n        this.sync(sync);\n        for (let i = 0; i < route.length; i++)\n            marks = this.enterInner(route[i], null, marks, false);\n        return marks;\n    }\n    // Try to insert the given node, adjusting the context when needed.\n    insertNode(node, marks, cautious) {\n        if (node.isInline && this.needsBlock && !this.top.type) {\n            let block = this.textblockFromContext();\n            if (block)\n                marks = this.enterInner(block, null, marks);\n        }\n        let innerMarks = this.findPlace(node, marks, cautious);\n        if (innerMarks) {\n            this.closeExtra();\n            let top = this.top;\n            if (top.match)\n                top.match = top.match.matchType(node.type);\n            let nodeMarks = Mark.none;\n            for (let m of innerMarks.concat(node.marks))\n                if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n                    nodeMarks = m.addToSet(nodeMarks);\n            top.content.push(node.mark(nodeMarks));\n            return true;\n        }\n        return false;\n    }\n    // Try to start a node of the given type, adjusting the context when\n    // necessary.\n    enter(type, attrs, marks, preserveWS) {\n        let innerMarks = this.findPlace(type.create(attrs), marks, false);\n        if (innerMarks)\n            innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n        return innerMarks;\n    }\n    // Open a node of the given type\n    enterInner(type, attrs, marks, solid = false, preserveWS) {\n        this.closeExtra();\n        let top = this.top;\n        top.match = top.match && top.match.matchType(type);\n        let options = wsOptionsFor(type, preserveWS, top.options);\n        if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n            options |= OPT_OPEN_LEFT;\n        let applyMarks = Mark.none;\n        marks = marks.filter(m => {\n            if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n                applyMarks = m.addToSet(applyMarks);\n                return false;\n            }\n            return true;\n        });\n        this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n        this.open++;\n        return marks;\n    }\n    // Make sure all nodes above this.open are finished and added to\n    // their parents\n    closeExtra(openEnd = false) {\n        let i = this.nodes.length - 1;\n        if (i > this.open) {\n            for (; i > this.open; i--)\n                this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n            this.nodes.length = this.open + 1;\n        }\n    }\n    finish() {\n        this.open = 0;\n        this.closeExtra(this.isOpen);\n        return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n    }\n    sync(to) {\n        for (let i = this.open; i >= 0; i--) {\n            if (this.nodes[i] == to) {\n                this.open = i;\n                return true;\n            }\n            else if (this.localPreserveWS) {\n                this.nodes[i].options |= OPT_PRESERVE_WS;\n            }\n        }\n        return false;\n    }\n    get currentPos() {\n        this.closeExtra();\n        let pos = 0;\n        for (let i = this.open; i >= 0; i--) {\n            let content = this.nodes[i].content;\n            for (let j = content.length - 1; j >= 0; j--)\n                pos += content[j].nodeSize;\n            if (i)\n                pos++;\n        }\n        return pos;\n    }\n    findAtPoint(parent, offset) {\n        if (this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].node == parent && this.find[i].offset == offset)\n                    this.find[i].pos = this.currentPos;\n            }\n    }\n    findInside(parent) {\n        if (this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n                    this.find[i].pos = this.currentPos;\n            }\n    }\n    findAround(parent, content, before) {\n        if (parent != content && this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n                    let pos = content.compareDocumentPosition(this.find[i].node);\n                    if (pos & (before ? 2 : 4))\n                        this.find[i].pos = this.currentPos;\n                }\n            }\n    }\n    findInText(textNode) {\n        if (this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].node == textNode)\n                    this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n            }\n    }\n    // Determines whether the given context string matches this context.\n    matchesContext(context) {\n        if (context.indexOf(\"|\") > -1)\n            return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n        let parts = context.split(\"/\");\n        let option = this.options.context;\n        let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n        let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n        let match = (i, depth) => {\n            for (; i >= 0; i--) {\n                let part = parts[i];\n                if (part == \"\") {\n                    if (i == parts.length - 1 || i == 0)\n                        continue;\n                    for (; depth >= minDepth; depth--)\n                        if (match(i - 1, depth))\n                            return true;\n                    return false;\n                }\n                else {\n                    let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n                        : option && depth >= minDepth ? option.node(depth - minDepth).type\n                            : null;\n                    if (!next || (next.name != part && !next.isInGroup(part)))\n                        return false;\n                    depth--;\n                }\n            }\n            return true;\n        };\n        return match(parts.length - 1, this.open);\n    }\n    textblockFromContext() {\n        let $context = this.options.context;\n        if ($context)\n            for (let d = $context.depth; d >= 0; d--) {\n                let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n                if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n                    return deflt;\n            }\n        for (let name in this.parser.schema.nodes) {\n            let type = this.parser.schema.nodes[name];\n            if (type.isTextblock && type.defaultAttrs)\n                return type;\n        }\n    }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n    for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n        let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n        if (name && listTags.hasOwnProperty(name) && prevItem) {\n            prevItem.appendChild(child);\n            child = prevItem;\n        }\n        else if (name == \"li\") {\n            prevItem = child;\n        }\n        else if (name) {\n            prevItem = null;\n        }\n    }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n    return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n    let copy = {};\n    for (let prop in obj)\n        copy[prop] = obj[prop];\n    return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n    let nodes = nodeType.schema.nodes;\n    for (let name in nodes) {\n        let parent = nodes[name];\n        if (!parent.allowsMarkType(markType))\n            continue;\n        let seen = [], scan = (match) => {\n            seen.push(match);\n            for (let i = 0; i < match.edgeCount; i++) {\n                let { type, next } = match.edge(i);\n                if (type == nodeType)\n                    return true;\n                if (seen.indexOf(next) < 0 && scan(next))\n                    return true;\n            }\n        };\n        if (scan(parent.contentMatch))\n            return true;\n    }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n    /**\n    Create a serializer. `nodes` should map node names to functions\n    that take a node and return a description of the corresponding\n    DOM. `marks` does the same for mark names, but also gets an\n    argument that tells it whether the mark's content is block or\n    inline content (for typical use, it'll always be inline). A mark\n    serializer may be `null` to indicate that marks of that type\n    should not be serialized.\n    */\n    constructor(\n    /**\n    The node serialization functions.\n    */\n    nodes, \n    /**\n    The mark serialization functions.\n    */\n    marks) {\n        this.nodes = nodes;\n        this.marks = marks;\n    }\n    /**\n    Serialize the content of this fragment to a DOM fragment. When\n    not in the browser, the `document` option, containing a DOM\n    document, should be passed so that the serializer can create\n    nodes.\n    */\n    serializeFragment(fragment, options = {}, target) {\n        if (!target)\n            target = doc(options).createDocumentFragment();\n        let top = target, active = [];\n        fragment.forEach(node => {\n            if (active.length || node.marks.length) {\n                let keep = 0, rendered = 0;\n                while (keep < active.length && rendered < node.marks.length) {\n                    let next = node.marks[rendered];\n                    if (!this.marks[next.type.name]) {\n                        rendered++;\n                        continue;\n                    }\n                    if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n                        break;\n                    keep++;\n                    rendered++;\n                }\n                while (keep < active.length)\n                    top = active.pop()[1];\n                while (rendered < node.marks.length) {\n                    let add = node.marks[rendered++];\n                    let markDOM = this.serializeMark(add, node.isInline, options);\n                    if (markDOM) {\n                        active.push([add, top]);\n                        top.appendChild(markDOM.dom);\n                        top = markDOM.contentDOM || markDOM.dom;\n                    }\n                }\n            }\n            top.appendChild(this.serializeNodeInner(node, options));\n        });\n        return target;\n    }\n    /**\n    @internal\n    */\n    serializeNodeInner(node, options) {\n        if (node.isText)\n            return doc(options).createTextNode(node.text);\n        let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n        if (contentDOM) {\n            if (node.isLeaf)\n                throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n            this.serializeFragment(node.content, options, contentDOM);\n        }\n        return dom;\n    }\n    /**\n    Serialize this node to a DOM node. This can be useful when you\n    need to serialize a part of a document, as opposed to the whole\n    document. To serialize a whole document, use\n    [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n    its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n    */\n    serializeNode(node, options = {}) {\n        let dom = this.serializeNodeInner(node, options);\n        for (let i = node.marks.length - 1; i >= 0; i--) {\n            let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n            if (wrap) {\n                (wrap.contentDOM || wrap.dom).appendChild(dom);\n                dom = wrap.dom;\n            }\n        }\n        return dom;\n    }\n    /**\n    @internal\n    */\n    serializeMark(mark, inline, options = {}) {\n        let toDOM = this.marks[mark.type.name];\n        return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n    }\n    static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n        // Kludge for backwards-compatibility with accidental original behavious\n        if (typeof structure == \"string\")\n            return { dom: doc.createTextNode(structure) };\n        return renderSpec(doc, structure, xmlNS, blockArraysIn);\n    }\n    /**\n    Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n    properties in a schema's node and mark specs.\n    */\n    static fromSchema(schema) {\n        return schema.cached.domSerializer ||\n            (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n    }\n    /**\n    Gather the serializers in a schema's node specs into an object.\n    This can be useful as a base to build a custom serializer from.\n    */\n    static nodesFromSchema(schema) {\n        let result = gatherToDOM(schema.nodes);\n        if (!result.text)\n            result.text = node => node.text;\n        return result;\n    }\n    /**\n    Gather the serializers in a schema's mark specs into an object.\n    */\n    static marksFromSchema(schema) {\n        return gatherToDOM(schema.marks);\n    }\n}\nfunction gatherToDOM(obj) {\n    let result = {};\n    for (let name in obj) {\n        let toDOM = obj[name].spec.toDOM;\n        if (toDOM)\n            result[name] = toDOM;\n    }\n    return result;\n}\nfunction doc(options) {\n    return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n    let value = suspiciousAttributeCache.get(attrs);\n    if (value === undefined)\n        suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n    return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n    let result = null;\n    function scan(value) {\n        if (value && typeof value == \"object\") {\n            if (Array.isArray(value)) {\n                if (typeof value[0] == \"string\") {\n                    if (!result)\n                        result = [];\n                    result.push(value);\n                }\n                else {\n                    for (let i = 0; i < value.length; i++)\n                        scan(value[i]);\n                }\n            }\n            else {\n                for (let prop in value)\n                    scan(value[prop]);\n            }\n        }\n    }\n    scan(attrs);\n    return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n    if (structure.nodeType == 1)\n        return { dom: structure };\n    if (structure.dom && structure.dom.nodeType == 1)\n        return structure;\n    let tagName = structure[0], suspicious;\n    if (typeof tagName != \"string\")\n        throw new RangeError(\"Invalid array passed to renderSpec\");\n    if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n        suspicious.indexOf(structure) > -1)\n        throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n    let space = tagName.indexOf(\" \");\n    if (space > 0) {\n        xmlNS = tagName.slice(0, space);\n        tagName = tagName.slice(space + 1);\n    }\n    let contentDOM;\n    let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n    let attrs = structure[1], start = 1;\n    if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n        start = 2;\n        for (let name in attrs)\n            if (attrs[name] != null) {\n                let space = name.indexOf(\" \");\n                if (space > 0)\n                    dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n                else if (name == \"style\" && dom.style)\n                    dom.style.cssText = attrs[name];\n                else\n                    dom.setAttribute(name, attrs[name]);\n            }\n    }\n    for (let i = start; i < structure.length; i++) {\n        let child = structure[i];\n        if (child === 0) {\n            if (i < structure.length - 1 || i > start)\n                throw new RangeError(\"Content hole must be the only child of its parent node\");\n            return { dom, contentDOM: dom };\n        }\n        else if (typeof child == \"string\") {\n            dom.appendChild(doc.createTextNode(child));\n        }\n        else {\n            let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n            dom.appendChild(inner);\n            if (innerContent) {\n                if (contentDOM)\n                    throw new RangeError(\"Multiple content holes\");\n                contentDOM = innerContent;\n            }\n        }\n    }\n    return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n", "import { ReplaceError, Slice, Mark, Fragment, MarkType } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The mapped version of the position.\n    */\n    pos, \n    /**\n    @internal\n    */\n    delInfo, \n    /**\n    @internal\n    */\n    recover) {\n        this.pos = pos;\n        this.delInfo = delInfo;\n        this.recover = recover;\n    }\n    /**\n    Tells you whether the position was deleted, that is, whether the\n    step removed the token on the side queried (via the `assoc`)\n    argument from the document.\n    */\n    get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n    /**\n    Tells you whether the token before the mapped position was deleted.\n    */\n    get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n    /**\n    True when the token after the mapped position was deleted.\n    */\n    get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n    /**\n    Tells whether any of the steps mapped through deletes across the\n    position (including both the token before and after the\n    position).\n    */\n    get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n    /**\n    Create a position map. The modifications to the document are\n    represented as an array of numbers, in which each group of three\n    represents a modified chunk as `[start, oldSize, newSize]`.\n    */\n    constructor(\n    /**\n    @internal\n    */\n    ranges, \n    /**\n    @internal\n    */\n    inverted = false) {\n        this.ranges = ranges;\n        this.inverted = inverted;\n        if (!ranges.length && StepMap.empty)\n            return StepMap.empty;\n    }\n    /**\n    @internal\n    */\n    recover(value) {\n        let diff = 0, index = recoverIndex(value);\n        if (!this.inverted)\n            for (let i = 0; i < index; i++)\n                diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n        return this.ranges[index * 3] + diff + recoverOffset(value);\n    }\n    mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n    map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n    /**\n    @internal\n    */\n    _map(pos, assoc, simple) {\n        let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n        for (let i = 0; i < this.ranges.length; i += 3) {\n            let start = this.ranges[i] - (this.inverted ? diff : 0);\n            if (start > pos)\n                break;\n            let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n            if (pos <= end) {\n                let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n                let result = start + diff + (side < 0 ? 0 : newSize);\n                if (simple)\n                    return result;\n                let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n                let del = 0;\n                if (oldSize) {\n                    del |= pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n                    if (assoc < 0 ? pos != start : pos != end)\n                        del |= DEL_SIDE;\n                }\n                return new MapResult(result, del, recover);\n            }\n            diff += newSize - oldSize;\n        }\n        return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n    }\n    /**\n    @internal\n    */\n    touches(pos, recover) {\n        let diff = 0, index = recoverIndex(recover);\n        let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n        for (let i = 0; i < this.ranges.length; i += 3) {\n            let start = this.ranges[i] - (this.inverted ? diff : 0);\n            if (start > pos)\n                break;\n            let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n            if (pos <= end && i == index * 3)\n                return true;\n            diff += this.ranges[i + newIndex] - oldSize;\n        }\n        return false;\n    }\n    /**\n    Calls the given function on each of the changed ranges included in\n    this map.\n    */\n    forEach(f) {\n        let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n        for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n            let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n            let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n            f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n            diff += newSize - oldSize;\n        }\n    }\n    /**\n    Create an inverted version of this map. The result can be used to\n    map positions in the post-step document to the pre-step document.\n    */\n    invert() {\n        return new StepMap(this.ranges, !this.inverted);\n    }\n    /**\n    @internal\n    */\n    toString() {\n        return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n    }\n    /**\n    Create a map that moves all positions by offset `n` (which may be\n    negative). This can be useful when applying steps meant for a\n    sub-document to a larger document, or vice-versa.\n    */\n    static offset(n) {\n        return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n    }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n\u2018[rebasing](https://prosemirror.net/docs/guide/#transform.rebasing)\u2019 steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n    /**\n    Create a new mapping with the given position maps.\n    */\n    constructor(maps, \n    /**\n    @internal\n    */\n    mirror, \n    /**\n    The starting position in the `maps` array, used when `map` or\n    `mapResult` is called.\n    */\n    from = 0, \n    /**\n    The end position in the `maps` array.\n    */\n    to = maps ? maps.length : 0) {\n        this.mirror = mirror;\n        this.from = from;\n        this.to = to;\n        this._maps = maps || [];\n        this.ownData = !(maps || mirror);\n    }\n    /**\n    The step maps in this mapping.\n    */\n    get maps() { return this._maps; }\n    /**\n    Create a mapping that maps only through a part of this one.\n    */\n    slice(from = 0, to = this.maps.length) {\n        return new Mapping(this._maps, this.mirror, from, to);\n    }\n    /**\n    Add a step map to the end of this mapping. If `mirrors` is\n    given, it should be the index of the step map that is the mirror\n    image of this one.\n    */\n    appendMap(map, mirrors) {\n        if (!this.ownData) {\n            this._maps = this._maps.slice();\n            this.mirror = this.mirror && this.mirror.slice();\n            this.ownData = true;\n        }\n        this.to = this._maps.push(map);\n        if (mirrors != null)\n            this.setMirror(this._maps.length - 1, mirrors);\n    }\n    /**\n    Add all the step maps in a given mapping to this one (preserving\n    mirroring information).\n    */\n    appendMapping(mapping) {\n        for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) {\n            let mirr = mapping.getMirror(i);\n            this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n        }\n    }\n    /**\n    Finds the offset of the step map that mirrors the map at the\n    given offset, in this mapping (as per the second argument to\n    `appendMap`).\n    */\n    getMirror(n) {\n        if (this.mirror)\n            for (let i = 0; i < this.mirror.length; i++)\n                if (this.mirror[i] == n)\n                    return this.mirror[i + (i % 2 ? -1 : 1)];\n    }\n    /**\n    @internal\n    */\n    setMirror(n, m) {\n        if (!this.mirror)\n            this.mirror = [];\n        this.mirror.push(n, m);\n    }\n    /**\n    Append the inverse of the given mapping to this one.\n    */\n    appendMappingInverted(mapping) {\n        for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) {\n            let mirr = mapping.getMirror(i);\n            this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n        }\n    }\n    /**\n    Create an inverted version of this mapping.\n    */\n    invert() {\n        let inverse = new Mapping;\n        inverse.appendMappingInverted(this);\n        return inverse;\n    }\n    /**\n    Map a position through this mapping.\n    */\n    map(pos, assoc = 1) {\n        if (this.mirror)\n            return this._map(pos, assoc, true);\n        for (let i = this.from; i < this.to; i++)\n            pos = this._maps[i].map(pos, assoc);\n        return pos;\n    }\n    /**\n    Map a position through this mapping, returning a mapping\n    result.\n    */\n    mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n    /**\n    @internal\n    */\n    _map(pos, assoc, simple) {\n        let delInfo = 0;\n        for (let i = this.from; i < this.to; i++) {\n            let map = this._maps[i], result = map.mapResult(pos, assoc);\n            if (result.recover != null) {\n                let corr = this.getMirror(i);\n                if (corr != null && corr > i && corr < this.to) {\n                    i = corr;\n                    pos = this._maps[corr].recover(result.recover);\n                    continue;\n                }\n            }\n            delInfo |= result.delInfo;\n            pos = result.pos;\n        }\n        return simple ? pos : new MapResult(pos, delInfo, null);\n    }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n    /**\n    Get the step map that represents the changes made by this step,\n    and which can be used to transform between positions in the old\n    and the new document.\n    */\n    getMap() { return StepMap.empty; }\n    /**\n    Try to merge this step with another one, to be applied directly\n    after it. Returns the merged step when possible, null if the\n    steps can't be merged.\n    */\n    merge(other) { return null; }\n    /**\n    Deserialize a step from its JSON representation. Will call\n    through to the step class' own implementation of this method.\n    */\n    static fromJSON(schema, json) {\n        if (!json || !json.stepType)\n            throw new RangeError(\"Invalid input for Step.fromJSON\");\n        let type = stepsByID[json.stepType];\n        if (!type)\n            throw new RangeError(`No step type ${json.stepType} defined`);\n        return type.fromJSON(schema, json);\n    }\n    /**\n    To be able to serialize steps to JSON, each step needs a string\n    ID to attach to its JSON representation. Use this method to\n    register an ID for your step classes. Try to pick something\n    that's unlikely to clash with steps from other modules.\n    */\n    static jsonID(id, stepClass) {\n        if (id in stepsByID)\n            throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n        stepsByID[id] = stepClass;\n        stepClass.prototype.jsonID = id;\n        return stepClass;\n    }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The transformed document, if successful.\n    */\n    doc, \n    /**\n    The failure message, if unsuccessful.\n    */\n    failed) {\n        this.doc = doc;\n        this.failed = failed;\n    }\n    /**\n    Create a successful step result.\n    */\n    static ok(doc) { return new StepResult(doc, null); }\n    /**\n    Create a failed step result.\n    */\n    static fail(message) { return new StepResult(null, message); }\n    /**\n    Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n    arguments. Create a successful result if it succeeds, and a\n    failed one if it throws a `ReplaceError`.\n    */\n    static fromReplace(doc, from, to, slice) {\n        try {\n            return StepResult.ok(doc.replace(from, to, slice));\n        }\n        catch (e) {\n            if (e instanceof ReplaceError)\n                return StepResult.fail(e.message);\n            throw e;\n        }\n    }\n}\n\nfunction mapFragment(fragment, f, parent) {\n    let mapped = [];\n    for (let i = 0; i < fragment.childCount; i++) {\n        let child = fragment.child(i);\n        if (child.content.size)\n            child = child.copy(mapFragment(child.content, f, child));\n        if (child.isInline)\n            child = f(child, parent, i);\n        mapped.push(child);\n    }\n    return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n    /**\n    Create a mark step.\n    */\n    constructor(\n    /**\n    The start of the marked range.\n    */\n    from, \n    /**\n    The end of the marked range.\n    */\n    to, \n    /**\n    The mark to add.\n    */\n    mark) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n        let parent = $from.node($from.sharedDepth(this.to));\n        let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n            if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n                return node;\n            return node.mark(this.mark.addToSet(node.marks));\n        }, parent), oldSlice.openStart, oldSlice.openEnd);\n        return StepResult.fromReplace(doc, this.from, this.to, slice);\n    }\n    invert(doc) {\n        let steps = [];\n        doc.nodesBetween(this.from, this.to, (node, pos) => {\n            if (node.isInline && node.isAtom) {\n                let added = this.mark.addToSet(node.marks);\n                if (!Mark.sameSet(added, node.marks)) {\n                    let from = Math.max(this.from, pos), to = Math.min(this.to, pos + node.nodeSize);\n                    pushMarkStep(RemoveMarkStep, from, to, this.mark, steps);\n                    for (let mark of node.marks)\n                        if (!mark.isInSet(added))\n                            pushMarkStep(AddMarkStep, from, to, mark, steps);\n                }\n            }\n        });\n        return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n    }\n    map(mapping) {\n        let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n        if (from >= to)\n            return null;\n        return new AddMarkStep(from, to, this.mark);\n    }\n    merge(other) {\n        if (other instanceof AddMarkStep &&\n            other.mark.eq(this.mark) &&\n            this.from <= other.to && this.to >= other.from)\n            return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n        return null;\n    }\n    toJSON() {\n        return { stepType: \"addMark\", mark: this.mark.toJSON(),\n            from: this.from, to: this.to };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\")\n            throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n        return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n    /**\n    Create a mark-removing step.\n    */\n    constructor(\n    /**\n    The start of the unmarked range.\n    */\n    from, \n    /**\n    The end of the unmarked range.\n    */\n    to, \n    /**\n    The mark to remove.\n    */\n    mark) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let oldSlice = doc.slice(this.from, this.to);\n        let slice = new Slice(mapFragment(oldSlice.content, node => {\n            return node.mark(this.mark.removeFromSet(node.marks));\n        }, doc), oldSlice.openStart, oldSlice.openEnd);\n        return StepResult.fromReplace(doc, this.from, this.to, slice);\n    }\n    invert(doc) {\n        let steps = [];\n        doc.nodesBetween(this.from, this.to, (node, pos) => {\n            if (node.isInline && node.isAtom && this.mark.isInSet(node.marks))\n                pushMarkStep(AddMarkStep, Math.max(this.from, pos), Math.min(this.to, pos + node.nodeSize), this.mark, steps);\n        });\n        return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n    }\n    map(mapping) {\n        let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n        if (from >= to)\n            return null;\n        return new RemoveMarkStep(from, to, this.mark);\n    }\n    merge(other) {\n        if (other instanceof RemoveMarkStep &&\n            other.mark.eq(this.mark) &&\n            this.from <= other.to && this.to >= other.from)\n            return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n        return null;\n    }\n    toJSON() {\n        return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n            from: this.from, to: this.to };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\")\n            throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n        return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\nfunction pushMarkStep(cls, from, to, mark, target) {\n    let last = target.length ? target[target.length - 1] : null;\n    if (last && last instanceof cls && last.to == from && last.mark.eq(mark)) {\n        target[target.length - 1] = new cls(last.from, to, mark);\n    }\n    else {\n        target.push(new cls(from, to, mark));\n    }\n}\nclass MarkSetStep extends Step {\n    constructor(steps) {\n        super();\n        this.steps = steps;\n    }\n    apply(doc) {\n        for (let step of this.steps) {\n            let result = step.apply(doc);\n            if (!result.doc)\n                return result;\n            doc = result.doc;\n        }\n        return new StepResult(doc, null);\n    }\n    invert(doc) {\n        return new MarkSetStep(this.steps.map(s => s.invert(doc)));\n    }\n    map(mapping) {\n        let result = [];\n        for (let step of this.steps) {\n            let mapped = step.map(mapping);\n            if (mapped)\n                result.push(mapped);\n        }\n        return result.length ? new MarkSetStep(result) : null;\n    }\n    toJSON() {\n        return { stepType: \"markSet\", steps: this.steps.map(s => s.toJSON()) };\n    }\n    static fromJSON(schema, json) {\n        if (!Array.isArray(json.steps) || !json.steps.every((s) => s.stepType == \"addMark\" || s.stepType == \"removeMark\"))\n            throw new RangeError(\"Invalid JSON for MarkSetStep\");\n        return new MarkSetStep(json.steps.map((s) => Step.fromJSON(schema, s)));\n    }\n}\nStep.jsonID(\"markSet\", MarkSetStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n    /**\n    Create a node mark step.\n    */\n    constructor(\n    /**\n    The position of the target node.\n    */\n    pos, \n    /**\n    The mark to add.\n    */\n    mark) {\n        super();\n        this.pos = pos;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node)\n            return StepResult.fail(\"No node at mark step's position\");\n        let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n        return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n    }\n    invert(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (node) {\n            let newSet = this.mark.addToSet(node.marks);\n            if (newSet.length == node.marks.length) {\n                for (let i = 0; i < node.marks.length; i++)\n                    if (!node.marks[i].isInSet(newSet))\n                        return new AddNodeMarkStep(this.pos, node.marks[i]);\n                return new AddNodeMarkStep(this.pos, this.mark);\n            }\n        }\n        return new RemoveNodeMarkStep(this.pos, this.mark);\n    }\n    map(mapping) {\n        let pos = mapping.mapResult(this.pos, 1);\n        return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n    }\n    toJSON() {\n        return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.pos != \"number\")\n            throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n        return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n    /**\n    Create a mark-removing step.\n    */\n    constructor(\n    /**\n    The position of the target node.\n    */\n    pos, \n    /**\n    The mark to remove.\n    */\n    mark) {\n        super();\n        this.pos = pos;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node)\n            return StepResult.fail(\"No node at mark step's position\");\n        let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n        return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n    }\n    invert(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node || !this.mark.isInSet(node.marks))\n            return this;\n        return new AddNodeMarkStep(this.pos, this.mark);\n    }\n    map(mapping) {\n        let pos = mapping.mapResult(this.pos, 1);\n        return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n    }\n    toJSON() {\n        return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.pos != \"number\")\n            throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n        return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n    /**\n    The given `slice` should fit the 'gap' between `from` and\n    `to`\u2014the depths must line up, and the surrounding nodes must be\n    able to be joined with the open sides of the slice. When\n    `structure` is true, the step will fail if the content between\n    from and to is not just a sequence of closing and then opening\n    tokens (this is to guard against rebased replace steps\n    overwriting something they weren't supposed to).\n    */\n    constructor(\n    /**\n    The start position of the replaced range.\n    */\n    from, \n    /**\n    The end position of the replaced range.\n    */\n    to, \n    /**\n    The slice to insert.\n    */\n    slice, \n    /**\n    @internal\n    */\n    structure = false) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.slice = slice;\n        this.structure = structure;\n    }\n    apply(doc) {\n        if (this.structure && contentBetween(doc, this.from, this.to))\n            return StepResult.fail(\"Structure replace would overwrite content\");\n        return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n    }\n    getMap() {\n        return new StepMap([this.from, this.to - this.from, this.slice.size]);\n    }\n    invert(doc) {\n        return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n    }\n    map(mapping) {\n        let to = mapping.mapResult(this.to, -1);\n        let from = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1);\n        if (from.deletedAcross && to.deletedAcross)\n            return null;\n        return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);\n    }\n    merge(other) {\n        if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n            return null;\n        if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n            let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n                : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n            return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n        }\n        else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n            let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n                : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n            return new ReplaceStep(other.from, this.to, slice, this.structure);\n        }\n        else {\n            return null;\n        }\n    }\n    toJSON() {\n        let json = { stepType: \"replace\", from: this.from, to: this.to };\n        if (this.slice.size)\n            json.slice = this.slice.toJSON();\n        if (this.structure)\n            json.structure = true;\n        return json;\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\")\n            throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n        return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n    }\n}\n/**\nBy default, for backwards compatibility, an inserting step\nmapped over an insertion at that same position fill move after\nthe inserted content. In a collaborative editing situation, that\ncan make redone insertions appear in unexpected places. You can\nset this to -1 to make such mapping keep the step before the\ninsertion instead.\n*/\nReplaceStep.MAP_BIAS = 1;\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n    /**\n    Create a replace-around step with the given range and gap.\n    `insert` should be the point in the slice into which the content\n    of the gap should be moved. `structure` has the same meaning as\n    it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n    */\n    constructor(\n    /**\n    The start position of the replaced range.\n    */\n    from, \n    /**\n    The end position of the replaced range.\n    */\n    to, \n    /**\n    The start of preserved range.\n    */\n    gapFrom, \n    /**\n    The end of preserved range.\n    */\n    gapTo, \n    /**\n    The slice to insert.\n    */\n    slice, \n    /**\n    The position in the slice where the preserved range should be\n    inserted.\n    */\n    insert, \n    /**\n    @internal\n    */\n    structure = false) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.gapFrom = gapFrom;\n        this.gapTo = gapTo;\n        this.slice = slice;\n        this.insert = insert;\n        this.structure = structure;\n    }\n    apply(doc) {\n        if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n            contentBetween(doc, this.gapTo, this.to)))\n            return StepResult.fail(\"Structure gap-replace would overwrite content\");\n        let gap = doc.slice(this.gapFrom, this.gapTo);\n        if (gap.openStart || gap.openEnd)\n            return StepResult.fail(\"Gap is not a flat range\");\n        let inserted = this.slice.insertAt(this.insert, gap.content);\n        if (!inserted)\n            return StepResult.fail(\"Content does not fit in gap\");\n        return StepResult.fromReplace(doc, this.from, this.to, inserted);\n    }\n    getMap() {\n        return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n            this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n    }\n    invert(doc) {\n        let gap = this.gapTo - this.gapFrom;\n        return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n    }\n    map(mapping) {\n        let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n        let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n        let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n        if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos || gapFrom > gapTo)\n            return null;\n        return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n    }\n    toJSON() {\n        let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n            gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n        if (this.slice.size)\n            json.slice = this.slice.toJSON();\n        if (this.structure)\n            json.structure = true;\n        return json;\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n            typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n            throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n        return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n    }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n    let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n    while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n        depth--;\n        dist--;\n    }\n    if (dist > 0) {\n        let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n        while (dist > 0) {\n            if (!next || next.isLeaf)\n                return true;\n            next = next.firstChild;\n            dist--;\n        }\n    }\n    return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n    let added = [];\n    tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n        if (!node.isInline)\n            return;\n        let marks = node.marks;\n        if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n            let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n            pushMarkStep(AddMarkStep, start, end, mark, added);\n        }\n    });\n    added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n    let matched = [], step = 0;\n    tr.doc.nodesBetween(from, to, (node, pos) => {\n        if (!node.isInline || !node.isAtom)\n            return;\n        step++;\n        let toRemove = null;\n        if (mark instanceof MarkType) {\n            let set = node.marks, found;\n            while (found = mark.isInSet(set)) {\n                (toRemove || (toRemove = [])).push(found);\n                set = found.removeFromSet(set);\n            }\n        }\n        else if (mark) {\n            if (mark.isInSet(node.marks))\n                toRemove = [mark];\n        }\n        else {\n            toRemove = node.marks;\n        }\n        if (toRemove && toRemove.length) {\n            let end = Math.min(pos + node.nodeSize, to);\n            for (let i = 0; i < toRemove.length; i++) {\n                let style = toRemove[i], found;\n                for (let j = 0; j < matched.length; j++) {\n                    let m = matched[j];\n                    if (m.step == step - 1 && style.eq(matched[j].style))\n                        found = m;\n                }\n                if (found) {\n                    found.to = end;\n                    found.step = step;\n                }\n                else {\n                    matched.push({ style, from: Math.max(pos, from), to: end, step });\n                }\n            }\n        }\n    });\n    matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n    let node = tr.doc.nodeAt(pos);\n    let replSteps = [], cur = pos + 1;\n    for (let i = 0; i < node.childCount; i++) {\n        let child = node.child(i), end = cur + child.nodeSize;\n        let allowed = match.matchType(child.type);\n        if (!allowed) {\n            replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n        }\n        else {\n            match = allowed;\n            for (let j = 0; j < child.marks.length; j++)\n                if (!parentType.allowsMarkType(child.marks[j].type))\n                    tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n            if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n                let m, newline = /\\r?\\n|\\r/g, slice;\n                while (m = newline.exec(child.text)) {\n                    if (!slice)\n                        slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n                    replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n                }\n            }\n        }\n        cur = end;\n    }\n    if (!match.validEnd) {\n        let fill = match.fillBefore(Fragment.empty, true);\n        tr.replace(cur, cur, new Slice(fill, 0, 0));\n    }\n    for (let i = replSteps.length - 1; i >= 0; i--)\n        tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n    return (start == 0 || node.canReplace(start, node.childCount)) &&\n        (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n    let parent = range.parent;\n    let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n    for (let depth = range.depth, contentBefore = 0, contentAfter = 0;; --depth) {\n        let node = range.$from.node(depth);\n        let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;\n        if (depth < range.depth && node.canReplace(index, endIndex, content))\n            return depth;\n        if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n            break;\n        if (index)\n            contentBefore = 1;\n        if (endIndex < node.childCount)\n            contentAfter = 1;\n    }\n    return null;\n}\nfunction lift(tr, range, target) {\n    let { $from, $to, depth } = range;\n    let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n    let start = gapStart, end = gapEnd;\n    let before = Fragment.empty, openStart = 0;\n    for (let d = depth, splitting = false; d > target; d--)\n        if (splitting || $from.index(d) > 0) {\n            splitting = true;\n            before = Fragment.from($from.node(d).copy(before));\n            openStart++;\n        }\n        else {\n            start--;\n        }\n    let after = Fragment.empty, openEnd = 0;\n    for (let d = depth, splitting = false; d > target; d--)\n        if (splitting || $to.after(d + 1) < $to.end(d)) {\n            splitting = true;\n            after = Fragment.from($to.node(d).copy(after));\n            openEnd++;\n        }\n        else {\n            end++;\n        }\n    tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n    let around = findWrappingOutside(range, nodeType);\n    let inner = around && findWrappingInside(innerRange, nodeType);\n    if (!inner)\n        return null;\n    return around.map(withAttrs)\n        .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n    let { parent, startIndex, endIndex } = range;\n    let around = parent.contentMatchAt(startIndex).findWrapping(type);\n    if (!around)\n        return null;\n    let outer = around.length ? around[0] : type;\n    return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n    let { parent, startIndex, endIndex } = range;\n    let inner = parent.child(startIndex);\n    let inside = type.contentMatch.findWrapping(inner.type);\n    if (!inside)\n        return null;\n    let lastType = inside.length ? inside[inside.length - 1] : type;\n    let innerMatch = lastType.contentMatch;\n    for (let i = startIndex; innerMatch && i < endIndex; i++)\n        innerMatch = innerMatch.matchType(parent.child(i).type);\n    if (!innerMatch || !innerMatch.validEnd)\n        return null;\n    return inside;\n}\nfunction wrap(tr, range, wrappers) {\n    let content = Fragment.empty;\n    for (let i = wrappers.length - 1; i >= 0; i--) {\n        if (content.size) {\n            let match = wrappers[i].type.contentMatch.matchFragment(content);\n            if (!match || !match.validEnd)\n                throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n        }\n        content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n    }\n    let start = range.start, end = range.end;\n    tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n    if (!type.isTextblock)\n        throw new RangeError(\"Type given to setBlockType should be a textblock\");\n    let mapFrom = tr.steps.length;\n    tr.doc.nodesBetween(from, to, (node, pos) => {\n        let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n        if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n            canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n            let convertNewlines = null;\n            if (type.schema.linebreakReplacement) {\n                let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n                if (pre && !supportLinebreak)\n                    convertNewlines = false;\n                else if (!pre && supportLinebreak)\n                    convertNewlines = true;\n            }\n            // Ensure all markup that isn't allowed in the new node type is cleared\n            if (convertNewlines === false)\n                replaceLinebreaks(tr, node, pos, mapFrom);\n            clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n            let mapping = tr.mapping.slice(mapFrom);\n            let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n            tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n            if (convertNewlines === true)\n                replaceNewlines(tr, node, pos, mapFrom);\n            return false;\n        }\n    });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n    node.forEach((child, offset) => {\n        if (child.isText) {\n            let m, newline = /\\r?\\n|\\r/g;\n            while (m = newline.exec(child.text)) {\n                let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n                tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n            }\n        }\n    });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n    node.forEach((child, offset) => {\n        if (child.type == child.type.schema.linebreakReplacement) {\n            let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n            tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n        }\n    });\n}\nfunction canChangeType(doc, pos, type) {\n    let $pos = doc.resolve(pos), index = $pos.index();\n    return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n    let node = tr.doc.nodeAt(pos);\n    if (!node)\n        throw new RangeError(\"No node at given position\");\n    if (!type)\n        type = node.type;\n    let newNode = type.create(attrs, null, marks || node.marks);\n    if (node.isLeaf)\n        return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n    if (!type.validContent(node.content))\n        throw new RangeError(\"Invalid content for node type \" + type.name);\n    tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n    let $pos = doc.resolve(pos), base = $pos.depth - depth;\n    let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n    if (base < 0 || $pos.parent.type.spec.isolating ||\n        !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n        !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n        return false;\n    for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n        let node = $pos.node(d), index = $pos.index(d);\n        if (node.type.spec.isolating)\n            return false;\n        let rest = node.content.cutByIndex(index, node.childCount);\n        let overrideChild = typesAfter && typesAfter[i + 1];\n        if (overrideChild)\n            rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n        let after = (typesAfter && typesAfter[i]) || node;\n        if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n            return false;\n    }\n    let index = $pos.indexAfter(base);\n    let baseType = typesAfter && typesAfter[0];\n    return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n    let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n    for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n        before = Fragment.from($pos.node(d).copy(before));\n        let typeAfter = typesAfter && typesAfter[i];\n        after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n    }\n    tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n    let $pos = doc.resolve(pos), index = $pos.index();\n    return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n        $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n    if (!b.content.size)\n        a.type.compatibleContent(b.type);\n    let match = a.contentMatchAt(a.childCount);\n    let { linebreakReplacement } = a.type.schema;\n    for (let i = 0; i < b.childCount; i++) {\n        let child = b.child(i);\n        let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n        match = match.matchType(type);\n        if (!match)\n            return false;\n        if (!a.type.allowsMarks(child.marks))\n            return false;\n    }\n    return match.validEnd;\n}\nfunction joinable(a, b) {\n    return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n    let $pos = doc.resolve(pos);\n    for (let d = $pos.depth;; d--) {\n        let before, after, index = $pos.index(d);\n        if (d == $pos.depth) {\n            before = $pos.nodeBefore;\n            after = $pos.nodeAfter;\n        }\n        else if (dir > 0) {\n            before = $pos.node(d + 1);\n            index++;\n            after = $pos.node(d).maybeChild(index);\n        }\n        else {\n            before = $pos.node(d).maybeChild(index - 1);\n            after = $pos.node(d + 1);\n        }\n        if (before && !before.isTextblock && joinable(before, after) &&\n            $pos.node(d).canReplace(index, index + 1))\n            return pos;\n        if (d == 0)\n            break;\n        pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n    }\n}\nfunction join(tr, pos, depth) {\n    let convertNewlines = null;\n    let { linebreakReplacement } = tr.doc.type.schema;\n    let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n    if (linebreakReplacement && beforeType.inlineContent) {\n        let pre = beforeType.whitespace == \"pre\";\n        let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n        if (pre && !supportLinebreak)\n            convertNewlines = false;\n        else if (!pre && supportLinebreak)\n            convertNewlines = true;\n    }\n    let mapFrom = tr.steps.length;\n    if (convertNewlines === false) {\n        let $after = tr.doc.resolve(pos + depth);\n        replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n    }\n    if (beforeType.inlineContent)\n        clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n    let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n    tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n    if (convertNewlines === true) {\n        let $full = tr.doc.resolve(start);\n        replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n    }\n    return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n    let $pos = doc.resolve(pos);\n    if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n        return pos;\n    if ($pos.parentOffset == 0)\n        for (let d = $pos.depth - 1; d >= 0; d--) {\n            let index = $pos.index(d);\n            if ($pos.node(d).canReplaceWith(index, index, nodeType))\n                return $pos.before(d + 1);\n            if (index > 0)\n                return null;\n        }\n    if ($pos.parentOffset == $pos.parent.content.size)\n        for (let d = $pos.depth - 1; d >= 0; d--) {\n            let index = $pos.indexAfter(d);\n            if ($pos.node(d).canReplaceWith(index, index, nodeType))\n                return $pos.after(d + 1);\n            if (index < $pos.node(d).childCount)\n                return null;\n        }\n    return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n    let $pos = doc.resolve(pos);\n    if (!slice.content.size)\n        return pos;\n    let content = slice.content;\n    for (let i = 0; i < slice.openStart; i++)\n        content = content.firstChild.content;\n    for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n        for (let d = $pos.depth; d >= 0; d--) {\n            let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n            let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n            let parent = $pos.node(d), fits = false;\n            if (pass == 1) {\n                fits = parent.canReplace(insertPos, insertPos, content);\n            }\n            else {\n                let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n                fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n            }\n            if (fits)\n                return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n        }\n    }\n    return null;\n}\n\n/**\n\u2018Fit\u2019 a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n    if (from == to && !slice.size)\n        return null;\n    let $from = doc.resolve(from), $to = doc.resolve(to);\n    // Optimization -- avoid work if it's obvious that it's not needed.\n    if (fitsTrivially($from, $to, slice))\n        return new ReplaceStep(from, to, slice);\n    return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n    return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n        $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in <p(\"foo\"), p(\"bar\")>, when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n//  - `frontier` holds a stack of `{type, match}` objects that\n//    represent the open side of the replacement. It starts at\n//    `$from`, then moves forward as content is placed, and is finally\n//    reconciled with `$to`.\n//\n//  - `unplaced` is a slice that represents the content that hasn't\n//    been placed yet.\n//\n//  - `placed` is a fragment of placed content. Its open-start value\n//    is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n    constructor($from, $to, unplaced) {\n        this.$from = $from;\n        this.$to = $to;\n        this.unplaced = unplaced;\n        this.frontier = [];\n        this.placed = Fragment.empty;\n        for (let i = 0; i <= $from.depth; i++) {\n            let node = $from.node(i);\n            this.frontier.push({\n                type: node.type,\n                match: node.contentMatchAt($from.indexAfter(i))\n            });\n        }\n        for (let i = $from.depth; i > 0; i--)\n            this.placed = Fragment.from($from.node(i).copy(this.placed));\n    }\n    get depth() { return this.frontier.length - 1; }\n    fit() {\n        // As long as there's unplaced content, try to place some of it.\n        // If that fails, either increase the open score of the unplaced\n        // slice, or drop nodes from it, and then try again.\n        while (this.unplaced.size) {\n            let fit = this.findFittable();\n            if (fit)\n                this.placeNodes(fit);\n            else\n                this.openMore() || this.dropNode();\n        }\n        // When there's inline content directly after the frontier _and_\n        // directly after `this.$to`, we must generate a `ReplaceAround`\n        // step that pulls that content into the node after the frontier.\n        // That means the fitting must be done to the end of the textblock\n        // node after `this.$to`, not `this.$to` itself.\n        let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n        let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n        if (!$to)\n            return null;\n        // If closing to `$to` succeeded, create a step\n        let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n        while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n            content = content.firstChild.content;\n            openStart--;\n            openEnd--;\n        }\n        let slice = new Slice(content, openStart, openEnd);\n        if (moveInline > -1)\n            return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n        if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n            return new ReplaceStep($from.pos, $to.pos, slice);\n        return null;\n    }\n    // Find a position on the start spine of `this.unplaced` that has\n    // content that can be moved somewhere on the frontier. Returns two\n    // depths, one for the slice and one for the frontier.\n    findFittable() {\n        let startDepth = this.unplaced.openStart;\n        for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n            let node = cur.firstChild;\n            if (cur.childCount > 1)\n                openEnd = 0;\n            if (node.type.spec.isolating && openEnd <= d) {\n                startDepth = d;\n                break;\n            }\n            cur = node.content;\n        }\n        // Only try wrapping nodes (pass 2) after finding a place without\n        // wrapping failed.\n        for (let pass = 1; pass <= 2; pass++) {\n            for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n                let fragment, parent = null;\n                if (sliceDepth) {\n                    parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n                    fragment = parent.content;\n                }\n                else {\n                    fragment = this.unplaced.content;\n                }\n                let first = fragment.firstChild;\n                for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n                    let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n                    // In pass 1, if the next node matches, or there is no next\n                    // node but the parents look compatible, we've found a\n                    // place.\n                    if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n                        : parent && type.compatibleContent(parent.type)))\n                        return { sliceDepth, frontierDepth, parent, inject };\n                    // In pass 2, look for a set of wrapping nodes that make\n                    // `first` fit here.\n                    else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n                        return { sliceDepth, frontierDepth, parent, wrap };\n                    // Don't continue looking further up if the parent node\n                    // would fit here.\n                    if (parent && match.matchType(parent.type))\n                        break;\n                }\n            }\n        }\n    }\n    openMore() {\n        let { content, openStart, openEnd } = this.unplaced;\n        if (maxOpen(content, -1) <= openStart)\n            return false;\n        if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd)\n            openEnd++;\n        this.unplaced = new Slice(content, openStart + 1, openEnd);\n        return true;\n    }\n    dropNode() {\n        let { content, openStart, openEnd } = this.unplaced;\n        let inner = contentAt(content, openStart);\n        if (inner.childCount <= 1 && openStart > 0) {\n            let openAtEnd = content.size - openStart <= openStart + inner.size;\n            this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n        }\n        else {\n            this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n        }\n    }\n    // Move content from the unplaced slice at `sliceDepth` to the\n    // frontier node at `frontierDepth`. Close that frontier node when\n    // applicable.\n    placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n        while (this.depth > frontierDepth)\n            this.closeFrontierNode();\n        if (wrap)\n            for (let i = 0; i < wrap.length; i++)\n                this.openFrontierNode(wrap[i]);\n        let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n        let openStart = slice.openStart - sliceDepth;\n        let taken = 0, add = [];\n        let { match, type } = this.frontier[frontierDepth];\n        if (inject) {\n            for (let i = 0; i < inject.childCount; i++)\n                add.push(inject.child(i));\n            match = match.matchFragment(inject);\n        }\n        // Computes the amount of (end) open nodes at the end of the\n        // fragment. When 0, the parent is open, but no more. When\n        // negative, nothing is open.\n        let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n        // Scan over the fragment, fitting as many child nodes as\n        // possible.\n        while (taken < fragment.childCount) {\n            let next = fragment.child(taken), matches = match.matchType(next.type);\n            if (!matches)\n                break;\n            taken++;\n            if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n                match = matches;\n                add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n            }\n        }\n        let toEnd = taken == fragment.childCount;\n        if (!toEnd)\n            openEndCount = -1;\n        this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n        this.frontier[frontierDepth].match = match;\n        // If the parent types match, and the entire node was moved, and\n        // it's not open, close this frontier node right away.\n        if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n            this.closeFrontierNode();\n        // Add new frontier nodes for any open nodes at the end.\n        for (let i = 0, cur = add[add.length - 1]; cur && i < openEndCount; i++) {\n            this.frontier.push({ type: cur.type, match: cur.contentMatchAt(cur.childCount) });\n            cur = cur.lastChild;\n        }\n        // Update `this.unplaced`. Drop the entire node from which we\n        // placed it we got to its end, otherwise just drop the placed\n        // nodes.\n        this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), sliceDepth, slice.openEnd)\n            : sliceDepth == 0 ? Slice.empty\n                : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n    }\n    mustMoveInline() {\n        if (!this.$to.parent.isTextblock)\n            return -1;\n        let top = this.frontier[this.depth], level;\n        if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n            (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n            return -1;\n        let { depth } = this.$to, after = this.$to.after(depth);\n        while (depth > 1 && after == this.$to.end(--depth))\n            ++after;\n        return after;\n    }\n    findCloseLevel($to) {\n        scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n            let { match, type } = this.frontier[i];\n            let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n            let fit = contentAfterFits($to, i, type, match, dropInner);\n            if (!fit)\n                continue;\n            for (let d = i - 1; d >= 0; d--) {\n                let { match, type } = this.frontier[d];\n                let matches = contentAfterFits($to, d, type, match, true);\n                if (!matches || matches.childCount)\n                    continue scan;\n            }\n            return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n        }\n    }\n    close($to) {\n        let close = this.findCloseLevel($to);\n        if (!close)\n            return null;\n        while (this.depth > close.depth)\n            this.closeFrontierNode();\n        if (close.fit.childCount)\n            this.placed = addToFragment(this.placed, close.depth, close.fit);\n        $to = close.move;\n        for (let d = close.depth + 1; d <= $to.depth; d++) {\n            let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n            this.openFrontierNode(node.type, node.attrs, add);\n        }\n        return $to;\n    }\n    openFrontierNode(type, attrs = null, content) {\n        let top = this.frontier[this.depth];\n        top.match = top.match.matchType(type);\n        this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n        this.frontier.push({ type, match: type.contentMatch });\n    }\n    closeFrontierNode() {\n        let open = this.frontier.pop();\n        let add = open.match.fillBefore(Fragment.empty, true);\n        if (add.childCount)\n            this.placed = addToFragment(this.placed, this.frontier.length, add);\n    }\n}\nfunction dropFromFragment(fragment, depth, count) {\n    if (depth == 0)\n        return fragment.cutByIndex(count, fragment.childCount);\n    return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n    if (depth == 0)\n        return fragment.append(content);\n    return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n    for (let i = 0; i < depth; i++)\n        fragment = fragment.firstChild.content;\n    return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n    if (openStart <= 0)\n        return node;\n    let frag = node.content;\n    if (openStart > 1)\n        frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n    if (openStart > 0) {\n        frag = node.type.contentMatch.fillBefore(frag).append(frag);\n        if (openEnd <= 0)\n            frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n    }\n    return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n    let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n    if (index == node.childCount && !type.compatibleContent(node.type))\n        return null;\n    let fit = match.fillBefore(node.content, true, index);\n    return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n    for (let i = start; i < fragment.childCount; i++)\n        if (!type.allowsMarks(fragment.child(i).marks))\n            return true;\n    return false;\n}\nfunction definesContent(type) {\n    return type.spec.defining || type.spec.definingForContent;\n}\nfunction maxOpen(frag, side) {\n    for (let count = 0;; count++) {\n        let ch = side < 0 ? frag.firstChild : frag.lastChild;\n        if (!ch || ch.isAtom)\n            return count;\n        frag = ch.content;\n    }\n}\nfunction replaceRange(tr, from, to, slice) {\n    if (!slice.size)\n        return tr.deleteRange(from, to);\n    let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n    if (fitsTrivially($from, $to, slice))\n        return tr.step(new ReplaceStep(from, to, slice));\n    let targetDepths = coveredDepths($from, $to);\n    // Can't replace the whole document, so remove 0 if it's present\n    if (targetDepths[targetDepths.length - 1] == 0)\n        targetDepths.pop();\n    // Negative numbers represent not expansion over the whole node at\n    // that depth, but replacing from $from.before(-D) to $to.pos.\n    let preferredTarget = -($from.depth + 1);\n    targetDepths.unshift(preferredTarget);\n    // This loop picks a preferred target depth, if one of the covering\n    // depths is not outside of a defining node, and adds negative\n    // depths for any depth that has $from at its start and does not\n    // cross a defining node.\n    for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n        let spec = $from.node(d).type.spec;\n        if (spec.defining || spec.definingAsContext || spec.isolating)\n            break;\n        if (targetDepths.indexOf(d) > -1)\n            preferredTarget = d;\n        else if ($from.before(d) == pos)\n            targetDepths.splice(1, 0, -d);\n    }\n    // Try to fit each possible depth of the slice into each possible\n    // target depth, starting with the preferred depths.\n    let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n    let leftNodes = [], preferredDepth = slice.openStart;\n    for (let content = slice.content, i = 0;; i++) {\n        let node = content.firstChild;\n        leftNodes.push(node);\n        if (i == slice.openStart)\n            break;\n        content = node.content;\n    }\n    // Back up preferredDepth to cover defining textblocks directly\n    // above it, possibly skipping a non-defining textblock.\n    for (let d = preferredDepth - 1; d >= 0; d--) {\n        let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n        if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n            preferredDepth = d;\n        else if (def || !leftNode.type.isTextblock)\n            break;\n    }\n    for (let j = slice.openStart; j >= 0; j--) {\n        let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n        let insert = leftNodes[openDepth];\n        if (!insert)\n            continue;\n        for (let i = 0; i < targetDepths.length; i++) {\n            // Loop over possible expansion levels, starting with the\n            // preferred one\n            let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n            if (targetDepth < 0) {\n                expand = false;\n                targetDepth = -targetDepth;\n            }\n            let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n            if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n                return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n        }\n    }\n    let startSteps = tr.steps.length;\n    for (let i = targetDepths.length - 1; i >= 0; i--) {\n        tr.replace(from, to, slice);\n        if (tr.steps.length > startSteps)\n            break;\n        let depth = targetDepths[i];\n        if (depth < 0)\n            continue;\n        from = $from.before(depth);\n        to = $to.after(depth);\n    }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n    if (depth < oldOpen) {\n        let first = fragment.firstChild;\n        fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n    }\n    if (depth > newOpen) {\n        let match = parent.contentMatchAt(0);\n        let start = match.fillBefore(fragment).append(fragment);\n        fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n    }\n    return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n    if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n        let point = insertPoint(tr.doc, from, node.type);\n        if (point != null)\n            from = to = point;\n    }\n    tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n    let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n    // When the deleted range spans from the start of one textblock to\n    // the start of another one, move out of the start of both blocks.\n    if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() &&\n        $from.parentOffset == 0 && $to.parentOffset == 0) {\n        let shared = $from.sharedDepth(to), isolated = false;\n        for (let d = $from.depth; d > shared; d--)\n            if ($from.node(d).type.spec.isolating)\n                isolated = true;\n        for (let d = $to.depth; d > shared; d--)\n            if ($to.node(d).type.spec.isolating)\n                isolated = true;\n        if (!isolated) {\n            for (let d = $from.depth; d > 0 && from == $from.start(d); d--)\n                from = $from.before(d);\n            for (let d = $to.depth; d > 0 && to == $to.start(d); d--)\n                to = $to.before(d);\n            $from = tr.doc.resolve(from);\n            $to = tr.doc.resolve(to);\n        }\n    }\n    let covered = coveredDepths($from, $to);\n    for (let i = 0; i < covered.length; i++) {\n        let depth = covered[i], last = i == covered.length - 1;\n        if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n            return tr.delete($from.start(depth), $to.end(depth));\n        if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n            return tr.delete($from.before(depth), $to.after(depth));\n    }\n    for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n        if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n            $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n            return tr.delete($from.before(d), to);\n    }\n    tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n    let result = [], minDepth = Math.min($from.depth, $to.depth);\n    for (let d = minDepth; d >= 0; d--) {\n        let start = $from.start(d);\n        if (start < $from.pos - ($from.depth - d) ||\n            $to.end(d) > $to.pos + ($to.depth - d) ||\n            $from.node(d).type.spec.isolating ||\n            $to.node(d).type.spec.isolating)\n            break;\n        if (start == $to.start(d) ||\n            (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n                d && $to.start(d - 1) == start - 1))\n            result.push(d);\n    }\n    return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n    /**\n    Construct an attribute step.\n    */\n    constructor(\n    /**\n    The position of the target node.\n    */\n    pos, \n    /**\n    The attribute to set.\n    */\n    attr, \n    // The attribute's new value.\n    value) {\n        super();\n        this.pos = pos;\n        this.attr = attr;\n        this.value = value;\n    }\n    apply(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node)\n            return StepResult.fail(\"No node at attribute step's position\");\n        let attrs = Object.create(null);\n        for (let name in node.attrs)\n            attrs[name] = node.attrs[name];\n        attrs[this.attr] = this.value;\n        let updated = node.type.create(attrs, null, node.marks);\n        return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n    }\n    getMap() {\n        return StepMap.empty;\n    }\n    invert(doc) {\n        return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n    }\n    map(mapping) {\n        let pos = mapping.mapResult(this.pos, 1);\n        return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n    }\n    toJSON() {\n        return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n    }\n    static fromJSON(schema, json) {\n        if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n            throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n        return new AttrStep(json.pos, json.attr, json.value);\n    }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n    /**\n    Construct an attribute step.\n    */\n    constructor(\n    /**\n    The attribute to set.\n    */\n    attr, \n    // The attribute's new value.\n    value) {\n        super();\n        this.attr = attr;\n        this.value = value;\n    }\n    apply(doc) {\n        let attrs = Object.create(null);\n        for (let name in doc.attrs)\n            attrs[name] = doc.attrs[name];\n        attrs[this.attr] = this.value;\n        let updated = doc.type.create(attrs, doc.content, doc.marks);\n        return StepResult.ok(updated);\n    }\n    getMap() {\n        return StepMap.empty;\n    }\n    invert(doc) {\n        return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n    }\n    map(mapping) {\n        return this;\n    }\n    toJSON() {\n        return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n    }\n    static fromJSON(schema, json) {\n        if (typeof json.attr != \"string\")\n            throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n        return new DocAttrStep(json.attr, json.value);\n    }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n    let err = Error.call(this, message);\n    err.__proto__ = TransformError.prototype;\n    return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n    /**\n    Create a transform that starts with the given document.\n    */\n    constructor(\n    /**\n    The current document (the result of applying the steps in the\n    transform).\n    */\n    doc) {\n        this.doc = doc;\n        /**\n        The steps in this transform.\n        */\n        this.steps = [];\n        /**\n        The documents before each of the steps.\n        */\n        this.docs = [];\n        /**\n        A mapping with the maps for each of the steps in this transform.\n        */\n        this.mapping = new Mapping;\n    }\n    /**\n    The starting document.\n    */\n    get before() { return this.docs.length ? this.docs[0] : this.doc; }\n    /**\n    Apply a new step in this transform, saving the result. Throws an\n    error when the step fails.\n    */\n    step(step) {\n        let result = this.maybeStep(step);\n        if (result.failed)\n            throw new TransformError(result.failed);\n        return this;\n    }\n    /**\n    Try to apply a step in this transformation, ignoring it if it\n    fails. Returns the step result.\n    */\n    maybeStep(step) {\n        let result = step.apply(this.doc);\n        if (!result.failed)\n            this.addStep(step, result.doc);\n        return result;\n    }\n    /**\n    True when the document has been changed (when there are any\n    steps).\n    */\n    get docChanged() {\n        return this.steps.length > 0;\n    }\n    /**\n    Return a single range, in post-transform document positions,\n    that covers all content changed by this transform. Returns null\n    if no replacements are made. Note that this will ignore changes\n    that add/remove marks without replacing the underlying content.\n    */\n    changedRange() {\n        let from = 1e9, to = -1e9;\n        for (let i = 0; i < this.mapping.maps.length; i++) {\n            let map = this.mapping.maps[i];\n            if (i) {\n                from = map.map(from, 1);\n                to = map.map(to, -1);\n            }\n            map.forEach((_f, _t, fromB, toB) => {\n                from = Math.min(from, fromB);\n                to = Math.max(to, toB);\n            });\n        }\n        return from == 1e9 ? null : { from, to };\n    }\n    /**\n    @internal\n    */\n    addStep(step, doc) {\n        this.docs.push(this.doc);\n        this.steps.push(step);\n        this.mapping.appendMap(step.getMap());\n        this.doc = doc;\n    }\n    /**\n    Replace the part of the document between `from` and `to` with the\n    given `slice`.\n    */\n    replace(from, to = from, slice = Slice.empty) {\n        let step = replaceStep(this.doc, from, to, slice);\n        if (step)\n            this.step(step);\n        return this;\n    }\n    /**\n    Replace the given range with the given content, which may be a\n    fragment, node, or array of nodes.\n    */\n    replaceWith(from, to, content) {\n        return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n    }\n    /**\n    Delete the content between the given positions.\n    */\n    delete(from, to) {\n        return this.replace(from, to, Slice.empty);\n    }\n    /**\n    Insert the given content at the given position.\n    */\n    insert(pos, content) {\n        return this.replaceWith(pos, pos, content);\n    }\n    /**\n    Replace a range of the document with a given slice, using\n    `from`, `to`, and the slice's\n    [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n    than fixed start and end points. This method may grow the\n    replaced area or close open nodes in the slice in order to get a\n    fit that is more in line with WYSIWYG expectations, by dropping\n    fully covered parent nodes of the replaced region when they are\n    marked [non-defining as\n    context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n    open parent node from the slice that _is_ marked as [defining\n    its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n    \n    This is the method, for example, to handle paste. The similar\n    [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n    primitive tool which will _not_ move the start and end of its given\n    range, and is useful in situations where you need more precise\n    control over what happens.\n    */\n    replaceRange(from, to, slice) {\n        replaceRange(this, from, to, slice);\n        return this;\n    }\n    /**\n    Replace the given range with a node, but use `from` and `to` as\n    hints, rather than precise positions. When from and to are the same\n    and are at the start or end of a parent node in which the given\n    node doesn't fit, this method may _move_ them out towards a parent\n    that does allow the given node to be placed. When the given range\n    completely covers a parent node, this method may completely replace\n    that parent node.\n    */\n    replaceRangeWith(from, to, node) {\n        replaceRangeWith(this, from, to, node);\n        return this;\n    }\n    /**\n    Delete the given range, expanding it to cover fully covered\n    parent nodes until a valid replace is found.\n    */\n    deleteRange(from, to) {\n        deleteRange(this, from, to);\n        return this;\n    }\n    /**\n    Split the content in the given range off from its parent, if there\n    is sibling content before or after it, and move it up the tree to\n    the depth specified by `target`. You'll probably want to use\n    [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n    sure the lift is valid.\n    */\n    lift(range, target) {\n        lift(this, range, target);\n        return this;\n    }\n    /**\n    Join the blocks around the given position. If depth is 2, their\n    last and first siblings are also joined, and so on.\n    */\n    join(pos, depth = 1) {\n        join(this, pos, depth);\n        return this;\n    }\n    /**\n    Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n    The wrappers are assumed to be valid in this position, and should\n    probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n    */\n    wrap(range, wrappers) {\n        wrap(this, range, wrappers);\n        return this;\n    }\n    /**\n    Set the type of all textblocks (partly) between `from` and `to` to\n    the given node type with the given attributes.\n    */\n    setBlockType(from, to = from, type, attrs = null) {\n        setBlockType(this, from, to, type, attrs);\n        return this;\n    }\n    /**\n    Change the type, attributes, and/or marks of the node at `pos`.\n    When `type` isn't given, the existing node type is preserved,\n    */\n    setNodeMarkup(pos, type, attrs = null, marks) {\n        setNodeMarkup(this, pos, type, attrs, marks);\n        return this;\n    }\n    /**\n    Set a single attribute on a given node to a new value.\n    The `pos` addresses the document content. Use `setDocAttribute`\n    to set attributes on the document itself.\n    */\n    setNodeAttribute(pos, attr, value) {\n        this.step(new AttrStep(pos, attr, value));\n        return this;\n    }\n    /**\n    Set a single attribute on the document to a new value.\n    */\n    setDocAttribute(attr, value) {\n        this.step(new DocAttrStep(attr, value));\n        return this;\n    }\n    /**\n    Add a mark to the node at position `pos`.\n    */\n    addNodeMark(pos, mark) {\n        this.step(new AddNodeMarkStep(pos, mark));\n        return this;\n    }\n    /**\n    Remove a mark (or all marks of the given type) from the node at\n    position `pos`.\n    */\n    removeNodeMark(pos, mark) {\n        let node = this.doc.nodeAt(pos);\n        if (!node)\n            throw new RangeError(\"No node at position \" + pos);\n        if (mark instanceof Mark) {\n            if (mark.isInSet(node.marks))\n                this.step(new RemoveNodeMarkStep(pos, mark));\n        }\n        else {\n            let set = node.marks, found, steps = [];\n            while (found = mark.isInSet(set)) {\n                steps.push(new RemoveNodeMarkStep(pos, found));\n                set = found.removeFromSet(set);\n            }\n            for (let i = steps.length - 1; i >= 0; i--)\n                this.step(steps[i]);\n        }\n        return this;\n    }\n    /**\n    Split the node at the given position, and optionally, if `depth` is\n    greater than one, any number of nodes above that. By default, the\n    parts split off will inherit the node type of the original node.\n    This can be changed by passing an array of types and attributes to\n    use after the split (with the outermost nodes coming first).\n    */\n    split(pos, depth = 1, typesAfter) {\n        split(this, pos, depth, typesAfter);\n        return this;\n    }\n    /**\n    Add the given mark to the inline content between `from` and `to`.\n    */\n    addMark(from, to, mark) {\n        addMark(this, from, to, mark);\n        return this;\n    }\n    /**\n    Remove marks from inline nodes between `from` and `to`. When\n    `mark` is a single mark, remove precisely that mark. When it is\n    a mark type, remove all marks of that type. When it is null,\n    remove all marks of any type.\n    */\n    removeMark(from, to, mark) {\n        removeMark(this, from, to, mark);\n        return this;\n    }\n    /**\n    Removes all marks and nodes from the content of the node at\n    `pos` that don't match the given new parent node type. Accepts\n    an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n    third argument.\n    */\n    clearIncompatible(pos, parentType, match) {\n        clearIncompatible(this, pos, parentType, match);\n        return this;\n    }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n", "import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n    /**\n    Initialize a selection with the head and anchor and ranges. If no\n    ranges are given, constructs a single range across `$anchor` and\n    `$head`.\n    */\n    constructor(\n    /**\n    The resolved anchor of the selection (the side that stays in\n    place when the selection is modified).\n    */\n    $anchor, \n    /**\n    The resolved head of the selection (the side that moves when\n    the selection is modified).\n    */\n    $head, ranges) {\n        this.$anchor = $anchor;\n        this.$head = $head;\n        this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n    }\n    /**\n    The selection's anchor, as an unresolved position.\n    */\n    get anchor() { return this.$anchor.pos; }\n    /**\n    The selection's head.\n    */\n    get head() { return this.$head.pos; }\n    /**\n    The lower bound of the selection's main range.\n    */\n    get from() { return this.$from.pos; }\n    /**\n    The upper bound of the selection's main range.\n    */\n    get to() { return this.$to.pos; }\n    /**\n    The resolved lower  bound of the selection's main range.\n    */\n    get $from() {\n        return this.ranges[0].$from;\n    }\n    /**\n    The resolved upper bound of the selection's main range.\n    */\n    get $to() {\n        return this.ranges[0].$to;\n    }\n    /**\n    Indicates whether the selection contains any content.\n    */\n    get empty() {\n        let ranges = this.ranges;\n        for (let i = 0; i < ranges.length; i++)\n            if (ranges[i].$from.pos != ranges[i].$to.pos)\n                return false;\n        return true;\n    }\n    /**\n    Get the content of this selection as a slice.\n    */\n    content() {\n        return this.$from.doc.slice(this.from, this.to, true);\n    }\n    /**\n    Replace the selection with a slice or, if no slice is given,\n    delete the selection. Will append to the given transaction.\n    */\n    replace(tr, content = Slice.empty) {\n        // Put the new selection at the position after the inserted\n        // content. When that ended in an inline node, search backwards,\n        // to get the position after that node. If not, search forward.\n        let lastNode = content.content.lastChild, lastParent = null;\n        for (let i = 0; i < content.openEnd; i++) {\n            lastParent = lastNode;\n            lastNode = lastNode.lastChild;\n        }\n        let mapFrom = tr.steps.length, ranges = this.ranges;\n        for (let i = 0; i < ranges.length; i++) {\n            let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n            tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n            if (i == 0)\n                selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n        }\n    }\n    /**\n    Replace the selection with the given node, appending the changes\n    to the given transaction.\n    */\n    replaceWith(tr, node) {\n        let mapFrom = tr.steps.length, ranges = this.ranges;\n        for (let i = 0; i < ranges.length; i++) {\n            let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n            let from = mapping.map($from.pos), to = mapping.map($to.pos);\n            if (i) {\n                tr.deleteRange(from, to);\n            }\n            else {\n                tr.replaceRangeWith(from, to, node);\n                selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n            }\n        }\n    }\n    /**\n    Find a valid cursor or leaf node selection starting at the given\n    position and searching back if `dir` is negative, and forward if\n    positive. When `textOnly` is true, only consider cursor\n    selections. Will return null when no valid selection position is\n    found.\n    */\n    static findFrom($pos, dir, textOnly = false) {\n        let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n            : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n        if (inner)\n            return inner;\n        for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n            let found = dir < 0\n                ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n                : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n            if (found)\n                return found;\n        }\n        return null;\n    }\n    /**\n    Find a valid cursor or leaf node selection near the given\n    position. Searches forward first by default, but if `bias` is\n    negative, it will search backwards first.\n    */\n    static near($pos, bias = 1) {\n        return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n    }\n    /**\n    Find the cursor or leaf node selection closest to the start of\n    the given document. Will return an\n    [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n    exists.\n    */\n    static atStart(doc) {\n        return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n    }\n    /**\n    Find the cursor or leaf node selection closest to the end of the\n    given document.\n    */\n    static atEnd(doc) {\n        return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n    }\n    /**\n    Deserialize the JSON representation of a selection. Must be\n    implemented for custom classes (as a static class method).\n    */\n    static fromJSON(doc, json) {\n        if (!json || !json.type)\n            throw new RangeError(\"Invalid input for Selection.fromJSON\");\n        let cls = classesById[json.type];\n        if (!cls)\n            throw new RangeError(`No selection type ${json.type} defined`);\n        return cls.fromJSON(doc, json);\n    }\n    /**\n    To be able to deserialize selections from JSON, custom selection\n    classes must register themselves with an ID string, so that they\n    can be disambiguated. Try to pick something that's unlikely to\n    clash with classes from other modules.\n    */\n    static jsonID(id, selectionClass) {\n        if (id in classesById)\n            throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n        classesById[id] = selectionClass;\n        selectionClass.prototype.jsonID = id;\n        return selectionClass;\n    }\n    /**\n    Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n    which is a value that can be mapped without having access to a\n    current document, and later resolved to a real selection for a\n    given document again. (This is used mostly by the history to\n    track and restore old selections.) The default implementation of\n    this method just converts the selection to a text selection and\n    returns the bookmark for that.\n    */\n    getBookmark() {\n        return TextSelection.between(this.$anchor, this.$head).getBookmark();\n    }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n    /**\n    Create a range.\n    */\n    constructor(\n    /**\n    The lower bound of the range.\n    */\n    $from, \n    /**\n    The upper bound of the range.\n    */\n    $to) {\n        this.$from = $from;\n        this.$to = $to;\n    }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n    if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n        warnedAboutTextSelection = true;\n        console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n    }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n    /**\n    Construct a text selection between the given points.\n    */\n    constructor($anchor, $head = $anchor) {\n        checkTextSelection($anchor);\n        checkTextSelection($head);\n        super($anchor, $head);\n    }\n    /**\n    Returns a resolved position if this is a cursor selection (an\n    empty text selection), and null otherwise.\n    */\n    get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n    map(doc, mapping) {\n        let $head = doc.resolve(mapping.map(this.head));\n        if (!$head.parent.inlineContent)\n            return Selection.near($head);\n        let $anchor = doc.resolve(mapping.map(this.anchor));\n        return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n    }\n    replace(tr, content = Slice.empty) {\n        super.replace(tr, content);\n        if (content == Slice.empty) {\n            let marks = this.$from.marksAcross(this.$to);\n            if (marks)\n                tr.ensureMarks(marks);\n        }\n    }\n    eq(other) {\n        return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n    }\n    getBookmark() {\n        return new TextBookmark(this.anchor, this.head);\n    }\n    toJSON() {\n        return { type: \"text\", anchor: this.anchor, head: this.head };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(doc, json) {\n        if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n            throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n        return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n    }\n    /**\n    Create a text selection from non-resolved positions.\n    */\n    static create(doc, anchor, head = anchor) {\n        let $anchor = doc.resolve(anchor);\n        return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n    }\n    /**\n    Return a text selection that spans the given positions or, if\n    they aren't text positions, find a text selection near them.\n    `bias` determines whether the method searches forward (default)\n    or backwards (negative number) first. Will fall back to calling\n    [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n    doesn't contain a valid text position.\n    */\n    static between($anchor, $head, bias) {\n        let dPos = $anchor.pos - $head.pos;\n        if (!bias || dPos)\n            bias = dPos >= 0 ? 1 : -1;\n        if (!$head.parent.inlineContent) {\n            let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n            if (found)\n                $head = found.$head;\n            else\n                return Selection.near($head, bias);\n        }\n        if (!$anchor.parent.inlineContent) {\n            if (dPos == 0) {\n                $anchor = $head;\n            }\n            else {\n                $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n                if (($anchor.pos < $head.pos) != (dPos < 0))\n                    $anchor = $head;\n            }\n        }\n        return new TextSelection($anchor, $head);\n    }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n    constructor(anchor, head) {\n        this.anchor = anchor;\n        this.head = head;\n    }\n    map(mapping) {\n        return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n    }\n    resolve(doc) {\n        return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n    }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n    /**\n    Create a node selection. Does not verify the validity of its\n    argument.\n    */\n    constructor($pos) {\n        let node = $pos.nodeAfter;\n        let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n        super($pos, $end);\n        this.node = node;\n    }\n    map(doc, mapping) {\n        let { deleted, pos } = mapping.mapResult(this.anchor);\n        let $pos = doc.resolve(pos);\n        if (deleted)\n            return Selection.near($pos);\n        return new NodeSelection($pos);\n    }\n    content() {\n        return new Slice(Fragment.from(this.node), 0, 0);\n    }\n    eq(other) {\n        return other instanceof NodeSelection && other.anchor == this.anchor;\n    }\n    toJSON() {\n        return { type: \"node\", anchor: this.anchor };\n    }\n    getBookmark() { return new NodeBookmark(this.anchor); }\n    /**\n    @internal\n    */\n    static fromJSON(doc, json) {\n        if (typeof json.anchor != \"number\")\n            throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n        return new NodeSelection(doc.resolve(json.anchor));\n    }\n    /**\n    Create a node selection from non-resolved positions.\n    */\n    static create(doc, from) {\n        return new NodeSelection(doc.resolve(from));\n    }\n    /**\n    Determines whether the given node may be selected as a node\n    selection.\n    */\n    static isSelectable(node) {\n        return !node.isText && node.type.spec.selectable !== false;\n    }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n    constructor(anchor) {\n        this.anchor = anchor;\n    }\n    map(mapping) {\n        let { deleted, pos } = mapping.mapResult(this.anchor);\n        return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n    }\n    resolve(doc) {\n        let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n        if (node && NodeSelection.isSelectable(node))\n            return new NodeSelection($pos);\n        return Selection.near($pos);\n    }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n    /**\n    Create an all-selection over the given document.\n    */\n    constructor(doc) {\n        super(doc.resolve(0), doc.resolve(doc.content.size));\n    }\n    replace(tr, content = Slice.empty) {\n        if (content == Slice.empty) {\n            tr.delete(0, tr.doc.content.size);\n            let sel = Selection.atStart(tr.doc);\n            if (!sel.eq(tr.selection))\n                tr.setSelection(sel);\n        }\n        else {\n            super.replace(tr, content);\n        }\n    }\n    toJSON() { return { type: \"all\" }; }\n    /**\n    @internal\n    */\n    static fromJSON(doc) { return new AllSelection(doc); }\n    map(doc) { return new AllSelection(doc); }\n    eq(other) { return other instanceof AllSelection; }\n    getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n    map() { return this; },\n    resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n    if (node.inlineContent)\n        return TextSelection.create(doc, pos);\n    for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n        let child = node.child(i);\n        if (!child.isAtom) {\n            let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n            if (inner)\n                return inner;\n        }\n        else if (!text && NodeSelection.isSelectable(child)) {\n            return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n        }\n        pos += child.nodeSize * dir;\n    }\n    return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n    let last = tr.steps.length - 1;\n    if (last < startLen)\n        return;\n    let step = tr.steps[last];\n    if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n        return;\n    let map = tr.mapping.maps[last], end;\n    map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n        end = newTo; });\n    tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n    /**\n    @internal\n    */\n    constructor(state) {\n        super(state.doc);\n        // The step count for which the current selection is valid.\n        this.curSelectionFor = 0;\n        // Bitfield to track which aspects of the state were updated by\n        // this transaction.\n        this.updated = 0;\n        // Object used to store metadata properties for the transaction.\n        this.meta = Object.create(null);\n        this.time = Date.now();\n        this.curSelection = state.selection;\n        this.storedMarks = state.storedMarks;\n    }\n    /**\n    The transaction's current selection. This defaults to the editor\n    selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n    transaction, but can be overwritten with\n    [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n    */\n    get selection() {\n        if (this.curSelectionFor < this.steps.length) {\n            this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n            this.curSelectionFor = this.steps.length;\n        }\n        return this.curSelection;\n    }\n    /**\n    Update the transaction's current selection. Will determine the\n    selection that the editor gets when the transaction is applied.\n    */\n    setSelection(selection) {\n        if (selection.$from.doc != this.doc)\n            throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n        this.curSelection = selection;\n        this.curSelectionFor = this.steps.length;\n        this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n        this.storedMarks = null;\n        return this;\n    }\n    /**\n    Whether the selection was explicitly updated by this transaction.\n    */\n    get selectionSet() {\n        return (this.updated & UPDATED_SEL) > 0;\n    }\n    /**\n    Set the current stored marks.\n    */\n    setStoredMarks(marks) {\n        this.storedMarks = marks;\n        this.updated |= UPDATED_MARKS;\n        return this;\n    }\n    /**\n    Make sure the current stored marks or, if that is null, the marks\n    at the selection, match the given set of marks. Does nothing if\n    this is already the case.\n    */\n    ensureMarks(marks) {\n        if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n            this.setStoredMarks(marks);\n        return this;\n    }\n    /**\n    Add a mark to the set of stored marks.\n    */\n    addStoredMark(mark) {\n        return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n    }\n    /**\n    Remove a mark or mark type from the set of stored marks.\n    */\n    removeStoredMark(mark) {\n        return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n    }\n    /**\n    Whether the stored marks were explicitly set for this transaction.\n    */\n    get storedMarksSet() {\n        return (this.updated & UPDATED_MARKS) > 0;\n    }\n    /**\n    @internal\n    */\n    addStep(step, doc) {\n        super.addStep(step, doc);\n        this.updated = this.updated & ~UPDATED_MARKS;\n        this.storedMarks = null;\n    }\n    /**\n    Update the timestamp for the transaction.\n    */\n    setTime(time) {\n        this.time = time;\n        return this;\n    }\n    /**\n    Replace the current selection with the given slice.\n    */\n    replaceSelection(slice) {\n        this.selection.replace(this, slice);\n        return this;\n    }\n    /**\n    Replace the selection with the given node. When `inheritMarks` is\n    true and the content is inline, it inherits the marks from the\n    place where it is inserted.\n    */\n    replaceSelectionWith(node, inheritMarks = true) {\n        let selection = this.selection;\n        if (inheritMarks)\n            node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n        selection.replaceWith(this, node);\n        return this;\n    }\n    /**\n    Delete the selection.\n    */\n    deleteSelection() {\n        this.selection.replace(this);\n        return this;\n    }\n    /**\n    Replace the given range, or the selection if no range is given,\n    with a text node containing the given string.\n    */\n    insertText(text, from, to) {\n        let schema = this.doc.type.schema;\n        if (from == null) {\n            if (!text)\n                return this.deleteSelection();\n            return this.replaceSelectionWith(schema.text(text), true);\n        }\n        else {\n            if (to == null)\n                to = from;\n            if (!text)\n                return this.deleteRange(from, to);\n            let marks = this.storedMarks;\n            if (!marks) {\n                let $from = this.doc.resolve(from);\n                marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n            }\n            this.replaceRangeWith(from, to, schema.text(text, marks));\n            if (!this.selection.empty && this.selection.to == from + text.length)\n                this.setSelection(Selection.near(this.selection.$to));\n            return this;\n        }\n    }\n    /**\n    Store a metadata property in this transaction, keyed either by\n    name or by plugin.\n    */\n    setMeta(key, value) {\n        this.meta[typeof key == \"string\" ? key : key.key] = value;\n        return this;\n    }\n    /**\n    Retrieve a metadata property for a given name or plugin.\n    */\n    getMeta(key) {\n        return this.meta[typeof key == \"string\" ? key : key.key];\n    }\n    /**\n    Returns true if this transaction doesn't contain any metadata,\n    and can thus safely be extended.\n    */\n    get isGeneric() {\n        for (let _ in this.meta)\n            return false;\n        return true;\n    }\n    /**\n    Indicate that the editor should scroll the selection into view\n    when updated to the state produced by this transaction.\n    */\n    scrollIntoView() {\n        this.updated |= UPDATED_SCROLL;\n        return this;\n    }\n    /**\n    True when this transaction has had `scrollIntoView` called on it.\n    */\n    get scrolledIntoView() {\n        return (this.updated & UPDATED_SCROLL) > 0;\n    }\n}\n\nfunction bind(f, self) {\n    return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n    constructor(name, desc, self) {\n        this.name = name;\n        this.init = bind(desc.init, self);\n        this.apply = bind(desc.apply, self);\n    }\n}\nconst baseFields = [\n    new FieldDesc(\"doc\", {\n        init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n        apply(tr) { return tr.doc; }\n    }),\n    new FieldDesc(\"selection\", {\n        init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n        apply(tr) { return tr.selection; }\n    }),\n    new FieldDesc(\"storedMarks\", {\n        init(config) { return config.storedMarks || null; },\n        apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n    }),\n    new FieldDesc(\"scrollToSelection\", {\n        init() { return 0; },\n        apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n    })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n    constructor(schema, plugins) {\n        this.schema = schema;\n        this.plugins = [];\n        this.pluginsByKey = Object.create(null);\n        this.fields = baseFields.slice();\n        if (plugins)\n            plugins.forEach(plugin => {\n                if (this.pluginsByKey[plugin.key])\n                    throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n                this.plugins.push(plugin);\n                this.pluginsByKey[plugin.key] = plugin;\n                if (plugin.spec.state)\n                    this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n            });\n    }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure\u2014it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    @internal\n    */\n    config) {\n        this.config = config;\n    }\n    /**\n    The schema of the state's document.\n    */\n    get schema() {\n        return this.config.schema;\n    }\n    /**\n    The plugins that are active in this state.\n    */\n    get plugins() {\n        return this.config.plugins;\n    }\n    /**\n    Apply the given transaction to produce a new state.\n    */\n    apply(tr) {\n        return this.applyTransaction(tr).state;\n    }\n    /**\n    @internal\n    */\n    filterTransaction(tr, ignore = -1) {\n        for (let i = 0; i < this.config.plugins.length; i++)\n            if (i != ignore) {\n                let plugin = this.config.plugins[i];\n                if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n                    return false;\n            }\n        return true;\n    }\n    /**\n    Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n    returns the precise transactions that were applied (which might\n    be influenced by the [transaction\n    hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n    plugins) along with the new state.\n    */\n    applyTransaction(rootTr) {\n        if (!this.filterTransaction(rootTr))\n            return { state: this, transactions: [] };\n        let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n        // This loop repeatedly gives plugins a chance to respond to\n        // transactions as new transactions are added, making sure to only\n        // pass the transactions the plugin did not see before.\n        for (;;) {\n            let haveNew = false;\n            for (let i = 0; i < this.config.plugins.length; i++) {\n                let plugin = this.config.plugins[i];\n                if (plugin.spec.appendTransaction) {\n                    let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n                    let tr = n < trs.length &&\n                        plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n                    if (tr && newState.filterTransaction(tr, i)) {\n                        tr.setMeta(\"appendedTransaction\", rootTr);\n                        if (!seen) {\n                            seen = [];\n                            for (let j = 0; j < this.config.plugins.length; j++)\n                                seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n                        }\n                        trs.push(tr);\n                        newState = newState.applyInner(tr);\n                        haveNew = true;\n                    }\n                    if (seen)\n                        seen[i] = { state: newState, n: trs.length };\n                }\n            }\n            if (!haveNew)\n                return { state: newState, transactions: trs };\n        }\n    }\n    /**\n    @internal\n    */\n    applyInner(tr) {\n        if (!tr.before.eq(this.doc))\n            throw new RangeError(\"Applying a mismatched transaction\");\n        let newInstance = new EditorState(this.config), fields = this.config.fields;\n        for (let i = 0; i < fields.length; i++) {\n            let field = fields[i];\n            newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n        }\n        return newInstance;\n    }\n    /**\n    Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n    */\n    get tr() { return new Transaction(this); }\n    /**\n    Create a new state.\n    */\n    static create(config) {\n        let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n        let instance = new EditorState($config);\n        for (let i = 0; i < $config.fields.length; i++)\n            instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n        return instance;\n    }\n    /**\n    Create a new state based on this one, but with an adjusted set\n    of active plugins. State fields that exist in both sets of\n    plugins are kept unchanged. Those that no longer exist are\n    dropped, and those that are new are initialized using their\n    [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n    configuration object..\n    */\n    reconfigure(config) {\n        let $config = new Configuration(this.schema, config.plugins);\n        let fields = $config.fields, instance = new EditorState($config);\n        for (let i = 0; i < fields.length; i++) {\n            let name = fields[i].name;\n            instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n        }\n        return instance;\n    }\n    /**\n    Serialize this state to JSON. If you want to serialize the state\n    of plugins, pass an object mapping property names to use in the\n    resulting JSON object to plugin objects. The argument may also be\n    a string or number, in which case it is ignored, to support the\n    way `JSON.stringify` calls `toString` methods.\n    */\n    toJSON(pluginFields) {\n        let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n        if (this.storedMarks)\n            result.storedMarks = this.storedMarks.map(m => m.toJSON());\n        if (pluginFields && typeof pluginFields == 'object')\n            for (let prop in pluginFields) {\n                if (prop == \"doc\" || prop == \"selection\")\n                    throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n                let plugin = pluginFields[prop], state = plugin.spec.state;\n                if (state && state.toJSON)\n                    result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n            }\n        return result;\n    }\n    /**\n    Deserialize a JSON representation of a state. `config` should\n    have at least a `schema` field, and should contain array of\n    plugins to initialize the state with. `pluginFields` can be used\n    to deserialize the state of plugins, by associating plugin\n    instances with the property names they use in the JSON object.\n    */\n    static fromJSON(config, json, pluginFields) {\n        if (!json)\n            throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n        if (!config.schema)\n            throw new RangeError(\"Required config field 'schema' missing\");\n        let $config = new Configuration(config.schema, config.plugins);\n        let instance = new EditorState($config);\n        $config.fields.forEach(field => {\n            if (field.name == \"doc\") {\n                instance.doc = Node.fromJSON(config.schema, json.doc);\n            }\n            else if (field.name == \"selection\") {\n                instance.selection = Selection.fromJSON(instance.doc, json.selection);\n            }\n            else if (field.name == \"storedMarks\") {\n                if (json.storedMarks)\n                    instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n            }\n            else {\n                if (pluginFields)\n                    for (let prop in pluginFields) {\n                        let plugin = pluginFields[prop], state = plugin.spec.state;\n                        if (plugin.key == field.name && state && state.fromJSON &&\n                            Object.prototype.hasOwnProperty.call(json, prop)) {\n                            instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n                            return;\n                        }\n                    }\n                instance[field.name] = field.init(config, instance);\n            }\n        });\n        return instance;\n    }\n}\n\nfunction bindProps(obj, self, target) {\n    for (let prop in obj) {\n        let val = obj[prop];\n        if (val instanceof Function)\n            val = val.bind(self);\n        else if (prop == \"handleDOMEvents\")\n            val = bindProps(val, self, {});\n        target[prop] = val;\n    }\n    return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n    /**\n    Create a plugin.\n    */\n    constructor(\n    /**\n    The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n    */\n    spec) {\n        this.spec = spec;\n        /**\n        The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n        */\n        this.props = {};\n        if (spec.props)\n            bindProps(spec.props, this, this.props);\n        this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n    }\n    /**\n    Extract the plugin's state field from an editor state.\n    */\n    getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n    if (name in keys)\n        return name + \"$\" + ++keys[name];\n    keys[name] = 0;\n    return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n    /**\n    Create a plugin key.\n    */\n    constructor(name = \"key\") { this.key = createKey(name); }\n    /**\n    Get the active plugin with this key, if any, from an editor\n    state.\n    */\n    get(state) { return state.config.pluginsByKey[this.key]; }\n    /**\n    Get the plugin's state from an editor state.\n    */\n    getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n", "import { TextSelection, NodeSelection, Selection, AllSelection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n    for (var index = 0;; index++) {\n        node = node.previousSibling;\n        if (!node)\n            return index;\n    }\n};\nconst parentNode = function (node) {\n    let parent = node.assignedSlot || node.parentNode;\n    return parent && parent.nodeType == 11 ? parent.host : parent;\n};\nlet reusedRange = null;\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nconst textRange = function (node, from, to) {\n    let range = reusedRange || (reusedRange = document.createRange());\n    range.setEnd(node, to == null ? node.nodeValue.length : to);\n    range.setStart(node, from || 0);\n    return range;\n};\nconst clearReusedRange = function () {\n    reusedRange = null;\n};\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nconst isEquivalentPosition = function (node, off, targetNode, targetOff) {\n    return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n        scanFor(node, off, targetNode, targetOff, 1));\n};\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n    var _a;\n    for (;;) {\n        if (node == targetNode && off == targetOff)\n            return true;\n        if (off == (dir < 0 ? 0 : nodeSize(node))) {\n            let parent = node.parentNode;\n            if (!parent || !isElt(parent) || hasBlockDesc(node) || atomElements.test(node.nodeName) ||\n                node.contentEditable == \"false\")\n                return false;\n            off = domIndex(node) + (dir < 0 ? 0 : 1);\n            node = parent;\n        }\n        else if (isElt(node)) {\n            let child = node.childNodes[off + (dir < 0 ? -1 : 0)];\n            if (isElt(child) && child.contentEditable == \"false\") {\n                if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection)\n                    off += dir;\n                else\n                    return false;\n            }\n            else {\n                node = child;\n                off = dir < 0 ? nodeSize(node) : 0;\n            }\n        }\n        else {\n            return false;\n        }\n    }\n}\nfunction nodeSize(node) {\n    return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isElt(node) { return node.nodeType == 1; }\nfunction isText(node) { return node.nodeType == 3; }\nfunction contains(parent, child) {\n    return child ? parent.contains(isElt(child) ? child : child.parentNode) : false;\n}\nfunction textNodeBefore$1(node, offset) {\n    for (;;) {\n        if (isText(node) && offset)\n            return node;\n        if (isElt(node) && offset > 0) {\n            if (node.contentEditable == \"false\")\n                return null;\n            node = node.childNodes[offset - 1];\n            offset = nodeSize(node);\n        }\n        else if (node.parentNode && !hasBlockDesc(node)) {\n            offset = domIndex(node);\n            node = node.parentNode;\n        }\n        else {\n            return null;\n        }\n    }\n}\nfunction textNodeAfter$1(node, offset) {\n    for (;;) {\n        if (isText(node) && offset < node.nodeValue.length)\n            return node;\n        if (isElt(node) && offset < node.childNodes.length) {\n            if (node.contentEditable == \"false\")\n                return null;\n            node = node.childNodes[offset];\n            offset = 0;\n        }\n        else if (node.parentNode && !hasBlockDesc(node)) {\n            offset = domIndex(node) + 1;\n            node = node.parentNode;\n        }\n        else {\n            return null;\n        }\n    }\n}\nfunction isOnEdge(node, offset, parent) {\n    for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n        if (node == parent)\n            return true;\n        let index = domIndex(node);\n        node = node.parentNode;\n        if (!node)\n            return false;\n        atStart = atStart && index == 0;\n        atEnd = atEnd && index == nodeSize(node);\n    }\n}\nfunction hasBlockDesc(dom) {\n    let desc;\n    for (let cur = dom; cur; cur = cur.parentNode)\n        if (desc = cur.pmViewDesc)\n            break;\n    return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nconst selectionCollapsed = function (domSel) {\n    return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n};\nfunction keyEvent(keyCode, key) {\n    let event = document.createEvent(\"Event\");\n    event.initEvent(\"keydown\", true, true);\n    event.keyCode = keyCode;\n    event.key = event.code = key;\n    return event;\n}\nfunction deepActiveElement(doc) {\n    let elt = doc.activeElement;\n    while (elt && elt.shadowRoot)\n        elt = elt.shadowRoot.activeElement;\n    return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n    if (doc.caretPositionFromPoint) {\n        try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n            let pos = doc.caretPositionFromPoint(x, y);\n            // Clip the offset, because Chrome will return a text offset\n            // into <input> nodes, which can't be treated as a regular DOM\n            // offset\n            if (pos)\n                return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n        }\n        catch (_) { }\n    }\n    if (doc.caretRangeFromPoint) {\n        let range = doc.caretRangeFromPoint(x, y);\n        if (range)\n            return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n    }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst ie_edge = /Edge\\/(\\d+)/.exec(agent);\nconst ie_upto10 = /MSIE \\d/.exec(agent);\nconst ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(agent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;\nconst gecko = !ie && /gecko\\/(\\d+)/i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = !ie && /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n    let vp = doc.defaultView && doc.defaultView.visualViewport;\n    if (vp)\n        return {\n            left: 0, right: vp.width,\n            top: 0, bottom: vp.height\n        };\n    return { left: 0, right: doc.documentElement.clientWidth,\n        top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n    return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n    let rect = node.getBoundingClientRect();\n    // Adjust for elements with style \"transform: scale()\"\n    let scaleX = (rect.width / node.offsetWidth) || 1;\n    let scaleY = (rect.height / node.offsetHeight) || 1;\n    // Make sure scrollbar width isn't included in the rectangle\n    return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n        top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n    // Skip empty rects with all sides at 0, for example, when the element has no CSS box (display: none)\n    if (!nonZero(rect) && rect.left == 0)\n        return;\n    let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n    let doc = view.dom.ownerDocument;\n    for (let parent = startDOM || view.dom;;) {\n        if (!parent)\n            break;\n        if (!isElt(parent)) {\n            parent = parentNode(parent);\n            continue;\n        }\n        let atTop = parent == doc.body;\n        let bounding = atTop ? windowRect(doc) : clientRect(parent);\n        let moveX = 0, moveY = 0;\n        if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n            moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\"));\n        else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n            moveY = rect.bottom - rect.top > bounding.bottom - bounding.top\n                ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n                : rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\");\n        if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n            moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\"));\n        else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n            moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\");\n        if (moveX || moveY) {\n            if (atTop) {\n                doc.defaultView.scrollBy(moveX, moveY);\n            }\n            else {\n                let startX = parent.scrollLeft, startY = parent.scrollTop;\n                if (moveY)\n                    parent.scrollTop += moveY;\n                if (moveX)\n                    parent.scrollLeft += moveX;\n                let dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY;\n                rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };\n            }\n        }\n        let pos = atTop ? \"fixed\" : getComputedStyle(parent).position;\n        if (/^(fixed|sticky)$/.test(pos))\n            break;\n        parent = pos == \"absolute\" ? parent.offsetParent : parentNode(parent);\n    }\n}\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n    let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n    let refDOM, refTop;\n    for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n        let dom = view.root.elementFromPoint(x, y);\n        if (!dom || dom == view.dom || !view.dom.contains(dom))\n            continue;\n        let localRect = dom.getBoundingClientRect();\n        if (localRect.top >= startY - 20) {\n            refDOM = dom;\n            refTop = localRect.top;\n            break;\n        }\n    }\n    return { refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom) };\n}\nfunction scrollStack(dom) {\n    let stack = [], doc = dom.ownerDocument;\n    for (let cur = dom; cur; cur = parentNode(cur)) {\n        stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n        if (dom == doc)\n            break;\n    }\n    return stack;\n}\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos({ refDOM, refTop, stack }) {\n    let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n    restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n    for (let i = 0; i < stack.length; i++) {\n        let { dom, top, left } = stack[i];\n        if (dom.scrollTop != top + dTop)\n            dom.scrollTop = top + dTop;\n        if (dom.scrollLeft != left)\n            dom.scrollLeft = left;\n    }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n    if (dom.setActive)\n        return dom.setActive(); // in IE\n    if (preventScrollSupported)\n        return dom.focus(preventScrollSupported);\n    let stored = scrollStack(dom);\n    dom.focus(preventScrollSupported == null ? {\n        get preventScroll() {\n            preventScrollSupported = { preventScroll: true };\n            return true;\n        }\n    } : undefined);\n    if (!preventScrollSupported) {\n        preventScrollSupported = false;\n        restoreScrollStack(stored, 0);\n    }\n}\nfunction findOffsetInNode(node, coords) {\n    let closest;\n    let dxClosest = 2e8, coordsClosest, offset = 0;\n    let rowBot = coords.top, rowTop = coords.top;\n    let firstBelow, coordsBelow;\n    for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n        let rects;\n        if (isElt(child))\n            rects = child.getClientRects();\n        else if (isText(child))\n            rects = textRange(child).getClientRects();\n        else\n            continue;\n        for (let i = 0; i < rects.length; i++) {\n            let rect = rects[i];\n            if (rect.top <= rowBot && rect.bottom >= rowTop) {\n                rowBot = Math.max(rect.bottom, rowBot);\n                rowTop = Math.min(rect.top, rowTop);\n                let dx = rect.left > coords.left ? rect.left - coords.left\n                    : rect.right < coords.left ? coords.left - rect.right : 0;\n                if (dx < dxClosest) {\n                    closest = child;\n                    dxClosest = dx;\n                    coordsClosest = dx && isText(closest) ? {\n                        left: rect.right < coords.left ? rect.right : rect.left,\n                        top: coords.top\n                    } : coords;\n                    if (isElt(child) && dx)\n                        offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n                    continue;\n                }\n            }\n            else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n                firstBelow = child;\n                coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\n            }\n            if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n                coords.left >= rect.left && coords.top >= rect.bottom))\n                offset = childIndex + 1;\n        }\n    }\n    if (!closest && firstBelow) {\n        closest = firstBelow;\n        coordsClosest = coordsBelow;\n        dxClosest = 0;\n    }\n    if (closest && isText(closest))\n        return findOffsetInText(closest, coordsClosest);\n    if (!closest || dxClosest)\n        return { node, offset };\n    return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n    let len = node.nodeValue.length;\n    let range = document.createRange(), result;\n    for (let i = 0; i < len; i++) {\n        range.setEnd(node, i + 1);\n        range.setStart(node, i);\n        let rect = singleRect(range, 1);\n        if (rect.top == rect.bottom)\n            continue;\n        if (inRect(coords, rect)) {\n            result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n            break;\n        }\n    }\n    range.detach();\n    return result || { node, offset: 0 };\n}\nfunction inRect(coords, rect) {\n    return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 &&\n        coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;\n}\nfunction targetKludge(dom, coords) {\n    let parent = dom.parentNode;\n    if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n        return parent;\n    return dom;\n}\nfunction posFromElement(view, elt, coords) {\n    let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n    if (isElt(node) && !node.firstChild) {\n        let rect = node.getBoundingClientRect();\n        bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n    }\n    return view.docView.posFromDOM(node, offset, bias);\n}\nfunction posFromCaret(view, node, offset, coords) {\n    // Browser (in caretPosition/RangeFromPoint) will agressively\n    // normalize towards nearby inline nodes. Since we are interested in\n    // positions between block nodes too, we first walk up the hierarchy\n    // of nodes to see if there are block nodes that the coordinates\n    // fall outside of. If so, we take the position before/after that\n    // block. If not, we call `posFromDOM` on the raw node/offset.\n    let outsideBlock = -1;\n    for (let cur = node, sawBlock = false;;) {\n        if (cur == view.dom)\n            break;\n        let desc = view.docView.nearestDesc(cur, true), rect;\n        if (!desc)\n            return null;\n        if (isElt(desc.dom) && (desc.node.isBlock && desc.parent || !desc.contentDOM) &&\n            // Ignore elements with zero-size bounding rectangles\n            ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n            if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {\n                // Only apply the horizontal test to the innermost block. Vertical for any parent.\n                if (!sawBlock && rect.left > coords.left || rect.top > coords.top)\n                    outsideBlock = desc.posBefore;\n                else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)\n                    outsideBlock = desc.posAfter;\n                sawBlock = true;\n            }\n            if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {\n                // If we are inside a leaf, return the side of the leaf closer to the coords\n                let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n                    : coords.left < (rect.left + rect.right) / 2;\n                return before ? desc.posBefore : desc.posAfter;\n            }\n        }\n        cur = desc.dom.parentNode;\n    }\n    return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);\n}\nfunction elementFromPoint(element, coords, box) {\n    let len = element.childNodes.length;\n    if (len && box.top < box.bottom) {\n        for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n            let child = element.childNodes[i];\n            if (isElt(child)) {\n                let rects = child.getClientRects();\n                for (let j = 0; j < rects.length; j++) {\n                    let rect = rects[j];\n                    if (inRect(coords, rect))\n                        return elementFromPoint(child, coords, rect);\n                }\n            }\n            if ((i = (i + 1) % len) == startI)\n                break;\n        }\n    }\n    return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n    let doc = view.dom.ownerDocument, node, offset = 0;\n    let caret = caretFromPoint(doc, coords.left, coords.top);\n    if (caret)\n        ({ node, offset } = caret);\n    let elt = (view.root.elementFromPoint ? view.root : doc)\n        .elementFromPoint(coords.left, coords.top);\n    let pos;\n    if (!elt || !view.dom.contains(elt)) {\n        let box = view.dom.getBoundingClientRect();\n        if (!inRect(coords, box))\n            return null;\n        elt = elementFromPoint(view.dom, coords, box);\n        if (!elt)\n            return null;\n    }\n    // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n    if (safari) {\n        for (let p = elt; node && p; p = parentNode(p))\n            if (p.draggable)\n                node = undefined;\n    }\n    elt = targetKludge(elt, coords);\n    if (node) {\n        if (gecko && isElt(node)) {\n            // Firefox will sometimes return offsets into <input> nodes, which\n            // have no actual children, from caretPositionFromPoint (#953)\n            offset = Math.min(offset, node.childNodes.length);\n            // It'll also move the returned position before image nodes,\n            // even if those are behind it.\n            if (offset < node.childNodes.length) {\n                let next = node.childNodes[offset], box;\n                if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n                    box.bottom > coords.top)\n                    offset++;\n            }\n        }\n        let prev;\n        // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n        if (webkit && offset && isElt(node) && isElt(prev = node.childNodes[offset - 1]) &&\n            prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n            offset--;\n        // Suspiciously specific kludge to work around caret*FromPoint\n        // never returning a position at the end of the document\n        if (node == view.dom && offset == node.childNodes.length - 1 && isElt(node.lastChild) &&\n            coords.top > node.lastChild.getBoundingClientRect().bottom)\n            pos = view.state.doc.content.size;\n        // Ignore positions directly after a BR, since caret*FromPoint\n        // 'round up' positions that would be more accurately placed\n        // before the BR node.\n        else if (offset == 0 || !isElt(node) || node.childNodes[offset - 1].nodeName != \"BR\")\n            pos = posFromCaret(view, node, offset, coords);\n    }\n    if (pos == null)\n        pos = posFromElement(view, elt, coords);\n    let desc = view.docView.nearestDesc(elt, true);\n    return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };\n}\nfunction nonZero(rect) {\n    return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n    let rects = target.getClientRects();\n    if (rects.length) {\n        let first = rects[bias < 0 ? 0 : rects.length - 1];\n        if (nonZero(first))\n            return first;\n    }\n    return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n    let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n    let supportEmptyRange = webkit || gecko;\n    if (isText(node)) {\n        // These browsers support querying empty text ranges. Prefer that in\n        // bidi context or when at the end of a node.\n        if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n            let rect = singleRect(textRange(node, offset, offset), side);\n            // Firefox returns bad results (the position before the space)\n            // when querying a position directly after line-broken\n            // whitespace. Detect this situation and and kludge around it\n            if (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n                let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n                if (rectBefore.top == rect.top) {\n                    let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n                    if (rectAfter.top != rect.top)\n                        return flattenV(rectAfter, rectAfter.left < rectBefore.left);\n                }\n            }\n            return rect;\n        }\n        else {\n            let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n            if (side < 0 && !offset) {\n                to++;\n                takeSide = -1;\n            }\n            else if (side >= 0 && offset == node.nodeValue.length) {\n                from--;\n                takeSide = 1;\n            }\n            else if (side < 0) {\n                from--;\n            }\n            else {\n                to++;\n            }\n            return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n        }\n    }\n    let $dom = view.state.doc.resolve(pos - (atom || 0));\n    // Return a horizontal line in block context\n    if (!$dom.parent.inlineContent) {\n        if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n            let before = node.childNodes[offset - 1];\n            if (isElt(before))\n                return flattenH(before.getBoundingClientRect(), false);\n        }\n        if (atom == null && offset < nodeSize(node)) {\n            let after = node.childNodes[offset];\n            if (isElt(after))\n                return flattenH(after.getBoundingClientRect(), true);\n        }\n        return flattenH(node.getBoundingClientRect(), side >= 0);\n    }\n    // Inline, not in text node (this is not Bidi-safe)\n    if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n        let before = node.childNodes[offset - 1];\n        let target = isText(before) ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n            // BR nodes tend to only return the rectangle before them.\n            // Only use them if they are the last element in their parent\n            : isElt(before) && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n        if (target)\n            return flattenV(singleRect(target, 1), false);\n    }\n    if (atom == null && offset < nodeSize(node)) {\n        let after = node.childNodes[offset];\n        while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n            after = after.nextSibling;\n        let target = !after ? null : isText(after) ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n            : isElt(after) ? after : null;\n        if (target)\n            return flattenV(singleRect(target, -1), true);\n    }\n    // All else failed, just try to get a rectangle for the target node\n    return flattenV(singleRect(isText(node) ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n    if (rect.width == 0)\n        return rect;\n    let x = left ? rect.left : rect.right;\n    return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n    if (rect.height == 0)\n        return rect;\n    let y = top ? rect.top : rect.bottom;\n    return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n    let viewState = view.state, active = view.root.activeElement;\n    if (viewState != state)\n        view.updateState(state);\n    if (active != view.dom)\n        view.focus();\n    try {\n        return f();\n    }\n    finally {\n        if (viewState != state)\n            view.updateState(viewState);\n        if (active != view.dom && active)\n            active.focus();\n    }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n    let sel = state.selection;\n    let $pos = dir == \"up\" ? sel.$from : sel.$to;\n    return withFlushedState(view, state, () => {\n        let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n        for (;;) {\n            let nearest = view.docView.nearestDesc(dom, true);\n            if (!nearest)\n                break;\n            if (nearest.node.isBlock) {\n                dom = nearest.contentDOM || nearest.dom;\n                break;\n            }\n            dom = nearest.dom.parentNode;\n        }\n        let coords = coordsAtPos(view, $pos.pos, 1);\n        for (let child = dom.firstChild; child; child = child.nextSibling) {\n            let boxes;\n            if (isElt(child))\n                boxes = child.getClientRects();\n            else if (isText(child))\n                boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n            else\n                continue;\n            for (let i = 0; i < boxes.length; i++) {\n                let box = boxes[i];\n                if (box.bottom > box.top + 1 &&\n                    (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n                        : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n                    return false;\n            }\n        }\n        return true;\n    });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n    let { $head } = state.selection;\n    if (!$head.parent.isTextblock)\n        return false;\n    let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n    let sel = view.domSelection();\n    if (!sel)\n        return $head.pos == $head.start() || $head.pos == $head.end();\n    // If the textblock is all LTR, or the browser doesn't support\n    // Selection.modify (Edge), fall back to a primitive approach\n    if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n        return dir == \"left\" || dir == \"backward\" ? atStart : atEnd;\n    return withFlushedState(view, state, () => {\n        // This is a huge hack, but appears to be the best we can\n        // currently do: use `Selection.modify` to move the selection by\n        // one character, and see if that moves the cursor out of the\n        // textblock (or doesn't move it at all, when at the start/end of\n        // the document).\n        let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();\n        let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n        ;\n        sel.modify(\"move\", dir, \"character\");\n        let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n        let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();\n        let result = newNode && !contains(parentDOM, newNode) || (oldNode == newNode && oldOff == newOff);\n        // Restore the previous selection\n        try {\n            sel.collapse(anchorNode, anchorOffset);\n            if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)\n                sel.extend(oldNode, oldOff);\n        }\n        catch (_) { }\n        if (oldBidiLevel != null)\n            sel.caretBidiLevel = oldBidiLevel;\n        return result;\n    });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n    if (cachedState == state && cachedDir == dir)\n        return cachedResult;\n    cachedState = state;\n    cachedDir = dir;\n    return cachedResult = dir == \"up\" || dir == \"down\"\n        ? endOfTextblockVertical(view, state, dir)\n        : endOfTextblockHorizontal(view, state, dir);\n}\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n//   corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n//   given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\nconst NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n    constructor(parent, children, dom, \n    // This is the node that holds the child views. It may be null for\n    // descs that don't have children.\n    contentDOM) {\n        this.parent = parent;\n        this.children = children;\n        this.dom = dom;\n        this.contentDOM = contentDOM;\n        this.dirty = NOT_DIRTY;\n        // An expando property on the DOM node provides a link back to its\n        // description.\n        dom.pmViewDesc = this;\n    }\n    // Used to check whether a given description corresponds to a\n    // widget/mark/node.\n    matchesWidget(widget) { return false; }\n    matchesMark(mark) { return false; }\n    matchesNode(node, outerDeco, innerDeco) { return false; }\n    matchesHack(nodeName) { return false; }\n    // When parsing in-editor content (in domchange.js), we allow\n    // descriptions to determine the parse rules that should be used to\n    // parse them.\n    parseRule(addedNodes) { return null; }\n    // Used by the editor's event handler to ignore events that come\n    // from certain descs.\n    stopEvent(event) { return false; }\n    // The size of the content represented by this desc.\n    get size() {\n        let size = 0;\n        for (let i = 0; i < this.children.length; i++)\n            size += this.children[i].size;\n        return size;\n    }\n    // For block nodes, this represents the space taken up by their\n    // start/end tokens.\n    get border() { return 0; }\n    destroy() {\n        this.parent = undefined;\n        if (this.dom.pmViewDesc == this)\n            this.dom.pmViewDesc = undefined;\n        for (let i = 0; i < this.children.length; i++)\n            this.children[i].destroy();\n    }\n    posBeforeChild(child) {\n        for (let i = 0, pos = this.posAtStart;; i++) {\n            let cur = this.children[i];\n            if (cur == child)\n                return pos;\n            pos += cur.size;\n        }\n    }\n    get posBefore() {\n        return this.parent.posBeforeChild(this);\n    }\n    get posAtStart() {\n        return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n    }\n    get posAfter() {\n        return this.posBefore + this.size;\n    }\n    get posAtEnd() {\n        return this.posAtStart + this.size - 2 * this.border;\n    }\n    localPosFromDOM(dom, offset, bias) {\n        // If the DOM position is in the content, use the child desc after\n        // it to figure out a position.\n        if (this.contentDOM && contains(this.contentDOM, dom)) {\n            if (bias < 0) {\n                let domBefore, desc;\n                if (dom == this.contentDOM) {\n                    domBefore = dom.childNodes[offset - 1];\n                }\n                else {\n                    while (dom.parentNode != this.contentDOM)\n                        dom = dom.parentNode;\n                    domBefore = dom.previousSibling;\n                }\n                while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n                    domBefore = domBefore.previousSibling;\n                return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n            }\n            else {\n                let domAfter, desc;\n                if (dom == this.contentDOM) {\n                    domAfter = dom.childNodes[offset];\n                }\n                else {\n                    while (dom.parentNode != this.contentDOM)\n                        dom = dom.parentNode;\n                    domAfter = dom.nextSibling;\n                }\n                while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n                    domAfter = domAfter.nextSibling;\n                return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;\n            }\n        }\n        // Otherwise, use various heuristics, falling back on the bias\n        // parameter, to determine whether to return the position at the\n        // start or at the end of this view desc.\n        let atEnd;\n        if (dom == this.dom && this.contentDOM) {\n            atEnd = offset > domIndex(this.contentDOM);\n        }\n        else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n            let rel = dom.compareDocumentPosition(this.contentDOM);\n            if (rel & 16) { // this.contentDOM is inside dom\n                atEnd = offset > Array.from(dom.childNodes).findIndex(n => n.contains(this.contentDOM));\n            }\n            else { // Check if after or before\n                atEnd = !(rel & 4);\n            }\n        }\n        else if (this.dom.firstChild) {\n            if (offset == 0)\n                for (let search = dom;; search = search.parentNode) {\n                    if (search == this.dom) {\n                        atEnd = false;\n                        break;\n                    }\n                    if (search.previousSibling)\n                        break;\n                }\n            if (atEnd == null && offset == dom.childNodes.length)\n                for (let search = dom;; search = search.parentNode) {\n                    if (search == this.dom) {\n                        atEnd = true;\n                        break;\n                    }\n                    if (search.nextSibling)\n                        break;\n                }\n        }\n        return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n    }\n    nearestDesc(dom, onlyNodes = false) {\n        for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n            let desc = this.getDesc(cur), nodeDOM;\n            if (desc && (!onlyNodes || desc.node)) {\n                // If dom is outside of this desc's nodeDOM, don't count it.\n                if (first && (nodeDOM = desc.nodeDOM) &&\n                    !(isElt(nodeDOM) ? contains(nodeDOM, dom) : nodeDOM == dom))\n                    first = false;\n                else\n                    return desc;\n            }\n        }\n    }\n    getDesc(dom) {\n        let desc = dom.pmViewDesc;\n        for (let cur = desc; cur; cur = cur.parent)\n            if (cur == this)\n                return desc;\n    }\n    posFromDOM(dom, offset, bias) {\n        for (let scan = dom; scan; scan = scan.parentNode) {\n            let desc = this.getDesc(scan);\n            if (desc)\n                return desc.localPosFromDOM(dom, offset, bias);\n        }\n        return -1;\n    }\n    // Find the desc for the node after the given pos, if any. (When a\n    // parent node overrode rendering, there might not be one.)\n    descAt(pos) {\n        for (let i = 0, offset = 0; i < this.children.length; i++) {\n            let child = this.children[i], end = offset + child.size;\n            if (offset == pos && end != offset) {\n                while (!child.border && child.children.length) {\n                    for (let i = 0; i < child.children.length; i++) {\n                        let inner = child.children[i];\n                        if (inner.size) {\n                            child = inner;\n                            break;\n                        }\n                    }\n                }\n                return child;\n            }\n            if (pos < end)\n                return child.descAt(pos - offset - child.border);\n            offset = end;\n        }\n    }\n    domFromPos(pos, side) {\n        if (!this.contentDOM)\n            return { node: this.dom, offset: 0, atom: pos + 1 };\n        // First find the position in the child array\n        let i = 0, offset = 0;\n        for (let curPos = 0; i < this.children.length; i++) {\n            let child = this.children[i], end = curPos + child.size;\n            if (end > pos) {\n                offset = pos - curPos;\n                break;\n            }\n            curPos = end;\n        }\n        // If this points into the middle of a child, call through\n        if (offset)\n            return this.children[i].domFromPos(offset - this.children[i].border, side);\n        // Go back if there were any zero-length widgets with side >= 0 before this point\n        for (; i > 0; i--) {\n            let prev = this.children[i - 1];\n            if (prev.size || !(prev instanceof BufferHackViewDesc || prev instanceof WidgetViewDesc && prev.side >= 0))\n                break;\n        }\n        // Scan towards the first useable node\n        if (side <= 0) {\n            let prev, enter = true;\n            for (;; i--, enter = false) {\n                prev = i ? this.children[i - 1] : null;\n                if (!prev || prev.dom.parentNode == this.contentDOM)\n                    break;\n            }\n            if (prev && side && enter && !prev.border && !prev.domAtom)\n                return prev.domFromPos(prev.size, side);\n            return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n        }\n        else {\n            let next, enter = true;\n            for (;; i++, enter = false) {\n                next = i < this.children.length ? this.children[i] : null;\n                if (!next || next.dom.parentNode == this.contentDOM)\n                    break;\n            }\n            if (next && enter && !next.border && !next.domAtom)\n                return next.domFromPos(0, side);\n            return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n        }\n    }\n    // Used to find a DOM range in a single parent for a given changed\n    // range.\n    parseRange(from, to, base = 0) {\n        if (this.children.length == 0)\n            return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n        let fromOffset = -1, toOffset = -1;\n        for (let offset = base, i = 0;; i++) {\n            let child = this.children[i], end = offset + child.size;\n            if (fromOffset == -1 && from <= end) {\n                let childBase = offset + child.border;\n                // FIXME maybe descend mark views to parse a narrower range?\n                if (from >= childBase && to <= end - child.border && child.node &&\n                    child.contentDOM && this.contentDOM.contains(child.contentDOM))\n                    return child.parseRange(from, to, childBase);\n                from = offset;\n                for (let j = i; j > 0; j--) {\n                    let prev = this.children[j - 1];\n                    if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n                        fromOffset = domIndex(prev.dom) + 1;\n                        break;\n                    }\n                    from -= prev.size;\n                }\n                if (fromOffset == -1)\n                    fromOffset = 0;\n            }\n            if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n                to = end;\n                for (let j = i + 1; j < this.children.length; j++) {\n                    let next = this.children[j];\n                    if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n                        toOffset = domIndex(next.dom);\n                        break;\n                    }\n                    to += next.size;\n                }\n                if (toOffset == -1)\n                    toOffset = this.contentDOM.childNodes.length;\n                break;\n            }\n            offset = end;\n        }\n        return { node: this.contentDOM, from, to, fromOffset, toOffset };\n    }\n    emptyChildAt(side) {\n        if (this.border || !this.contentDOM || !this.children.length)\n            return false;\n        let child = this.children[side < 0 ? 0 : this.children.length - 1];\n        return child.size == 0 || child.emptyChildAt(side);\n    }\n    domAfterPos(pos) {\n        let { node, offset } = this.domFromPos(pos, 0);\n        if (!isElt(node) || offset == node.childNodes.length)\n            throw new RangeError(\"No node after pos \" + pos);\n        return node.childNodes[offset];\n    }\n    // View descs are responsible for setting any selection that falls\n    // entirely inside of them, so that custom implementations can do\n    // custom things with the selection. Note that this falls apart when\n    // a selection starts in such a node and ends in another, in which\n    // case we just use whatever domFromPos produces as a best effort.\n    setSelection(anchor, head, view, force = false) {\n        // If the selection falls entirely in a child, give it to that child\n        let from = Math.min(anchor, head), to = Math.max(anchor, head);\n        for (let i = 0, offset = 0; i < this.children.length; i++) {\n            let child = this.children[i], end = offset + child.size;\n            if (from > offset && to < end)\n                return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);\n            offset = end;\n        }\n        let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);\n        let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);\n        let domSel = view.root.getSelection();\n        let selRange = view.domSelectionRange();\n        let brKludge = false;\n        // On Firefox, using Selection.collapse to put the cursor after a\n        // BR node for some reason doesn't always work (#1073). On Safari,\n        // the cursor sometimes inexplicable visually lags behind its\n        // reported position in such situations (#1092).\n        if ((gecko || safari) && anchor == head) {\n            let { node, offset } = anchorDOM;\n            if (isText(node)) {\n                brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n                // Issue #1128\n                if (brKludge && offset == node.nodeValue.length) {\n                    for (let scan = node, after; scan; scan = scan.parentNode) {\n                        if (after = scan.nextSibling) {\n                            if (after.nodeName == \"BR\")\n                                anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n                            break;\n                        }\n                        let desc = scan.pmViewDesc;\n                        if (desc && desc.node && desc.node.isBlock)\n                            break;\n                    }\n                }\n            }\n            else {\n                let prev = node.childNodes[offset - 1];\n                brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n            }\n        }\n        // Firefox can act strangely when the selection is in front of an\n        // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n        if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && isElt(selRange.focusNode)) {\n            let after = selRange.focusNode.childNodes[selRange.focusOffset];\n            if (after && after.contentEditable == \"false\")\n                force = true;\n        }\n        if (!(force || brKludge && safari) &&\n            isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n            isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n            return;\n        // Selection.extend can be used to create an 'inverted' selection\n        // (one where the focus is before the anchor), but not all\n        // browsers support it yet.\n        let domSelExtended = false;\n        if ((domSel.extend || anchor == head) && !(brKludge && gecko)) {\n            domSel.collapse(anchorDOM.node, anchorDOM.offset);\n            try {\n                if (anchor != head)\n                    domSel.extend(headDOM.node, headDOM.offset);\n                domSelExtended = true;\n            }\n            catch (_) {\n                // In some cases with Chrome the selection is empty after calling\n                // collapse, even when it should be valid. This appears to be a bug, but\n                // it is difficult to isolate. If this happens fallback to the old path\n                // without using extend.\n                // Similarly, this could crash on Safari if the editor is hidden, and\n                // there was no selection.\n            }\n        }\n        if (!domSelExtended) {\n            if (anchor > head) {\n                let tmp = anchorDOM;\n                anchorDOM = headDOM;\n                headDOM = tmp;\n            }\n            let range = document.createRange();\n            range.setEnd(headDOM.node, headDOM.offset);\n            range.setStart(anchorDOM.node, anchorDOM.offset);\n            domSel.removeAllRanges();\n            domSel.addRange(range);\n        }\n    }\n    ignoreMutation(mutation) {\n        return !this.contentDOM && mutation.type != \"selection\";\n    }\n    get contentLost() {\n        return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\n    }\n    // Remove a subtree of the element tree that has been touched\n    // by a DOM change, so that the next update will redraw it.\n    markDirty(from, to) {\n        for (let offset = 0, i = 0; i < this.children.length; i++) {\n            let child = this.children[i], end = offset + child.size;\n            if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n                let startInside = offset + child.border, endInside = end - child.border;\n                if (from >= startInside && to <= endInside) {\n                    this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n                    if (from == startInside && to == endInside &&\n                        (child.contentLost || child.dom.parentNode != this.contentDOM))\n                        child.dirty = NODE_DIRTY;\n                    else\n                        child.markDirty(from - startInside, to - startInside);\n                    return;\n                }\n                else {\n                    child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length\n                        ? CONTENT_DIRTY : NODE_DIRTY;\n                }\n            }\n            offset = end;\n        }\n        this.dirty = CONTENT_DIRTY;\n    }\n    markParentsDirty() {\n        let level = 1;\n        for (let node = this.parent; node; node = node.parent, level++) {\n            let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n            if (node.dirty < dirty)\n                node.dirty = dirty;\n        }\n    }\n    get domAtom() { return false; }\n    get ignoreForCoords() { return false; }\n    get ignoreForSelection() { return false; }\n    isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n    constructor(parent, widget, view, pos) {\n        let self, dom = widget.type.toDOM;\n        if (typeof dom == \"function\")\n            dom = dom(view, () => {\n                if (!self)\n                    return pos;\n                if (self.parent)\n                    return self.parent.posBeforeChild(self);\n            });\n        if (!widget.type.spec.raw) {\n            let elt = isElt(dom) ? dom : document.createElement(\"span\");\n            if (elt != dom) {\n                elt.appendChild(dom);\n                dom = elt;\n            }\n            if (!elt.hasAttribute(\"contenteditable\"))\n                elt.contentEditable = \"false\";\n            elt.classList.add(\"ProseMirror-widget\");\n        }\n        super(parent, [], dom, null);\n        this.widget = widget;\n        this.widget = widget;\n        self = this;\n    }\n    matchesWidget(widget) {\n        return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);\n    }\n    parseRule() { return { ignore: true }; }\n    stopEvent(event) {\n        let stop = this.widget.spec.stopEvent;\n        return stop ? stop(event) : false;\n    }\n    ignoreMutation(mutation) {\n        return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n    }\n    destroy() {\n        this.widget.type.destroy(this.dom);\n        super.destroy();\n    }\n    get domAtom() { return true; }\n    get ignoreForSelection() { return !!this.widget.type.spec.relaxedSide; }\n    get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n    constructor(parent, dom, textDOM, text) {\n        super(parent, [], dom, null);\n        this.textDOM = textDOM;\n        this.text = text;\n    }\n    get size() { return this.text.length; }\n    localPosFromDOM(dom, offset) {\n        if (dom != this.textDOM)\n            return this.posAtStart + (offset ? this.size : 0);\n        return this.posAtStart + offset;\n    }\n    domFromPos(pos) {\n        return { node: this.textDOM, offset: pos };\n    }\n    ignoreMutation(mut) {\n        return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;\n    }\n}\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nclass MarkViewDesc extends ViewDesc {\n    constructor(parent, mark, dom, contentDOM, spec) {\n        super(parent, [], dom, contentDOM);\n        this.mark = mark;\n        this.spec = spec;\n    }\n    static create(parent, mark, inline, view) {\n        let custom = view.nodeViews[mark.type.name];\n        let spec = custom && custom(mark, view, inline);\n        if (!spec || !spec.dom)\n            spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n        return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n    }\n    parseRule() {\n        if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView)\n            return null;\n        return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n    }\n    matchesMark(mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark); }\n    markDirty(from, to) {\n        super.markDirty(from, to);\n        // Move dirty info to nearest node view\n        if (this.dirty != NOT_DIRTY) {\n            let parent = this.parent;\n            while (!parent.node)\n                parent = parent.parent;\n            if (parent.dirty < this.dirty)\n                parent.dirty = this.dirty;\n            this.dirty = NOT_DIRTY;\n        }\n    }\n    slice(from, to, view) {\n        let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n        let nodes = this.children, size = this.size;\n        if (to < size)\n            nodes = replaceNodes(nodes, to, size, view);\n        if (from > 0)\n            nodes = replaceNodes(nodes, 0, from, view);\n        for (let i = 0; i < nodes.length; i++)\n            nodes[i].parent = copy;\n        copy.children = nodes;\n        return copy;\n    }\n    ignoreMutation(mutation) {\n        return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n    }\n    destroy() {\n        if (this.spec.destroy)\n            this.spec.destroy();\n        super.destroy();\n    }\n}\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nclass NodeViewDesc extends ViewDesc {\n    constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM) {\n        super(parent, [], dom, contentDOM);\n        this.node = node;\n        this.outerDeco = outerDeco;\n        this.innerDeco = innerDeco;\n        this.nodeDOM = nodeDOM;\n    }\n    // By default, a node is rendered using the `toDOM` method from the\n    // node type spec. But client code can use the `nodeViews` spec to\n    // supply a custom node view, which can influence various aspects of\n    // the way the node works.\n    //\n    // (Using subclassing for this was intentionally decided against,\n    // since it'd require exposing a whole slew of finicky\n    // implementation details to the user code that they probably will\n    // never need.)\n    static create(parent, node, outerDeco, innerDeco, view, pos) {\n        let custom = view.nodeViews[node.type.name], descObj;\n        let spec = custom && custom(node, view, () => {\n            // (This is a function that allows the custom view to find its\n            // own position)\n            if (!descObj)\n                return pos;\n            if (descObj.parent)\n                return descObj.parent.posBeforeChild(descObj);\n        }, outerDeco, innerDeco);\n        let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n        if (node.isText) {\n            if (!dom)\n                dom = document.createTextNode(node.text);\n            else if (!isText(dom))\n                throw new RangeError(\"Text must be rendered as a DOM text node\");\n        }\n        else if (!dom) {\n            let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n            ({ dom, contentDOM } = spec);\n        }\n        if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by <br contenteditable=false>\n            if (!dom.hasAttribute(\"contenteditable\"))\n                dom.contentEditable = \"false\";\n            if (node.type.spec.draggable)\n                dom.draggable = true;\n        }\n        let nodeDOM = dom;\n        dom = applyOuterDeco(dom, outerDeco, node);\n        if (spec)\n            return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec);\n        else if (node.isText)\n            return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM);\n        else\n            return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM);\n    }\n    parseRule(addedNodes) {\n        // Experimental kludge to allow opt-in re-parsing of nodes\n        if (this.node.type.spec.reparseInView)\n            return null;\n        // FIXME the assumption that this can always return the current\n        // attrs means that if the user somehow manages to change the\n        // attrs in the dom, that won't be picked up. Not entirely sure\n        // whether this is a problem\n        let rule = { node: this.node.type.name, attrs: this.node.attrs };\n        if (this.node.type.whitespace == \"pre\")\n            rule.preserveWhitespace = \"full\";\n        if (!this.contentDOM) {\n            rule.getContent = () => this.node.content;\n        }\n        else if (!this.contentLost) {\n            rule.contentElement = this.contentDOM;\n        }\n        else {\n            // Chrome likes to randomly recreate parent nodes when\n            // backspacing things. When that happens, this tries to find the\n            // new parent.\n            for (let i = this.children.length - 1; i >= 0; i--) {\n                let child = this.children[i];\n                if (this.dom.contains(child.dom.parentNode)) {\n                    rule.contentElement = child.dom.parentNode;\n                    break;\n                }\n            }\n            if (!rule.contentElement) {\n                let found = addedNodes &&\n                    addedNodes.find(n => isElt(n) && addedNodes.indexOf(n.parentNode) < 0 && this.dom.contains(n));\n                if (found)\n                    rule.contentElement = found;\n                else\n                    rule.getContent = () => Fragment.empty;\n            }\n        }\n        return rule;\n    }\n    matchesNode(node, outerDeco, innerDeco) {\n        return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n            sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);\n    }\n    get size() { return this.node.nodeSize; }\n    get border() { return this.node.isLeaf ? 0 : 1; }\n    // Syncs `this.children` to match `this.node.content` and the local\n    // decorations, possibly introducing nesting for marks. Then, in a\n    // separate step, syncs the DOM inside `this.contentDOM` to\n    // `this.children`.\n    updateChildren(view, pos) {\n        let inline = this.node.inlineContent, off = pos;\n        let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n        let localComposition = composition && composition.pos > -1 ? composition : null;\n        let compositionInChild = composition && composition.pos < 0;\n        let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n        let addBuffers = this.node.inlineContent, atBufferPos = addBuffers && this.node.isBlock;\n        iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n            if (widget.spec.marks)\n                updater.syncToMarks(widget.spec.marks, inline, view, i);\n            else if (widget.type.side >= 0 && !insideNode)\n                updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i);\n            // If the next node is a desc matching this widget, reuse it,\n            // otherwise insert the widget as a new view desc.\n            updater.placeWidget(widget, view, off);\n        }, (child, outerDeco, innerDeco, i) => {\n            // Make sure the wrapping mark descs match the node's marks.\n            updater.syncToMarks(child.marks, inline, view, i);\n            if (atBufferPos && child.isAtom && !child.isText)\n                updater.addHackNode(\"IMG\", updater.top);\n            // Try several strategies for drawing this node\n            let compIndex;\n            if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n            else if (compositionInChild && view.state.selection.from > off &&\n                view.state.selection.to < off + child.nodeSize &&\n                (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n                updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;\n            else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n            else {\n                // Add it as a new view\n                updater.addNode(child, outerDeco, innerDeco, view, off);\n            }\n            off += child.nodeSize;\n            if (addBuffers)\n                atBufferPos = child.isAtom && !child.isText;\n        });\n        // Drop all remaining descs after the current position.\n        updater.syncToMarks([], inline, view, 0);\n        if (this.node.isTextblock)\n            updater.addTextblockHacks();\n        updater.destroyRest();\n        // Sync the DOM if anything changed\n        if (updater.changed || this.dirty == CONTENT_DIRTY) {\n            // May have to protect focused DOM from being changed if a composition is active\n            if (localComposition)\n                this.protectLocalComposition(view, localComposition);\n            renderDescs(this.contentDOM, this.children, view);\n            if (ios)\n                iosHacks(this.dom);\n        }\n    }\n    localCompositionInfo(view, pos) {\n        // Only do something if both the selection and a focused text node\n        // are inside of this node\n        let { from, to } = view.state.selection;\n        if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n            return null;\n        let textNode = view.input.compositionNode;\n        if (!textNode || !this.dom.contains(textNode.parentNode))\n            return null;\n        if (this.node.inlineContent) {\n            // Find the text in the focused node in the node, stop if it's not\n            // there (may have been modified through other means, in which\n            // case it should overwritten)\n            let text = textNode.nodeValue;\n            let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n            return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n        }\n        else {\n            return { node: textNode, pos: -1, text: \"\" };\n        }\n    }\n    protectLocalComposition(view, { node, pos, text }) {\n        // The node is already part of a local view desc, leave it there\n        if (this.getDesc(node))\n            return;\n        // Create a composition view for the orphaned nodes\n        let topNode = node;\n        for (;; topNode = topNode.parentNode) {\n            if (topNode.parentNode == this.contentDOM)\n                break;\n            while (topNode.previousSibling)\n                topNode.parentNode.removeChild(topNode.previousSibling);\n            while (topNode.nextSibling)\n                topNode.parentNode.removeChild(topNode.nextSibling);\n            if (topNode.pmViewDesc)\n                topNode.pmViewDesc = undefined;\n        }\n        let desc = new CompositionViewDesc(this, topNode, node, text);\n        view.input.compositionNodes.push(desc);\n        // Patch up this.children to contain the composition view\n        this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n    }\n    // If this desc must be updated to match the given node decoration,\n    // do so and return true.\n    update(node, outerDeco, innerDeco, view) {\n        if (this.dirty == NODE_DIRTY ||\n            !node.sameMarkup(this.node))\n            return false;\n        this.updateInner(node, outerDeco, innerDeco, view);\n        return true;\n    }\n    updateInner(node, outerDeco, innerDeco, view) {\n        this.updateOuterDeco(outerDeco);\n        this.node = node;\n        this.innerDeco = innerDeco;\n        if (this.contentDOM)\n            this.updateChildren(view, this.posAtStart);\n        this.dirty = NOT_DIRTY;\n    }\n    updateOuterDeco(outerDeco) {\n        if (sameOuterDeco(outerDeco, this.outerDeco))\n            return;\n        let needsWrap = !isElt(this.nodeDOM);\n        let oldDOM = this.dom;\n        this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n        if (this.dom != oldDOM) {\n            oldDOM.pmViewDesc = undefined;\n            this.dom.pmViewDesc = this;\n        }\n        this.outerDeco = outerDeco;\n    }\n    // Mark this node as being the selected node.\n    selectNode() {\n        if (isElt(this.nodeDOM)) {\n            this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n            if (this.contentDOM || !this.node.type.spec.draggable)\n                this.nodeDOM.draggable = true;\n        }\n    }\n    // Remove selected node marking from this node.\n    deselectNode() {\n        if (isElt(this.nodeDOM)) {\n            this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n            if (this.contentDOM || !this.node.type.spec.draggable)\n                this.nodeDOM.removeAttribute(\"draggable\");\n        }\n    }\n    get domAtom() { return this.node.isAtom; }\n}\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n    applyOuterDeco(dom, outerDeco, doc);\n    let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom);\n    if (docView.contentDOM)\n        docView.updateChildren(view, 0);\n    return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n    constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM) {\n        super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM);\n    }\n    parseRule() {\n        let skip = this.nodeDOM.parentNode;\n        while (skip && skip != this.dom && !skip.pmIsDeco)\n            skip = skip.parentNode;\n        return { skip: (skip || true) };\n    }\n    update(node, outerDeco, innerDeco, view) {\n        if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n            !node.sameMarkup(this.node))\n            return false;\n        this.updateOuterDeco(outerDeco);\n        if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n            this.nodeDOM.nodeValue = node.text;\n            if (view.trackWrites == this.nodeDOM)\n                view.trackWrites = null;\n        }\n        this.node = node;\n        this.dirty = NOT_DIRTY;\n        return true;\n    }\n    inParent() {\n        let parentDOM = this.parent.contentDOM;\n        for (let n = this.nodeDOM; n; n = n.parentNode)\n            if (n == parentDOM)\n                return true;\n        return false;\n    }\n    domFromPos(pos) {\n        return { node: this.nodeDOM, offset: pos };\n    }\n    localPosFromDOM(dom, offset, bias) {\n        if (dom == this.nodeDOM)\n            return this.posAtStart + Math.min(offset, this.node.text.length);\n        return super.localPosFromDOM(dom, offset, bias);\n    }\n    ignoreMutation(mutation) {\n        return mutation.type != \"characterData\" && mutation.type != \"selection\";\n    }\n    slice(from, to, _view) {\n        let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n        return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom);\n    }\n    markDirty(from, to) {\n        super.markDirty(from, to);\n        if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))\n            this.dirty = NODE_DIRTY;\n    }\n    get domAtom() { return false; }\n    isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag extra BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass BufferHackViewDesc extends ViewDesc {\n    parseRule() { return { ignore: true }; }\n    matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; }\n    get domAtom() { return true; }\n    get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\n}\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nclass CustomNodeViewDesc extends NodeViewDesc {\n    constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec) {\n        super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM);\n        this.spec = spec;\n    }\n    // A custom `update` method gets to decide whether the update goes\n    // through. If it does, and there's a `contentDOM` node, our logic\n    // updates the children.\n    update(node, outerDeco, innerDeco, view) {\n        if (this.dirty == NODE_DIRTY)\n            return false;\n        if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n            let result = this.spec.update(node, outerDeco, innerDeco);\n            if (result)\n                this.updateInner(node, outerDeco, innerDeco, view);\n            return result;\n        }\n        else if (!this.contentDOM && !node.isLeaf) {\n            return false;\n        }\n        else {\n            return super.update(node, outerDeco, innerDeco, view);\n        }\n    }\n    selectNode() {\n        this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n    }\n    deselectNode() {\n        this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n    }\n    setSelection(anchor, head, view, force) {\n        this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root)\n            : super.setSelection(anchor, head, view, force);\n    }\n    destroy() {\n        if (this.spec.destroy)\n            this.spec.destroy();\n        super.destroy();\n    }\n    stopEvent(event) {\n        return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n    }\n    ignoreMutation(mutation) {\n        return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n    }\n}\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n    let dom = parentDOM.firstChild, written = false;\n    for (let i = 0; i < descs.length; i++) {\n        let desc = descs[i], childDOM = desc.dom;\n        if (childDOM.parentNode == parentDOM) {\n            while (childDOM != dom) {\n                dom = rm(dom);\n                written = true;\n            }\n            dom = dom.nextSibling;\n        }\n        else {\n            written = true;\n            parentDOM.insertBefore(childDOM, dom);\n        }\n        if (desc instanceof MarkViewDesc) {\n            let pos = dom ? dom.previousSibling : parentDOM.lastChild;\n            renderDescs(desc.contentDOM, desc.children, view);\n            dom = pos ? pos.nextSibling : parentDOM.firstChild;\n        }\n    }\n    while (dom) {\n        dom = rm(dom);\n        written = true;\n    }\n    if (written && view.trackWrites == parentDOM)\n        view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n    if (nodeName)\n        this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n    if (outerDeco.length == 0)\n        return noDeco;\n    let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n    for (let i = 0; i < outerDeco.length; i++) {\n        let attrs = outerDeco[i].type.attrs;\n        if (!attrs)\n            continue;\n        if (attrs.nodeName)\n            result.push(top = new OuterDecoLevel(attrs.nodeName));\n        for (let name in attrs) {\n            let val = attrs[name];\n            if (val == null)\n                continue;\n            if (needsWrap && result.length == 1)\n                result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n            if (name == \"class\")\n                top.class = (top.class ? top.class + \" \" : \"\") + val;\n            else if (name == \"style\")\n                top.style = (top.style ? top.style + \";\" : \"\") + val;\n            else if (name != \"nodeName\")\n                top[name] = val;\n        }\n    }\n    return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n    // Shortcut for trivial case\n    if (prevComputed == noDeco && curComputed == noDeco)\n        return nodeDOM;\n    let curDOM = nodeDOM;\n    for (let i = 0; i < curComputed.length; i++) {\n        let deco = curComputed[i], prev = prevComputed[i];\n        if (i) {\n            let parent;\n            if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n                (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n                curDOM = parent;\n            }\n            else {\n                parent = document.createElement(deco.nodeName);\n                parent.pmIsDeco = true;\n                parent.appendChild(curDOM);\n                prev = noDeco[0];\n                curDOM = parent;\n            }\n        }\n        patchAttributes(curDOM, prev || noDeco[0], deco);\n    }\n    return curDOM;\n}\nfunction patchAttributes(dom, prev, cur) {\n    for (let name in prev)\n        if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n            dom.removeAttribute(name);\n    for (let name in cur)\n        if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n            dom.setAttribute(name, cur[name]);\n    if (prev.class != cur.class) {\n        let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n        let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n        for (let i = 0; i < prevList.length; i++)\n            if (curList.indexOf(prevList[i]) == -1)\n                dom.classList.remove(prevList[i]);\n        for (let i = 0; i < curList.length; i++)\n            if (prevList.indexOf(curList[i]) == -1)\n                dom.classList.add(curList[i]);\n        if (dom.classList.length == 0)\n            dom.removeAttribute(\"class\");\n    }\n    if (prev.style != cur.style) {\n        if (prev.style) {\n            let prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n            while (m = prop.exec(prev.style))\n                dom.style.removeProperty(m[1]);\n        }\n        if (cur.style)\n            dom.style.cssText += cur.style;\n    }\n}\nfunction applyOuterDeco(dom, deco, node) {\n    return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, !isElt(dom)));\n}\nfunction sameOuterDeco(a, b) {\n    if (a.length != b.length)\n        return false;\n    for (let i = 0; i < a.length; i++)\n        if (!a[i].type.eq(b[i].type))\n            return false;\n    return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n    let next = dom.nextSibling;\n    dom.parentNode.removeChild(dom);\n    return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n    constructor(top, lock, view) {\n        this.lock = lock;\n        this.view = view;\n        // Index into `this.top`'s child array, represents the current\n        // update position.\n        this.index = 0;\n        // When entering a mark, the current top and index are pushed\n        // onto this.\n        this.stack = [];\n        // Tracks whether anything was changed\n        this.changed = false;\n        this.top = top;\n        this.preMatch = preMatch(top.node.content, top);\n    }\n    // Destroy and remove the children between the given indices in\n    // `this.top`.\n    destroyBetween(start, end) {\n        if (start == end)\n            return;\n        for (let i = start; i < end; i++)\n            this.top.children[i].destroy();\n        this.top.children.splice(start, end - start);\n        this.changed = true;\n    }\n    // Destroy all remaining children in `this.top`.\n    destroyRest() {\n        this.destroyBetween(this.index, this.top.children.length);\n    }\n    // Sync the current stack of mark descs with the given array of\n    // marks, reusing existing mark descs when possible.\n    syncToMarks(marks, inline, view, parentIndex) {\n        let keep = 0, depth = this.stack.length >> 1;\n        let maxKeep = Math.min(depth, marks.length);\n        while (keep < maxKeep &&\n            (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n                .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n            keep++;\n        while (keep < depth) {\n            this.destroyRest();\n            this.top.dirty = NOT_DIRTY;\n            this.index = this.stack.pop();\n            this.top = this.stack.pop();\n            depth--;\n        }\n        while (depth < marks.length) {\n            this.stack.push(this.top, this.index + 1);\n            let found = -1, scanTo = this.top.children.length;\n            if (parentIndex < this.preMatch.index)\n                scanTo = Math.min(this.index + 3, scanTo);\n            for (let i = this.index; i < scanTo; i++) {\n                let next = this.top.children[i];\n                if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n                    found = i;\n                    break;\n                }\n            }\n            // When nothing matches, try to update the mark view at this position\n            // in place, so a custom mark view can adapt to a changed mark without\n            // re-creating its DOM.\n            if (found < 0 && this.index < this.top.children.length) {\n                let cur = this.top.children[this.index];\n                if (cur instanceof MarkViewDesc && cur.dirty != NODE_DIRTY &&\n                    cur.mark.type == marks[depth].type && cur.spec.update &&\n                    !this.isLocked(cur.dom) && cur.spec.update(marks[depth])) {\n                    cur.mark = marks[depth];\n                    found = this.index;\n                    this.changed = true;\n                }\n            }\n            if (found > -1) {\n                if (found > this.index) {\n                    this.changed = true;\n                    this.destroyBetween(this.index, found);\n                }\n                this.top = this.top.children[this.index];\n            }\n            else {\n                let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n                this.top.children.splice(this.index, 0, markDesc);\n                this.top = markDesc;\n                this.changed = true;\n            }\n            this.index = 0;\n            depth++;\n        }\n    }\n    // Try to find a node desc matching the given data. Skip over it and\n    // return true when successful.\n    findNodeMatch(node, outerDeco, innerDeco, index) {\n        let found = -1, targetDesc;\n        if (index >= this.preMatch.index &&\n            (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n            targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n            found = this.top.children.indexOf(targetDesc, this.index);\n        }\n        else {\n            for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n                let child = this.top.children[i];\n                if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n                    found = i;\n                    break;\n                }\n            }\n        }\n        if (found < 0)\n            return false;\n        this.destroyBetween(this.index, found);\n        this.index++;\n        return true;\n    }\n    updateNodeAt(node, outerDeco, innerDeco, index, view) {\n        let child = this.top.children[index];\n        if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)\n            child.dirty = CONTENT_DIRTY;\n        if (!child.update(node, outerDeco, innerDeco, view))\n            return false;\n        this.destroyBetween(this.index, index);\n        this.index++;\n        return true;\n    }\n    findIndexWithChild(domNode) {\n        for (;;) {\n            let parent = domNode.parentNode;\n            if (!parent)\n                return -1;\n            if (parent == this.top.contentDOM) {\n                let desc = domNode.pmViewDesc;\n                if (desc)\n                    for (let i = this.index; i < this.top.children.length; i++) {\n                        if (this.top.children[i] == desc)\n                            return i;\n                    }\n                return -1;\n            }\n            domNode = parent;\n        }\n    }\n    // Try to update the next node, if any, to the given data. Checks\n    // pre-matches to avoid overwriting nodes that could still be used.\n    updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n        for (let i = this.index; i < this.top.children.length; i++) {\n            let next = this.top.children[i];\n            if (next instanceof NodeViewDesc) {\n                let preMatch = this.preMatch.matched.get(next);\n                if (preMatch != null && preMatch != index)\n                    return false;\n                let nextDOM = next.dom, updated;\n                // Can't update if nextDOM is or contains this.lock, except if\n                // it's a text node whose content already matches the new text\n                // and whose decorations match the new ones.\n                let locked = this.isLocked(nextDOM) &&\n                    !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n                        next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n                if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n                    this.destroyBetween(this.index, i);\n                    if (next.dom != nextDOM)\n                        this.changed = true;\n                    this.index++;\n                    return true;\n                }\n                else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n                    this.destroyBetween(this.index, i);\n                    this.top.children[this.index] = updated;\n                    if (updated.contentDOM) {\n                        updated.dirty = CONTENT_DIRTY;\n                        updated.updateChildren(view, pos + 1);\n                        updated.dirty = NOT_DIRTY;\n                    }\n                    this.changed = true;\n                    this.index++;\n                    return true;\n                }\n                break;\n            }\n        }\n        return false;\n    }\n    // When a node with content is replaced by a different node with\n    // identical content, move over its children.\n    recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n        if (next.dirty || node.isAtom || !next.children.length ||\n            !next.node.content.eq(node.content) ||\n            !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n            return null;\n        let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n        if (wrapper.contentDOM) {\n            wrapper.children = next.children;\n            next.children = [];\n            for (let ch of wrapper.children)\n                ch.parent = wrapper;\n        }\n        next.destroy();\n        return wrapper;\n    }\n    // Insert the node as a newly created node desc.\n    addNode(node, outerDeco, innerDeco, view, pos) {\n        let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n        if (desc.contentDOM)\n            desc.updateChildren(view, pos + 1);\n        this.top.children.splice(this.index++, 0, desc);\n        this.changed = true;\n    }\n    placeWidget(widget, view, pos) {\n        let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n        if (next && next.matchesWidget(widget) &&\n            (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n            this.index++;\n        }\n        else {\n            let desc = new WidgetViewDesc(this.top, widget, view, pos);\n            this.top.children.splice(this.index++, 0, desc);\n            this.changed = true;\n        }\n    }\n    // Make sure a textblock looks and behaves correctly in\n    // contentEditable.\n    addTextblockHacks() {\n        let lastChild = this.top.children[this.index - 1], parent = this.top;\n        while (lastChild instanceof MarkViewDesc) {\n            parent = lastChild;\n            lastChild = parent.children[parent.children.length - 1];\n        }\n        if (!lastChild || // Empty textblock\n            !(lastChild instanceof TextViewDesc) ||\n            /\\n$/.test(lastChild.node.text) ||\n            (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n            // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n            if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n                this.addHackNode(\"IMG\", parent);\n            this.addHackNode(\"BR\", this.top);\n        }\n    }\n    addHackNode(nodeName, parent) {\n        if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n            this.index++;\n        }\n        else {\n            let dom = document.createElement(nodeName);\n            if (nodeName == \"IMG\") {\n                dom.className = \"ProseMirror-separator\";\n                dom.alt = \"\";\n            }\n            if (nodeName == \"BR\")\n                dom.className = \"ProseMirror-trailingBreak\";\n            let hack = new BufferHackViewDesc(this.top, [], dom, null);\n            if (parent != this.top)\n                parent.children.push(hack);\n            else\n                parent.children.splice(this.index++, 0, hack);\n            this.changed = true;\n        }\n    }\n    isLocked(node) {\n        return this.lock && (node == this.lock || isElt(node) && node.contains(this.lock.parentNode));\n    }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes.\nfunction preMatch(frag, parentDesc) {\n    let curDesc = parentDesc, descI = curDesc.children.length;\n    let fI = frag.childCount, matched = new Map, matches = [];\n    outer: while (fI > 0) {\n        let desc;\n        for (;;) {\n            if (descI) {\n                let next = curDesc.children[descI - 1];\n                if (next instanceof MarkViewDesc) {\n                    curDesc = next;\n                    descI = next.children.length;\n                }\n                else {\n                    desc = next;\n                    descI--;\n                    break;\n                }\n            }\n            else if (curDesc == parentDesc) {\n                break outer;\n            }\n            else {\n                descI = curDesc.parent.children.indexOf(curDesc);\n                curDesc = curDesc.parent;\n            }\n        }\n        let node = desc.node;\n        if (!node)\n            continue;\n        if (node != frag.child(fI - 1))\n            break;\n        --fI;\n        matched.set(desc, fI);\n        matches.push(desc);\n    }\n    return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n    return a.type.side - b.type.side;\n}\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n    let locals = deco.locals(parent), offset = 0;\n    // Simple, cheap variant for when there are no local decorations\n    if (locals.length == 0) {\n        for (let i = 0; i < parent.childCount; i++) {\n            let child = parent.child(i);\n            onNode(child, locals, deco.forChild(offset, child), i);\n            offset += child.nodeSize;\n        }\n        return;\n    }\n    let decoIndex = 0, active = [], restNode = null;\n    for (let parentIndex = 0;;) {\n        let widget, widgets;\n        while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n            let next = locals[decoIndex++];\n            if (next.widget) {\n                if (!widget)\n                    widget = next;\n                else\n                    (widgets || (widgets = [widget])).push(next);\n            }\n        }\n        if (widget) {\n            if (widgets) {\n                widgets.sort(compareSide);\n                for (let i = 0; i < widgets.length; i++)\n                    onWidget(widgets[i], parentIndex, !!restNode);\n            }\n            else {\n                onWidget(widget, parentIndex, !!restNode);\n            }\n        }\n        let child, index;\n        if (restNode) {\n            index = -1;\n            child = restNode;\n            restNode = null;\n        }\n        else if (parentIndex < parent.childCount) {\n            index = parentIndex;\n            child = parent.child(parentIndex++);\n        }\n        else {\n            break;\n        }\n        for (let i = 0; i < active.length; i++)\n            if (active[i].to <= offset)\n                active.splice(i--, 1);\n        while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n            active.push(locals[decoIndex++]);\n        let end = offset + child.nodeSize;\n        if (child.isText) {\n            let cutAt = end;\n            if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n                cutAt = locals[decoIndex].from;\n            for (let i = 0; i < active.length; i++)\n                if (active[i].to < cutAt)\n                    cutAt = active[i].to;\n            if (cutAt < end) {\n                restNode = child.cut(cutAt - offset);\n                child = child.cut(0, cutAt - offset);\n                end = cutAt;\n                index = -1;\n            }\n        }\n        else {\n            while (decoIndex < locals.length && locals[decoIndex].to < end)\n                decoIndex++;\n        }\n        let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n        onNode(child, outerDeco, deco.forChild(offset, child), index);\n        offset = end;\n    }\n}\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n    if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n        let oldCSS = dom.style.cssText;\n        dom.style.cssText = oldCSS + \"; list-style: square !important\";\n        window.getComputedStyle(dom).listStyle;\n        dom.style.cssText = oldCSS;\n    }\n}\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n    for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n        let child = frag.child(i++), childStart = pos;\n        pos += child.nodeSize;\n        if (!child.isText)\n            continue;\n        let str = child.text;\n        while (i < frag.childCount) {\n            let next = frag.child(i++);\n            pos += next.nodeSize;\n            if (!next.isText)\n                break;\n            str += next.text;\n        }\n        if (pos >= from) {\n            if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n                return to - text.length;\n            let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n            if (found >= 0 && found + text.length + childStart >= from)\n                return childStart + found;\n            if (from == to && str.length >= (to + text.length) - childStart &&\n                str.slice(to - childStart, to - childStart + text.length) == text)\n                return to;\n        }\n    }\n    return -1;\n}\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n    let result = [];\n    for (let i = 0, off = 0; i < nodes.length; i++) {\n        let child = nodes[i], start = off, end = off += child.size;\n        if (start >= to || end <= from) {\n            result.push(child);\n        }\n        else {\n            if (start < from)\n                result.push(child.slice(0, from - start, view));\n            if (replacement) {\n                result.push(replacement);\n                replacement = undefined;\n            }\n            if (end > to)\n                result.push(child.slice(to - start, child.size, view));\n        }\n    }\n    return result;\n}\n\nfunction selectionFromDOM(view, origin = null) {\n    let domSel = view.domSelectionRange(), doc = view.state.doc;\n    if (!domSel.focusNode)\n        return null;\n    let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n    let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n    if (head < 0)\n        return null;\n    let $head = doc.resolve(head), anchor, selection;\n    if (selectionCollapsed(domSel)) {\n        anchor = head;\n        while (nearestDesc && !nearestDesc.node)\n            nearestDesc = nearestDesc.parent;\n        if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) &&\n            nearestDesc.parent &&\n            !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n            let pos = nearestDesc.posBefore;\n            selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n        }\n        else if (gecko && origin == \"key\" && head > view.state.selection.to &&\n            isElt(domSel.focusNode) && domSel.focusOffset == domSel.focusNode.childNodes.length &&\n            nearestDesc && nearestDesc.posAtStart > view.state.selection.to) {\n            // Firefox will jump across scrollable wrapper nodes on keyboard\n            // cursor motion (#1594). This tries to detect this situation\n            // and work around it.\n            for (let scan = domSel.focusNode;; scan = scan.parentNode) {\n                if (getComputedStyle(scan).overflow != \"visible\") {\n                    selection = Selection.findFrom(doc.resolve(nearestDesc.posAtStart), 1);\n                    break;\n                }\n                if (scan == nearestDesc.dom || scan.nextSibling || !scan.parentNode || !isElt(scan.parentNode))\n                    break;\n            }\n        }\n    }\n    else {\n        if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n            let min = head, max = head;\n            for (let i = 0; i < domSel.rangeCount; i++) {\n                let range = domSel.getRangeAt(i);\n                min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n                max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n            }\n            if (min < 0)\n                return null;\n            [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n            $head = doc.resolve(head);\n        }\n        else {\n            anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n        }\n        if (anchor < 0)\n            return null;\n    }\n    let $anchor = doc.resolve(anchor);\n    if (!selection) {\n        let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n        selection = selectionBetween(view, $anchor, $head, bias);\n    }\n    return selection;\n}\nfunction editorOwnsSelection(view) {\n    return view.editable ? view.hasFocus() :\n        hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);\n}\nfunction selectionToDOM(view, force = false) {\n    let sel = view.state.selection;\n    syncNodeSelection(view, sel);\n    if (!editorOwnsSelection(view))\n        return;\n    // Need to delay selection normalization during a native selection\n    // drag on Chrome, or it will cause further dragging to glitch.\n    let mouseDown = view.input.mouseDown;\n    if (!force && chrome && mouseDown) {\n        let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;\n        if (domSel.anchorNode && curSel.anchorNode &&\n            isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset) &&\n            mouseDown.delaySelUpdate()) {\n            view.domObserver.setCurSelection();\n            return;\n        }\n    }\n    view.domObserver.disconnectSelection();\n    if (view.cursorWrapper) {\n        selectCursorWrapper(view);\n    }\n    else {\n        let { anchor, head } = sel, resetEditableFrom, resetEditableTo;\n        if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n            if (!sel.$from.parent.inlineContent)\n                resetEditableFrom = temporarilyEditableNear(view, sel.from);\n            if (!sel.empty && !sel.$from.parent.inlineContent)\n                resetEditableTo = temporarilyEditableNear(view, sel.to);\n        }\n        view.docView.setSelection(anchor, head, view, force);\n        if (brokenSelectBetweenUneditable) {\n            if (resetEditableFrom)\n                resetEditable(resetEditableFrom);\n            if (resetEditableTo)\n                resetEditable(resetEditableTo);\n        }\n        if (sel.visible) {\n            view.dom.classList.remove(\"ProseMirror-hideselection\");\n        }\n        else {\n            view.dom.classList.add(\"ProseMirror-hideselection\");\n            if (\"onselectionchange\" in document)\n                removeClassOnSelectionChange(view);\n        }\n    }\n    view.domObserver.setCurSelection();\n    view.domObserver.connectSelection();\n}\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n    let { node, offset } = view.docView.domFromPos(pos, 0);\n    let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n    let before = offset ? node.childNodes[offset - 1] : null;\n    if (safari && after && after.contentEditable == \"false\")\n        return setEditable(after);\n    if ((!after || after.contentEditable == \"false\") &&\n        (!before || before.contentEditable == \"false\")) {\n        if (after)\n            return setEditable(after);\n        else if (before)\n            return setEditable(before);\n    }\n}\nfunction setEditable(element) {\n    element.contentEditable = \"true\";\n    if (safari && element.draggable) {\n        element.draggable = false;\n        element.wasDraggable = true;\n    }\n    return element;\n}\nfunction resetEditable(element) {\n    element.contentEditable = \"false\";\n    if (element.wasDraggable) {\n        element.draggable = true;\n        element.wasDraggable = null;\n    }\n}\nfunction removeClassOnSelectionChange(view) {\n    let doc = view.dom.ownerDocument;\n    doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n    let domSel = view.domSelectionRange();\n    let node = domSel.anchorNode, offset = domSel.anchorOffset;\n    doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n        if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n            doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n            setTimeout(() => {\n                if (!editorOwnsSelection(view) || view.state.selection.visible)\n                    view.dom.classList.remove(\"ProseMirror-hideselection\");\n            }, 20);\n        }\n    });\n}\nfunction selectCursorWrapper(view) {\n    let domSel = view.domSelection();\n    if (!domSel)\n        return;\n    let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n    if (img)\n        domSel.collapse(node.parentNode, domIndex(node) + 1);\n    else\n        domSel.collapse(node, 0);\n    // Kludge to kill 'control selection' in IE11 when selecting an\n    // invisible cursor wrapper, since that would result in those weird\n    // resize handles and a selection that considers the absolutely\n    // positioned wrapper, rather than the root editable node, the\n    // focused element.\n    if (!img && !view.state.selection.visible && ie && ie_version <= 11) {\n        node.disabled = true;\n        node.disabled = false;\n    }\n}\nfunction syncNodeSelection(view, sel) {\n    if (sel instanceof NodeSelection) {\n        let desc = view.docView.descAt(sel.from);\n        if (desc != view.lastSelectedViewDesc) {\n            clearNodeSelection(view);\n            if (desc)\n                desc.selectNode();\n            view.lastSelectedViewDesc = desc;\n        }\n    }\n    else {\n        clearNodeSelection(view);\n    }\n}\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n    if (view.lastSelectedViewDesc) {\n        if (view.lastSelectedViewDesc.parent)\n            view.lastSelectedViewDesc.deselectNode();\n        view.lastSelectedViewDesc = undefined;\n    }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n    return view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n        || TextSelection.between($anchor, $head, bias);\n}\nfunction hasFocusAndSelection(view) {\n    if (view.editable && !view.hasFocus())\n        return false;\n    return hasSelection(view);\n}\nfunction hasSelection(view) {\n    let sel = view.domSelectionRange();\n    if (!sel.anchorNode)\n        return false;\n    try {\n        // Firefox will raise 'permission denied' errors when accessing\n        // properties of `sel.anchorNode` when it's in a generated CSS\n        // element.\n        return contains(view.dom, sel.anchorNode) && (view.editable || contains(view.dom, sel.focusNode));\n    }\n    catch (_) {\n        return false;\n    }\n}\nfunction anchorInRightPlace(view) {\n    let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);\n    let domSel = view.domSelectionRange();\n    return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);\n}\n\nfunction moveSelectionBlock(state, dir) {\n    let { $anchor, $head } = state.selection;\n    let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n    let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n    return $start && Selection.findFrom($start, dir);\n}\nfunction apply(view, sel) {\n    view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n    return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n    let sel = view.state.selection;\n    if (sel instanceof TextSelection) {\n        if (mods.indexOf(\"s\") > -1) {\n            let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n            if (!node || node.isText || !node.isLeaf)\n                return false;\n            let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n            return apply(view, new TextSelection(sel.$anchor, $newHead));\n        }\n        else if (!sel.empty) {\n            return false;\n        }\n        else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n            let next = moveSelectionBlock(view.state, dir);\n            if (next && (next instanceof NodeSelection))\n                return apply(view, next);\n            return false;\n        }\n        else if (!mac || mods.indexOf(\"m\") < 0) {\n            let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n            if (!node || node.isText)\n                return false;\n            let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n            if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n                return false;\n            if (NodeSelection.isSelectable(node)) {\n                return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));\n            }\n            else {\n                // Chrome and Safari will introduce extra pointless cursor\n                // positions around inline uneditable nodes (#937), and\n                // Firefox will sometimes just plain refuse to move across\n                // them (#1592), so in this situation we move the cursor\n                // ourselves.\n                return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n            }\n        }\n    }\n    else if (sel instanceof NodeSelection && sel.node.isInline) {\n        return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n    }\n    else {\n        let next = moveSelectionBlock(view.state, dir);\n        if (next)\n            return apply(view, next);\n        return false;\n    }\n}\nfunction isIgnorable(dom, dir) {\n    let desc = dom.pmViewDesc;\n    return desc ? desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\")\n        : isElt(dom) && dom.contentEditable == \"false\";\n}\nfunction skipIgnoredNodes(view, dir) {\n    return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\n}\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesBefore(view) {\n    let sel = view.domSelectionRange();\n    let node = sel.focusNode, offset = sel.focusOffset;\n    if (!node)\n        return;\n    let moveNode, moveOffset, force = false;\n    // Gecko will do odd things when the selection is directly in front\n    // of a non-editable node, so in that case, move it into the next\n    // node if possible. Issue prosemirror/prosemirror#832.\n    if (gecko && isElt(node) && offset < nodeSize(node) && isIgnorable(node.childNodes[offset], -1))\n        force = true;\n    for (;;) {\n        if (offset > 0) {\n            if (!isElt(node))\n                break;\n            let before = node.childNodes[offset - 1];\n            if (isIgnorable(before, -1)) {\n                moveNode = node;\n                moveOffset = --offset;\n            }\n            else if (isText(before)) {\n                node = before;\n                offset = node.nodeValue.length;\n            }\n            else {\n                break;\n            }\n        }\n        else if (isBlockNode(node)) {\n            break;\n        }\n        else {\n            let prev = node.previousSibling;\n            while (prev && isIgnorable(prev, -1)) {\n                moveNode = node.parentNode;\n                moveOffset = domIndex(prev);\n                prev = prev.previousSibling;\n            }\n            if (!prev) {\n                node = node.parentNode;\n                if (node == view.dom)\n                    break;\n                offset = 0;\n            }\n            else {\n                node = prev;\n                offset = nodeSize(node);\n            }\n        }\n    }\n    if (force)\n        setSelFocus(view, node, offset);\n    else if (moveNode)\n        setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n    let sel = view.domSelectionRange();\n    let node = sel.focusNode, offset = sel.focusOffset;\n    if (!node)\n        return;\n    let len = nodeSize(node);\n    let moveNode, moveOffset;\n    for (;;) {\n        if (offset < len) {\n            if (!isElt(node))\n                break;\n            let after = node.childNodes[offset];\n            if (isIgnorable(after, 1)) {\n                moveNode = node;\n                moveOffset = ++offset;\n            }\n            else {\n                break;\n            }\n        }\n        else if (isBlockNode(node)) {\n            break;\n        }\n        else {\n            let next = node.nextSibling;\n            while (next && isIgnorable(next, 1)) {\n                moveNode = next.parentNode;\n                moveOffset = domIndex(next) + 1;\n                next = next.nextSibling;\n            }\n            if (!next) {\n                node = node.parentNode;\n                if (node == view.dom)\n                    break;\n                offset = len = 0;\n            }\n            else {\n                node = next;\n                offset = 0;\n                len = nodeSize(node);\n            }\n        }\n    }\n    if (moveNode)\n        setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n    let desc = dom.pmViewDesc;\n    return desc && desc.node && desc.node.isBlock;\n}\nfunction textNodeAfter(node, offset) {\n    while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {\n        offset = domIndex(node) + 1;\n        node = node.parentNode;\n    }\n    while (node && offset < node.childNodes.length) {\n        let next = node.childNodes[offset];\n        if (isText(next))\n            return next;\n        if (isElt(next) && next.contentEditable == \"false\")\n            break;\n        node = next;\n        offset = 0;\n    }\n}\nfunction textNodeBefore(node, offset) {\n    while (node && !offset && !hasBlockDesc(node)) {\n        offset = domIndex(node);\n        node = node.parentNode;\n    }\n    while (node && offset) {\n        let next = node.childNodes[offset - 1];\n        if (isText(next))\n            return next;\n        if (isElt(next) && next.contentEditable == \"false\")\n            break;\n        node = next;\n        offset = node.childNodes.length;\n    }\n}\nfunction setSelFocus(view, node, offset) {\n    if (!isText(node)) {\n        let before, after;\n        if (after = textNodeAfter(node, offset)) {\n            node = after;\n            offset = 0;\n        }\n        else if (before = textNodeBefore(node, offset)) {\n            node = before;\n            offset = before.nodeValue.length;\n        }\n    }\n    let sel = view.domSelection(), range = view.domSelectionRange();\n    if (!sel)\n        return;\n    if (selectionCollapsed(range)) {\n        sel.collapse(node, offset);\n    }\n    else if (sel.extend) {\n        sel.collapse(range.anchorNode, range.anchorOffset);\n        sel.extend(node, offset);\n    }\n    view.domObserver.setCurSelection();\n    let { state } = view;\n    // If no state update ends up happening, reset the selection.\n    setTimeout(() => {\n        if (view.state == state)\n            selectionToDOM(view);\n    }, 50);\n}\nfunction findDirection(view, pos) {\n    let $pos = view.state.doc.resolve(pos);\n    if (!(chrome || windows) && $pos.parent.inlineContent) {\n        let coords = view.coordsAtPos(pos);\n        if (pos > $pos.start()) {\n            let before = view.coordsAtPos(pos - 1);\n            let mid = (before.top + before.bottom) / 2;\n            if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n                return before.left < coords.left ? \"ltr\" : \"rtl\";\n        }\n        if (pos < $pos.end()) {\n            let after = view.coordsAtPos(pos + 1);\n            let mid = (after.top + after.bottom) / 2;\n            if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n                return after.left > coords.left ? \"ltr\" : \"rtl\";\n        }\n    }\n    let block = view.dom;\n    for (let d = $pos.depth; d > 0; d--)\n        if ($pos.node(d).isBlock) {\n            block = view.nodeDOM($pos.before(d)) || block;\n            break;\n        }\n    let computed = getComputedStyle(block).direction;\n    return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n    let sel = view.state.selection;\n    if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n        return false;\n    if (mac && mods.indexOf(\"m\") > -1)\n        return false;\n    let { $from, $to } = sel;\n    if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n        let next = moveSelectionBlock(view.state, dir);\n        if (next && (next instanceof NodeSelection))\n            return apply(view, next);\n    }\n    if (!$from.parent.inlineContent) {\n        let side = dir < 0 ? $from : $to;\n        let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n        return beyond ? apply(view, beyond) : false;\n    }\n    return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n    if (!(view.state.selection instanceof TextSelection))\n        return true;\n    let { $head, $anchor, empty } = view.state.selection;\n    if (!$head.sameParent($anchor))\n        return true;\n    if (!empty)\n        return false;\n    if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n        return true;\n    let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n    if (nextNode && !nextNode.isText) {\n        let tr = view.state.tr;\n        if (dir < 0)\n            tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n        else\n            tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n        view.dispatch(tr);\n        return true;\n    }\n    return false;\n}\nfunction switchEditable(view, node, state) {\n    view.domObserver.stop();\n    node.contentEditable = state;\n    view.domObserver.start();\n}\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n    if (!safari || view.state.selection.$head.parentOffset > 0)\n        return false;\n    let { focusNode, focusOffset } = view.domSelectionRange();\n    if (focusNode && isElt(focusNode) && focusOffset == 0 &&\n        focusNode.firstChild && isElt(focusNode.firstChild) && focusNode.firstChild.contentEditable == \"false\") {\n        let child = focusNode.firstChild;\n        switchEditable(view, child, \"true\");\n        setTimeout(() => switchEditable(view, child, \"false\"), 20);\n    }\n    return false;\n}\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\nfunction getMods(event) {\n    let result = \"\";\n    if (event.ctrlKey)\n        result += \"c\";\n    if (event.metaKey)\n        result += \"m\";\n    if (event.altKey)\n        result += \"a\";\n    if (event.shiftKey)\n        result += \"s\";\n    return result;\n}\nfunction captureKeyDown(view, event) {\n    let code = event.keyCode, mods = getMods(event);\n    if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n        return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n    }\n    else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n        return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n    }\n    else if (code == 13 || code == 27) { // Enter, Esc\n        return true;\n    }\n    else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n        let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n        return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n    }\n    else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n        let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n        return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n    }\n    else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n        return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n    }\n    else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n        return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n    }\n    else if (mods == (mac ? \"m\" : \"c\") &&\n        (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n        return true;\n    }\n    return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n    view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n    let context = [], { content, openStart, openEnd } = slice;\n    while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n        openStart--;\n        openEnd--;\n        let node = content.firstChild;\n        context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n        content = node.content;\n    }\n    let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n    let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n    wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n    let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n    while (firstChild && isElt(firstChild) && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n        for (let i = needsWrap.length - 1; i >= 0; i--) {\n            let wrapper = doc.createElement(needsWrap[i]);\n            while (wrap.firstChild)\n                wrapper.appendChild(wrap.firstChild);\n            wrap.appendChild(wrapper);\n            wrappers++;\n        }\n        firstChild = wrap.firstChild;\n    }\n    if (firstChild && isElt(firstChild))\n        firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n    let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n        slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n    return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n    let inCode = $context.parent.type.spec.code;\n    let dom, slice;\n    if (!html && !text)\n        return null;\n    let asText = !!text && (plainText || inCode || !html);\n    if (asText) {\n        view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n        if (inCode) {\n            slice = new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0);\n            view.someProp(\"transformPasted\", f => { slice = f(slice, view, true); });\n            return slice;\n        }\n        let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n        if (parsed) {\n            slice = parsed;\n        }\n        else {\n            let marks = $context.marks();\n            let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n            dom = document.createElement(\"div\");\n            text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n                let p = dom.appendChild(document.createElement(\"p\"));\n                if (block)\n                    p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n            });\n        }\n    }\n    else {\n        view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n        dom = readHTML(html);\n        if (webkit)\n            restoreReplacedSpaces(dom);\n    }\n    let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n    let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n    if (sliceData && sliceData[3])\n        for (let i = +sliceData[3]; i > 0; i--) {\n            let child = dom.firstChild;\n            while (child && !isElt(child))\n                child = child.nextSibling;\n            if (!child)\n                break;\n            dom = child;\n        }\n    if (!slice) {\n        let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n        slice = parser.parseSlice(dom, {\n            preserveWhitespace: !!(asText || sliceData),\n            context: $context,\n            ruleFromNode(dom) {\n                if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n                    dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n                    return { ignore: true };\n                return null;\n            }\n        });\n    }\n    if (sliceData) {\n        slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n    }\n    else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n        slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n        if (slice.openStart || slice.openEnd) {\n            let openStart = 0, openEnd = 0;\n            for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n            for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n            slice = closeSlice(slice, openStart, openEnd);\n        }\n    }\n    view.someProp(\"transformPasted\", f => { slice = f(slice, view, asText); });\n    return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n    if (fragment.childCount < 2)\n        return fragment;\n    for (let d = $context.depth; d >= 0; d--) {\n        let parent = $context.node(d);\n        let match = parent.contentMatchAt($context.index(d));\n        let lastWrap, result = [];\n        fragment.forEach(node => {\n            if (!result)\n                return;\n            let wrap = match.findWrapping(node.type), inLast;\n            if (!wrap)\n                return result = null;\n            if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n                result[result.length - 1] = inLast;\n            }\n            else {\n                if (result.length)\n                    result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n                let wrapped = withWrappers(node, wrap);\n                result.push(wrapped);\n                match = match.matchType(wrapped.type);\n                lastWrap = wrap;\n            }\n        });\n        if (result)\n            return Fragment.from(result);\n    }\n    return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n    for (let i = wrap.length - 1; i >= from; i--)\n        node = wrap[i].create(null, Fragment.from(node));\n    return node;\n}\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n    if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n        let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n        if (inner)\n            return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n        let match = sibling.contentMatchAt(sibling.childCount);\n        if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n            return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))));\n    }\n}\nfunction closeRight(node, depth) {\n    if (depth == 0)\n        return node;\n    let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n    let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n    return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n    let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n    if (fragment.childCount > 1)\n        openEnd = 0;\n    if (depth < to - 1)\n        inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n    if (depth >= from)\n        inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner)\n            : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));\n    return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));\n}\nfunction closeSlice(slice, openStart, openEnd) {\n    if (openStart < slice.openStart)\n        slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);\n    if (openEnd < slice.openEnd)\n        slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);\n    return slice;\n}\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"<td>..</td>\"` the table cells are ignored.\nconst wrapMap = {\n    thead: [\"table\"],\n    tbody: [\"table\"],\n    tfoot: [\"table\"],\n    caption: [\"table\"],\n    colgroup: [\"table\"],\n    col: [\"table\", \"colgroup\"],\n    tr: [\"table\", \"tbody\"],\n    td: [\"table\", \"tbody\", \"tr\"],\n    th: [\"table\", \"tbody\", \"tr\"]\n};\nfunction detachedDoc() {\n    return document.implementation.createHTMLDocument(\"title\");\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n    let trustedTypes = window.trustedTypes;\n    if (!trustedTypes)\n        return html;\n    // With the require-trusted-types-for CSP, Chrome will block\n    // innerHTML, even on a detached document. This wraps the string in\n    // a way that makes the browser allow us to use its parser again.\n    if (!_policy) {\n        if (_policy = trustedTypes.defaultPolicy)\n            try {\n                return _policy.createHTML(html);\n            }\n            catch (_a) { }\n        _policy = trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n    }\n    return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n    let metas = /^(\\s*<meta [^>]*>)*/.exec(html);\n    if (metas)\n        html = html.slice(metas[0].length);\n    let doc = detachedDoc(), elt = doc.body;\n    let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n    if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n        html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"</\" + n + \">\").reverse().join(\"\");\n    elt.innerHTML = maybeWrapTrusted(html);\n    if (wrap)\n        for (let i = 0; i < wrap.length; i++)\n            elt = elt.querySelector(wrap[i]) || elt;\n    // Inline styles defined in the pasted content, so that parse rules pick them up\n    for (let i = 0; i < doc.styleSheets.length; i++) {\n        let style = doc.styleSheets[i];\n        for (let j = 0; j < style.rules.length; j++) {\n            let rule = style.rules[j];\n            if (rule instanceof CSSStyleRule) {\n                let matches = elt.querySelectorAll(rule.selectorText);\n                for (let k = 0; k < matches.length; k++)\n                    matches[k].style.cssText += rule.style.cssText;\n            }\n        }\n    }\n    return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n    let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n    for (let i = 0; i < nodes.length; i++) {\n        let node = nodes[i];\n        if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n            node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n    }\n}\nfunction addContext(slice, context) {\n    if (!slice.size)\n        return slice;\n    let schema = slice.content.firstChild.type.schema, array;\n    try {\n        array = JSON.parse(context);\n    }\n    catch (e) {\n        return slice;\n    }\n    let { content, openStart, openEnd } = slice;\n    for (let i = array.length - 2; i >= 0; i -= 2) {\n        let type = schema.nodes[array[i]];\n        if (!type || type.hasRequiredAttrs())\n            break;\n        try {\n            content = Fragment.from(type.create(array[i + 1], content));\n        }\n        catch (e) {\n            break;\n        }\n        openStart++;\n        openEnd++;\n    }\n    return new Slice(content, openStart, openEnd);\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n    constructor() {\n        this.shiftKey = false;\n        this.mouseDown = null;\n        this.lastKeyCode = null;\n        this.lastKeyCodeTime = 0;\n        this.lastKeyDispatched = false;\n        this.lastClick = { time: 0, x: 0, y: 0, type: \"\", button: 0 };\n        this.lastSelectionOrigin = null;\n        this.lastSelectionTime = 0;\n        this.lastIOSEnter = 0;\n        this.lastIOSEnterFallbackTimeout = -1;\n        this.lastFocus = 0;\n        this.lastTouch = 0;\n        this.lastChromeDelete = 0;\n        this.composing = false;\n        this.compositionNode = null;\n        this.composingTimeout = -1;\n        this.compositionNodes = [];\n        this.compositionEndedAt = -2e8;\n        this.compositionID = 1;\n        this.badSafariComposition = false;\n        // Set to a composition ID when there are pending changes at compositionend\n        this.compositionPendingChanges = 0;\n        this.domChangeCount = 0;\n        this.eventHandlers = Object.create(null);\n        this.hideSelectionGuard = null;\n    }\n}\nfunction initInput(view) {\n    for (let event in handlers) {\n        let handler = handlers[event];\n        view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n            if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n                (view.editable || !(event.type in editHandlers)))\n                handler(view, event);\n        }, passiveHandlers[event] ? { passive: true } : undefined);\n    }\n    // On Safari, for reasons beyond my understanding, adding an input\n    // event handler makes an issue where the composition vanishes when\n    // you press enter go away.\n    if (safari)\n        view.dom.addEventListener(\"input\", () => null);\n    ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n    view.input.lastSelectionOrigin = origin;\n    view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n    if (view.input.mouseDown)\n        view.input.mouseDown.done();\n    view.domObserver.stop();\n    for (let type in view.input.eventHandlers)\n        view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n    clearTimeout(view.input.composingTimeout);\n    clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n    view.someProp(\"handleDOMEvents\", currentHandlers => {\n        for (let type in currentHandlers)\n            if (!view.input.eventHandlers[type])\n                view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n    });\n}\nfunction runCustomHandler(view, event) {\n    return view.someProp(\"handleDOMEvents\", handlers => {\n        let handler = handlers[event.type];\n        return handler ? handler(view, event) || event.defaultPrevented : false;\n    });\n}\nfunction eventBelongsToView(view, event) {\n    if (!event.bubbles)\n        return true;\n    if (event.defaultPrevented)\n        return false;\n    for (let node = event.target; node != view.dom; node = node.parentNode)\n        if (!node || node.nodeType == 11 ||\n            (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n            return false;\n    return true;\n}\nfunction dispatchEvent(view, event) {\n    if (!runCustomHandler(view, event) && handlers[event.type] &&\n        (view.editable || !(event.type in editHandlers)))\n        handlers[event.type](view, event);\n}\nfunction dispatchKey(view, event) {\n    let { input } = view;\n    if (input.lastKeyDispatched || view.composing)\n        return false;\n    input.lastKeyDispatched = true;\n    if (typeof event == \"string\")\n        event = keyEvent(event == \"Backspace\" ? 8 : 13, event);\n    return view.someProp(\"handleKeyDown\", f => f(view, event));\n}\neditHandlers.keydown = (view, _event) => {\n    let event = _event;\n    view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n    if (inOrNearComposition(view))\n        return;\n    view.input.lastKeyCode = event.keyCode;\n    view.input.lastKeyCodeTime = Date.now();\n    view.input.lastKeyDispatched = false;\n    // Suppress enter key events on Chrome Android, because those tend\n    // to be part of a confused sequence of composition events fired,\n    // and handling them eagerly tends to corrupt the input.\n    if (android && chrome && event.keyCode == 13)\n        return;\n    if (event.keyCode != 229)\n        view.domObserver.forceFlush();\n    // On iOS, if we preventDefault enter key presses, the virtual\n    // keyboard gets confused. So the hack here is to set a flag that\n    // makes the DOM change code recognize that what just happens should\n    // be replaced by whatever the Enter key handlers do.\n    if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n        let now = Date.now();\n        view.input.lastIOSEnter = now;\n        view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n            if (view.input.lastIOSEnter == now) {\n                dispatchKey(view, \"Enter\");\n                view.input.lastIOSEnter = 0;\n            }\n        }, 200);\n    }\n    else if (dispatchKey(view, event) || captureKeyDown(view, event)) {\n        event.preventDefault();\n    }\n    else {\n        setSelectionOrigin(view, \"key\");\n    }\n};\neditHandlers.keyup = (view, event) => {\n    if (event.keyCode == 16)\n        view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n    let event = _event;\n    if (inOrNearComposition(view) || !event.charCode ||\n        event.ctrlKey && !event.altKey || mac && event.metaKey)\n        return;\n    if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n        event.preventDefault();\n        return;\n    }\n    let sel = view.state.selection;\n    if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n        let text = String.fromCharCode(event.charCode);\n        let deflt = () => view.state.tr.insertText(text).scrollIntoView();\n        if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text, deflt)))\n            view.dispatch(deflt());\n        event.preventDefault();\n    }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n    let dx = click.x - event.clientX, dy = click.y - event.clientY;\n    return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n    if (inside == -1)\n        return false;\n    let $pos = view.state.doc.resolve(inside);\n    for (let i = $pos.depth + 1; i > 0; i--) {\n        if (view.someProp(propName, f => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n            : f(view, pos, $pos.node(i), $pos.before(i), event, false)))\n            return true;\n    }\n    return false;\n}\nfunction updateSelection(view, selection, origin) {\n    if (!view.focused)\n        view.focus();\n    if (view.state.selection.eq(selection))\n        return;\n    let tr = view.state.tr.setSelection(selection);\n    tr.setMeta(\"pointer\", true);\n    view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n    if (inside == -1)\n        return false;\n    let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n    if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n        updateSelection(view, new NodeSelection($pos));\n        return true;\n    }\n    return false;\n}\nfunction selectClickedNode(view, inside) {\n    if (inside == -1)\n        return false;\n    let sel = view.state.selection, selectedNode, selectAt;\n    if (sel instanceof NodeSelection)\n        selectedNode = sel.node;\n    let $pos = view.state.doc.resolve(inside);\n    for (let i = $pos.depth + 1; i > 0; i--) {\n        let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n        if (NodeSelection.isSelectable(node)) {\n            if (selectedNode && sel.$from.depth > 0 &&\n                i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n                selectAt = $pos.before(sel.$from.depth);\n            else\n                selectAt = $pos.before(i);\n            break;\n        }\n    }\n    if (selectAt != null) {\n        updateSelection(view, NodeSelection.create(view.state.doc, selectAt));\n        return true;\n    }\n    else {\n        return false;\n    }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n    return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n        view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n        (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n    return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n        view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n    return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n        view.someProp(\"handleTripleClick\", f => f(view, pos, event)) ||\n        defaultTripleClick(view, inside, event);\n}\nfunction defaultTripleClick(view, inside, event) {\n    if (event.button != 0)\n        return false;\n    let selection = selectionForTripleClick(view, inside, true), doc = view.state.doc;\n    if (!selection)\n        return false;\n    updateSelection(view, selection);\n    if (selection instanceof TextSelection && doc.eq(view.state.doc))\n        view.input.mouseDown = new TripleClickDrag(view, selection);\n    return true;\n}\nfunction selectionForTripleClick(view, inside, selectNodes) {\n    let doc = view.state.doc;\n    if (inside == -1)\n        return doc.inlineContent ? TextSelection.create(doc, 0, doc.content.size) : null;\n    let $pos = doc.resolve(inside);\n    for (let i = $pos.depth + 1; i > 0; i--) {\n        let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n        let nodePos = $pos.before(i);\n        if (node.inlineContent)\n            return TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size);\n        else if (selectNodes && NodeSelection.isSelectable(node))\n            return NodeSelection.create(doc, nodePos);\n    }\n    return null;\n}\nfunction forceDOMFlush(view) {\n    return endComposition(view);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n    let event = _event;\n    view.input.shiftKey = event.shiftKey;\n    let flushed = forceDOMFlush(view);\n    let now = Date.now(), type = \"singleClick\";\n    if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] &&\n        view.input.lastClick.button == event.button) {\n        if (view.input.lastClick.type == \"singleClick\")\n            type = \"doubleClick\";\n        else if (view.input.lastClick.type == \"doubleClick\")\n            type = \"tripleClick\";\n    }\n    view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };\n    if (view.input.mouseDown)\n        view.input.mouseDown.done();\n    let pos = view.posAtCoords(eventCoords(event));\n    if (!pos)\n        return;\n    if (type == \"singleClick\") {\n        view.input.mouseDown = new LeftMouseDown(view, pos, event, !!flushed);\n    }\n    else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {\n        event.preventDefault();\n    }\n    else {\n        setSelectionOrigin(view, \"pointer\");\n    }\n};\nclass MouseDown {\n    constructor(view) {\n        this.view = view;\n        this.mightDrag = null;\n        view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n        view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n    }\n    up(event) {\n        this.done();\n    }\n    move(event) {\n        if (event.buttons == 0)\n            this.done();\n    }\n    done() {\n        this.view.root.removeEventListener(\"mouseup\", this.up);\n        this.view.root.removeEventListener(\"mousemove\", this.move);\n        if (this.view.input.mouseDown == this)\n            this.view.input.mouseDown = null;\n    }\n    delaySelUpdate() { return false; }\n}\nclass LeftMouseDown extends MouseDown {\n    constructor(view, pos, event, flushed) {\n        super(view);\n        this.pos = pos;\n        this.event = event;\n        this.flushed = flushed;\n        this.delayedSelectionSync = false;\n        this.startDoc = view.state.doc;\n        this.selectNode = !!event[selectNodeModifier];\n        this.allowDefault = event.shiftKey;\n        let targetNode, targetPos;\n        if (pos.inside > -1) {\n            targetNode = view.state.doc.nodeAt(pos.inside);\n            targetPos = pos.inside;\n        }\n        else {\n            let $pos = view.state.doc.resolve(pos.pos);\n            targetNode = $pos.parent;\n            targetPos = $pos.depth ? $pos.before() : 0;\n        }\n        const target = flushed ? null : event.target;\n        const targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n        this.target = targetDesc && isElt(targetDesc.nodeDOM) ? targetDesc.nodeDOM : null;\n        let { selection } = view.state;\n        if (event.button == 0 &&\n            (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n                selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos))\n            this.mightDrag = {\n                node: targetNode,\n                pos: targetPos,\n                addAttr: !!(this.target && !this.target.draggable),\n                setUneditable: !!(this.target && gecko && !this.target.hasAttribute(\"contentEditable\"))\n            };\n        if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n            this.view.domObserver.stop();\n            if (this.mightDrag.addAttr)\n                this.target.draggable = true;\n            if (this.mightDrag.setUneditable)\n                setTimeout(() => {\n                    if (this.view.input.mouseDown == this)\n                        this.target.setAttribute(\"contentEditable\", \"false\");\n                }, 20);\n            this.view.domObserver.start();\n        }\n        setSelectionOrigin(view, \"pointer\");\n    }\n    done() {\n        super.done();\n        if (this.mightDrag && this.target) {\n            this.view.domObserver.stop();\n            if (this.mightDrag.addAttr)\n                this.target.removeAttribute(\"draggable\");\n            if (this.mightDrag.setUneditable)\n                this.target.removeAttribute(\"contentEditable\");\n            this.view.domObserver.start();\n        }\n        if (this.delayedSelectionSync)\n            setTimeout(() => {\n                if (!this.view.isDestroyed)\n                    selectionToDOM(this.view);\n            });\n    }\n    up(event) {\n        this.done();\n        if (!this.view.dom.contains(event.target))\n            return;\n        let pos = this.pos;\n        if (this.view.state.doc != this.startDoc)\n            pos = this.view.posAtCoords(eventCoords(event));\n        this.updateAllowDefault(event);\n        if (this.allowDefault || !pos) {\n            setSelectionOrigin(this.view, \"pointer\");\n        }\n        else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n            event.preventDefault();\n        }\n        else if (event.button == 0 &&\n            (this.flushed ||\n                // Safari ignores clicks on draggable elements\n                (safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n                // Chrome will sometimes treat a node selection as a\n                // cursor, but still report that the node is selected\n                // when asked through getSelection. You'll then get a\n                // situation where clicking at the point where that\n                // (hidden) cursor is doesn't change the selection, and\n                // thus doesn't get a reaction from ProseMirror. This\n                // works around that.\n                (chrome && !this.view.state.selection.visible &&\n                    Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2))) {\n            updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)));\n            event.preventDefault();\n        }\n        else {\n            setSelectionOrigin(this.view, \"pointer\");\n        }\n    }\n    move(event) {\n        this.updateAllowDefault(event);\n        setSelectionOrigin(this.view, \"pointer\");\n        super.move(event);\n    }\n    updateAllowDefault(event) {\n        if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n            Math.abs(this.event.y - event.clientY) > 4))\n            this.allowDefault = true;\n    }\n    delaySelUpdate() {\n        if (!this.allowDefault)\n            return false;\n        this.delayedSelectionSync = true;\n        return true;\n    }\n}\nclass TripleClickDrag extends MouseDown {\n    constructor(view, startSelection) {\n        super(view);\n        this.startSelection = startSelection;\n        this.startDoc = view.state.doc;\n    }\n    move(event) {\n        if (event.buttons == 0 || this.view.isDestroyed || !this.view.state.doc.eq(this.startDoc)) {\n            this.done();\n            return;\n        }\n        event.preventDefault();\n        setSelectionOrigin(this.view, \"pointer\");\n        let pos = this.view.posAtCoords(eventCoords(event));\n        let target = pos && selectionForTripleClick(this.view, pos.inside, false);\n        if (!target)\n            return;\n        let { doc } = this.view.state, start = this.startSelection;\n        let [anchor, head] = target.from < start.from ? [start.to, target.from] : [start.from, target.to];\n        updateSelection(this.view, TextSelection.create(doc, anchor, head));\n    }\n}\nhandlers.touchstart = view => {\n    view.input.lastTouch = Date.now();\n    forceDOMFlush(view);\n    setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n    view.input.lastTouch = Date.now();\n    setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => forceDOMFlush(view);\nfunction inOrNearComposition(view, event) {\n    if (view.composing)\n        return true;\n    // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n    // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n    // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n    // emitted. The keydown event triggers newline insertion, which we don't want.\n    // This method returns true if the keydown event should be ignored.\n    // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n    // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n    // This guards against the case where compositionend is triggered without the keyboard\n    // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n    // afterwards- we wouldn't want to ignore the keydown event in this case.\n    if (safari && Math.abs(Date.now() - view.input.compositionEndedAt) < 500) {\n        view.input.compositionEndedAt = -2e8;\n        return true;\n    }\n    return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n    if (!view.composing) {\n        view.domObserver.flush();\n        let { state } = view, $pos = state.selection.$to;\n        if (state.selection instanceof TextSelection && state.selection.empty &&\n            (state.storedMarks ||\n                (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)) ||\n                chrome && windows && selectionBeforeUneditable(view))) { // Issue #1500\n            // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n            view.markCursor = view.state.storedMarks || $pos.marks();\n            endComposition(view, true);\n            view.markCursor = null;\n        }\n        else {\n            endComposition(view, !state.selection.empty);\n            // In firefox, if the cursor is after but outside a marked node,\n            // the inserted text won't inherit the marks. So this moves it\n            // inside if necessary.\n            if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n                let sel = view.domSelectionRange();\n                for (let node = sel.focusNode, offset = sel.focusOffset; node && isElt(node) && offset != 0;) {\n                    let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n                    if (!before)\n                        break;\n                    if (isText(before)) {\n                        let sel = view.domSelection();\n                        if (sel)\n                            sel.collapse(before, before.nodeValue.length);\n                        break;\n                    }\n                    else {\n                        node = before;\n                        offset = -1;\n                    }\n                }\n            }\n        }\n        view.input.composing = true;\n    }\n    scheduleComposeEnd(view, timeoutComposition);\n};\nfunction selectionBeforeUneditable(view) {\n    let { focusNode, focusOffset } = view.domSelectionRange();\n    if (!focusNode || !isElt(focusNode) || focusOffset >= focusNode.childNodes.length)\n        return false;\n    let next = focusNode.childNodes[focusOffset];\n    return isElt(next) && next.contentEditable == \"false\";\n}\neditHandlers.compositionend = (view, event) => {\n    if (view.composing) {\n        view.input.composing = false;\n        view.input.compositionEndedAt = Date.now();\n        view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n        view.input.compositionNode = null;\n        if (view.input.badSafariComposition)\n            view.domObserver.forceFlush();\n        else if (view.input.compositionPendingChanges)\n            Promise.resolve().then(() => view.domObserver.flush());\n        view.input.compositionID++;\n        scheduleComposeEnd(view, 20);\n    }\n};\nfunction scheduleComposeEnd(view, delay) {\n    clearTimeout(view.input.composingTimeout);\n    if (delay > -1)\n        view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n    if (view.composing) {\n        view.input.composing = false;\n        view.input.compositionEndedAt = Date.now();\n    }\n    while (view.input.compositionNodes.length > 0)\n        view.input.compositionNodes.pop().markParentsDirty();\n}\nfunction findCompositionNode(view) {\n    let sel = view.domSelectionRange();\n    if (!sel.focusNode)\n        return null;\n    let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);\n    let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);\n    if (textBefore && textAfter && textBefore != textAfter) {\n        let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n        if (textBefore == lastChanged || textAfter == lastChanged)\n            return lastChanged;\n        if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n            return textAfter;\n        }\n        else if (view.input.compositionNode == textAfter) {\n            let descBefore = textBefore.pmViewDesc;\n            if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n                return textAfter;\n        }\n    }\n    return textBefore || textAfter;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n    if (android && view.domObserver.flushingSoon >= 0)\n        return;\n    view.domObserver.forceFlush();\n    clearComposition(view);\n    if (restarting || view.docView && view.docView.dirty) {\n        let sel = selectionFromDOM(view), cur = view.state.selection;\n        if (sel && !sel.eq(cur))\n            view.dispatch(view.state.tr.setSelection(sel));\n        else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)\n            view.dispatch(view.state.tr.deleteSelection());\n        else\n            view.updateState(view.state);\n        return true;\n    }\n    return false;\n}\nfunction captureCopy(view, dom) {\n    // The extra wrapper is somehow necessary on IE/Edge to prevent the\n    // content from being mangled when it is put onto the clipboard\n    if (!view.dom.parentNode)\n        return;\n    let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n    wrap.appendChild(dom);\n    wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n    let sel = getSelection(), range = document.createRange();\n    range.selectNodeContents(dom);\n    // Done because IE will fire a selectionchange moving the selection\n    // to its start when removeAllRanges is called and the editor still\n    // has focus (which will mess up the editor's selection state).\n    view.dom.blur();\n    sel.removeAllRanges();\n    sel.addRange(range);\n    setTimeout(() => {\n        if (wrap.parentNode)\n            wrap.parentNode.removeChild(wrap);\n        view.focus();\n    }, 50);\n}\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API\u2014all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (ie && ie_version < 15) ||\n    (ios && webkit_version < 604);\nhandlers.copy = editHandlers.cut = (view, _event) => {\n    let event = _event;\n    let sel = view.state.selection, cut = event.type == \"cut\";\n    if (sel.empty)\n        return;\n    // IE and Edge's clipboard interface is completely broken\n    let data = brokenClipboardAPI ? null : event.clipboardData;\n    let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n    if (data) {\n        event.preventDefault();\n        data.clearData();\n        data.setData(\"text/html\", dom.innerHTML);\n        data.setData(\"text/plain\", text);\n    }\n    else {\n        captureCopy(view, dom);\n    }\n    if (cut)\n        view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n    return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n    if (!view.dom.parentNode)\n        return;\n    let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n    let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n    if (!plainText)\n        target.contentEditable = \"true\";\n    target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n    target.focus();\n    let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n    setTimeout(() => {\n        view.focus();\n        if (target.parentNode)\n            target.parentNode.removeChild(target);\n        if (plainText)\n            doPaste(view, target.value, null, plain, event);\n        else\n            doPaste(view, target.textContent, target.innerHTML, plain, event);\n    }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n    let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n    if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n        return true;\n    if (!slice)\n        return false;\n    let singleNode = sliceSingleNode(slice);\n    let tr = singleNode\n        ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n        : view.state.tr.replaceSelection(slice);\n    view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n    return true;\n}\nfunction getText(clipboardData) {\n    let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n    if (text)\n        return text;\n    let uris = clipboardData.getData(\"text/uri-list\");\n    return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n    let event = _event;\n    // Handling paste from JavaScript during composition is very poorly\n    // handled by browsers, so as a dodgy but preferable kludge, we just\n    // let the browser do its native thing there, except on Android,\n    // where the editor is almost always composing.\n    if (view.composing && !android)\n        return;\n    let data = brokenClipboardAPI ? null : event.clipboardData;\n    let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n    if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n        event.preventDefault();\n    else\n        capturePaste(view, event);\n};\nclass Dragging {\n    constructor(slice, move, node) {\n        this.slice = slice;\n        this.move = move;\n        this.node = node;\n    }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nfunction dragMoves(view, event) {\n    let copy;\n    view.someProp(\"dragCopies\", test => { copy = copy || test(event); });\n    return copy != null ? !copy : !event[dragCopyModifier];\n}\nhandlers.dragstart = (view, _event) => {\n    let event = _event;\n    let mouseDown = view.input.mouseDown;\n    if (mouseDown)\n        mouseDown.done();\n    if (!event.dataTransfer)\n        return;\n    let sel = view.state.selection;\n    let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n    let node;\n    if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n    else if (mouseDown && mouseDown.mightDrag) {\n        node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n    }\n    else if (event.target && isElt(event.target)) {\n        let desc = view.docView.nearestDesc(event.target, true);\n        if (desc && desc.node.type.spec.draggable && desc != view.docView)\n            node = NodeSelection.create(view.state.doc, desc.posBefore);\n    }\n    let draggedSlice = (node || view.state.selection).content();\n    let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n    // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n    if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n        event.dataTransfer.clearData();\n    event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n    // See https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1156\n    event.dataTransfer.effectAllowed = \"copyMove\";\n    if (!brokenClipboardAPI)\n        event.dataTransfer.setData(\"text/plain\", text);\n    view.dragging = new Dragging(slice, dragMoves(view, event), node);\n};\nhandlers.dragend = view => {\n    let dragging = view.dragging;\n    window.setTimeout(() => {\n        if (view.dragging == dragging)\n            view.dragging = null;\n    }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, event) => {\n    try {\n        handleDrop(view, event, view.dragging);\n    }\n    finally {\n        view.dragging = null;\n    }\n};\nfunction handleDrop(view, event, dragging) {\n    if (!event.dataTransfer)\n        return;\n    let eventPos = view.posAtCoords(eventCoords(event));\n    if (!eventPos)\n        return;\n    let $mouse = view.state.doc.resolve(eventPos.pos);\n    let slice = dragging && dragging.slice;\n    if (slice) {\n        view.someProp(\"transformPasted\", f => { slice = f(slice, view, false); });\n    }\n    else {\n        slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n    }\n    let move = !!(dragging && dragMoves(view, event));\n    if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n        event.preventDefault();\n        return;\n    }\n    if (!slice)\n        return;\n    event.preventDefault();\n    let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n    if (insertPos == null)\n        insertPos = $mouse.pos;\n    let tr = view.state.tr;\n    if (move) {\n        let { node } = dragging;\n        if (node)\n            node.replace(tr);\n        else\n            tr.deleteSelection();\n    }\n    let pos = tr.mapping.map(insertPos);\n    let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n    let beforeInsert = tr.doc;\n    if (isNode)\n        tr.replaceRangeWith(pos, pos, slice.content.firstChild);\n    else\n        tr.replaceRange(pos, pos, slice);\n    if (tr.doc.eq(beforeInsert))\n        return;\n    let $pos = tr.doc.resolve(pos);\n    if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n        $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n        tr.setSelection(new NodeSelection($pos));\n    }\n    else {\n        let end = tr.mapping.map(insertPos);\n        tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n        tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n    }\n    view.focus();\n    view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n}\nhandlers.focus = view => {\n    view.input.lastFocus = Date.now();\n    if (!view.focused) {\n        view.domObserver.stop();\n        view.dom.classList.add(\"ProseMirror-focused\");\n        view.domObserver.start();\n        view.focused = true;\n        let startSel = view.domSelectionRange();\n        if (!view.domObserver.currentSelection.eq(startSel)) {\n            let { focusNode, focusOffset } = startSel;\n            setTimeout(() => {\n                let newSel = view.domSelectionRange();\n                if (newSel.focusNode == focusNode && newSel.focusOffset == focusOffset && view.docView && view.hasFocus())\n                    selectionToDOM(view);\n            }, 20);\n        }\n    }\n};\nhandlers.blur = (view, _event) => {\n    let event = _event;\n    if (view.focused) {\n        view.domObserver.stop();\n        view.dom.classList.remove(\"ProseMirror-focused\");\n        view.domObserver.start();\n        if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n            view.domObserver.currentSelection.clear();\n        view.focused = false;\n    }\n};\nhandlers.beforeinput = (view, _event) => {\n    let event = _event;\n    // We should probably do more with beforeinput events, but support\n    // is so spotty that I'm still waiting to see where they are going.\n    // Very specific hack to deal with backspace sometimes failing on\n    // Chrome and Firefox Android when after an uneditable node.\n    if (android && event.inputType == \"deleteContentBackward\") {\n        view.domObserver.flushSoon();\n        let { domChangeCount } = view.input;\n        setTimeout(() => {\n            if (view.input.domChangeCount != domChangeCount || view.domObserver.pendingRecords().length)\n                return; // Event already had some effect\n            // This bug tends to close the virtual keyboard, so we refocus\n            view.dom.blur();\n            view.focus();\n            if (dispatchKey(view, \"Backspace\"))\n                return;\n            let { $cursor } = view.state.selection;\n            // Crude approximation of backspace behavior when no command handled it\n            if ($cursor && $cursor.pos > 0)\n                view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n        }, 50);\n    }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n    handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n    if (a == b)\n        return true;\n    for (let p in a)\n        if (a[p] !== b[p])\n            return false;\n    for (let p in b)\n        if (!(p in a))\n            return false;\n    return true;\n}\nclass FragmentCursor {\n    constructor(frag) {\n        this.frag = frag;\n        this.index = 0;\n        this.off = 0;\n    }\n    nodeAt(off) {\n        while (this.off <= off && this.index < this.frag.childCount) {\n            let next = this.frag.child(this.index);\n            if (this.off == off)\n                return next;\n            this.off += next.nodeSize;\n            this.index++;\n        }\n        return null;\n    }\n}\nclass WidgetType {\n    constructor(toDOM, spec) {\n        this.toDOM = toDOM;\n        this.spec = spec || noSpec;\n        this.side = this.spec.side || 0;\n    }\n    map(mapping, span, offset, oldOffset) {\n        let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n        return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n    }\n    valid() { return true; }\n    eq(other) {\n        return this == other ||\n            (other instanceof WidgetType &&\n                (this.spec.key && this.spec.key == other.spec.key ||\n                    this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)));\n    }\n    destroy(node) {\n        if (this.spec.destroy)\n            this.spec.destroy(node);\n    }\n}\nclass InlineType {\n    constructor(attrs, spec) {\n        this.attrs = attrs;\n        this.spec = spec || noSpec;\n    }\n    map(mapping, span, offset, oldOffset) {\n        let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n        let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n        return from >= to ? null : new Decoration(from, to, this);\n    }\n    valid(_, span) { return span.from < span.to; }\n    eq(other) {\n        return this == other ||\n            (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n                compareObjs(this.spec, other.spec));\n    }\n    static is(span) { return span.type instanceof InlineType; }\n    destroy() { }\n}\nclass NodeType {\n    constructor(attrs, spec) {\n        this.attrs = attrs;\n        this.spec = spec || noSpec;\n    }\n    map(mapping, span, offset, oldOffset) {\n        let from = mapping.mapResult(span.from + oldOffset, 1);\n        if (from.deleted)\n            return null;\n        let to = mapping.mapResult(span.to + oldOffset, -1);\n        if (to.deleted || to.pos <= from.pos)\n            return null;\n        return new Decoration(from.pos - offset, to.pos - offset, this);\n    }\n    valid(node, span, cursor) {\n        let found = cursor.nodeAt(span.from);\n        return !!found && !found.isText && span.from + found.nodeSize == span.to;\n    }\n    eq(other) {\n        return this == other ||\n            (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n                compareObjs(this.spec, other.spec));\n    }\n    destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants\u2014see the static members of this class for details.\n*/\nclass Decoration {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The start position of the decoration.\n    */\n    from, \n    /**\n    The end position. Will be the same as `from` for [widget\n    decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n    */\n    to, \n    /**\n    @internal\n    */\n    type) {\n        this.from = from;\n        this.to = to;\n        this.type = type;\n    }\n    /**\n    @internal\n    */\n    copy(from, to) {\n        return new Decoration(from, to, this.type);\n    }\n    /**\n    @internal\n    */\n    eq(other, offset = 0) {\n        return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n    }\n    /**\n    @internal\n    */\n    map(mapping, offset, oldOffset) {\n        return this.type.map(mapping, this, offset, oldOffset);\n    }\n    /**\n    Creates a widget decoration, which is a DOM node that's shown in\n    the document at the given position. It is recommended that you\n    delay rendering the widget by passing a function that will be\n    called when the widget is actually drawn in a view, but you can\n    also directly pass a DOM node. `getPos` can be used to find the\n    widget's current document position.\n    */\n    static widget(pos, toDOM, spec) {\n        return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n    }\n    /**\n    Creates an inline decoration, which adds the given attributes to\n    each inline node between `from` and `to`.\n    */\n    static inline(from, to, attrs, spec) {\n        return new Decoration(from, to, new InlineType(attrs, spec));\n    }\n    /**\n    Creates a node decoration. `from` and `to` should point precisely\n    before and after a node in the document. That node, and only that\n    node, will receive the given attributes.\n    */\n    static node(from, to, attrs, spec) {\n        return new Decoration(from, to, new NodeType(attrs, spec));\n    }\n    /**\n    The spec provided when creating this decoration. Can be useful\n    if you've stored extra information in that object.\n    */\n    get spec() { return this.type.spec; }\n    /**\n    @internal\n    */\n    get inline() { return this.type instanceof InlineType; }\n    /**\n    @internal\n    */\n    get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure\u2014it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n    /**\n    @internal\n    */\n    constructor(local, children) {\n        this.local = local.length ? local : none;\n        this.children = children.length ? children : none;\n    }\n    /**\n    Create a set of decorations, using the structure of the given\n    document. This will consume (modify) the `decorations` array, so\n    you must make a copy if you want need to preserve that.\n    */\n    static create(doc, decorations) {\n        return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n    }\n    /**\n    Find all decorations in this set which touch the given range\n    (including decorations that start or end directly at the\n    boundaries) and match the given predicate on their spec. When\n    `start` and `end` are omitted, all decorations in the set are\n    considered. When `predicate` isn't given, all decorations are\n    assumed to match.\n    */\n    find(start, end, predicate) {\n        let result = [];\n        this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n        return result;\n    }\n    findInner(start, end, result, offset, predicate) {\n        for (let i = 0; i < this.local.length; i++) {\n            let span = this.local[i];\n            if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n                result.push(span.copy(span.from + offset, span.to + offset));\n        }\n        for (let i = 0; i < this.children.length; i += 3) {\n            if (this.children[i] < end && this.children[i + 1] > start) {\n                let childOff = this.children[i] + 1;\n                this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n            }\n        }\n    }\n    /**\n    Map the set of decorations in response to a change in the\n    document.\n    */\n    map(mapping, doc, options) {\n        if (this == empty || mapping.maps.length == 0)\n            return this;\n        return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n    }\n    /**\n    @internal\n    */\n    mapInner(mapping, node, offset, oldOffset, options) {\n        let newLocal;\n        if (this.local.length) {\n            let cur = new FragmentCursor(node.content);\n            for (let i = 0; i < this.local.length; i++) {\n                let mapped = this.local[i].map(mapping, offset, oldOffset);\n                if (mapped && mapped.type.valid(node, mapped, cur))\n                    (newLocal || (newLocal = [])).push(mapped);\n                else if (options.onRemove)\n                    options.onRemove(this.local[i].spec);\n            }\n        }\n        if (this.children.length)\n            return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);\n        else\n            return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;\n    }\n    /**\n    Add the given array of decorations to the ones in the set,\n    producing a new set. Consumes the `decorations` array. Needs\n    access to the current document to create the appropriate tree\n    structure.\n    */\n    add(doc, decorations) {\n        if (!decorations.length)\n            return this;\n        if (this == empty)\n            return DecorationSet.create(doc, decorations);\n        return this.addInner(doc, decorations, 0);\n    }\n    addInner(doc, decorations, offset) {\n        let children, childIndex = 0;\n        doc.forEach((childNode, childOffset) => {\n            let baseOffset = childOffset + offset, found;\n            if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n                return;\n            if (!children)\n                children = this.children.slice();\n            while (childIndex < children.length && children[childIndex] < childOffset)\n                childIndex += 3;\n            if (children[childIndex] == childOffset)\n                children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);\n            else\n                children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));\n            childIndex += 3;\n        });\n        let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n        if (local.length) {\n            let cur = new FragmentCursor(doc.content);\n            for (let i = 0; i < local.length; i++)\n                if (!local[i].type.valid(doc, local[i], cur))\n                    local.splice(i--, 1);\n        }\n        return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n    }\n    /**\n    Create a new set that contains the decorations in this set, minus\n    the ones in the given array.\n    */\n    remove(decorations) {\n        if (decorations.length == 0 || this == empty)\n            return this;\n        return this.removeInner(decorations, 0);\n    }\n    removeInner(decorations, offset) {\n        let children = this.children, local = this.local;\n        for (let i = 0; i < children.length; i += 3) {\n            let found;\n            let from = children[i] + offset, to = children[i + 1] + offset;\n            for (let j = 0, span; j < decorations.length; j++)\n                if (span = decorations[j]) {\n                    if (span.from > from && span.to < to) {\n                        decorations[j] = null;\n                        (found || (found = [])).push(span);\n                    }\n                }\n            if (!found)\n                continue;\n            if (children == this.children)\n                children = this.children.slice();\n            let removed = children[i + 2].removeInner(found, from + 1);\n            if (removed != empty) {\n                children[i + 2] = removed;\n            }\n            else {\n                children.splice(i, 3);\n                i -= 3;\n            }\n        }\n        if (local.length)\n            for (let i = 0, span; i < decorations.length; i++)\n                if (span = decorations[i]) {\n                    for (let j = 0; j < local.length; j++)\n                        if (local[j].eq(span, offset)) {\n                            if (local == this.local)\n                                local = this.local.slice();\n                            local.splice(j--, 1);\n                        }\n                }\n        if (children == this.children && local == this.local)\n            return this;\n        return local.length || children.length ? new DecorationSet(local, children) : empty;\n    }\n    forChild(offset, node) {\n        if (this == empty)\n            return this;\n        if (node.isLeaf)\n            return DecorationSet.empty;\n        let child, local;\n        for (let i = 0; i < this.children.length; i += 3)\n            if (this.children[i] >= offset) {\n                if (this.children[i] == offset)\n                    child = this.children[i + 2];\n                break;\n            }\n        let start = offset + 1, end = start + node.content.size;\n        for (let i = 0; i < this.local.length; i++) {\n            let dec = this.local[i];\n            if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n                let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n                if (from < to)\n                    (local || (local = [])).push(dec.copy(from, to));\n            }\n        }\n        if (local) {\n            let localSet = new DecorationSet(local.sort(byPos), none);\n            return child ? new DecorationGroup([localSet, child]) : localSet;\n        }\n        return child || empty;\n    }\n    /**\n    @internal\n    */\n    eq(other) {\n        if (this == other)\n            return true;\n        if (!(other instanceof DecorationSet) ||\n            this.local.length != other.local.length ||\n            this.children.length != other.children.length)\n            return false;\n        for (let i = 0; i < this.local.length; i++)\n            if (!this.local[i].eq(other.local[i]))\n                return false;\n        for (let i = 0; i < this.children.length; i += 3)\n            if (this.children[i] != other.children[i] ||\n                this.children[i + 1] != other.children[i + 1] ||\n                !this.children[i + 2].eq(other.children[i + 2]))\n                return false;\n        return true;\n    }\n    /**\n    @internal\n    */\n    locals(node) {\n        return removeOverlap(this.localsInner(node));\n    }\n    /**\n    @internal\n    */\n    localsInner(node) {\n        if (this == empty)\n            return none;\n        if (node.inlineContent || !this.local.some(InlineType.is))\n            return this.local;\n        let result = [];\n        for (let i = 0; i < this.local.length; i++) {\n            if (!(this.local[i].type instanceof InlineType))\n                result.push(this.local[i]);\n        }\n        return result;\n    }\n    forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\n// An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nclass DecorationGroup {\n    constructor(members) {\n        this.members = members;\n    }\n    map(mapping, doc) {\n        const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n        return DecorationGroup.from(mappedDecos);\n    }\n    forChild(offset, child) {\n        if (child.isLeaf)\n            return DecorationSet.empty;\n        let found = [];\n        for (let i = 0; i < this.members.length; i++) {\n            let result = this.members[i].forChild(offset, child);\n            if (result == empty)\n                continue;\n            if (result instanceof DecorationGroup)\n                found = found.concat(result.members);\n            else\n                found.push(result);\n        }\n        return DecorationGroup.from(found);\n    }\n    eq(other) {\n        if (!(other instanceof DecorationGroup) ||\n            other.members.length != this.members.length)\n            return false;\n        for (let i = 0; i < this.members.length; i++)\n            if (!this.members[i].eq(other.members[i]))\n                return false;\n        return true;\n    }\n    locals(node) {\n        let result, sorted = true;\n        for (let i = 0; i < this.members.length; i++) {\n            let locals = this.members[i].localsInner(node);\n            if (!locals.length)\n                continue;\n            if (!result) {\n                result = locals;\n            }\n            else {\n                if (sorted) {\n                    result = result.slice();\n                    sorted = false;\n                }\n                for (let j = 0; j < locals.length; j++)\n                    result.push(locals[j]);\n            }\n        }\n        return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n    }\n    // Create a group for the given array of decoration sets, or return\n    // a single set when possible.\n    static from(members) {\n        switch (members.length) {\n            case 0: return empty;\n            case 1: return members[0];\n            default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n                members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n        }\n    }\n    forEachSet(f) {\n        for (let i = 0; i < this.members.length; i++)\n            this.members[i].forEachSet(f);\n    }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n    let children = oldChildren.slice();\n    // Mark the children that are directly touched by changes, and\n    // move those that are after the changes.\n    for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n        let moved = 0;\n        mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n            let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n            for (let i = 0; i < children.length; i += 3) {\n                let end = children[i + 1];\n                if (end < 0 || oldStart > end + baseOffset - moved)\n                    continue;\n                let start = children[i] + baseOffset - moved;\n                if (oldEnd >= start) {\n                    children[i + 1] = oldStart <= start ? -2 : -1;\n                }\n                else if (oldStart >= baseOffset && dSize) {\n                    children[i] += dSize;\n                    children[i + 1] += dSize;\n                }\n            }\n            moved += dSize;\n        });\n        baseOffset = mapping.maps[i].map(baseOffset, -1);\n    }\n    // Find the child nodes that still correspond to a single node,\n    // recursively call mapInner on them and update their positions.\n    let mustRebuild = false;\n    for (let i = 0; i < children.length; i += 3)\n        if (children[i + 1] < 0) { // Touched nodes\n            if (children[i + 1] == -2) {\n                mustRebuild = true;\n                children[i + 1] = -1;\n                continue;\n            }\n            let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset;\n            if (fromLocal < 0 || fromLocal >= node.content.size) {\n                mustRebuild = true;\n                continue;\n            }\n            // Must read oldChildren because children was tagged with -1\n            let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n            let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n            let childNode = node.maybeChild(index);\n            if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n                let mapped = children[i + 2]\n                    .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n                if (mapped != empty) {\n                    children[i] = fromLocal;\n                    children[i + 1] = toLocal;\n                    children[i + 2] = mapped;\n                }\n                else {\n                    children[i + 1] = -2;\n                    mustRebuild = true;\n                }\n            }\n            else {\n                mustRebuild = true;\n            }\n        }\n    // Remaining children must be collected and rebuilt into the appropriate structure\n    if (mustRebuild) {\n        let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n        let built = buildTree(decorations, node, 0, options);\n        newLocal = built.local;\n        for (let i = 0; i < children.length; i += 3)\n            if (children[i + 1] < 0) {\n                children.splice(i, 3);\n                i -= 3;\n            }\n        for (let i = 0, j = 0; i < built.children.length; i += 3) {\n            let from = built.children[i];\n            while (j < children.length && children[j] < from)\n                j += 3;\n            children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n        }\n    }\n    return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n    if (!offset || !spans.length)\n        return spans;\n    let result = [];\n    for (let i = 0; i < spans.length; i++) {\n        let span = spans[i];\n        result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n    }\n    return result;\n}\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n    // Gather all decorations from the remaining marked children\n    function gather(set, oldOffset) {\n        for (let i = 0; i < set.local.length; i++) {\n            let mapped = set.local[i].map(mapping, offset, oldOffset);\n            if (mapped)\n                decorations.push(mapped);\n            else if (options.onRemove)\n                options.onRemove(set.local[i].spec);\n        }\n        for (let i = 0; i < set.children.length; i += 3)\n            gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n    }\n    for (let i = 0; i < children.length; i += 3)\n        if (children[i + 1] == -1)\n            gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n    return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n    if (node.isLeaf)\n        return null;\n    let end = offset + node.nodeSize, found = null;\n    for (let i = 0, span; i < spans.length; i++) {\n        if ((span = spans[i]) && span.from > offset && span.to < end) {\n            (found || (found = [])).push(span);\n            spans[i] = null;\n        }\n    }\n    return found;\n}\nfunction withoutNulls(array) {\n    let result = [];\n    for (let i = 0; i < array.length; i++)\n        if (array[i] != null)\n            result.push(array[i]);\n    return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n    let children = [], hasNulls = false;\n    node.forEach((childNode, localStart) => {\n        let found = takeSpansForNode(spans, childNode, localStart + offset);\n        if (found) {\n            hasNulls = true;\n            let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n            if (subtree != empty)\n                children.push(localStart, localStart + childNode.nodeSize, subtree);\n        }\n    });\n    let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n    if (locals.length) {\n        let cur = new FragmentCursor(node.content);\n        for (let i = 0; i < locals.length; i++)\n            if (!locals[i].type.valid(node, locals[i], cur)) {\n                if (options.onRemove)\n                    options.onRemove(locals[i].spec);\n                locals.splice(i--, 1);\n            }\n    }\n    return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n    return a.from - b.from || a.to - b.to;\n}\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n    let working = spans;\n    for (let i = 0; i < working.length - 1; i++) {\n        let span = working[i];\n        if (span.from != span.to)\n            for (let j = i + 1; j < working.length; j++) {\n                let next = working[j];\n                if (next.from == span.from) {\n                    if (next.to != span.to) {\n                        if (working == spans)\n                            working = spans.slice();\n                        // Followed by a partially overlapping larger span. Split that\n                        // span.\n                        working[j] = next.copy(next.from, span.to);\n                        insertAhead(working, j + 1, next.copy(span.to, next.to));\n                    }\n                    continue;\n                }\n                else {\n                    if (next.from < span.to) {\n                        if (working == spans)\n                            working = spans.slice();\n                        // The end of this one overlaps with a subsequent span. Split\n                        // this one.\n                        working[i] = span.copy(span.from, next.from);\n                        insertAhead(working, j, span.copy(next.from, span.to));\n                    }\n                    break;\n                }\n            }\n    }\n    return working;\n}\nfunction insertAhead(array, i, deco) {\n    while (i < array.length && byPos(deco, array[i]) > 0)\n        i++;\n    array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n    let found = [];\n    view.someProp(\"decorations\", f => {\n        let result = f(view.state);\n        if (result && result != empty)\n            found.push(result);\n    });\n    if (view.cursorWrapper)\n        found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));\n    return DecorationGroup.from(found);\n}\n\nconst observeOptions = {\n    childList: true,\n    characterData: true,\n    characterDataOldValue: true,\n    attributes: true,\n    attributeOldValue: true,\n    subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nconst useCharData = ie && ie_version <= 11;\nclass SelectionState {\n    constructor() {\n        this.anchorNode = null;\n        this.anchorOffset = 0;\n        this.focusNode = null;\n        this.focusOffset = 0;\n    }\n    set(sel) {\n        this.anchorNode = sel.anchorNode;\n        this.anchorOffset = sel.anchorOffset;\n        this.focusNode = sel.focusNode;\n        this.focusOffset = sel.focusOffset;\n    }\n    clear() {\n        this.anchorNode = this.focusNode = null;\n    }\n    eq(sel) {\n        return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n            sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n    }\n}\nclass DOMObserver {\n    constructor(view, handleDOMChange) {\n        this.view = view;\n        this.handleDOMChange = handleDOMChange;\n        this.queue = [];\n        this.flushingSoon = -1;\n        this.observer = null;\n        this.currentSelection = new SelectionState;\n        this.onCharData = null;\n        this.suppressingSelectionUpdates = false;\n        this.lastChangedTextNode = null;\n        this.observer = window.MutationObserver &&\n            new window.MutationObserver(mutations => {\n                for (let i = 0; i < mutations.length; i++)\n                    this.queue.push(mutations[i]);\n                if (ie && ie_version <= 11 && mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n                    m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length)) {\n                    // IE11 will sometimes (on backspacing out a single character\n                    // text node after a BR node) call the observer callback\n                    // before actually updating the DOM, which will cause\n                    // ProseMirror to miss the change (see #930)\n                    this.flushSoon();\n                }\n                else if (safari && view.composing && mutations.some(m => m.type == \"childList\" && m.target.nodeName == \"TR\")) {\n                    // Safari does weird stuff when finishing a composition in a\n                    // table cell, which tends to involve inserting inappropriate\n                    // nodes in the table row.\n                    view.input.badSafariComposition = true;\n                    this.flushSoon();\n                }\n                else {\n                    this.flush();\n                }\n            });\n        if (useCharData) {\n            this.onCharData = e => {\n                this.queue.push({ target: e.target, type: \"characterData\", oldValue: e.prevValue });\n                this.flushSoon();\n            };\n        }\n        this.onSelectionChange = this.onSelectionChange.bind(this);\n    }\n    flushSoon() {\n        if (this.flushingSoon < 0)\n            this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n    }\n    forceFlush() {\n        if (this.flushingSoon > -1) {\n            window.clearTimeout(this.flushingSoon);\n            this.flushingSoon = -1;\n            this.flush();\n        }\n    }\n    start() {\n        if (this.observer) {\n            this.observer.takeRecords();\n            this.observer.observe(this.view.dom, observeOptions);\n        }\n        if (this.onCharData)\n            this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n        this.connectSelection();\n    }\n    stop() {\n        if (this.observer) {\n            let take = this.observer.takeRecords();\n            if (take.length) {\n                for (let i = 0; i < take.length; i++)\n                    this.queue.push(take[i]);\n                window.setTimeout(() => this.flush(), 20);\n            }\n            this.observer.disconnect();\n        }\n        if (this.onCharData)\n            this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n        this.disconnectSelection();\n    }\n    connectSelection() {\n        this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n    }\n    disconnectSelection() {\n        this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n    }\n    suppressSelectionUpdates() {\n        this.suppressingSelectionUpdates = true;\n        setTimeout(() => this.suppressingSelectionUpdates = false, 50);\n    }\n    onSelectionChange() {\n        if (!hasFocusAndSelection(this.view))\n            return;\n        if (this.suppressingSelectionUpdates)\n            return selectionToDOM(this.view);\n        // Deletions on IE11 fire their events in the wrong order, giving\n        // us a selection change event before the DOM changes are\n        // reported.\n        if (ie && ie_version <= 11 && !this.view.state.selection.empty) {\n            let sel = this.view.domSelectionRange();\n            // Selection.isCollapsed isn't reliable on IE\n            if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n                return this.flushSoon();\n        }\n        this.flush();\n    }\n    setCurSelection() {\n        this.currentSelection.set(this.view.domSelectionRange());\n    }\n    ignoreSelectionChange(sel) {\n        if (!sel.focusNode)\n            return true;\n        let ancestors = new Set, container;\n        for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n            ancestors.add(scan);\n        for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n            if (ancestors.has(scan)) {\n                container = scan;\n                break;\n            }\n        let desc = container && this.view.docView.nearestDesc(container);\n        if (desc && desc.ignoreMutation({\n            type: \"selection\",\n            target: isText(container) ? container.parentNode : container\n        })) {\n            this.setCurSelection();\n            return true;\n        }\n    }\n    pendingRecords() {\n        if (this.observer)\n            for (let mut of this.observer.takeRecords())\n                this.queue.push(mut);\n        return this.queue;\n    }\n    flush() {\n        let { view } = this;\n        if (!view.docView || this.flushingSoon > -1)\n            return;\n        let mutations = this.pendingRecords();\n        if (mutations.length)\n            this.queue = [];\n        let selRange, newSel = false;\n        if (!this.suppressingSelectionUpdates && hasFocusAndSelection(view)) {\n            selRange = view.domSelectionRange();\n            newSel = !this.currentSelection.eq(selRange) && !this.ignoreSelectionChange(selRange);\n        }\n        let from = -1, to = -1, typeOver = false, added = [];\n        if (view.editable) {\n            for (let i = 0; i < mutations.length; i++) {\n                let result = this.registerMutation(mutations[i], added);\n                if (result) {\n                    from = from < 0 ? result.from : Math.min(result.from, from);\n                    to = to < 0 ? result.to : Math.max(result.to, to);\n                    if (result.typeOver)\n                        typeOver = true;\n                }\n            }\n        }\n        if (added.some(n => n.nodeName == \"BR\") &&\n            (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46 ||\n                chrome && (view.composing || view.input.compositionEndedAt > Date.now() - 50) &&\n                    mutations.some(m => m.type == \"childList\" && m.removedNodes.length))) {\n            // Browsers sometimes insert a bogus break node if you\n            // backspace out the last bit of text before an inline-flex node (#1552)\n            for (let node of added)\n                if (node.nodeName == \"BR\" && node.parentNode) {\n                    let after = node.nextSibling;\n                    while (after && isElt(after)) {\n                        if (after.contentEditable == \"false\") {\n                            node.parentNode.removeChild(node);\n                            break;\n                        }\n                        after = after.firstChild;\n                    }\n                }\n        }\n        else if (gecko && added.length) {\n            let brs = added.filter(n => n.nodeName == \"BR\");\n            if (brs.length == 2) {\n                let [a, b] = brs;\n                if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n                    b.remove();\n                else\n                    a.remove();\n            }\n            else {\n                let { focusNode } = this.currentSelection;\n                for (let br of brs) {\n                    let parent = br.parentNode;\n                    if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n                        br.remove();\n                }\n            }\n        }\n        let readSel = null;\n        // If it looks like the browser has reset the selection to the\n        // start of the document after focus, restore the selection from\n        // the state\n        if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 &&\n            Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 &&\n            selectionCollapsed(selRange) && (readSel = selectionFromDOM(view)) &&\n            readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n            view.input.lastFocus = 0;\n            selectionToDOM(view);\n            this.currentSelection.set(selRange);\n            view.scrollToSelection();\n        }\n        else if (from > -1 || newSel) {\n            if (from > -1) {\n                view.docView.markDirty(from, to);\n                checkCSS(view);\n            }\n            if (view.input.badSafariComposition) {\n                view.input.badSafariComposition = false;\n                fixUpBadSafariComposition(view, added);\n            }\n            this.handleDOMChange(from, to, typeOver, added);\n            if (view.docView && view.docView.dirty)\n                view.updateState(view.state);\n            else if (selRange && !this.currentSelection.eq(selRange))\n                selectionToDOM(view);\n            if (selRange)\n                this.currentSelection.set(selRange);\n        }\n    }\n    registerMutation(mut, added) {\n        // Ignore mutations inside nodes that were already noted as inserted\n        if (added.indexOf(mut.target) > -1)\n            return null;\n        let desc = this.view.docView.nearestDesc(mut.target);\n        if (mut.type == \"attributes\" &&\n            (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n                // Firefox sometimes fires spurious events for null/empty styles\n                (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n            return null;\n        if (!desc || desc.ignoreMutation(mut))\n            return null;\n        if (mut.type == \"childList\") {\n            for (let i = 0; i < mut.addedNodes.length; i++) {\n                let node = mut.addedNodes[i];\n                added.push(node);\n                if (isText(node))\n                    this.lastChangedTextNode = node;\n            }\n            if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))\n                return { from: desc.posBefore, to: desc.posAfter };\n            let prev = mut.previousSibling, next = mut.nextSibling;\n            if (ie && ie_version <= 11 && mut.addedNodes.length) {\n                // IE11 gives us incorrect next/prev siblings for some\n                // insertions, so if there are added nodes, recompute those\n                for (let i = 0; i < mut.addedNodes.length; i++) {\n                    let { previousSibling, nextSibling } = mut.addedNodes[i];\n                    if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)\n                        prev = previousSibling;\n                    if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)\n                        next = nextSibling;\n                }\n            }\n            let fromOffset = prev && prev.parentNode == mut.target\n                ? domIndex(prev) + 1 : 0;\n            let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n            let toOffset = next && next.parentNode == mut.target\n                ? domIndex(next) : mut.target.childNodes.length;\n            let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n            return { from, to };\n        }\n        else if (mut.type == \"attributes\") {\n            return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n        }\n        else { // \"characterData\"\n            this.lastChangedTextNode = mut.target;\n            return {\n                from: desc.posAtStart,\n                to: desc.posAtEnd,\n                // An event was generated for a text change that didn't change\n                // any text. Mark the dom change to fall back to assuming the\n                // selection was typed over with an identical value if it can't\n                // find another change.\n                typeOver: mut.target.nodeValue == mut.oldValue\n            };\n        }\n    }\n}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n    if (cssChecked.has(view))\n        return;\n    cssChecked.set(view, null);\n    if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n        view.requiresGeckoHackNode = gecko;\n        if (cssCheckWarned)\n            return;\n        console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\");\n        cssCheckWarned = true;\n    }\n}\nfunction rangeToSelectionRange(view, range) {\n    let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n    let focusNode = range.endContainer, focusOffset = range.endOffset;\n    let currentAnchor = view.domAtPos(view.state.selection.anchor);\n    // Since such a range doesn't distinguish between anchor and head,\n    // use a heuristic that flips it around if its end matches the\n    // current anchor.\n    if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n        [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n    return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug\n// Based on https://github.com/codemirror/dev/issues/414 fix\nfunction safariShadowSelectionRange(view, selection) {\n    if (selection.getComposedRanges) {\n        let range = selection.getComposedRanges(view.root)[0];\n        if (range)\n            return rangeToSelectionRange(view, range);\n    }\n    let found;\n    function read(event) {\n        event.preventDefault();\n        event.stopImmediatePropagation();\n        found = event.getTargetRanges()[0];\n    }\n    // Because Safari (at least in 2018-2022) doesn't provide regular\n    // access to the selection inside a shadowRoot, we have to perform a\n    // ridiculous hack to get at it\u2014using `execCommand` to trigger a\n    // `beforeInput` event so that we can read the target range from the\n    // event.\n    view.dom.addEventListener(\"beforeinput\", read, true);\n    document.execCommand(\"indent\");\n    view.dom.removeEventListener(\"beforeinput\", read, true);\n    return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction blockParent(view, node) {\n    for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n        let desc = view.docView.nearestDesc(p, true);\n        if (desc && desc.node.isBlock)\n            return p;\n    }\n    return null;\n}\n// Kludge for a Safari bug where, on ending a composition in an\n// otherwise empty table cell, it randomly moves the composed text\n// into the table row around that cell, greatly confusing everything\n// (#188).\nfunction fixUpBadSafariComposition(view, addedNodes) {\n    var _a;\n    let { focusNode, focusOffset } = view.domSelectionRange();\n    for (let node of addedNodes) {\n        if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == \"TR\") {\n            let nextCell = node.nextSibling;\n            while (nextCell && (nextCell.nodeName != \"TD\" && nextCell.nodeName != \"TH\"))\n                nextCell = nextCell.nextSibling;\n            if (nextCell) {\n                let parent = nextCell;\n                for (;;) {\n                    let first = parent.firstChild;\n                    if (!first || !isElt(first) || first.contentEditable == \"false\" || /^(BR|IMG)$/.test(first.nodeName))\n                        break;\n                    parent = first;\n                }\n                parent.insertBefore(node, parent.firstChild);\n                if (focusNode == node)\n                    view.domSelection().collapse(node, focusOffset);\n            }\n            else {\n                node.parentNode.removeChild(node);\n            }\n        }\n    }\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\nfunction parseBetween(view, from_, to_, addedNodes) {\n    let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n    let domSel = view.domSelectionRange();\n    let find;\n    let anchor = domSel.anchorNode;\n    if (anchor && contains(view.dom, anchor)) {\n        find = [{ node: anchor, offset: domSel.anchorOffset }];\n        if (!selectionCollapsed(domSel))\n            find.push({ node: domSel.focusNode, offset: domSel.focusOffset });\n    }\n    // Work around issue in Chrome where backspacing sometimes replaces\n    // the deleted content with a random BR node (issues #799, #831)\n    if (chrome && view.input.lastKeyCode === 8) {\n        for (let off = toOffset; off > fromOffset; off--) {\n            let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n            if (node.nodeName == \"BR\" && !desc) {\n                toOffset = off;\n                break;\n            }\n            if (!desc || desc.size)\n                break;\n        }\n    }\n    let startDoc = view.state.doc;\n    let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n    let $from = startDoc.resolve(from);\n    let sel = null, doc = parser.parse(parent, {\n        topNode: $from.parent,\n        topMatch: $from.parent.contentMatchAt($from.index()),\n        topOpen: true,\n        from: fromOffset,\n        to: toOffset,\n        preserveWhitespace: $from.parent.type.whitespace == \"pre\" ? \"full\" : true,\n        findPositions: find,\n        ruleFromNode: ruleFromNode(addedNodes),\n        context: $from\n    });\n    if (find && find[0].pos != null) {\n        let anchor = find[0].pos, head = find[1] && find[1].pos;\n        if (head == null)\n            head = anchor;\n        sel = { anchor: anchor + from, head: head + from };\n    }\n    return { doc, sel, from, to };\n}\nconst ruleFromNode = (added) => (dom) => {\n    let desc = dom.pmViewDesc;\n    if (desc) {\n        return desc.parseRule(added);\n    }\n    else if (dom.nodeName == \"BR\" && dom.parentNode) {\n        // Safari replaces the list item or table cell with a BR\n        // directly in the list node (?!) if you delete the last\n        // character in a list item or table cell (#708, #862)\n        if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n            let skip = document.createElement(\"div\");\n            skip.appendChild(document.createElement(\"li\"));\n            return { skip };\n        }\n        else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n            return { ignore: true };\n        }\n    }\n    else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n        return { ignore: true };\n    }\n    return null;\n};\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n    let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n    view.input.compositionPendingChanges = 0;\n    if (from < 0) {\n        let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n        let newSel = selectionFromDOM(view, origin);\n        if (newSel && !view.state.selection.eq(newSel)) {\n            if (chrome && android &&\n                view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n                dispatchKey(view, \"Enter\"))\n                return;\n            let tr = view.state.tr.setSelection(newSel);\n            if (origin == \"pointer\")\n                tr.setMeta(\"pointer\", true);\n            else if (origin == \"key\")\n                tr.scrollIntoView();\n            if (compositionID)\n                tr.setMeta(\"composition\", compositionID);\n            view.dispatch(tr);\n        }\n        return;\n    }\n    let $before = view.state.doc.resolve(from);\n    let shared = $before.sharedDepth(to);\n    from = $before.before(shared + 1);\n    to = view.state.doc.resolve(to).after(shared + 1);\n    let sel = view.state.selection;\n    let parse = parseBetween(view, from, to, addedNodes);\n    let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n    let preferredPos, preferredSide;\n    // Prefer anchoring to end when Backspace is pressed\n    if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n        preferredPos = view.state.selection.to;\n        preferredSide = \"end\";\n    }\n    else {\n        preferredPos = view.state.selection.from;\n        preferredSide = \"start\";\n    }\n    view.input.lastKeyCode = null;\n    let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n    if (change)\n        view.input.domChangeCount++;\n    if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n        addedNodes.some(n => isElt(n) && !isInline.test(n.nodeName)) &&\n        (!change || change.endA >= change.endB) &&\n        dispatchKey(view, \"Enter\")) {\n        view.input.lastIOSEnter = 0;\n        return;\n    }\n    if (!change) {\n        if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n            !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n            change = { start: sel.from, endA: sel.to, endB: sel.to };\n        }\n        else {\n            if (parse.sel) {\n                let sel = resolveSelection(view, view.state.doc, parse.sel);\n                if (sel && !sel.eq(view.state.selection)) {\n                    let tr = view.state.tr.setSelection(sel);\n                    if (compositionID)\n                        tr.setMeta(\"composition\", compositionID);\n                    view.dispatch(tr);\n                }\n            }\n            return;\n        }\n    }\n    // Handle the case where overwriting a selection by typing matches\n    // the start or end of the selected content, creating a change\n    // that's smaller than what was actually overwritten.\n    if (view.state.selection.from < view.state.selection.to &&\n        change.start == change.endB &&\n        view.state.selection instanceof TextSelection) {\n        if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 &&\n            view.state.selection.from >= parse.from) {\n            change.start = view.state.selection.from;\n        }\n        else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n            view.state.selection.to <= parse.to) {\n            change.endB += (view.state.selection.to - change.endA);\n            change.endA = view.state.selection.to;\n        }\n    }\n    // IE11 will insert a non-breaking space _ahead_ of the space after\n    // the cursor space when adding a space before another space. When\n    // that happened, adjust the change to cover the space instead.\n    if (ie && ie_version <= 11 && change.endB == change.start + 1 &&\n        change.endA == change.start && change.start > parse.from &&\n        parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n        change.start--;\n        change.endA--;\n        change.endB--;\n    }\n    let $from = parse.doc.resolveNoCache(change.start - parse.from);\n    let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n    let $fromA = doc.resolve(change.start);\n    let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\n    // If this looks like the effect of pressing Enter (or was recorded\n    // as being an iOS enter press), just dispatch an Enter key instead.\n    if (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n        (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n        (!inlineChange && looksLikeEnter(parse.doc, $from.pos, $to.pos))) &&\n        dispatchKey(view, \"Enter\")) {\n        view.input.lastIOSEnter = 0;\n        return;\n    }\n    // Same for backspace\n    if (view.state.selection.anchor > change.start &&\n        (inlineChange ? change.endA > change.start && change.endB == change.start\n            : looksLikeBlockJoin(doc, change.start, change.endA, $from, $to)) &&\n        dispatchKey(view, \"Backspace\")) {\n        if (android && chrome)\n            view.domObserver.suppressSelectionUpdates(); // #820\n        return;\n    }\n    // Chrome will occasionally, during composition, delete the\n    // entire composition and then immediately insert it again. This is\n    // used to detect that situation.\n    if (chrome && change.endB == change.start)\n        view.input.lastChromeDelete = Date.now();\n    // This tries to detect Android virtual keyboard\n    // enter-and-pick-suggestion action. That sometimes (see issue\n    // #1059) first fires a DOM mutation, before moving the selection to\n    // the newly created block. And then, because ProseMirror cleans up\n    // the DOM selection, it gives up moving the selection entirely,\n    // leaving the cursor in the wrong place. When that happens, we drop\n    // the new paragraph from the initial change, and fire a simulated\n    // enter key afterwards.\n    if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n        parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n        change.endB -= 2;\n        $to = parse.doc.resolveNoCache(change.endB - parse.from);\n        setTimeout(() => dispatchKey(view, \"Enter\"), 20);\n    }\n    let chFrom = change.start, chTo = change.endA;\n    let mkTr = (base) => {\n        let tr = base || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n        if (parse.sel) {\n            let sel = resolveSelection(view, tr.doc, parse.sel);\n            // Chrome will sometimes, during composition, report the\n            // selection in the wrong place. If it looks like that is\n            // happening, don't update the selection.\n            // Edge just doesn't move the cursor forward when you start typing\n            // in an empty block or between br nodes.\n            if (sel && !(chrome && view.composing && sel.empty &&\n                (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n                (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1) ||\n                ie && sel.empty && sel.head == chFrom))\n                tr.setSelection(sel);\n        }\n        if (compositionID)\n            tr.setMeta(\"composition\", compositionID);\n        return tr.scrollIntoView();\n    };\n    let markChange;\n    if (inlineChange) {\n        if ($from.pos == $to.pos) { // Deletion\n            // IE11 sometimes weirdly moves the DOM selection around after\n            // backspacing out the first element in a textblock\n            if (ie && ie_version <= 11 && $from.parentOffset == 0) {\n                view.domObserver.suppressSelectionUpdates();\n                setTimeout(() => selectionToDOM(view), 20);\n            }\n            let tr = mkTr(view.state.tr.delete(chFrom, chTo));\n            let marks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n            if (marks)\n                tr.ensureMarks(marks);\n            view.dispatch(tr);\n        }\n        else if ( // Adding or removing a mark\n        change.endA == change.endB &&\n            (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n            let tr = mkTr(view.state.tr);\n            if (markChange.type == \"add\")\n                tr.addMark(chFrom, chTo, markChange.mark);\n            else\n                tr.removeMark(chFrom, chTo, markChange.mark);\n            view.dispatch(tr);\n        }\n        else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n            // Both positions in the same text node -- simply insert text\n            let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n            let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo));\n            if (!view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text, deflt)))\n                view.dispatch(deflt());\n        }\n        else {\n            view.dispatch(mkTr());\n        }\n    }\n    else {\n        view.dispatch(mkTr());\n    }\n}\nfunction resolveSelection(view, doc, parsedSel) {\n    if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n        return null;\n    return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n    let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n    let added = curMarks, removed = prevMarks, type, mark, update;\n    for (let i = 0; i < prevMarks.length; i++)\n        added = prevMarks[i].removeFromSet(added);\n    for (let i = 0; i < curMarks.length; i++)\n        removed = curMarks[i].removeFromSet(removed);\n    if (added.length == 1 && removed.length == 0) {\n        mark = added[0];\n        type = \"add\";\n        update = (node) => node.mark(mark.addToSet(node.marks));\n    }\n    else if (added.length == 0 && removed.length == 1) {\n        mark = removed[0];\n        type = \"remove\";\n        update = (node) => node.mark(mark.removeFromSet(node.marks));\n    }\n    else {\n        return null;\n    }\n    let updated = [];\n    for (let i = 0; i < prev.childCount; i++)\n        updated.push(update(prev.child(i)));\n    if (Fragment.from(updated).eq(cur))\n        return { mark, type };\n}\nfunction looksLikeBlockJoin(old, start, end, $newStart, $newEnd) {\n    if ( // The content must have shrunk\n    end - start <= $newEnd.pos - $newStart.pos ||\n        // newEnd must point directly at or after the end of the block that newStart points into\n        skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n        return false;\n    let $start = old.resolve(start);\n    // Handle the case where, rather than joining blocks, the change just removed an entire block\n    if (!$newStart.parent.inlineContent) {\n        let after = $start.nodeAfter;\n        return after != null && end == start + after.nodeSize;\n    }\n    // Start must be at the end of a block\n    if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n        return false;\n    let $next = old.resolve(skipClosingAndOpening($start, true, true));\n    // The next textblock must start before end and end near it\n    if (!$next.parent.isTextblock || $next.pos > end ||\n        skipClosingAndOpening($next, true, false) < end)\n        return false;\n    // The fragments after the join point must match\n    return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction looksLikeEnter(content, from, to) {\n    let newTextlines = 0, newLeaves = 0;\n    content.nodesBetween(from, to, (node, pos) => {\n        if (node.isTextblock && pos >= from && pos < to)\n            newTextlines++;\n        else if (node.isText ? /\\S/.test(node.text.slice(Math.max(0, from - pos), Math.min(node.nodeSize, to - pos))) : node.isLeaf)\n            newLeaves++;\n    });\n    return newLeaves == 0 && newTextlines == 1;\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n    let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n    while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n        depth--;\n        end++;\n        fromEnd = false;\n    }\n    if (mayOpen) {\n        let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n        while (next && !next.isLeaf) {\n            next = next.firstChild;\n            end++;\n        }\n    }\n    return end;\n}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n    let start = a.findDiffStart(b, pos), lenA = pos + a.size, lenB = pos + b.size;\n    if (start == null)\n        return null;\n    let { a: endA, b: endB } = a.findDiffEnd(b, lenA, lenB);\n    if (preferredSide == \"end\") {\n        let adjust = Math.max(0, start - Math.min(endA, endB));\n        preferredPos -= endA + adjust - start;\n    }\n    if (endA < start && lenA < lenB) {\n        let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n        start -= move;\n        endB = start + (endB - endA);\n        endA = start;\n    }\n    else if (endB < start) {\n        let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n        start -= move;\n        endA = start + (endA - endB);\n        endB = start;\n    }\n    return { start, endA, endB };\n}\n\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n    /**\n    Create a view. `place` may be a DOM node that the editor should\n    be appended to, a function that will place it into the document,\n    or an object whose `mount` property holds the node to use as the\n    document container. If it is `null`, the editor will not be\n    added to the document.\n    */\n    constructor(place, props) {\n        this._root = null;\n        /**\n        @internal\n        */\n        this.focused = false;\n        /**\n        Kludge used to work around a Chrome bug @internal\n        */\n        this.trackWrites = null;\n        this.mounted = false;\n        /**\n        @internal\n        */\n        this.markCursor = null;\n        /**\n        @internal\n        */\n        this.cursorWrapper = null;\n        /**\n        @internal\n        */\n        this.lastSelectedViewDesc = undefined;\n        /**\n        @internal\n        */\n        this.input = new InputState;\n        this.prevDirectPlugins = [];\n        this.pluginViews = [];\n        /**\n        Holds `true` when a hack node is needed in Firefox to prevent the\n        [space is eaten issue](https://code.haverbeke.berlin/prosemirror/prosemirror/issues/651)\n        @internal\n        */\n        this.requiresGeckoHackNode = false;\n        /**\n        When editor content is being dragged, this object contains\n        information about the dragged slice and whether it is being\n        copied or moved. At any other time, it is null.\n        */\n        this.dragging = null;\n        this._props = props;\n        this.state = props.state;\n        this.directPlugins = props.plugins || [];\n        this.directPlugins.forEach(checkStateComponent);\n        this.dispatch = this.dispatch.bind(this);\n        this.dom = (place && place.mount) || document.createElement(\"div\");\n        if (place) {\n            if (place.appendChild)\n                place.appendChild(this.dom);\n            else if (typeof place == \"function\")\n                place(this.dom);\n            else if (place.mount)\n                this.mounted = true;\n        }\n        this.editable = getEditable(this);\n        updateCursorWrapper(this);\n        this.nodeViews = buildNodeViews(this);\n        this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n        this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));\n        this.domObserver.start();\n        initInput(this);\n        this.updatePluginViews();\n    }\n    /**\n    Holds `true` when a\n    [composition](https://w3c.github.io/uievents/#events-compositionevents)\n    is active.\n    */\n    get composing() { return this.input.composing; }\n    /**\n    The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n    */\n    get props() {\n        if (this._props.state != this.state) {\n            let prev = this._props;\n            this._props = {};\n            for (let name in prev)\n                this._props[name] = prev[name];\n            this._props.state = this.state;\n        }\n        return this._props;\n    }\n    /**\n    Update the view's props. Will immediately cause an update to\n    the DOM.\n    */\n    update(props) {\n        if (props.handleDOMEvents != this._props.handleDOMEvents)\n            ensureListeners(this);\n        let prevProps = this._props;\n        this._props = props;\n        if (props.plugins) {\n            props.plugins.forEach(checkStateComponent);\n            this.directPlugins = props.plugins;\n        }\n        this.updateStateInner(props.state, prevProps);\n    }\n    /**\n    Update the view by updating existing props object with the object\n    given as argument. Equivalent to `view.update(Object.assign({},\n    view.props, props))`.\n    */\n    setProps(props) {\n        let updated = {};\n        for (let name in this._props)\n            updated[name] = this._props[name];\n        updated.state = this.state;\n        for (let name in props)\n            updated[name] = props[name];\n        this.update(updated);\n    }\n    /**\n    Update the editor's `state` prop, without touching any of the\n    other props.\n    */\n    updateState(state) {\n        this.updateStateInner(state, this._props);\n    }\n    updateStateInner(state, prevProps) {\n        var _a;\n        let prev = this.state, redraw = false, updateSel = false;\n        // When stored marks are added, stop composition, so that they can\n        // be displayed.\n        if (state.storedMarks && this.composing) {\n            clearComposition(this);\n            updateSel = true;\n        }\n        this.state = state;\n        let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n        if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n            let nodeViews = buildNodeViews(this);\n            if (changedNodeViews(nodeViews, this.nodeViews)) {\n                this.nodeViews = nodeViews;\n                redraw = true;\n            }\n        }\n        if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n            ensureListeners(this);\n        }\n        this.editable = getEditable(this);\n        updateCursorWrapper(this);\n        let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n        let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n            : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n        let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n        if (updateDoc || !state.selection.eq(prev.selection))\n            updateSel = true;\n        let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n        if (updateSel) {\n            this.domObserver.stop();\n            // Work around an issue in Chrome, IE, and Edge where changing\n            // the DOM around an active selection puts it into a broken\n            // state where the thing the user sees differs from the\n            // selection reported by the Selection object (#710, #973,\n            // #1011, #1013, #1035).\n            let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing &&\n                !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n            if (updateDoc) {\n                // If the node that the selection points into is written to,\n                // Chrome sometimes starts misreporting the selection, so this\n                // tracks that and forces a selection reset when our update\n                // did write to the node.\n                let chromeKludge = chrome ? (this.trackWrites = this.domSelectionRange().focusNode) : null;\n                if (this.composing)\n                    this.input.compositionNode = findCompositionNode(this);\n                if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n                    this.docView.updateOuterDeco(outerDeco);\n                    this.docView.destroy();\n                    this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n                }\n                if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites)))\n                    forceSelUpdate = true;\n            }\n            // Work around for an issue where an update arriving right between\n            // a DOM selection change and the \"selectionchange\" event for it\n            // can cause a spurious DOM selection update, disrupting mouse\n            // drag selection.\n            let mouseDown = this.input.mouseDown;\n            if (forceSelUpdate ||\n                !(mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) &&\n                    anchorInRightPlace(this) && mouseDown.delaySelUpdate())) {\n                selectionToDOM(this, forceSelUpdate);\n            }\n            else {\n                syncNodeSelection(this, state.selection);\n                this.domObserver.setCurSelection();\n            }\n            this.domObserver.start();\n        }\n        this.updatePluginViews(prev);\n        if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n            this.updateDraggedNode(this.dragging, prev);\n        if (scroll == \"reset\") {\n            this.dom.scrollTop = 0;\n        }\n        else if (scroll == \"to selection\") {\n            this.scrollToSelection();\n        }\n        else if (oldScrollPos) {\n            resetScrollPos(oldScrollPos);\n        }\n    }\n    /**\n    @internal\n    */\n    scrollToSelection() {\n        let startDOM = this.domSelectionRange().focusNode;\n        if (!startDOM || !contains(this.dom, startDOM)) ;\n        else if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n        else if (this.state.selection instanceof NodeSelection) {\n            let target = this.docView.domAfterPos(this.state.selection.from);\n            if (isElt(target))\n                scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n        }\n        else {\n            scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n        }\n    }\n    destroyPluginViews() {\n        let view;\n        while (view = this.pluginViews.pop())\n            if (view.destroy)\n                view.destroy();\n    }\n    updatePluginViews(prevState) {\n        if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n            this.prevDirectPlugins = this.directPlugins;\n            this.destroyPluginViews();\n            for (let i = 0; i < this.directPlugins.length; i++) {\n                let plugin = this.directPlugins[i];\n                if (plugin.spec.view)\n                    this.pluginViews.push(plugin.spec.view(this));\n            }\n            for (let i = 0; i < this.state.plugins.length; i++) {\n                let plugin = this.state.plugins[i];\n                if (plugin.spec.view)\n                    this.pluginViews.push(plugin.spec.view(this));\n            }\n        }\n        else {\n            for (let i = 0; i < this.pluginViews.length; i++) {\n                let pluginView = this.pluginViews[i];\n                if (pluginView.update)\n                    pluginView.update(this, prevState);\n            }\n        }\n    }\n    updateDraggedNode(dragging, prev) {\n        let sel = dragging.node, found = -1;\n        if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) {\n            found = sel.from;\n        }\n        else {\n            let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n            let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos);\n            if (moved == sel.node)\n                found = movedPos;\n        }\n        this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n    }\n    someProp(propName, f) {\n        let prop = this._props && this._props[propName], value;\n        if (prop != null && (value = f ? f(prop) : prop))\n            return value;\n        for (let i = 0; i < this.directPlugins.length; i++) {\n            let prop = this.directPlugins[i].props[propName];\n            if (prop != null && (value = f ? f(prop) : prop))\n                return value;\n        }\n        let plugins = this.state.plugins;\n        if (plugins)\n            for (let i = 0; i < plugins.length; i++) {\n                let prop = plugins[i].props[propName];\n                if (prop != null && (value = f ? f(prop) : prop))\n                    return value;\n            }\n    }\n    /**\n    Query whether the view has focus.\n    */\n    hasFocus() {\n        // Work around IE not handling focus correctly if resize handles are shown.\n        // If the cursor is inside an element with resize handles, activeElement\n        // will be that element instead of this.dom.\n        if (ie) {\n            // If activeElement is within this.dom, and there are no other elements\n            // setting `contenteditable` to false in between, treat it as focused.\n            let node = this.root.activeElement;\n            if (node == this.dom)\n                return true;\n            if (!node || !this.dom.contains(node))\n                return false;\n            while (node && this.dom != node && this.dom.contains(node)) {\n                if (node.contentEditable == 'false')\n                    return false;\n                node = node.parentElement;\n            }\n            return true;\n        }\n        return this.root.activeElement == this.dom;\n    }\n    /**\n    Focus the editor.\n    */\n    focus() {\n        this.domObserver.stop();\n        if (this.editable)\n            focusPreventScroll(this.dom);\n        selectionToDOM(this);\n        this.domObserver.start();\n    }\n    /**\n    Get the document root in which the editor exists. This will\n    usually be the top-level `document`, but might be a [shadow\n    DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n    root if the editor is inside one.\n    */\n    get root() {\n        let cached = this._root;\n        if (cached == null)\n            for (let search = this.dom.parentNode; search; search = search.parentNode) {\n                if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n                    if (!search.getSelection)\n                        Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n                    return this._root = search;\n                }\n            }\n        return cached || document;\n    }\n    /**\n    When an existing editor view is moved to a new document or\n    shadow tree, call this to make it recompute its root.\n    */\n    updateRoot() {\n        this._root = null;\n    }\n    /**\n    Given a pair of viewport coordinates, return the document\n    position that corresponds to them. May return null if the given\n    coordinates aren't inside of the editor. When an object is\n    returned, its `pos` property is the position nearest to the\n    coordinates, and its `inside` property holds the position of the\n    inner node that the position falls inside of, or -1 if it is at\n    the top level, not in any node.\n    */\n    posAtCoords(coords) {\n        return posAtCoords(this, coords);\n    }\n    /**\n    Returns the viewport rectangle at a given document position.\n    `left` and `right` will be the same number, as this returns a\n    flat cursor-ish rectangle. If the position is between two things\n    that aren't directly adjacent, `side` determines which element\n    is used. When < 0, the element before the position is used,\n    otherwise the element after.\n    */\n    coordsAtPos(pos, side = 1) {\n        return coordsAtPos(this, pos, side);\n    }\n    /**\n    Find the DOM position that corresponds to the given document\n    position. When `side` is negative, find the position as close as\n    possible to the content before the position. When positive,\n    prefer positions close to the content after the position. When\n    zero, prefer as shallow a position as possible.\n    \n    Note that you should **not** mutate the editor's internal DOM,\n    only inspect it (and even that is usually not necessary).\n    */\n    domAtPos(pos, side = 0) {\n        return this.docView.domFromPos(pos, side);\n    }\n    /**\n    Find the DOM node that represents the document node after the\n    given position. May return `null` when the position doesn't point\n    in front of a node or if the node is inside an opaque node view.\n    \n    This is intended to be able to call things like\n    `getBoundingClientRect` on that DOM node. Do **not** mutate the\n    editor DOM directly, or add styling this way, since that will be\n    immediately overriden by the editor as it redraws the node.\n    */\n    nodeDOM(pos) {\n        let desc = this.docView.descAt(pos);\n        return desc ? desc.nodeDOM : null;\n    }\n    /**\n    Find the document position that corresponds to a given DOM\n    position. (Whenever possible, it is preferable to inspect the\n    document structure directly, rather than poking around in the\n    DOM, but sometimes\u2014for example when interpreting an event\n    target\u2014you don't have a choice.)\n    \n    The `bias` parameter can be used to influence which side of a DOM\n    node to use when the position is inside a leaf node.\n    */\n    posAtDOM(node, offset, bias = -1) {\n        let pos = this.docView.posFromDOM(node, offset, bias);\n        if (pos == null)\n            throw new RangeError(\"DOM position not inside the editor\");\n        return pos;\n    }\n    /**\n    Find out whether the selection is at the end of a textblock when\n    moving in a given direction. When, for example, given `\"left\"`,\n    it will return true if moving left from the current cursor\n    position would leave that position's parent textblock. Will apply\n    to the view's current state by default, but it is possible to\n    pass a different state.\n    */\n    endOfTextblock(dir, state) {\n        return endOfTextblock(this, state || this.state, dir);\n    }\n    /**\n    Run the editor's paste logic with the given HTML string. The\n    `event`, if given, will be passed to the\n    [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n    */\n    pasteHTML(html, event) {\n        return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n    }\n    /**\n    Run the editor's paste logic with the given plain-text input.\n    */\n    pasteText(text, event) {\n        return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n    }\n    /**\n    Serialize the given slice as it would be if it was copied from\n    this editor. Returns a DOM element that contains a\n    representation of the slice as its children, a textual\n    representation, and the transformed slice (which can be\n    different from the given input due to hooks like\n    [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).\n    */\n    serializeForClipboard(slice) {\n        return serializeForClipboard(this, slice);\n    }\n    /**\n    Removes the editor from the DOM and destroys all [node\n    views](https://prosemirror.net/docs/ref/#view.NodeView).\n    */\n    destroy() {\n        if (!this.docView)\n            return;\n        destroyInput(this);\n        this.destroyPluginViews();\n        if (this.mounted) {\n            this.docView.update(this.state.doc, [], viewDecorations(this), this);\n            this.dom.textContent = \"\";\n        }\n        else if (this.dom.parentNode) {\n            this.dom.parentNode.removeChild(this.dom);\n        }\n        this.docView.destroy();\n        this.docView = null;\n        clearReusedRange();\n    }\n    /**\n    This is true when the view has been\n    [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n    used anymore).\n    */\n    get isDestroyed() {\n        return this.docView == null;\n    }\n    /**\n    Used for testing.\n    */\n    dispatchEvent(event) {\n        return dispatchEvent(this, event);\n    }\n    /**\n    @internal\n    */\n    domSelectionRange() {\n        let sel = this.dom.isConnected !== false && this.domSelection();\n        if (!sel)\n            return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };\n        return safari && this.root.nodeType === 11 &&\n            deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;\n    }\n    /**\n    @internal\n    */\n    domSelection() {\n        return this.root.getSelection();\n    }\n}\nEditorView.prototype.dispatch = function (tr) {\n    let dispatchTransaction = this._props.dispatchTransaction;\n    if (dispatchTransaction)\n        dispatchTransaction.call(this, tr);\n    else\n        this.updateState(this.state.apply(tr));\n};\nfunction computeDocDeco(view) {\n    let attrs = Object.create(null);\n    attrs.class = \"ProseMirror\";\n    attrs.contenteditable = String(view.editable);\n    view.someProp(\"attributes\", value => {\n        if (typeof value == \"function\")\n            value = value(view.state);\n        if (value)\n            for (let attr in value) {\n                if (attr == \"class\")\n                    attrs.class += \" \" + value[attr];\n                else if (attr == \"style\")\n                    attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n                else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n                    attrs[attr] = String(value[attr]);\n            }\n    });\n    if (!attrs.translate)\n        attrs.translate = \"no\";\n    return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n    if (view.markCursor) {\n        let dom = document.createElement(\"img\");\n        dom.className = \"ProseMirror-separator\";\n        dom.setAttribute(\"mark-placeholder\", \"true\");\n        dom.setAttribute(\"alt\", \"\");\n        view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n    }\n    else {\n        view.cursorWrapper = null;\n    }\n}\nfunction getEditable(view) {\n    return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n    let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n    return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n    let result = Object.create(null);\n    function add(obj) {\n        for (let prop in obj)\n            if (!Object.prototype.hasOwnProperty.call(result, prop))\n                result[prop] = obj[prop];\n    }\n    view.someProp(\"nodeViews\", add);\n    view.someProp(\"markViews\", add);\n    return result;\n}\nfunction changedNodeViews(a, b) {\n    let nA = 0, nB = 0;\n    for (let prop in a) {\n        if (a[prop] != b[prop])\n            return true;\n        nA++;\n    }\n    for (let _ in b)\n        nB++;\n    return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n    if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n        throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard };\n", "export var base = {\n  8: \"Backspace\",\n  9: \"Tab\",\n  10: \"Enter\",\n  12: \"NumLock\",\n  13: \"Enter\",\n  16: \"Shift\",\n  17: \"Control\",\n  18: \"Alt\",\n  20: \"CapsLock\",\n  27: \"Escape\",\n  32: \" \",\n  33: \"PageUp\",\n  34: \"PageDown\",\n  35: \"End\",\n  36: \"Home\",\n  37: \"ArrowLeft\",\n  38: \"ArrowUp\",\n  39: \"ArrowRight\",\n  40: \"ArrowDown\",\n  44: \"PrintScreen\",\n  45: \"Insert\",\n  46: \"Delete\",\n  59: \";\",\n  61: \"=\",\n  91: \"Meta\",\n  92: \"Meta\",\n  106: \"*\",\n  107: \"+\",\n  108: \",\",\n  109: \"-\",\n  110: \".\",\n  111: \"/\",\n  144: \"NumLock\",\n  145: \"ScrollLock\",\n  160: \"Shift\",\n  161: \"Shift\",\n  162: \"Control\",\n  163: \"Control\",\n  164: \"Alt\",\n  165: \"Alt\",\n  173: \"-\",\n  186: \";\",\n  187: \"=\",\n  188: \",\",\n  189: \"-\",\n  190: \".\",\n  191: \"/\",\n  192: \"`\",\n  219: \"[\",\n  220: \"\\\\\",\n  221: \"]\",\n  222: \"'\"\n}\n\nexport var shift = {\n  48: \")\",\n  49: \"!\",\n  50: \"@\",\n  51: \"#\",\n  52: \"$\",\n  53: \"%\",\n  54: \"^\",\n  55: \"&\",\n  56: \"*\",\n  57: \"(\",\n  59: \":\",\n  61: \"+\",\n  173: \"_\",\n  186: \":\",\n  187: \"+\",\n  188: \"<\",\n  189: \"_\",\n  190: \">\",\n  191: \"?\",\n  192: \"~\",\n  219: \"{\",\n  220: \"|\",\n  221: \"}\",\n  222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n  base[i] = String.fromCharCode(i + 32)\n  shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n  // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n  // On IE, shift effect is never included in `.key`.\n  var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n      ie && event.shiftKey && event.key && event.key.length == 1 ||\n      event.key == \"Unidentified\"\n  var name = (!ignoreKey && event.key) ||\n    (event.shiftKey ? shift : base)[event.keyCode] ||\n    event.key || \"Unidentified\"\n  // Edge sometimes produces wrong names (Issue #3)\n  if (name == \"Esc\") name = \"Escape\"\n  if (name == \"Del\") name = \"Delete\"\n  // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n  if (name == \"Left\") name = \"ArrowLeft\"\n  if (name == \"Up\") name = \"ArrowUp\"\n  if (name == \"Right\") name = \"ArrowRight\"\n  if (name == \"Down\") name = \"ArrowDown\"\n  return name\n}\n", "import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\nconst mac = typeof navigator != \"undefined\" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);\nconst windows = typeof navigator != \"undefined\" && /Win/.test(navigator.platform);\nfunction normalizeKeyName(name) {\n    let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n    if (result == \"Space\")\n        result = \" \";\n    let alt, ctrl, shift, meta;\n    for (let i = 0; i < parts.length - 1; i++) {\n        let mod = parts[i];\n        if (/^(cmd|meta|m)$/i.test(mod))\n            meta = true;\n        else if (/^a(lt)?$/i.test(mod))\n            alt = true;\n        else if (/^(c|ctrl|control)$/i.test(mod))\n            ctrl = true;\n        else if (/^s(hift)?$/i.test(mod))\n            shift = true;\n        else if (/^mod$/i.test(mod)) {\n            if (mac)\n                meta = true;\n            else\n                ctrl = true;\n        }\n        else\n            throw new Error(\"Unrecognized modifier name: \" + mod);\n    }\n    if (alt)\n        result = \"Alt-\" + result;\n    if (ctrl)\n        result = \"Ctrl-\" + result;\n    if (meta)\n        result = \"Meta-\" + result;\n    if (shift)\n        result = \"Shift-\" + result;\n    return result;\n}\nfunction normalize(map) {\n    let copy = Object.create(null);\n    for (let prop in map)\n        copy[normalizeKeyName(prop)] = map[prop];\n    return copy;\n}\nfunction modifiers(name, event, shift = true) {\n    if (event.altKey)\n        name = \"Alt-\" + name;\n    if (event.ctrlKey)\n        name = \"Ctrl-\" + name;\n    if (event.metaKey)\n        name = \"Meta-\" + name;\n    if (shift && event.shiftKey)\n        name = \"Shift-\" + name;\n    return name;\n}\n/**\nCreate a keymap plugin for the given set of bindings.\n\nBindings should map key names to [command](https://prosemirror.net/docs/ref/#commands)-style\nfunctions, which will be called with `(EditorState, dispatch,\nEditorView)` arguments, and should return true when they've handled\nthe key. Note that the view argument isn't part of the command\nprotocol, but can be used as an escape hatch if a binding needs to\ndirectly interact with the UI.\n\nKey names may be strings like `\"Shift-Ctrl-Enter\"`\u2014a key\nidentifier prefixed with zero or more modifiers. Key identifiers\nare based on the strings that can appear in\n[`KeyEvent.key`](https:developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\nUse lowercase letters to refer to letter keys (or uppercase letters\nif you want shift to be held). You may use `\"Space\"` as an alias\nfor the `\" \"` name.\n\nModifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n`Meta-`) are recognized. For characters that are created by holding\nshift, the `Shift-` prefix is implied, and should not be added\nexplicitly.\n\nYou can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\nother platforms.\n\nYou can add multiple keymap plugins to an editor. The order in\nwhich they appear determines their precedence (the ones early in\nthe array get to dispatch first).\n*/\nfunction keymap(bindings) {\n    return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });\n}\n/**\nGiven a set of bindings (using the same format as\n[`keymap`](https://prosemirror.net/docs/ref/#keymap.keymap)), return a [keydown\nhandler](https://prosemirror.net/docs/ref/#view.EditorProps.handleKeyDown) that handles them.\n*/\nfunction keydownHandler(bindings) {\n    let map = normalize(bindings);\n    return function (view, event) {\n        let name = keyName(event), baseName, direct = map[modifiers(name, event)];\n        if (direct && direct(view.state, view.dispatch, view))\n            return true;\n        // A character key\n        if (name.length == 1 && name != \" \") {\n            if (event.shiftKey) {\n                // In case the name was already modified by shift, try looking\n                // it up without its shift modifier\n                let noShift = map[modifiers(name, event, false)];\n                if (noShift && noShift(view.state, view.dispatch, view))\n                    return true;\n            }\n            if ((event.altKey || event.metaKey || event.ctrlKey) &&\n                // Ctrl-Alt may be used for AltGr on Windows\n                !(windows && event.ctrlKey && event.altKey) &&\n                (baseName = base[event.keyCode]) && baseName != name) {\n                // Try falling back to the keyCode when there's a modifier\n                // active or the character produced isn't ASCII, and our table\n                // produces a different name from the the keyCode. See #668,\n                // #1060, #1529.\n                let fromCode = map[modifiers(baseName, event)];\n                if (fromCode && fromCode(view.state, view.dispatch, view))\n                    return true;\n            }\n        }\n        return false;\n    };\n}\n\nexport { keydownHandler, keymap };\n", "import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection, SelectionRange } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n    if (state.selection.empty)\n        return false;\n    if (dispatch)\n        dispatch(state.tr.deleteSelection().scrollIntoView());\n    return true;\n};\nfunction atBlockStart(state, view) {\n    let { $cursor } = state.selection;\n    if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n        : $cursor.parentOffset > 0))\n        return null;\n    return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it\u2014if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n    let $cursor = atBlockStart(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutBefore($cursor);\n    // If there is no node before this, try to lift\n    if (!$cut) {\n        let range = $cursor.blockRange(), target = range && liftTarget(range);\n        if (target == null)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.lift(range, target).scrollIntoView());\n        return true;\n    }\n    let before = $cut.nodeBefore;\n    // Apply the joining algorithm\n    if (deleteBarrier(state, $cut, dispatch, -1))\n        return true;\n    // If the node below has no content and the node above is\n    // selectable, delete the node below and select the one above.\n    if ($cursor.parent.content.size == 0 &&\n        (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n        for (let depth = $cursor.depth;; depth--) {\n            let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);\n            if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n                if (dispatch) {\n                    let tr = state.tr.step(delStep);\n                    tr.setSelection(textblockAt(before, \"end\")\n                        ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n                        : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n                    dispatch(tr.scrollIntoView());\n                }\n                return true;\n            }\n            if (depth == 1 || $cursor.node(depth - 1).childCount > 1)\n                break;\n        }\n    }\n    // If the node before is an atom, delete it\n    if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n        if (dispatch)\n            dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n        return true;\n    }\n    return false;\n};\n/**\nA more limited form of [`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n    let $cursor = atBlockStart(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutBefore($cursor);\n    return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n    let $cursor = atBlockEnd(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutAfter($cursor);\n    return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n    let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;\n    for (; !beforeText.isTextblock; beforePos--) {\n        if (beforeText.type.spec.isolating)\n            return false;\n        let child = beforeText.lastChild;\n        if (!child)\n            return false;\n        beforeText = child;\n    }\n    let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;\n    for (; !afterText.isTextblock; afterPos++) {\n        if (afterText.type.spec.isolating)\n            return false;\n        let child = afterText.firstChild;\n        if (!child)\n            return false;\n        afterText = child;\n    }\n    let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n    if (!step || step.from != beforePos ||\n        step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)\n        return false;\n    if (dispatch) {\n        let tr = state.tr.step(step);\n        tr.setSelection(TextSelection.create(tr.doc, beforePos));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n}\nfunction textblockAt(node, side, only = false) {\n    for (let scan = node; scan; scan = (side == \"start\" ? scan.firstChild : scan.lastChild)) {\n        if (scan.isTextblock)\n            return true;\n        if (only && scan.childCount != 1)\n            return false;\n    }\n    return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n    let { $head, empty } = state.selection, $cut = $head;\n    if (!empty)\n        return false;\n    if ($head.parent.isTextblock) {\n        if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0)\n            return false;\n        $cut = findCutBefore($head);\n    }\n    let node = $cut && $cut.nodeBefore;\n    if (!node || !NodeSelection.isSelectable(node))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n    return true;\n};\nfunction findCutBefore($pos) {\n    if (!$pos.parent.type.spec.isolating)\n        for (let i = $pos.depth - 1; i >= 0; i--) {\n            if ($pos.index(i) > 0)\n                return $pos.doc.resolve($pos.before(i + 1));\n            if ($pos.node(i).type.spec.isolating)\n                break;\n        }\n    return null;\n}\nfunction atBlockEnd(state, view) {\n    let { $cursor } = state.selection;\n    if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n        : $cursor.parentOffset < $cursor.parent.content.size))\n        return null;\n    return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n    let $cursor = atBlockEnd(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutAfter($cursor);\n    // If there is no node after this, there's nothing to do\n    if (!$cut)\n        return false;\n    let after = $cut.nodeAfter;\n    // Try the joining algorithm\n    if (deleteBarrier(state, $cut, dispatch, 1))\n        return true;\n    // If the node above has no content and the node below is\n    // selectable, delete the node above and select the one below.\n    if ($cursor.parent.content.size == 0 &&\n        (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n        let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n        if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n            if (dispatch) {\n                let tr = state.tr.step(delStep);\n                tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n                    : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n                dispatch(tr.scrollIntoView());\n            }\n            return true;\n        }\n    }\n    // If the next node is an atom, delete it\n    if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n        if (dispatch)\n            dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n        return true;\n    }\n    return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n    let { $head, empty } = state.selection, $cut = $head;\n    if (!empty)\n        return false;\n    if ($head.parent.isTextblock) {\n        if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n            return false;\n        $cut = findCutAfter($head);\n    }\n    let node = $cut && $cut.nodeAfter;\n    if (!node || !NodeSelection.isSelectable(node))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n    return true;\n};\nfunction findCutAfter($pos) {\n    if (!$pos.parent.type.spec.isolating)\n        for (let i = $pos.depth - 1; i >= 0; i--) {\n            let parent = $pos.node(i);\n            if ($pos.index(i) + 1 < parent.childCount)\n                return $pos.doc.resolve($pos.after(i + 1));\n            if (parent.type.spec.isolating)\n                break;\n        }\n    return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n    let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n    if (nodeSel) {\n        if (sel.node.isTextblock || !canJoin(state.doc, sel.from))\n            return false;\n        point = sel.from;\n    }\n    else {\n        point = joinPoint(state.doc, sel.from, -1);\n        if (point == null)\n            return false;\n    }\n    if (dispatch) {\n        let tr = state.tr.join(point);\n        if (nodeSel)\n            tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n    let sel = state.selection, point;\n    if (sel instanceof NodeSelection) {\n        if (sel.node.isTextblock || !canJoin(state.doc, sel.to))\n            return false;\n        point = sel.to;\n    }\n    else {\n        point = joinPoint(state.doc, sel.to, 1);\n        if (point == null)\n            return false;\n    }\n    if (dispatch)\n        dispatch(state.tr.join(point).scrollIntoView());\n    return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n    let { $from, $to } = state.selection;\n    let range = $from.blockRange($to), target = range && liftTarget(range);\n    if (target == null)\n        return false;\n    if (dispatch)\n        dispatch(state.tr.lift(range, target).scrollIntoView());\n    return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n    let { $head, $anchor } = state.selection;\n    if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n    return true;\n};\nfunction defaultBlockAt(match) {\n    for (let i = 0; i < match.edgeCount; i++) {\n        let { type } = match.edge(i);\n        if (type.isTextblock && !type.hasRequiredAttrs())\n            return type;\n    }\n    return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n    let { $head, $anchor } = state.selection;\n    if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n        return false;\n    let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n    if (!type || !above.canReplaceWith(after, after, type))\n        return false;\n    if (dispatch) {\n        let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n        tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n    let sel = state.selection, { $from, $to } = sel;\n    if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)\n        return false;\n    let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n    if (!type || !type.isTextblock)\n        return false;\n    if (dispatch) {\n        let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n        let tr = state.tr.insert(side, type.createAndFill());\n        tr.setSelection(TextSelection.create(tr.doc, side + 1));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n    let { $cursor } = state.selection;\n    if (!$cursor || $cursor.parent.content.size)\n        return false;\n    if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n        let before = $cursor.before();\n        if (canSplit(state.doc, before)) {\n            if (dispatch)\n                dispatch(state.tr.split(before).scrollIntoView());\n            return true;\n        }\n    }\n    let range = $cursor.blockRange(), target = range && liftTarget(range);\n    if (target == null)\n        return false;\n    if (dispatch)\n        dispatch(state.tr.lift(range, target).scrollIntoView());\n    return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n    return (state, dispatch) => {\n        if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n            let { $from } = state.selection;\n            if (!$from.parentOffset || !canSplit(state.doc, $from.pos))\n                return false;\n            if (dispatch)\n                dispatch(state.tr.split($from.pos).scrollIntoView());\n            return true;\n        }\n        if (!state.selection.$from.depth)\n            return false;\n        let tr = state.tr;\n        if (!state.selection.empty && (state.selection instanceof TextSelection || state.selection instanceof AllSelection))\n            tr.deleteSelection();\n        let { $from } = tr.selection, mapFrom = tr.steps.length;\n        let types = [];\n        let splitDepth, deflt, atEnd = false, atStart = false;\n        for (let d = $from.depth;; d--) {\n            let node = $from.node(d);\n            if (node.isBlock) {\n                atEnd = $from.end(d) == $from.pos + ($from.depth - d);\n                atStart = $from.start(d) == $from.pos - ($from.depth - d);\n                deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));\n                let splitType = splitNode && splitNode($from.parent, atEnd, $from);\n                types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));\n                splitDepth = d;\n                break;\n            }\n            else {\n                if (d == 1)\n                    return false;\n                types.unshift(null);\n            }\n        }\n        let splitPos = $from.pos;\n        let can = canSplit(tr.doc, splitPos, types.length, types);\n        if (!can) {\n            types[0] = deflt ? { type: deflt } : null;\n            can = canSplit(tr.doc, splitPos, types.length, types);\n        }\n        if (!can)\n            return false;\n        tr.split(splitPos, types.length, types);\n        if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {\n            let mapping = tr.mapping.slice(mapFrom);\n            let first = mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);\n            if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))\n                tr.setNodeMarkup(mapping.map($from.before(splitDepth)), deflt);\n        }\n        if (dispatch)\n            dispatch(tr.scrollIntoView());\n        return true;\n    };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n    return splitBlock(state, dispatch && (tr => {\n        let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n        if (marks)\n            tr.ensureMarks(marks);\n        dispatch(tr);\n    }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n    let { $from, to } = state.selection, pos;\n    let same = $from.sharedDepth(to);\n    if (same == 0)\n        return false;\n    pos = $from.before(same);\n    if (dispatch)\n        dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n    return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n    if (dispatch)\n        dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n    return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n    let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n    if (!before || !after || !before.type.compatibleContent(after.type))\n        return false;\n    if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n        if (dispatch)\n            dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n        return true;\n    }\n    if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.join($pos.pos).scrollIntoView());\n    return true;\n}\nfunction deleteBarrier(state, $cut, dispatch, dir) {\n    let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n    let isolated = before.type.spec.isolating || after.type.spec.isolating;\n    if (!isolated && joinMaybeClear(state, $cut, dispatch))\n        return true;\n    let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n    if (canDelAfter &&\n        (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n        match.matchType(conn[0] || after.type).validEnd) {\n        if (dispatch) {\n            let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n            for (let i = conn.length - 1; i >= 0; i--)\n                wrap = Fragment.from(conn[i].create(null, wrap));\n            wrap = Fragment.from(before.copy(wrap));\n            let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n            let $joinAt = tr.doc.resolve(end + 2 * conn.length);\n            if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type &&\n                canJoin(tr.doc, $joinAt.pos))\n                tr.join($joinAt.pos);\n            dispatch(tr.scrollIntoView());\n        }\n        return true;\n    }\n    let selAfter = after.type.spec.isolating || (dir > 0 && isolated) ? null : Selection.findFrom($cut, 1);\n    let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n    if (target != null && target >= $cut.depth) {\n        if (dispatch)\n            dispatch(state.tr.lift(range, target).scrollIntoView());\n        return true;\n    }\n    if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n        let at = before, wrap = [];\n        for (;;) {\n            wrap.push(at);\n            if (at.isTextblock)\n                break;\n            at = at.lastChild;\n        }\n        let afterText = after, afterDepth = 1;\n        for (; !afterText.isTextblock; afterText = afterText.firstChild)\n            afterDepth++;\n        if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n            if (dispatch) {\n                let end = Fragment.empty;\n                for (let i = wrap.length - 1; i >= 0; i--)\n                    end = Fragment.from(wrap[i].copy(end));\n                let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n                dispatch(tr.scrollIntoView());\n            }\n            return true;\n        }\n    }\n    return false;\n}\nfunction selectTextblockSide(side) {\n    return function (state, dispatch) {\n        let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;\n        let depth = $pos.depth;\n        while ($pos.node(depth).isInline) {\n            if (!depth)\n                return false;\n            depth--;\n        }\n        if (!$pos.node(depth).isTextblock)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n        return true;\n    };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n        if (!wrapping)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n        return true;\n    };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n    return function (state, dispatch) {\n        let applicable = false;\n        for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n            let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n            state.doc.nodesBetween(from, to, (node, pos) => {\n                if (applicable)\n                    return false;\n                if (!node.isTextblock || node.hasMarkup(nodeType, attrs))\n                    return;\n                if (node.type == nodeType) {\n                    applicable = true;\n                }\n                else {\n                    let $pos = state.doc.resolve(pos), index = $pos.index();\n                    applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n                }\n            });\n        }\n        if (!applicable)\n            return false;\n        if (dispatch) {\n            let tr = state.tr;\n            for (let i = 0; i < state.selection.ranges.length; i++) {\n                let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n                tr.setBlockType(from, to, nodeType, attrs);\n            }\n            dispatch(tr.scrollIntoView());\n        }\n        return true;\n    };\n}\nfunction markApplies(doc, ranges, type, enterAtoms) {\n    for (let i = 0; i < ranges.length; i++) {\n        let { $from, $to } = ranges[i];\n        let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n        doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n            if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)\n                return false;\n            can = node.inlineContent && node.type.allowsMarkType(type);\n        });\n        if (can)\n            return true;\n    }\n    return false;\n}\nfunction removeInlineAtoms(ranges) {\n    let result = [];\n    for (let i = 0; i < ranges.length; i++) {\n        let { $from, $to } = ranges[i];\n        $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n            if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {\n                if (pos + 1 > $from.pos)\n                    result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));\n                $from = $from.doc.resolve(pos + 1 + node.content.size);\n                return false;\n            }\n        });\n        if ($from.pos < $to.pos)\n            result.push(new SelectionRange($from, $to));\n    }\n    return result;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null, options) {\n    let removeWhenPresent = (options && options.removeWhenPresent) !== false;\n    let enterAtoms = (options && options.enterInlineAtoms) !== false;\n    let dropSpace = !(options && options.includeWhitespace);\n    return function (state, dispatch) {\n        let { empty, $cursor, ranges } = state.selection;\n        if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType, enterAtoms))\n            return false;\n        if (dispatch) {\n            if ($cursor) {\n                if (markType.isInSet(state.storedMarks || $cursor.marks()))\n                    dispatch(state.tr.removeStoredMark(markType));\n                else\n                    dispatch(state.tr.addStoredMark(markType.create(attrs)));\n            }\n            else {\n                let add, tr = state.tr;\n                if (!enterAtoms)\n                    ranges = removeInlineAtoms(ranges);\n                if (removeWhenPresent) {\n                    add = !ranges.some(r => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));\n                }\n                else {\n                    add = !ranges.every(r => {\n                        let missing = false;\n                        tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {\n                            if (missing)\n                                return false;\n                            missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) &&\n                                !(node.isText && /^\\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));\n                        });\n                        return !missing;\n                    });\n                }\n                for (let i = 0; i < ranges.length; i++) {\n                    let { $from, $to } = ranges[i];\n                    if (!add) {\n                        tr.removeMark($from.pos, $to.pos, markType);\n                    }\n                    else {\n                        let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;\n                        let spaceStart = dropSpace && start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n                        let spaceEnd = dropSpace && end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n                        if (from + spaceStart < to) {\n                            from += spaceStart;\n                            to -= spaceEnd;\n                        }\n                        tr.addMark(from, to, markType.create(attrs));\n                    }\n                }\n                dispatch(tr.scrollIntoView());\n            }\n        }\n        return true;\n    };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n    return (tr) => {\n        if (!tr.isGeneric)\n            return dispatch(tr);\n        let ranges = [];\n        for (let i = 0; i < tr.mapping.maps.length; i++) {\n            let map = tr.mapping.maps[i];\n            for (let j = 0; j < ranges.length; j++)\n                ranges[j] = map.map(ranges[j]);\n            map.forEach((_s, _e, from, to) => ranges.push(from, to));\n        }\n        // Figure out which joinable points exist inside those ranges,\n        // by checking all node boundaries in their parent nodes.\n        let joinable = [];\n        for (let i = 0; i < ranges.length; i += 2) {\n            let from = ranges[i], to = ranges[i + 1];\n            let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n            for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n                let after = parent.maybeChild(index);\n                if (!after)\n                    break;\n                if (index && joinable.indexOf(pos) == -1) {\n                    let before = parent.child(index - 1);\n                    if (before.type == after.type && isJoinable(before, after))\n                        joinable.push(pos);\n                }\n                pos += after.nodeSize;\n            }\n        }\n        // Join the joinable points\n        joinable.sort((a, b) => a - b);\n        for (let i = joinable.length - 1; i >= 0; i--) {\n            if (canJoin(tr.doc, joinable[i]))\n                tr.join(joinable[i]);\n        }\n        dispatch(tr);\n    };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n    let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1\n        : isJoinable;\n    return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n    return function (state, dispatch, view) {\n        for (let i = 0; i < commands.length; i++)\n            if (commands[i](state, dispatch, view))\n                return true;\n        return false;\n    };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n    \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n    \"Mod-Enter\": exitCode,\n    \"Backspace\": backspace,\n    \"Mod-Backspace\": backspace,\n    \"Shift-Backspace\": backspace,\n    \"Delete\": del,\n    \"Mod-Delete\": del,\n    \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n    \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n    \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n    \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n    \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n    \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n    \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n    \"Ctrl-a\": selectTextblockStart,\n    \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap)\n    macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n    // @ts-ignore\n    : typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };\n", "import { findWrapping, ReplaceAroundStep, canSplit, liftTarget, canJoin } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice, NodeType } from 'prosemirror-model';\nimport { Selection } from 'prosemirror-state';\n\nconst olDOM = [\"ol\", 0], ulDOM = [\"ul\", 0], liDOM = [\"li\", 0];\n/**\nAn ordered list [node spec](https://prosemirror.net/docs/ref/#model.NodeSpec). Has a single\nattribute, `order`, which determines the number at which the list\nstarts counting, and defaults to 1. Represented as an `<ol>`\nelement.\n*/\nconst orderedList = {\n    attrs: { order: { default: 1, validate: \"number\" } },\n    parseDOM: [{ tag: \"ol\", getAttrs(dom) {\n                return { order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1 };\n            } }],\n    toDOM(node) {\n        return node.attrs.order == 1 ? olDOM : [\"ol\", { start: node.attrs.order }, 0];\n    }\n};\n/**\nA bullet list node spec, represented in the DOM as `<ul>`.\n*/\nconst bulletList = {\n    parseDOM: [{ tag: \"ul\" }],\n    toDOM() { return ulDOM; }\n};\n/**\nA list item (`<li>`) spec.\n*/\nconst listItem = {\n    parseDOM: [{ tag: \"li\" }],\n    toDOM() { return liDOM; },\n    defining: true\n};\nfunction add(obj, props) {\n    let copy = {};\n    for (let prop in obj)\n        copy[prop] = obj[prop];\n    for (let prop in props)\n        copy[prop] = props[prop];\n    return copy;\n}\n/**\nConvenience function for adding list-related node types to a map\nspecifying the nodes for a schema. Adds\n[`orderedList`](https://prosemirror.net/docs/ref/#schema-list.orderedList) as `\"ordered_list\"`,\n[`bulletList`](https://prosemirror.net/docs/ref/#schema-list.bulletList) as `\"bullet_list\"`, and\n[`listItem`](https://prosemirror.net/docs/ref/#schema-list.listItem) as `\"list_item\"`.\n\n`itemContent` determines the content expression for the list items.\nIf you want the commands defined in this module to apply to your\nlist structure, it should have a shape like `\"paragraph block*\"` or\n`\"paragraph (ordered_list | bullet_list)*\"`. `listGroup` can be\ngiven to assign a group name to the list node types, for example\n`\"block\"`.\n*/\nfunction addListNodes(nodes, itemContent, listGroup) {\n    return nodes.append({\n        ordered_list: add(orderedList, { content: \"list_item+\", group: listGroup }),\n        bullet_list: add(bulletList, { content: \"list_item+\", group: listGroup }),\n        list_item: add(listItem, { content: itemContent })\n    });\n}\n/**\nReturns a command function that wraps the selection in a list with\nthe given type an attributes. If `dispatch` is null, only return a\nvalue to indicate whether this is possible, but don't actually\nperform the change.\n*/\nfunction wrapInList(listType, attrs = null) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to);\n        if (!range)\n            return false;\n        let tr = dispatch ? state.tr : null;\n        if (!wrapRangeInList(tr, range, listType, attrs))\n            return false;\n        if (dispatch)\n            dispatch(tr.scrollIntoView());\n        return true;\n    };\n}\n/**\nTry to wrap the given node range in a list of the given type.\nReturn `true` when this is possible, `false` otherwise. When `tr`\nis non-null, the wrapping is added to that transaction. When it is\n`null`, the function only queries whether the wrapping is\npossible.\n*/\nfunction wrapRangeInList(tr, range, listType, attrs = null) {\n    let doJoin = false, outerRange = range, doc = range.$from.doc;\n    // This is at the top of an existing list item\n    if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {\n        // Don't do anything if this is the top of the list\n        if (range.$from.index(range.depth - 1) == 0)\n            return false;\n        let $insert = doc.resolve(range.start - 2);\n        outerRange = new NodeRange($insert, $insert, range.depth);\n        if (range.endIndex < range.parent.childCount)\n            range = new NodeRange(range.$from, doc.resolve(range.$to.end(range.depth)), range.depth);\n        doJoin = true;\n    }\n    let wrap = findWrapping(outerRange, listType, attrs, range);\n    if (!wrap)\n        return false;\n    if (tr)\n        doWrapInList(tr, range, wrap, doJoin, listType);\n    return true;\n}\nfunction doWrapInList(tr, range, wrappers, joinBefore, listType) {\n    let content = Fragment.empty;\n    for (let i = wrappers.length - 1; i >= 0; i--)\n        content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n    tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));\n    let found = 0;\n    for (let i = 0; i < wrappers.length; i++)\n        if (wrappers[i].type == listType)\n            found = i + 1;\n    let splitDepth = wrappers.length - found;\n    let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;\n    for (let i = range.startIndex, e = range.endIndex, first = true; i < e; i++, first = false) {\n        if (!first && splitDepth && canSplit(tr.doc, splitPos, splitDepth)) {\n            tr.split(splitPos, splitDepth);\n            splitPos += 2 * splitDepth;\n        }\n        splitPos += parent.child(i).nodeSize;\n    }\n    return tr;\n}\nfunction isItem(itemType, type) {\n    return itemType instanceof NodeType ? type == itemType : itemType.indexOf(type) > -1;\n}\n/**\nBuild a command that splits a non-empty textblock at the top level\nof a list item by also splitting that list item. `itemType` may be\nan array, when there are multiple node types that act as list\nitems. The new item gets the same type as the item that was split.\n*/\nfunction splitListItem(itemType, itemAttrs) {\n    return function (state, dispatch) {\n        let { $from, $to, node } = state.selection;\n        if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to))\n            return false;\n        let grandParent = $from.node(-1);\n        if (!isItem(itemType, grandParent.type))\n            return false;\n        if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {\n            // In an empty block. If this is a nested list, the wrapping\n            // list item should be split. Otherwise, bail out and let next\n            // command handle lifting.\n            if ($from.depth == 3 || !isItem(itemType, $from.node(-3).type) ||\n                $from.index(-2) != $from.node(-2).childCount - 1)\n                return false;\n            if (dispatch) {\n                let wrap = Fragment.empty;\n                let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;\n                // Build a fragment containing empty versions of the structure\n                // from the outer list item to the parent node of the cursor\n                for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d--)\n                    wrap = Fragment.from($from.node(d).copy(wrap));\n                let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1\n                    : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;\n                // Add a second list item with an empty default start node\n                wrap = wrap.append(Fragment.from($from.node(-3).type.createAndFill()));\n                let start = $from.before($from.depth - (depthBefore - 1));\n                let tr = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));\n                let sel = -1;\n                tr.doc.nodesBetween(start, tr.doc.content.size, (node, pos) => {\n                    if (sel > -1)\n                        return false;\n                    if (node.isTextblock && node.content.size == 0)\n                        sel = pos + 1;\n                });\n                if (sel > -1)\n                    tr.setSelection(Selection.near(tr.doc.resolve(sel)));\n                dispatch(tr.scrollIntoView());\n            }\n            return true;\n        }\n        let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;\n        let tr = state.tr.delete($from.pos, $to.pos);\n        let types = nextType ? [itemAttrs ? { type: grandParent.type, attrs: itemAttrs } : null, { type: nextType }] : undefined;\n        if (!canSplit(tr.doc, $from.pos, 2, types))\n            return false;\n        if (dispatch)\n            dispatch(tr.split($from.pos, 2, types).scrollIntoView());\n        return true;\n    };\n}\n/**\nActs like [`splitListItem`](https://prosemirror.net/docs/ref/#schema-list.splitListItem), but\nwithout resetting the set of active marks at the cursor.\n*/\nfunction splitListItemKeepMarks(itemType, itemAttrs) {\n    let split = splitListItem(itemType, itemAttrs);\n    return (state, dispatch) => {\n        return split(state, dispatch && (tr => {\n            let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n            if (marks)\n                tr.ensureMarks(marks);\n            dispatch(tr);\n        }));\n    };\n}\n/**\nCreate a command to lift the list item around the selection up into\na wrapping list. `itemType` may be an array of list item types.\n*/\nfunction liftListItem(itemType) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to, node => node.childCount > 0 && isItem(itemType, node.firstChild.type));\n        if (!range)\n            return false;\n        if (!dispatch)\n            return true;\n        if (isItem(itemType, $from.node(range.depth - 1).type)) // Inside a parent list\n            return liftToOuterList(state, dispatch, range);\n        else // Outer list node\n            return liftOutOfList(state, dispatch, range);\n    };\n}\nfunction liftToOuterList(state, dispatch, range) {\n    let tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth);\n    let itemType = range.parent.child(range.endIndex - 1).type;\n    if (end < endOfList) {\n        // There are siblings after the lifted items, which must become\n        // children of the last item\n        tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));\n        range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);\n    }\n    const target = liftTarget(range);\n    if (target == null)\n        return false;\n    tr.lift(range, target);\n    let $after = tr.doc.resolve(tr.mapping.map(end, -1) - 1);\n    if (canJoin(tr.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type)\n        tr.join($after.pos);\n    dispatch(tr.scrollIntoView());\n    return true;\n}\nfunction liftOutOfList(state, dispatch, range) {\n    let tr = state.tr, list = range.parent;\n    // Merge the list items into a single big item\n    for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {\n        pos -= list.child(i).nodeSize;\n        tr.delete(pos - 1, pos + 1);\n    }\n    let $start = tr.doc.resolve(range.start), item = $start.nodeAfter;\n    if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)\n        return false;\n    let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount;\n    let parent = $start.node(-1), indexBefore = $start.index(-1);\n    if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))\n        return false;\n    let start = $start.pos, end = start + item.nodeSize;\n    // Strip off the surrounding list. At the sides where we're not at\n    // the end of the list, the existing list is closed. At sides where\n    // this is the end, it is overwritten to its end.\n    tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty)))\n        .append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));\n    dispatch(tr.scrollIntoView());\n    return true;\n}\n/**\nCreate a command to sink the list item around the selection down\ninto an inner list. `itemType` may be an array of list item types.\n*/\nfunction sinkListItem(itemType) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to, node => node.childCount > 0 && isItem(itemType, node.firstChild.type));\n        if (!range)\n            return false;\n        let startIndex = range.startIndex;\n        if (startIndex == 0)\n            return false;\n        let parent = range.parent, nodeBefore = parent.child(startIndex - 1);\n        if (!isItem(itemType, nodeBefore.type))\n            return false;\n        if (dispatch) {\n            let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;\n            let inner = Fragment.from(nestedBefore ? nodeBefore.lastChild.lastChild.type.create() : null);\n            let slice = new Slice(Fragment.from(nodeBefore.type.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);\n            let before = range.start, after = range.end;\n            dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true))\n                .scrollIntoView());\n        }\n        return true;\n    };\n}\n\nexport { addListNodes, bulletList, liftListItem, listItem, orderedList, sinkListItem, splitListItem, splitListItemKeepMarks, wrapInList, wrapRangeInList };\n", "import { EditorState, Transaction } from '@tiptap/pm/state'\n\n/**\n * Takes a Transaction & Editor State and turns it into a chainable state object\n * @param config The transaction and state to create the chainable state from\n * @returns A chainable Editor state object\n */\nexport function createChainableState(config: {\n  transaction: Transaction\n  state: EditorState\n}): EditorState {\n  const { state, transaction } = config\n  let { selection } = transaction\n  let { doc } = transaction\n  let { storedMarks } = transaction\n\n  return {\n    ...state,\n    apply: state.apply.bind(state),\n    applyTransaction: state.applyTransaction.bind(state),\n    plugins: state.plugins,\n    schema: state.schema,\n    reconfigure: state.reconfigure.bind(state),\n    toJSON: state.toJSON.bind(state),\n    get storedMarks() {\n      return storedMarks\n    },\n    get selection() {\n      return selection\n    },\n    get doc() {\n      return doc\n    },\n    get tr() {\n      selection = transaction.selection\n      doc = transaction.doc\n      storedMarks = transaction.storedMarks\n\n      return transaction\n    },\n  }\n}\n", "import { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport {\n  AnyCommands, CanCommands, ChainedCommands, CommandProps, SingleCommands,\n} from './types.js'\n\nexport class CommandManager {\n  editor: Editor\n\n  rawCommands: AnyCommands\n\n  customState?: EditorState\n\n  constructor(props: { editor: Editor; state?: EditorState }) {\n    this.editor = props.editor\n    this.rawCommands = this.editor.extensionManager.commands\n    this.customState = props.state\n  }\n\n  get hasCustomState(): boolean {\n    return !!this.customState\n  }\n\n  get state(): EditorState {\n    return this.customState || this.editor.state\n  }\n\n  get commands(): SingleCommands {\n    const { rawCommands, editor, state } = this\n    const { view } = editor\n    const { tr } = state\n    const props = this.buildProps(tr)\n\n    return Object.fromEntries(\n      Object.entries(rawCommands).map(([name, command]) => {\n        const method = (...args: any[]) => {\n          const callback = command(...args)(props)\n\n          if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {\n            view.dispatch(tr)\n          }\n\n          return callback\n        }\n\n        return [name, method]\n      }),\n    ) as unknown as SingleCommands\n  }\n\n  get chain(): () => ChainedCommands {\n    return () => this.createChain()\n  }\n\n  get can(): () => CanCommands {\n    return () => this.createCan()\n  }\n\n  public createChain(startTr?: Transaction, shouldDispatch = true): ChainedCommands {\n    const { rawCommands, editor, state } = this\n    const { view } = editor\n    const callbacks: boolean[] = []\n    const hasStartTransaction = !!startTr\n    const tr = startTr || state.tr\n\n    const run = () => {\n      if (\n        !hasStartTransaction\n        && shouldDispatch\n        && !tr.getMeta('preventDispatch')\n        && !this.hasCustomState\n      ) {\n        view.dispatch(tr)\n      }\n\n      return callbacks.every(callback => callback === true)\n    }\n\n    const chain = {\n      ...Object.fromEntries(\n        Object.entries(rawCommands).map(([name, command]) => {\n          const chainedCommand = (...args: never[]) => {\n            const props = this.buildProps(tr, shouldDispatch)\n            const callback = command(...args)(props)\n\n            callbacks.push(callback)\n\n            return chain\n          }\n\n          return [name, chainedCommand]\n        }),\n      ),\n      run,\n    } as unknown as ChainedCommands\n\n    return chain\n  }\n\n  public createCan(startTr?: Transaction): CanCommands {\n    const { rawCommands, state } = this\n    const dispatch = false\n    const tr = startTr || state.tr\n    const props = this.buildProps(tr, dispatch)\n    const formattedCommands = Object.fromEntries(\n      Object.entries(rawCommands).map(([name, command]) => {\n        return [name, (...args: never[]) => command(...args)({ ...props, dispatch: undefined })]\n      }),\n    ) as unknown as SingleCommands\n\n    return {\n      ...formattedCommands,\n      chain: () => this.createChain(tr, dispatch),\n    } as CanCommands\n  }\n\n  public buildProps(tr: Transaction, shouldDispatch = true): CommandProps {\n    const { rawCommands, editor, state } = this\n    const { view } = editor\n\n    const props: CommandProps = {\n      tr,\n      editor,\n      view,\n      state: createChainableState({\n        state,\n        transaction: tr,\n      }),\n      dispatch: shouldDispatch ? () => undefined : undefined,\n      chain: () => this.createChain(tr, shouldDispatch),\n      can: () => this.createCan(tr),\n      get commands() {\n        return Object.fromEntries(\n          Object.entries(rawCommands).map(([name, command]) => {\n            return [name, (...args: never[]) => command(...args)(props)]\n          }),\n        ) as unknown as SingleCommands\n      },\n    }\n\n    return props\n  }\n}\n", "type StringKeyOf<T> = Extract<keyof T, string>\ntype CallbackType<\n  T extends Record<string, any>,\n  EventName extends StringKeyOf<T>,\n> = T[EventName] extends any[] ? T[EventName] : [T[EventName]]\ntype CallbackFunction<\n  T extends Record<string, any>,\n  EventName extends StringKeyOf<T>,\n> = (...props: CallbackType<T, EventName>) => any\n\nexport class EventEmitter<T extends Record<string, any>> {\n\n  private callbacks: { [key: string]: Array<(...args: any[])=>void> } = {}\n\n  public on<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n    if (!this.callbacks[event]) {\n      this.callbacks[event] = []\n    }\n\n    this.callbacks[event].push(fn)\n\n    return this\n  }\n\n  public emit<EventName extends StringKeyOf<T>>(event: EventName, ...args: CallbackType<T, EventName>): this {\n    const callbacks = this.callbacks[event]\n\n    if (callbacks) {\n      callbacks.forEach(callback => callback.apply(this, args))\n    }\n\n    return this\n  }\n\n  public off<EventName extends StringKeyOf<T>>(event: EventName, fn?: CallbackFunction<T, EventName>): this {\n    const callbacks = this.callbacks[event]\n\n    if (callbacks) {\n      if (fn) {\n        this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n      } else {\n        delete this.callbacks[event]\n      }\n    }\n\n    return this\n  }\n\n  public once<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n    const onceFn = (...args: CallbackType<T, EventName>) => {\n      this.off(event, onceFn)\n      fn.apply(this, args)\n    }\n\n    return this.on(event, onceFn)\n  }\n\n  public removeAllListeners(): void {\n    this.callbacks = {}\n  }\n}\n", "import { AnyExtension, MaybeThisParameterType, RemoveThis } from '../types.js'\n\n/**\n * Returns a field from an extension\n * @param extension The Tiptap extension\n * @param field The field, for example `renderHTML` or `priority`\n * @param context The context object that should be passed as `this` into the function\n * @returns The field value\n */\nexport function getExtensionField<T = any>(\n  extension: AnyExtension,\n  field: string,\n  context?: Omit<MaybeThisParameterType<T>, 'parent'>,\n): RemoveThis<T> {\n\n  if (extension.config[field] === undefined && extension.parent) {\n    return getExtensionField(extension.parent, field, context)\n  }\n\n  if (typeof extension.config[field] === 'function') {\n    const value = extension.config[field].bind({\n      ...context,\n      parent: extension.parent\n        ? getExtensionField(extension.parent, field, context)\n        : null,\n    })\n\n    return value\n  }\n\n  return extension.config[field]\n}\n", "import { Extension } from '../Extension.js'\nimport { Mark } from '../Mark.js'\nimport { Node } from '../Node.js'\nimport { Extensions } from '../types.js'\n\nexport function splitExtensions(extensions: Extensions) {\n  const baseExtensions = extensions.filter(extension => extension.type === 'extension') as Extension[]\n  const nodeExtensions = extensions.filter(extension => extension.type === 'node') as Node[]\n  const markExtensions = extensions.filter(extension => extension.type === 'mark') as Mark[]\n\n  return {\n    baseExtensions,\n    nodeExtensions,\n    markExtensions,\n  }\n}\n", "import { MarkConfig, NodeConfig } from '../index.js'\nimport {\n  AnyConfig,\n  Attribute,\n  Attributes,\n  ExtensionAttribute,\n  Extensions,\n} from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { splitExtensions } from './splitExtensions.js'\n\n/**\n * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.\n * @param extensions List of extensions\n */\nexport function getAttributesFromExtensions(extensions: Extensions): ExtensionAttribute[] {\n  const extensionAttributes: ExtensionAttribute[] = []\n  const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n  const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]\n  const defaultAttribute: Required<Attribute> = {\n    default: null,\n    rendered: true,\n    renderHTML: null,\n    parseHTML: null,\n    keepOnSplit: true,\n    isRequired: false,\n  }\n\n  extensions.forEach(extension => {\n    const context = {\n      name: extension.name,\n      options: extension.options,\n      storage: extension.storage,\n      extensions: nodeAndMarkExtensions,\n    }\n\n    const addGlobalAttributes = getExtensionField<AnyConfig['addGlobalAttributes']>(\n      extension,\n      'addGlobalAttributes',\n      context,\n    )\n\n    if (!addGlobalAttributes) {\n      return\n    }\n\n    const globalAttributes = addGlobalAttributes()\n\n    globalAttributes.forEach(globalAttribute => {\n      globalAttribute.types.forEach(type => {\n        Object\n          .entries(globalAttribute.attributes)\n          .forEach(([name, attribute]) => {\n            extensionAttributes.push({\n              type,\n              name,\n              attribute: {\n                ...defaultAttribute,\n                ...attribute,\n              },\n            })\n          })\n      })\n    })\n  })\n\n  nodeAndMarkExtensions.forEach(extension => {\n    const context = {\n      name: extension.name,\n      options: extension.options,\n      storage: extension.storage,\n    }\n\n    const addAttributes = getExtensionField<NodeConfig['addAttributes'] | MarkConfig['addAttributes']>(\n      extension,\n      'addAttributes',\n      context,\n    )\n\n    if (!addAttributes) {\n      return\n    }\n\n    // TODO: remove `as Attributes`\n    const attributes = addAttributes() as Attributes\n\n    Object\n      .entries(attributes)\n      .forEach(([name, attribute]) => {\n        const mergedAttr = {\n          ...defaultAttribute,\n          ...attribute,\n        }\n\n        if (typeof mergedAttr?.default === 'function') {\n          mergedAttr.default = mergedAttr.default()\n        }\n\n        if (mergedAttr?.isRequired && mergedAttr?.default === undefined) {\n          delete mergedAttr.default\n        }\n\n        extensionAttributes.push({\n          type: extension.name,\n          name,\n          attribute: mergedAttr,\n        })\n      })\n  })\n\n  return extensionAttributes\n}\n", "import { NodeType, Schema } from '@tiptap/pm/model'\n\nexport function getNodeType(nameOrType: string | NodeType, schema: Schema): NodeType {\n  if (typeof nameOrType === 'string') {\n    if (!schema.nodes[nameOrType]) {\n      throw Error(\n        `There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`,\n      )\n    }\n\n    return schema.nodes[nameOrType]\n  }\n\n  return nameOrType\n}\n", "export function mergeAttributes(...objects: Record<string, any>[]): Record<string, any> {\n  return objects\n    .filter(item => !!item)\n    .reduce((items, item) => {\n      const mergedAttributes = { ...items }\n\n      Object.entries(item).forEach(([key, value]) => {\n        // Define a data property so untrusted input cannot change the merged object's prototype.\n        if (key === '__proto__') {\n          Object.defineProperty(mergedAttributes, key, {\n            configurable: true,\n            enumerable: true,\n            value,\n            writable: true,\n          })\n\n          return\n        }\n\n        const exists = mergedAttributes[key]\n\n        if (!exists) {\n          mergedAttributes[key] = value\n\n          return\n        }\n\n        if (key === 'class') {\n          const valueClasses: string[] = value ? String(value).split(' ') : []\n          const existingClasses: string[] = mergedAttributes[key] ? mergedAttributes[key].split(' ') : []\n\n          const insertClasses = valueClasses.filter(\n            valueClass => !existingClasses.includes(valueClass),\n          )\n\n          mergedAttributes[key] = [...existingClasses, ...insertClasses].join(' ')\n        } else if (key === 'style') {\n          const newStyles: string[] = value ? value.split(';').map((style: string) => style.trim()).filter(Boolean) : []\n          const existingStyles: string[] = mergedAttributes[key] ? mergedAttributes[key].split(';').map((style: string) => style.trim()).filter(Boolean) : []\n\n          const styleMap = new Map<string, string>()\n\n          existingStyles.forEach(style => {\n            const [property, val] = style.split(':').map(part => part.trim())\n\n            styleMap.set(property, val)\n          })\n\n          newStyles.forEach(style => {\n            const [property, val] = style.split(':').map(part => part.trim())\n\n            styleMap.set(property, val)\n          })\n\n          mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join('; ')\n        } else {\n          mergedAttributes[key] = value\n        }\n      })\n\n      return mergedAttributes\n    }, {})\n}\n", "import { Mark, Node } from '@tiptap/pm/model'\n\nimport { ExtensionAttribute } from '../types.js'\nimport { mergeAttributes } from '../utilities/mergeAttributes.js'\n\nexport function getRenderedAttributes(\n  nodeOrMark: Node | Mark,\n  extensionAttributes: ExtensionAttribute[],\n): Record<string, any> {\n  return extensionAttributes\n    .filter(\n      attribute => attribute.type === nodeOrMark.type.name,\n    )\n    .filter(item => item.attribute.rendered)\n    .map(item => {\n      if (!item.attribute.renderHTML) {\n        return {\n          [item.name]: nodeOrMark.attrs[item.name],\n        }\n      }\n\n      return item.attribute.renderHTML(nodeOrMark.attrs) || {}\n    })\n    .reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {})\n}\n", "// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport function isFunction(value: any): value is Function {\n  return typeof value === 'function'\n}\n", "import { MaybeReturnType } from '../types.js'\nimport { isFunction } from './isFunction.js'\n\n/**\n * Optionally calls `value` as a function.\n * Otherwise it is returned directly.\n * @param value Function or any value.\n * @param context Optional context to bind to function.\n * @param props Optional props to pass to function.\n */\nexport function callOrReturn<T>(value: T, context: any = undefined, ...props: any[]): MaybeReturnType<T> {\n  if (isFunction(value)) {\n    if (context) {\n      return value.bind(context)(...props)\n    }\n\n    return value(...props)\n  }\n\n  return value as MaybeReturnType<T>\n}\n", "export function isEmptyObject(value = {}): boolean {\n  return Object.keys(value).length === 0 && value.constructor === Object\n}\n", "export function fromString(value: any): any {\n  if (typeof value !== 'string') {\n    return value\n  }\n\n  if (value.match(/^[+-]?(?:\\d*\\.)?\\d+$/)) {\n    return Number(value)\n  }\n\n  if (value === 'true') {\n    return true\n  }\n\n  if (value === 'false') {\n    return false\n  }\n\n  return value\n}\n", "import { ParseRule } from '@tiptap/pm/model'\n\nimport { ExtensionAttribute } from '../types.js'\nimport { fromString } from '../utilities/fromString.js'\n\n/**\n * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).\n * Cancels when `getAttrs` returned `false`.\n * @param parseRule ProseMirror ParseRule\n * @param extensionAttributes List of attributes to inject\n */\nexport function injectExtensionAttributesToParseRule(\n  parseRule: ParseRule,\n  extensionAttributes: ExtensionAttribute[],\n): ParseRule {\n  if ('style' in parseRule) {\n    return parseRule\n  }\n\n  return {\n    ...parseRule,\n    getAttrs: (node: HTMLElement) => {\n      const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs\n\n      if (oldAttributes === false) {\n        return false\n      }\n\n      const newAttributes = extensionAttributes.reduce((items, item) => {\n        const value = item.attribute.parseHTML\n          ? item.attribute.parseHTML(node)\n          : fromString((node).getAttribute(item.name))\n\n        if (value === null || value === undefined) {\n          return items\n        }\n\n        return {\n          ...items,\n          [item.name]: value,\n        }\n      }, {})\n\n      return { ...oldAttributes, ...newAttributes }\n    },\n  }\n}\n", "import {\n  MarkSpec, NodeSpec, Schema, TagParseRule,\n} from '@tiptap/pm/model'\n\nimport { Editor, MarkConfig, NodeConfig } from '../index.js'\nimport { AnyConfig, Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { isEmptyObject } from '../utilities/isEmptyObject.js'\nimport { getAttributesFromExtensions } from './getAttributesFromExtensions.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { getRenderedAttributes } from './getRenderedAttributes.js'\nimport { injectExtensionAttributesToParseRule } from './injectExtensionAttributesToParseRule.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nfunction cleanUpSchemaItem<T>(data: T) {\n  return Object.fromEntries(\n    // @ts-ignore\n    Object.entries(data).filter(([key, value]) => {\n      if (key === 'attrs' && isEmptyObject(value as object | undefined)) {\n        return false\n      }\n\n      return value !== null && value !== undefined\n    }),\n  ) as T\n}\n\n/**\n * Creates a new Prosemirror schema based on the given extensions.\n * @param extensions An array of Tiptap extensions\n * @param editor The editor instance\n * @returns A Prosemirror schema\n */\nexport function getSchemaByResolvedExtensions(extensions: Extensions, editor?: Editor): Schema {\n  const allAttributes = getAttributesFromExtensions(extensions)\n  const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n  const topNode = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))?.name\n\n  const nodes = Object.fromEntries(\n    nodeExtensions.map(extension => {\n      const extensionAttributes = allAttributes.filter(\n        attribute => attribute.type === extension.name,\n      )\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: extension.storage,\n        editor,\n      }\n\n      const extraNodeFields = extensions.reduce((fields, e) => {\n        const extendNodeSchema = getExtensionField<AnyConfig['extendNodeSchema']>(\n          e,\n          'extendNodeSchema',\n          context,\n        )\n\n        return {\n          ...fields,\n          ...(extendNodeSchema ? extendNodeSchema(extension) : {}),\n        }\n      }, {})\n\n      const schema: NodeSpec = cleanUpSchemaItem({\n        ...extraNodeFields,\n        content: callOrReturn(\n          getExtensionField<NodeConfig['content']>(extension, 'content', context),\n        ),\n        marks: callOrReturn(getExtensionField<NodeConfig['marks']>(extension, 'marks', context)),\n        group: callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context)),\n        inline: callOrReturn(getExtensionField<NodeConfig['inline']>(extension, 'inline', context)),\n        atom: callOrReturn(getExtensionField<NodeConfig['atom']>(extension, 'atom', context)),\n        selectable: callOrReturn(\n          getExtensionField<NodeConfig['selectable']>(extension, 'selectable', context),\n        ),\n        draggable: callOrReturn(\n          getExtensionField<NodeConfig['draggable']>(extension, 'draggable', context),\n        ),\n        code: callOrReturn(getExtensionField<NodeConfig['code']>(extension, 'code', context)),\n        whitespace: callOrReturn(getExtensionField<NodeConfig['whitespace']>(extension, 'whitespace', context)),\n        linebreakReplacement: callOrReturn(getExtensionField<NodeConfig['linebreakReplacement']>(extension, 'linebreakReplacement', context)),\n        defining: callOrReturn(\n          getExtensionField<NodeConfig['defining']>(extension, 'defining', context),\n        ),\n        isolating: callOrReturn(\n          getExtensionField<NodeConfig['isolating']>(extension, 'isolating', context),\n        ),\n        attrs: Object.fromEntries(\n          extensionAttributes.map(extensionAttribute => {\n            return [extensionAttribute.name, { default: extensionAttribute?.attribute?.default }]\n          }),\n        ),\n      })\n\n      const parseHTML = callOrReturn(\n        getExtensionField<NodeConfig['parseHTML']>(extension, 'parseHTML', context),\n      )\n\n      if (parseHTML) {\n        schema.parseDOM = parseHTML.map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)) as TagParseRule[]\n      }\n\n      const renderHTML = getExtensionField<NodeConfig['renderHTML']>(\n        extension,\n        'renderHTML',\n        context,\n      )\n\n      if (renderHTML) {\n        schema.toDOM = node => renderHTML({\n          node,\n          HTMLAttributes: getRenderedAttributes(node, extensionAttributes),\n        })\n      }\n\n      const renderText = getExtensionField<NodeConfig['renderText']>(\n        extension,\n        'renderText',\n        context,\n      )\n\n      if (renderText) {\n        schema.toText = renderText\n      }\n\n      return [extension.name, schema]\n    }),\n  )\n\n  const marks = Object.fromEntries(\n    markExtensions.map(extension => {\n      const extensionAttributes = allAttributes.filter(\n        attribute => attribute.type === extension.name,\n      )\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: extension.storage,\n        editor,\n      }\n\n      const extraMarkFields = extensions.reduce((fields, e) => {\n        const extendMarkSchema = getExtensionField<AnyConfig['extendMarkSchema']>(\n          e,\n          'extendMarkSchema',\n          context,\n        )\n\n        return {\n          ...fields,\n          ...(extendMarkSchema ? extendMarkSchema(extension as any) : {}),\n        }\n      }, {})\n\n      const schema: MarkSpec = cleanUpSchemaItem({\n        ...extraMarkFields,\n        inclusive: callOrReturn(\n          getExtensionField<MarkConfig['inclusive']>(extension, 'inclusive', context),\n        ),\n        excludes: callOrReturn(\n          getExtensionField<MarkConfig['excludes']>(extension, 'excludes', context),\n        ),\n        group: callOrReturn(getExtensionField<MarkConfig['group']>(extension, 'group', context)),\n        spanning: callOrReturn(\n          getExtensionField<MarkConfig['spanning']>(extension, 'spanning', context),\n        ),\n        code: callOrReturn(getExtensionField<MarkConfig['code']>(extension, 'code', context)),\n        attrs: Object.fromEntries(\n          extensionAttributes.map(extensionAttribute => {\n            return [extensionAttribute.name, { default: extensionAttribute?.attribute?.default }]\n          }),\n        ),\n      })\n\n      const parseHTML = callOrReturn(\n        getExtensionField<MarkConfig['parseHTML']>(extension, 'parseHTML', context),\n      )\n\n      if (parseHTML) {\n        schema.parseDOM = parseHTML.map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes))\n      }\n\n      const renderHTML = getExtensionField<MarkConfig['renderHTML']>(\n        extension,\n        'renderHTML',\n        context,\n      )\n\n      if (renderHTML) {\n        schema.toDOM = mark => renderHTML({\n          mark,\n          HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),\n        })\n      }\n\n      return [extension.name, schema]\n    }),\n  )\n\n  return new Schema({\n    topNode,\n    nodes,\n    marks,\n  })\n}\n", "import { MarkType, NodeType, Schema } from '@tiptap/pm/model'\n\n/**\n * Tries to get a node or mark type by its name.\n * @param name The name of the node or mark type\n * @param schema The Prosemiror schema to search in\n * @returns The node or mark type, or null if it doesn't exist\n */\nexport function getSchemaTypeByName(name: string, schema: Schema): NodeType | MarkType | null {\n  return schema.nodes[name] || schema.marks[name] || null\n}\n", "import { AnyExtension, EnableRules } from '../types.js'\n\nexport function isExtensionRulesEnabled(extension: AnyExtension, enabled: EnableRules): boolean {\n  if (Array.isArray(enabled)) {\n    return enabled.some(enabledExtension => {\n      const name = typeof enabledExtension === 'string'\n        ? enabledExtension\n        : enabledExtension.name\n\n      return name === extension.name\n    })\n  }\n\n  return enabled\n}\n", "import { DOMSerializer, Fragment, Schema } from '@tiptap/pm/model'\n\nexport function getHTMLFromFragment(fragment: Fragment, schema: Schema): string {\n  const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment)\n\n  const temporaryDocument = document.implementation.createHTMLDocument()\n  const container = temporaryDocument.createElement('div')\n\n  container.appendChild(documentFragment)\n\n  return container.innerHTML\n}\n", "import { ResolvedPos } from '@tiptap/pm/model'\n\n/**\n * Returns the text content of a resolved prosemirror position\n * @param $from The resolved position to get the text content from\n * @param maxMatch The maximum number of characters to match\n * @returns The text content\n */\nexport const getTextContentFromNodes = ($from: ResolvedPos, maxMatch = 500) => {\n  let textBefore = ''\n\n  const sliceEndPos = $from.parentOffset\n\n  $from.parent.nodesBetween(\n    Math.max(0, sliceEndPos - maxMatch),\n    sliceEndPos,\n    (node, pos, parent, index) => {\n      const chunk = node.type.spec.toText?.({\n        node,\n        pos,\n        parent,\n        index,\n      })\n        || node.textContent\n        || '%leaf%'\n\n      textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos))\n    },\n  )\n\n  return textBefore\n}\n", "export function isRegExp(value: any): value is RegExp {\n  return Object.prototype.toString.call(value) === '[object RegExp]'\n}\n", "import { Fragment, Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { EditorState, Plugin, TextSelection } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getTextContentFromNodes } from './helpers/getTextContentFromNodes.js'\nimport {\n  CanCommands,\n  ChainedCommands,\n  ExtendedRegExpMatchArray,\n  Range,\n  SingleCommands,\n} from './types.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type InputRuleMatch = {\n  index: number;\n  text: string;\n  replaceWith?: string;\n  match?: RegExpMatchArray;\n  data?: Record<string, any>;\n};\n\nexport type InputRuleFinder = RegExp | ((text: string) => InputRuleMatch | null);\n\nexport class InputRule {\n  find: InputRuleFinder\n\n  handler: (props: {\n    state: EditorState;\n    range: Range;\n    match: ExtendedRegExpMatchArray;\n    commands: SingleCommands;\n    chain: () => ChainedCommands;\n    can: () => CanCommands;\n  }) => void | null\n\n  constructor(config: {\n    find: InputRuleFinder;\n    handler: (props: {\n      state: EditorState;\n      range: Range;\n      match: ExtendedRegExpMatchArray;\n      commands: SingleCommands;\n      chain: () => ChainedCommands;\n      can: () => CanCommands;\n    }) => void | null;\n  }) {\n    this.find = config.find\n    this.handler = config.handler\n  }\n}\n\nconst inputRuleMatcherHandler = (\n  text: string,\n  find: InputRuleFinder,\n): ExtendedRegExpMatchArray | null => {\n  if (isRegExp(find)) {\n    return find.exec(text)\n  }\n\n  const inputRuleMatch = find(text)\n\n  if (!inputRuleMatch) {\n    return null\n  }\n\n  const result: ExtendedRegExpMatchArray = [inputRuleMatch.text]\n\n  result.index = inputRuleMatch.index\n  result.input = text\n  result.data = inputRuleMatch.data\n\n  if (inputRuleMatch.replaceWith) {\n    if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {\n      console.warn(\n        '[tiptap warn]: \"inputRuleMatch.replaceWith\" must be part of \"inputRuleMatch.text\".',\n      )\n    }\n\n    result.push(inputRuleMatch.replaceWith)\n  }\n\n  return result\n}\n\nfunction run(config: {\n  editor: Editor;\n  from: number;\n  to: number;\n  text: string;\n  rules: InputRule[];\n  plugin: Plugin;\n}): boolean {\n  const {\n    editor, from, to, text, rules, plugin,\n  } = config\n  const { view } = editor\n\n  if (view.composing) {\n    return false\n  }\n\n  const $from = view.state.doc.resolve(from)\n\n  if (\n    // check for code node\n    $from.parent.type.spec.code\n    // check for code mark\n    || !!($from.nodeBefore || $from.nodeAfter)?.marks.find(mark => mark.type.spec.code)\n  ) {\n    return false\n  }\n\n  let matched = false\n\n  const textBefore = getTextContentFromNodes($from) + text\n\n  rules.forEach(rule => {\n    if (matched) {\n      return\n    }\n\n    const match = inputRuleMatcherHandler(textBefore, rule.find)\n\n    if (!match) {\n      return\n    }\n\n    const tr = view.state.tr\n    const state = createChainableState({\n      state: view.state,\n      transaction: tr,\n    })\n    const range = {\n      from: from - (match[0].length - text.length),\n      to,\n    }\n\n    const { commands, chain, can } = new CommandManager({\n      editor,\n      state,\n    })\n\n    const handler = rule.handler({\n      state,\n      range,\n      match,\n      commands,\n      chain,\n      can,\n    })\n\n    // stop if there are no changes\n    if (handler === null || !tr.steps.length) {\n      return\n    }\n\n    // store transform as meta data\n    // so we can undo input rules within the `undoInputRules` command\n    tr.setMeta(plugin, {\n      transform: tr,\n      from,\n      to,\n      text,\n    })\n\n    view.dispatch(tr)\n    matched = true\n  })\n\n  return matched\n}\n\n/**\n * Create an input rules plugin. When enabled, it will cause text\n * input that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function inputRulesPlugin(props: { editor: Editor; rules: InputRule[] }): Plugin {\n  const { editor, rules } = props\n  const plugin = new Plugin({\n    state: {\n      init() {\n        return null\n      },\n      apply(tr, prev, state) {\n        const stored = tr.getMeta(plugin)\n\n        if (stored) {\n          return stored\n        }\n\n        // if InputRule is triggered by insertContent()\n        const simulatedInputMeta = tr.getMeta('applyInputRules') as\n          | undefined\n          | {\n              from: number;\n              text: string | ProseMirrorNode | Fragment;\n            }\n        const isSimulatedInput = !!simulatedInputMeta\n\n        if (isSimulatedInput) {\n          setTimeout(() => {\n            let { text } = simulatedInputMeta\n\n            if (typeof text === 'string') {\n              text = text as string\n            } else {\n              text = getHTMLFromFragment(Fragment.from(text), state.schema)\n            }\n\n            const { from } = simulatedInputMeta\n            const to = from + text.length\n\n            run({\n              editor,\n              from,\n              to,\n              text,\n              rules,\n              plugin,\n            })\n          })\n        }\n\n        return tr.selectionSet || tr.docChanged ? null : prev\n      },\n    },\n\n    props: {\n      handleTextInput(view, from, to, text) {\n        return run({\n          editor,\n          from,\n          to,\n          text,\n          rules,\n          plugin,\n        })\n      },\n\n      handleDOMEvents: {\n        compositionend: view => {\n          setTimeout(() => {\n            const { $cursor } = view.state.selection as TextSelection\n\n            if ($cursor) {\n              run({\n                editor,\n                from: $cursor.pos,\n                to: $cursor.pos,\n                text: '',\n                rules,\n                plugin,\n              })\n            }\n          })\n\n          return false\n        },\n      },\n\n      // add support for input rules to trigger on enter\n      // this is useful for example for code blocks\n      handleKeyDown(view, event) {\n        if (event.key !== 'Enter') {\n          return false\n        }\n\n        const { $cursor } = view.state.selection as TextSelection\n\n        if ($cursor) {\n          return run({\n            editor,\n            from: $cursor.pos,\n            to: $cursor.pos,\n            text: '\\n',\n            rules,\n            plugin,\n          })\n        }\n\n        return false\n      },\n    },\n\n    // @ts-ignore\n    isInputRules: true,\n  }) as Plugin\n\n  return plugin\n}\n", "// see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts\n\nfunction getType(value: any): string {\n  return Object.prototype.toString.call(value).slice(8, -1)\n}\n\nexport function isPlainObject(value: any): value is Record<string, any> {\n  if (getType(value) !== 'Object') {\n    return false\n  }\n\n  return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype\n}\n", "import { isPlainObject } from './isPlainObject.js'\n\nexport function mergeDeep(target: Record<string, any>, source: Record<string, any>): Record<string, any> {\n  const output = { ...target }\n\n  if (isPlainObject(target) && isPlainObject(source)) {\n    Object.keys(source).forEach(key => {\n      if (isPlainObject(source[key]) && isPlainObject(target[key])) {\n        output[key] = mergeDeep(target[key], source[key])\n      } else {\n        output[key] = source[key]\n      }\n    })\n  }\n\n  return output\n}\n", "import {\n  DOMOutputSpec, Mark as ProseMirrorMark, MarkSpec, MarkType,\n} from '@tiptap/pm/model'\nimport { Plugin, Transaction } from '@tiptap/pm/state'\n\nimport { Editor } from './Editor.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport { MarkConfig } from './index.js'\nimport { InputRule } from './InputRule.js'\nimport { Node } from './Node.js'\nimport { PasteRule } from './PasteRule.js'\nimport {\n  AnyConfig,\n  Attributes,\n  Extensions,\n  GlobalAttributes,\n  KeyboardShortcutCommand,\n  ParentConfig,\n  RawCommands,\n} from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { mergeDeep } from './utilities/mergeDeep.js'\n\ndeclare module '@tiptap/core' {\n  export interface MarkConfig<Options = any, Storage = any> {\n    // @ts-ignore - this is a dynamic key\n    [key: string]: any\n\n    /**\n     * The extension name - this must be unique.\n     * It will be used to identify the extension.\n     *\n     * @example 'myExtension'\n     */\n    name: string\n\n    /**\n     * The priority of your extension. The higher, the earlier it will be called\n     * and will take precedence over other extensions with a lower priority.\n     * @default 100\n     * @example 101\n     */\n    priority?: number\n\n    /**\n     * The default options for this extension.\n     * @example\n     * defaultOptions: {\n     *   myOption: 'foo',\n     *   myOtherOption: 10,\n     * }\n     */\n    defaultOptions?: Options\n\n    /**\n     * This method will add options to this extension\n     * @see https://tiptap.dev/guide/custom-extensions#settings\n     * @example\n     * addOptions() {\n     *  return {\n     *    myOption: 'foo',\n     *    myOtherOption: 10,\n     * }\n     */\n    addOptions?: (this: {\n      name: string\n      parent: Exclude<ParentConfig<MarkConfig<Options, Storage>>['addOptions'], undefined>\n    }) => Options\n\n    /**\n     * The default storage this extension can save data to.\n     * @see https://tiptap.dev/guide/custom-extensions#storage\n     * @example\n     * defaultStorage: {\n     *   prefetchedUsers: [],\n     *   loading: false,\n     * }\n     */\n    addStorage?: (this: {\n      name: string\n      options: Options\n      parent: Exclude<ParentConfig<MarkConfig<Options, Storage>>['addStorage'], undefined>\n    }) => Storage\n\n    /**\n     * This function adds globalAttributes to specific nodes.\n     * @see https://tiptap.dev/guide/custom-extensions#global-attributes\n     * @example\n     * addGlobalAttributes() {\n     *   return [\n     *     {\n             // Extend the following extensions\n     *       types: [\n     *         'heading',\n     *         'paragraph',\n     *       ],\n     *       // … with those attributes\n     *       attributes: {\n     *         textAlign: {\n     *           default: 'left',\n     *           renderHTML: attributes => ({\n     *             style: `text-align: ${attributes.textAlign}`,\n     *           }),\n     *           parseHTML: element => element.style.textAlign || 'left',\n     *         },\n     *       },\n     *     },\n     *   ]\n     * }\n     */\n    addGlobalAttributes?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      extensions: (Node | Mark)[]\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addGlobalAttributes']\n    }) => GlobalAttributes\n\n    /**\n     * This function adds commands to the editor\n     * @see https://tiptap.dev/guide/custom-extensions#keyboard-shortcuts\n     * @example\n     * addCommands() {\n     *   return {\n     *     myCommand: () => ({ chain }) => chain().setMark('type', 'foo').run(),\n     *   }\n     * }\n     */\n    addCommands?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: MarkType\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addCommands']\n    }) => Partial<RawCommands>\n\n    /**\n     * This function registers keyboard shortcuts.\n     * @see https://tiptap.dev/guide/custom-extensions#keyboard-shortcuts\n     * @example\n     * addKeyboardShortcuts() {\n     *   return {\n     *     'Mod-l': () => this.editor.commands.toggleBulletList(),\n     *   }\n     * },\n     */\n    addKeyboardShortcuts?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: MarkType\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addKeyboardShortcuts']\n    }) => {\n      [key: string]: KeyboardShortcutCommand\n    }\n\n    /**\n     * This function adds input rules to the editor.\n     * @see https://tiptap.dev/guide/custom-extensions#input-rules\n     * @example\n     * addInputRules() {\n     *   return [\n     *     markInputRule({\n     *       find: inputRegex,\n     *       type: this.type,\n     *     }),\n     *   ]\n     * },\n     */\n    addInputRules?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: MarkType\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addInputRules']\n    }) => InputRule[]\n\n    /**\n     * This function adds paste rules to the editor.\n     * @see https://tiptap.dev/guide/custom-extensions#paste-rules\n     * @example\n     * addPasteRules() {\n     *   return [\n     *     markPasteRule({\n     *       find: pasteRegex,\n     *       type: this.type,\n     *     }),\n     *   ]\n     * },\n     */\n    addPasteRules?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: MarkType\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addPasteRules']\n    }) => PasteRule[]\n\n    /**\n     * This function adds Prosemirror plugins to the editor\n     * @see https://tiptap.dev/guide/custom-extensions#prosemirror-plugins\n     * @example\n     * addProseMirrorPlugins() {\n     *   return [\n     *     customPlugin(),\n     *   ]\n     * }\n     */\n    addProseMirrorPlugins?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: MarkType\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addProseMirrorPlugins']\n    }) => Plugin[]\n\n    /**\n     * This function adds additional extensions to the editor. This is useful for\n     * building extension kits.\n     * @example\n     * addExtensions() {\n     *   return [\n     *     BulletList,\n     *     OrderedList,\n     *     ListItem\n     *   ]\n     * }\n     */\n    addExtensions?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addExtensions']\n    }) => Extensions\n\n    /**\n     * This function extends the schema of the node.\n     * @example\n     * extendNodeSchema() {\n     *   return {\n     *     group: 'inline',\n     *     selectable: false,\n     *   }\n     * }\n     */\n    extendNodeSchema?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<MarkConfig<Options, Storage>>['extendNodeSchema']\n          },\n          extension: Node,\n        ) => Record<string, any>)\n      | null\n\n    /**\n     * This function extends the schema of the mark.\n     * @example\n     * extendMarkSchema() {\n     *   return {\n     *     group: 'inline',\n     *     selectable: false,\n     *   }\n     * }\n     */\n    extendMarkSchema?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<MarkConfig<Options, Storage>>['extendMarkSchema']\n          },\n          extension: Mark,\n        ) => Record<string, any>)\n      | null\n\n    /**\n     * The editor is not ready yet.\n     */\n    onBeforeCreate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: MarkType\n          parent: ParentConfig<MarkConfig<Options, Storage>>['onBeforeCreate']\n        }) => void)\n      | null\n\n    /**\n     * The editor is ready.\n     */\n    onCreate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: MarkType\n          parent: ParentConfig<MarkConfig<Options, Storage>>['onCreate']\n        }) => void)\n      | null\n\n    /**\n     * The content has changed.\n     */\n    onUpdate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: MarkType\n          parent: ParentConfig<MarkConfig<Options, Storage>>['onUpdate']\n        }) => void)\n      | null\n\n    /**\n     * The selection has changed.\n     */\n    onSelectionUpdate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: MarkType\n          parent: ParentConfig<MarkConfig<Options, Storage>>['onSelectionUpdate']\n        }) => void)\n      | null\n\n    /**\n     * The editor state has changed.\n     */\n    onTransaction?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            type: MarkType\n            parent: ParentConfig<MarkConfig<Options, Storage>>['onTransaction']\n          },\n          props: {\n            editor: Editor\n            transaction: Transaction\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor is focused.\n     */\n    onFocus?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            type: MarkType\n            parent: ParentConfig<MarkConfig<Options, Storage>>['onFocus']\n          },\n          props: {\n            event: FocusEvent\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor isn’t focused anymore.\n     */\n    onBlur?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            type: MarkType\n            parent: ParentConfig<MarkConfig<Options, Storage>>['onBlur']\n          },\n          props: {\n            event: FocusEvent\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor is destroyed.\n     */\n    onDestroy?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: MarkType\n          parent: ParentConfig<MarkConfig<Options, Storage>>['onDestroy']\n        }) => void)\n      | null\n\n    /**\n     * Keep mark after split node\n     */\n    keepOnSplit?: boolean | (() => boolean)\n\n    /**\n     * Inclusive\n     */\n    inclusive?:\n      | MarkSpec['inclusive']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<MarkConfig<Options, Storage>>['inclusive']\n          editor?: Editor\n        }) => MarkSpec['inclusive'])\n\n    /**\n     * Excludes\n     */\n    excludes?:\n      | MarkSpec['excludes']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<MarkConfig<Options, Storage>>['excludes']\n          editor?: Editor\n        }) => MarkSpec['excludes'])\n\n    /**\n     * Marks this Mark as exitable\n     */\n    exitable?: boolean | (() => boolean)\n\n    /**\n     * Group\n     */\n    group?:\n      | MarkSpec['group']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<MarkConfig<Options, Storage>>['group']\n          editor?: Editor\n        }) => MarkSpec['group'])\n\n    /**\n     * Spanning\n     */\n    spanning?:\n      | MarkSpec['spanning']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<MarkConfig<Options, Storage>>['spanning']\n          editor?: Editor\n        }) => MarkSpec['spanning'])\n\n    /**\n     * Code\n     */\n    code?:\n      | boolean\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<MarkConfig<Options, Storage>>['code']\n          editor?: Editor\n        }) => boolean)\n\n    /**\n     * Parse HTML\n     */\n    parseHTML?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<MarkConfig<Options, Storage>>['parseHTML']\n      editor?: Editor\n    }) => MarkSpec['parseDOM']\n\n    /**\n     * Render HTML\n     */\n    renderHTML?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<MarkConfig<Options, Storage>>['renderHTML']\n            editor?: Editor\n          },\n          props: {\n            mark: ProseMirrorMark\n            HTMLAttributes: Record<string, any>\n          },\n        ) => DOMOutputSpec)\n      | null\n\n    /**\n     * Attributes\n     */\n    addAttributes?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<MarkConfig<Options, Storage>>['addAttributes']\n      editor?: Editor\n    // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n    }) => Attributes | {}\n  }\n}\n\n/**\n * The Mark class is used to create custom mark extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Mark<Options = any, Storage = any> {\n  type = 'mark'\n\n  name = 'mark'\n\n  parent: Mark | null = null\n\n  child: Mark | null = null\n\n  options: Options\n\n  storage: Storage\n\n  config: MarkConfig = {\n    name: this.name,\n    defaultOptions: {},\n  }\n\n  constructor(config: Partial<MarkConfig<Options, Storage>> = {}) {\n    this.config = {\n      ...this.config,\n      ...config,\n    }\n\n    this.name = this.config.name\n\n    if (config.defaultOptions && Object.keys(config.defaultOptions).length > 0) {\n      console.warn(\n        `[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${this.name}\".`,\n      )\n    }\n\n    // TODO: remove `addOptions` fallback\n    this.options = this.config.defaultOptions\n\n    if (this.config.addOptions) {\n      this.options = callOrReturn(\n        getExtensionField<AnyConfig['addOptions']>(this, 'addOptions', {\n          name: this.name,\n        }),\n      )\n    }\n\n    this.storage = callOrReturn(\n      getExtensionField<AnyConfig['addStorage']>(this, 'addStorage', {\n        name: this.name,\n        options: this.options,\n      }),\n    ) || {}\n  }\n\n  static create<O = any, S = any>(config: Partial<MarkConfig<O, S>> = {}) {\n    return new Mark<O, S>(config)\n  }\n\n  configure(options: Partial<Options> = {}) {\n    // return a new instance so we can use the same extension\n    // with different calls of `configure`\n    const extension = this.extend<Options, Storage>({\n      ...this.config,\n      addOptions: () => {\n        return mergeDeep(this.options as Record<string, any>, options) as Options\n      },\n    })\n\n    // Always preserve the current name\n    extension.name = this.name\n    // Set the parent to be our parent\n    extension.parent = this.parent\n\n    return extension\n  }\n\n  extend<ExtendedOptions = Options, ExtendedStorage = Storage>(\n    extendedConfig: Partial<MarkConfig<ExtendedOptions, ExtendedStorage>> = {},\n  ) {\n    const extension = new Mark<ExtendedOptions, ExtendedStorage>(extendedConfig)\n\n    extension.parent = this\n\n    this.child = extension\n\n    extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name\n\n    if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {\n      console.warn(\n        `[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${extension.name}\".`,\n      )\n    }\n\n    extension.options = callOrReturn(\n      getExtensionField<AnyConfig['addOptions']>(extension, 'addOptions', {\n        name: extension.name,\n      }),\n    )\n\n    extension.storage = callOrReturn(\n      getExtensionField<AnyConfig['addStorage']>(extension, 'addStorage', {\n        name: extension.name,\n        options: extension.options,\n      }),\n    )\n\n    return extension\n  }\n\n  static handleExit({ editor, mark }: { editor: Editor; mark: Mark }) {\n    const { tr } = editor.state\n    const currentPos = editor.state.selection.$from\n    const isAtEnd = currentPos.pos === currentPos.end()\n\n    if (isAtEnd) {\n      const currentMarks = currentPos.marks()\n      const isInMark = !!currentMarks.find(m => m?.type.name === mark.name)\n\n      if (!isInMark) {\n        return false\n      }\n\n      const removeMark = currentMarks.find(m => m?.type.name === mark.name)\n\n      if (removeMark) {\n        tr.removeStoredMark(removeMark)\n      }\n      tr.insertText(' ', currentPos.pos)\n\n      editor.view.dispatch(tr)\n\n      return true\n    }\n\n    return false\n  }\n}\n", "export function isNumber(value: any): value is number {\n  return typeof value === 'number'\n}\n", "import { Fragment, Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { EditorState, Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport {\n  CanCommands,\n  ChainedCommands,\n  ExtendedRegExpMatchArray,\n  Range,\n  SingleCommands,\n} from './types.js'\nimport { isNumber } from './utilities/isNumber.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type PasteRuleMatch = {\n  index: number;\n  text: string;\n  replaceWith?: string;\n  match?: RegExpMatchArray;\n  data?: Record<string, any>;\n};\n\nexport type PasteRuleFinder =\n  | RegExp\n  | ((text: string, event?: ClipboardEvent | null) => PasteRuleMatch[] | null | undefined);\n\n/**\n * Paste rules are used to react to pasted content.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport class PasteRule {\n  find: PasteRuleFinder\n\n  handler: (props: {\n    state: EditorState;\n    range: Range;\n    match: ExtendedRegExpMatchArray;\n    commands: SingleCommands;\n    chain: () => ChainedCommands;\n    can: () => CanCommands;\n    pasteEvent: ClipboardEvent | null;\n    dropEvent: DragEvent | null;\n  }) => void | null\n\n  constructor(config: {\n    find: PasteRuleFinder;\n    handler: (props: {\n      can: () => CanCommands;\n      chain: () => ChainedCommands;\n      commands: SingleCommands;\n      dropEvent: DragEvent | null;\n      match: ExtendedRegExpMatchArray;\n      pasteEvent: ClipboardEvent | null;\n      range: Range;\n      state: EditorState;\n    }) => void | null;\n  }) {\n    this.find = config.find\n    this.handler = config.handler\n  }\n}\n\nconst pasteRuleMatcherHandler = (\n  text: string,\n  find: PasteRuleFinder,\n  event?: ClipboardEvent | null,\n): ExtendedRegExpMatchArray[] => {\n  if (isRegExp(find)) {\n    return [...text.matchAll(find)]\n  }\n\n  const matches = find(text, event)\n\n  if (!matches) {\n    return []\n  }\n\n  return matches.map(pasteRuleMatch => {\n    const result: ExtendedRegExpMatchArray = [pasteRuleMatch.text]\n\n    result.index = pasteRuleMatch.index\n    result.input = text\n    result.data = pasteRuleMatch.data\n\n    if (pasteRuleMatch.replaceWith) {\n      if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {\n        console.warn(\n          '[tiptap warn]: \"pasteRuleMatch.replaceWith\" must be part of \"pasteRuleMatch.text\".',\n        )\n      }\n\n      result.push(pasteRuleMatch.replaceWith)\n    }\n\n    return result\n  })\n}\n\nfunction run(config: {\n  editor: Editor;\n  state: EditorState;\n  from: number;\n  to: number;\n  rule: PasteRule;\n  pasteEvent: ClipboardEvent | null;\n  dropEvent: DragEvent | null;\n}): boolean {\n  const {\n    editor, state, from, to, rule, pasteEvent, dropEvent,\n  } = config\n\n  const { commands, chain, can } = new CommandManager({\n    editor,\n    state,\n  })\n\n  const handlers: (void | null)[] = []\n\n  state.doc.nodesBetween(from, to, (node, pos) => {\n    if (!node.isTextblock || node.type.spec.code) {\n      return\n    }\n\n    const resolvedFrom = Math.max(from, pos)\n    const resolvedTo = Math.min(to, pos + node.content.size)\n    const textToMatch = node.textBetween(resolvedFrom - pos, resolvedTo - pos, undefined, '\\ufffc')\n\n    const matches = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent)\n\n    matches.forEach(match => {\n      if (match.index === undefined) {\n        return\n      }\n\n      const start = resolvedFrom + match.index + 1\n      const end = start + match[0].length\n      const range = {\n        from: state.tr.mapping.map(start),\n        to: state.tr.mapping.map(end),\n      }\n\n      const handler = rule.handler({\n        state,\n        range,\n        match,\n        commands,\n        chain,\n        can,\n        pasteEvent,\n        dropEvent,\n      })\n\n      handlers.push(handler)\n    })\n  })\n\n  const success = handlers.every(handler => handler !== null)\n\n  return success\n}\n\n// When dragging across editors, must get another editor instance to delete selection content.\nlet tiptapDragFromOtherEditor: Editor | null = null\n\nconst createClipboardPasteEvent = (text: string) => {\n  const event = new ClipboardEvent('paste', {\n    clipboardData: new DataTransfer(),\n  })\n\n  event.clipboardData?.setData('text/html', text)\n\n  return event\n}\n\n/**\n * Create an paste rules plugin. When enabled, it will cause pasted\n * text that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function pasteRulesPlugin(props: { editor: Editor; rules: PasteRule[] }): Plugin[] {\n  const { editor, rules } = props\n  let dragSourceElement: Element | null = null\n  let isPastedFromProseMirror = false\n  let isDroppedFromProseMirror = false\n  let pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n  let dropEvent: DragEvent | null\n\n  try {\n    dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n  } catch {\n    dropEvent = null\n  }\n\n  const processEvent = ({\n    state,\n    from,\n    to,\n    rule,\n    pasteEvt,\n  }: {\n    state: EditorState;\n    from: number;\n    to: { b: number };\n    rule: PasteRule;\n    pasteEvt: ClipboardEvent | null;\n  }) => {\n    const tr = state.tr\n    const chainableState = createChainableState({\n      state,\n      transaction: tr,\n    })\n\n    const handler = run({\n      editor,\n      state: chainableState,\n      from: Math.max(from - 1, 0),\n      to: to.b - 1,\n      rule,\n      pasteEvent: pasteEvt,\n      dropEvent,\n    })\n\n    if (!handler || !tr.steps.length) {\n      return\n    }\n\n    try {\n      dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n    } catch {\n      dropEvent = null\n    }\n    pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n\n    return tr\n  }\n\n  const plugins = rules.map(rule => {\n    return new Plugin({\n      // we register a global drag handler to track the current drag source element\n      view(view) {\n        const handleDragstart = (event: DragEvent) => {\n          dragSourceElement = view.dom.parentElement?.contains(event.target as Element)\n            ? view.dom.parentElement\n            : null\n\n          if (dragSourceElement) {\n            tiptapDragFromOtherEditor = editor\n          }\n        }\n\n        const handleDragend = () => {\n          if (tiptapDragFromOtherEditor) {\n            tiptapDragFromOtherEditor = null\n          }\n        }\n\n        window.addEventListener('dragstart', handleDragstart)\n        window.addEventListener('dragend', handleDragend)\n\n        return {\n          destroy() {\n            window.removeEventListener('dragstart', handleDragstart)\n            window.removeEventListener('dragend', handleDragend)\n          },\n        }\n      },\n\n      props: {\n        handleDOMEvents: {\n          drop: (view, event: Event) => {\n            isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement\n            dropEvent = event as DragEvent\n\n            if (!isDroppedFromProseMirror) {\n              const dragFromOtherEditor = tiptapDragFromOtherEditor\n\n              if (dragFromOtherEditor?.isEditable) {\n                // setTimeout to avoid the wrong content after drop, timeout arg can't be empty or 0\n                setTimeout(() => {\n                  const selection = dragFromOtherEditor.state.selection\n\n                  if (selection) {\n                    dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to })\n                  }\n                }, 10)\n              }\n            }\n            return false\n          },\n\n          paste: (_view, event: Event) => {\n            const html = (event as ClipboardEvent).clipboardData?.getData('text/html')\n\n            pasteEvent = event as ClipboardEvent\n\n            isPastedFromProseMirror = !!html?.includes('data-pm-slice')\n\n            return false\n          },\n        },\n      },\n\n      appendTransaction: (transactions, oldState, state) => {\n        const transaction = transactions[0]\n        const isPaste = transaction.getMeta('uiEvent') === 'paste' && !isPastedFromProseMirror\n        const isDrop = transaction.getMeta('uiEvent') === 'drop' && !isDroppedFromProseMirror\n\n        // if PasteRule is triggered by insertContent()\n        const simulatedPasteMeta = transaction.getMeta('applyPasteRules') as\n          | undefined\n          | { from: number; text: string | ProseMirrorNode | Fragment }\n        const isSimulatedPaste = !!simulatedPasteMeta\n\n        if (!isPaste && !isDrop && !isSimulatedPaste) {\n          return\n        }\n\n        // Handle simulated paste\n        if (isSimulatedPaste) {\n          let { text } = simulatedPasteMeta\n\n          if (typeof text === 'string') {\n            text = text as string\n          } else {\n            text = getHTMLFromFragment(Fragment.from(text), state.schema)\n          }\n\n          const { from } = simulatedPasteMeta\n          const to = from + text.length\n\n          const pasteEvt = createClipboardPasteEvent(text)\n\n          return processEvent({\n            rule,\n            state,\n            from,\n            to: { b: to },\n            pasteEvt,\n          })\n        }\n\n        // handle actual paste/drop\n        const from = oldState.doc.content.findDiffStart(state.doc.content)\n        const to = oldState.doc.content.findDiffEnd(state.doc.content)\n\n        // stop if there is no changed range\n        if (!isNumber(from) || !to || from === to.b) {\n          return\n        }\n\n        return processEvent({\n          rule,\n          state,\n          from,\n          to,\n          pasteEvt: pasteEvent,\n        })\n      },\n    })\n  })\n\n  return plugins\n}\n", "export function findDuplicates(items: any[]): any[] {\n  const filtered = items.filter((el, index) => items.indexOf(el) !== index)\n\n  return Array.from(new Set(filtered))\n}\n", "import { keymap } from '@tiptap/pm/keymap'\nimport { Schema } from '@tiptap/pm/model'\nimport { Plugin } from '@tiptap/pm/state'\nimport { NodeViewConstructor } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport { getAttributesFromExtensions } from './helpers/getAttributesFromExtensions.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport { getNodeType } from './helpers/getNodeType.js'\nimport { getRenderedAttributes } from './helpers/getRenderedAttributes.js'\nimport { getSchemaByResolvedExtensions } from './helpers/getSchemaByResolvedExtensions.js'\nimport { getSchemaTypeByName } from './helpers/getSchemaTypeByName.js'\nimport { isExtensionRulesEnabled } from './helpers/isExtensionRulesEnabled.js'\nimport { splitExtensions } from './helpers/splitExtensions.js'\nimport type { NodeConfig } from './index.js'\nimport { InputRule, inputRulesPlugin } from './InputRule.js'\nimport { Mark } from './Mark.js'\nimport { PasteRule, pasteRulesPlugin } from './PasteRule.js'\nimport { AnyConfig, Extensions, RawCommands } from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { findDuplicates } from './utilities/findDuplicates.js'\n\nexport class ExtensionManager {\n  editor: Editor\n\n  schema: Schema\n\n  extensions: Extensions\n\n  splittableMarks: string[] = []\n\n  constructor(extensions: Extensions, editor: Editor) {\n    this.editor = editor\n    this.extensions = ExtensionManager.resolve(extensions)\n    this.schema = getSchemaByResolvedExtensions(this.extensions, editor)\n    this.setupExtensions()\n  }\n\n  /**\n   * Returns a flattened and sorted extension list while\n   * also checking for duplicated extensions and warns the user.\n   * @param extensions An array of Tiptap extensions\n   * @returns An flattened and sorted array of Tiptap extensions\n   */\n  static resolve(extensions: Extensions): Extensions {\n    const resolvedExtensions = ExtensionManager.sort(ExtensionManager.flatten(extensions))\n    const duplicatedNames = findDuplicates(resolvedExtensions.map(extension => extension.name))\n\n    if (duplicatedNames.length) {\n      console.warn(\n        `[tiptap warn]: Duplicate extension names found: [${duplicatedNames\n          .map(item => `'${item}'`)\n          .join(', ')}]. This can lead to issues.`,\n      )\n    }\n\n    return resolvedExtensions\n  }\n\n  /**\n   * Create a flattened array of extensions by traversing the `addExtensions` field.\n   * @param extensions An array of Tiptap extensions\n   * @returns A flattened array of Tiptap extensions\n   */\n  static flatten(extensions: Extensions): Extensions {\n    return (\n      extensions\n        .map(extension => {\n          const context = {\n            name: extension.name,\n            options: extension.options,\n            storage: extension.storage,\n          }\n\n          const addExtensions = getExtensionField<AnyConfig['addExtensions']>(\n            extension,\n            'addExtensions',\n            context,\n          )\n\n          if (addExtensions) {\n            return [extension, ...this.flatten(addExtensions())]\n          }\n\n          return extension\n        })\n        // `Infinity` will break TypeScript so we set a number that is probably high enough\n        .flat(10)\n    )\n  }\n\n  /**\n   * Sort extensions by priority.\n   * @param extensions An array of Tiptap extensions\n   * @returns A sorted array of Tiptap extensions by priority\n   */\n  static sort(extensions: Extensions): Extensions {\n    const defaultPriority = 100\n\n    return extensions.sort((a, b) => {\n      const priorityA = getExtensionField<AnyConfig['priority']>(a, 'priority') || defaultPriority\n      const priorityB = getExtensionField<AnyConfig['priority']>(b, 'priority') || defaultPriority\n\n      if (priorityA > priorityB) {\n        return -1\n      }\n\n      if (priorityA < priorityB) {\n        return 1\n      }\n\n      return 0\n    })\n  }\n\n  /**\n   * Get all commands from the extensions.\n   * @returns An object with all commands where the key is the command name and the value is the command function\n   */\n  get commands(): RawCommands {\n    return this.extensions.reduce((commands, extension) => {\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: extension.storage,\n        editor: this.editor,\n        type: getSchemaTypeByName(extension.name, this.schema),\n      }\n\n      const addCommands = getExtensionField<AnyConfig['addCommands']>(\n        extension,\n        'addCommands',\n        context,\n      )\n\n      if (!addCommands) {\n        return commands\n      }\n\n      return {\n        ...commands,\n        ...addCommands(),\n      }\n    }, {} as RawCommands)\n  }\n\n  /**\n   * Get all registered Prosemirror plugins from the extensions.\n   * @returns An array of Prosemirror plugins\n   */\n  get plugins(): Plugin[] {\n    const { editor } = this\n\n    // With ProseMirror, first plugins within an array are executed first.\n    // In Tiptap, we provide the ability to override plugins,\n    // so it feels more natural to run plugins at the end of an array first.\n    // That’s why we have to reverse the `extensions` array and sort again\n    // based on the `priority` option.\n    const extensions = ExtensionManager.sort([...this.extensions].reverse())\n\n    const inputRules: InputRule[] = []\n    const pasteRules: PasteRule[] = []\n\n    const allPlugins = extensions\n      .map(extension => {\n        const context = {\n          name: extension.name,\n          options: extension.options,\n          storage: extension.storage,\n          editor,\n          type: getSchemaTypeByName(extension.name, this.schema),\n        }\n\n        const plugins: Plugin[] = []\n\n        const addKeyboardShortcuts = getExtensionField<AnyConfig['addKeyboardShortcuts']>(\n          extension,\n          'addKeyboardShortcuts',\n          context,\n        )\n\n        let defaultBindings: Record<string, () => boolean> = {}\n\n        // bind exit handling\n        if (extension.type === 'mark' && getExtensionField<AnyConfig['exitable']>(extension, 'exitable', context)) {\n          defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension as Mark })\n        }\n\n        if (addKeyboardShortcuts) {\n          const bindings = Object.fromEntries(\n            Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {\n              return [shortcut, () => method({ editor })]\n            }),\n          )\n\n          defaultBindings = { ...defaultBindings, ...bindings }\n        }\n\n        const keyMapPlugin = keymap(defaultBindings)\n\n        plugins.push(keyMapPlugin)\n\n        const addInputRules = getExtensionField<AnyConfig['addInputRules']>(\n          extension,\n          'addInputRules',\n          context,\n        )\n\n        if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {\n          inputRules.push(...addInputRules())\n        }\n\n        const addPasteRules = getExtensionField<AnyConfig['addPasteRules']>(\n          extension,\n          'addPasteRules',\n          context,\n        )\n\n        if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {\n          pasteRules.push(...addPasteRules())\n        }\n\n        const addProseMirrorPlugins = getExtensionField<AnyConfig['addProseMirrorPlugins']>(\n          extension,\n          'addProseMirrorPlugins',\n          context,\n        )\n\n        if (addProseMirrorPlugins) {\n          const proseMirrorPlugins = addProseMirrorPlugins()\n\n          plugins.push(...proseMirrorPlugins)\n        }\n\n        return plugins\n      })\n      .flat()\n\n    return [\n      inputRulesPlugin({\n        editor,\n        rules: inputRules,\n      }),\n      ...pasteRulesPlugin({\n        editor,\n        rules: pasteRules,\n      }),\n      ...allPlugins,\n    ]\n  }\n\n  /**\n   * Get all attributes from the extensions.\n   * @returns An array of attributes\n   */\n  get attributes() {\n    return getAttributesFromExtensions(this.extensions)\n  }\n\n  /**\n   * Get all node views from the extensions.\n   * @returns An object with all node views where the key is the node name and the value is the node view function\n   */\n  get nodeViews(): Record<string, NodeViewConstructor> {\n    const { editor } = this\n    const { nodeExtensions } = splitExtensions(this.extensions)\n\n    return Object.fromEntries(\n      nodeExtensions\n        .filter(extension => !!getExtensionField(extension, 'addNodeView'))\n        .map(extension => {\n          const extensionAttributes = this.attributes.filter(\n            attribute => attribute.type === extension.name,\n          )\n          const context = {\n            name: extension.name,\n            options: extension.options,\n            storage: extension.storage,\n            editor,\n            type: getNodeType(extension.name, this.schema),\n          }\n          const addNodeView = getExtensionField<NodeConfig['addNodeView']>(\n            extension,\n            'addNodeView',\n            context,\n          )\n\n          if (!addNodeView) {\n            return []\n          }\n\n          const nodeview: NodeViewConstructor = (\n            node,\n            view,\n            getPos,\n            decorations,\n            innerDecorations,\n          ) => {\n            const HTMLAttributes = getRenderedAttributes(node, extensionAttributes)\n\n            return addNodeView()({\n              // pass-through\n              node,\n              view,\n              getPos: getPos as () => number,\n              decorations,\n              innerDecorations,\n              // tiptap-specific\n              editor,\n              extension,\n              HTMLAttributes,\n            })\n          }\n\n          return [extension.name, nodeview]\n        }),\n    )\n  }\n\n  /**\n   * Go through all extensions, create extension storages & setup marks\n   * & bind editor event listener.\n   */\n  private setupExtensions() {\n    this.extensions.forEach(extension => {\n      // store extension storage in editor\n      this.editor.extensionStorage[extension.name] = extension.storage\n\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: extension.storage,\n        editor: this.editor,\n        type: getSchemaTypeByName(extension.name, this.schema),\n      }\n\n      if (extension.type === 'mark') {\n        const keepOnSplit = callOrReturn(getExtensionField(extension, 'keepOnSplit', context)) ?? true\n\n        if (keepOnSplit) {\n          this.splittableMarks.push(extension.name)\n        }\n      }\n\n      const onBeforeCreate = getExtensionField<AnyConfig['onBeforeCreate']>(\n        extension,\n        'onBeforeCreate',\n        context,\n      )\n      const onCreate = getExtensionField<AnyConfig['onCreate']>(extension, 'onCreate', context)\n      const onUpdate = getExtensionField<AnyConfig['onUpdate']>(extension, 'onUpdate', context)\n      const onSelectionUpdate = getExtensionField<AnyConfig['onSelectionUpdate']>(\n        extension,\n        'onSelectionUpdate',\n        context,\n      )\n      const onTransaction = getExtensionField<AnyConfig['onTransaction']>(\n        extension,\n        'onTransaction',\n        context,\n      )\n      const onFocus = getExtensionField<AnyConfig['onFocus']>(extension, 'onFocus', context)\n      const onBlur = getExtensionField<AnyConfig['onBlur']>(extension, 'onBlur', context)\n      const onDestroy = getExtensionField<AnyConfig['onDestroy']>(extension, 'onDestroy', context)\n\n      if (onBeforeCreate) {\n        this.editor.on('beforeCreate', onBeforeCreate)\n      }\n\n      if (onCreate) {\n        this.editor.on('create', onCreate)\n      }\n\n      if (onUpdate) {\n        this.editor.on('update', onUpdate)\n      }\n\n      if (onSelectionUpdate) {\n        this.editor.on('selectionUpdate', onSelectionUpdate)\n      }\n\n      if (onTransaction) {\n        this.editor.on('transaction', onTransaction)\n      }\n\n      if (onFocus) {\n        this.editor.on('focus', onFocus)\n      }\n\n      if (onBlur) {\n        this.editor.on('blur', onBlur)\n      }\n\n      if (onDestroy) {\n        this.editor.on('destroy', onDestroy)\n      }\n    })\n  }\n}\n", "import { Plugin, Transaction } from '@tiptap/pm/state'\n\nimport { Editor } from './Editor.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport { ExtensionConfig } from './index.js'\nimport { InputRule } from './InputRule.js'\nimport { Mark } from './Mark.js'\nimport { Node } from './Node.js'\nimport { PasteRule } from './PasteRule.js'\nimport {\n  AnyConfig,\n  Extensions,\n  GlobalAttributes,\n  KeyboardShortcutCommand,\n  ParentConfig,\n  RawCommands,\n} from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { mergeDeep } from './utilities/mergeDeep.js'\n\ndeclare module '@tiptap/core' {\n  interface ExtensionConfig<Options = any, Storage = any> {\n    // @ts-ignore - this is a dynamic key\n    [key: string]: any\n\n    /**\n     * The extension name - this must be unique.\n     * It will be used to identify the extension.\n     *\n     * @example 'myExtension'\n     */\n    name: string\n\n    /**\n     * The priority of your extension. The higher, the earlier it will be called\n     * and will take precedence over other extensions with a lower priority.\n     * @default 100\n     * @example 101\n     */\n    priority?: number\n\n    /**\n     * The default options for this extension.\n     * @example\n     * defaultOptions: {\n     *   myOption: 'foo',\n     *   myOtherOption: 10,\n     * }\n     */\n    defaultOptions?: Options\n\n    /**\n     * This method will add options to this extension\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#settings\n     * @example\n     * addOptions() {\n     *  return {\n     *    myOption: 'foo',\n     *    myOtherOption: 10,\n     * }\n     */\n    addOptions?: (this: {\n      name: string\n      parent: Exclude<ParentConfig<ExtensionConfig<Options, Storage>>['addOptions'], undefined>\n    }) => Options\n\n    /**\n     * The default storage this extension can save data to.\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#storage\n     * @example\n     * defaultStorage: {\n     *   prefetchedUsers: [],\n     *   loading: false,\n     * }\n     */\n    addStorage?: (this: {\n      name: string\n      options: Options\n      parent: Exclude<ParentConfig<ExtensionConfig<Options, Storage>>['addStorage'], undefined>\n    }) => Storage\n\n    /**\n     * This function adds globalAttributes to specific nodes.\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#global-attributes\n     * @example\n     * addGlobalAttributes() {\n     *   return [\n     *     {\n             // Extend the following extensions\n     *       types: [\n     *         'heading',\n     *         'paragraph',\n     *       ],\n     *       // … with those attributes\n     *       attributes: {\n     *         textAlign: {\n     *           default: 'left',\n     *           renderHTML: attributes => ({\n     *             style: `text-align: ${attributes.textAlign}`,\n     *           }),\n     *           parseHTML: element => element.style.textAlign || 'left',\n     *         },\n     *       },\n     *     },\n     *   ]\n     * }\n     */\n    addGlobalAttributes?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      extensions: (Node | Mark)[]\n      parent: ParentConfig<ExtensionConfig<Options, Storage>>['addGlobalAttributes']\n    }) => GlobalAttributes\n\n    /**\n     * This function adds commands to the editor\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#commands\n     * @example\n     * addCommands() {\n     *   return {\n     *     myCommand: () => ({ chain }) => chain().setMark('type', 'foo').run(),\n     *   }\n     * }\n     */\n    addCommands?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      parent: ParentConfig<ExtensionConfig<Options, Storage>>['addCommands']\n    }) => Partial<RawCommands>\n\n    /**\n     * This function registers keyboard shortcuts.\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#keyboard-shortcuts\n     * @example\n     * addKeyboardShortcuts() {\n     *   return {\n     *     'Mod-l': () => this.editor.commands.toggleBulletList(),\n     *   }\n     * },\n     */\n    addKeyboardShortcuts?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      parent: ParentConfig<ExtensionConfig<Options, Storage>>['addKeyboardShortcuts']\n    }) => {\n      [key: string]: KeyboardShortcutCommand\n    }\n\n    /**\n     * This function adds input rules to the editor.\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#input-rules\n     * @example\n     * addInputRules() {\n     *   return [\n     *     markInputRule({\n     *       find: inputRegex,\n     *       type: this.type,\n     *     }),\n     *   ]\n     * },\n     */\n    addInputRules?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      parent: ParentConfig<ExtensionConfig<Options, Storage>>['addInputRules']\n    }) => InputRule[]\n\n    /**\n     * This function adds paste rules to the editor.\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#paste-rules\n     * @example\n     * addPasteRules() {\n     *   return [\n     *     markPasteRule({\n     *       find: pasteRegex,\n     *       type: this.type,\n     *     }),\n     *   ]\n     * },\n     */\n    addPasteRules?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      parent: ParentConfig<ExtensionConfig<Options, Storage>>['addPasteRules']\n    }) => PasteRule[]\n\n    /**\n     * This function adds Prosemirror plugins to the editor\n     * @see https://tiptap.dev/docs/editor/guide/custom-extensions#prosemirror-plugins\n     * @example\n     * addProseMirrorPlugins() {\n     *   return [\n     *     customPlugin(),\n     *   ]\n     * }\n     */\n    addProseMirrorPlugins?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      parent: ParentConfig<ExtensionConfig<Options, Storage>>['addProseMirrorPlugins']\n    }) => Plugin[]\n\n    /**\n     * This function adds additional extensions to the editor. This is useful for\n     * building extension kits.\n     * @example\n     * addExtensions() {\n     *   return [\n     *     BulletList,\n     *     OrderedList,\n     *     ListItem\n     *   ]\n     * }\n     */\n    addExtensions?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<ExtensionConfig<Options, Storage>>['addExtensions']\n    }) => Extensions\n\n    /**\n     * This function extends the schema of the node.\n     * @example\n     * extendNodeSchema() {\n     *   return {\n     *     group: 'inline',\n     *     selectable: false,\n     *   }\n     * }\n     */\n    extendNodeSchema?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<ExtensionConfig<Options, Storage>>['extendNodeSchema']\n          },\n          extension: Node,\n        ) => Record<string, any>)\n      | null\n\n    /**\n     * This function extends the schema of the mark.\n     * @example\n     * extendMarkSchema() {\n     *   return {\n     *     group: 'inline',\n     *     selectable: false,\n     *   }\n     * }\n     */\n    extendMarkSchema?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<ExtensionConfig<Options, Storage>>['extendMarkSchema']\n          },\n          extension: Mark,\n        ) => Record<string, any>)\n      | null\n\n    /**\n     * The editor is not ready yet.\n     */\n    onBeforeCreate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          parent: ParentConfig<ExtensionConfig<Options, Storage>>['onBeforeCreate']\n        }) => void)\n      | null\n\n    /**\n     * The editor is ready.\n     */\n    onCreate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          parent: ParentConfig<ExtensionConfig<Options, Storage>>['onCreate']\n        }) => void)\n      | null\n\n    /**\n     * The content has changed.\n     */\n    onUpdate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          parent: ParentConfig<ExtensionConfig<Options, Storage>>['onUpdate']\n        }) => void)\n      | null\n\n    /**\n     * The selection has changed.\n     */\n    onSelectionUpdate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          parent: ParentConfig<ExtensionConfig<Options, Storage>>['onSelectionUpdate']\n        }) => void)\n      | null\n\n    /**\n     * The editor state has changed.\n     */\n    onTransaction?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            parent: ParentConfig<ExtensionConfig<Options, Storage>>['onTransaction']\n          },\n          props: {\n            editor: Editor\n            transaction: Transaction\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor is focused.\n     */\n    onFocus?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            parent: ParentConfig<ExtensionConfig<Options, Storage>>['onFocus']\n          },\n          props: {\n            event: FocusEvent\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor isn’t focused anymore.\n     */\n    onBlur?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            parent: ParentConfig<ExtensionConfig<Options, Storage>>['onBlur']\n          },\n          props: {\n            event: FocusEvent\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor is destroyed.\n     */\n    onDestroy?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          parent: ParentConfig<ExtensionConfig<Options, Storage>>['onDestroy']\n        }) => void)\n      | null\n  }\n}\n\n/**\n * The Extension class is the base class for all extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Extension<Options = any, Storage = any> {\n  type = 'extension'\n\n  name = 'extension'\n\n  parent: Extension | null = null\n\n  child: Extension | null = null\n\n  options: Options\n\n  storage: Storage\n\n  config: ExtensionConfig = {\n    name: this.name,\n    defaultOptions: {},\n  }\n\n  constructor(config: Partial<ExtensionConfig<Options, Storage>> = {}) {\n    this.config = {\n      ...this.config,\n      ...config,\n    }\n\n    this.name = this.config.name\n\n    if (config.defaultOptions && Object.keys(config.defaultOptions).length > 0) {\n      console.warn(\n        `[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${this.name}\".`,\n      )\n    }\n\n    // TODO: remove `addOptions` fallback\n    this.options = this.config.defaultOptions\n\n    if (this.config.addOptions) {\n      this.options = callOrReturn(\n        getExtensionField<AnyConfig['addOptions']>(this, 'addOptions', {\n          name: this.name,\n        }),\n      )\n    }\n\n    this.storage = callOrReturn(\n      getExtensionField<AnyConfig['addStorage']>(this, 'addStorage', {\n        name: this.name,\n        options: this.options,\n      }),\n    ) || {}\n  }\n\n  static create<O = any, S = any>(config: Partial<ExtensionConfig<O, S>> = {}) {\n    return new Extension<O, S>(config)\n  }\n\n  configure(options: Partial<Options> = {}) {\n    // return a new instance so we can use the same extension\n    // with different calls of `configure`\n    const extension = this.extend<Options, Storage>({\n      ...this.config,\n      addOptions: () => {\n        return mergeDeep(this.options as Record<string, any>, options) as Options\n      },\n    })\n\n    // Always preserve the current name\n    extension.name = this.name\n    // Set the parent to be our parent\n    extension.parent = this.parent\n\n    return extension\n  }\n\n  extend<ExtendedOptions = Options, ExtendedStorage = Storage>(\n    extendedConfig: Partial<ExtensionConfig<ExtendedOptions, ExtendedStorage>> = {},\n  ) {\n    const extension = new Extension<ExtendedOptions, ExtendedStorage>({ ...this.config, ...extendedConfig })\n\n    extension.parent = this\n\n    this.child = extension\n\n    extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name\n\n    if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {\n      console.warn(\n        `[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${extension.name}\".`,\n      )\n    }\n\n    extension.options = callOrReturn(\n      getExtensionField<AnyConfig['addOptions']>(extension, 'addOptions', {\n        name: extension.name,\n      }),\n    )\n\n    extension.storage = callOrReturn(\n      getExtensionField<AnyConfig['addStorage']>(extension, 'addStorage', {\n        name: extension.name,\n        options: extension.options,\n      }),\n    )\n\n    return extension\n  }\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { Range, TextSerializer } from '../types.js'\n\n/**\n * Gets the text between two positions in a Prosemirror node\n * and serializes it using the given text serializers and block separator (see getText)\n * @param startNode The Prosemirror node to start from\n * @param range The range of the text to get\n * @param options Options for the text serializer & block separator\n * @returns The text between the two positions\n */\nexport function getTextBetween(\n  startNode: ProseMirrorNode,\n  range: Range,\n  options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  },\n): string {\n  const { from, to } = range\n  const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n  let text = ''\n\n  startNode.nodesBetween(from, to, (node, pos, parent, index) => {\n    if (node.isBlock && pos > from) {\n      text += blockSeparator\n    }\n\n    const textSerializer = textSerializers?.[node.type.name]\n\n    if (textSerializer) {\n      if (parent) {\n        text += textSerializer({\n          node,\n          pos,\n          parent,\n          index,\n          range,\n        })\n      }\n      // do not descend into child nodes when there exists a serializer\n      return false\n    }\n\n    if (node.isText) {\n      text += node?.text?.slice(Math.max(from, pos) - pos, to - pos) // eslint-disable-line\n    }\n  })\n\n  return text\n}\n", "import { Schema } from '@tiptap/pm/model'\n\nimport { TextSerializer } from '../types.js'\n\n/**\n * Find text serializers `toText` in a Prosemirror schema\n * @param schema The Prosemirror schema to search in\n * @returns A record of text serializers by node name\n */\nexport function getTextSerializersFromSchema(schema: Schema): Record<string, TextSerializer> {\n  return Object.fromEntries(\n    Object.entries(schema.nodes)\n      .filter(([, node]) => node.spec.toText)\n      .map(([name, node]) => [name, node.spec.toText]),\n  )\n}\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\nimport { getTextBetween } from '../helpers/getTextBetween.js'\nimport { getTextSerializersFromSchema } from '../helpers/getTextSerializersFromSchema.js'\n\nexport type ClipboardTextSerializerOptions = {\n  blockSeparator?: string,\n}\n\nexport const ClipboardTextSerializer = Extension.create<ClipboardTextSerializerOptions>({\n  name: 'clipboardTextSerializer',\n\n  addOptions() {\n    return {\n      blockSeparator: undefined,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('clipboardTextSerializer'),\n        props: {\n          clipboardTextSerializer: () => {\n            const { editor } = this\n            const { state, schema } = editor\n            const { doc, selection } = state\n            const { ranges } = selection\n            const from = Math.min(...ranges.map(range => range.$from.pos))\n            const to = Math.max(...ranges.map(range => range.$to.pos))\n            const textSerializers = getTextSerializersFromSchema(schema)\n            const range = { from, to }\n\n            return getTextBetween(doc, range, {\n              ...(this.options.blockSeparator !== undefined\n                ? { blockSeparator: this.options.blockSeparator }\n                : {}),\n              textSerializers,\n            })\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    blur: {\n      /**\n       * Removes focus from the editor.\n       * @example editor.commands.blur()\n       */\n      blur: () => ReturnType,\n    }\n  }\n}\n\nexport const blur: RawCommands['blur'] = () => ({ editor, view }) => {\n  requestAnimationFrame(() => {\n    if (!editor.isDestroyed) {\n      (view.dom as HTMLElement).blur()\n\n      // Browsers should remove the caret on blur but safari does not.\n      // See: https://github.com/ueberdosis/tiptap/issues/2405\n      window?.getSelection()?.removeAllRanges()\n    }\n  })\n\n  return true\n}\n", "import { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    clearContent: {\n      /**\n       * Clear the whole document.\n       * @param emitUpdate Whether to emit an update event.\n       * @example editor.commands.clearContent()\n       */\n      clearContent: (emitUpdate?: boolean) => ReturnType,\n    }\n  }\n}\n\nexport const clearContent: RawCommands['clearContent'] = (emitUpdate = false) => ({ commands }) => {\n  return commands.setContent('', emitUpdate)\n}\n", "import { liftTarget } from '@tiptap/pm/transform'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    clearNodes: {\n      /**\n       * Normalize nodes to a simple paragraph.\n       * @example editor.commands.clearNodes()\n       */\n      clearNodes: () => ReturnType,\n    }\n  }\n}\n\nexport const clearNodes: RawCommands['clearNodes'] = () => ({ state, tr, dispatch }) => {\n  const { selection } = tr\n  const { ranges } = selection\n\n  if (!dispatch) {\n    return true\n  }\n\n  ranges.forEach(({ $from, $to }) => {\n    state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n      if (node.type.isText) {\n        return\n      }\n\n      const { doc, mapping } = tr\n      const $mappedFrom = doc.resolve(mapping.map(pos))\n      const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize))\n      const nodeRange = $mappedFrom.blockRange($mappedTo)\n\n      if (!nodeRange) {\n        return\n      }\n\n      const targetLiftDepth = liftTarget(nodeRange)\n\n      if (node.type.isTextblock) {\n        const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index())\n\n        tr.setNodeMarkup(nodeRange.start, defaultType)\n      }\n\n      if (targetLiftDepth || targetLiftDepth === 0) {\n        tr.lift(nodeRange, targetLiftDepth)\n      }\n    })\n  })\n\n  return true\n}\n", "import { Command, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    command: {\n      /**\n       * Define a command inline.\n       * @param fn The command function.\n       * @example\n       * editor.commands.command(({ tr, state }) => {\n       *   ...\n       *   return true\n       * })\n       */\n      command: (fn: (props: Parameters<Command>[0]) => boolean) => ReturnType,\n    }\n  }\n}\n\nexport const command: RawCommands['command'] = fn => props => {\n  return fn(props)\n}\n", "import { createParagraphNear as originalCreateParagraphNear } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    createParagraphNear: {\n      /**\n       * Create a paragraph nearby.\n       * @example editor.commands.createParagraphNear()\n       */\n      createParagraphNear: () => ReturnType\n    }\n  }\n}\n\nexport const createParagraphNear: RawCommands['createParagraphNear'] = () => ({ state, dispatch }) => {\n  return originalCreateParagraphNear(state, dispatch)\n}\n", "import { TextSelection } from '@tiptap/pm/state'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    cut: {\n      /**\n       * Cuts content from a range and inserts it at a given position.\n       * @param range The range to cut.\n       * @param range.from The start position of the range.\n       * @param range.to The end position of the range.\n       * @param targetPos The position to insert the content at.\n       * @example editor.commands.cut({ from: 1, to: 3 }, 5)\n       */\n      cut: ({ from, to }: { from: number, to: number }, targetPos: number) => ReturnType,\n    }\n  }\n}\n\nexport const cut: RawCommands['cut'] = (originRange, targetPos) => ({ editor, tr }) => {\n  const { state } = editor\n\n  const contentSlice = state.doc.slice(originRange.from, originRange.to)\n\n  tr.deleteRange(originRange.from, originRange.to)\n  const newPos = tr.mapping.map(targetPos)\n\n  tr.insert(newPos, contentSlice.content)\n\n  tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))))\n\n  return true\n}\n", "import { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteCurrentNode: {\n      /**\n       * Delete the node that currently has the selection anchor.\n       * @example editor.commands.deleteCurrentNode()\n       */\n      deleteCurrentNode: () => ReturnType,\n    }\n  }\n}\n\nexport const deleteCurrentNode: RawCommands['deleteCurrentNode'] = () => ({ tr, dispatch }) => {\n  const { selection } = tr\n  const currentNode = selection.$anchor.node()\n\n  // if there is content inside the current node, break out of this command\n  if (currentNode.content.size > 0) {\n    return false\n  }\n\n  const $pos = tr.selection.$anchor\n\n  for (let depth = $pos.depth; depth > 0; depth -= 1) {\n    const node = $pos.node(depth)\n\n    if (node.type === currentNode.type) {\n      if (dispatch) {\n        const from = $pos.before(depth)\n        const to = $pos.after(depth)\n\n        tr.delete(from, to).scrollIntoView()\n      }\n\n      return true\n    }\n  }\n\n  return false\n}\n", "import { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteNode: {\n      /**\n       * Delete a node with a given type or name.\n       * @param typeOrName The type or name of the node.\n       * @example editor.commands.deleteNode('paragraph')\n       */\n      deleteNode: (typeOrName: string | NodeType) => ReturnType,\n    }\n  }\n}\n\nexport const deleteNode: RawCommands['deleteNode'] = typeOrName => ({ tr, state, dispatch }) => {\n  const type = getNodeType(typeOrName, state.schema)\n  const $pos = tr.selection.$anchor\n\n  for (let depth = $pos.depth; depth > 0; depth -= 1) {\n    const node = $pos.node(depth)\n\n    if (node.type === type) {\n      if (dispatch) {\n        const from = $pos.before(depth)\n        const to = $pos.after(depth)\n\n        tr.delete(from, to).scrollIntoView()\n      }\n\n      return true\n    }\n  }\n\n  return false\n}\n", "import { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteRange: {\n      /**\n       * Delete a given range.\n       * @param range The range to delete.\n       * @example editor.commands.deleteRange({ from: 1, to: 3 })\n       */\n      deleteRange: (range: Range) => ReturnType,\n    }\n  }\n}\n\nexport const deleteRange: RawCommands['deleteRange'] = range => ({ tr, dispatch }) => {\n  const { from, to } = range\n\n  if (dispatch) {\n    tr.delete(from, to)\n  }\n\n  return true\n}\n", "import { deleteSelection as originalDeleteSelection } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteSelection: {\n      /**\n       * Delete the selection, if there is one.\n       * @example editor.commands.deleteSelection()\n       */\n      deleteSelection: () => ReturnType\n    }\n  }\n}\n\nexport const deleteSelection: RawCommands['deleteSelection'] = () => ({ state, dispatch }) => {\n  return originalDeleteSelection(state, dispatch)\n}\n", "import { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    enter: {\n      /**\n       * Trigger enter.\n       * @example editor.commands.enter()\n       */\n      enter: () => ReturnType,\n    }\n  }\n}\n\nexport const enter: RawCommands['enter'] = () => ({ commands }) => {\n  return commands.keyboardShortcut('Enter')\n}\n", "import { exitCode as originalExitCode } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    exitCode: {\n      /**\n       * Exit from a code block.\n       * @example editor.commands.exitCode()\n       */\n      exitCode: () => ReturnType\n    }\n  }\n}\n\nexport const exitCode: RawCommands['exitCode'] = () => ({ state, dispatch }) => {\n  return originalExitCode(state, dispatch)\n}\n", "import { isRegExp } from './isRegExp.js'\n\n/**\n * Check if object1 includes object2\n * @param object1 Object\n * @param object2 Object\n */\nexport function objectIncludes(\n  object1: Record<string, any>,\n  object2: Record<string, any>,\n  options: { strict: boolean } = { strict: true },\n): boolean {\n  const keys = Object.keys(object2)\n\n  if (!keys.length) {\n    return true\n  }\n\n  return keys.every(key => {\n    if (options.strict) {\n      return object2[key] === object1[key]\n    }\n\n    if (isRegExp(object2[key])) {\n      return object2[key].test(object1[key])\n    }\n\n    return object2[key] === object1[key]\n  })\n}\n", "import { Mark as ProseMirrorMark, MarkType, ResolvedPos } from '@tiptap/pm/model'\n\nimport { Range } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\n\nfunction findMarkInSet(\n  marks: ProseMirrorMark[],\n  type: MarkType,\n  attributes: Record<string, any> = {},\n): ProseMirrorMark | undefined {\n  return marks.find(item => {\n    return (\n      item.type === type\n      && objectIncludes(\n        // Only check equality for the attributes that are provided\n        Object.fromEntries(Object.keys(attributes).map(k => [k, item.attrs[k]])),\n        attributes,\n      )\n    )\n  })\n}\n\nfunction isMarkInSet(\n  marks: ProseMirrorMark[],\n  type: MarkType,\n  attributes: Record<string, any> = {},\n): boolean {\n  return !!findMarkInSet(marks, type, attributes)\n}\n\n/**\n * Get the range of a mark at a resolved position.\n */\nexport function getMarkRange(\n  /**\n   * The position to get the mark range for.\n   */\n  $pos: ResolvedPos,\n  /**\n   * The mark type to get the range for.\n   */\n  type: MarkType,\n  /**\n   * The attributes to match against.\n   * If not provided, only the first mark at the position will be matched.\n   */\n  attributes?: Record<string, any>,\n): Range | void {\n  if (!$pos || !type) {\n    return\n  }\n  let start = $pos.parent.childAfter($pos.parentOffset)\n\n  // If the cursor is at the start of a text node that does not have the mark, look backward\n  if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n    start = $pos.parent.childBefore($pos.parentOffset)\n  }\n\n  // If there is no text node with the mark even backward, return undefined\n  if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n    return\n  }\n\n  // Default to only matching against the first mark's attributes\n  attributes = attributes || start.node.marks[0]?.attrs\n\n  // We now know that the cursor is either at the start, middle or end of a text node with the specified mark\n  // so we can look it up on the targeted mark\n  const mark = findMarkInSet([...start.node.marks], type, attributes)\n\n  if (!mark) {\n    return\n  }\n\n  let startIndex = start.index\n  let startPos = $pos.start() + start.offset\n  let endIndex = startIndex + 1\n  let endPos = startPos + start.node.nodeSize\n\n  while (\n    startIndex > 0\n    && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)\n  ) {\n    startIndex -= 1\n    startPos -= $pos.parent.child(startIndex).nodeSize\n  }\n\n  while (\n    endIndex < $pos.parent.childCount\n    && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)\n  ) {\n    endPos += $pos.parent.child(endIndex).nodeSize\n    endIndex += 1\n  }\n\n  return {\n    from: startPos,\n    to: endPos,\n  }\n}\n", "import { MarkType, Schema } from '@tiptap/pm/model'\n\nexport function getMarkType(nameOrType: string | MarkType, schema: Schema): MarkType {\n  if (typeof nameOrType === 'string') {\n    if (!schema.marks[nameOrType]) {\n      throw Error(\n        `There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`,\n      )\n    }\n\n    return schema.marks[nameOrType]\n  }\n\n  return nameOrType\n}\n", "import { MarkType } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    extendMarkRange: {\n      /**\n       * Extends the text selection to the current mark by type or name.\n       * @param typeOrName The type or name of the mark.\n       * @param attributes The attributes of the mark.\n       * @example editor.commands.extendMarkRange('bold')\n       * @example editor.commands.extendMarkRange('mention', { userId: \"1\" })\n       */\n      extendMarkRange: (\n        /**\n         * The type or name of the mark.\n         */\n        typeOrName: string | MarkType,\n\n        /**\n         * The attributes of the mark.\n         */\n        attributes?: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const extendMarkRange: RawCommands['extendMarkRange'] = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {\n  const type = getMarkType(typeOrName, state.schema)\n  const { doc, selection } = tr\n  const { $from, from, to } = selection\n\n  if (dispatch) {\n    const range = getMarkRange($from, type, attributes)\n\n    if (range && range.from <= from && range.to >= to) {\n      const newSelection = TextSelection.create(doc, range.from, range.to)\n\n      tr.setSelection(newSelection)\n    }\n  }\n\n  return true\n}\n", "import { Command, CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    first: {\n      /**\n       * Runs one command after the other and stops at the first which returns true.\n       * @param commands The commands to run.\n       * @example editor.commands.first([command1, command2])\n       */\n      first: (commands: Command[] | ((props: CommandProps) => Command[])) => ReturnType,\n    }\n  }\n}\n\nexport const first: RawCommands['first'] = commands => props => {\n  const items = typeof commands === 'function'\n    ? commands(props)\n    : commands\n\n  for (let i = 0; i < items.length; i += 1) {\n    if (items[i](props)) {\n      return true\n    }\n  }\n\n  return false\n}\n", "import { TextSelection } from '@tiptap/pm/state'\n\nexport function isTextSelection(value: unknown): value is TextSelection {\n  return value instanceof TextSelection\n}\n", "export function minMax(value = 0, min = 0, max = 0): number {\n  return Math.min(Math.max(value, min), max)\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Selection, TextSelection } from '@tiptap/pm/state'\n\nimport { FocusPosition } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\nexport function resolveFocusPosition(\n  doc: ProseMirrorNode,\n  position: FocusPosition = null,\n): Selection | null {\n  if (!position) {\n    return null\n  }\n\n  const selectionAtStart = Selection.atStart(doc)\n  const selectionAtEnd = Selection.atEnd(doc)\n\n  if (position === 'start' || position === true) {\n    return selectionAtStart\n  }\n\n  if (position === 'end') {\n    return selectionAtEnd\n  }\n\n  const minPos = selectionAtStart.from\n  const maxPos = selectionAtEnd.to\n\n  if (position === 'all') {\n    return TextSelection.create(\n      doc,\n      minMax(0, minPos, maxPos),\n      minMax(doc.content.size, minPos, maxPos),\n    )\n  }\n\n  return TextSelection.create(\n    doc,\n    minMax(position, minPos, maxPos),\n    minMax(position, minPos, maxPos),\n  )\n}\n", "export function isAndroid(): boolean {\n  return navigator.platform === 'Android' || /android/i.test(navigator.userAgent)\n}\n", "export function isiOS(): boolean {\n  return [\n    'iPad Simulator',\n    'iPhone Simulator',\n    'iPod Simulator',\n    'iPad',\n    'iPhone',\n    'iPod',\n  ].includes(navigator.platform)\n  // iPad on iOS 13 detection\n  || (navigator.userAgent.includes('Mac') && 'ontouchend' in document)\n}\n", "/**\n * Detects if the current browser is Safari (but not iOS Safari or Chrome).\n * @returns `true` if the browser is Safari, `false` otherwise.\n * @example\n * if (isSafari()) {\n *   // Safari-specific handling\n * }\n */\nexport function isSafari(): boolean {\n  return typeof navigator !== 'undefined' ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false\n}\n", "import { isTextSelection } from '../helpers/isTextSelection.js'\nimport { resolveFocusPosition } from '../helpers/resolveFocusPosition.js'\nimport { FocusPosition, RawCommands } from '../types.js'\nimport { isAndroid } from '../utilities/isAndroid.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isSafari } from '../utilities/isSafari.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    focus: {\n      /**\n       * Focus the editor at the given position.\n       * @param position The position to focus at.\n       * @param options.scrollIntoView Scroll the focused position into view after focusing\n       * @example editor.commands.focus()\n       * @example editor.commands.focus(32, { scrollIntoView: false })\n       */\n      focus: (\n        /**\n         * The position to focus at.\n         */\n        position?: FocusPosition,\n\n        /**\n         * Optional options\n         * @default { scrollIntoView: true }\n         */\n        options?: {\n          scrollIntoView?: boolean,\n        },\n      ) => ReturnType,\n    }\n  }\n}\n\nexport const focus: RawCommands['focus'] = (position = null, options = {}) => ({\n  editor,\n  view,\n  tr,\n  dispatch,\n}) => {\n  options = {\n    scrollIntoView: true,\n    ...options,\n  }\n\n  const delayedFocus = () => {\n    // focus within `requestAnimationFrame` breaks focus on iOS and Android\n    // so we have to call this\n    if (isiOS() || isAndroid()) {\n      (view.dom as HTMLElement).focus()\n    }\n\n    // For React we have to focus asynchronously. Otherwise wild things happen.\n    // see: https://github.com/ueberdosis/tiptap/issues/1520\n    requestAnimationFrame(() => {\n      if (!editor.isDestroyed) {\n        view.focus()\n\n        // Safari requires preventScroll to avoid the browser scrolling to the\n        // top of the editor when focus is called before the selection is set.\n        // We exclude iOS and Android since they are already handled above.\n        // see: https://github.com/ueberdosis/tiptap/issues/7318\n        if (isSafari() && !isiOS() && !isAndroid()) {\n          (view.dom as HTMLElement).focus({ preventScroll: true })\n        }\n      }\n    })\n  }\n\n  if ((view.hasFocus() && position === null) || position === false) {\n    return true\n  }\n\n  // we don’t try to resolve a NodeSelection or CellSelection\n  if (dispatch && position === null && !isTextSelection(editor.state.selection)) {\n    delayedFocus()\n    return true\n  }\n\n  // pass through tr.doc instead of editor.state.doc\n  // since transactions could change the editors state before this command has been run\n  const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection\n  const isSameSelection = editor.state.selection.eq(selection)\n\n  if (dispatch) {\n    if (!isSameSelection) {\n      tr.setSelection(selection)\n    }\n\n    // `tr.setSelection` resets the stored marks\n    // so we’ll restore them if the selection is the same as before\n    if (isSameSelection && tr.storedMarks) {\n      tr.setStoredMarks(tr.storedMarks)\n    }\n\n    delayedFocus()\n  }\n\n  return true\n}\n", "import { CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    forEach: {\n      /**\n       * Loop through an array of items.\n       */\n      forEach: <T>(\n        items: T[],\n        fn: (\n          item: T,\n          props: CommandProps & {\n            index: number,\n          },\n        ) => boolean,\n      ) => ReturnType,\n    }\n  }\n}\n\nexport const forEach: RawCommands['forEach'] = (items, fn) => props => {\n  return items.every((item, index) => fn(item, { ...props, index }))\n}\n", "import { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport { Content, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    insertContent: {\n      /**\n       * Insert a node or string of HTML at the current position.\n       * @example editor.commands.insertContent('<h1>Example</h1>')\n       * @example editor.commands.insertContent('<h1>Example</h1>', { updateSelection: false })\n       */\n      insertContent: (\n        /**\n         * The ProseMirror content to insert.\n         */\n        value: Content | ProseMirrorNode | Fragment,\n\n        /**\n         * Optional options\n         */\n        options?: {\n          /**\n           * Options for parsing the content.\n           */\n          parseOptions?: ParseOptions;\n\n          /**\n           * Whether to update the selection after inserting the content.\n           */\n          updateSelection?: boolean;\n          applyInputRules?: boolean;\n          applyPasteRules?: boolean;\n        }\n      ) => ReturnType;\n    };\n  }\n}\n\nexport const insertContent: RawCommands['insertContent'] = (value, options) => ({ tr, commands }) => {\n  return commands.insertContentAt(\n    { from: tr.selection.from, to: tr.selection.to },\n    value,\n    options,\n  )\n}\n", "const removeWhitespaces = (node: HTMLElement) => {\n  const children = node.childNodes\n\n  for (let i = children.length - 1; i >= 0; i -= 1) {\n    const child = children[i]\n\n    if (child.nodeType === 3 && child.nodeValue && /^(\\n\\s\\s|\\n)$/.test(child.nodeValue)) {\n      node.removeChild(child)\n    } else if (child.nodeType === 1) {\n      removeWhitespaces(child as HTMLElement)\n    }\n  }\n\n  return node\n}\n\nexport function elementFromString(value: string): HTMLElement {\n  // add a wrapper to preserve leading and trailing whitespace\n  const wrappedValue = `<body>${value}</body>`\n\n  const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body\n\n  return removeWhitespaces(html)\n}\n", "import {\n  DOMParser,\n  Fragment,\n  Node as ProseMirrorNode,\n  ParseOptions,\n  Schema,\n} from '@tiptap/pm/model'\n\nimport { Content } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\n\nexport type CreateNodeFromContentOptions = {\n  slice?: boolean\n  parseOptions?: ParseOptions\n  errorOnInvalidContent?: boolean\n}\n\n/**\n * Takes a JSON or HTML content and creates a Prosemirror node or fragment from it.\n * @param content The JSON or HTML content to create the node from\n * @param schema The Prosemirror schema to use for the node\n * @param options Options for the parser\n * @returns The created Prosemirror node or fragment\n */\nexport function createNodeFromContent(\n  content: Content | ProseMirrorNode | Fragment,\n  schema: Schema,\n  options?: CreateNodeFromContentOptions,\n): ProseMirrorNode | Fragment {\n  if (content instanceof ProseMirrorNode || content instanceof Fragment) {\n    return content\n  }\n  options = {\n    slice: true,\n    parseOptions: {},\n    ...options,\n  }\n\n  const isJSONContent = typeof content === 'object' && content !== null\n  const isTextContent = typeof content === 'string'\n\n  if (isJSONContent) {\n    try {\n      const isArrayContent = Array.isArray(content) && content.length > 0\n\n      // if the JSON Content is an array of nodes, create a fragment for each node\n      if (isArrayContent) {\n        return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)))\n      }\n\n      const node = schema.nodeFromJSON(content)\n\n      if (options.errorOnInvalidContent) {\n        node.check()\n      }\n\n      return node\n    } catch (error) {\n      if (options.errorOnInvalidContent) {\n        throw new Error('[tiptap error]: Invalid JSON content', { cause: error as Error })\n      }\n\n      console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)\n\n      return createNodeFromContent('', schema, options)\n    }\n  }\n\n  if (isTextContent) {\n\n    // Check for invalid content\n    if (options.errorOnInvalidContent) {\n      let hasInvalidContent = false\n      let invalidContent = ''\n\n      // A copy of the current schema with a catch-all node at the end\n      const contentCheckSchema = new Schema({\n        topNode: schema.spec.topNode,\n        marks: schema.spec.marks,\n        // Prosemirror's schemas are executed such that: the last to execute, matches last\n        // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle\n        nodes: schema.spec.nodes.append({\n          __tiptap__private__unknown__catch__all__node: {\n            content: 'inline*',\n            group: 'block',\n            parseDOM: [\n              {\n                tag: '*',\n                getAttrs: e => {\n                  // If this is ever called, we know that the content has something that we don't know how to handle in the schema\n                  hasInvalidContent = true\n                  // Try to stringify the element for a more helpful error message\n                  invalidContent = typeof e === 'string' ? e : e.outerHTML\n                  return null\n                },\n              },\n            ],\n          },\n        }),\n      })\n\n      if (options.slice) {\n        DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions)\n      } else {\n        DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions)\n      }\n\n      if (options.errorOnInvalidContent && hasInvalidContent) {\n        throw new Error('[tiptap error]: Invalid HTML content', { cause: new Error(`Invalid element found: ${invalidContent}`) })\n      }\n    }\n\n    const parser = DOMParser.fromSchema(schema)\n\n    if (options.slice) {\n      return parser.parseSlice(elementFromString(content), options.parseOptions).content\n    }\n\n    return parser.parse(elementFromString(content), options.parseOptions)\n\n  }\n\n  return createNodeFromContent('', schema, options)\n}\n", "import { Selection, Transaction } from '@tiptap/pm/state'\nimport { ReplaceAroundStep, ReplaceStep } from '@tiptap/pm/transform'\n\n// source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466\nexport function selectionToInsertionEnd(tr: Transaction, startLen: number, bias: number) {\n  const last = tr.steps.length - 1\n\n  if (last < startLen) {\n    return\n  }\n\n  const step = tr.steps[last]\n\n  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {\n    return\n  }\n\n  const map = tr.mapping.maps[last]\n  let end = 0\n\n  map.forEach((_from, _to, _newFrom, newTo) => {\n    if (end === 0) {\n      end = newTo\n    }\n  })\n\n  tr.setSelection(Selection.near(tr.doc.resolve(end), bias))\n}\n", "import { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport { createNodeFromContent } from '../helpers/createNodeFromContent.js'\nimport { selectionToInsertionEnd } from '../helpers/selectionToInsertionEnd.js'\nimport { Content, Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    insertContentAt: {\n      /**\n       * Insert a node or string of HTML at a specific position.\n       * @example editor.commands.insertContentAt(0, '<h1>Example</h1>')\n       */\n      insertContentAt: (\n        /**\n         * The position to insert the content at.\n         */\n        position: number | Range,\n\n        /**\n         * The ProseMirror content to insert.\n         */\n        value: Content | ProseMirrorNode | Fragment,\n\n        /**\n         * Optional options\n         */\n        options?: {\n          /**\n           * Options for parsing the content.\n           */\n          parseOptions?: ParseOptions\n\n          /**\n           * Whether to update the selection after inserting the content.\n           */\n          updateSelection?: boolean\n\n          /**\n           * Whether to apply input rules after inserting the content.\n           */\n          applyInputRules?: boolean\n\n          /**\n           * Whether to apply paste rules after inserting the content.\n           */\n          applyPasteRules?: boolean\n\n          /**\n           * Whether to throw an error if the content is invalid.\n           */\n          errorOnInvalidContent?: boolean\n        },\n      ) => ReturnType\n    }\n  }\n}\n\nconst isFragment = (nodeOrFragment: ProseMirrorNode | Fragment): nodeOrFragment is Fragment => {\n  return !('type' in nodeOrFragment)\n}\n\nexport const insertContentAt: RawCommands['insertContentAt'] = (position, value, options) => ({ tr, dispatch, editor }) => {\n  if (dispatch) {\n    options = {\n      parseOptions: editor.options.parseOptions,\n      updateSelection: true,\n      applyInputRules: false,\n      applyPasteRules: false,\n      ...options,\n    }\n\n    let content: Fragment | ProseMirrorNode\n\n    const emitContentError = (error: Error) => {\n      editor.emit('contentError', {\n        editor,\n        error,\n        disableCollaboration: () => {\n          if (editor.storage.collaboration) {\n            editor.storage.collaboration.isDisabled = true\n          }\n        },\n      })\n    }\n\n    const parseOptions: ParseOptions = {\n      preserveWhitespace: 'full',\n      ...options.parseOptions,\n    }\n\n    // If `emitContentError` is enabled, we want to check the content for errors\n    // but ignore them (do not remove the invalid content from the document)\n    if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {\n      try {\n        createNodeFromContent(value, editor.schema, {\n          parseOptions,\n          errorOnInvalidContent: true,\n        })\n      } catch (e) {\n        emitContentError(e as Error)\n      }\n    }\n\n    try {\n      content = createNodeFromContent(value, editor.schema, {\n        parseOptions,\n        errorOnInvalidContent: options.errorOnInvalidContent ?? editor.options.enableContentCheck,\n      })\n    } catch (e) {\n      emitContentError(e as Error)\n      return false\n    }\n\n    let { from, to } = typeof position === 'number' ? { from: position, to: position } : { from: position.from, to: position.to }\n\n    let isOnlyTextContent = true\n    let isOnlyBlockContent = true\n    const nodes = isFragment(content) ? content : [content]\n\n    nodes.forEach(node => {\n      // check if added node is valid\n      node.check()\n\n      isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false\n\n      isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false\n    })\n\n    // check if we can replace the wrapping node by\n    // the newly inserted content\n    // example:\n    // replace an empty paragraph by an inserted image\n    // instead of inserting the image below the paragraph\n    if (from === to && isOnlyBlockContent) {\n      const { parent } = tr.doc.resolve(from)\n      const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount\n\n      if (isEmptyTextBlock) {\n        from -= 1\n        to += 1\n      }\n    }\n\n    let newContent\n\n    // if there is only plain text we have to use `insertText`\n    // because this will keep the current marks\n    if (isOnlyTextContent) {\n      // if value is string, we can use it directly\n      // otherwise if it is an array, we have to join it\n      if (Array.isArray(value)) {\n        newContent = value.map(v => v.text || '').join('')\n      } else if (value instanceof Fragment) {\n        let text = ''\n\n        value.forEach(node => {\n          if (node.text) {\n            text += node.text\n          }\n        })\n\n        newContent = text\n      } else if (typeof value === 'object' && !!value && !!value.text) {\n        newContent = value.text\n      } else {\n        newContent = value as string\n      }\n\n      tr.insertText(newContent, from, to)\n    } else {\n      newContent = content\n\n      tr.replaceWith(from, to, newContent)\n    }\n\n    // set cursor at end of inserted content\n    if (options.updateSelection) {\n      selectionToInsertionEnd(tr, tr.steps.length - 1, -1)\n    }\n\n    if (options.applyInputRules) {\n      tr.setMeta('applyInputRules', { from, text: newContent })\n    }\n\n    if (options.applyPasteRules) {\n      tr.setMeta('applyPasteRules', { from, text: newContent })\n    }\n  }\n\n  return true\n}\n", "import {\n  joinBackward as originalJoinBackward,\n  joinDown as originalJoinDown,\n  joinForward as originalJoinForward,\n  joinUp as originalJoinUp,\n} from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinUp: {\n      /**\n       * Join the selected block or, if there is a text selection, the closest ancestor block of the selection that can be joined, with the sibling above it.\n       * @example editor.commands.joinUp()\n       */\n      joinUp: () => ReturnType\n    }\n    joinDown: {\n      /**\n       * Join the selected block, or the closest ancestor of the selection that can be joined, with the sibling after it.\n       * @example editor.commands.joinDown()\n       */\n      joinDown: () => ReturnType\n    }\n    joinBackward: {\n      /**\n       * If the selection is empty and at the start of a textblock, try to reduce the distance between that block and the one before it—if there's a block directly before it that can be joined, join them.\n       * If not, try to move the selected block closer to the next one in the document structure by lifting it out of its\n       * parent or moving it into a parent of the previous block. Will use the view for accurate (bidi-aware) start-of-textblock detection if given.\n       * @example editor.commands.joinBackward()\n       */\n      joinBackward: () => ReturnType\n    }\n    joinForward: {\n      /**\n       * If the selection is empty and the cursor is at the end of a textblock, try to reduce or remove the boundary between that block and the one after it,\n       * either by joining them or by moving the other block closer to this one in the tree structure.\n       * Will use the view for accurate start-of-textblock detection if given.\n       * @example editor.commands.joinForward()\n       */\n      joinForward: () => ReturnType\n    }\n  }\n}\n\nexport const joinUp: RawCommands['joinUp'] = () => ({ state, dispatch }) => {\n  return originalJoinUp(state, dispatch)\n}\n\nexport const joinDown: RawCommands['joinDown'] = () => ({ state, dispatch }) => {\n  return originalJoinDown(state, dispatch)\n}\n\nexport const joinBackward: RawCommands['joinBackward'] = () => ({ state, dispatch }) => {\n  return originalJoinBackward(state, dispatch)\n}\n\nexport const joinForward: RawCommands['joinForward'] = () => ({ state, dispatch }) => {\n  return originalJoinForward(state, dispatch)\n}\n", "import { joinPoint } from '@tiptap/pm/transform'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinItemBackward: {\n      /**\n       * Join two items backward.\n       * @example editor.commands.joinItemBackward()\n       */\n      joinItemBackward: () => ReturnType\n    }\n  }\n}\n\nexport const joinItemBackward: RawCommands['joinItemBackward'] = () => ({\n  state,\n  dispatch,\n  tr,\n}) => {\n  try {\n    const point = joinPoint(state.doc, state.selection.$from.pos, -1)\n\n    if (point === null || point === undefined) {\n      return false\n    }\n\n    tr.join(point, 2)\n\n    if (dispatch) {\n      dispatch(tr)\n    }\n\n    return true\n  } catch {\n    return false\n  }\n}\n", "import { joinPoint } from '@tiptap/pm/transform'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinItemForward: {\n      /**\n       * Join two items Forwards.\n       * @example editor.commands.joinItemForward()\n       */\n      joinItemForward: () => ReturnType\n    }\n  }\n}\n\nexport const joinItemForward: RawCommands['joinItemForward'] = () => ({\n  state,\n  dispatch,\n  tr,\n}) => {\n  try {\n    const point = joinPoint(state.doc, state.selection.$from.pos, +1)\n\n    if (point === null || point === undefined) {\n      return false\n    }\n\n    tr.join(point, 2)\n\n    if (dispatch) {\n      dispatch(tr)\n    }\n\n    return true\n  } catch {\n    return false\n  }\n}\n", "import { joinTextblockBackward as originalCommand } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinTextblockBackward: {\n      /**\n       * A more limited form of joinBackward that only tries to join the current textblock to the one before it, if the cursor is at the start of a textblock.\n       */\n      joinTextblockBackward: () => ReturnType\n    }\n  }\n}\n\nexport const joinTextblockBackward: RawCommands['joinTextblockBackward'] = () => ({ state, dispatch }) => {\n  return originalCommand(state, dispatch)\n}\n", "import { joinTextblockForward as originalCommand } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinTextblockForward: {\n      /**\n       * A more limited form of joinForward that only tries to join the current textblock to the one after it, if the cursor is at the end of a textblock.\n       */\n      joinTextblockForward: () => ReturnType\n    }\n  }\n}\n\nexport const joinTextblockForward: RawCommands['joinTextblockForward'] = () => ({ state, dispatch }) => {\n  return originalCommand(state, dispatch)\n}\n", "export function isMacOS(): boolean {\n  return typeof navigator !== 'undefined'\n    ? /Mac/.test(navigator.platform)\n    : false\n}\n", "import { RawCommands } from '../types.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nfunction normalizeKeyName(name: string) {\n  const parts = name.split(/-(?!$)/)\n  let result = parts[parts.length - 1]\n\n  if (result === 'Space') {\n    result = ' '\n  }\n\n  let alt\n  let ctrl\n  let shift\n  let meta\n\n  for (let i = 0; i < parts.length - 1; i += 1) {\n    const mod = parts[i]\n\n    if (/^(cmd|meta|m)$/i.test(mod)) {\n      meta = true\n    } else if (/^a(lt)?$/i.test(mod)) {\n      alt = true\n    } else if (/^(c|ctrl|control)$/i.test(mod)) {\n      ctrl = true\n    } else if (/^s(hift)?$/i.test(mod)) {\n      shift = true\n    } else if (/^mod$/i.test(mod)) {\n      if (isiOS() || isMacOS()) {\n        meta = true\n      } else {\n        ctrl = true\n      }\n    } else {\n      throw new Error(`Unrecognized modifier name: ${mod}`)\n    }\n  }\n\n  if (alt) {\n    result = `Alt-${result}`\n  }\n\n  if (ctrl) {\n    result = `Ctrl-${result}`\n  }\n\n  if (meta) {\n    result = `Meta-${result}`\n  }\n\n  if (shift) {\n    result = `Shift-${result}`\n  }\n\n  return result\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    keyboardShortcut: {\n      /**\n       * Trigger a keyboard shortcut.\n       * @param name The name of the keyboard shortcut.\n       * @example editor.commands.keyboardShortcut('Mod-b')\n       */\n      keyboardShortcut: (name: string) => ReturnType,\n    }\n  }\n}\n\nexport const keyboardShortcut: RawCommands['keyboardShortcut'] = name => ({\n  editor,\n  view,\n  tr,\n  dispatch,\n}) => {\n  const keys = normalizeKeyName(name).split(/-(?!$)/)\n  const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item))\n  const event = new KeyboardEvent('keydown', {\n    key: key === 'Space'\n      ? ' '\n      : key,\n    altKey: keys.includes('Alt'),\n    ctrlKey: keys.includes('Ctrl'),\n    metaKey: keys.includes('Meta'),\n    shiftKey: keys.includes('Shift'),\n    bubbles: true,\n    cancelable: true,\n  })\n\n  const capturedTransaction = editor.captureTransaction(() => {\n    view.someProp('handleKeyDown', f => f(view, event))\n  })\n\n  capturedTransaction?.steps.forEach(step => {\n    const newStep = step.map(tr.mapping)\n\n    if (newStep && dispatch) {\n      tr.maybeStep(newStep)\n    }\n  })\n\n  return true\n}\n", "import { NodeType } from '@tiptap/pm/model'\nimport { EditorState } from '@tiptap/pm/state'\n\nimport { NodeRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getNodeType } from './getNodeType.js'\n\nexport function isNodeActive(\n  state: EditorState,\n  typeOrName: NodeType | string | null,\n  attributes: Record<string, any> = {},\n): boolean {\n  const { from, to, empty } = state.selection\n  const type = typeOrName ? getNodeType(typeOrName, state.schema) : null\n\n  const nodeRanges: NodeRange[] = []\n\n  state.doc.nodesBetween(from, to, (node, pos) => {\n    if (node.isText) {\n      return\n    }\n\n    const relativeFrom = Math.max(from, pos)\n    const relativeTo = Math.min(to, pos + node.nodeSize)\n\n    nodeRanges.push({\n      node,\n      from: relativeFrom,\n      to: relativeTo,\n    })\n  })\n\n  const selectionRange = to - from\n  const matchedNodeRanges = nodeRanges\n    .filter(nodeRange => {\n      if (!type) {\n        return true\n      }\n\n      return type.name === nodeRange.node.type.name\n    })\n    .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }))\n\n  if (empty) {\n    return !!matchedNodeRanges.length\n  }\n\n  const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0)\n\n  return range >= selectionRange\n}\n", "import { lift as originalLift } from '@tiptap/pm/commands'\nimport { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    lift: {\n      /**\n       * Removes an existing wrap if possible lifting the node out of it\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.lift('paragraph')\n       * @example editor.commands.lift('heading', { level: 1 })\n       */\n      lift: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const lift: RawCommands['lift'] = (typeOrName, attributes = {}) => ({ state, dispatch }) => {\n  const type = getNodeType(typeOrName, state.schema)\n  const isActive = isNodeActive(state, type, attributes)\n\n  if (!isActive) {\n    return false\n  }\n\n  return originalLift(state, dispatch)\n}\n", "import { liftEmptyBlock as originalLiftEmptyBlock } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    liftEmptyBlock: {\n      /**\n       * If the cursor is in an empty textblock that can be lifted, lift the block.\n       * @example editor.commands.liftEmptyBlock()\n       */\n      liftEmptyBlock: () => ReturnType,\n    }\n  }\n}\n\nexport const liftEmptyBlock: RawCommands['liftEmptyBlock'] = () => ({ state, dispatch }) => {\n  return originalLiftEmptyBlock(state, dispatch)\n}\n", "import { NodeType } from '@tiptap/pm/model'\nimport { liftListItem as originalLiftListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    liftListItem: {\n      /**\n       * Create a command to lift the list item around the selection up into a wrapping list.\n       * @param typeOrName The type or name of the node.\n       * @example editor.commands.liftListItem('listItem')\n       */\n      liftListItem: (typeOrName: string | NodeType) => ReturnType\n    }\n  }\n}\n\nexport const liftListItem: RawCommands['liftListItem'] = typeOrName => ({ state, dispatch }) => {\n  const type = getNodeType(typeOrName, state.schema)\n\n  return originalLiftListItem(type)(state, dispatch)\n}\n", "import { newlineInCode as originalNewlineInCode } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    newlineInCode: {\n      /**\n       * Add a newline character in code.\n       * @example editor.commands.newlineInCode()\n       */\n      newlineInCode: () => ReturnType\n    }\n  }\n}\n\nexport const newlineInCode: RawCommands['newlineInCode'] = () => ({ state, dispatch }) => {\n  return originalNewlineInCode(state, dispatch)\n}\n", "import { Schema } from '@tiptap/pm/model'\n\n/**\n * Get the type of a schema item by its name.\n * @param name The name of the schema item\n * @param schema The Prosemiror schema to search in\n * @returns The type of the schema item (`node` or `mark`), or null if it doesn't exist\n */\nexport function getSchemaTypeNameByName(name: string, schema: Schema): 'node' | 'mark' | null {\n  if (schema.nodes[name]) {\n    return 'node'\n  }\n\n  if (schema.marks[name]) {\n    return 'mark'\n  }\n\n  return null\n}\n", "/**\n * Remove a property or an array of properties from an object\n * @param obj Object\n * @param key Key to remove\n */\nexport function deleteProps(obj: Record<string, any>, propOrProps: string | string[]): Record<string, any> {\n  const props = typeof propOrProps === 'string'\n    ? [propOrProps]\n    : propOrProps\n\n  return Object\n    .keys(obj)\n    .reduce((newObj: Record<string, any>, prop) => {\n      if (!props.includes(prop)) {\n        newObj[prop] = obj[prop]\n      }\n\n      return newObj\n    }, {})\n}\n", "import { MarkType, NodeType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport { RawCommands } from '../types.js'\nimport { deleteProps } from '../utilities/deleteProps.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    resetAttributes: {\n      /**\n       * Resets some node attributes to the default value.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node to reset.\n       * @example editor.commands.resetAttributes('heading', 'level')\n       */\n      resetAttributes: (\n        typeOrName: string | NodeType | MarkType,\n        attributes: string | string[],\n      ) => ReturnType\n    }\n  }\n}\n\nexport const resetAttributes: RawCommands['resetAttributes'] = (typeOrName, attributes) => ({ tr, state, dispatch }) => {\n  let nodeType: NodeType | null = null\n  let markType: MarkType | null = null\n\n  const schemaType = getSchemaTypeNameByName(\n    typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n    state.schema,\n  )\n\n  if (!schemaType) {\n    return false\n  }\n\n  if (schemaType === 'node') {\n    nodeType = getNodeType(typeOrName as NodeType, state.schema)\n  }\n\n  if (schemaType === 'mark') {\n    markType = getMarkType(typeOrName as MarkType, state.schema)\n  }\n\n  if (dispatch) {\n    tr.selection.ranges.forEach(range => {\n      state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {\n        if (nodeType && nodeType === node.type) {\n          tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes))\n        }\n\n        if (markType && node.marks.length) {\n          node.marks.forEach(mark => {\n            if (markType === mark.type) {\n              tr.addMark(\n                pos,\n                pos + node.nodeSize,\n                markType.create(deleteProps(mark.attrs, attributes)),\n              )\n            }\n          })\n        }\n      })\n    })\n  }\n\n  return true\n}\n", "import { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    scrollIntoView: {\n      /**\n       * Scroll the selection into view.\n       * @example editor.commands.scrollIntoView()\n       */\n      scrollIntoView: () => ReturnType,\n    }\n  }\n}\n\nexport const scrollIntoView: RawCommands['scrollIntoView'] = () => ({ tr, dispatch }) => {\n  if (dispatch) {\n    tr.scrollIntoView()\n  }\n\n  return true\n}\n", "import { AllSelection } from '@tiptap/pm/state'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectAll: {\n      /**\n       * Select the whole document.\n       * @example editor.commands.selectAll()\n       */\n      selectAll: () => ReturnType,\n    }\n  }\n}\n\nexport const selectAll: RawCommands['selectAll'] = () => ({ tr, dispatch }) => {\n  if (dispatch) {\n    const selection = new AllSelection(tr.doc)\n\n    tr.setSelection(selection)\n  }\n\n  return true\n}\n", "import { selectNodeBackward as originalSelectNodeBackward } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectNodeBackward: {\n      /**\n       * Select a node backward.\n       * @example editor.commands.selectNodeBackward()\n       */\n      selectNodeBackward: () => ReturnType\n    }\n  }\n}\n\nexport const selectNodeBackward: RawCommands['selectNodeBackward'] = () => ({ state, dispatch }) => {\n  return originalSelectNodeBackward(state, dispatch)\n}\n", "import { selectNodeForward as originalSelectNodeForward } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectNodeForward: {\n      /**\n       * Select a node forward.\n       * @example editor.commands.selectNodeForward()\n       */\n      selectNodeForward: () => ReturnType\n    }\n  }\n}\n\nexport const selectNodeForward: RawCommands['selectNodeForward'] = () => ({ state, dispatch }) => {\n  return originalSelectNodeForward(state, dispatch)\n}\n", "import { selectParentNode as originalSelectParentNode } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectParentNode: {\n      /**\n       * Select the parent node.\n       * @example editor.commands.selectParentNode()\n       */\n      selectParentNode: () => ReturnType\n    }\n  }\n}\n\nexport const selectParentNode: RawCommands['selectParentNode'] = () => ({ state, dispatch }) => {\n  return originalSelectParentNode(state, dispatch)\n}\n", "// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockEnd as originalSelectTextblockEnd } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectTextblockEnd: {\n      /**\n       * Moves the cursor to the end of current text block.\n       * @example editor.commands.selectTextblockEnd()\n       */\n      selectTextblockEnd: () => ReturnType\n    }\n  }\n}\n\nexport const selectTextblockEnd: RawCommands['selectTextblockEnd'] = () => ({ state, dispatch }) => {\n  return originalSelectTextblockEnd(state, dispatch)\n}\n", "// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockStart as originalSelectTextblockStart } from '@tiptap/pm/commands'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectTextblockStart: {\n      /**\n       * Moves the cursor to the start of current text block.\n       * @example editor.commands.selectTextblockStart()\n       */\n      selectTextblockStart: () => ReturnType\n    }\n  }\n}\n\nexport const selectTextblockStart: RawCommands['selectTextblockStart'] = () => ({ state, dispatch }) => {\n  return originalSelectTextblockStart(state, dispatch)\n}\n", "import {\n  Fragment, Node as ProseMirrorNode, ParseOptions, Schema,\n} from '@tiptap/pm/model'\n\nimport { Content } from '../types.js'\nimport { createNodeFromContent } from './createNodeFromContent.js'\n\n/**\n * Create a new Prosemirror document node from content.\n * @param content The JSON or HTML content to create the document from\n * @param schema The Prosemirror schema to use for the document\n * @param parseOptions Options for the parser\n * @returns The created Prosemirror document node\n */\nexport function createDocument(\n  content: Content | ProseMirrorNode | Fragment,\n  schema: Schema,\n  parseOptions: ParseOptions = {},\n  options: { errorOnInvalidContent?: boolean } = {},\n): ProseMirrorNode {\n  return createNodeFromContent(content, schema, {\n    slice: false,\n    parseOptions,\n    errorOnInvalidContent: options.errorOnInvalidContent,\n  }) as ProseMirrorNode\n}\n", "import { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport { createDocument } from '../helpers/createDocument.js'\nimport { Content, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setContent: {\n      /**\n       * Replace the whole document with new content.\n       * @param content The new content.\n       * @param emitUpdate Whether to emit an update event.\n       * @param parseOptions Options for parsing the content.\n       * @example editor.commands.setContent('<p>Example text</p>')\n       */\n      setContent: (\n        /**\n         * The new content.\n         */\n        content: Content | Fragment | ProseMirrorNode,\n\n        /**\n         * Whether to emit an update event.\n         * @default false\n         */\n        emitUpdate?: boolean,\n\n        /**\n         * Options for parsing the content.\n         * @default {}\n         */\n        parseOptions?: ParseOptions,\n        /**\n         * Options for `setContent`.\n         */\n        options?: {\n          /**\n           * Whether to throw an error if the content is invalid.\n           */\n          errorOnInvalidContent?: boolean;\n        }\n      ) => ReturnType;\n    };\n  }\n}\n\nexport const setContent: RawCommands['setContent'] = (content, emitUpdate = false, parseOptions = {}, options = {}) => ({\n  editor, tr, dispatch, commands,\n}) => {\n  const { doc } = tr\n\n  // This is to keep backward compatibility with the previous behavior\n  // TODO remove this in the next major version\n  if (parseOptions.preserveWhitespace !== 'full') {\n    const document = createDocument(content, editor.schema, parseOptions, {\n      errorOnInvalidContent: options.errorOnInvalidContent ?? editor.options.enableContentCheck,\n    })\n\n    if (dispatch) {\n      tr.replaceWith(0, doc.content.size, document).setMeta('preventUpdate', !emitUpdate)\n    }\n    return true\n  }\n\n  if (dispatch) {\n    tr.setMeta('preventUpdate', !emitUpdate)\n  }\n\n  return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {\n    parseOptions,\n    errorOnInvalidContent: options.errorOnInvalidContent ?? editor.options.enableContentCheck,\n  })\n}\n", "import { Mark, MarkType } from '@tiptap/pm/model'\nimport { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkType } from './getMarkType.js'\n\nexport function getMarkAttributes(\n  state: EditorState,\n  typeOrName: string | MarkType,\n): Record<string, any> {\n  const type = getMarkType(typeOrName, state.schema)\n  const { from, to, empty } = state.selection\n  const marks: Mark[] = []\n\n  if (empty) {\n    if (state.storedMarks) {\n      marks.push(...state.storedMarks)\n    }\n\n    marks.push(...state.selection.$head.marks())\n  } else {\n    state.doc.nodesBetween(from, to, node => {\n      marks.push(...node.marks)\n    })\n  }\n\n  const mark = marks.find(markItem => markItem.type.name === type.name)\n\n  if (!mark) {\n    return {}\n  }\n\n  return { ...mark.attrs }\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Transaction } from '@tiptap/pm/state'\nimport { Transform } from '@tiptap/pm/transform'\n\n/**\n * Returns a new `Transform` based on all steps of the passed transactions.\n * @param oldDoc The Prosemirror node to start from\n * @param transactions The transactions to combine\n * @returns A new `Transform` with all steps of the passed transactions\n */\nexport function combineTransactionSteps(\n  oldDoc: ProseMirrorNode,\n  transactions: Transaction[],\n): Transform {\n  const transform = new Transform(oldDoc)\n\n  transactions.forEach(transaction => {\n    transaction.steps.forEach(step => {\n      transform.step(step)\n    })\n  })\n\n  return transform\n}\n", "import { ContentMatch, NodeType } from '@tiptap/pm/model'\n\n/**\n * Gets the default block type at a given match\n * @param match The content match to get the default block type from\n * @returns The default block type or null\n */\nexport function defaultBlockAt(match: ContentMatch): NodeType | null {\n  for (let i = 0; i < match.edgeCount; i += 1) {\n    const { type } = match.edge(i)\n\n    if (type.isTextblock && !type.hasRequiredAttrs()) {\n      return type\n    }\n  }\n\n  return null\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { NodeWithPos, Predicate } from '../types.js'\n\n/**\n * Find children inside a Prosemirror node that match a predicate.\n * @param node The Prosemirror node to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildren(node: ProseMirrorNode, predicate: Predicate): NodeWithPos[] {\n  const nodesWithPos: NodeWithPos[] = []\n\n  node.descendants((child, pos) => {\n    if (predicate(child)) {\n      nodesWithPos.push({\n        node: child,\n        pos,\n      })\n    }\n  })\n\n  return nodesWithPos\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { NodeWithPos, Predicate, Range } from '../types.js'\n\n/**\n * Same as `findChildren` but searches only within a `range`.\n * @param node The Prosemirror node to search in\n * @param range The range to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildrenInRange(\n  node: ProseMirrorNode,\n  range: Range,\n  predicate: Predicate,\n): NodeWithPos[] {\n  const nodesWithPos: NodeWithPos[] = []\n\n  // if (range.from === range.to) {\n  //   const nodeAt = node.nodeAt(range.from)\n\n  //   if (nodeAt) {\n  //     nodesWithPos.push({\n  //       node: nodeAt,\n  //       pos: range.from,\n  //     })\n  //   }\n  // }\n\n  node.nodesBetween(range.from, range.to, (child, pos) => {\n    if (predicate(child)) {\n      nodesWithPos.push({\n        node: child,\n        pos,\n      })\n    }\n  })\n\n  return nodesWithPos\n}\n", "import { Node as ProseMirrorNode, ResolvedPos } from '@tiptap/pm/model'\n\nimport { Predicate } from '../types.js'\n\n/**\n * Finds the closest parent node to a resolved position that matches a predicate.\n * @param $pos The resolved position to search from\n * @param predicate The predicate to match\n * @returns The closest parent node to the resolved position that matches the predicate\n * @example ```js\n * findParentNodeClosestToPos($from, node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNodeClosestToPos(\n  $pos: ResolvedPos,\n  predicate: Predicate,\n):\n  | {\n      pos: number\n      start: number\n      depth: number\n      node: ProseMirrorNode\n    }\n  | undefined {\n  for (let i = $pos.depth; i > 0; i -= 1) {\n    const node = $pos.node(i)\n\n    if (predicate(node)) {\n      return {\n        pos: i > 0 ? $pos.before(i) : 0,\n        start: $pos.start(i),\n        depth: i,\n        node,\n      }\n    }\n  }\n}\n", "import { Selection } from '@tiptap/pm/state'\n\nimport { Predicate } from '../types.js'\nimport { findParentNodeClosestToPos } from './findParentNodeClosestToPos.js'\n\n/**\n * Finds the closest parent node to the current selection that matches a predicate.\n * @param predicate The predicate to match\n * @returns A command that finds the closest parent node to the current selection that matches the predicate\n * @example ```js\n * findParentNode(node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNode(predicate: Predicate) {\n  return (selection: Selection) => findParentNodeClosestToPos(selection.$from, predicate)\n}\n", "import { Schema } from '@tiptap/pm/model'\n\nimport { Editor } from '../Editor.js'\nimport { ExtensionManager } from '../ExtensionManager.js'\nimport { Extensions } from '../types.js'\nimport { getSchemaByResolvedExtensions } from './getSchemaByResolvedExtensions.js'\n\nexport function getSchema(extensions: Extensions, editor?: Editor): Schema {\n  const resolvedExtensions = ExtensionManager.resolve(extensions)\n\n  return getSchemaByResolvedExtensions(resolvedExtensions, editor)\n}\n", "import { Node } from '@tiptap/pm/model'\n\nimport { Extensions, JSONContent } from '../types.js'\nimport { getHTMLFromFragment } from './getHTMLFromFragment.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate HTML from a JSONContent\n * @param doc The JSONContent to generate HTML from\n * @param extensions The extensions to use for the schema\n * @returns The generated HTML\n */\nexport function generateHTML(doc: JSONContent, extensions: Extensions): string {\n  const schema = getSchema(extensions)\n  const contentNode = Node.fromJSON(schema, doc)\n\n  return getHTMLFromFragment(contentNode.content, schema)\n}\n", "import { DOMParser } from '@tiptap/pm/model'\n\nimport { Extensions } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate JSONContent from HTML\n * @param html The HTML to generate JSONContent from\n * @param extensions The extensions to use for the schema\n * @returns The generated JSONContent\n */\nexport function generateJSON(html: string, extensions: Extensions): Record<string, any> {\n  const schema = getSchema(extensions)\n  const dom = elementFromString(html)\n\n  return DOMParser.fromSchema(schema).parse(dom).toJSON()\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { TextSerializer } from '../types.js'\nimport { getTextBetween } from './getTextBetween.js'\n\n/**\n * Gets the text of a Prosemirror node\n * @param node The Prosemirror node\n * @param options Options for the text serializer & block separator\n * @returns The text of the node\n * @example ```js\n * const text = getText(node, { blockSeparator: '\\n' })\n * ```\n */\nexport function getText(\n  node: ProseMirrorNode,\n  options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  },\n) {\n  const range = {\n    from: 0,\n    to: node.content.size,\n  }\n\n  return getTextBetween(node, range, options)\n}\n", "import { Node } from '@tiptap/pm/model'\n\nimport { Extensions, JSONContent, TextSerializer } from '../types.js'\nimport { getSchema } from './getSchema.js'\nimport { getText } from './getText.js'\nimport { getTextSerializersFromSchema } from './getTextSerializersFromSchema.js'\n\n/**\n * Generate raw text from a JSONContent\n * @param doc The JSONContent to generate text from\n * @param extensions The extensions to use for the schema\n * @param options Options for the text generation f.e. blockSeparator or textSerializers\n * @returns The generated text\n */\nexport function generateText(\n  doc: JSONContent,\n  extensions: Extensions,\n  options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  },\n): string {\n  const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n  const schema = getSchema(extensions)\n  const contentNode = Node.fromJSON(schema, doc)\n\n  return getText(contentNode, {\n    blockSeparator,\n    textSerializers: {\n      ...getTextSerializersFromSchema(schema),\n      ...textSerializers,\n    },\n  })\n}\n", "import { Node, NodeType } from '@tiptap/pm/model'\nimport { EditorState } from '@tiptap/pm/state'\n\nimport { getNodeType } from './getNodeType.js'\n\nexport function getNodeAttributes(\n  state: EditorState,\n  typeOrName: string | NodeType,\n): Record<string, any> {\n  const type = getNodeType(typeOrName, state.schema)\n  const { from, to } = state.selection\n  const nodes: Node[] = []\n\n  state.doc.nodesBetween(from, to, node => {\n    nodes.push(node)\n  })\n\n  const node = nodes.reverse().find(nodeItem => nodeItem.type.name === type.name)\n\n  if (!node) {\n    return {}\n  }\n\n  return { ...node.attrs }\n}\n", "import { MarkType, NodeType } from '@tiptap/pm/model'\nimport { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from './getMarkAttributes.js'\nimport { getNodeAttributes } from './getNodeAttributes.js'\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\n\n/**\n * Get node or mark attributes by type or name on the current editor state\n * @param state The current editor state\n * @param typeOrName The node or mark type or name\n * @returns The attributes of the node or mark or an empty object\n */\nexport function getAttributes(\n  state: EditorState,\n  typeOrName: string | NodeType | MarkType,\n): Record<string, any> {\n  const schemaType = getSchemaTypeNameByName(\n    typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n    state.schema,\n  )\n\n  if (schemaType === 'node') {\n    return getNodeAttributes(state, typeOrName as NodeType)\n  }\n\n  if (schemaType === 'mark') {\n    return getMarkAttributes(state, typeOrName as MarkType)\n  }\n\n  return {}\n}\n", "/**\n * Removes duplicated values within an array.\n * Supports numbers, strings and objects.\n */\nexport function removeDuplicates<T>(array: T[], by = JSON.stringify): T[] {\n  const seen: Record<any, any> = {}\n\n  return array.filter(item => {\n    const key = by(item)\n\n    return Object.prototype.hasOwnProperty.call(seen, key)\n      ? false\n      : (seen[key] = true)\n  })\n}\n", "import { Step, Transform } from '@tiptap/pm/transform'\n\nimport { Range } from '../types.js'\nimport { removeDuplicates } from '../utilities/removeDuplicates.js'\n\nexport type ChangedRange = {\n  oldRange: Range,\n  newRange: Range,\n}\n\n/**\n * Removes duplicated ranges and ranges that are\n * fully captured by other ranges.\n */\nfunction simplifyChangedRanges(changes: ChangedRange[]): ChangedRange[] {\n  const uniqueChanges = removeDuplicates(changes)\n\n  return uniqueChanges.length === 1\n    ? uniqueChanges\n    : uniqueChanges.filter((change, index) => {\n      const rest = uniqueChanges.filter((_, i) => i !== index)\n\n      return !rest.some(otherChange => {\n        return change.oldRange.from >= otherChange.oldRange.from\n          && change.oldRange.to <= otherChange.oldRange.to\n          && change.newRange.from >= otherChange.newRange.from\n          && change.newRange.to <= otherChange.newRange.to\n      })\n    })\n}\n\n/**\n * Returns a list of changed ranges\n * based on the first and last state of all steps.\n */\nexport function getChangedRanges(transform: Transform): ChangedRange[] {\n  const { mapping, steps } = transform\n  const changes: ChangedRange[] = []\n\n  mapping.maps.forEach((stepMap, index) => {\n    const ranges: Range[] = []\n\n    // This accounts for step changes where no range was actually altered\n    // e.g. when setting a mark, node attribute, etc.\n    // @ts-ignore\n    if (!stepMap.ranges.length) {\n      const { from, to } = steps[index] as Step & {\n        from?: number,\n        to?: number,\n      }\n\n      if (from === undefined || to === undefined) {\n        return\n      }\n\n      ranges.push({ from, to })\n    } else {\n      stepMap.forEach((from, to) => {\n        ranges.push({ from, to })\n      })\n    }\n\n    ranges.forEach(({ from, to }) => {\n      const newStart = mapping.slice(index).map(from, -1)\n      const newEnd = mapping.slice(index).map(to)\n      const oldStart = mapping.invert().map(newStart, -1)\n      const oldEnd = mapping.invert().map(newEnd)\n\n      changes.push({\n        oldRange: {\n          from: oldStart,\n          to: oldEnd,\n        },\n        newRange: {\n          from: newStart,\n          to: newEnd,\n        },\n      })\n    })\n  })\n\n  return simplifyChangedRanges(changes)\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { JSONContent } from '../types.js'\n\ninterface DebugJSONContent extends JSONContent {\n  from: number\n  to: number\n}\n\nexport function getDebugJSON(node: ProseMirrorNode, startOffset = 0): DebugJSONContent {\n  const isTopNode = node.type === node.type.schema.topNodeType\n  const increment = isTopNode ? 0 : 1\n  const from = startOffset\n  const to = from + node.nodeSize\n  const marks = node.marks.map(mark => {\n    const output: { type: string; attrs?: Record<string, any> } = {\n      type: mark.type.name,\n    }\n\n    if (Object.keys(mark.attrs).length) {\n      output.attrs = { ...mark.attrs }\n    }\n\n    return output\n  })\n  const attrs = { ...node.attrs }\n  const output: DebugJSONContent = {\n    type: node.type.name,\n    from,\n    to,\n  }\n\n  if (Object.keys(attrs).length) {\n    output.attrs = attrs\n  }\n\n  if (marks.length) {\n    output.marks = marks\n  }\n\n  if (node.content.childCount) {\n    output.content = []\n\n    node.forEach((child, offset) => {\n      output.content?.push(getDebugJSON(child, startOffset + offset + increment))\n    })\n  }\n\n  if (node.text) {\n    output.text = node.text\n  }\n\n  return output\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { MarkRange } from '../types.js'\nimport { getMarkRange } from './getMarkRange.js'\n\nexport function getMarksBetween(from: number, to: number, doc: ProseMirrorNode): MarkRange[] {\n  const marks: MarkRange[] = []\n\n  // get all inclusive marks on empty selection\n  if (from === to) {\n    doc\n      .resolve(from)\n      .marks()\n      .forEach(mark => {\n        const $pos = doc.resolve(from)\n        const range = getMarkRange($pos, mark.type)\n\n        if (!range) {\n          return\n        }\n\n        marks.push({\n          mark,\n          ...range,\n        })\n      })\n  } else {\n    doc.nodesBetween(from, to, (node, pos) => {\n      if (!node || node?.nodeSize === undefined) {\n        return\n      }\n\n      marks.push(\n        ...node.marks.map(mark => ({\n          from: pos,\n          to: pos + node.nodeSize,\n          mark,\n        })),\n      )\n    })\n  }\n\n  return marks\n}\n", "import { Node, NodeType } from '@tiptap/pm/model'\nimport { EditorState } from '@tiptap/pm/state'\n\n/**\n * Finds the first node of a given type or name in the current selection.\n * @param state The editor state.\n * @param typeOrName The node type or name.\n * @param pos The position to start searching from.\n * @param maxDepth The maximum depth to search.\n * @returns The node and the depth as an array.\n */\nexport const getNodeAtPosition = (state: EditorState, typeOrName: string | NodeType, pos: number, maxDepth = 20) => {\n  const $pos = state.doc.resolve(pos)\n\n  let currentDepth = maxDepth\n  let node: Node | null = null\n\n  while (currentDepth > 0 && node === null) {\n    const currentNode = $pos.node(currentDepth)\n\n    if (currentNode?.type.name === typeOrName) {\n      node = currentNode\n    } else {\n      currentDepth -= 1\n    }\n  }\n\n  return [node, currentDepth] as [Node | null, number]\n}\n", "import { ExtensionAttribute } from '../types.js'\n\n/**\n * Return attributes of an extension that should be splitted by keepOnSplit flag\n * @param extensionAttributes Array of extension attributes\n * @param typeName The type of the extension\n * @param attributes The attributes of the extension\n * @returns The splitted attributes\n */\nexport function getSplittedAttributes(\n  extensionAttributes: ExtensionAttribute[],\n  typeName: string,\n  attributes: Record<string, any>,\n): Record<string, any> {\n  return Object.fromEntries(Object\n    .entries(attributes)\n    .filter(([name]) => {\n      const extensionAttribute = extensionAttributes.find(item => {\n        return item.type === typeName && item.name === name\n      })\n\n      if (!extensionAttribute) {\n        return false\n      }\n\n      return extensionAttribute.attribute.keepOnSplit\n    }))\n}\n", "import { MarkType } from '@tiptap/pm/model'\nimport { EditorState } from '@tiptap/pm/state'\n\nimport { MarkRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getMarkType } from './getMarkType.js'\n\nexport function isMarkActive(\n  state: EditorState,\n  typeOrName: MarkType | string | null,\n  attributes: Record<string, any> = {},\n): boolean {\n  const { empty, ranges } = state.selection\n  const type = typeOrName ? getMarkType(typeOrName, state.schema) : null\n\n  if (empty) {\n    return !!(state.storedMarks || state.selection.$from.marks())\n      .filter(mark => {\n        if (!type) {\n          return true\n        }\n\n        return type.name === mark.type.name\n      })\n      .find(mark => objectIncludes(mark.attrs, attributes, { strict: false }))\n  }\n\n  let selectionRange = 0\n  const markRanges: MarkRange[] = []\n\n  ranges.forEach(({ $from, $to }) => {\n    const from = $from.pos\n    const to = $to.pos\n\n    state.doc.nodesBetween(from, to, (node, pos) => {\n      if (!node.isText && !node.marks.length) {\n        return\n      }\n\n      const relativeFrom = Math.max(from, pos)\n      const relativeTo = Math.min(to, pos + node.nodeSize)\n      const range = relativeTo - relativeFrom\n\n      selectionRange += range\n\n      markRanges.push(\n        ...node.marks.map(mark => ({\n          mark,\n          from: relativeFrom,\n          to: relativeTo,\n        })),\n      )\n    })\n  })\n\n  if (selectionRange === 0) {\n    return false\n  }\n\n  // calculate range of matched mark\n  const matchedRange = markRanges\n    .filter(markRange => {\n      if (!type) {\n        return true\n      }\n\n      return type.name === markRange.mark.type.name\n    })\n    .filter(markRange => objectIncludes(markRange.mark.attrs, attributes, { strict: false }))\n    .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n  // calculate range of marks that excludes the searched mark\n  // for example `code` doesn’t allow any other marks\n  const excludedRange = markRanges\n    .filter(markRange => {\n      if (!type) {\n        return true\n      }\n\n      return markRange.mark.type !== type && markRange.mark.type.excludes(type)\n    })\n    .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n  // we only include the result of `excludedRange`\n  // if there is a match at all\n  const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange\n\n  return range >= selectionRange\n}\n", "import { EditorState } from '@tiptap/pm/state'\n\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\nimport { isMarkActive } from './isMarkActive.js'\nimport { isNodeActive } from './isNodeActive.js'\n\nexport function isActive(\n  state: EditorState,\n  name: string | null,\n  attributes: Record<string, any> = {},\n): boolean {\n  if (!name) {\n    return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes)\n  }\n\n  const schemaType = getSchemaTypeNameByName(name, state.schema)\n\n  if (schemaType === 'node') {\n    return isNodeActive(state, name, attributes)\n  }\n\n  if (schemaType === 'mark') {\n    return isMarkActive(state, name, attributes)\n  }\n\n  return false\n}\n", "import { EditorState } from '@tiptap/pm/state'\n\nimport { findParentNode } from './findParentNode.js'\n\nexport const isAtEndOfNode = (state: EditorState, nodeType?: string) => {\n  const { $from, $to, $anchor } = state.selection\n\n  if (nodeType) {\n    const parentNode = findParentNode(node => node.type.name === nodeType)(state.selection)\n\n    if (!parentNode) {\n      return false\n    }\n\n    const $parentPos = state.doc.resolve(parentNode.pos + 1)\n\n    if ($anchor.pos + 1 === $parentPos.end()) {\n      return true\n    }\n\n    return false\n  }\n\n  if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {\n    return false\n  }\n\n  return true\n}\n", "import { EditorState } from '@tiptap/pm/state'\n\nexport const isAtStartOfNode = (state: EditorState) => {\n  const { $from, $to } = state.selection\n\n  if ($from.parentOffset > 0 || $from.pos !== $to.pos) {\n    return false\n  }\n\n  return true\n}\n", "import { getExtensionField } from '../helpers/getExtensionField.js'\nimport { NodeConfig } from '../index.js'\nimport { Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nexport function isList(name: string, extensions: Extensions): boolean {\n  const { nodeExtensions } = splitExtensions(extensions)\n  const extension = nodeExtensions.find(item => item.name === name)\n\n  if (!extension) {\n    return false\n  }\n\n  const context = {\n    name: extension.name,\n    options: extension.options,\n    storage: extension.storage,\n  }\n  const group = callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context))\n\n  if (typeof group !== 'string') {\n    return false\n  }\n\n  return group.split(' ').includes('list')\n}\n", "import { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/**\n * Returns true if the given prosemirror node is empty.\n */\nexport function isNodeEmpty(\n  node: ProseMirrorNode,\n  {\n    checkChildren = true,\n    ignoreWhitespace = false,\n  }: {\n    /**\n     * When true (default), it will also check if all children are empty.\n     */\n    checkChildren?: boolean;\n    /**\n     * When true, it will ignore whitespace when checking for emptiness.\n     */\n    ignoreWhitespace?: boolean;\n  } = {},\n): boolean {\n  if (ignoreWhitespace) {\n    if (node.type.name === 'hardBreak') {\n      // Hard breaks are considered empty\n      return true\n    }\n    if (node.isText) {\n      return /^\\s*$/m.test(node.text ?? '')\n    }\n  }\n\n  if (node.isText) {\n    return !node.text\n  }\n\n  if (node.isAtom || node.isLeaf) {\n    return false\n  }\n\n  if (node.content.childCount === 0) {\n    return true\n  }\n\n  if (checkChildren) {\n    let isContentEmpty = true\n\n    node.content.forEach(childNode => {\n      if (isContentEmpty === false) {\n        // Exit early for perf\n        return\n      }\n\n      if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {\n        isContentEmpty = false\n      }\n    })\n\n    return isContentEmpty\n  }\n\n  return false\n}\n", "import { NodeSelection } from '@tiptap/pm/state'\n\nexport function isNodeSelection(value: unknown): value is NodeSelection {\n  return value instanceof NodeSelection\n}\n", "import { EditorView } from '@tiptap/pm/view'\n\nimport { minMax } from '../utilities/minMax.js'\n\nexport function posToDOMRect(view: EditorView, from: number, to: number): DOMRect {\n  const minPos = 0\n  const maxPos = view.state.doc.content.size\n  const resolvedFrom = minMax(from, minPos, maxPos)\n  const resolvedEnd = minMax(to, minPos, maxPos)\n  const start = view.coordsAtPos(resolvedFrom)\n  const end = view.coordsAtPos(resolvedEnd, -1)\n  const top = Math.min(start.top, end.top)\n  const bottom = Math.max(start.bottom, end.bottom)\n  const left = Math.min(start.left, end.left)\n  const right = Math.max(start.right, end.right)\n  const width = right - left\n  const height = bottom - top\n  const x = left\n  const y = top\n  const data = {\n    top,\n    bottom,\n    left,\n    right,\n    width,\n    height,\n    x,\n    y,\n  }\n\n  return {\n    ...data,\n    toJSON: () => data,\n  }\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ntype RewriteUnknownContentOptions = {\n  /**\n   * If true, unknown nodes will be treated as paragraphs\n   * @default true\n   */\n  fallbackToParagraph?: boolean;\n};\n\ntype RewrittenContent = {\n  /**\n   * The original JSON content that was rewritten\n   */\n  original: JSONContent;\n  /**\n   * The name of the node or mark that was unsupported\n   */\n  unsupported: string;\n}[];\n\n/**\n * The actual implementation of the rewriteUnknownContent function\n */\nfunction rewriteUnknownContentInner({\n  json,\n  validMarks,\n  validNodes,\n  options,\n  rewrittenContent = [],\n}: {\n  json: JSONContent;\n  validMarks: Set<string>;\n  validNodes: Set<string>;\n  options?: RewriteUnknownContentOptions;\n  rewrittenContent?: RewrittenContent;\n}): {\n  /**\n   * The cleaned JSON content\n   */\n  json: JSONContent | null;\n  /**\n   * The array of nodes and marks that were rewritten\n   */\n  rewrittenContent: RewrittenContent;\n} {\n  if (json.marks && Array.isArray(json.marks)) {\n    json.marks = json.marks.filter(mark => {\n      const name = typeof mark === 'string' ? mark : mark.type\n\n      if (validMarks.has(name)) {\n        return true\n      }\n\n      rewrittenContent.push({\n        original: JSON.parse(JSON.stringify(mark)),\n        unsupported: name,\n      })\n      // Just ignore any unknown marks\n      return false\n    })\n  }\n\n  if (json.content && Array.isArray(json.content)) {\n    json.content = json.content\n      .map(\n        value => rewriteUnknownContentInner({\n          json: value,\n          validMarks,\n          validNodes,\n          options,\n          rewrittenContent,\n        }).json,\n      )\n      .filter(a => a !== null && a !== undefined)\n  }\n\n  if (json.type && !validNodes.has(json.type)) {\n    rewrittenContent.push({\n      original: JSON.parse(JSON.stringify(json)),\n      unsupported: json.type,\n    })\n\n    if (json.content && Array.isArray(json.content) && (options?.fallbackToParagraph !== false)) {\n      // Just treat it like a paragraph and hope for the best\n      json.type = 'paragraph'\n\n      return {\n        json,\n        rewrittenContent,\n      }\n    }\n\n    // or just omit it entirely\n    return {\n      json: null,\n      rewrittenContent,\n    }\n  }\n\n  return { json, rewrittenContent }\n}\n\n/**\n * Rewrite unknown nodes and marks within JSON content\n * Allowing for user within the editor\n */\nexport function rewriteUnknownContent(\n  /**\n   * The JSON content to clean of unknown nodes and marks\n   */\n  json: JSONContent,\n  /**\n   * The schema to use for validation\n   */\n  schema: Schema,\n  /**\n   * Options for the cleaning process\n   */\n  options?: RewriteUnknownContentOptions,\n): {\n  /**\n   * The cleaned JSON content\n   */\n  json: JSONContent | null;\n  /**\n   * The array of nodes and marks that were rewritten\n   */\n  rewrittenContent: {\n    /**\n     * The original JSON content that was rewritten\n     */\n    original: JSONContent;\n    /**\n     * The name of the node or mark that was unsupported\n     */\n    unsupported: string;\n  }[];\n} {\n  return rewriteUnknownContentInner({\n    json,\n    validNodes: new Set(Object.keys(schema.nodes)),\n    validMarks: new Set(Object.keys(schema.marks)),\n    options,\n  })\n}\n", "import { MarkType, ResolvedPos } from '@tiptap/pm/model'\nimport { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from '../helpers/getMarkAttributes.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isTextSelection } from '../helpers/index.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setMark: {\n      /**\n       * Add a mark with new attributes.\n       * @param typeOrName The mark type or name.\n       * @example editor.commands.setMark('bold', { level: 1 })\n       */\n      setMark: (typeOrName: string | MarkType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nfunction canSetMark(state: EditorState, tr: Transaction, newMarkType: MarkType) {\n  const { selection } = tr\n  let cursor: ResolvedPos | null = null\n\n  if (isTextSelection(selection)) {\n    cursor = selection.$cursor\n  }\n\n  if (cursor) {\n    const currentMarks = state.storedMarks ?? cursor.marks()\n\n    // There can be no current marks that exclude the new mark\n    return (\n      !!newMarkType.isInSet(currentMarks)\n      || !currentMarks.some(mark => mark.type.excludes(newMarkType))\n    )\n  }\n\n  const { ranges } = selection\n\n  return ranges.some(({ $from, $to }) => {\n    let someNodeSupportsMark = $from.depth === 0\n      ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType)\n      : false\n\n    state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {\n      // If we already found a mark that we can enable, return false to bypass the remaining search\n      if (someNodeSupportsMark) {\n        return false\n      }\n\n      if (node.isInline) {\n        const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType)\n        const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks)\n          || !node.marks.some(otherMark => otherMark.type.excludes(newMarkType))\n\n        someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType\n      }\n      return !someNodeSupportsMark\n    })\n\n    return someNodeSupportsMark\n  })\n}\nexport const setMark: RawCommands['setMark'] = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {\n  const { selection } = tr\n  const { empty, ranges } = selection\n  const type = getMarkType(typeOrName, state.schema)\n\n  if (dispatch) {\n    if (empty) {\n      const oldAttributes = getMarkAttributes(state, type)\n\n      tr.addStoredMark(\n        type.create({\n          ...oldAttributes,\n          ...attributes,\n        }),\n      )\n    } else {\n      ranges.forEach(range => {\n        const from = range.$from.pos\n        const to = range.$to.pos\n\n        state.doc.nodesBetween(from, to, (node, pos) => {\n          const trimmedFrom = Math.max(pos, from)\n          const trimmedTo = Math.min(pos + node.nodeSize, to)\n          const someHasMark = node.marks.find(mark => mark.type === type)\n\n          // if there is already a mark of this type\n          // we know that we have to merge its attributes\n          // otherwise we add a fresh new mark\n          if (someHasMark) {\n            node.marks.forEach(mark => {\n              if (type === mark.type) {\n                tr.addMark(\n                  trimmedFrom,\n                  trimmedTo,\n                  type.create({\n                    ...mark.attrs,\n                    ...attributes,\n                  }),\n                )\n              }\n            })\n          } else {\n            tr.addMark(trimmedFrom, trimmedTo, type.create(attributes))\n          }\n        })\n      })\n    }\n  }\n\n  return canSetMark(state, tr, type)\n}\n", "import type { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setMeta: {\n      /**\n       * Store a metadata property in the current transaction.\n       * @param key The key of the metadata property.\n       * @param value The value to store.\n       * @example editor.commands.setMeta('foo', 'bar')\n       */\n      setMeta: (key: string | Plugin | PluginKey, value: any) => ReturnType,\n    }\n  }\n}\n\nexport const setMeta: RawCommands['setMeta'] = (key, value) => ({ tr }) => {\n  tr.setMeta(key, value)\n\n  return true\n}\n", "import { setBlockType } from '@tiptap/pm/commands'\nimport { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setNode: {\n      /**\n       * Replace a given range with a node.\n       * @param typeOrName The type or name of the node\n       * @param attributes The attributes of the node\n       * @example editor.commands.setNode('paragraph')\n       */\n      setNode: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {\n  const type = getNodeType(typeOrName, state.schema)\n\n  let attributesToCopy: Record<string, any> | undefined\n\n  if (state.selection.$anchor.sameParent(state.selection.$head)) {\n    // only copy attributes if the selection is pointing to a node of the same type\n    attributesToCopy = state.selection.$anchor.parent.attrs\n  }\n\n  // TODO: use a fallback like insertContent?\n  if (!type.isTextblock) {\n    console.warn('[tiptap warn]: Currently \"setNode()\" only supports text block nodes.')\n\n    return false\n  }\n\n  return (\n    chain()\n    // try to convert node to default node if needed\n      .command(({ commands }) => {\n        const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state)\n\n        if (canSetBlock) {\n          return true\n        }\n\n        return commands.clearNodes()\n      })\n      .command(({ state: updatedState }) => {\n        return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch)\n      })\n      .run()\n  )\n}\n", "import { NodeSelection } from '@tiptap/pm/state'\n\nimport { RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setNodeSelection: {\n      /**\n       * Creates a NodeSelection.\n       * @param position - Position of the node.\n       * @example editor.commands.setNodeSelection(10)\n       */\n      setNodeSelection: (position: number) => ReturnType\n    }\n  }\n}\n\nexport const setNodeSelection: RawCommands['setNodeSelection'] = position => ({ tr, dispatch }) => {\n  if (dispatch) {\n    const { doc } = tr\n    const from = minMax(position, 0, doc.content.size)\n    const selection = NodeSelection.create(doc, from)\n\n    tr.setSelection(selection)\n  }\n\n  return true\n}\n", "import { TextSelection } from '@tiptap/pm/state'\n\nimport { Range, RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setTextSelection: {\n      /**\n       * Creates a TextSelection.\n       * @param position The position of the selection.\n       * @example editor.commands.setTextSelection(10)\n       */\n      setTextSelection: (position: number | Range) => ReturnType\n    }\n  }\n}\n\nexport const setTextSelection: RawCommands['setTextSelection'] = position => ({ tr, dispatch }) => {\n  if (dispatch) {\n    const { doc } = tr\n    const { from, to } = typeof position === 'number' ? { from: position, to: position } : position\n    const minPos = TextSelection.atStart(doc).from\n    const maxPos = TextSelection.atEnd(doc).to\n    const resolvedFrom = minMax(from, minPos, maxPos)\n    const resolvedEnd = minMax(to, minPos, maxPos)\n    const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd)\n\n    tr.setSelection(selection)\n  }\n\n  return true\n}\n", "import { NodeType } from '@tiptap/pm/model'\nimport { sinkListItem as originalSinkListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    sinkListItem: {\n      /**\n       * Sink the list item down into an inner list.\n       * @param typeOrName The type or name of the node.\n       * @example editor.commands.sinkListItem('listItem')\n       */\n      sinkListItem: (typeOrName: string | NodeType) => ReturnType\n    }\n  }\n}\n\nexport const sinkListItem: RawCommands['sinkListItem'] = typeOrName => ({ state, dispatch }) => {\n  const type = getNodeType(typeOrName, state.schema)\n\n  return originalSinkListItem(type)(state, dispatch)\n}\n", "import { EditorState, NodeSelection, TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { defaultBlockAt } from '../helpers/defaultBlockAt.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport { RawCommands } from '../types.js'\n\nfunction ensureMarks(state: EditorState, splittableMarks?: string[]) {\n  const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks())\n\n  if (marks) {\n    const filteredMarks = marks.filter(mark => splittableMarks?.includes(mark.type.name))\n\n    state.tr.ensureMarks(filteredMarks)\n  }\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    splitBlock: {\n      /**\n       * Forks a new node from an existing node.\n       * @param options.keepMarks Keep marks from the previous node.\n       * @example editor.commands.splitBlock()\n       * @example editor.commands.splitBlock({ keepMarks: true })\n       */\n      splitBlock: (options?: { keepMarks?: boolean }) => ReturnType\n    }\n  }\n}\n\nexport const splitBlock: RawCommands['splitBlock'] = ({ keepMarks = true } = {}) => ({\n  tr, state, dispatch, editor,\n}) => {\n  const { selection, doc } = tr\n  const { $from, $to } = selection\n  const extensionAttributes = editor.extensionManager.attributes\n  const newAttributes = getSplittedAttributes(\n    extensionAttributes,\n    $from.node().type.name,\n    $from.node().attrs,\n  )\n\n  if (selection instanceof NodeSelection && selection.node.isBlock) {\n    if (!$from.parentOffset || !canSplit(doc, $from.pos)) {\n      return false\n    }\n\n    if (dispatch) {\n      if (keepMarks) {\n        ensureMarks(state, editor.extensionManager.splittableMarks)\n      }\n\n      tr.split($from.pos).scrollIntoView()\n    }\n\n    return true\n  }\n\n  if (!$from.parent.isBlock) {\n    return false\n  }\n\n  const atEnd = $to.parentOffset === $to.parent.content.size\n\n  const deflt = $from.depth === 0\n    ? undefined\n    : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)))\n\n  let types = atEnd && deflt\n    ? [\n      {\n        type: deflt,\n        attrs: newAttributes,\n      },\n    ]\n    : undefined\n\n  let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types)\n\n  if (\n    !types\n      && !can\n      && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)\n  ) {\n    can = true\n    types = deflt\n      ? [\n        {\n          type: deflt,\n          attrs: newAttributes,\n        },\n      ]\n      : undefined\n  }\n\n  if (dispatch) {\n    if (can) {\n      if (selection instanceof TextSelection) {\n        tr.deleteSelection()\n      }\n\n      tr.split(tr.mapping.map($from.pos), 1, types)\n\n      if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {\n        const first = tr.mapping.map($from.before())\n        const $first = tr.doc.resolve(first)\n\n        if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {\n          tr.setNodeMarkup(tr.mapping.map($from.before()), deflt)\n        }\n      }\n    }\n\n    if (keepMarks) {\n      ensureMarks(state, editor.extensionManager.splittableMarks)\n    }\n\n    tr.scrollIntoView()\n  }\n\n  return can\n}\n", "import {\n  Fragment, Node as ProseMirrorNode, NodeType, Slice,\n} from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    splitListItem: {\n      /**\n       * Splits one list item into two list items.\n       * @param typeOrName The type or name of the node.\n       * @param overrideAttrs The attributes to ensure on the new node.\n       * @example editor.commands.splitListItem('listItem')\n       */\n      splitListItem: (typeOrName: string | NodeType, overrideAttrs?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const splitListItem: RawCommands['splitListItem'] = (typeOrName, overrideAttrs = {}) => ({\n  tr, state, dispatch, editor,\n}) => {\n  const type = getNodeType(typeOrName, state.schema)\n  const { $from, $to } = state.selection\n\n  // @ts-ignore\n  // eslint-disable-next-line\n    const node: ProseMirrorNode = state.selection.node\n\n  if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {\n    return false\n  }\n\n  const grandParent = $from.node(-1)\n\n  if (grandParent.type !== type) {\n    return false\n  }\n\n  const extensionAttributes = editor.extensionManager.attributes\n\n  if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {\n    // In an empty block. If this is a nested list, the wrapping\n    // list item should be split. Otherwise, bail out and let next\n    // command handle lifting.\n    if (\n      $from.depth === 2\n        || $from.node(-3).type !== type\n        || $from.index(-2) !== $from.node(-2).childCount - 1\n    ) {\n      return false\n    }\n\n    if (dispatch) {\n      let wrap = Fragment.empty\n      // eslint-disable-next-line\n        const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3\n\n      // Build a fragment containing empty versions of the structure\n      // from the outer list item to the parent node of the cursor\n      for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {\n        wrap = Fragment.from($from.node(d).copy(wrap))\n      }\n\n      // eslint-disable-next-line\n        const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3\n\n      // Add a second list item with an empty default start node\n      const newNextTypeAttributes = {\n        ...getSplittedAttributes(\n          extensionAttributes,\n          $from.node().type.name,\n          $from.node().attrs,\n        ),\n        ...overrideAttrs,\n      }\n      const nextType = type.contentMatch.defaultType?.createAndFill(newNextTypeAttributes) || undefined\n\n      wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType) || undefined))\n\n      const start = $from.before($from.depth - (depthBefore - 1))\n\n      tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0))\n\n      let sel = -1\n\n      tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {\n        if (sel > -1) {\n          return false\n        }\n\n        if (n.isTextblock && n.content.size === 0) {\n          sel = pos + 1\n        }\n      })\n\n      if (sel > -1) {\n        tr.setSelection(TextSelection.near(tr.doc.resolve(sel)))\n      }\n\n      tr.scrollIntoView()\n    }\n\n    return true\n  }\n\n  const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null\n\n  const newTypeAttributes = {\n    ...getSplittedAttributes(\n      extensionAttributes,\n      grandParent.type.name,\n      grandParent.attrs,\n    ),\n    ...overrideAttrs,\n  }\n  const newNextTypeAttributes = {\n    ...getSplittedAttributes(\n      extensionAttributes,\n      $from.node().type.name,\n      $from.node().attrs,\n    ),\n    ...overrideAttrs,\n  }\n\n  tr.delete($from.pos, $to.pos)\n\n  const types = nextType\n    ? [\n      { type, attrs: newTypeAttributes },\n      { type: nextType, attrs: newNextTypeAttributes },\n    ]\n    : [{ type, attrs: newTypeAttributes }]\n\n  if (!canSplit(tr.doc, $from.pos, 2)) {\n    return false\n  }\n\n  if (dispatch) {\n    const { selection, storedMarks } = state\n    const { splittableMarks } = editor.extensionManager\n    const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n    tr.split($from.pos, 2, types).scrollIntoView()\n\n    if (!marks || !dispatch) {\n      return true\n    }\n\n    const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n    tr.ensureMarks(filteredMarks)\n  }\n\n  return true\n}\n", "import { NodeType } from '@tiptap/pm/model'\nimport { Transaction } from '@tiptap/pm/state'\nimport { canJoin } from '@tiptap/pm/transform'\n\nimport { findParentNode } from '../helpers/findParentNode.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isList } from '../helpers/isList.js'\nimport { RawCommands } from '../types.js'\n\nconst joinListBackwards = (tr: Transaction, listType: NodeType): boolean => {\n  const list = findParentNode(node => node.type === listType)(tr.selection)\n\n  if (!list) {\n    return true\n  }\n\n  const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth)\n\n  if (before === undefined) {\n    return true\n  }\n\n  const nodeBefore = tr.doc.nodeAt(before)\n  const canJoinBackwards = list.node.type === nodeBefore?.type && canJoin(tr.doc, list.pos)\n\n  if (!canJoinBackwards) {\n    return true\n  }\n\n  tr.join(list.pos)\n\n  return true\n}\n\nconst joinListForwards = (tr: Transaction, listType: NodeType): boolean => {\n  const list = findParentNode(node => node.type === listType)(tr.selection)\n\n  if (!list) {\n    return true\n  }\n\n  const after = tr.doc.resolve(list.start).after(list.depth)\n\n  if (after === undefined) {\n    return true\n  }\n\n  const nodeAfter = tr.doc.nodeAt(after)\n  const canJoinForwards = list.node.type === nodeAfter?.type && canJoin(tr.doc, after)\n\n  if (!canJoinForwards) {\n    return true\n  }\n\n  tr.join(after)\n\n  return true\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleList: {\n      /**\n       * Toggle between different list types.\n       * @param listTypeOrName The type or name of the list.\n       * @param itemTypeOrName The type or name of the list item.\n       * @param keepMarks Keep marks when toggling.\n       * @param attributes Attributes for the new list.\n       * @example editor.commands.toggleList('bulletList', 'listItem')\n       */\n      toggleList: (listTypeOrName: string | NodeType, itemTypeOrName: string | NodeType, keepMarks?: boolean, attributes?: Record<string, any>) => ReturnType;\n    }\n  }\n}\n\nexport const toggleList: RawCommands['toggleList'] = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({\n  editor, tr, state, dispatch, chain, commands, can,\n}) => {\n  const { extensions, splittableMarks } = editor.extensionManager\n  const listType = getNodeType(listTypeOrName, state.schema)\n  const itemType = getNodeType(itemTypeOrName, state.schema)\n  const { selection, storedMarks } = state\n  const { $from, $to } = selection\n  const range = $from.blockRange($to)\n\n  const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n  if (!range) {\n    return false\n  }\n\n  const parentList = findParentNode(node => isList(node.type.name, extensions))(selection)\n\n  if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {\n    // remove list\n    if (parentList.node.type === listType) {\n      return commands.liftListItem(itemType)\n    }\n\n    // change list type\n    if (\n      isList(parentList.node.type.name, extensions)\n        && listType.validContent(parentList.node.content)\n        && dispatch\n    ) {\n      return chain()\n        .command(() => {\n          tr.setNodeMarkup(parentList.pos, listType)\n\n          return true\n        })\n        .command(() => joinListBackwards(tr, listType))\n        .command(() => joinListForwards(tr, listType))\n        .run()\n    }\n  }\n  if (!keepMarks || !marks || !dispatch) {\n\n    return chain()\n      // try to convert node to default node if needed\n      .command(() => {\n        const canWrapInList = can().wrapInList(listType, attributes)\n\n        if (canWrapInList) {\n          return true\n        }\n\n        return commands.clearNodes()\n      })\n      .wrapInList(listType, attributes)\n      .command(() => joinListBackwards(tr, listType))\n      .command(() => joinListForwards(tr, listType))\n      .run()\n  }\n\n  return (\n    chain()\n    // try to convert node to default node if needed\n      .command(() => {\n        const canWrapInList = can().wrapInList(listType, attributes)\n\n        const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n        tr.ensureMarks(filteredMarks)\n\n        if (canWrapInList) {\n          return true\n        }\n\n        return commands.clearNodes()\n      })\n      .wrapInList(listType, attributes)\n      .command(() => joinListBackwards(tr, listType))\n      .command(() => joinListForwards(tr, listType))\n      .run()\n  )\n}\n", "import { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isMarkActive } from '../helpers/isMarkActive.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleMark: {\n      /**\n       * Toggle a mark on and off.\n       * @param typeOrName The mark type or name.\n       * @param attributes The attributes of the mark.\n       * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n       * @example editor.commands.toggleMark('bold')\n       */\n      toggleMark: (\n        /**\n         * The mark type or name.\n         */\n        typeOrName: string | MarkType,\n\n        /**\n         * The attributes of the mark.\n         */\n        attributes?: Record<string, any>,\n\n        options?: {\n          /**\n           * Removes the mark even across the current selection. Defaults to `false`.\n           */\n          extendEmptyMarkRange?: boolean\n        },\n      ) => ReturnType\n    }\n  }\n}\n\nexport const toggleMark: RawCommands['toggleMark'] = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => {\n  const { extendEmptyMarkRange = false } = options\n  const type = getMarkType(typeOrName, state.schema)\n  const isActive = isMarkActive(state, type, attributes)\n\n  if (isActive) {\n    return commands.unsetMark(type, { extendEmptyMarkRange })\n  }\n\n  return commands.setMark(type, attributes)\n}\n", "import { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleNode: {\n      /**\n       * Toggle a node with another node.\n       * @param typeOrName The type or name of the node.\n       * @param toggleTypeOrName The type or name of the node to toggle.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.toggleNode('heading', 'paragraph')\n       */\n      toggleNode: (\n        typeOrName: string | NodeType,\n        toggleTypeOrName: string | NodeType,\n        attributes?: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const toggleNode: RawCommands['toggleNode'] = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {\n  const type = getNodeType(typeOrName, state.schema)\n  const toggleType = getNodeType(toggleTypeOrName, state.schema)\n  const isActive = isNodeActive(state, type, attributes)\n\n  let attributesToCopy: Record<string, any> | undefined\n\n  if (state.selection.$anchor.sameParent(state.selection.$head)) {\n    // only copy attributes if the selection is pointing to a node of the same type\n    attributesToCopy = state.selection.$anchor.parent.attrs\n  }\n\n  if (isActive) {\n    return commands.setNode(toggleType, attributesToCopy)\n  }\n\n  // If the node is not active, we want to set the new node type with the given attributes\n  // Copying over the attributes from the current node if the selection is pointing to a node of the same type\n  return commands.setNode(type, { ...attributesToCopy, ...attributes })\n}\n", "import { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleWrap: {\n      /**\n       * Wraps nodes in another node, or removes an existing wrap.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.toggleWrap('blockquote')\n       */\n      toggleWrap: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const toggleWrap: RawCommands['toggleWrap'] = (typeOrName, attributes = {}) => ({ state, commands }) => {\n  const type = getNodeType(typeOrName, state.schema)\n  const isActive = isNodeActive(state, type, attributes)\n\n  if (isActive) {\n    return commands.lift(type)\n  }\n\n  return commands.wrapIn(type, attributes)\n}\n", "import { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    undoInputRule: {\n      /**\n       * Undo an input rule.\n       * @example editor.commands.undoInputRule()\n       */\n      undoInputRule: () => ReturnType,\n    }\n  }\n}\n\nexport const undoInputRule: RawCommands['undoInputRule'] = () => ({ state, dispatch }) => {\n  const plugins = state.plugins\n\n  for (let i = 0; i < plugins.length; i += 1) {\n    const plugin = plugins[i]\n    let undoable\n\n    // @ts-ignore\n    // eslint-disable-next-line\n    if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {\n      if (dispatch) {\n        const tr = state.tr\n        const toUndo = undoable.transform\n\n        for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {\n          tr.step(toUndo.steps[j].invert(toUndo.docs[j]))\n        }\n\n        if (undoable.text) {\n          const marks = tr.doc.resolve(undoable.from).marks()\n\n          tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))\n        } else {\n          tr.delete(undoable.from, undoable.to)\n        }\n      }\n\n      return true\n    }\n  }\n\n  return false\n}\n", "import { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    unsetAllMarks: {\n      /**\n       * Remove all marks in the current selection.\n       * @example editor.commands.unsetAllMarks()\n       */\n      unsetAllMarks: () => ReturnType,\n    }\n  }\n}\n\nexport const unsetAllMarks: RawCommands['unsetAllMarks'] = () => ({ tr, dispatch }) => {\n  const { selection } = tr\n  const { empty, ranges } = selection\n\n  if (empty) {\n    return true\n  }\n\n  if (dispatch) {\n    ranges.forEach(range => {\n      tr.removeMark(range.$from.pos, range.$to.pos)\n    })\n  }\n\n  return true\n}\n", "import { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    unsetMark: {\n      /**\n       * Remove all marks in the current selection.\n       * @param typeOrName The mark type or name.\n       * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n       * @example editor.commands.unsetMark('bold')\n       */\n      unsetMark: (\n        /**\n         * The mark type or name.\n         */\n        typeOrName: string | MarkType,\n\n        options?: {\n          /**\n           * Removes the mark even across the current selection. Defaults to `false`.\n           */\n          extendEmptyMarkRange?: boolean\n        },\n      ) => ReturnType\n    }\n  }\n}\n\nexport const unsetMark: RawCommands['unsetMark'] = (typeOrName, options = {}) => ({ tr, state, dispatch }) => {\n  const { extendEmptyMarkRange = false } = options\n  const { selection } = tr\n  const type = getMarkType(typeOrName, state.schema)\n  const { $from, empty, ranges } = selection\n\n  if (!dispatch) {\n    return true\n  }\n\n  if (empty && extendEmptyMarkRange) {\n    let { from, to } = selection\n    const attrs = $from.marks().find(mark => mark.type === type)?.attrs\n    const range = getMarkRange($from, type, attrs)\n\n    if (range) {\n      from = range.from\n      to = range.to\n    }\n\n    tr.removeMark(from, to, type)\n  } else {\n    ranges.forEach(range => {\n      tr.removeMark(range.$from.pos, range.$to.pos, type)\n    })\n  }\n\n  tr.removeStoredMark(type)\n\n  return true\n}\n", "import {\n  Mark, MarkType, Node, NodeType,\n} from '@tiptap/pm/model'\nimport { SelectionRange } from '@tiptap/pm/state'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    updateAttributes: {\n      /**\n       * Update attributes of a node or mark.\n       * @param typeOrName The type or name of the node or mark.\n       * @param attributes The attributes of the node or mark.\n       * @example editor.commands.updateAttributes('mention', { userId: \"2\" })\n       */\n      updateAttributes: (\n        /**\n         * The type or name of the node or mark.\n         */\n        typeOrName: string | NodeType | MarkType,\n\n        /**\n         * The attributes of the node or mark.\n         */\n        attributes: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const updateAttributes: RawCommands['updateAttributes'] = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {\n\n  let nodeType: NodeType | null = null\n  let markType: MarkType | null = null\n\n  const schemaType = getSchemaTypeNameByName(\n    typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n    state.schema,\n  )\n\n  if (!schemaType) {\n    return false\n  }\n\n  if (schemaType === 'node') {\n    nodeType = getNodeType(typeOrName as NodeType, state.schema)\n  }\n\n  if (schemaType === 'mark') {\n    markType = getMarkType(typeOrName as MarkType, state.schema)\n  }\n\n  if (dispatch) {\n    tr.selection.ranges.forEach((range: SelectionRange) => {\n\n      const from = range.$from.pos\n      const to = range.$to.pos\n\n      let lastPos: number | undefined\n      let lastNode: Node | undefined\n      let trimmedFrom: number\n      let trimmedTo: number\n\n      if (tr.selection.empty) {\n        state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n\n          if (nodeType && nodeType === node.type) {\n            trimmedFrom = Math.max(pos, from)\n            trimmedTo = Math.min(pos + node.nodeSize, to)\n            lastPos = pos\n            lastNode = node\n          }\n        })\n      } else {\n        state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n\n          if (pos < from && nodeType && nodeType === node.type) {\n            trimmedFrom = Math.max(pos, from)\n            trimmedTo = Math.min(pos + node.nodeSize, to)\n            lastPos = pos\n            lastNode = node\n          }\n\n          if (pos >= from && pos <= to) {\n\n            if (nodeType && nodeType === node.type) {\n              tr.setNodeMarkup(pos, undefined, {\n                ...node.attrs,\n                ...attributes,\n              })\n            }\n\n            if (markType && node.marks.length) {\n              node.marks.forEach((mark: Mark) => {\n\n                if (markType === mark.type) {\n                  const trimmedFrom2 = Math.max(pos, from)\n                  const trimmedTo2 = Math.min(pos + node.nodeSize, to)\n\n                  tr.addMark(\n                    trimmedFrom2,\n                    trimmedTo2,\n                    markType.create({\n                      ...mark.attrs,\n                      ...attributes,\n                    }),\n                  )\n                }\n              })\n            }\n          }\n        })\n      }\n\n      if (lastNode) {\n\n        if (lastPos !== undefined) {\n          tr.setNodeMarkup(lastPos, undefined, {\n            ...lastNode.attrs,\n            ...attributes,\n          })\n        }\n\n        if (markType && lastNode.marks.length) {\n          lastNode.marks.forEach((mark: Mark) => {\n\n            if (markType === mark.type) {\n              tr.addMark(\n                trimmedFrom,\n                trimmedTo,\n                markType.create({\n                  ...mark.attrs,\n                  ...attributes,\n                }),\n              )\n            }\n          })\n        }\n      }\n    })\n  }\n\n  return true\n}\n", "import { wrapIn as originalWrapIn } from '@tiptap/pm/commands'\nimport { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    wrapIn: {\n      /**\n       * Wraps nodes in another node.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.wrapIn('blockquote')\n       */\n      wrapIn: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const wrapIn: RawCommands['wrapIn'] = (typeOrName, attributes = {}) => ({ state, dispatch }) => {\n  const type = getNodeType(typeOrName, state.schema)\n\n  return originalWrapIn(type, attributes)(state, dispatch)\n}\n", "import { NodeType } from '@tiptap/pm/model'\nimport { wrapInList as originalWrapInList } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    wrapInList: {\n      /**\n       * Wrap a node in a list.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.wrapInList('bulletList')\n       */\n      wrapInList: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const wrapInList: RawCommands['wrapInList'] = (typeOrName, attributes = {}) => ({ state, dispatch }) => {\n  const type = getNodeType(typeOrName, state.schema)\n\n  return originalWrapInList(type, attributes)(state, dispatch)\n}\n", "import * as commands from '../commands/index.js'\nimport { Extension } from '../Extension.js'\n\nexport * from '../commands/index.js'\n\nexport const Commands = Extension.create({\n  name: 'commands',\n\n  addCommands() {\n    return {\n      ...commands,\n    }\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Drop = Extension.create({\n  name: 'drop',\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('tiptapDrop'),\n\n        props: {\n          handleDrop: (_, e, slice, moved) => {\n            this.editor.emit('drop', {\n              editor: this.editor,\n              event: e,\n              slice,\n              moved,\n            })\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Editable = Extension.create({\n  name: 'editable',\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('editable'),\n        props: {\n          editable: () => this.editor.options.editable,\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const focusEventsPluginKey = new PluginKey('focusEvents')\n\nexport const FocusEvents = Extension.create({\n  name: 'focusEvents',\n\n  addProseMirrorPlugins() {\n    const { editor } = this\n\n    return [\n      new Plugin({\n        key: focusEventsPluginKey,\n        props: {\n          handleDOMEvents: {\n            focus: (view, event: Event) => {\n              editor.isFocused = true\n\n              const transaction = editor.state.tr\n                .setMeta('focus', { event })\n                .setMeta('addToHistory', false)\n\n              view.dispatch(transaction)\n\n              return false\n            },\n            blur: (view, event: Event) => {\n              editor.isFocused = false\n\n              const transaction = editor.state.tr\n                .setMeta('blur', { event })\n                .setMeta('addToHistory', false)\n\n              view.dispatch(transaction)\n\n              return false\n            },\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey, Selection } from '@tiptap/pm/state'\n\nimport { CommandManager } from '../CommandManager.js'\nimport { Extension } from '../Extension.js'\nimport { createChainableState } from '../helpers/createChainableState.js'\nimport { isNodeEmpty } from '../helpers/isNodeEmpty.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nexport const Keymap = Extension.create({\n  name: 'keymap',\n\n  addKeyboardShortcuts() {\n    const handleBackspace = () => this.editor.commands.first(({ commands }) => [\n      () => commands.undoInputRule(),\n\n      // maybe convert first text block node to default node\n      () => commands.command(({ tr }) => {\n        const { selection, doc } = tr\n        const { empty, $anchor } = selection\n        const { pos, parent } = $anchor\n        const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor\n        const parentIsIsolating = $parentPos.parent.type.spec.isolating\n\n        const parentPos = $anchor.pos - $anchor.parentOffset\n\n        const isAtStart = (parentIsIsolating && $parentPos.parent.childCount === 1)\n          ? parentPos === $anchor.pos\n          : Selection.atStart(doc).from === pos\n\n        if (\n          !empty\n          || !parent.type.isTextblock\n          || parent.textContent.length\n          || !isAtStart\n          || (isAtStart && $anchor.parent.type.name === 'paragraph') // prevent clearNodes when no nodes to clear, otherwise history stack is appended\n        ) {\n          return false\n        }\n\n        return commands.clearNodes()\n      }),\n\n      () => commands.deleteSelection(),\n      () => commands.joinBackward(),\n      () => commands.selectNodeBackward(),\n    ])\n\n    const handleDelete = () => this.editor.commands.first(({ commands }) => [\n      () => commands.deleteSelection(),\n      () => commands.deleteCurrentNode(),\n      () => commands.joinForward(),\n      () => commands.selectNodeForward(),\n    ])\n\n    const handleEnter = () => this.editor.commands.first(({ commands }) => [\n      () => commands.newlineInCode(),\n      () => commands.createParagraphNear(),\n      () => commands.liftEmptyBlock(),\n      () => commands.splitBlock(),\n    ])\n\n    const baseKeymap = {\n      Enter: handleEnter,\n      'Mod-Enter': () => this.editor.commands.exitCode(),\n      Backspace: handleBackspace,\n      'Mod-Backspace': handleBackspace,\n      'Shift-Backspace': handleBackspace,\n      Delete: handleDelete,\n      'Mod-Delete': handleDelete,\n      'Mod-a': () => this.editor.commands.selectAll(),\n    }\n\n    const pcKeymap = {\n      ...baseKeymap,\n    }\n\n    const macKeymap = {\n      ...baseKeymap,\n      'Ctrl-h': handleBackspace,\n      'Alt-Backspace': handleBackspace,\n      'Ctrl-d': handleDelete,\n      'Ctrl-Alt-Backspace': handleDelete,\n      'Alt-Delete': handleDelete,\n      'Alt-d': handleDelete,\n      'Ctrl-a': () => this.editor.commands.selectTextblockStart(),\n      'Ctrl-e': () => this.editor.commands.selectTextblockEnd(),\n    }\n\n    if (isiOS() || isMacOS()) {\n      return macKeymap\n    }\n\n    return pcKeymap\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      // With this plugin we check if the whole document was selected and deleted.\n      // In this case we will additionally call `clearNodes()` to convert e.g. a heading\n      // to a paragraph if necessary.\n      // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well\n      // with many other commands.\n      new Plugin({\n        key: new PluginKey('clearDocument'),\n        appendTransaction: (transactions, oldState, newState) => {\n          if (transactions.some(tr => tr.getMeta('composition'))) {\n            return\n          }\n\n          const docChanges = transactions.some(transaction => transaction.docChanged)\n            && !oldState.doc.eq(newState.doc)\n\n          const ignoreTr = transactions.some(transaction => transaction.getMeta('preventClearDocument'))\n\n          if (!docChanges || ignoreTr) {\n            return\n          }\n\n          const { empty, from, to } = oldState.selection\n          const allFrom = Selection.atStart(oldState.doc).from\n          const allEnd = Selection.atEnd(oldState.doc).to\n          const allWasSelected = from === allFrom && to === allEnd\n\n          if (empty || !allWasSelected) {\n            return\n          }\n\n          const isEmpty = isNodeEmpty(newState.doc)\n\n          if (!isEmpty) {\n            return\n          }\n\n          const tr = newState.tr\n          const state = createChainableState({\n            state: newState,\n            transaction: tr,\n          })\n          const { commands } = new CommandManager({\n            editor: this.editor,\n            state,\n          })\n\n          commands.clearNodes()\n\n          if (!tr.steps.length) {\n            return\n          }\n\n          return tr\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Paste = Extension.create({\n  name: 'paste',\n\n  addProseMirrorPlugins() {\n\n    return [\n      new Plugin({\n        key: new PluginKey('tiptapPaste'),\n\n        props: {\n          handlePaste: (_view, e, slice) => {\n            this.editor.emit('paste', {\n              editor: this.editor,\n              event: e,\n              slice,\n            })\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Tabindex = Extension.create({\n  name: 'tabindex',\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('tabindex'),\n        props: {\n          attributes: (): { [name: string]: string; } => (this.editor.isEditable ? { tabindex: '0' } : {}),\n        },\n      }),\n    ]\n  },\n})\n", "import {\n  Fragment, Node, ResolvedPos,\n} from '@tiptap/pm/model'\n\nimport { Editor } from './Editor.js'\nimport { Content, Range } from './types.js'\n\nexport class NodePos {\n  private resolvedPos: ResolvedPos\n\n  private isBlock: boolean\n\n  private editor: Editor\n\n  private get name(): string {\n    return this.node.type.name\n  }\n\n  constructor(pos: ResolvedPos, editor: Editor, isBlock = false, node: Node | null = null) {\n    this.isBlock = isBlock\n    this.resolvedPos = pos\n    this.editor = editor\n    this.currentNode = node\n  }\n\n  private currentNode: Node | null = null\n\n  get node(): Node {\n    return this.currentNode || this.resolvedPos.node()\n  }\n\n  get element(): HTMLElement {\n    return this.editor.view.domAtPos(this.pos).node as HTMLElement\n  }\n\n  public actualDepth: number | null = null\n\n  get depth(): number {\n    return this.actualDepth ?? this.resolvedPos.depth\n  }\n\n  get pos(): number {\n    return this.resolvedPos.pos\n  }\n\n  get content(): Fragment {\n    return this.node.content\n  }\n\n  set content(content: Content) {\n    let from = this.from\n    let to = this.to\n\n    if (this.isBlock) {\n      if (this.content.size === 0) {\n        console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`)\n        return\n      }\n\n      from = this.from + 1\n      to = this.to - 1\n    }\n\n    this.editor.commands.insertContentAt({ from, to }, content)\n  }\n\n  get attributes(): { [key: string]: any } {\n    return this.node.attrs\n  }\n\n  get textContent(): string {\n    return this.node.textContent\n  }\n\n  get size(): number {\n    return this.node.nodeSize\n  }\n\n  get from(): number {\n    if (this.isBlock) {\n      return this.pos\n    }\n\n    return this.resolvedPos.start(this.resolvedPos.depth)\n  }\n\n  get range(): Range {\n    return {\n      from: this.from,\n      to: this.to,\n    }\n  }\n\n  get to(): number {\n    if (this.isBlock) {\n      return this.pos + this.size\n    }\n\n    return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1)\n  }\n\n  get parent(): NodePos | null {\n    if (this.depth === 0) {\n      return null\n    }\n\n    const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1)\n    const $pos = this.resolvedPos.doc.resolve(parentPos)\n\n    return new NodePos($pos, this.editor)\n  }\n\n  get before(): NodePos | null {\n    let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2))\n\n    if ($pos.depth !== this.depth) {\n      $pos = this.resolvedPos.doc.resolve(this.from - 3)\n    }\n\n    return new NodePos($pos, this.editor)\n  }\n\n  get after(): NodePos | null {\n    let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1))\n\n    if ($pos.depth !== this.depth) {\n      $pos = this.resolvedPos.doc.resolve(this.to + 3)\n    }\n\n    return new NodePos($pos, this.editor)\n  }\n\n  get children(): NodePos[] {\n    const children: NodePos[] = []\n\n    this.node.content.forEach((node, offset) => {\n      const isBlock = node.isBlock && !node.isTextblock\n      const isNonTextAtom = node.isAtom && !node.isText\n\n      const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1)\n\n      // Check if targetPos is within valid document range\n      if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) {\n        return\n      }\n\n      const $pos = this.resolvedPos.doc.resolve(targetPos)\n\n      if (!isBlock && $pos.depth <= this.depth) {\n        return\n      }\n\n      const childNodePos = new NodePos($pos, this.editor, isBlock, isBlock ? node : null)\n\n      if (isBlock) {\n        childNodePos.actualDepth = this.depth + 1\n      }\n\n      children.push(new NodePos($pos, this.editor, isBlock, isBlock ? node : null))\n    })\n\n    return children\n  }\n\n  get firstChild(): NodePos | null {\n    return this.children[0] || null\n  }\n\n  get lastChild(): NodePos | null {\n    const children = this.children\n\n    return children[children.length - 1] || null\n  }\n\n  closest(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n    let node: NodePos | null = null\n    let currentNode = this.parent\n\n    while (currentNode && !node) {\n      if (currentNode.node.type.name === selector) {\n        if (Object.keys(attributes).length > 0) {\n          const nodeAttributes = currentNode.node.attrs\n          const attrKeys = Object.keys(attributes)\n\n          for (let index = 0; index < attrKeys.length; index += 1) {\n            const key = attrKeys[index]\n\n            if (nodeAttributes[key] !== attributes[key]) {\n              break\n            }\n          }\n        } else {\n          node = currentNode\n        }\n      }\n\n      currentNode = currentNode.parent\n    }\n\n    return node\n  }\n\n  querySelector(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n    return this.querySelectorAll(selector, attributes, true)[0] || null\n  }\n\n  querySelectorAll(selector: string, attributes: { [key: string]: any } = {}, firstItemOnly = false): NodePos[] {\n    let nodes: NodePos[] = []\n\n    if (!this.children || this.children.length === 0) {\n      return nodes\n    }\n    const attrKeys = Object.keys(attributes)\n\n    /**\n     * Finds all children recursively that match the selector and attributes\n     * If firstItemOnly is true, it will return the first item found\n     */\n    this.children.forEach(childPos => {\n      // If we already found a node and we only want the first item, we dont need to keep going\n      if (firstItemOnly && nodes.length > 0) {\n        return\n      }\n\n      if (childPos.node.type.name === selector) {\n        const doesAllAttributesMatch = attrKeys.every(key => attributes[key] === childPos.node.attrs[key])\n\n        if (doesAllAttributesMatch) {\n          nodes.push(childPos)\n        }\n      }\n\n      // If we already found a node and we only want the first item, we can stop here and skip the recursion\n      if (firstItemOnly && nodes.length > 0) {\n        return\n      }\n\n      nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly))\n    })\n\n    return nodes\n  }\n\n  setAttribute(attributes: { [key: string]: any }) {\n    const { tr } = this.editor.state\n\n    tr.setNodeMarkup(this.from, undefined, {\n      ...this.node.attrs,\n      ...attributes,\n    })\n\n    this.editor.view.dispatch(tr)\n  }\n}\n", "export const style = `.ProseMirror {\n  position: relative;\n}\n\n.ProseMirror {\n  word-wrap: break-word;\n  white-space: pre-wrap;\n  white-space: break-spaces;\n  -webkit-font-variant-ligatures: none;\n  font-variant-ligatures: none;\n  font-feature-settings: \"liga\" 0; /* the above doesn't seem to work in Edge */\n}\n\n.ProseMirror [contenteditable=\"false\"] {\n  white-space: normal;\n}\n\n.ProseMirror [contenteditable=\"false\"] [contenteditable=\"true\"] {\n  white-space: pre-wrap;\n}\n\n.ProseMirror pre {\n  white-space: pre-wrap;\n}\n\nimg.ProseMirror-separator {\n  display: inline !important;\n  border: none !important;\n  margin: 0 !important;\n  width: 0 !important;\n  height: 0 !important;\n}\n\n.ProseMirror-gapcursor {\n  display: none;\n  pointer-events: none;\n  position: absolute;\n  margin: 0;\n}\n\n.ProseMirror-gapcursor:after {\n  content: \"\";\n  display: block;\n  position: absolute;\n  top: -2px;\n  width: 20px;\n  border-top: 1px solid black;\n  animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n}\n\n@keyframes ProseMirror-cursor-blink {\n  to {\n    visibility: hidden;\n  }\n}\n\n.ProseMirror-hideselection *::selection {\n  background: transparent;\n}\n\n.ProseMirror-hideselection *::-moz-selection {\n  background: transparent;\n}\n\n.ProseMirror-hideselection * {\n  caret-color: transparent;\n}\n\n.ProseMirror-focused .ProseMirror-gapcursor {\n  display: block;\n}\n\n.tippy-box[data-animation=fade][data-state=hidden] {\n  opacity: 0\n}`\n", "export function createStyleTag(style: string, nonce?: string, suffix?: string): HTMLStyleElement {\n  const tiptapStyleTag = (<HTMLStyleElement>document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ''}]`))\n\n  if (tiptapStyleTag !== null) {\n    return tiptapStyleTag\n  }\n\n  const styleNode = document.createElement('style')\n\n  if (nonce) {\n    styleNode.setAttribute('nonce', nonce)\n  }\n\n  styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ''}`, '')\n  styleNode.innerHTML = style\n  document.getElementsByTagName('head')[0].appendChild(styleNode)\n\n  return styleNode\n}\n", "/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport {\n  MarkType,\n  Node as ProseMirrorNode,\n  NodeType,\n  Schema,\n} from '@tiptap/pm/model'\nimport {\n  EditorState, Plugin, PluginKey, Transaction,\n} from '@tiptap/pm/state'\nimport { EditorView } from '@tiptap/pm/view'\n\nimport { CommandManager } from './CommandManager.js'\nimport { EventEmitter } from './EventEmitter.js'\nimport { ExtensionManager } from './ExtensionManager.js'\nimport {\n  ClipboardTextSerializer, Commands, Drop, Editable, FocusEvents, Keymap, Paste,\n  Tabindex,\n} from './extensions/index.js'\nimport { createDocument } from './helpers/createDocument.js'\nimport { getAttributes } from './helpers/getAttributes.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getText } from './helpers/getText.js'\nimport { getTextSerializersFromSchema } from './helpers/getTextSerializersFromSchema.js'\nimport { isActive } from './helpers/isActive.js'\nimport { isNodeEmpty } from './helpers/isNodeEmpty.js'\nimport { resolveFocusPosition } from './helpers/resolveFocusPosition.js'\nimport { NodePos } from './NodePos.js'\nimport { style } from './style.js'\nimport {\n  CanCommands,\n  ChainedCommands,\n  EditorEvents,\n  EditorOptions,\n  JSONContent,\n  SingleCommands,\n  TextSerializer,\n} from './types.js'\nimport { createStyleTag } from './utilities/createStyleTag.js'\nimport { isFunction } from './utilities/isFunction.js'\n\nexport * as extensions from './extensions/index.js'\n\n// @ts-ignore\nexport interface TiptapEditorHTMLElement extends HTMLElement {\n  editor?: Editor\n}\n\nexport class Editor extends EventEmitter<EditorEvents> {\n  private commandManager!: CommandManager\n\n  public extensionManager!: ExtensionManager\n\n  private css!: HTMLStyleElement\n\n  public schema!: Schema\n\n  public view!: EditorView\n\n  public isFocused = false\n\n  /**\n   * The editor is considered initialized after the `create` event has been emitted.\n   */\n  public isInitialized = false\n\n  public extensionStorage: Record<string, any> = {}\n\n  public options: EditorOptions = {\n    element: document.createElement('div'),\n    content: '',\n    injectCSS: true,\n    injectNonce: undefined,\n    extensions: [],\n    autofocus: false,\n    editable: true,\n    editorProps: {},\n    parseOptions: {},\n    coreExtensionOptions: {},\n    enableInputRules: true,\n    enablePasteRules: true,\n    enableCoreExtensions: true,\n    enableContentCheck: false,\n    emitContentError: false,\n    onBeforeCreate: () => null,\n    onCreate: () => null,\n    onUpdate: () => null,\n    onSelectionUpdate: () => null,\n    onTransaction: () => null,\n    onFocus: () => null,\n    onBlur: () => null,\n    onDestroy: () => null,\n    onContentError: ({ error }) => { throw error },\n    onPaste: () => null,\n    onDrop: () => null,\n  }\n\n  constructor(options: Partial<EditorOptions> = {}) {\n    super()\n    this.setOptions(options)\n    this.createExtensionManager()\n    this.createCommandManager()\n    this.createSchema()\n    this.on('beforeCreate', this.options.onBeforeCreate)\n    this.emit('beforeCreate', { editor: this })\n    this.on('contentError', this.options.onContentError)\n    this.createView()\n    this.injectCSS()\n    this.on('create', this.options.onCreate)\n    this.on('update', this.options.onUpdate)\n    this.on('selectionUpdate', this.options.onSelectionUpdate)\n    this.on('transaction', this.options.onTransaction)\n    this.on('focus', this.options.onFocus)\n    this.on('blur', this.options.onBlur)\n    this.on('destroy', this.options.onDestroy)\n    this.on('drop', ({ event, slice, moved }) => this.options.onDrop(event, slice, moved))\n    this.on('paste', ({ event, slice }) => this.options.onPaste(event, slice))\n\n    window.setTimeout(() => {\n      if (this.isDestroyed) {\n        return\n      }\n\n      this.commands.focus(this.options.autofocus)\n      this.emit('create', { editor: this })\n      this.isInitialized = true\n    }, 0)\n  }\n\n  /**\n   * Returns the editor storage.\n   */\n  public get storage(): Record<string, any> {\n    return this.extensionStorage\n  }\n\n  /**\n   * An object of all registered commands.\n   */\n  public get commands(): SingleCommands {\n    return this.commandManager.commands\n  }\n\n  /**\n   * Create a command chain to call multiple commands at once.\n   */\n  public chain(): ChainedCommands {\n    return this.commandManager.chain()\n  }\n\n  /**\n   * Check if a command or a command chain can be executed. Without executing it.\n   */\n  public can(): CanCommands {\n    return this.commandManager.can()\n  }\n\n  /**\n   * Inject CSS styles.\n   */\n  private injectCSS(): void {\n    if (this.options.injectCSS && document) {\n      this.css = createStyleTag(style, this.options.injectNonce)\n    }\n  }\n\n  /**\n   * Update editor options.\n   *\n   * @param options A list of options\n   */\n  public setOptions(options: Partial<EditorOptions> = {}): void {\n    this.options = {\n      ...this.options,\n      ...options,\n    }\n\n    if (!this.view || !this.state || this.isDestroyed) {\n      return\n    }\n\n    if (this.options.editorProps) {\n      this.view.setProps(this.options.editorProps)\n    }\n\n    this.view.updateState(this.state)\n  }\n\n  /**\n   * Update editable state of the editor.\n   */\n  public setEditable(editable: boolean, emitUpdate = true): void {\n    this.setOptions({ editable })\n\n    if (emitUpdate) {\n      this.emit('update', { editor: this, transaction: this.state.tr })\n    }\n  }\n\n  /**\n   * Returns whether the editor is editable.\n   */\n  public get isEditable(): boolean {\n    // since plugins are applied after creating the view\n    // `editable` is always `true` for one tick.\n    // that’s why we also have to check for `options.editable`\n    return this.options.editable && this.view && this.view.editable\n  }\n\n  /**\n   * Returns the editor state.\n   */\n  public get state(): EditorState {\n    return this.view.state\n  }\n\n  /**\n   * Register a ProseMirror plugin.\n   *\n   * @param plugin A ProseMirror plugin\n   * @param handlePlugins Control how to merge the plugin into the existing plugins.\n   * @returns The new editor state\n   */\n  public registerPlugin(\n    plugin: Plugin,\n    handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[],\n  ): EditorState {\n    const plugins = isFunction(handlePlugins)\n      ? handlePlugins(plugin, [...this.state.plugins])\n      : [...this.state.plugins, plugin]\n\n    const state = this.state.reconfigure({ plugins })\n\n    this.view.updateState(state)\n\n    return state\n  }\n\n  /**\n   * Unregister a ProseMirror plugin.\n   *\n   * @param nameOrPluginKeyToRemove The plugins name\n   * @returns The new editor state or undefined if the editor is destroyed\n   */\n  public unregisterPlugin(nameOrPluginKeyToRemove: string | PluginKey | (string | PluginKey)[]): EditorState | undefined {\n    if (this.isDestroyed) {\n      return undefined\n    }\n\n    const prevPlugins = this.state.plugins\n    let plugins = prevPlugins;\n\n    ([] as (string | PluginKey)[]).concat(nameOrPluginKeyToRemove).forEach(nameOrPluginKey => {\n      // @ts-ignore\n      const name = typeof nameOrPluginKey === 'string' ? `${nameOrPluginKey}$` : nameOrPluginKey.key\n\n      // @ts-ignore\n      plugins = plugins.filter(plugin => !plugin.key.startsWith(name))\n    })\n\n    if (prevPlugins.length === plugins.length) {\n      // No plugin was removed, so we don’t need to update the state\n      return undefined\n    }\n\n    const state = this.state.reconfigure({\n      plugins,\n    })\n\n    this.view.updateState(state)\n\n    return state\n  }\n\n  /**\n   * Creates an extension manager.\n   */\n  private createExtensionManager(): void {\n\n    const coreExtensions = this.options.enableCoreExtensions ? [\n      Editable,\n      ClipboardTextSerializer.configure({\n        blockSeparator: this.options.coreExtensionOptions?.clipboardTextSerializer?.blockSeparator,\n      }),\n      Commands,\n      FocusEvents,\n      Keymap,\n      Tabindex,\n      Drop,\n      Paste,\n    ].filter(ext => {\n      if (typeof this.options.enableCoreExtensions === 'object') {\n        return this.options.enableCoreExtensions[ext.name as keyof typeof this.options.enableCoreExtensions] !== false\n      }\n      return true\n    }) : []\n    const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {\n      return ['extension', 'node', 'mark'].includes(extension?.type)\n    })\n\n    this.extensionManager = new ExtensionManager(allExtensions, this)\n  }\n\n  /**\n   * Creates an command manager.\n   */\n  private createCommandManager(): void {\n    this.commandManager = new CommandManager({\n      editor: this,\n    })\n  }\n\n  /**\n   * Creates a ProseMirror schema.\n   */\n  private createSchema(): void {\n    this.schema = this.extensionManager.schema\n  }\n\n  /**\n   * Creates a ProseMirror view.\n   */\n  private createView(): void {\n    let doc: ProseMirrorNode\n\n    try {\n      doc = createDocument(\n        this.options.content,\n        this.schema,\n        this.options.parseOptions,\n        { errorOnInvalidContent: this.options.enableContentCheck },\n      )\n    } catch (e) {\n      if (!(e instanceof Error) || !['[tiptap error]: Invalid JSON content', '[tiptap error]: Invalid HTML content'].includes(e.message)) {\n        // Not the content error we were expecting\n        throw e\n      }\n      this.emit('contentError', {\n        editor: this,\n        error: e as Error,\n        disableCollaboration: () => {\n          if (this.storage.collaboration) {\n            this.storage.collaboration.isDisabled = true\n          }\n          // To avoid syncing back invalid content, reinitialize the extensions without the collaboration extension\n          this.options.extensions = this.options.extensions.filter(extension => extension.name !== 'collaboration')\n\n          // Restart the initialization process by recreating the extension manager with the new set of extensions\n          this.createExtensionManager()\n        },\n      })\n\n      // Content is invalid, but attempt to create it anyway, stripping out the invalid parts\n      doc = createDocument(\n        this.options.content,\n        this.schema,\n        this.options.parseOptions,\n        { errorOnInvalidContent: false },\n      )\n    }\n    const selection = resolveFocusPosition(doc, this.options.autofocus)\n\n    this.view = new EditorView(this.options.element, {\n      ...this.options.editorProps,\n      attributes: {\n        // add `role=\"textbox\"` to the editor element\n        role: 'textbox',\n        ...this.options.editorProps?.attributes,\n      },\n      dispatchTransaction: this.dispatchTransaction.bind(this),\n      state: EditorState.create({\n        doc,\n        selection: selection || undefined,\n      }),\n    })\n\n    // `editor.view` is not yet available at this time.\n    // Therefore we will add all plugins and node views directly afterwards.\n    const newState = this.state.reconfigure({\n      plugins: this.extensionManager.plugins,\n    })\n\n    this.view.updateState(newState)\n\n    this.createNodeViews()\n    this.prependClass()\n\n    // Let’s store the editor instance in the DOM element.\n    // So we’ll have access to it for tests.\n    // @ts-ignore\n    const dom = this.view.dom as TiptapEditorHTMLElement\n\n    dom.editor = this\n  }\n\n  /**\n   * Creates all node views.\n   */\n  public createNodeViews(): void {\n    if (this.view.isDestroyed) {\n      return\n    }\n\n    this.view.setProps({\n      nodeViews: this.extensionManager.nodeViews,\n    })\n  }\n\n  /**\n   * Prepend class name to element.\n   */\n  public prependClass(): void {\n    this.view.dom.className = `tiptap ${this.view.dom.className}`\n  }\n\n  public isCapturingTransaction = false\n\n  private capturedTransaction: Transaction | null = null\n\n  public captureTransaction(fn: () => void) {\n    this.isCapturingTransaction = true\n    fn()\n    this.isCapturingTransaction = false\n\n    const tr = this.capturedTransaction\n\n    this.capturedTransaction = null\n\n    return tr\n  }\n\n  /**\n   * The callback over which to send transactions (state updates) produced by the view.\n   *\n   * @param transaction An editor state transaction\n   */\n  private dispatchTransaction(transaction: Transaction): void {\n    // if the editor / the view of the editor was destroyed\n    // the transaction should not be dispatched as there is no view anymore.\n    if (this.view.isDestroyed) {\n      return\n    }\n\n    if (this.isCapturingTransaction) {\n      if (!this.capturedTransaction) {\n        this.capturedTransaction = transaction\n\n        return\n      }\n\n      transaction.steps.forEach(step => this.capturedTransaction?.step(step))\n\n      return\n    }\n\n    const state = this.state.apply(transaction)\n    const selectionHasChanged = !this.state.selection.eq(state.selection)\n\n    this.emit('beforeTransaction', {\n      editor: this,\n      transaction,\n      nextState: state,\n    })\n    this.view.updateState(state)\n    this.emit('transaction', {\n      editor: this,\n      transaction,\n    })\n\n    if (selectionHasChanged) {\n      this.emit('selectionUpdate', {\n        editor: this,\n        transaction,\n      })\n    }\n\n    const focus = transaction.getMeta('focus')\n    const blur = transaction.getMeta('blur')\n\n    if (focus) {\n      this.emit('focus', {\n        editor: this,\n        event: focus.event,\n        transaction,\n      })\n    }\n\n    if (blur) {\n      this.emit('blur', {\n        editor: this,\n        event: blur.event,\n        transaction,\n      })\n    }\n\n    if (!transaction.docChanged || transaction.getMeta('preventUpdate')) {\n      return\n    }\n\n    this.emit('update', {\n      editor: this,\n      transaction,\n    })\n  }\n\n  /**\n   * Get attributes of the currently selected node or mark.\n   */\n  public getAttributes(nameOrType: string | NodeType | MarkType): Record<string, any> {\n    return getAttributes(this.state, nameOrType)\n  }\n\n  /**\n   * Returns if the currently selected node or mark is active.\n   *\n   * @param name Name of the node or mark\n   * @param attributes Attributes of the node or mark\n   */\n  public isActive(name: string, attributes?: {}): boolean\n  public isActive(attributes: {}): boolean\n  public isActive(nameOrAttributes: string, attributesOrUndefined?: {}): boolean {\n    const name = typeof nameOrAttributes === 'string' ? nameOrAttributes : null\n\n    const attributes = typeof nameOrAttributes === 'string' ? attributesOrUndefined : nameOrAttributes\n\n    return isActive(this.state, name, attributes)\n  }\n\n  /**\n   * Get the document as JSON.\n   */\n  public getJSON(): JSONContent {\n    return this.state.doc.toJSON()\n  }\n\n  /**\n   * Get the document as HTML.\n   */\n  public getHTML(): string {\n    return getHTMLFromFragment(this.state.doc.content, this.schema)\n  }\n\n  /**\n   * Get the document as text.\n   */\n  public getText(options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  }): string {\n    const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n\n    return getText(this.state.doc, {\n      blockSeparator,\n      textSerializers: {\n        ...getTextSerializersFromSchema(this.schema),\n        ...textSerializers,\n      },\n    })\n  }\n\n  /**\n   * Check if there is no content.\n   */\n  public get isEmpty(): boolean {\n    return isNodeEmpty(this.state.doc)\n  }\n\n  /**\n   * Get the number of characters for the current document.\n   *\n   * @deprecated\n   */\n  public getCharacterCount(): number {\n    console.warn(\n      '[tiptap warn]: \"editor.getCharacterCount()\" is deprecated. Please use \"editor.storage.characterCount.characters()\" instead.',\n    )\n\n    return this.state.doc.content.size - 2\n  }\n\n  /**\n   * Destroy the editor.\n   */\n  public destroy(): void {\n    this.emit('destroy')\n\n    if (this.view) {\n      // Cleanup our reference to prevent circular references which caused memory leaks\n      // @ts-ignore\n      const dom = this.view.dom as TiptapEditorHTMLElement\n\n      if (dom && dom.editor) {\n        delete dom.editor\n      }\n      this.view.destroy()\n    }\n\n    this.removeAllListeners()\n  }\n\n  /**\n   * Check if the editor is already destroyed.\n   */\n  public get isDestroyed(): boolean {\n    // @ts-ignore\n    return !this.view?.docView\n  }\n\n  public $node(selector: string, attributes?: { [key: string]: any }): NodePos | null {\n    return this.$doc?.querySelector(selector, attributes) || null\n  }\n\n  public $nodes(selector: string, attributes?: { [key: string]: any }): NodePos[] | null {\n    return this.$doc?.querySelectorAll(selector, attributes) || null\n  }\n\n  public $pos(pos: number) {\n    const $pos = this.state.doc.resolve(pos)\n\n    return new NodePos($pos, this)\n  }\n\n  get $doc() {\n    return this.$pos(0)\n  }\n}\n", "import { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport { InputRule, InputRuleFinder } from '../InputRule.js'\nimport { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a mark when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function markInputRule(config: {\n  find: InputRuleFinder\n  type: MarkType\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match)\n\n      if (attributes === false || attributes === null) {\n        return null\n      }\n\n      const { tr } = state\n      const captureGroup = match[match.length - 1]\n      const fullMatch = match[0]\n\n      if (captureGroup) {\n        const startSpaces = fullMatch.search(/\\S/)\n        const textStart = range.from + fullMatch.indexOf(captureGroup)\n        const textEnd = textStart + captureGroup.length\n\n        const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n          .filter(item => {\n            // @ts-ignore\n            const excluded = item.mark.type.excluded as MarkType[]\n\n            return excluded.find(type => type === config.type && type !== item.mark.type)\n          })\n          .filter(item => item.to > textStart)\n\n        if (excludedMarks.length) {\n          return null\n        }\n\n        if (textEnd < range.to) {\n          tr.delete(textEnd, range.to)\n        }\n\n        if (textStart > range.from) {\n          tr.delete(range.from + startSpaces, textStart)\n        }\n\n        const markEnd = range.from + startSpaces + captureGroup.length\n\n        tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n        tr.removeStoredMark(config.type)\n      }\n    },\n  })\n}\n", "import { NodeType } from '@tiptap/pm/model'\n\nimport { InputRule, InputRuleFinder } from '../InputRule.js'\nimport { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a node when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function nodeInputRule(config: {\n  /**\n   * The regex to match.\n   */\n  find: InputRuleFinder\n\n  /**\n   * The node type to add.\n   */\n  type: NodeType\n\n  /**\n   * A function that returns the attributes for the node\n   * can also be an object of attributes\n   */\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n      const { tr } = state\n      const start = range.from\n      let end = range.to\n\n      const newNode = config.type.create(attributes)\n\n      if (match[1]) {\n        const offset = match[0].lastIndexOf(match[1])\n        let matchStart = start + offset\n\n        if (matchStart > end) {\n          matchStart = end\n        } else {\n          end = matchStart + match[1].length\n        }\n\n        // insert last typed character\n        const lastChar = match[0][match[0].length - 1]\n\n        tr.insertText(lastChar, start + match[0].length - 1)\n\n        // insert node from input rule\n        tr.replaceWith(matchStart, end, newNode)\n      } else if (match[0]) {\n        const insertionStart = config.type.isInline ? start : start - 1\n\n        tr.insert(insertionStart, config.type.create(attributes)).delete(\n          tr.mapping.map(start),\n          tr.mapping.map(end),\n        )\n      }\n\n      tr.scrollIntoView()\n    },\n  })\n}\n", "import { NodeType } from '@tiptap/pm/model'\n\nimport { InputRule, InputRuleFinder } from '../InputRule.js'\nimport { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that changes the type of a textblock when the\n * matched text is typed into it. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textblockTypeInputRule(config: {\n  find: InputRuleFinder\n  type: NodeType\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      const $start = state.doc.resolve(range.from)\n      const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n\n      if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {\n        return null\n      }\n\n      state.tr\n        .delete(range.from, range.to)\n        .setBlockType(range.from, range.from, config.type, attributes)\n    },\n  })\n}\n", "import { InputRule, InputRuleFinder } from '../InputRule.js'\n\n/**\n * Build an input rule that replaces text when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textInputRule(config: {\n  find: InputRuleFinder,\n  replace: string,\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      let insert = config.replace\n      let start = range.from\n      const end = range.to\n\n      if (match[1]) {\n        const offset = match[0].lastIndexOf(match[1])\n\n        insert += match[0].slice(offset + match[1].length)\n        start += offset\n\n        const cutOff = start - end\n\n        if (cutOff > 0) {\n          insert = match[0].slice(offset - cutOff, offset) + insert\n          start = end\n        }\n      }\n\n      state.tr.insertText(insert, start, end)\n    },\n  })\n}\n", "import { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { canJoin, findWrapping } from '@tiptap/pm/transform'\n\nimport { Editor } from '../Editor.js'\nimport { InputRule, InputRuleFinder } from '../InputRule.js'\nimport { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule for automatically wrapping a textblock when a\n * given string is typed. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n *\n * `type` is the type of node to wrap in.\n *\n * By default, if there’s a node with the same type above the newly\n * wrapped node, the rule will try to join those\n * two nodes. You can pass a join predicate, which takes a regular\n * expression match and the node before the wrapped node, and can\n * return a boolean to indicate whether a join should happen.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function wrappingInputRule(config: {\n  find: InputRuleFinder,\n  type: NodeType,\n  keepMarks?: boolean,\n  keepAttributes?: boolean,\n  editor?: Editor\n  getAttributes?:\n  | Record<string, any>\n  | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n  | false\n  | null\n  ,\n  joinPredicate?: (match: ExtendedRegExpMatchArray, node: ProseMirrorNode) => boolean,\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({\n      state, range, match, chain,\n    }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n      const tr = state.tr.delete(range.from, range.to)\n      const $start = tr.doc.resolve(range.from)\n      const blockRange = $start.blockRange()\n      const wrapping = blockRange && findWrapping(blockRange, config.type, attributes)\n\n      if (!wrapping) {\n        return null\n      }\n\n      tr.wrap(blockRange, wrapping)\n\n      if (config.keepMarks && config.editor) {\n        const { selection, storedMarks } = state\n        const { splittableMarks } = config.editor.extensionManager\n        const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n        if (marks) {\n          const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n          tr.ensureMarks(filteredMarks)\n        }\n      }\n      if (config.keepAttributes) {\n        /** If the nodeType is `bulletList` or `orderedList` set the `nodeType` as `listItem` */\n        const nodeType = config.type.name === 'bulletList' || config.type.name === 'orderedList' ? 'listItem' : 'taskList'\n\n        chain().updateAttributes(nodeType, attributes).run()\n      }\n\n      const before = tr.doc.resolve(range.from - 1).nodeBefore\n\n      if (\n        before\n        && before.type === config.type\n        && canJoin(tr.doc, range.from - 1)\n        && (!config.joinPredicate || config.joinPredicate(match, before))\n      ) {\n        tr.join(range.from - 1)\n      }\n    },\n  })\n}\n", "import {\n  DOMOutputSpec, Node as ProseMirrorNode, NodeSpec, NodeType,\n} from '@tiptap/pm/model'\nimport { Plugin, Transaction } from '@tiptap/pm/state'\n\nimport { Editor } from './Editor.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport { NodeConfig } from './index.js'\nimport { InputRule } from './InputRule.js'\nimport { Mark } from './Mark.js'\nimport { PasteRule } from './PasteRule.js'\nimport {\n  AnyConfig,\n  Attributes,\n  Extensions,\n  GlobalAttributes,\n  KeyboardShortcutCommand,\n  NodeViewRenderer,\n  ParentConfig,\n  RawCommands,\n} from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { mergeDeep } from './utilities/mergeDeep.js'\n\ndeclare module '@tiptap/core' {\n  interface NodeConfig<Options = any, Storage = any> {\n    // @ts-ignore - this is a dynamic key\n    [key: string]: any\n\n    /**\n     * The extension name - this must be unique.\n     * It will be used to identify the extension.\n     *\n     * @example 'myExtension'\n     */\n    name: string\n\n    /**\n     * The priority of your extension. The higher, the earlier it will be called\n     * and will take precedence over other extensions with a lower priority.\n     * @default 100\n     * @example 101\n     */\n    priority?: number\n\n    /**\n     * The default options for this extension.\n     * @example\n     * defaultOptions: {\n     *   myOption: 'foo',\n     *   myOtherOption: 10,\n     * }\n     */\n    defaultOptions?: Options\n\n    /**\n     * This method will add options to this extension\n     * @see https://tiptap.dev/guide/custom-extensions#settings\n     * @example\n     * addOptions() {\n     *  return {\n     *    myOption: 'foo',\n     *    myOtherOption: 10,\n     * }\n     */\n    addOptions?: (this: {\n      name: string\n      parent: Exclude<ParentConfig<NodeConfig<Options, Storage>>['addOptions'], undefined>\n    }) => Options\n\n    /**\n     * The default storage this extension can save data to.\n     * @see https://tiptap.dev/guide/custom-extensions#storage\n     * @example\n     * defaultStorage: {\n     *   prefetchedUsers: [],\n     *   loading: false,\n     * }\n     */\n    addStorage?: (this: {\n      name: string\n      options: Options\n      parent: Exclude<ParentConfig<NodeConfig<Options, Storage>>['addStorage'], undefined>\n    }) => Storage\n\n    /**\n     * This function adds globalAttributes to specific nodes.\n     * @see https://tiptap.dev/guide/custom-extensions#global-attributes\n     * @example\n     * addGlobalAttributes() {\n     *   return [\n     *     {\n             // Extend the following extensions\n     *       types: [\n     *         'heading',\n     *         'paragraph',\n     *       ],\n     *       // … with those attributes\n     *       attributes: {\n     *         textAlign: {\n     *           default: 'left',\n     *           renderHTML: attributes => ({\n     *             style: `text-align: ${attributes.textAlign}`,\n     *           }),\n     *           parseHTML: element => element.style.textAlign || 'left',\n     *         },\n     *       },\n     *     },\n     *   ]\n     * }\n     */\n    addGlobalAttributes?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      extensions: (Node | Mark)[]\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addGlobalAttributes']\n    }) => GlobalAttributes\n\n    /**\n     * This function adds commands to the editor\n     * @see https://tiptap.dev/guide/custom-extensions#keyboard-shortcuts\n     * @example\n     * addCommands() {\n     *   return {\n     *     myCommand: () => ({ chain }) => chain().setMark('type', 'foo').run(),\n     *   }\n     * }\n     */\n    addCommands?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: NodeType\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addCommands']\n    }) => Partial<RawCommands>\n\n    /**\n     * This function registers keyboard shortcuts.\n     * @see https://tiptap.dev/guide/custom-extensions#keyboard-shortcuts\n     * @example\n     * addKeyboardShortcuts() {\n     *   return {\n     *     'Mod-l': () => this.editor.commands.toggleBulletList(),\n     *   }\n     * },\n     */\n    addKeyboardShortcuts?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: NodeType\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addKeyboardShortcuts']\n    }) => {\n      [key: string]: KeyboardShortcutCommand\n    }\n\n    /**\n     * This function adds input rules to the editor.\n     * @see https://tiptap.dev/guide/custom-extensions#input-rules\n     * @example\n     * addInputRules() {\n     *   return [\n     *     markInputRule({\n     *       find: inputRegex,\n     *       type: this.type,\n     *     }),\n     *   ]\n     * },\n     */\n    addInputRules?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: NodeType\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addInputRules']\n    }) => InputRule[]\n\n    /**\n     * This function adds paste rules to the editor.\n     * @see https://tiptap.dev/guide/custom-extensions#paste-rules\n     * @example\n     * addPasteRules() {\n     *   return [\n     *     markPasteRule({\n     *       find: pasteRegex,\n     *       type: this.type,\n     *     }),\n     *   ]\n     * },\n     */\n    addPasteRules?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: NodeType\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addPasteRules']\n    }) => PasteRule[]\n\n    /**\n     * This function adds Prosemirror plugins to the editor\n     * @see https://tiptap.dev/guide/custom-extensions#prosemirror-plugins\n     * @example\n     * addProseMirrorPlugins() {\n     *   return [\n     *     customPlugin(),\n     *   ]\n     * }\n     */\n    addProseMirrorPlugins?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: NodeType\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addProseMirrorPlugins']\n    }) => Plugin[]\n\n    /**\n     * This function adds additional extensions to the editor. This is useful for\n     * building extension kits.\n     * @example\n     * addExtensions() {\n     *   return [\n     *     BulletList,\n     *     OrderedList,\n     *     ListItem\n     *   ]\n     * }\n     */\n    addExtensions?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addExtensions']\n    }) => Extensions\n\n    /**\n     * This function extends the schema of the node.\n     * @example\n     * extendNodeSchema() {\n     *   return {\n     *     group: 'inline',\n     *     selectable: false,\n     *   }\n     * }\n     */\n    extendNodeSchema?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<NodeConfig<Options, Storage>>['extendNodeSchema']\n          },\n          extension: Node,\n        ) => Record<string, any>)\n      | null\n\n    /**\n     * This function extends the schema of the mark.\n     * @example\n     * extendMarkSchema() {\n     *   return {\n     *     group: 'inline',\n     *     selectable: false,\n     *   }\n     * }\n     */\n    extendMarkSchema?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<NodeConfig<Options, Storage>>['extendMarkSchema']\n            editor?: Editor\n          },\n          extension: Node,\n        ) => Record<string, any>)\n      | null\n\n    /**\n     * The editor is not ready yet.\n     */\n    onBeforeCreate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: NodeType\n          parent: ParentConfig<NodeConfig<Options, Storage>>['onBeforeCreate']\n        }) => void)\n      | null\n\n    /**\n     * The editor is ready.\n     */\n    onCreate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: NodeType\n          parent: ParentConfig<NodeConfig<Options, Storage>>['onCreate']\n        }) => void)\n      | null\n\n    /**\n     * The content has changed.\n     */\n    onUpdate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: NodeType\n          parent: ParentConfig<NodeConfig<Options, Storage>>['onUpdate']\n        }) => void)\n      | null\n\n    /**\n     * The selection has changed.\n     */\n    onSelectionUpdate?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: NodeType\n          parent: ParentConfig<NodeConfig<Options, Storage>>['onSelectionUpdate']\n        }) => void)\n      | null\n\n    /**\n     * The editor state has changed.\n     */\n    onTransaction?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            type: NodeType\n            parent: ParentConfig<NodeConfig<Options, Storage>>['onTransaction']\n          },\n          props: {\n            editor: Editor\n            transaction: Transaction\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor is focused.\n     */\n    onFocus?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            type: NodeType\n            parent: ParentConfig<NodeConfig<Options, Storage>>['onFocus']\n          },\n          props: {\n            event: FocusEvent\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor isn’t focused anymore.\n     */\n    onBlur?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            editor: Editor\n            type: NodeType\n            parent: ParentConfig<NodeConfig<Options, Storage>>['onBlur']\n          },\n          props: {\n            event: FocusEvent\n          },\n        ) => void)\n      | null\n\n    /**\n     * The editor is destroyed.\n     */\n    onDestroy?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: NodeType\n          parent: ParentConfig<NodeConfig<Options, Storage>>['onDestroy']\n        }) => void)\n      | null\n\n    /**\n     * Node View\n     */\n    addNodeView?:\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: NodeType\n          parent: ParentConfig<NodeConfig<Options, Storage>>['addNodeView']\n        }) => NodeViewRenderer)\n      | null\n\n    /**\n     * Defines if this node should be a top level node (doc)\n     * @default false\n     * @example true\n     */\n    topNode?: boolean\n\n    /**\n     * The content expression for this node, as described in the [schema\n     * guide](/docs/guide/#schema.content_expressions). When not given,\n     * the node does not allow any content.\n     *\n     * You can read more about it on the Prosemirror documentation here\n     * @see https://prosemirror.net/docs/guide/#schema.content_expressions\n     * @default undefined\n     * @example content: 'block+'\n     * @example content: 'headline paragraph block*'\n     */\n    content?:\n      | NodeSpec['content']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['content']\n          editor?: Editor\n        }) => NodeSpec['content'])\n\n    /**\n     * The marks that are allowed inside of this node. May be a\n     * space-separated string referring to mark names or groups, `\"_\"`\n     * to explicitly allow all marks, or `\"\"` to disallow marks. When\n     * not given, nodes with inline content default to allowing all\n     * marks, other nodes default to not allowing marks.\n     *\n     * @example marks: 'strong em'\n     */\n    marks?:\n      | NodeSpec['marks']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['marks']\n          editor?: Editor\n        }) => NodeSpec['marks'])\n\n    /**\n     * The group or space-separated groups to which this node belongs,\n     * which can be referred to in the content expressions for the\n     * schema.\n     *\n     * By default Tiptap uses the groups 'block' and 'inline' for nodes. You\n     * can also use custom groups if you want to group specific nodes together\n     * and handle them in your schema.\n     * @example group: 'block'\n     * @example group: 'inline'\n     * @example group: 'customBlock' // this uses a custom group\n     */\n    group?:\n      | NodeSpec['group']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['group']\n          editor?: Editor\n        }) => NodeSpec['group'])\n\n    /**\n     * Should be set to true for inline nodes. (Implied for text nodes.)\n     */\n    inline?:\n      | NodeSpec['inline']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['inline']\n          editor?: Editor\n        }) => NodeSpec['inline'])\n\n    /**\n     * Can be set to true to indicate that, though this isn't a [leaf\n     * node](https://prosemirror.net/docs/ref/#model.NodeType.isLeaf), it doesn't have directly editable\n     * content and should be treated as a single unit in the view.\n     *\n     * @example atom: true\n     */\n    atom?:\n      | NodeSpec['atom']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['atom']\n          editor?: Editor\n        }) => NodeSpec['atom'])\n\n    /**\n     * Controls whether nodes of this type can be selected as a [node\n     * selection](https://prosemirror.net/docs/ref/#state.NodeSelection). Defaults to true for non-text\n     * nodes.\n     *\n     * @default true\n     * @example selectable: false\n     */\n    selectable?:\n      | NodeSpec['selectable']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['selectable']\n          editor?: Editor\n        }) => NodeSpec['selectable'])\n\n    /**\n     * Determines whether nodes of this type can be dragged without\n     * being selected. Defaults to false.\n     *\n     * @default: false\n     * @example: draggable: true\n     */\n    draggable?:\n      | NodeSpec['draggable']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['draggable']\n          editor?: Editor\n        }) => NodeSpec['draggable'])\n\n    /**\n     * Can be used to indicate that this node contains code, which\n     * causes some commands to behave differently.\n     */\n    code?:\n      | NodeSpec['code']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['code']\n          editor?: Editor\n        }) => NodeSpec['code'])\n\n    /**\n     * Controls way whitespace in this a node is parsed. The default is\n     * `\"normal\"`, which causes the [DOM parser](https://prosemirror.net/docs/ref/#model.DOMParser) to\n     * collapse whitespace in normal mode, and normalize it (replacing\n     * newlines and such with spaces) otherwise. `\"pre\"` causes the\n     * parser to preserve spaces inside the node. When this option isn't\n     * given, but [`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) is true, `whitespace`\n     * will default to `\"pre\"`. Note that this option doesn't influence\n     * the way the node is rendered—that should be handled by `toDOM`\n     * and/or styling.\n     */\n    whitespace?:\n      | NodeSpec['whitespace']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['whitespace']\n          editor?: Editor\n        }) => NodeSpec['whitespace'])\n\n    /**\n     * Allows a **single** node to be set as linebreak equivalent (e.g. hardBreak).\n     * When converting between block types that have whitespace set to \"pre\"\n     * and don't support the linebreak node (e.g. codeBlock) and other block types\n     * that do support the linebreak node (e.g. paragraphs) - this node will be used\n     * as the linebreak instead of stripping the newline.\n     *\n     * See [linebreakReplacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement).\n     */\n    linebreakReplacement?:\n      | NodeSpec['linebreakReplacement']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['linebreakReplacement']\n          editor?: Editor\n        }) => NodeSpec['linebreakReplacement'])\n\n    /**\n     * When enabled, enables both\n     * [`definingAsContext`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext) and\n     * [`definingForContent`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n     *\n     * @default false\n     * @example isolating: true\n     */\n    defining?:\n      | NodeSpec['defining']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['defining']\n          editor?: Editor\n        }) => NodeSpec['defining'])\n\n    /**\n     * When enabled (default is false), the sides of nodes of this type\n     * count as boundaries that regular editing operations, like\n     * backspacing or lifting, won't cross. An example of a node that\n     * should probably have this enabled is a table cell.\n     */\n    isolating?:\n      | NodeSpec['isolating']\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['isolating']\n          editor?: Editor\n        }) => NodeSpec['isolating'])\n\n    /**\n     * Associates DOM parser information with this node, which can be\n     * used by [`DOMParser.fromSchema`](https://prosemirror.net/docs/ref/#model.DOMParser^fromSchema) to\n     * automatically derive a parser. The `node` field in the rules is\n     * implied (the name of this node will be filled in automatically).\n     * If you supply your own parser, you do not need to also specify\n     * parsing rules in your schema.\n     *\n     * @example parseHTML: [{ tag: 'div', attrs: { 'data-id': 'my-block' } }]\n     */\n    parseHTML?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<NodeConfig<Options, Storage>>['parseHTML']\n      editor?: Editor\n    }) => NodeSpec['parseDOM']\n\n    /**\n     * A description of a DOM structure. Can be either a string, which is\n     * interpreted as a text node, a DOM node, which is interpreted as\n     * itself, a `{dom, contentDOM}` object, or an array.\n     *\n     * An array describes a DOM element. The first value in the array\n     * should be a string—the name of the DOM element, optionally prefixed\n     * by a namespace URL and a space. If the second element is plain\n     * object, it is interpreted as a set of attributes for the element.\n     * Any elements after that (including the 2nd if it's not an attribute\n     * object) are interpreted as children of the DOM elements, and must\n     * either be valid `DOMOutputSpec` values, or the number zero.\n     *\n     * The number zero (pronounced “hole”) is used to indicate the place\n     * where a node's child nodes should be inserted. If it occurs in an\n     * output spec, it should be the only child element in its parent\n     * node.\n     *\n     * @example toDOM: ['div[data-id=\"my-block\"]', { class: 'my-block' }, 0]\n     */\n    renderHTML?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<NodeConfig<Options, Storage>>['renderHTML']\n            editor?: Editor\n          },\n          props: {\n            node: ProseMirrorNode\n            HTMLAttributes: Record<string, any>\n          },\n        ) => DOMOutputSpec)\n      | null\n\n    /**\n     * renders the node as text\n     * @example renderText: () => 'foo\n     */\n    renderText?:\n      | ((\n          this: {\n            name: string\n            options: Options\n            storage: Storage\n            parent: ParentConfig<NodeConfig<Options, Storage>>['renderText']\n            editor?: Editor\n          },\n          props: {\n            node: ProseMirrorNode\n            pos: number\n            parent: ProseMirrorNode\n            index: number\n          },\n        ) => string)\n      | null\n\n    /**\n     * Add attributes to the node\n     * @example addAttributes: () => ({ class: 'foo' })\n     */\n    addAttributes?: (this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<NodeConfig<Options, Storage>>['addAttributes']\n      editor?: Editor\n    // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n    }) => Attributes | {}\n  }\n}\n\n/**\n * The Node class is used to create custom node extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Node<Options = any, Storage = any> {\n  type = 'node'\n\n  name = 'node'\n\n  parent: Node | null = null\n\n  child: Node | null = null\n\n  options: Options\n\n  storage: Storage\n\n  config: NodeConfig = {\n    name: this.name,\n    defaultOptions: {},\n  }\n\n  constructor(config: Partial<NodeConfig<Options, Storage>> = {}) {\n    this.config = {\n      ...this.config,\n      ...config,\n    }\n\n    this.name = this.config.name\n\n    if (config.defaultOptions && Object.keys(config.defaultOptions).length > 0) {\n      console.warn(\n        `[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${this.name}\".`,\n      )\n    }\n\n    // TODO: remove `addOptions` fallback\n    this.options = this.config.defaultOptions\n\n    if (this.config.addOptions) {\n      this.options = callOrReturn(\n        getExtensionField<AnyConfig['addOptions']>(this, 'addOptions', {\n          name: this.name,\n        }),\n      )\n    }\n\n    this.storage = callOrReturn(\n      getExtensionField<AnyConfig['addStorage']>(this, 'addStorage', {\n        name: this.name,\n        options: this.options,\n      }),\n    ) || {}\n  }\n\n  static create<O = any, S = any>(config: Partial<NodeConfig<O, S>> = {}) {\n    return new Node<O, S>(config)\n  }\n\n  configure(options: Partial<Options> = {}) {\n    // return a new instance so we can use the same extension\n    // with different calls of `configure`\n    const extension = this.extend<Options, Storage>({\n      ...this.config,\n      addOptions: () => {\n        return mergeDeep(this.options as Record<string, any>, options) as Options\n      },\n    })\n\n    // Always preserve the current name\n    extension.name = this.name\n    // Set the parent to be our parent\n    extension.parent = this.parent\n\n    return extension\n  }\n\n  extend<ExtendedOptions = Options, ExtendedStorage = Storage>(\n    extendedConfig: Partial<NodeConfig<ExtendedOptions, ExtendedStorage>> = {},\n  ) {\n    const extension = new Node<ExtendedOptions, ExtendedStorage>(extendedConfig)\n\n    extension.parent = this\n\n    this.child = extension\n\n    extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name\n\n    if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {\n      console.warn(\n        `[tiptap warn]: BREAKING CHANGE: \"defaultOptions\" is deprecated. Please use \"addOptions\" instead. Found in extension: \"${extension.name}\".`,\n      )\n    }\n\n    extension.options = callOrReturn(\n      getExtensionField<AnyConfig['addOptions']>(extension, 'addOptions', {\n        name: extension.name,\n      }),\n    )\n\n    extension.storage = callOrReturn(\n      getExtensionField<AnyConfig['addStorage']>(extension, 'addStorage', {\n        name: extension.name,\n        options: extension.options,\n      }),\n    )\n\n    return extension\n  }\n}\n", "import { NodeSelection } from '@tiptap/pm/state'\nimport { NodeView as ProseMirrorNodeView, ViewMutationRecord } from '@tiptap/pm/view'\n\nimport { Editor as CoreEditor } from './Editor.js'\nimport { DecorationWithType, NodeViewRendererOptions, NodeViewRendererProps } from './types.js'\nimport { isAndroid } from './utilities/isAndroid.js'\nimport { isiOS } from './utilities/isiOS.js'\n\n/**\n * Node views are used to customize the rendered DOM structure of a node.\n * @see https://tiptap.dev/guide/node-views\n */\nexport class NodeView<\n  Component,\n  NodeEditor extends CoreEditor = CoreEditor,\n  Options extends NodeViewRendererOptions = NodeViewRendererOptions,\n> implements ProseMirrorNodeView {\n  component: Component\n\n  editor: NodeEditor\n\n  options: Options\n\n  extension: NodeViewRendererProps['extension']\n\n  node: NodeViewRendererProps['node']\n\n  decorations: NodeViewRendererProps['decorations']\n\n  innerDecorations: NodeViewRendererProps['innerDecorations']\n\n  view: NodeViewRendererProps['view']\n\n  getPos: NodeViewRendererProps['getPos']\n\n  HTMLAttributes: NodeViewRendererProps['HTMLAttributes']\n\n  isDragging = false\n\n  constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>) {\n    this.component = component\n    this.editor = props.editor as NodeEditor\n    this.options = {\n      stopEvent: null,\n      ignoreMutation: null,\n      ...options,\n    } as Options\n    this.extension = props.extension\n    this.node = props.node\n    this.decorations = props.decorations as DecorationWithType[]\n    this.innerDecorations = props.innerDecorations\n    this.view = props.view\n    this.HTMLAttributes = props.HTMLAttributes\n    this.getPos = props.getPos\n    this.mount()\n  }\n\n  mount() {\n    // eslint-disable-next-line\n    return\n  }\n\n  get dom(): HTMLElement {\n    return this.editor.view.dom as HTMLElement\n  }\n\n  get contentDOM(): HTMLElement | null {\n    return null\n  }\n\n  onDragStart(event: DragEvent) {\n    const { view } = this.editor\n    const target = event.target as HTMLElement\n\n    // get the drag handle element\n    // `closest` is not available for text nodes so we may have to use its parent\n    const dragHandle = target.nodeType === 3\n      ? target.parentElement?.closest('[data-drag-handle]')\n      : target.closest('[data-drag-handle]')\n\n    if (!this.dom || this.contentDOM?.contains(target) || !dragHandle) {\n      return\n    }\n\n    let x = 0\n    let y = 0\n\n    // calculate offset for drag element if we use a different drag handle element\n    if (this.dom !== dragHandle) {\n      const domBox = this.dom.getBoundingClientRect()\n      const handleBox = dragHandle.getBoundingClientRect()\n\n      // In React, we have to go through nativeEvent to reach offsetX/offsetY.\n      const offsetX = event.offsetX ?? (event as any).nativeEvent?.offsetX\n      const offsetY = event.offsetY ?? (event as any).nativeEvent?.offsetY\n\n      x = handleBox.x - domBox.x + offsetX\n      y = handleBox.y - domBox.y + offsetY\n    }\n\n    const clonedNode = this.dom.cloneNode(true) as HTMLElement\n\n    event.dataTransfer?.setDragImage(clonedNode, x, y)\n\n    const pos = this.getPos()\n\n    if (typeof pos !== 'number') {\n      return\n    }\n    // we need to tell ProseMirror that we want to move the whole node\n    // so we create a NodeSelection\n    const selection = NodeSelection.create(view.state.doc, pos)\n    const transaction = view.state.tr.setSelection(selection)\n\n    view.dispatch(transaction)\n  }\n\n  stopEvent(event: Event) {\n    if (!this.dom) {\n      return false\n    }\n\n    if (typeof this.options.stopEvent === 'function') {\n      return this.options.stopEvent({ event })\n    }\n\n    const target = event.target as HTMLElement\n    const isInElement = this.dom.contains(target) && !this.contentDOM?.contains(target)\n\n    // any event from child nodes should be handled by ProseMirror\n    if (!isInElement) {\n      return false\n    }\n\n    const isDragEvent = event.type.startsWith('drag')\n    const isDropEvent = event.type === 'drop'\n    const isInput = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName) || target.isContentEditable\n\n    // any input event within node views should be ignored by ProseMirror\n    if (isInput && !isDropEvent && !isDragEvent) {\n      return true\n    }\n\n    const { isEditable } = this.editor\n    const { isDragging } = this\n    const isDraggable = !!this.node.type.spec.draggable\n    const isSelectable = NodeSelection.isSelectable(this.node)\n    const isCopyEvent = event.type === 'copy'\n    const isPasteEvent = event.type === 'paste'\n    const isCutEvent = event.type === 'cut'\n    const isClickEvent = event.type === 'mousedown'\n\n    // ProseMirror tries to drag selectable nodes\n    // even if `draggable` is set to `false`\n    // this fix prevents that\n    if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) {\n      event.preventDefault()\n    }\n\n    if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) {\n      event.preventDefault()\n      return false\n    }\n\n    // we have to store that dragging started\n    if (isDraggable && isEditable && !isDragging && isClickEvent) {\n      const dragHandle = target.closest('[data-drag-handle]')\n      const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle))\n\n      if (isValidDragHandle) {\n        this.isDragging = true\n\n        document.addEventListener(\n          'dragend',\n          () => {\n            this.isDragging = false\n          },\n          { once: true },\n        )\n\n        document.addEventListener(\n          'drop',\n          () => {\n            this.isDragging = false\n          },\n          { once: true },\n        )\n\n        document.addEventListener(\n          'mouseup',\n          () => {\n            this.isDragging = false\n          },\n          { once: true },\n        )\n      }\n    }\n\n    // these events are handled by prosemirror\n    if (\n      isDragging\n      || isDropEvent\n      || isCopyEvent\n      || isPasteEvent\n      || isCutEvent\n      || (isClickEvent && isSelectable)\n    ) {\n      return false\n    }\n\n    return true\n  }\n\n  /**\n   * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.\n   * @return `false` if the editor should re-read the selection or re-parse the range around the mutation\n   * @return `true` if it can safely be ignored.\n   */\n  ignoreMutation(mutation: ViewMutationRecord) {\n    if (!this.dom || !this.contentDOM) {\n      return true\n    }\n\n    if (typeof this.options.ignoreMutation === 'function') {\n      return this.options.ignoreMutation({ mutation })\n    }\n\n    // a leaf/atom node is like a black box for ProseMirror\n    // and should be fully handled by the node view\n    if (this.node.isLeaf || this.node.isAtom) {\n      return true\n    }\n\n    // ProseMirror should handle any selections\n    if (mutation.type === 'selection') {\n      return false\n    }\n\n    // try to prevent a bug on iOS and Android that will break node views on enter\n    // this is because ProseMirror can’t preventDispatch on enter\n    // this will lead to a re-render of the node view on enter\n    // see: https://github.com/ueberdosis/tiptap/issues/1214\n    // see: https://github.com/ueberdosis/tiptap/issues/2534\n    if (\n      this.dom.contains(mutation.target)\n      && mutation.type === 'childList'\n      && (isiOS() || isAndroid())\n      && this.editor.isFocused\n    ) {\n      const changedNodes = [\n        ...Array.from(mutation.addedNodes),\n        ...Array.from(mutation.removedNodes),\n      ] as HTMLElement[]\n\n      // we’ll check if every changed node is contentEditable\n      // to make sure it’s probably mutated by ProseMirror\n      if (changedNodes.every(node => node.isContentEditable)) {\n        return false\n      }\n    }\n\n    // we will allow mutation contentDOM with attributes\n    // so we can for example adding classes within our node view\n    if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n      return true\n    }\n\n    // ProseMirror should handle any changes within contentDOM\n    if (this.contentDOM.contains(mutation.target)) {\n      return false\n    }\n\n    return true\n  }\n\n  /**\n   * Update the attributes of the prosemirror node.\n   */\n  updateAttributes(attributes: Record<string, any>): void {\n    this.editor.commands.command(({ tr }) => {\n      const pos = this.getPos()\n\n      if (typeof pos !== 'number') {\n        return false\n      }\n\n      tr.setNodeMarkup(pos, undefined, {\n        ...this.node.attrs,\n        ...attributes,\n      })\n\n      return true\n    })\n  }\n\n  /**\n   * Delete the node.\n   */\n  deleteNode(): void {\n    const from = this.getPos()\n\n    if (typeof from !== 'number') {\n      return\n    }\n    const to = from + this.node.nodeSize\n\n    this.editor.commands.deleteRange({ from, to })\n  }\n}\n", "import { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport { PasteRule, PasteRuleFinder } from '../PasteRule.js'\nimport { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an paste rule that adds a mark when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function markPasteRule(config: {\n  find: PasteRuleFinder\n  type: MarkType\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new PasteRule({\n    find: config.find,\n    handler: ({\n      state, range, match, pasteEvent,\n    }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n\n      if (attributes === false || attributes === null) {\n        return null\n      }\n\n      const { tr } = state\n      const captureGroup = match[match.length - 1]\n      const fullMatch = match[0]\n      let markEnd = range.to\n\n      if (captureGroup) {\n        const startSpaces = fullMatch.search(/\\S/)\n        const textStart = range.from + fullMatch.indexOf(captureGroup)\n        const textEnd = textStart + captureGroup.length\n\n        const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n          .filter(item => {\n            // @ts-ignore\n            const excluded = item.mark.type.excluded as MarkType[]\n\n            return excluded.find(type => type === config.type && type !== item.mark.type)\n          })\n          .filter(item => item.to > textStart)\n\n        if (excludedMarks.length) {\n          return null\n        }\n\n        if (textEnd < range.to) {\n          tr.delete(textEnd, range.to)\n        }\n\n        if (textStart > range.from) {\n          tr.delete(range.from + startSpaces, textStart)\n        }\n\n        markEnd = range.from + startSpaces + captureGroup.length\n\n        tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n        tr.removeStoredMark(config.type)\n      }\n    },\n  })\n}\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\n\nexport function canInsertNode(state: EditorState, nodeType: NodeType): boolean {\n  const { selection } = state\n  const { $from } = selection\n\n  // Special handling for NodeSelection\n  if (selection instanceof NodeSelection) {\n    const index = $from.index()\n    const parent = $from.parent\n\n    // Can we replace the selected node with the horizontal rule?\n    return parent.canReplaceWith(index, index + 1, nodeType)\n  }\n\n  // Default: check if we can insert at the current position\n  let depth = $from.depth\n\n  while (depth >= 0) {\n    const index = $from.index(depth)\n    const parent = $from.node(depth)\n    const match = parent.contentMatchAt(index)\n\n    if (match.matchType(nodeType)) {\n      return true\n    }\n    depth -= 1\n  }\n  return false\n}\n", "// source: https://stackoverflow.com/a/6969486\nexport function escapeForRegEx(string: string): string {\n  return string.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n}\n", "export function isString(value: any): value is string {\n  return typeof value === 'string'\n}\n", "import { NodeType } from '@tiptap/pm/model'\n\nimport { PasteRule, PasteRuleFinder } from '../PasteRule.js'\nimport { ExtendedRegExpMatchArray, JSONContent } from '../types.js'\nimport { callOrReturn } from '../utilities/index.js'\n\n/**\n * Build an paste rule that adds a node when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function nodePasteRule(config: {\n  find: PasteRuleFinder\n  type: NodeType\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n    | false\n    | null\n  getContent?:\n    | JSONContent[]\n    | ((attrs: Record<string, any>) => JSONContent[])\n    | false\n    | null\n}) {\n  return new PasteRule({\n    find: config.find,\n    handler({\n      match, chain, range, pasteEvent,\n    }) {\n      const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n      const content = callOrReturn(config.getContent, undefined, attributes)\n\n      if (attributes === false || attributes === null) {\n        return null\n      }\n\n      const node = { type: config.type.name, attrs: attributes } as JSONContent\n\n      if (content) {\n        node.content = content\n      }\n\n      if (match.input) {\n        chain().deleteRange(range).insertContentAt(range.from, node)\n      }\n    },\n  })\n}\n", "import { PasteRule, PasteRuleFinder } from '../PasteRule.js'\n\n/**\n * Build an paste rule that replaces text when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function textPasteRule(config: {\n  find: PasteRuleFinder,\n  replace: string,\n}) {\n  return new PasteRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      let insert = config.replace\n      let start = range.from\n      const end = range.to\n\n      if (match[1]) {\n        const offset = match[0].lastIndexOf(match[1])\n\n        insert += match[0].slice(offset + match[1].length)\n        start += offset\n\n        const cutOff = start - end\n\n        if (cutOff > 0) {\n          insert = match[0].slice(offset - cutOff, offset) + insert\n          start = end\n        }\n      }\n\n      state.tr.insertText(insert, start, end)\n    },\n  })\n}\n", "import { Transaction } from '@tiptap/pm/state'\n\nexport interface TrackerResult {\n  position: number\n  deleted: boolean\n}\n\nexport class Tracker {\n  transaction: Transaction\n\n  currentStep: number\n\n  constructor(transaction: Transaction) {\n    this.transaction = transaction\n    this.currentStep = this.transaction.steps.length\n  }\n\n  map(position: number): TrackerResult {\n    let deleted = false\n\n    const mappedPosition = this.transaction.steps\n      .slice(this.currentStep)\n      .reduce((newPosition, step) => {\n        const mapResult = step.getMap().mapResult(newPosition)\n\n        if (mapResult.deleted) {\n          deleted = true\n        }\n\n        return mapResult.pos\n      }, position)\n\n    return {\n      position: mappedPosition,\n      deleted,\n    }\n  }\n}\n", "export var top = 'top';\nexport var bottom = 'bottom';\nexport var right = 'right';\nexport var left = 'left';\nexport var auto = 'auto';\nexport var basePlacements = [top, bottom, right, left];\nexport var start = 'start';\nexport var end = 'end';\nexport var clippingParents = 'clippingParents';\nexport var viewport = 'viewport';\nexport var popper = 'popper';\nexport var reference = 'reference';\nexport var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {\n  return acc.concat([placement + \"-\" + start, placement + \"-\" + end]);\n}, []);\nexport var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {\n  return acc.concat([placement, placement + \"-\" + start, placement + \"-\" + end]);\n}, []); // modifiers that need to read the DOM\n\nexport var beforeRead = 'beforeRead';\nexport var read = 'read';\nexport var afterRead = 'afterRead'; // pure-logic modifiers\n\nexport var beforeMain = 'beforeMain';\nexport var main = 'main';\nexport var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)\n\nexport var beforeWrite = 'beforeWrite';\nexport var write = 'write';\nexport var afterWrite = 'afterWrite';\nexport var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];", "export default function getNodeName(element) {\n  return element ? (element.nodeName || '').toLowerCase() : null;\n}", "export default function getWindow(node) {\n  if (node == null) {\n    return window;\n  }\n\n  if (node.toString() !== '[object Window]') {\n    var ownerDocument = node.ownerDocument;\n    return ownerDocument ? ownerDocument.defaultView || window : window;\n  }\n\n  return node;\n}", "import getWindow from \"./getWindow.js\";\n\nfunction isElement(node) {\n  var OwnElement = getWindow(node).Element;\n  return node instanceof OwnElement || node instanceof Element;\n}\n\nfunction isHTMLElement(node) {\n  var OwnElement = getWindow(node).HTMLElement;\n  return node instanceof OwnElement || node instanceof HTMLElement;\n}\n\nfunction isShadowRoot(node) {\n  // IE 11 has no ShadowRoot\n  if (typeof ShadowRoot === 'undefined') {\n    return false;\n  }\n\n  var OwnElement = getWindow(node).ShadowRoot;\n  return node instanceof OwnElement || node instanceof ShadowRoot;\n}\n\nexport { isElement, isHTMLElement, isShadowRoot };", "import getNodeName from \"../dom-utils/getNodeName.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // This modifier takes the styles prepared by the `computeStyles` modifier\n// and applies them to the HTMLElements such as popper and arrow\n\nfunction applyStyles(_ref) {\n  var state = _ref.state;\n  Object.keys(state.elements).forEach(function (name) {\n    var style = state.styles[name] || {};\n    var attributes = state.attributes[name] || {};\n    var element = state.elements[name]; // arrow is optional + virtual elements\n\n    if (!isHTMLElement(element) || !getNodeName(element)) {\n      return;\n    } // Flow doesn't support to extend this property, but it's the most\n    // effective way to apply styles to an HTMLElement\n    // $FlowFixMe[cannot-write]\n\n\n    Object.assign(element.style, style);\n    Object.keys(attributes).forEach(function (name) {\n      var value = attributes[name];\n\n      if (value === false) {\n        element.removeAttribute(name);\n      } else {\n        element.setAttribute(name, value === true ? '' : value);\n      }\n    });\n  });\n}\n\nfunction effect(_ref2) {\n  var state = _ref2.state;\n  var initialStyles = {\n    popper: {\n      position: state.options.strategy,\n      left: '0',\n      top: '0',\n      margin: '0'\n    },\n    arrow: {\n      position: 'absolute'\n    },\n    reference: {}\n  };\n  Object.assign(state.elements.popper.style, initialStyles.popper);\n  state.styles = initialStyles;\n\n  if (state.elements.arrow) {\n    Object.assign(state.elements.arrow.style, initialStyles.arrow);\n  }\n\n  return function () {\n    Object.keys(state.elements).forEach(function (name) {\n      var element = state.elements[name];\n      var attributes = state.attributes[name] || {};\n      var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them\n\n      var style = styleProperties.reduce(function (style, property) {\n        style[property] = '';\n        return style;\n      }, {}); // arrow is optional + virtual elements\n\n      if (!isHTMLElement(element) || !getNodeName(element)) {\n        return;\n      }\n\n      Object.assign(element.style, style);\n      Object.keys(attributes).forEach(function (attribute) {\n        element.removeAttribute(attribute);\n      });\n    });\n  };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'applyStyles',\n  enabled: true,\n  phase: 'write',\n  fn: applyStyles,\n  effect: effect,\n  requires: ['computeStyles']\n};", "import { auto } from \"../enums.js\";\nexport default function getBasePlacement(placement) {\n  return placement.split('-')[0];\n}", "export var max = Math.max;\nexport var min = Math.min;\nexport var round = Math.round;", "export default function getUAString() {\n  var uaData = navigator.userAgentData;\n\n  if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {\n    return uaData.brands.map(function (item) {\n      return item.brand + \"/\" + item.version;\n    }).join(' ');\n  }\n\n  return navigator.userAgent;\n}", "import getUAString from \"../utils/userAgent.js\";\nexport default function isLayoutViewport() {\n  return !/^((?!chrome|android).)*safari/i.test(getUAString());\n}", "import { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport { round } from \"../utils/math.js\";\nimport getWindow from \"./getWindow.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getBoundingClientRect(element, includeScale, isFixedStrategy) {\n  if (includeScale === void 0) {\n    includeScale = false;\n  }\n\n  if (isFixedStrategy === void 0) {\n    isFixedStrategy = false;\n  }\n\n  var clientRect = element.getBoundingClientRect();\n  var scaleX = 1;\n  var scaleY = 1;\n\n  if (includeScale && isHTMLElement(element)) {\n    scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;\n    scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;\n  }\n\n  var _ref = isElement(element) ? getWindow(element) : window,\n      visualViewport = _ref.visualViewport;\n\n  var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;\n  var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;\n  var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;\n  var width = clientRect.width / scaleX;\n  var height = clientRect.height / scaleY;\n  return {\n    width: width,\n    height: height,\n    top: y,\n    right: x + width,\n    bottom: y + height,\n    left: x,\n    x: x,\n    y: y\n  };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\"; // Returns the layout rect of an element relative to its offsetParent. Layout\n// means it doesn't take into account transforms.\n\nexport default function getLayoutRect(element) {\n  var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.\n  // Fixes https://github.com/popperjs/popper-core/issues/1223\n\n  var width = element.offsetWidth;\n  var height = element.offsetHeight;\n\n  if (Math.abs(clientRect.width - width) <= 1) {\n    width = clientRect.width;\n  }\n\n  if (Math.abs(clientRect.height - height) <= 1) {\n    height = clientRect.height;\n  }\n\n  return {\n    x: element.offsetLeft,\n    y: element.offsetTop,\n    width: width,\n    height: height\n  };\n}", "import { isShadowRoot } from \"./instanceOf.js\";\nexport default function contains(parent, child) {\n  var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method\n\n  if (parent.contains(child)) {\n    return true;\n  } // then fallback to custom implementation with Shadow DOM support\n  else if (rootNode && isShadowRoot(rootNode)) {\n      var next = child;\n\n      do {\n        if (next && parent.isSameNode(next)) {\n          return true;\n        } // $FlowFixMe[prop-missing]: need a better way to handle this...\n\n\n        next = next.parentNode || next.host;\n      } while (next);\n    } // Give up, the result is false\n\n\n  return false;\n}", "import getWindow from \"./getWindow.js\";\nexport default function getComputedStyle(element) {\n  return getWindow(element).getComputedStyle(element);\n}", "import getNodeName from \"./getNodeName.js\";\nexport default function isTableElement(element) {\n  return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;\n}", "import { isElement } from \"./instanceOf.js\";\nexport default function getDocumentElement(element) {\n  // $FlowFixMe[incompatible-return]: assume body is always available\n  return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]\n  element.document) || window.document).documentElement;\n}", "import getNodeName from \"./getNodeName.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport { isShadowRoot } from \"./instanceOf.js\";\nexport default function getParentNode(element) {\n  if (getNodeName(element) === 'html') {\n    return element;\n  }\n\n  return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle\n    // $FlowFixMe[incompatible-return]\n    // $FlowFixMe[prop-missing]\n    element.assignedSlot || // step into the shadow DOM of the parent of a slotted node\n    element.parentNode || ( // DOM Element detected\n    isShadowRoot(element) ? element.host : null) || // ShadowRoot detected\n    // $FlowFixMe[incompatible-call]: HTMLElement is a Node\n    getDocumentElement(element) // fallback\n\n  );\n}", "import getWindow from \"./getWindow.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isHTMLElement, isShadowRoot } from \"./instanceOf.js\";\nimport isTableElement from \"./isTableElement.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getUAString from \"../utils/userAgent.js\";\n\nfunction getTrueOffsetParent(element) {\n  if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837\n  getComputedStyle(element).position === 'fixed') {\n    return null;\n  }\n\n  return element.offsetParent;\n} // `.offsetParent` reports `null` for fixed elements, while absolute elements\n// return the containing block\n\n\nfunction getContainingBlock(element) {\n  var isFirefox = /firefox/i.test(getUAString());\n  var isIE = /Trident/i.test(getUAString());\n\n  if (isIE && isHTMLElement(element)) {\n    // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport\n    var elementCss = getComputedStyle(element);\n\n    if (elementCss.position === 'fixed') {\n      return null;\n    }\n  }\n\n  var currentNode = getParentNode(element);\n\n  if (isShadowRoot(currentNode)) {\n    currentNode = currentNode.host;\n  }\n\n  while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {\n    var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that\n    // create a containing block.\n    // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n\n    if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {\n      return currentNode;\n    } else {\n      currentNode = currentNode.parentNode;\n    }\n  }\n\n  return null;\n} // Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\n\n\nexport default function getOffsetParent(element) {\n  var window = getWindow(element);\n  var offsetParent = getTrueOffsetParent(element);\n\n  while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n    offsetParent = getTrueOffsetParent(offsetParent);\n  }\n\n  if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {\n    return window;\n  }\n\n  return offsetParent || getContainingBlock(element) || window;\n}", "export default function getMainAxisFromPlacement(placement) {\n  return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';\n}", "import { max as mathMax, min as mathMin } from \"./math.js\";\nexport function within(min, value, max) {\n  return mathMax(min, mathMin(value, max));\n}\nexport function withinMaxClamp(min, value, max) {\n  var v = within(min, value, max);\n  return v > max ? max : v;\n}", "export default function getFreshSideObject() {\n  return {\n    top: 0,\n    right: 0,\n    bottom: 0,\n    left: 0\n  };\n}", "import getFreshSideObject from \"./getFreshSideObject.js\";\nexport default function mergePaddingObject(paddingObject) {\n  return Object.assign({}, getFreshSideObject(), paddingObject);\n}", "export default function expandToHashMap(value, keys) {\n  return keys.reduce(function (hashMap, key) {\n    hashMap[key] = value;\n    return hashMap;\n  }, {});\n}", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport contains from \"../dom-utils/contains.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport { within } from \"../utils/within.js\";\nimport mergePaddingObject from \"../utils/mergePaddingObject.js\";\nimport expandToHashMap from \"../utils/expandToHashMap.js\";\nimport { left, right, basePlacements, top, bottom } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar toPaddingObject = function toPaddingObject(padding, state) {\n  padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {\n    placement: state.placement\n  })) : padding;\n  return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n};\n\nfunction arrow(_ref) {\n  var _state$modifiersData$;\n\n  var state = _ref.state,\n      name = _ref.name,\n      options = _ref.options;\n  var arrowElement = state.elements.arrow;\n  var popperOffsets = state.modifiersData.popperOffsets;\n  var basePlacement = getBasePlacement(state.placement);\n  var axis = getMainAxisFromPlacement(basePlacement);\n  var isVertical = [left, right].indexOf(basePlacement) >= 0;\n  var len = isVertical ? 'height' : 'width';\n\n  if (!arrowElement || !popperOffsets) {\n    return;\n  }\n\n  var paddingObject = toPaddingObject(options.padding, state);\n  var arrowRect = getLayoutRect(arrowElement);\n  var minProp = axis === 'y' ? top : left;\n  var maxProp = axis === 'y' ? bottom : right;\n  var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];\n  var startDiff = popperOffsets[axis] - state.rects.reference[axis];\n  var arrowOffsetParent = getOffsetParent(arrowElement);\n  var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;\n  var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is\n  // outside of the popper bounds\n\n  var min = paddingObject[minProp];\n  var max = clientSize - arrowRect[len] - paddingObject[maxProp];\n  var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;\n  var offset = within(min, center, max); // Prevents breaking syntax highlighting...\n\n  var axisProp = axis;\n  state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);\n}\n\nfunction effect(_ref2) {\n  var state = _ref2.state,\n      options = _ref2.options;\n  var _options$element = options.element,\n      arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;\n\n  if (arrowElement == null) {\n    return;\n  } // CSS selector\n\n\n  if (typeof arrowElement === 'string') {\n    arrowElement = state.elements.popper.querySelector(arrowElement);\n\n    if (!arrowElement) {\n      return;\n    }\n  }\n\n  if (!contains(state.elements.popper, arrowElement)) {\n    return;\n  }\n\n  state.elements.arrow = arrowElement;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'arrow',\n  enabled: true,\n  phase: 'main',\n  fn: arrow,\n  effect: effect,\n  requires: ['popperOffsets'],\n  requiresIfExists: ['preventOverflow']\n};", "export default function getVariation(placement) {\n  return placement.split('-')[1];\n}", "import { top, left, right, bottom, end } from \"../enums.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getWindow from \"../dom-utils/getWindow.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getComputedStyle from \"../dom-utils/getComputedStyle.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport { round } from \"../utils/math.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar unsetSides = {\n  top: 'auto',\n  right: 'auto',\n  bottom: 'auto',\n  left: 'auto'\n}; // Round the offsets to the nearest suitable subpixel based on the DPR.\n// Zooming can change the DPR, but it seems to report a value that will\n// cleanly divide the values into the appropriate subpixels.\n\nfunction roundOffsetsByDPR(_ref, win) {\n  var x = _ref.x,\n      y = _ref.y;\n  var dpr = win.devicePixelRatio || 1;\n  return {\n    x: round(x * dpr) / dpr || 0,\n    y: round(y * dpr) / dpr || 0\n  };\n}\n\nexport function mapToStyles(_ref2) {\n  var _Object$assign2;\n\n  var popper = _ref2.popper,\n      popperRect = _ref2.popperRect,\n      placement = _ref2.placement,\n      variation = _ref2.variation,\n      offsets = _ref2.offsets,\n      position = _ref2.position,\n      gpuAcceleration = _ref2.gpuAcceleration,\n      adaptive = _ref2.adaptive,\n      roundOffsets = _ref2.roundOffsets,\n      isFixed = _ref2.isFixed;\n  var _offsets$x = offsets.x,\n      x = _offsets$x === void 0 ? 0 : _offsets$x,\n      _offsets$y = offsets.y,\n      y = _offsets$y === void 0 ? 0 : _offsets$y;\n\n  var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({\n    x: x,\n    y: y\n  }) : {\n    x: x,\n    y: y\n  };\n\n  x = _ref3.x;\n  y = _ref3.y;\n  var hasX = offsets.hasOwnProperty('x');\n  var hasY = offsets.hasOwnProperty('y');\n  var sideX = left;\n  var sideY = top;\n  var win = window;\n\n  if (adaptive) {\n    var offsetParent = getOffsetParent(popper);\n    var heightProp = 'clientHeight';\n    var widthProp = 'clientWidth';\n\n    if (offsetParent === getWindow(popper)) {\n      offsetParent = getDocumentElement(popper);\n\n      if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {\n        heightProp = 'scrollHeight';\n        widthProp = 'scrollWidth';\n      }\n    } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it\n\n\n    offsetParent = offsetParent;\n\n    if (placement === top || (placement === left || placement === right) && variation === end) {\n      sideY = bottom;\n      var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]\n      offsetParent[heightProp];\n      y -= offsetY - popperRect.height;\n      y *= gpuAcceleration ? 1 : -1;\n    }\n\n    if (placement === left || (placement === top || placement === bottom) && variation === end) {\n      sideX = right;\n      var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]\n      offsetParent[widthProp];\n      x -= offsetX - popperRect.width;\n      x *= gpuAcceleration ? 1 : -1;\n    }\n  }\n\n  var commonStyles = Object.assign({\n    position: position\n  }, adaptive && unsetSides);\n\n  var _ref4 = roundOffsets === true ? roundOffsetsByDPR({\n    x: x,\n    y: y\n  }, getWindow(popper)) : {\n    x: x,\n    y: y\n  };\n\n  x = _ref4.x;\n  y = _ref4.y;\n\n  if (gpuAcceleration) {\n    var _Object$assign;\n\n    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? \"translate(\" + x + \"px, \" + y + \"px)\" : \"translate3d(\" + x + \"px, \" + y + \"px, 0)\", _Object$assign));\n  }\n\n  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + \"px\" : '', _Object$assign2[sideX] = hasX ? x + \"px\" : '', _Object$assign2.transform = '', _Object$assign2));\n}\n\nfunction computeStyles(_ref5) {\n  var state = _ref5.state,\n      options = _ref5.options;\n  var _options$gpuAccelerat = options.gpuAcceleration,\n      gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,\n      _options$adaptive = options.adaptive,\n      adaptive = _options$adaptive === void 0 ? true : _options$adaptive,\n      _options$roundOffsets = options.roundOffsets,\n      roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;\n  var commonStyles = {\n    placement: getBasePlacement(state.placement),\n    variation: getVariation(state.placement),\n    popper: state.elements.popper,\n    popperRect: state.rects.popper,\n    gpuAcceleration: gpuAcceleration,\n    isFixed: state.options.strategy === 'fixed'\n  };\n\n  if (state.modifiersData.popperOffsets != null) {\n    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {\n      offsets: state.modifiersData.popperOffsets,\n      position: state.options.strategy,\n      adaptive: adaptive,\n      roundOffsets: roundOffsets\n    })));\n  }\n\n  if (state.modifiersData.arrow != null) {\n    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {\n      offsets: state.modifiersData.arrow,\n      position: 'absolute',\n      adaptive: false,\n      roundOffsets: roundOffsets\n    })));\n  }\n\n  state.attributes.popper = Object.assign({}, state.attributes.popper, {\n    'data-popper-placement': state.placement\n  });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'computeStyles',\n  enabled: true,\n  phase: 'beforeWrite',\n  fn: computeStyles,\n  data: {}\n};", "import getWindow from \"../dom-utils/getWindow.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar passive = {\n  passive: true\n};\n\nfunction effect(_ref) {\n  var state = _ref.state,\n      instance = _ref.instance,\n      options = _ref.options;\n  var _options$scroll = options.scroll,\n      scroll = _options$scroll === void 0 ? true : _options$scroll,\n      _options$resize = options.resize,\n      resize = _options$resize === void 0 ? true : _options$resize;\n  var window = getWindow(state.elements.popper);\n  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);\n\n  if (scroll) {\n    scrollParents.forEach(function (scrollParent) {\n      scrollParent.addEventListener('scroll', instance.update, passive);\n    });\n  }\n\n  if (resize) {\n    window.addEventListener('resize', instance.update, passive);\n  }\n\n  return function () {\n    if (scroll) {\n      scrollParents.forEach(function (scrollParent) {\n        scrollParent.removeEventListener('scroll', instance.update, passive);\n      });\n    }\n\n    if (resize) {\n      window.removeEventListener('resize', instance.update, passive);\n    }\n  };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'eventListeners',\n  enabled: true,\n  phase: 'write',\n  fn: function fn() {},\n  effect: effect,\n  data: {}\n};", "var hash = {\n  left: 'right',\n  right: 'left',\n  bottom: 'top',\n  top: 'bottom'\n};\nexport default function getOppositePlacement(placement) {\n  return placement.replace(/left|right|bottom|top/g, function (matched) {\n    return hash[matched];\n  });\n}", "var hash = {\n  start: 'end',\n  end: 'start'\n};\nexport default function getOppositeVariationPlacement(placement) {\n  return placement.replace(/start|end/g, function (matched) {\n    return hash[matched];\n  });\n}", "import getWindow from \"./getWindow.js\";\nexport default function getWindowScroll(node) {\n  var win = getWindow(node);\n  var scrollLeft = win.pageXOffset;\n  var scrollTop = win.pageYOffset;\n  return {\n    scrollLeft: scrollLeft,\n    scrollTop: scrollTop\n  };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nexport default function getWindowScrollBarX(element) {\n  // If <html> has a CSS width greater than the viewport, then this will be\n  // incorrect for RTL.\n  // Popper 1 is broken in this case and never had a bug report so let's assume\n  // it's not an issue. I don't think anyone ever specifies width on <html>\n  // anyway.\n  // Browsers where the left scrollbar doesn't cause an issue report `0` for\n  // this (e.g. Edge 2019, IE11, Safari)\n  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;\n}", "import getWindow from \"./getWindow.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getViewportRect(element, strategy) {\n  var win = getWindow(element);\n  var html = getDocumentElement(element);\n  var visualViewport = win.visualViewport;\n  var width = html.clientWidth;\n  var height = html.clientHeight;\n  var x = 0;\n  var y = 0;\n\n  if (visualViewport) {\n    width = visualViewport.width;\n    height = visualViewport.height;\n    var layoutViewport = isLayoutViewport();\n\n    if (layoutViewport || !layoutViewport && strategy === 'fixed') {\n      x = visualViewport.offsetLeft;\n      y = visualViewport.offsetTop;\n    }\n  }\n\n  return {\n    width: width,\n    height: height,\n    x: x + getWindowScrollBarX(element),\n    y: y\n  };\n}", "import getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nimport { max } from \"../utils/math.js\"; // Gets the entire size of the scrollable document area, even extending outside\n// of the `<html>` and `<body>` rect bounds if horizontally scrollable\n\nexport default function getDocumentRect(element) {\n  var _element$ownerDocumen;\n\n  var html = getDocumentElement(element);\n  var winScroll = getWindowScroll(element);\n  var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;\n  var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);\n  var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);\n  var x = -winScroll.scrollLeft + getWindowScrollBarX(element);\n  var y = -winScroll.scrollTop;\n\n  if (getComputedStyle(body || html).direction === 'rtl') {\n    x += max(html.clientWidth, body ? body.clientWidth : 0) - width;\n  }\n\n  return {\n    width: width,\n    height: height,\n    x: x,\n    y: y\n  };\n}", "import getComputedStyle from \"./getComputedStyle.js\";\nexport default function isScrollParent(element) {\n  // Firefox wants us to check `-x` and `-y` variations as well\n  var _getComputedStyle = getComputedStyle(element),\n      overflow = _getComputedStyle.overflow,\n      overflowX = _getComputedStyle.overflowX,\n      overflowY = _getComputedStyle.overflowY;\n\n  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);\n}", "import getParentNode from \"./getParentNode.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nexport default function getScrollParent(node) {\n  if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {\n    // $FlowFixMe[incompatible-return]: assume body is always available\n    return node.ownerDocument.body;\n  }\n\n  if (isHTMLElement(node) && isScrollParent(node)) {\n    return node;\n  }\n\n  return getScrollParent(getParentNode(node));\n}", "import getScrollParent from \"./getScrollParent.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getWindow from \"./getWindow.js\";\nimport isScrollParent from \"./isScrollParent.js\";\n/*\ngiven a DOM element, return the list of all scroll parents, up the list of ancesors\nuntil we get to the top window object. This list is what we attach scroll listeners\nto, because if any of these parent elements scroll, we'll need to re-calculate the\nreference element's position.\n*/\n\nexport default function listScrollParents(element, list) {\n  var _element$ownerDocumen;\n\n  if (list === void 0) {\n    list = [];\n  }\n\n  var scrollParent = getScrollParent(element);\n  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);\n  var win = getWindow(scrollParent);\n  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;\n  var updatedList = list.concat(target);\n  return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here\n  updatedList.concat(listScrollParents(getParentNode(target)));\n}", "export default function rectToClientRect(rect) {\n  return Object.assign({}, rect, {\n    left: rect.x,\n    top: rect.y,\n    right: rect.x + rect.width,\n    bottom: rect.y + rect.height\n  });\n}", "import { viewport } from \"../enums.js\";\nimport getViewportRect from \"./getViewportRect.js\";\nimport getDocumentRect from \"./getDocumentRect.js\";\nimport listScrollParents from \"./listScrollParents.js\";\nimport getOffsetParent from \"./getOffsetParent.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport contains from \"./contains.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport rectToClientRect from \"../utils/rectToClientRect.js\";\nimport { max, min } from \"../utils/math.js\";\n\nfunction getInnerBoundingClientRect(element, strategy) {\n  var rect = getBoundingClientRect(element, false, strategy === 'fixed');\n  rect.top = rect.top + element.clientTop;\n  rect.left = rect.left + element.clientLeft;\n  rect.bottom = rect.top + element.clientHeight;\n  rect.right = rect.left + element.clientWidth;\n  rect.width = element.clientWidth;\n  rect.height = element.clientHeight;\n  rect.x = rect.left;\n  rect.y = rect.top;\n  return rect;\n}\n\nfunction getClientRectFromMixedType(element, clippingParent, strategy) {\n  return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));\n} // A \"clipping parent\" is an overflowable container with the characteristic of\n// clipping (or hiding) overflowing elements with a position different from\n// `initial`\n\n\nfunction getClippingParents(element) {\n  var clippingParents = listScrollParents(getParentNode(element));\n  var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;\n  var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;\n\n  if (!isElement(clipperElement)) {\n    return [];\n  } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414\n\n\n  return clippingParents.filter(function (clippingParent) {\n    return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';\n  });\n} // Gets the maximum area that the element is visible in due to any number of\n// clipping parents\n\n\nexport default function getClippingRect(element, boundary, rootBoundary, strategy) {\n  var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);\n  var clippingParents = [].concat(mainClippingParents, [rootBoundary]);\n  var firstClippingParent = clippingParents[0];\n  var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {\n    var rect = getClientRectFromMixedType(element, clippingParent, strategy);\n    accRect.top = max(rect.top, accRect.top);\n    accRect.right = min(rect.right, accRect.right);\n    accRect.bottom = min(rect.bottom, accRect.bottom);\n    accRect.left = max(rect.left, accRect.left);\n    return accRect;\n  }, getClientRectFromMixedType(element, firstClippingParent, strategy));\n  clippingRect.width = clippingRect.right - clippingRect.left;\n  clippingRect.height = clippingRect.bottom - clippingRect.top;\n  clippingRect.x = clippingRect.left;\n  clippingRect.y = clippingRect.top;\n  return clippingRect;\n}", "import getBasePlacement from \"./getBasePlacement.js\";\nimport getVariation from \"./getVariation.js\";\nimport getMainAxisFromPlacement from \"./getMainAxisFromPlacement.js\";\nimport { top, right, bottom, left, start, end } from \"../enums.js\";\nexport default function computeOffsets(_ref) {\n  var reference = _ref.reference,\n      element = _ref.element,\n      placement = _ref.placement;\n  var basePlacement = placement ? getBasePlacement(placement) : null;\n  var variation = placement ? getVariation(placement) : null;\n  var commonX = reference.x + reference.width / 2 - element.width / 2;\n  var commonY = reference.y + reference.height / 2 - element.height / 2;\n  var offsets;\n\n  switch (basePlacement) {\n    case top:\n      offsets = {\n        x: commonX,\n        y: reference.y - element.height\n      };\n      break;\n\n    case bottom:\n      offsets = {\n        x: commonX,\n        y: reference.y + reference.height\n      };\n      break;\n\n    case right:\n      offsets = {\n        x: reference.x + reference.width,\n        y: commonY\n      };\n      break;\n\n    case left:\n      offsets = {\n        x: reference.x - element.width,\n        y: commonY\n      };\n      break;\n\n    default:\n      offsets = {\n        x: reference.x,\n        y: reference.y\n      };\n  }\n\n  var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;\n\n  if (mainAxis != null) {\n    var len = mainAxis === 'y' ? 'height' : 'width';\n\n    switch (variation) {\n      case start:\n        offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);\n        break;\n\n      case end:\n        offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);\n        break;\n\n      default:\n    }\n  }\n\n  return offsets;\n}", "import getClippingRect from \"../dom-utils/getClippingRect.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getBoundingClientRect from \"../dom-utils/getBoundingClientRect.js\";\nimport computeOffsets from \"./computeOffsets.js\";\nimport rectToClientRect from \"./rectToClientRect.js\";\nimport { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from \"../enums.js\";\nimport { isElement } from \"../dom-utils/instanceOf.js\";\nimport mergePaddingObject from \"./mergePaddingObject.js\";\nimport expandToHashMap from \"./expandToHashMap.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport default function detectOverflow(state, options) {\n  if (options === void 0) {\n    options = {};\n  }\n\n  var _options = options,\n      _options$placement = _options.placement,\n      placement = _options$placement === void 0 ? state.placement : _options$placement,\n      _options$strategy = _options.strategy,\n      strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,\n      _options$boundary = _options.boundary,\n      boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,\n      _options$rootBoundary = _options.rootBoundary,\n      rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,\n      _options$elementConte = _options.elementContext,\n      elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,\n      _options$altBoundary = _options.altBoundary,\n      altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,\n      _options$padding = _options.padding,\n      padding = _options$padding === void 0 ? 0 : _options$padding;\n  var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n  var altContext = elementContext === popper ? reference : popper;\n  var popperRect = state.rects.popper;\n  var element = state.elements[altBoundary ? altContext : elementContext];\n  var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);\n  var referenceClientRect = getBoundingClientRect(state.elements.reference);\n  var popperOffsets = computeOffsets({\n    reference: referenceClientRect,\n    element: popperRect,\n    strategy: 'absolute',\n    placement: placement\n  });\n  var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));\n  var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect\n  // 0 or negative = within the clipping rect\n\n  var overflowOffsets = {\n    top: clippingClientRect.top - elementClientRect.top + paddingObject.top,\n    bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,\n    left: clippingClientRect.left - elementClientRect.left + paddingObject.left,\n    right: elementClientRect.right - clippingClientRect.right + paddingObject.right\n  };\n  var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element\n\n  if (elementContext === popper && offsetData) {\n    var offset = offsetData[placement];\n    Object.keys(overflowOffsets).forEach(function (key) {\n      var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;\n      var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';\n      overflowOffsets[key] += offset[axis] * multiply;\n    });\n  }\n\n  return overflowOffsets;\n}", "import getVariation from \"./getVariation.js\";\nimport { variationPlacements, basePlacements, placements as allPlacements } from \"../enums.js\";\nimport detectOverflow from \"./detectOverflow.js\";\nimport getBasePlacement from \"./getBasePlacement.js\";\nexport default function computeAutoPlacement(state, options) {\n  if (options === void 0) {\n    options = {};\n  }\n\n  var _options = options,\n      placement = _options.placement,\n      boundary = _options.boundary,\n      rootBoundary = _options.rootBoundary,\n      padding = _options.padding,\n      flipVariations = _options.flipVariations,\n      _options$allowedAutoP = _options.allowedAutoPlacements,\n      allowedAutoPlacements = _options$allowedAutoP === void 0 ? allPlacements : _options$allowedAutoP;\n  var variation = getVariation(placement);\n  var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {\n    return getVariation(placement) === variation;\n  }) : basePlacements;\n  var allowedPlacements = placements.filter(function (placement) {\n    return allowedAutoPlacements.indexOf(placement) >= 0;\n  });\n\n  if (allowedPlacements.length === 0) {\n    allowedPlacements = placements;\n  } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...\n\n\n  var overflows = allowedPlacements.reduce(function (acc, placement) {\n    acc[placement] = detectOverflow(state, {\n      placement: placement,\n      boundary: boundary,\n      rootBoundary: rootBoundary,\n      padding: padding\n    })[getBasePlacement(placement)];\n    return acc;\n  }, {});\n  return Object.keys(overflows).sort(function (a, b) {\n    return overflows[a] - overflows[b];\n  });\n}", "import getOppositePlacement from \"../utils/getOppositePlacement.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getOppositeVariationPlacement from \"../utils/getOppositeVariationPlacement.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport computeAutoPlacement from \"../utils/computeAutoPlacement.js\";\nimport { bottom, top, start, right, left, auto } from \"../enums.js\";\nimport getVariation from \"../utils/getVariation.js\"; // eslint-disable-next-line import/no-unused-modules\n\nfunction getExpandedFallbackPlacements(placement) {\n  if (getBasePlacement(placement) === auto) {\n    return [];\n  }\n\n  var oppositePlacement = getOppositePlacement(placement);\n  return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];\n}\n\nfunction flip(_ref) {\n  var state = _ref.state,\n      options = _ref.options,\n      name = _ref.name;\n\n  if (state.modifiersData[name]._skip) {\n    return;\n  }\n\n  var _options$mainAxis = options.mainAxis,\n      checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n      _options$altAxis = options.altAxis,\n      checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,\n      specifiedFallbackPlacements = options.fallbackPlacements,\n      padding = options.padding,\n      boundary = options.boundary,\n      rootBoundary = options.rootBoundary,\n      altBoundary = options.altBoundary,\n      _options$flipVariatio = options.flipVariations,\n      flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,\n      allowedAutoPlacements = options.allowedAutoPlacements;\n  var preferredPlacement = state.options.placement;\n  var basePlacement = getBasePlacement(preferredPlacement);\n  var isBasePlacement = basePlacement === preferredPlacement;\n  var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));\n  var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {\n    return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {\n      placement: placement,\n      boundary: boundary,\n      rootBoundary: rootBoundary,\n      padding: padding,\n      flipVariations: flipVariations,\n      allowedAutoPlacements: allowedAutoPlacements\n    }) : placement);\n  }, []);\n  var referenceRect = state.rects.reference;\n  var popperRect = state.rects.popper;\n  var checksMap = new Map();\n  var makeFallbackChecks = true;\n  var firstFittingPlacement = placements[0];\n\n  for (var i = 0; i < placements.length; i++) {\n    var placement = placements[i];\n\n    var _basePlacement = getBasePlacement(placement);\n\n    var isStartVariation = getVariation(placement) === start;\n    var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;\n    var len = isVertical ? 'width' : 'height';\n    var overflow = detectOverflow(state, {\n      placement: placement,\n      boundary: boundary,\n      rootBoundary: rootBoundary,\n      altBoundary: altBoundary,\n      padding: padding\n    });\n    var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;\n\n    if (referenceRect[len] > popperRect[len]) {\n      mainVariationSide = getOppositePlacement(mainVariationSide);\n    }\n\n    var altVariationSide = getOppositePlacement(mainVariationSide);\n    var checks = [];\n\n    if (checkMainAxis) {\n      checks.push(overflow[_basePlacement] <= 0);\n    }\n\n    if (checkAltAxis) {\n      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);\n    }\n\n    if (checks.every(function (check) {\n      return check;\n    })) {\n      firstFittingPlacement = placement;\n      makeFallbackChecks = false;\n      break;\n    }\n\n    checksMap.set(placement, checks);\n  }\n\n  if (makeFallbackChecks) {\n    // `2` may be desired in some cases \u2013 research later\n    var numberOfChecks = flipVariations ? 3 : 1;\n\n    var _loop = function _loop(_i) {\n      var fittingPlacement = placements.find(function (placement) {\n        var checks = checksMap.get(placement);\n\n        if (checks) {\n          return checks.slice(0, _i).every(function (check) {\n            return check;\n          });\n        }\n      });\n\n      if (fittingPlacement) {\n        firstFittingPlacement = fittingPlacement;\n        return \"break\";\n      }\n    };\n\n    for (var _i = numberOfChecks; _i > 0; _i--) {\n      var _ret = _loop(_i);\n\n      if (_ret === \"break\") break;\n    }\n  }\n\n  if (state.placement !== firstFittingPlacement) {\n    state.modifiersData[name]._skip = true;\n    state.placement = firstFittingPlacement;\n    state.reset = true;\n  }\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'flip',\n  enabled: true,\n  phase: 'main',\n  fn: flip,\n  requiresIfExists: ['offset'],\n  data: {\n    _skip: false\n  }\n};", "import { top, bottom, left, right } from \"../enums.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\n\nfunction getSideOffsets(overflow, rect, preventedOffsets) {\n  if (preventedOffsets === void 0) {\n    preventedOffsets = {\n      x: 0,\n      y: 0\n    };\n  }\n\n  return {\n    top: overflow.top - rect.height - preventedOffsets.y,\n    right: overflow.right - rect.width + preventedOffsets.x,\n    bottom: overflow.bottom - rect.height + preventedOffsets.y,\n    left: overflow.left - rect.width - preventedOffsets.x\n  };\n}\n\nfunction isAnySideFullyClipped(overflow) {\n  return [top, right, bottom, left].some(function (side) {\n    return overflow[side] >= 0;\n  });\n}\n\nfunction hide(_ref) {\n  var state = _ref.state,\n      name = _ref.name;\n  var referenceRect = state.rects.reference;\n  var popperRect = state.rects.popper;\n  var preventedOffsets = state.modifiersData.preventOverflow;\n  var referenceOverflow = detectOverflow(state, {\n    elementContext: 'reference'\n  });\n  var popperAltOverflow = detectOverflow(state, {\n    altBoundary: true\n  });\n  var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);\n  var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);\n  var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);\n  var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);\n  state.modifiersData[name] = {\n    referenceClippingOffsets: referenceClippingOffsets,\n    popperEscapeOffsets: popperEscapeOffsets,\n    isReferenceHidden: isReferenceHidden,\n    hasPopperEscaped: hasPopperEscaped\n  };\n  state.attributes.popper = Object.assign({}, state.attributes.popper, {\n    'data-popper-reference-hidden': isReferenceHidden,\n    'data-popper-escaped': hasPopperEscaped\n  });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'hide',\n  enabled: true,\n  phase: 'main',\n  requiresIfExists: ['preventOverflow'],\n  fn: hide\n};", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport { top, left, right, placements } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport function distanceAndSkiddingToXY(placement, rects, offset) {\n  var basePlacement = getBasePlacement(placement);\n  var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;\n\n  var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {\n    placement: placement\n  })) : offset,\n      skidding = _ref[0],\n      distance = _ref[1];\n\n  skidding = skidding || 0;\n  distance = (distance || 0) * invertDistance;\n  return [left, right].indexOf(basePlacement) >= 0 ? {\n    x: distance,\n    y: skidding\n  } : {\n    x: skidding,\n    y: distance\n  };\n}\n\nfunction offset(_ref2) {\n  var state = _ref2.state,\n      options = _ref2.options,\n      name = _ref2.name;\n  var _options$offset = options.offset,\n      offset = _options$offset === void 0 ? [0, 0] : _options$offset;\n  var data = placements.reduce(function (acc, placement) {\n    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);\n    return acc;\n  }, {});\n  var _data$state$placement = data[state.placement],\n      x = _data$state$placement.x,\n      y = _data$state$placement.y;\n\n  if (state.modifiersData.popperOffsets != null) {\n    state.modifiersData.popperOffsets.x += x;\n    state.modifiersData.popperOffsets.y += y;\n  }\n\n  state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'offset',\n  enabled: true,\n  phase: 'main',\n  requires: ['popperOffsets'],\n  fn: offset\n};", "import computeOffsets from \"../utils/computeOffsets.js\";\n\nfunction popperOffsets(_ref) {\n  var state = _ref.state,\n      name = _ref.name;\n  // Offsets are the actual position the popper needs to have to be\n  // properly positioned near its reference element\n  // This is the most basic placement, and will be adjusted by\n  // the modifiers in the next step\n  state.modifiersData[name] = computeOffsets({\n    reference: state.rects.reference,\n    element: state.rects.popper,\n    strategy: 'absolute',\n    placement: state.placement\n  });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'popperOffsets',\n  enabled: true,\n  phase: 'read',\n  fn: popperOffsets,\n  data: {}\n};", "export default function getAltAxis(axis) {\n  return axis === 'x' ? 'y' : 'x';\n}", "import { top, left, right, bottom, start } from \"../enums.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport getAltAxis from \"../utils/getAltAxis.js\";\nimport { within, withinMaxClamp } from \"../utils/within.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport getFreshSideObject from \"../utils/getFreshSideObject.js\";\nimport { min as mathMin, max as mathMax } from \"../utils/math.js\";\n\nfunction preventOverflow(_ref) {\n  var state = _ref.state,\n      options = _ref.options,\n      name = _ref.name;\n  var _options$mainAxis = options.mainAxis,\n      checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n      _options$altAxis = options.altAxis,\n      checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,\n      boundary = options.boundary,\n      rootBoundary = options.rootBoundary,\n      altBoundary = options.altBoundary,\n      padding = options.padding,\n      _options$tether = options.tether,\n      tether = _options$tether === void 0 ? true : _options$tether,\n      _options$tetherOffset = options.tetherOffset,\n      tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;\n  var overflow = detectOverflow(state, {\n    boundary: boundary,\n    rootBoundary: rootBoundary,\n    padding: padding,\n    altBoundary: altBoundary\n  });\n  var basePlacement = getBasePlacement(state.placement);\n  var variation = getVariation(state.placement);\n  var isBasePlacement = !variation;\n  var mainAxis = getMainAxisFromPlacement(basePlacement);\n  var altAxis = getAltAxis(mainAxis);\n  var popperOffsets = state.modifiersData.popperOffsets;\n  var referenceRect = state.rects.reference;\n  var popperRect = state.rects.popper;\n  var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {\n    placement: state.placement\n  })) : tetherOffset;\n  var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {\n    mainAxis: tetherOffsetValue,\n    altAxis: tetherOffsetValue\n  } : Object.assign({\n    mainAxis: 0,\n    altAxis: 0\n  }, tetherOffsetValue);\n  var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;\n  var data = {\n    x: 0,\n    y: 0\n  };\n\n  if (!popperOffsets) {\n    return;\n  }\n\n  if (checkMainAxis) {\n    var _offsetModifierState$;\n\n    var mainSide = mainAxis === 'y' ? top : left;\n    var altSide = mainAxis === 'y' ? bottom : right;\n    var len = mainAxis === 'y' ? 'height' : 'width';\n    var offset = popperOffsets[mainAxis];\n    var min = offset + overflow[mainSide];\n    var max = offset - overflow[altSide];\n    var additive = tether ? -popperRect[len] / 2 : 0;\n    var minLen = variation === start ? referenceRect[len] : popperRect[len];\n    var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go\n    // outside the reference bounds\n\n    var arrowElement = state.elements.arrow;\n    var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {\n      width: 0,\n      height: 0\n    };\n    var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();\n    var arrowPaddingMin = arrowPaddingObject[mainSide];\n    var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want\n    // to include its full size in the calculation. If the reference is small\n    // and near the edge of a boundary, the popper can overflow even if the\n    // reference is not overflowing as well (e.g. virtual elements with no\n    // width or height)\n\n    var arrowLen = within(0, referenceRect[len], arrowRect[len]);\n    var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;\n    var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;\n    var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);\n    var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;\n    var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;\n    var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;\n    var tetherMax = offset + maxOffset - offsetModifierValue;\n    var preventedOffset = within(tether ? mathMin(min, tetherMin) : min, offset, tether ? mathMax(max, tetherMax) : max);\n    popperOffsets[mainAxis] = preventedOffset;\n    data[mainAxis] = preventedOffset - offset;\n  }\n\n  if (checkAltAxis) {\n    var _offsetModifierState$2;\n\n    var _mainSide = mainAxis === 'x' ? top : left;\n\n    var _altSide = mainAxis === 'x' ? bottom : right;\n\n    var _offset = popperOffsets[altAxis];\n\n    var _len = altAxis === 'y' ? 'height' : 'width';\n\n    var _min = _offset + overflow[_mainSide];\n\n    var _max = _offset - overflow[_altSide];\n\n    var isOriginSide = [top, left].indexOf(basePlacement) !== -1;\n\n    var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;\n\n    var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;\n\n    var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;\n\n    var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);\n\n    popperOffsets[altAxis] = _preventedOffset;\n    data[altAxis] = _preventedOffset - _offset;\n  }\n\n  state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n  name: 'preventOverflow',\n  enabled: true,\n  phase: 'main',\n  fn: preventOverflow,\n  requiresIfExists: ['offset']\n};", "export default function getHTMLElementScroll(element) {\n  return {\n    scrollLeft: element.scrollLeft,\n    scrollTop: element.scrollTop\n  };\n}", "import getWindowScroll from \"./getWindowScroll.js\";\nimport getWindow from \"./getWindow.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getHTMLElementScroll from \"./getHTMLElementScroll.js\";\nexport default function getNodeScroll(node) {\n  if (node === getWindow(node) || !isHTMLElement(node)) {\n    return getWindowScroll(node);\n  } else {\n    return getHTMLElementScroll(node);\n  }\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getNodeScroll from \"./getNodeScroll.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport { round } from \"../utils/math.js\";\n\nfunction isElementScaled(element) {\n  var rect = element.getBoundingClientRect();\n  var scaleX = round(rect.width) / element.offsetWidth || 1;\n  var scaleY = round(rect.height) / element.offsetHeight || 1;\n  return scaleX !== 1 || scaleY !== 1;\n} // Returns the composite rect of an element relative to its offsetParent.\n// Composite means it takes into account transforms as well as layout.\n\n\nexport default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {\n  if (isFixed === void 0) {\n    isFixed = false;\n  }\n\n  var isOffsetParentAnElement = isHTMLElement(offsetParent);\n  var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);\n  var documentElement = getDocumentElement(offsetParent);\n  var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);\n  var scroll = {\n    scrollLeft: 0,\n    scrollTop: 0\n  };\n  var offsets = {\n    x: 0,\n    y: 0\n  };\n\n  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n    if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078\n    isScrollParent(documentElement)) {\n      scroll = getNodeScroll(offsetParent);\n    }\n\n    if (isHTMLElement(offsetParent)) {\n      offsets = getBoundingClientRect(offsetParent, true);\n      offsets.x += offsetParent.clientLeft;\n      offsets.y += offsetParent.clientTop;\n    } else if (documentElement) {\n      offsets.x = getWindowScrollBarX(documentElement);\n    }\n  }\n\n  return {\n    x: rect.left + scroll.scrollLeft - offsets.x,\n    y: rect.top + scroll.scrollTop - offsets.y,\n    width: rect.width,\n    height: rect.height\n  };\n}", "import { modifierPhases } from \"../enums.js\"; // source: https://stackoverflow.com/questions/49875255\n\nfunction order(modifiers) {\n  var map = new Map();\n  var visited = new Set();\n  var result = [];\n  modifiers.forEach(function (modifier) {\n    map.set(modifier.name, modifier);\n  }); // On visiting object, check for its dependencies and visit them recursively\n\n  function sort(modifier) {\n    visited.add(modifier.name);\n    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);\n    requires.forEach(function (dep) {\n      if (!visited.has(dep)) {\n        var depModifier = map.get(dep);\n\n        if (depModifier) {\n          sort(depModifier);\n        }\n      }\n    });\n    result.push(modifier);\n  }\n\n  modifiers.forEach(function (modifier) {\n    if (!visited.has(modifier.name)) {\n      // check for visited object\n      sort(modifier);\n    }\n  });\n  return result;\n}\n\nexport default function orderModifiers(modifiers) {\n  // order based on dependencies\n  var orderedModifiers = order(modifiers); // order based on phase\n\n  return modifierPhases.reduce(function (acc, phase) {\n    return acc.concat(orderedModifiers.filter(function (modifier) {\n      return modifier.phase === phase;\n    }));\n  }, []);\n}", "export default function debounce(fn) {\n  var pending;\n  return function () {\n    if (!pending) {\n      pending = new Promise(function (resolve) {\n        Promise.resolve().then(function () {\n          pending = undefined;\n          resolve(fn());\n        });\n      });\n    }\n\n    return pending;\n  };\n}", "export default function mergeByName(modifiers) {\n  var merged = modifiers.reduce(function (merged, current) {\n    var existing = merged[current.name];\n    merged[current.name] = existing ? Object.assign({}, existing, current, {\n      options: Object.assign({}, existing.options, current.options),\n      data: Object.assign({}, existing.data, current.data)\n    }) : current;\n    return merged;\n  }, {}); // IE11 does not support Object.values\n\n  return Object.keys(merged).map(function (key) {\n    return merged[key];\n  });\n}", "import getCompositeRect from \"./dom-utils/getCompositeRect.js\";\nimport getLayoutRect from \"./dom-utils/getLayoutRect.js\";\nimport listScrollParents from \"./dom-utils/listScrollParents.js\";\nimport getOffsetParent from \"./dom-utils/getOffsetParent.js\";\nimport orderModifiers from \"./utils/orderModifiers.js\";\nimport debounce from \"./utils/debounce.js\";\nimport mergeByName from \"./utils/mergeByName.js\";\nimport detectOverflow from \"./utils/detectOverflow.js\";\nimport { isElement } from \"./dom-utils/instanceOf.js\";\nvar DEFAULT_OPTIONS = {\n  placement: 'bottom',\n  modifiers: [],\n  strategy: 'absolute'\n};\n\nfunction areValidElements() {\n  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n    args[_key] = arguments[_key];\n  }\n\n  return !args.some(function (element) {\n    return !(element && typeof element.getBoundingClientRect === 'function');\n  });\n}\n\nexport function popperGenerator(generatorOptions) {\n  if (generatorOptions === void 0) {\n    generatorOptions = {};\n  }\n\n  var _generatorOptions = generatorOptions,\n      _generatorOptions$def = _generatorOptions.defaultModifiers,\n      defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,\n      _generatorOptions$def2 = _generatorOptions.defaultOptions,\n      defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;\n  return function createPopper(reference, popper, options) {\n    if (options === void 0) {\n      options = defaultOptions;\n    }\n\n    var state = {\n      placement: 'bottom',\n      orderedModifiers: [],\n      options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),\n      modifiersData: {},\n      elements: {\n        reference: reference,\n        popper: popper\n      },\n      attributes: {},\n      styles: {}\n    };\n    var effectCleanupFns = [];\n    var isDestroyed = false;\n    var instance = {\n      state: state,\n      setOptions: function setOptions(setOptionsAction) {\n        var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;\n        cleanupModifierEffects();\n        state.options = Object.assign({}, defaultOptions, state.options, options);\n        state.scrollParents = {\n          reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],\n          popper: listScrollParents(popper)\n        }; // Orders the modifiers based on their dependencies and `phase`\n        // properties\n\n        var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers\n\n        state.orderedModifiers = orderedModifiers.filter(function (m) {\n          return m.enabled;\n        });\n        runModifierEffects();\n        return instance.update();\n      },\n      // Sync update \u2013 it will always be executed, even if not necessary. This\n      // is useful for low frequency updates where sync behavior simplifies the\n      // logic.\n      // For high frequency updates (e.g. `resize` and `scroll` events), always\n      // prefer the async Popper#update method\n      forceUpdate: function forceUpdate() {\n        if (isDestroyed) {\n          return;\n        }\n\n        var _state$elements = state.elements,\n            reference = _state$elements.reference,\n            popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements\n        // anymore\n\n        if (!areValidElements(reference, popper)) {\n          return;\n        } // Store the reference and popper rects to be read by modifiers\n\n\n        state.rects = {\n          reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),\n          popper: getLayoutRect(popper)\n        }; // Modifiers have the ability to reset the current update cycle. The\n        // most common use case for this is the `flip` modifier changing the\n        // placement, which then needs to re-run all the modifiers, because the\n        // logic was previously ran for the previous placement and is therefore\n        // stale/incorrect\n\n        state.reset = false;\n        state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier\n        // is filled with the initial data specified by the modifier. This means\n        // it doesn't persist and is fresh on each update.\n        // To ensure persistent data, use `${name}#persistent`\n\n        state.orderedModifiers.forEach(function (modifier) {\n          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);\n        });\n\n        for (var index = 0; index < state.orderedModifiers.length; index++) {\n          if (state.reset === true) {\n            state.reset = false;\n            index = -1;\n            continue;\n          }\n\n          var _state$orderedModifie = state.orderedModifiers[index],\n              fn = _state$orderedModifie.fn,\n              _state$orderedModifie2 = _state$orderedModifie.options,\n              _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,\n              name = _state$orderedModifie.name;\n\n          if (typeof fn === 'function') {\n            state = fn({\n              state: state,\n              options: _options,\n              name: name,\n              instance: instance\n            }) || state;\n          }\n        }\n      },\n      // Async and optimistically optimized update \u2013 it will not be executed if\n      // not necessary (debounced to run at most once-per-tick)\n      update: debounce(function () {\n        return new Promise(function (resolve) {\n          instance.forceUpdate();\n          resolve(state);\n        });\n      }),\n      destroy: function destroy() {\n        cleanupModifierEffects();\n        isDestroyed = true;\n      }\n    };\n\n    if (!areValidElements(reference, popper)) {\n      return instance;\n    }\n\n    instance.setOptions(options).then(function (state) {\n      if (!isDestroyed && options.onFirstUpdate) {\n        options.onFirstUpdate(state);\n      }\n    }); // Modifiers have the ability to execute arbitrary code before the first\n    // update cycle runs. They will be executed in the same order as the update\n    // cycle. This is useful when a modifier adds some persistent data that\n    // other modifiers need to use, but the modifier is run after the dependent\n    // one.\n\n    function runModifierEffects() {\n      state.orderedModifiers.forEach(function (_ref) {\n        var name = _ref.name,\n            _ref$options = _ref.options,\n            options = _ref$options === void 0 ? {} : _ref$options,\n            effect = _ref.effect;\n\n        if (typeof effect === 'function') {\n          var cleanupFn = effect({\n            state: state,\n            name: name,\n            instance: instance,\n            options: options\n          });\n\n          var noopFn = function noopFn() {};\n\n          effectCleanupFns.push(cleanupFn || noopFn);\n        }\n      });\n    }\n\n    function cleanupModifierEffects() {\n      effectCleanupFns.forEach(function (fn) {\n        return fn();\n      });\n      effectCleanupFns = [];\n    }\n\n    return instance;\n  };\n}\nexport var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules\n\nexport { detectOverflow };", "import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nimport offset from \"./modifiers/offset.js\";\nimport flip from \"./modifiers/flip.js\";\nimport preventOverflow from \"./modifiers/preventOverflow.js\";\nimport arrow from \"./modifiers/arrow.js\";\nimport hide from \"./modifiers/hide.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles, offset, flip, preventOverflow, arrow, hide];\nvar createPopper = /*#__PURE__*/popperGenerator({\n  defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow }; // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper as createPopperLite } from \"./popper-lite.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport * from \"./modifiers/index.js\";", "export const ROUND_ARROW =\n  '<svg width=\"16\" height=\"6\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 6s1.796-.013 4.67-3.615C5.851.9 6.93.006 8 0c1.07-.006 2.148.887 3.343 2.385C14.233 6.005 16 6 16 6H0z\"></svg>';\n\nexport const BOX_CLASS = `__NAMESPACE_PREFIX__-box`;\nexport const CONTENT_CLASS = `__NAMESPACE_PREFIX__-content`;\nexport const BACKDROP_CLASS = `__NAMESPACE_PREFIX__-backdrop`;\nexport const ARROW_CLASS = `__NAMESPACE_PREFIX__-arrow`;\nexport const SVG_ARROW_CLASS = `__NAMESPACE_PREFIX__-svg-arrow`;\n\nexport const TOUCH_OPTIONS = {passive: true, capture: true};\n\nexport const TIPPY_DEFAULT_APPEND_TO = () => document.body;\n", "import {BasePlacement, Placement} from './types';\n\nexport function hasOwnProperty(\n  obj: Record<string, unknown>,\n  key: string\n): boolean {\n  return {}.hasOwnProperty.call(obj, key);\n}\n\nexport function getValueAtIndexOrReturn<T>(\n  value: T | [T | null, T | null],\n  index: number,\n  defaultValue: T | [T, T]\n): T {\n  if (Array.isArray(value)) {\n    const v = value[index];\n    return v == null\n      ? Array.isArray(defaultValue)\n        ? defaultValue[index]\n        : defaultValue\n      : v;\n  }\n\n  return value;\n}\n\nexport function isType(value: any, type: string): boolean {\n  const str = {}.toString.call(value);\n  return str.indexOf('[object') === 0 && str.indexOf(`${type}]`) > -1;\n}\n\nexport function invokeWithArgsOrReturn(value: any, args: any[]): any {\n  return typeof value === 'function' ? value(...args) : value;\n}\n\nexport function debounce<T>(\n  fn: (arg: T) => void,\n  ms: number\n): (arg: T) => void {\n  // Avoid wrapping in `setTimeout` if ms is 0 anyway\n  if (ms === 0) {\n    return fn;\n  }\n\n  let timeout: any;\n\n  return (arg): void => {\n    clearTimeout(timeout);\n    timeout = setTimeout(() => {\n      fn(arg);\n    }, ms);\n  };\n}\n\nexport function removeProperties<T>(obj: T, keys: string[]): Partial<T> {\n  const clone = {...obj};\n  keys.forEach((key) => {\n    delete (clone as any)[key];\n  });\n  return clone;\n}\n\nexport function splitBySpaces(value: string): string[] {\n  return value.split(/\\s+/).filter(Boolean);\n}\n\nexport function normalizeToArray<T>(value: T | T[]): T[] {\n  return ([] as T[]).concat(value);\n}\n\nexport function pushIfUnique<T>(arr: T[], value: T): void {\n  if (arr.indexOf(value) === -1) {\n    arr.push(value);\n  }\n}\n\nexport function appendPxIfNumber(value: string | number): string {\n  return typeof value === 'number' ? `${value}px` : value;\n}\n\nexport function unique<T>(arr: T[]): T[] {\n  return arr.filter((item, index) => arr.indexOf(item) === index);\n}\n\nexport function getNumber(value: string | number): number {\n  return typeof value === 'number' ? value : parseFloat(value);\n}\n\nexport function getBasePlacement(placement: Placement): BasePlacement {\n  return placement.split('-')[0] as BasePlacement;\n}\n\nexport function arrayFrom(value: ArrayLike<any>): any[] {\n  return [].slice.call(value);\n}\n\nexport function removeUndefinedProps(\n  obj: Record<string, unknown>\n): Partial<Record<string, unknown>> {\n  return Object.keys(obj).reduce((acc, key) => {\n    if (obj[key] !== undefined) {\n      (acc as any)[key] = obj[key];\n    }\n\n    return acc;\n  }, {});\n}\n", "import {ReferenceElement, Targets} from './types';\nimport {PopperTreeData} from './types-internal';\nimport {arrayFrom, isType, normalizeToArray, getBasePlacement} from './utils';\n\nexport function div(): HTMLDivElement {\n  return document.createElement('div');\n}\n\nexport function isElement(value: unknown): value is Element | DocumentFragment {\n  return ['Element', 'Fragment'].some((type) => isType(value, type));\n}\n\nexport function isNodeList(value: unknown): value is NodeList {\n  return isType(value, 'NodeList');\n}\n\nexport function isMouseEvent(value: unknown): value is MouseEvent {\n  return isType(value, 'MouseEvent');\n}\n\nexport function isReferenceElement(value: any): value is ReferenceElement {\n  return !!(value && value._tippy && value._tippy.reference === value);\n}\n\nexport function getArrayOfElements(value: Targets): Element[] {\n  if (isElement(value)) {\n    return [value];\n  }\n\n  if (isNodeList(value)) {\n    return arrayFrom(value);\n  }\n\n  if (Array.isArray(value)) {\n    return value;\n  }\n\n  return arrayFrom(document.querySelectorAll(value));\n}\n\nexport function setTransitionDuration(\n  els: (HTMLDivElement | null)[],\n  value: number\n): void {\n  els.forEach((el) => {\n    if (el) {\n      el.style.transitionDuration = `${value}ms`;\n    }\n  });\n}\n\nexport function setVisibilityState(\n  els: (HTMLDivElement | null)[],\n  state: 'visible' | 'hidden'\n): void {\n  els.forEach((el) => {\n    if (el) {\n      el.setAttribute('data-state', state);\n    }\n  });\n}\n\nexport function getOwnerDocument(\n  elementOrElements: Element | Element[]\n): Document {\n  const [element] = normalizeToArray(elementOrElements);\n\n  // Elements created via a <template> have an ownerDocument with no reference to the body\n  return element?.ownerDocument?.body ? element.ownerDocument : document;\n}\n\nexport function isCursorOutsideInteractiveBorder(\n  popperTreeData: PopperTreeData[],\n  event: MouseEvent\n): boolean {\n  const {clientX, clientY} = event;\n\n  return popperTreeData.every(({popperRect, popperState, props}) => {\n    const {interactiveBorder} = props;\n    const basePlacement = getBasePlacement(popperState.placement);\n    const offsetData = popperState.modifiersData.offset;\n\n    if (!offsetData) {\n      return true;\n    }\n\n    const topDistance = basePlacement === 'bottom' ? offsetData.top!.y : 0;\n    const bottomDistance = basePlacement === 'top' ? offsetData.bottom!.y : 0;\n    const leftDistance = basePlacement === 'right' ? offsetData.left!.x : 0;\n    const rightDistance = basePlacement === 'left' ? offsetData.right!.x : 0;\n\n    const exceedsTop =\n      popperRect.top - clientY + topDistance > interactiveBorder;\n    const exceedsBottom =\n      clientY - popperRect.bottom - bottomDistance > interactiveBorder;\n    const exceedsLeft =\n      popperRect.left - clientX + leftDistance > interactiveBorder;\n    const exceedsRight =\n      clientX - popperRect.right - rightDistance > interactiveBorder;\n\n    return exceedsTop || exceedsBottom || exceedsLeft || exceedsRight;\n  });\n}\n\nexport function updateTransitionEndListener(\n  box: HTMLDivElement,\n  action: 'add' | 'remove',\n  listener: (event: TransitionEvent) => void\n): void {\n  const method = `${action}EventListener` as\n    | 'addEventListener'\n    | 'removeEventListener';\n\n  // some browsers apparently support `transition` (unprefixed) but only fire\n  // `webkitTransitionEnd`...\n  ['transitionend', 'webkitTransitionEnd'].forEach((event) => {\n    box[method](event, listener as EventListener);\n  });\n}\n\n/**\n * Compared to xxx.contains, this function works for dom structures with shadow\n * dom\n */\nexport function actualContains(parent: Element, child: Element): boolean {\n  let target = child;\n  while (target) {\n    if (parent.contains(target)) {\n      return true;\n    }\n    target = (target.getRootNode?.() as any)?.host;\n  }\n  return false;\n}\n", "import {TOUCH_OPTIONS} from './constants';\nimport {isReferenceElement} from './dom-utils';\n\nexport const currentInput = {isTouch: false};\nlet lastMouseMoveTime = 0;\n\n/**\n * When a `touchstart` event is fired, it's assumed the user is using touch\n * input. We'll bind a `mousemove` event listener to listen for mouse input in\n * the future. This way, the `isTouch` property is fully dynamic and will handle\n * hybrid devices that use a mix of touch + mouse input.\n */\nexport function onDocumentTouchStart(): void {\n  if (currentInput.isTouch) {\n    return;\n  }\n\n  currentInput.isTouch = true;\n\n  if (window.performance) {\n    document.addEventListener('mousemove', onDocumentMouseMove);\n  }\n}\n\n/**\n * When two `mousemove` event are fired consecutively within 20ms, it's assumed\n * the user is using mouse input again. `mousemove` can fire on touch devices as\n * well, but very rarely that quickly.\n */\nexport function onDocumentMouseMove(): void {\n  const now = performance.now();\n\n  if (now - lastMouseMoveTime < 20) {\n    currentInput.isTouch = false;\n\n    document.removeEventListener('mousemove', onDocumentMouseMove);\n  }\n\n  lastMouseMoveTime = now;\n}\n\n/**\n * When an element is in focus and has a tippy, leaving the tab/window and\n * returning causes it to show again. For mouse users this is unexpected, but\n * for keyboard use it makes sense.\n * TODO: find a better technique to solve this problem\n */\nexport function onWindowBlur(): void {\n  const activeElement = document.activeElement as HTMLElement | null;\n\n  if (isReferenceElement(activeElement)) {\n    const instance = activeElement._tippy!;\n\n    if (activeElement.blur && !instance.state.isVisible) {\n      activeElement.blur();\n    }\n  }\n}\n\nexport default function bindGlobalEventListeners(): void {\n  document.addEventListener('touchstart', onDocumentTouchStart, TOUCH_OPTIONS);\n  window.addEventListener('blur', onWindowBlur);\n}\n", "export const isBrowser =\n  typeof window !== 'undefined' && typeof document !== 'undefined';\n\nexport const isIE11 = isBrowser\n  ? // @ts-ignore\n    !!window.msCrypto\n  : false;\n", "import {Targets} from './types';\n\nexport function createMemoryLeakWarning(method: string): string {\n  const txt = method === 'destroy' ? 'n already-' : ' ';\n\n  return [\n    `${method}() was called on a${txt}destroyed instance. This is a no-op but`,\n    'indicates a potential memory leak.',\n  ].join(' ');\n}\n\nexport function clean(value: string): string {\n  const spacesAndTabs = /[ \\t]{2,}/g;\n  const lineStartWithSpaces = /^[ \\t]*/gm;\n\n  return value\n    .replace(spacesAndTabs, ' ')\n    .replace(lineStartWithSpaces, '')\n    .trim();\n}\n\nfunction getDevMessage(message: string): string {\n  return clean(`\n  %ctippy.js\n\n  %c${clean(message)}\n\n  %c👷‍ This is a development-only message. It will be removed in production.\n  `);\n}\n\nexport function getFormattedMessage(message: string): string[] {\n  return [\n    getDevMessage(message),\n    // title\n    'color: #00C584; font-size: 1.3em; font-weight: bold;',\n    // message\n    'line-height: 1.5',\n    // footer\n    'color: #a6a095;',\n  ];\n}\n\n// Assume warnings and errors never have the same message\nlet visitedMessages: Set<string>;\nif (__DEV__) {\n  resetVisitedMessages();\n}\n\nexport function resetVisitedMessages(): void {\n  visitedMessages = new Set();\n}\n\nexport function warnWhen(condition: boolean, message: string): void {\n  if (condition && !visitedMessages.has(message)) {\n    visitedMessages.add(message);\n    console.warn(...getFormattedMessage(message));\n  }\n}\n\nexport function errorWhen(condition: boolean, message: string): void {\n  if (condition && !visitedMessages.has(message)) {\n    visitedMessages.add(message);\n    console.error(...getFormattedMessage(message));\n  }\n}\n\nexport function validateTargets(targets: Targets): void {\n  const didPassFalsyValue = !targets;\n  const didPassPlainObject =\n    Object.prototype.toString.call(targets) === '[object Object]' &&\n    !(targets as any).addEventListener;\n\n  errorWhen(\n    didPassFalsyValue,\n    [\n      'tippy() was passed',\n      '`' + String(targets) + '`',\n      'as its targets (first) argument. Valid types are: String, Element,',\n      'Element[], or NodeList.',\n    ].join(' ')\n  );\n\n  errorWhen(\n    didPassPlainObject,\n    [\n      'tippy() was passed a plain object which is not supported as an argument',\n      'for virtual positioning. Use props.getReferenceClientRect instead.',\n    ].join(' ')\n  );\n}\n", "import {DefaultProps, Plugin, Props, ReferenceElement, Tippy} from './types';\nimport {\n  hasOwnProperty,\n  removeProperties,\n  invokeWithArgsOrReturn,\n} from './utils';\nimport {warnWhen} from './validation';\nimport {TIPPY_DEFAULT_APPEND_TO} from './constants';\n\nconst pluginProps = {\n  animateFill: false,\n  followCursor: false,\n  inlinePositioning: false,\n  sticky: false,\n};\n\nconst renderProps = {\n  allowHTML: false,\n  animation: 'fade',\n  arrow: true,\n  content: '',\n  inertia: false,\n  maxWidth: 350,\n  role: 'tooltip',\n  theme: '',\n  zIndex: 9999,\n};\n\nexport const defaultProps: DefaultProps = {\n  appendTo: TIPPY_DEFAULT_APPEND_TO,\n  aria: {\n    content: 'auto',\n    expanded: 'auto',\n  },\n  delay: 0,\n  duration: [300, 250],\n  getReferenceClientRect: null,\n  hideOnClick: true,\n  ignoreAttributes: false,\n  interactive: false,\n  interactiveBorder: 2,\n  interactiveDebounce: 0,\n  moveTransition: '',\n  offset: [0, 10],\n  onAfterUpdate() {},\n  onBeforeUpdate() {},\n  onCreate() {},\n  onDestroy() {},\n  onHidden() {},\n  onHide() {},\n  onMount() {},\n  onShow() {},\n  onShown() {},\n  onTrigger() {},\n  onUntrigger() {},\n  onClickOutside() {},\n  placement: 'top',\n  plugins: [],\n  popperOptions: {},\n  render: null,\n  showOnCreate: false,\n  touch: true,\n  trigger: 'mouseenter focus',\n  triggerTarget: null,\n  ...pluginProps,\n  ...renderProps,\n};\n\nconst defaultKeys = Object.keys(defaultProps);\n\nexport const setDefaultProps: Tippy['setDefaultProps'] = (partialProps) => {\n  /* istanbul ignore else */\n  if (__DEV__) {\n    validateProps(partialProps, []);\n  }\n\n  const keys = Object.keys(partialProps) as Array<keyof DefaultProps>;\n  keys.forEach((key) => {\n    (defaultProps as any)[key] = partialProps[key];\n  });\n};\n\nexport function getExtendedPassedProps(\n  passedProps: Partial<Props> & Record<string, unknown>\n): Partial<Props> {\n  const plugins = passedProps.plugins || [];\n  const pluginProps = plugins.reduce<Record<string, unknown>>((acc, plugin) => {\n    const {name, defaultValue} = plugin;\n\n    if (name) {\n      acc[name] =\n        passedProps[name] !== undefined\n          ? passedProps[name]\n          : (defaultProps as any)[name] ?? defaultValue;\n    }\n\n    return acc;\n  }, {});\n\n  return {\n    ...passedProps,\n    ...pluginProps,\n  };\n}\n\nexport function getDataAttributeProps(\n  reference: ReferenceElement,\n  plugins: Plugin[]\n): Record<string, unknown> {\n  const propKeys = plugins\n    ? Object.keys(getExtendedPassedProps({...defaultProps, plugins}))\n    : defaultKeys;\n\n  const props = propKeys.reduce(\n    (acc: Partial<Props> & Record<string, unknown>, key) => {\n      const valueAsString = (\n        reference.getAttribute(`data-tippy-${key}`) || ''\n      ).trim();\n\n      if (!valueAsString) {\n        return acc;\n      }\n\n      if (key === 'content') {\n        acc[key] = valueAsString;\n      } else {\n        try {\n          acc[key] = JSON.parse(valueAsString);\n        } catch (e) {\n          acc[key] = valueAsString;\n        }\n      }\n\n      return acc;\n    },\n    {}\n  );\n\n  return props;\n}\n\nexport function evaluateProps(\n  reference: ReferenceElement,\n  props: Props\n): Props {\n  const out = {\n    ...props,\n    content: invokeWithArgsOrReturn(props.content, [reference]),\n    ...(props.ignoreAttributes\n      ? {}\n      : getDataAttributeProps(reference, props.plugins)),\n  };\n\n  out.aria = {\n    ...defaultProps.aria,\n    ...out.aria,\n  };\n\n  out.aria = {\n    expanded:\n      out.aria.expanded === 'auto' ? props.interactive : out.aria.expanded,\n    content:\n      out.aria.content === 'auto'\n        ? props.interactive\n          ? null\n          : 'describedby'\n        : out.aria.content,\n  };\n\n  return out;\n}\n\nexport function validateProps(\n  partialProps: Partial<Props> = {},\n  plugins: Plugin[] = []\n): void {\n  const keys = Object.keys(partialProps) as Array<keyof Props>;\n  keys.forEach((prop) => {\n    const nonPluginProps = removeProperties(\n      defaultProps,\n      Object.keys(pluginProps)\n    );\n\n    let didPassUnknownProp = !hasOwnProperty(nonPluginProps, prop);\n\n    // Check if the prop exists in `plugins`\n    if (didPassUnknownProp) {\n      didPassUnknownProp =\n        plugins.filter((plugin) => plugin.name === prop).length === 0;\n    }\n\n    warnWhen(\n      didPassUnknownProp,\n      [\n        `\\`${prop}\\``,\n        \"is not a valid prop. You may have spelled it incorrectly, or if it's\",\n        'a plugin, forgot to pass it in an array as props.plugins.',\n        '\\n\\n',\n        'All props: https://atomiks.github.io/tippyjs/v6/all-props/\\n',\n        'Plugins: https://atomiks.github.io/tippyjs/v6/plugins/',\n      ].join(' ')\n    );\n  });\n}\n", "import {\n  ARROW_CLASS,\n  BACKDROP_CLASS,\n  BOX_CLASS,\n  CONTENT_CLASS,\n  SVG_ARROW_CLASS,\n} from './constants';\nimport {div, isElement} from './dom-utils';\nimport {Instance, PopperElement, Props} from './types';\nimport {PopperChildren} from './types-internal';\nimport {arrayFrom} from './utils';\n\n// Firefox extensions don't allow .innerHTML = \"...\" property. This tricks it.\nconst innerHTML = (): 'innerHTML' => 'innerHTML';\n\nfunction dangerouslySetInnerHTML(element: Element, html: string): void {\n  element[innerHTML()] = html;\n}\n\nfunction createArrowElement(value: Props['arrow']): HTMLDivElement {\n  const arrow = div();\n\n  if (value === true) {\n    arrow.className = ARROW_CLASS;\n  } else {\n    arrow.className = SVG_ARROW_CLASS;\n\n    if (isElement(value)) {\n      arrow.appendChild(value);\n    } else {\n      dangerouslySetInnerHTML(arrow, value as string);\n    }\n  }\n\n  return arrow;\n}\n\nexport function setContent(content: HTMLDivElement, props: Props): void {\n  if (isElement(props.content)) {\n    dangerouslySetInnerHTML(content, '');\n    content.appendChild(props.content);\n  } else if (typeof props.content !== 'function') {\n    if (props.allowHTML) {\n      dangerouslySetInnerHTML(content, props.content);\n    } else {\n      content.textContent = props.content;\n    }\n  }\n}\n\nexport function getChildren(popper: PopperElement): PopperChildren {\n  const box = popper.firstElementChild as HTMLDivElement;\n  const boxChildren = arrayFrom(box.children);\n\n  return {\n    box,\n    content: boxChildren.find((node) => node.classList.contains(CONTENT_CLASS)),\n    arrow: boxChildren.find(\n      (node) =>\n        node.classList.contains(ARROW_CLASS) ||\n        node.classList.contains(SVG_ARROW_CLASS)\n    ),\n    backdrop: boxChildren.find((node) =>\n      node.classList.contains(BACKDROP_CLASS)\n    ),\n  };\n}\n\nexport function render(\n  instance: Instance\n): {\n  popper: PopperElement;\n  onUpdate?: (prevProps: Props, nextProps: Props) => void;\n} {\n  const popper = div();\n\n  const box = div();\n  box.className = BOX_CLASS;\n  box.setAttribute('data-state', 'hidden');\n  box.setAttribute('tabindex', '-1');\n\n  const content = div();\n  content.className = CONTENT_CLASS;\n  content.setAttribute('data-state', 'hidden');\n\n  setContent(content, instance.props);\n\n  popper.appendChild(box);\n  box.appendChild(content);\n\n  onUpdate(instance.props, instance.props);\n\n  function onUpdate(prevProps: Props, nextProps: Props): void {\n    const {box, content, arrow} = getChildren(popper);\n\n    if (nextProps.theme) {\n      box.setAttribute('data-theme', nextProps.theme);\n    } else {\n      box.removeAttribute('data-theme');\n    }\n\n    if (typeof nextProps.animation === 'string') {\n      box.setAttribute('data-animation', nextProps.animation);\n    } else {\n      box.removeAttribute('data-animation');\n    }\n\n    if (nextProps.inertia) {\n      box.setAttribute('data-inertia', '');\n    } else {\n      box.removeAttribute('data-inertia');\n    }\n\n    box.style.maxWidth =\n      typeof nextProps.maxWidth === 'number'\n        ? `${nextProps.maxWidth}px`\n        : nextProps.maxWidth;\n\n    if (nextProps.role) {\n      box.setAttribute('role', nextProps.role);\n    } else {\n      box.removeAttribute('role');\n    }\n\n    if (\n      prevProps.content !== nextProps.content ||\n      prevProps.allowHTML !== nextProps.allowHTML\n    ) {\n      setContent(content, instance.props);\n    }\n\n    if (nextProps.arrow) {\n      if (!arrow) {\n        box.appendChild(createArrowElement(nextProps.arrow));\n      } else if (prevProps.arrow !== nextProps.arrow) {\n        box.removeChild(arrow);\n        box.appendChild(createArrowElement(nextProps.arrow));\n      }\n    } else if (arrow) {\n      box.removeChild(arrow!);\n    }\n  }\n\n  return {\n    popper,\n    onUpdate,\n  };\n}\n\n// Runtime check to identify if the render function is the default one; this\n// way we can apply default CSS transitions logic and it can be tree-shaken away\nrender.$$tippy = true;\n", "import {createPopper, StrictModifiers, Modifier} from '@popperjs/core';\nimport {currentInput} from './bindGlobalEventListeners';\nimport {isIE11} from './browser';\nimport {TIPPY_DEFAULT_APPEND_TO, TOUCH_OPTIONS} from './constants';\nimport {\n  actualContains,\n  div,\n  getOwnerDocument,\n  isCursorOutsideInteractiveBorder,\n  isMouseEvent,\n  setTransitionDuration,\n  setVisibilityState,\n  updateTransitionEndListener,\n} from './dom-utils';\nimport {defaultProps, evaluateProps, getExtendedPassedProps} from './props';\nimport {getChildren} from './template';\nimport {\n  Content,\n  Instance,\n  LifecycleHooks,\n  PopperElement,\n  Props,\n  ReferenceElement,\n} from './types';\nimport {ListenerObject, PopperTreeData, PopperChildren} from './types-internal';\nimport {\n  arrayFrom,\n  debounce,\n  getValueAtIndexOrReturn,\n  invokeWithArgsOrReturn,\n  normalizeToArray,\n  pushIfUnique,\n  splitBySpaces,\n  unique,\n  removeUndefinedProps,\n} from './utils';\nimport {createMemoryLeakWarning, errorWhen, warnWhen} from './validation';\n\nlet idCounter = 1;\nlet mouseMoveListeners: ((event: MouseEvent) => void)[] = [];\n\n// Used by `hideAll()`\nexport let mountedInstances: Instance[] = [];\n\nexport default function createTippy(\n  reference: ReferenceElement,\n  passedProps: Partial<Props>\n): Instance {\n  const props = evaluateProps(reference, {\n    ...defaultProps,\n    ...getExtendedPassedProps(removeUndefinedProps(passedProps)),\n  });\n\n  // ===========================================================================\n  // 🔒 Private members\n  // ===========================================================================\n  let showTimeout: any;\n  let hideTimeout: any;\n  let scheduleHideAnimationFrame: number;\n  let isVisibleFromClick = false;\n  let didHideDueToDocumentMouseDown = false;\n  let didTouchMove = false;\n  let ignoreOnFirstUpdate = false;\n  let lastTriggerEvent: Event | undefined;\n  let currentTransitionEndListener: (event: TransitionEvent) => void;\n  let onFirstUpdate: () => void;\n  let listeners: ListenerObject[] = [];\n  let debouncedOnMouseMove = debounce(onMouseMove, props.interactiveDebounce);\n  let currentTarget: Element;\n\n  // ===========================================================================\n  // 🔑 Public members\n  // ===========================================================================\n  const id = idCounter++;\n  const popperInstance = null;\n  const plugins = unique(props.plugins);\n\n  const state = {\n    // Is the instance currently enabled?\n    isEnabled: true,\n    // Is the tippy currently showing and not transitioning out?\n    isVisible: false,\n    // Has the instance been destroyed?\n    isDestroyed: false,\n    // Is the tippy currently mounted to the DOM?\n    isMounted: false,\n    // Has the tippy finished transitioning in?\n    isShown: false,\n  };\n\n  const instance: Instance = {\n    // properties\n    id,\n    reference,\n    popper: div(),\n    popperInstance,\n    props,\n    state,\n    plugins,\n    // methods\n    clearDelayTimeouts,\n    setProps,\n    setContent,\n    show,\n    hide,\n    hideWithInteractivity,\n    enable,\n    disable,\n    unmount,\n    destroy,\n  };\n\n  // TODO: Investigate why this early return causes a TDZ error in the tests —\n  // it doesn't seem to happen in the browser\n  /* istanbul ignore if */\n  if (!props.render) {\n    if (__DEV__) {\n      errorWhen(true, 'render() function has not been supplied.');\n    }\n\n    return instance;\n  }\n\n  // ===========================================================================\n  // Initial mutations\n  // ===========================================================================\n  const {popper, onUpdate} = props.render(instance);\n\n  popper.setAttribute('data-__NAMESPACE_PREFIX__-root', '');\n  popper.id = `__NAMESPACE_PREFIX__-${instance.id}`;\n\n  instance.popper = popper;\n  reference._tippy = instance;\n  popper._tippy = instance;\n\n  const pluginsHooks = plugins.map((plugin) => plugin.fn(instance));\n  const hasAriaExpanded = reference.hasAttribute('aria-expanded');\n\n  addListeners();\n  handleAriaExpandedAttribute();\n  handleStyles();\n\n  invokeHook('onCreate', [instance]);\n\n  if (props.showOnCreate) {\n    scheduleShow();\n  }\n\n  // Prevent a tippy with a delay from hiding if the cursor left then returned\n  // before it started hiding\n  popper.addEventListener('mouseenter', () => {\n    if (instance.props.interactive && instance.state.isVisible) {\n      instance.clearDelayTimeouts();\n    }\n  });\n\n  popper.addEventListener('mouseleave', () => {\n    if (\n      instance.props.interactive &&\n      instance.props.trigger.indexOf('mouseenter') >= 0\n    ) {\n      getDocument().addEventListener('mousemove', debouncedOnMouseMove);\n    }\n  });\n\n  return instance;\n\n  // ===========================================================================\n  // 🔒 Private methods\n  // ===========================================================================\n  function getNormalizedTouchSettings(): [string | boolean, number] {\n    const {touch} = instance.props;\n    return Array.isArray(touch) ? touch : [touch, 0];\n  }\n\n  function getIsCustomTouchBehavior(): boolean {\n    return getNormalizedTouchSettings()[0] === 'hold';\n  }\n\n  function getIsDefaultRenderFn(): boolean {\n    // @ts-ignore\n    return !!instance.props.render?.$$tippy;\n  }\n\n  function getCurrentTarget(): Element {\n    return currentTarget || reference;\n  }\n\n  function getDocument(): Document {\n    const parent = getCurrentTarget().parentNode as Element;\n    return parent ? getOwnerDocument(parent) : document;\n  }\n\n  function getDefaultTemplateChildren(): PopperChildren {\n    return getChildren(popper);\n  }\n\n  function getDelay(isShow: boolean): number {\n    // For touch or keyboard input, force `0` delay for UX reasons\n    // Also if the instance is mounted but not visible (transitioning out),\n    // ignore delay\n    if (\n      (instance.state.isMounted && !instance.state.isVisible) ||\n      currentInput.isTouch ||\n      (lastTriggerEvent && lastTriggerEvent.type === 'focus')\n    ) {\n      return 0;\n    }\n\n    return getValueAtIndexOrReturn(\n      instance.props.delay,\n      isShow ? 0 : 1,\n      defaultProps.delay\n    );\n  }\n\n  function handleStyles(fromHide = false): void {\n    popper.style.pointerEvents =\n      instance.props.interactive && !fromHide ? '' : 'none';\n    popper.style.zIndex = `${instance.props.zIndex}`;\n  }\n\n  function invokeHook(\n    hook: keyof LifecycleHooks,\n    args: [Instance, any?],\n    shouldInvokePropsHook = true\n  ): void {\n    pluginsHooks.forEach((pluginHooks) => {\n      if (pluginHooks[hook]) {\n        pluginHooks[hook]!(...args);\n      }\n    });\n\n    if (shouldInvokePropsHook) {\n      instance.props[hook](...args);\n    }\n  }\n\n  function handleAriaContentAttribute(): void {\n    const {aria} = instance.props;\n\n    if (!aria.content) {\n      return;\n    }\n\n    const attr = `aria-${aria.content}`;\n    const id = popper.id;\n    const nodes = normalizeToArray(instance.props.triggerTarget || reference);\n\n    nodes.forEach((node) => {\n      const currentValue = node.getAttribute(attr);\n\n      if (instance.state.isVisible) {\n        node.setAttribute(attr, currentValue ? `${currentValue} ${id}` : id);\n      } else {\n        const nextValue = currentValue && currentValue.replace(id, '').trim();\n\n        if (nextValue) {\n          node.setAttribute(attr, nextValue);\n        } else {\n          node.removeAttribute(attr);\n        }\n      }\n    });\n  }\n\n  function handleAriaExpandedAttribute(): void {\n    if (hasAriaExpanded || !instance.props.aria.expanded) {\n      return;\n    }\n\n    const nodes = normalizeToArray(instance.props.triggerTarget || reference);\n\n    nodes.forEach((node) => {\n      if (instance.props.interactive) {\n        node.setAttribute(\n          'aria-expanded',\n          instance.state.isVisible && node === getCurrentTarget()\n            ? 'true'\n            : 'false'\n        );\n      } else {\n        node.removeAttribute('aria-expanded');\n      }\n    });\n  }\n\n  function cleanupInteractiveMouseListeners(): void {\n    getDocument().removeEventListener('mousemove', debouncedOnMouseMove);\n    mouseMoveListeners = mouseMoveListeners.filter(\n      (listener) => listener !== debouncedOnMouseMove\n    );\n  }\n\n  function onDocumentPress(event: MouseEvent | TouchEvent): void {\n    // Moved finger to scroll instead of an intentional tap outside\n    if (currentInput.isTouch) {\n      if (didTouchMove || event.type === 'mousedown') {\n        return;\n      }\n    }\n\n    const actualTarget =\n      (event.composedPath && event.composedPath()[0]) || event.target;\n\n    // Clicked on interactive popper\n    if (\n      instance.props.interactive &&\n      actualContains(popper, actualTarget as Element)\n    ) {\n      return;\n    }\n\n    // Clicked on the event listeners target\n    if (\n      normalizeToArray(instance.props.triggerTarget || reference).some((el) =>\n        actualContains(el, actualTarget as Element)\n      )\n    ) {\n      if (currentInput.isTouch) {\n        return;\n      }\n\n      if (\n        instance.state.isVisible &&\n        instance.props.trigger.indexOf('click') >= 0\n      ) {\n        return;\n      }\n    } else {\n      invokeHook('onClickOutside', [instance, event]);\n    }\n\n    if (instance.props.hideOnClick === true) {\n      instance.clearDelayTimeouts();\n      instance.hide();\n\n      // `mousedown` event is fired right before `focus` if pressing the\n      // currentTarget. This lets a tippy with `focus` trigger know that it\n      // should not show\n      didHideDueToDocumentMouseDown = true;\n      setTimeout(() => {\n        didHideDueToDocumentMouseDown = false;\n      });\n\n      // The listener gets added in `scheduleShow()`, but this may be hiding it\n      // before it shows, and hide()'s early bail-out behavior can prevent it\n      // from being cleaned up\n      if (!instance.state.isMounted) {\n        removeDocumentPress();\n      }\n    }\n  }\n\n  function onTouchMove(): void {\n    didTouchMove = true;\n  }\n\n  function onTouchStart(): void {\n    didTouchMove = false;\n  }\n\n  function addDocumentPress(): void {\n    const doc = getDocument();\n    doc.addEventListener('mousedown', onDocumentPress, true);\n    doc.addEventListener('touchend', onDocumentPress, TOUCH_OPTIONS);\n    doc.addEventListener('touchstart', onTouchStart, TOUCH_OPTIONS);\n    doc.addEventListener('touchmove', onTouchMove, TOUCH_OPTIONS);\n  }\n\n  function removeDocumentPress(): void {\n    const doc = getDocument();\n    doc.removeEventListener('mousedown', onDocumentPress, true);\n    doc.removeEventListener('touchend', onDocumentPress, TOUCH_OPTIONS);\n    doc.removeEventListener('touchstart', onTouchStart, TOUCH_OPTIONS);\n    doc.removeEventListener('touchmove', onTouchMove, TOUCH_OPTIONS);\n  }\n\n  function onTransitionedOut(duration: number, callback: () => void): void {\n    onTransitionEnd(duration, () => {\n      if (\n        !instance.state.isVisible &&\n        popper.parentNode &&\n        popper.parentNode.contains(popper)\n      ) {\n        callback();\n      }\n    });\n  }\n\n  function onTransitionedIn(duration: number, callback: () => void): void {\n    onTransitionEnd(duration, callback);\n  }\n\n  function onTransitionEnd(duration: number, callback: () => void): void {\n    const box = getDefaultTemplateChildren().box;\n\n    function listener(event: TransitionEvent): void {\n      if (event.target === box) {\n        updateTransitionEndListener(box, 'remove', listener);\n        callback();\n      }\n    }\n\n    // Make callback synchronous if duration is 0\n    // `transitionend` won't fire otherwise\n    if (duration === 0) {\n      return callback();\n    }\n\n    updateTransitionEndListener(box, 'remove', currentTransitionEndListener);\n    updateTransitionEndListener(box, 'add', listener);\n\n    currentTransitionEndListener = listener;\n  }\n\n  function on(\n    eventType: string,\n    handler: EventListener,\n    options: boolean | Record<string, unknown> = false\n  ): void {\n    const nodes = normalizeToArray(instance.props.triggerTarget || reference);\n    nodes.forEach((node) => {\n      node.addEventListener(eventType, handler, options);\n      listeners.push({node, eventType, handler, options});\n    });\n  }\n\n  function addListeners(): void {\n    if (getIsCustomTouchBehavior()) {\n      on('touchstart', onTrigger, {passive: true});\n      on('touchend', onMouseLeave as EventListener, {passive: true});\n    }\n\n    splitBySpaces(instance.props.trigger).forEach((eventType) => {\n      if (eventType === 'manual') {\n        return;\n      }\n\n      on(eventType, onTrigger);\n\n      switch (eventType) {\n        case 'mouseenter':\n          on('mouseleave', onMouseLeave as EventListener);\n          break;\n        case 'focus':\n          on(isIE11 ? 'focusout' : 'blur', onBlurOrFocusOut as EventListener);\n          break;\n        case 'focusin':\n          on('focusout', onBlurOrFocusOut as EventListener);\n          break;\n      }\n    });\n  }\n\n  function removeListeners(): void {\n    listeners.forEach(({node, eventType, handler, options}: ListenerObject) => {\n      node.removeEventListener(eventType, handler, options);\n    });\n    listeners = [];\n  }\n\n  function onTrigger(event: Event): void {\n    let shouldScheduleClickHide = false;\n\n    if (\n      !instance.state.isEnabled ||\n      isEventListenerStopped(event) ||\n      didHideDueToDocumentMouseDown\n    ) {\n      return;\n    }\n\n    const wasFocused = lastTriggerEvent?.type === 'focus';\n\n    lastTriggerEvent = event;\n    currentTarget = event.currentTarget as Element;\n\n    handleAriaExpandedAttribute();\n\n    if (!instance.state.isVisible && isMouseEvent(event)) {\n      // If scrolling, `mouseenter` events can be fired if the cursor lands\n      // over a new target, but `mousemove` events don't get fired. This\n      // causes interactive tooltips to get stuck open until the cursor is\n      // moved\n      mouseMoveListeners.forEach((listener) => listener(event));\n    }\n\n    // Toggle show/hide when clicking click-triggered tooltips\n    if (\n      event.type === 'click' &&\n      (instance.props.trigger.indexOf('mouseenter') < 0 ||\n        isVisibleFromClick) &&\n      instance.props.hideOnClick !== false &&\n      instance.state.isVisible\n    ) {\n      shouldScheduleClickHide = true;\n    } else {\n      scheduleShow(event);\n    }\n\n    if (event.type === 'click') {\n      isVisibleFromClick = !shouldScheduleClickHide;\n    }\n\n    if (shouldScheduleClickHide && !wasFocused) {\n      scheduleHide(event);\n    }\n  }\n\n  function onMouseMove(event: MouseEvent): void {\n    const target = event.target as Node;\n    const isCursorOverReferenceOrPopper =\n      getCurrentTarget().contains(target) || popper.contains(target);\n\n    if (event.type === 'mousemove' && isCursorOverReferenceOrPopper) {\n      return;\n    }\n\n    const popperTreeData = getNestedPopperTree()\n      .concat(popper)\n      .map((popper) => {\n        const instance = popper._tippy!;\n        const state = instance.popperInstance?.state;\n\n        if (state) {\n          return {\n            popperRect: popper.getBoundingClientRect(),\n            popperState: state,\n            props,\n          };\n        }\n\n        return null;\n      })\n      .filter(Boolean) as PopperTreeData[];\n\n    if (isCursorOutsideInteractiveBorder(popperTreeData, event)) {\n      cleanupInteractiveMouseListeners();\n      scheduleHide(event);\n    }\n  }\n\n  function onMouseLeave(event: MouseEvent): void {\n    const shouldBail =\n      isEventListenerStopped(event) ||\n      (instance.props.trigger.indexOf('click') >= 0 && isVisibleFromClick);\n\n    if (shouldBail) {\n      return;\n    }\n\n    if (instance.props.interactive) {\n      instance.hideWithInteractivity(event);\n      return;\n    }\n\n    scheduleHide(event);\n  }\n\n  function onBlurOrFocusOut(event: FocusEvent): void {\n    if (\n      instance.props.trigger.indexOf('focusin') < 0 &&\n      event.target !== getCurrentTarget()\n    ) {\n      return;\n    }\n\n    // If focus was moved to within the popper\n    if (\n      instance.props.interactive &&\n      event.relatedTarget &&\n      popper.contains(event.relatedTarget as Element)\n    ) {\n      return;\n    }\n\n    scheduleHide(event);\n  }\n\n  function isEventListenerStopped(event: Event): boolean {\n    return currentInput.isTouch\n      ? getIsCustomTouchBehavior() !== event.type.indexOf('touch') >= 0\n      : false;\n  }\n\n  function createPopperInstance(): void {\n    destroyPopperInstance();\n\n    const {\n      popperOptions,\n      placement,\n      offset,\n      getReferenceClientRect,\n      moveTransition,\n    } = instance.props;\n\n    const arrow = getIsDefaultRenderFn() ? getChildren(popper).arrow : null;\n\n    const computedReference = getReferenceClientRect\n      ? {\n          getBoundingClientRect: getReferenceClientRect,\n          contextElement:\n            getReferenceClientRect.contextElement || getCurrentTarget(),\n        }\n      : reference;\n\n    const tippyModifier: Modifier<'$$tippy', Record<string, unknown>> = {\n      name: '$$tippy',\n      enabled: true,\n      phase: 'beforeWrite',\n      requires: ['computeStyles'],\n      fn({state}) {\n        if (getIsDefaultRenderFn()) {\n          const {box} = getDefaultTemplateChildren();\n\n          ['placement', 'reference-hidden', 'escaped'].forEach((attr) => {\n            if (attr === 'placement') {\n              box.setAttribute('data-placement', state.placement);\n            } else {\n              if (state.attributes.popper[`data-popper-${attr}`]) {\n                box.setAttribute(`data-${attr}`, '');\n              } else {\n                box.removeAttribute(`data-${attr}`);\n              }\n            }\n          });\n\n          state.attributes.popper = {};\n        }\n      },\n    };\n\n    type TippyModifier = Modifier<'$$tippy', Record<string, unknown>>;\n    type ExtendedModifiers = StrictModifiers | Partial<TippyModifier>;\n\n    const modifiers: Array<ExtendedModifiers> = [\n      {\n        name: 'offset',\n        options: {\n          offset,\n        },\n      },\n      {\n        name: 'preventOverflow',\n        options: {\n          padding: {\n            top: 2,\n            bottom: 2,\n            left: 5,\n            right: 5,\n          },\n        },\n      },\n      {\n        name: 'flip',\n        options: {\n          padding: 5,\n        },\n      },\n      {\n        name: 'computeStyles',\n        options: {\n          adaptive: !moveTransition,\n        },\n      },\n      tippyModifier,\n    ];\n\n    if (getIsDefaultRenderFn() && arrow) {\n      modifiers.push({\n        name: 'arrow',\n        options: {\n          element: arrow,\n          padding: 3,\n        },\n      });\n    }\n\n    modifiers.push(...(popperOptions?.modifiers || []));\n\n    instance.popperInstance = createPopper<ExtendedModifiers>(\n      computedReference,\n      popper,\n      {\n        ...popperOptions,\n        placement,\n        onFirstUpdate,\n        modifiers,\n      }\n    );\n  }\n\n  function destroyPopperInstance(): void {\n    if (instance.popperInstance) {\n      instance.popperInstance.destroy();\n      instance.popperInstance = null;\n    }\n  }\n\n  function mount(): void {\n    const {appendTo} = instance.props;\n\n    let parentNode: any;\n\n    // By default, we'll append the popper to the triggerTargets's parentNode so\n    // it's directly after the reference element so the elements inside the\n    // tippy can be tabbed to\n    // If there are clipping issues, the user can specify a different appendTo\n    // and ensure focus management is handled correctly manually\n    const node = getCurrentTarget();\n\n    if (\n      (instance.props.interactive && appendTo === TIPPY_DEFAULT_APPEND_TO) ||\n      appendTo === 'parent'\n    ) {\n      parentNode = node.parentNode;\n    } else {\n      parentNode = invokeWithArgsOrReturn(appendTo, [node]);\n    }\n\n    // The popper element needs to exist on the DOM before its position can be\n    // updated as Popper needs to read its dimensions\n    if (!parentNode.contains(popper)) {\n      parentNode.appendChild(popper);\n    }\n\n    instance.state.isMounted = true;\n\n    createPopperInstance();\n\n    /* istanbul ignore else */\n    if (__DEV__) {\n      // Accessibility check\n      warnWhen(\n        instance.props.interactive &&\n          appendTo === defaultProps.appendTo &&\n          node.nextElementSibling !== popper,\n        [\n          'Interactive tippy element may not be accessible via keyboard',\n          'navigation because it is not directly after the reference element',\n          'in the DOM source order.',\n          '\\n\\n',\n          'Using a wrapper <div> or <span> tag around the reference element',\n          'solves this by creating a new parentNode context.',\n          '\\n\\n',\n          'Specifying `appendTo: document.body` silences this warning, but it',\n          'assumes you are using a focus management solution to handle',\n          'keyboard navigation.',\n          '\\n\\n',\n          'See: https://atomiks.github.io/tippyjs/v6/accessibility/#interactivity',\n        ].join(' ')\n      );\n    }\n  }\n\n  function getNestedPopperTree(): PopperElement[] {\n    return arrayFrom(\n      popper.querySelectorAll('[data-__NAMESPACE_PREFIX__-root]')\n    );\n  }\n\n  function scheduleShow(event?: Event): void {\n    instance.clearDelayTimeouts();\n\n    if (event) {\n      invokeHook('onTrigger', [instance, event]);\n    }\n\n    addDocumentPress();\n\n    let delay = getDelay(true);\n    const [touchValue, touchDelay] = getNormalizedTouchSettings();\n\n    if (currentInput.isTouch && touchValue === 'hold' && touchDelay) {\n      delay = touchDelay;\n    }\n\n    if (delay) {\n      showTimeout = setTimeout(() => {\n        instance.show();\n      }, delay);\n    } else {\n      instance.show();\n    }\n  }\n\n  function scheduleHide(event: Event): void {\n    instance.clearDelayTimeouts();\n\n    invokeHook('onUntrigger', [instance, event]);\n\n    if (!instance.state.isVisible) {\n      removeDocumentPress();\n\n      return;\n    }\n\n    // For interactive tippies, scheduleHide is added to a document.body handler\n    // from onMouseLeave so must intercept scheduled hides from mousemove/leave\n    // events when trigger contains mouseenter and click, and the tip is\n    // currently shown as a result of a click.\n    if (\n      instance.props.trigger.indexOf('mouseenter') >= 0 &&\n      instance.props.trigger.indexOf('click') >= 0 &&\n      ['mouseleave', 'mousemove'].indexOf(event.type) >= 0 &&\n      isVisibleFromClick\n    ) {\n      return;\n    }\n\n    const delay = getDelay(false);\n\n    if (delay) {\n      hideTimeout = setTimeout(() => {\n        if (instance.state.isVisible) {\n          instance.hide();\n        }\n      }, delay);\n    } else {\n      // Fixes a `transitionend` problem when it fires 1 frame too\n      // late sometimes, we don't want hide() to be called.\n      scheduleHideAnimationFrame = requestAnimationFrame(() => {\n        instance.hide();\n      });\n    }\n  }\n\n  // ===========================================================================\n  // 🔑 Public methods\n  // ===========================================================================\n  function enable(): void {\n    instance.state.isEnabled = true;\n  }\n\n  function disable(): void {\n    // Disabling the instance should also hide it\n    // https://github.com/atomiks/tippy.js-react/issues/106\n    instance.hide();\n    instance.state.isEnabled = false;\n  }\n\n  function clearDelayTimeouts(): void {\n    clearTimeout(showTimeout);\n    clearTimeout(hideTimeout);\n    cancelAnimationFrame(scheduleHideAnimationFrame);\n  }\n\n  function setProps(partialProps: Partial<Props>): void {\n    /* istanbul ignore else */\n    if (__DEV__) {\n      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('setProps'));\n    }\n\n    if (instance.state.isDestroyed) {\n      return;\n    }\n\n    invokeHook('onBeforeUpdate', [instance, partialProps]);\n\n    removeListeners();\n\n    const prevProps = instance.props;\n    const nextProps = evaluateProps(reference, {\n      ...prevProps,\n      ...removeUndefinedProps(partialProps),\n      ignoreAttributes: true,\n    });\n\n    instance.props = nextProps;\n\n    addListeners();\n\n    if (prevProps.interactiveDebounce !== nextProps.interactiveDebounce) {\n      cleanupInteractiveMouseListeners();\n      debouncedOnMouseMove = debounce(\n        onMouseMove,\n        nextProps.interactiveDebounce\n      );\n    }\n\n    // Ensure stale aria-expanded attributes are removed\n    if (prevProps.triggerTarget && !nextProps.triggerTarget) {\n      normalizeToArray(prevProps.triggerTarget).forEach((node) => {\n        node.removeAttribute('aria-expanded');\n      });\n    } else if (nextProps.triggerTarget) {\n      reference.removeAttribute('aria-expanded');\n    }\n\n    handleAriaExpandedAttribute();\n    handleStyles();\n\n    if (onUpdate) {\n      onUpdate(prevProps, nextProps);\n    }\n\n    if (instance.popperInstance) {\n      createPopperInstance();\n\n      // Fixes an issue with nested tippies if they are all getting re-rendered,\n      // and the nested ones get re-rendered first.\n      // https://github.com/atomiks/tippyjs-react/issues/177\n      // TODO: find a cleaner / more efficient solution(!)\n      getNestedPopperTree().forEach((nestedPopper) => {\n        // React (and other UI libs likely) requires a rAF wrapper as it flushes\n        // its work in one\n        requestAnimationFrame(nestedPopper._tippy!.popperInstance!.forceUpdate);\n      });\n    }\n\n    invokeHook('onAfterUpdate', [instance, partialProps]);\n  }\n\n  function setContent(content: Content): void {\n    instance.setProps({content});\n  }\n\n  function show(): void {\n    /* istanbul ignore else */\n    if (__DEV__) {\n      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('show'));\n    }\n\n    // Early bail-out\n    const isAlreadyVisible = instance.state.isVisible;\n    const isDestroyed = instance.state.isDestroyed;\n    const isDisabled = !instance.state.isEnabled;\n    const isTouchAndTouchDisabled =\n      currentInput.isTouch && !instance.props.touch;\n    const duration = getValueAtIndexOrReturn(\n      instance.props.duration,\n      0,\n      defaultProps.duration\n    );\n\n    if (\n      isAlreadyVisible ||\n      isDestroyed ||\n      isDisabled ||\n      isTouchAndTouchDisabled\n    ) {\n      return;\n    }\n\n    // Normalize `disabled` behavior across browsers.\n    // Firefox allows events on disabled elements, but Chrome doesn't.\n    // Using a wrapper element (i.e. <span>) is recommended.\n    if (getCurrentTarget().hasAttribute('disabled')) {\n      return;\n    }\n\n    invokeHook('onShow', [instance], false);\n    if (instance.props.onShow(instance) === false) {\n      return;\n    }\n\n    instance.state.isVisible = true;\n\n    if (getIsDefaultRenderFn()) {\n      popper.style.visibility = 'visible';\n    }\n\n    handleStyles();\n    addDocumentPress();\n\n    if (!instance.state.isMounted) {\n      popper.style.transition = 'none';\n    }\n\n    // If flipping to the opposite side after hiding at least once, the\n    // animation will use the wrong placement without resetting the duration\n    if (getIsDefaultRenderFn()) {\n      const {box, content} = getDefaultTemplateChildren();\n      setTransitionDuration([box, content], 0);\n    }\n\n    onFirstUpdate = (): void => {\n      if (!instance.state.isVisible || ignoreOnFirstUpdate) {\n        return;\n      }\n\n      ignoreOnFirstUpdate = true;\n\n      // reflow\n      void popper.offsetHeight;\n\n      popper.style.transition = instance.props.moveTransition;\n\n      if (getIsDefaultRenderFn() && instance.props.animation) {\n        const {box, content} = getDefaultTemplateChildren();\n        setTransitionDuration([box, content], duration);\n        setVisibilityState([box, content], 'visible');\n      }\n\n      handleAriaContentAttribute();\n      handleAriaExpandedAttribute();\n\n      pushIfUnique(mountedInstances, instance);\n\n      // certain modifiers (e.g. `maxSize`) require a second update after the\n      // popper has been positioned for the first time\n      instance.popperInstance?.forceUpdate();\n\n      invokeHook('onMount', [instance]);\n\n      if (instance.props.animation && getIsDefaultRenderFn()) {\n        onTransitionedIn(duration, () => {\n          instance.state.isShown = true;\n          invokeHook('onShown', [instance]);\n        });\n      }\n    };\n\n    mount();\n  }\n\n  function hide(): void {\n    /* istanbul ignore else */\n    if (__DEV__) {\n      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('hide'));\n    }\n\n    // Early bail-out\n    const isAlreadyHidden = !instance.state.isVisible;\n    const isDestroyed = instance.state.isDestroyed;\n    const isDisabled = !instance.state.isEnabled;\n    const duration = getValueAtIndexOrReturn(\n      instance.props.duration,\n      1,\n      defaultProps.duration\n    );\n\n    if (isAlreadyHidden || isDestroyed || isDisabled) {\n      return;\n    }\n\n    invokeHook('onHide', [instance], false);\n    if (instance.props.onHide(instance) === false) {\n      return;\n    }\n\n    instance.state.isVisible = false;\n    instance.state.isShown = false;\n    ignoreOnFirstUpdate = false;\n    isVisibleFromClick = false;\n\n    if (getIsDefaultRenderFn()) {\n      popper.style.visibility = 'hidden';\n    }\n\n    cleanupInteractiveMouseListeners();\n    removeDocumentPress();\n    handleStyles(true);\n\n    if (getIsDefaultRenderFn()) {\n      const {box, content} = getDefaultTemplateChildren();\n\n      if (instance.props.animation) {\n        setTransitionDuration([box, content], duration);\n        setVisibilityState([box, content], 'hidden');\n      }\n    }\n\n    handleAriaContentAttribute();\n    handleAriaExpandedAttribute();\n\n    if (instance.props.animation) {\n      if (getIsDefaultRenderFn()) {\n        onTransitionedOut(duration, instance.unmount);\n      }\n    } else {\n      instance.unmount();\n    }\n  }\n\n  function hideWithInteractivity(event: MouseEvent): void {\n    /* istanbul ignore else */\n    if (__DEV__) {\n      warnWhen(\n        instance.state.isDestroyed,\n        createMemoryLeakWarning('hideWithInteractivity')\n      );\n    }\n\n    getDocument().addEventListener('mousemove', debouncedOnMouseMove);\n    pushIfUnique(mouseMoveListeners, debouncedOnMouseMove);\n    debouncedOnMouseMove(event);\n  }\n\n  function unmount(): void {\n    /* istanbul ignore else */\n    if (__DEV__) {\n      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('unmount'));\n    }\n\n    if (instance.state.isVisible) {\n      instance.hide();\n    }\n\n    if (!instance.state.isMounted) {\n      return;\n    }\n\n    destroyPopperInstance();\n\n    // If a popper is not interactive, it will be appended outside the popper\n    // tree by default. This seems mainly for interactive tippies, but we should\n    // find a workaround if possible\n    getNestedPopperTree().forEach((nestedPopper) => {\n      nestedPopper._tippy!.unmount();\n    });\n\n    if (popper.parentNode) {\n      popper.parentNode.removeChild(popper);\n    }\n\n    mountedInstances = mountedInstances.filter((i) => i !== instance);\n\n    instance.state.isMounted = false;\n    invokeHook('onHidden', [instance]);\n  }\n\n  function destroy(): void {\n    /* istanbul ignore else */\n    if (__DEV__) {\n      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('destroy'));\n    }\n\n    if (instance.state.isDestroyed) {\n      return;\n    }\n\n    instance.clearDelayTimeouts();\n    instance.unmount();\n\n    removeListeners();\n\n    delete reference._tippy;\n\n    instance.state.isDestroyed = true;\n\n    invokeHook('onDestroy', [instance]);\n  }\n}\n", "import bindGlobalEventListeners, {\n  currentInput,\n} from './bindGlobalEventListeners';\nimport createTippy, {mountedInstances} from './createTippy';\nimport {getArrayOfElements, isElement, isReferenceElement} from './dom-utils';\nimport {defaultProps, setDefaultProps, validateProps} from './props';\nimport {HideAll, HideAllOptions, Instance, Props, Targets} from './types';\nimport {validateTargets, warnWhen} from './validation';\n\nfunction tippy(\n  targets: Targets,\n  optionalProps: Partial<Props> = {}\n): Instance | Instance[] {\n  const plugins = defaultProps.plugins.concat(optionalProps.plugins || []);\n\n  /* istanbul ignore else */\n  if (__DEV__) {\n    validateTargets(targets);\n    validateProps(optionalProps, plugins);\n  }\n\n  bindGlobalEventListeners();\n\n  const passedProps: Partial<Props> = {...optionalProps, plugins};\n\n  const elements = getArrayOfElements(targets);\n\n  /* istanbul ignore else */\n  if (__DEV__) {\n    const isSingleContentElement = isElement(passedProps.content);\n    const isMoreThanOneReferenceElement = elements.length > 1;\n    warnWhen(\n      isSingleContentElement && isMoreThanOneReferenceElement,\n      [\n        'tippy() was passed an Element as the `content` prop, but more than',\n        'one tippy instance was created by this invocation. This means the',\n        'content element will only be appended to the last tippy instance.',\n        '\\n\\n',\n        'Instead, pass the .innerHTML of the element, or use a function that',\n        'returns a cloned version of the element instead.',\n        '\\n\\n',\n        '1) content: element.innerHTML\\n',\n        '2) content: () => element.cloneNode(true)',\n      ].join(' ')\n    );\n  }\n\n  const instances = elements.reduce<Instance[]>(\n    (acc, reference): Instance[] => {\n      const instance = reference && createTippy(reference, passedProps);\n\n      if (instance) {\n        acc.push(instance);\n      }\n\n      return acc;\n    },\n    []\n  );\n\n  return isElement(targets) ? instances[0] : instances;\n}\n\ntippy.defaultProps = defaultProps;\ntippy.setDefaultProps = setDefaultProps;\ntippy.currentInput = currentInput;\n\nexport default tippy;\n\nexport const hideAll: HideAll = ({\n  exclude: excludedReferenceOrInstance,\n  duration,\n}: HideAllOptions = {}) => {\n  mountedInstances.forEach((instance) => {\n    let isExcluded = false;\n\n    if (excludedReferenceOrInstance) {\n      isExcluded = isReferenceElement(excludedReferenceOrInstance)\n        ? instance.reference === excludedReferenceOrInstance\n        : instance.popper === (excludedReferenceOrInstance as Instance).popper;\n    }\n\n    if (!isExcluded) {\n      const originalDuration = instance.props.duration;\n\n      instance.setProps({duration});\n      instance.hide();\n\n      if (!instance.state.isDestroyed) {\n        instance.setProps({duration: originalDuration});\n      }\n    }\n  });\n};\n", "import tippy from '..';\nimport {div} from '../dom-utils';\nimport {\n  CreateSingleton,\n  Plugin,\n  CreateSingletonProps,\n  ReferenceElement,\n  CreateSingletonInstance,\n  Instance,\n  Props,\n} from '../types';\nimport {normalizeToArray, removeProperties} from '../utils';\nimport {errorWhen} from '../validation';\nimport {applyStyles, Modifier} from '@popperjs/core';\n\n// The default `applyStyles` modifier has a cleanup function that gets called\n// every time the popper is destroyed (i.e. a new target), removing the styles\n// and causing transitions to break for singletons when the console is open, but\n// most notably for non-transform styles being used, `gpuAcceleration: false`.\nconst applyStylesModifier: Modifier<'applyStyles', Record<string, unknown>> = {\n  ...applyStyles,\n  effect({state}) {\n    const initialStyles = {\n      popper: {\n        position: state.options.strategy,\n        left: '0',\n        top: '0',\n        margin: '0',\n      },\n      arrow: {\n        position: 'absolute',\n      },\n      reference: {},\n    };\n\n    Object.assign(state.elements.popper.style, initialStyles.popper);\n    state.styles = initialStyles;\n\n    if (state.elements.arrow) {\n      Object.assign(state.elements.arrow.style, initialStyles.arrow);\n    }\n\n    // intentionally return no cleanup function\n    // return () => { ... }\n  },\n};\n\nconst createSingleton: CreateSingleton = (\n  tippyInstances,\n  optionalProps = {}\n) => {\n  /* istanbul ignore else */\n  if (__DEV__) {\n    errorWhen(\n      !Array.isArray(tippyInstances),\n      [\n        'The first argument passed to createSingleton() must be an array of',\n        'tippy instances. The passed value was',\n        String(tippyInstances),\n      ].join(' ')\n    );\n  }\n\n  let individualInstances = tippyInstances;\n  let references: Array<ReferenceElement> = [];\n  let triggerTargets: Array<Element> = [];\n  let currentTarget: Element | null;\n  let overrides = optionalProps.overrides;\n  let interceptSetPropsCleanups: Array<() => void> = [];\n  let shownOnCreate = false;\n\n  function setTriggerTargets(): void {\n    triggerTargets = individualInstances\n      .map((instance) =>\n        normalizeToArray(instance.props.triggerTarget || instance.reference)\n      )\n      .reduce((acc, item) => acc.concat(item), []);\n  }\n\n  function setReferences(): void {\n    references = individualInstances.map((instance) => instance.reference);\n  }\n\n  function enableInstances(isEnabled: boolean): void {\n    individualInstances.forEach((instance) => {\n      if (isEnabled) {\n        instance.enable();\n      } else {\n        instance.disable();\n      }\n    });\n  }\n\n  function interceptSetProps(singleton: Instance): Array<() => void> {\n    return individualInstances.map((instance) => {\n      const originalSetProps = instance.setProps;\n\n      instance.setProps = (props): void => {\n        originalSetProps(props);\n\n        if (instance.reference === currentTarget) {\n          singleton.setProps(props);\n        }\n      };\n\n      return (): void => {\n        instance.setProps = originalSetProps;\n      };\n    });\n  }\n\n  // have to pass singleton, as it maybe undefined on first call\n  function prepareInstance(\n    singleton: Instance,\n    target: ReferenceElement\n  ): void {\n    const index = triggerTargets.indexOf(target);\n\n    // bail-out\n    if (target === currentTarget) {\n      return;\n    }\n\n    currentTarget = target;\n\n    const overrideProps: Partial<Props> = (overrides || [])\n      .concat('content')\n      .reduce((acc, prop) => {\n        (acc as any)[prop] = individualInstances[index].props[prop];\n        return acc;\n      }, {});\n\n    singleton.setProps({\n      ...overrideProps,\n      getReferenceClientRect:\n        typeof overrideProps.getReferenceClientRect === 'function'\n          ? overrideProps.getReferenceClientRect\n          : (): ClientRect => references[index]?.getBoundingClientRect(),\n    });\n  }\n\n  enableInstances(false);\n  setReferences();\n  setTriggerTargets();\n\n  const plugin: Plugin = {\n    fn() {\n      return {\n        onDestroy(): void {\n          enableInstances(true);\n        },\n        onHidden(): void {\n          currentTarget = null;\n        },\n        onClickOutside(instance): void {\n          if (instance.props.showOnCreate && !shownOnCreate) {\n            shownOnCreate = true;\n            currentTarget = null;\n          }\n        },\n        onShow(instance): void {\n          if (instance.props.showOnCreate && !shownOnCreate) {\n            shownOnCreate = true;\n            prepareInstance(instance, references[0]);\n          }\n        },\n        onTrigger(instance, event): void {\n          prepareInstance(instance, event.currentTarget as Element);\n        },\n      };\n    },\n  };\n\n  const singleton = tippy(div(), {\n    ...removeProperties(optionalProps, ['overrides']),\n    plugins: [plugin, ...(optionalProps.plugins || [])],\n    triggerTarget: triggerTargets,\n    popperOptions: {\n      ...optionalProps.popperOptions,\n      modifiers: [\n        ...(optionalProps.popperOptions?.modifiers || []),\n        applyStylesModifier,\n      ],\n    },\n  }) as CreateSingletonInstance<CreateSingletonProps>;\n\n  const originalShow = singleton.show;\n\n  singleton.show = (target?: ReferenceElement | Instance | number): void => {\n    originalShow();\n\n    // first time, showOnCreate or programmatic call with no params\n    // default to showing first instance\n    if (!currentTarget && target == null) {\n      return prepareInstance(singleton, references[0]);\n    }\n\n    // triggered from event (do nothing as prepareInstance already called by onTrigger)\n    // programmatic call with no params when already visible (do nothing again)\n    if (currentTarget && target == null) {\n      return;\n    }\n\n    // target is index of instance\n    if (typeof target === 'number') {\n      return (\n        references[target] && prepareInstance(singleton, references[target])\n      );\n    }\n\n    // target is a child tippy instance\n    if (individualInstances.indexOf(target as Instance) >= 0) {\n      const ref = (target as Instance).reference;\n      return prepareInstance(singleton, ref);\n    }\n\n    // target is a ReferenceElement\n    if (references.indexOf(target as ReferenceElement) >= 0) {\n      return prepareInstance(singleton, target as ReferenceElement);\n    }\n  };\n\n  singleton.showNext = (): void => {\n    const first = references[0];\n    if (!currentTarget) {\n      return singleton.show(0);\n    }\n    const index = references.indexOf(currentTarget);\n    singleton.show(references[index + 1] || first);\n  };\n\n  singleton.showPrevious = (): void => {\n    const last = references[references.length - 1];\n    if (!currentTarget) {\n      return singleton.show(last);\n    }\n    const index = references.indexOf(currentTarget);\n    const target = references[index - 1] || last;\n    singleton.show(target);\n  };\n\n  const originalSetProps = singleton.setProps;\n\n  singleton.setProps = (props): void => {\n    overrides = props.overrides || overrides;\n    originalSetProps(props);\n  };\n\n  singleton.setInstances = (nextInstances): void => {\n    enableInstances(true);\n    interceptSetPropsCleanups.forEach((fn) => fn());\n\n    individualInstances = nextInstances;\n\n    enableInstances(false);\n    setReferences();\n    setTriggerTargets();\n    interceptSetPropsCleanups = interceptSetProps(singleton);\n\n    singleton.setProps({triggerTarget: triggerTargets});\n  };\n\n  interceptSetPropsCleanups = interceptSetProps(singleton);\n\n  return singleton;\n};\n\nexport default createSingleton;\n", "import tippy from '..';\nimport {TOUCH_OPTIONS} from '../constants';\nimport {defaultProps} from '../props';\nimport {Instance, Props, Targets} from '../types';\nimport {ListenerObject} from '../types-internal';\nimport {normalizeToArray, removeProperties} from '../utils';\nimport {errorWhen} from '../validation';\n\nconst BUBBLING_EVENTS_MAP = {\n  mouseover: 'mouseenter',\n  focusin: 'focus',\n  click: 'click',\n};\n\n/**\n * Creates a delegate instance that controls the creation of tippy instances\n * for child elements (`target` CSS selector).\n */\nfunction delegate(\n  targets: Targets,\n  props: Partial<Props> & {target: string}\n): Instance | Instance[] {\n  /* istanbul ignore else */\n  if (__DEV__) {\n    errorWhen(\n      !(props && props.target),\n      [\n        'You must specity a `target` prop indicating a CSS selector string matching',\n        'the target elements that should receive a tippy.',\n      ].join(' ')\n    );\n  }\n\n  let listeners: ListenerObject[] = [];\n  let childTippyInstances: Instance[] = [];\n  let disabled = false;\n\n  const {target} = props;\n\n  const nativeProps = removeProperties(props, ['target']);\n  const parentProps = {...nativeProps, trigger: 'manual', touch: false};\n  const childProps = {\n    touch: defaultProps.touch,\n    ...nativeProps,\n    showOnCreate: true,\n  };\n\n  const returnValue = tippy(targets, parentProps);\n  const normalizedReturnValue = normalizeToArray(returnValue);\n\n  function onTrigger(event: Event): void {\n    if (!event.target || disabled) {\n      return;\n    }\n\n    const targetNode = (event.target as Element).closest(target);\n\n    if (!targetNode) {\n      return;\n    }\n\n    // Get relevant trigger with fallbacks:\n    // 1. Check `data-tippy-trigger` attribute on target node\n    // 2. Fallback to `trigger` passed to `delegate()`\n    // 3. Fallback to `defaultProps.trigger`\n    const trigger =\n      targetNode.getAttribute('data-tippy-trigger') ||\n      props.trigger ||\n      defaultProps.trigger;\n\n    // @ts-ignore\n    if (targetNode._tippy) {\n      return;\n    }\n\n    if (event.type === 'touchstart' && typeof childProps.touch === 'boolean') {\n      return;\n    }\n\n    if (\n      event.type !== 'touchstart' &&\n      trigger.indexOf((BUBBLING_EVENTS_MAP as any)[event.type]) < 0\n    ) {\n      return;\n    }\n\n    const instance = tippy(targetNode, childProps);\n\n    if (instance) {\n      childTippyInstances = childTippyInstances.concat(instance);\n    }\n  }\n\n  function on(\n    node: Element,\n    eventType: string,\n    handler: EventListener,\n    options: boolean | Record<string, unknown> = false\n  ): void {\n    node.addEventListener(eventType, handler, options);\n    listeners.push({node, eventType, handler, options});\n  }\n\n  function addEventListeners(instance: Instance): void {\n    const {reference} = instance;\n\n    on(reference, 'touchstart', onTrigger, TOUCH_OPTIONS);\n    on(reference, 'mouseover', onTrigger);\n    on(reference, 'focusin', onTrigger);\n    on(reference, 'click', onTrigger);\n  }\n\n  function removeEventListeners(): void {\n    listeners.forEach(({node, eventType, handler, options}: ListenerObject) => {\n      node.removeEventListener(eventType, handler, options);\n    });\n    listeners = [];\n  }\n\n  function applyMutations(instance: Instance): void {\n    const originalDestroy = instance.destroy;\n    const originalEnable = instance.enable;\n    const originalDisable = instance.disable;\n\n    instance.destroy = (shouldDestroyChildInstances = true): void => {\n      if (shouldDestroyChildInstances) {\n        childTippyInstances.forEach((instance) => {\n          instance.destroy();\n        });\n      }\n\n      childTippyInstances = [];\n\n      removeEventListeners();\n      originalDestroy();\n    };\n\n    instance.enable = (): void => {\n      originalEnable();\n      childTippyInstances.forEach((instance) => instance.enable());\n      disabled = false;\n    };\n\n    instance.disable = (): void => {\n      originalDisable();\n      childTippyInstances.forEach((instance) => instance.disable());\n      disabled = true;\n    };\n\n    addEventListeners(instance);\n  }\n\n  normalizedReturnValue.forEach(applyMutations);\n\n  return returnValue;\n}\n\nexport default delegate;\n", "import {BACKDROP_CLASS} from '../constants';\nimport {div, setVisibilityState} from '../dom-utils';\nimport {getChildren} from '../template';\nimport {AnimateFill} from '../types';\nimport {errorWhen} from '../validation';\n\nconst animateFill: AnimateFill = {\n  name: 'animateFill',\n  defaultValue: false,\n  fn(instance) {\n    // @ts-ignore\n    if (!instance.props.render?.$$tippy) {\n      if (__DEV__) {\n        errorWhen(\n          instance.props.animateFill,\n          'The `animateFill` plugin requires the default render function.'\n        );\n      }\n\n      return {};\n    }\n\n    const {box, content} = getChildren(instance.popper);\n\n    const backdrop = instance.props.animateFill\n      ? createBackdropElement()\n      : null;\n\n    return {\n      onCreate(): void {\n        if (backdrop) {\n          box.insertBefore(backdrop, box.firstElementChild!);\n          box.setAttribute('data-animatefill', '');\n          box.style.overflow = 'hidden';\n\n          instance.setProps({arrow: false, animation: 'shift-away'});\n        }\n      },\n      onMount(): void {\n        if (backdrop) {\n          const {transitionDuration} = box.style;\n          const duration = Number(transitionDuration.replace('ms', ''));\n\n          // The content should fade in after the backdrop has mostly filled the\n          // tooltip element. `clip-path` is the other alternative but is not\n          // well-supported and is buggy on some devices.\n          content.style.transitionDelay = `${Math.round(duration / 10)}ms`;\n\n          backdrop.style.transitionDuration = transitionDuration;\n          setVisibilityState([backdrop], 'visible');\n        }\n      },\n      onShow(): void {\n        if (backdrop) {\n          backdrop.style.transitionDuration = '0ms';\n        }\n      },\n      onHide(): void {\n        if (backdrop) {\n          setVisibilityState([backdrop], 'hidden');\n        }\n      },\n    };\n  },\n};\n\nexport default animateFill;\n\nfunction createBackdropElement(): HTMLDivElement {\n  const backdrop = div();\n  backdrop.className = BACKDROP_CLASS;\n  setVisibilityState([backdrop], 'hidden');\n  return backdrop;\n}\n", "import {getOwnerDocument, isMouseEvent} from '../dom-utils';\nimport {FollowCursor, Instance} from '../types';\n\nlet mouseCoords = {clientX: 0, clientY: 0};\nlet activeInstances: Array<{instance: Instance; doc: Document}> = [];\n\nfunction storeMouseCoords({clientX, clientY}: MouseEvent): void {\n  mouseCoords = {clientX, clientY};\n}\n\nfunction addMouseCoordsListener(doc: Document): void {\n  doc.addEventListener('mousemove', storeMouseCoords);\n}\n\nfunction removeMouseCoordsListener(doc: Document): void {\n  doc.removeEventListener('mousemove', storeMouseCoords);\n}\n\nconst followCursor: FollowCursor = {\n  name: 'followCursor',\n  defaultValue: false,\n  fn(instance) {\n    const reference = instance.reference;\n    const doc = getOwnerDocument(instance.props.triggerTarget || reference);\n\n    let isInternalUpdate = false;\n    let wasFocusEvent = false;\n    let isUnmounted = true;\n    let prevProps = instance.props;\n\n    function getIsInitialBehavior(): boolean {\n      return (\n        instance.props.followCursor === 'initial' && instance.state.isVisible\n      );\n    }\n\n    function addListener(): void {\n      doc.addEventListener('mousemove', onMouseMove);\n    }\n\n    function removeListener(): void {\n      doc.removeEventListener('mousemove', onMouseMove);\n    }\n\n    function unsetGetReferenceClientRect(): void {\n      isInternalUpdate = true;\n      instance.setProps({getReferenceClientRect: null});\n      isInternalUpdate = false;\n    }\n\n    function onMouseMove(event: MouseEvent): void {\n      // If the instance is interactive, avoid updating the position unless it's\n      // over the reference element\n      const isCursorOverReference = event.target\n        ? reference.contains(event.target as Node)\n        : true;\n      const {followCursor} = instance.props;\n      const {clientX, clientY} = event;\n\n      const rect = reference.getBoundingClientRect();\n      const relativeX = clientX - rect.left;\n      const relativeY = clientY - rect.top;\n\n      if (isCursorOverReference || !instance.props.interactive) {\n        instance.setProps({\n          // @ts-ignore - unneeded DOMRect properties\n          getReferenceClientRect() {\n            const rect = reference.getBoundingClientRect();\n\n            let x = clientX;\n            let y = clientY;\n\n            if (followCursor === 'initial') {\n              x = rect.left + relativeX;\n              y = rect.top + relativeY;\n            }\n\n            const top = followCursor === 'horizontal' ? rect.top : y;\n            const right = followCursor === 'vertical' ? rect.right : x;\n            const bottom = followCursor === 'horizontal' ? rect.bottom : y;\n            const left = followCursor === 'vertical' ? rect.left : x;\n\n            return {\n              width: right - left,\n              height: bottom - top,\n              top,\n              right,\n              bottom,\n              left,\n            };\n          },\n        });\n      }\n    }\n\n    function create(): void {\n      if (instance.props.followCursor) {\n        activeInstances.push({instance, doc});\n        addMouseCoordsListener(doc);\n      }\n    }\n\n    function destroy(): void {\n      activeInstances = activeInstances.filter(\n        (data) => data.instance !== instance\n      );\n\n      if (activeInstances.filter((data) => data.doc === doc).length === 0) {\n        removeMouseCoordsListener(doc);\n      }\n    }\n\n    return {\n      onCreate: create,\n      onDestroy: destroy,\n      onBeforeUpdate(): void {\n        prevProps = instance.props;\n      },\n      onAfterUpdate(_, {followCursor}): void {\n        if (isInternalUpdate) {\n          return;\n        }\n\n        if (\n          followCursor !== undefined &&\n          prevProps.followCursor !== followCursor\n        ) {\n          destroy();\n\n          if (followCursor) {\n            create();\n\n            if (\n              instance.state.isMounted &&\n              !wasFocusEvent &&\n              !getIsInitialBehavior()\n            ) {\n              addListener();\n            }\n          } else {\n            removeListener();\n            unsetGetReferenceClientRect();\n          }\n        }\n      },\n      onMount(): void {\n        if (instance.props.followCursor && !wasFocusEvent) {\n          if (isUnmounted) {\n            onMouseMove(mouseCoords as MouseEvent);\n            isUnmounted = false;\n          }\n\n          if (!getIsInitialBehavior()) {\n            addListener();\n          }\n        }\n      },\n      onTrigger(_, event): void {\n        if (isMouseEvent(event)) {\n          mouseCoords = {clientX: event.clientX, clientY: event.clientY};\n        }\n        wasFocusEvent = event.type === 'focus';\n      },\n      onHidden(): void {\n        if (instance.props.followCursor) {\n          unsetGetReferenceClientRect();\n          removeListener();\n          isUnmounted = true;\n        }\n      },\n    };\n  },\n};\n\nexport default followCursor;\n", "import {Modifier, Placement} from '@popperjs/core';\nimport {isMouseEvent} from '../dom-utils';\nimport {BasePlacement, InlinePositioning, Props} from '../types';\nimport {arrayFrom, getBasePlacement} from '../utils';\n\nfunction getProps(props: Props, modifier: Modifier<any, any>): Partial<Props> {\n  return {\n    popperOptions: {\n      ...props.popperOptions,\n      modifiers: [\n        ...(props.popperOptions?.modifiers || []).filter(\n          ({name}) => name !== modifier.name\n        ),\n        modifier,\n      ],\n    },\n  };\n}\n\nconst inlinePositioning: InlinePositioning = {\n  name: 'inlinePositioning',\n  defaultValue: false,\n  fn(instance) {\n    const {reference} = instance;\n\n    function isEnabled(): boolean {\n      return !!instance.props.inlinePositioning;\n    }\n\n    let placement: Placement;\n    let cursorRectIndex = -1;\n    let isInternalUpdate = false;\n    let triedPlacements: Array<string> = [];\n\n    const modifier: Modifier<\n      'tippyInlinePositioning',\n      Record<string, unknown>\n    > = {\n      name: 'tippyInlinePositioning',\n      enabled: true,\n      phase: 'afterWrite',\n      fn({state}) {\n        if (isEnabled()) {\n          if (triedPlacements.indexOf(state.placement) !== -1) {\n            triedPlacements = [];\n          }\n\n          if (\n            placement !== state.placement &&\n            triedPlacements.indexOf(state.placement) === -1\n          ) {\n            triedPlacements.push(state.placement);\n            instance.setProps({\n              // @ts-ignore - unneeded DOMRect properties\n              getReferenceClientRect: () =>\n                getReferenceClientRect(state.placement),\n            });\n          }\n\n          placement = state.placement;\n        }\n      },\n    };\n\n    function getReferenceClientRect(placement: Placement): Partial<DOMRect> {\n      return getInlineBoundingClientRect(\n        getBasePlacement(placement),\n        reference.getBoundingClientRect(),\n        arrayFrom(reference.getClientRects()),\n        cursorRectIndex\n      );\n    }\n\n    function setInternalProps(partialProps: Partial<Props>): void {\n      isInternalUpdate = true;\n      instance.setProps(partialProps);\n      isInternalUpdate = false;\n    }\n\n    function addModifier(): void {\n      if (!isInternalUpdate) {\n        setInternalProps(getProps(instance.props, modifier));\n      }\n    }\n\n    return {\n      onCreate: addModifier,\n      onAfterUpdate: addModifier,\n      onTrigger(_, event): void {\n        if (isMouseEvent(event)) {\n          const rects = arrayFrom(instance.reference.getClientRects());\n          const cursorRect = rects.find(\n            (rect) =>\n              rect.left - 2 <= event.clientX &&\n              rect.right + 2 >= event.clientX &&\n              rect.top - 2 <= event.clientY &&\n              rect.bottom + 2 >= event.clientY\n          );\n          const index = rects.indexOf(cursorRect);\n          cursorRectIndex = index > -1 ? index : cursorRectIndex;\n        }\n      },\n      onHidden(): void {\n        cursorRectIndex = -1;\n      },\n    };\n  },\n};\n\nexport default inlinePositioning;\n\nexport function getInlineBoundingClientRect(\n  currentBasePlacement: BasePlacement | null,\n  boundingRect: DOMRect,\n  clientRects: DOMRect[],\n  cursorRectIndex: number\n): {\n  top: number;\n  bottom: number;\n  left: number;\n  right: number;\n  width: number;\n  height: number;\n} {\n  // Not an inline element, or placement is not yet known\n  if (clientRects.length < 2 || currentBasePlacement === null) {\n    return boundingRect;\n  }\n\n  // There are two rects and they are disjoined\n  if (\n    clientRects.length === 2 &&\n    cursorRectIndex >= 0 &&\n    clientRects[0].left > clientRects[1].right\n  ) {\n    return clientRects[cursorRectIndex] || boundingRect;\n  }\n\n  switch (currentBasePlacement) {\n    case 'top':\n    case 'bottom': {\n      const firstRect = clientRects[0];\n      const lastRect = clientRects[clientRects.length - 1];\n      const isTop = currentBasePlacement === 'top';\n\n      const top = firstRect.top;\n      const bottom = lastRect.bottom;\n      const left = isTop ? firstRect.left : lastRect.left;\n      const right = isTop ? firstRect.right : lastRect.right;\n      const width = right - left;\n      const height = bottom - top;\n\n      return {top, bottom, left, right, width, height};\n    }\n    case 'left':\n    case 'right': {\n      const minLeft = Math.min(...clientRects.map((rects) => rects.left));\n      const maxRight = Math.max(...clientRects.map((rects) => rects.right));\n      const measureRects = clientRects.filter((rect) =>\n        currentBasePlacement === 'left'\n          ? rect.left === minLeft\n          : rect.right === maxRight\n      );\n\n      const top = measureRects[0].top;\n      const bottom = measureRects[measureRects.length - 1].bottom;\n      const left = minLeft;\n      const right = maxRight;\n      const width = right - left;\n      const height = bottom - top;\n\n      return {top, bottom, left, right, width, height};\n    }\n    default: {\n      return boundingRect;\n    }\n  }\n}\n", "import {VirtualElement} from '@popperjs/core';\nimport {ReferenceElement, Sticky} from '../types';\n\nconst sticky: Sticky = {\n  name: 'sticky',\n  defaultValue: false,\n  fn(instance) {\n    const {reference, popper} = instance;\n\n    function getReference(): ReferenceElement | VirtualElement {\n      return instance.popperInstance\n        ? instance.popperInstance.state.elements.reference\n        : reference;\n    }\n\n    function shouldCheck(value: 'reference' | 'popper'): boolean {\n      return instance.props.sticky === true || instance.props.sticky === value;\n    }\n\n    let prevRefRect: ClientRect | null = null;\n    let prevPopRect: ClientRect | null = null;\n\n    function updatePosition(): void {\n      const currentRefRect = shouldCheck('reference')\n        ? getReference().getBoundingClientRect()\n        : null;\n      const currentPopRect = shouldCheck('popper')\n        ? popper.getBoundingClientRect()\n        : null;\n\n      if (\n        (currentRefRect && areRectsDifferent(prevRefRect, currentRefRect)) ||\n        (currentPopRect && areRectsDifferent(prevPopRect, currentPopRect))\n      ) {\n        if (instance.popperInstance) {\n          instance.popperInstance.update();\n        }\n      }\n\n      prevRefRect = currentRefRect;\n      prevPopRect = currentPopRect;\n\n      if (instance.state.isMounted) {\n        requestAnimationFrame(updatePosition);\n      }\n    }\n\n    return {\n      onMount(): void {\n        if (instance.props.sticky) {\n          updatePosition();\n        }\n      },\n    };\n  },\n};\n\nexport default sticky;\n\nfunction areRectsDifferent(\n  rectA: ClientRect | null,\n  rectB: ClientRect | null\n): boolean {\n  if (rectA && rectB) {\n    return (\n      rectA.top !== rectB.top ||\n      rectA.right !== rectB.right ||\n      rectA.bottom !== rectB.bottom ||\n      rectA.left !== rectB.left\n    );\n  }\n\n  return true;\n}\n", "import tippy from '../src';\nimport {render} from '../src/template';\n\ntippy.setDefaultProps({render});\n\nexport {default, hideAll} from '../src';\nexport {default as createSingleton} from '../src/addons/createSingleton';\nexport {default as delegate} from '../src/addons/delegate';\nexport {default as animateFill} from '../src/plugins/animateFill';\nexport {default as followCursor} from '../src/plugins/followCursor';\nexport {default as inlinePositioning} from '../src/plugins/inlinePositioning';\nexport {default as sticky} from '../src/plugins/sticky';\nexport {ROUND_ARROW as roundArrow} from '../src/constants';\n", "import {\n  Editor, getText, getTextSerializersFromSchema, posToDOMRect,\n} from '@tiptap/core'\nimport { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { EditorState, Plugin, PluginKey } from '@tiptap/pm/state'\nimport { EditorView } from '@tiptap/pm/view'\nimport tippy, { Instance, Props } from 'tippy.js'\n\nexport interface FloatingMenuPluginProps {\n  /**\n   * The plugin key for the floating menu.\n   * @default 'floatingMenu'\n   */\n  pluginKey: PluginKey | string\n\n  /**\n   * The editor instance.\n   * @default null\n   */\n  editor: Editor\n\n  /**\n   * The DOM element that contains your menu.\n   * @default null\n   */\n  element: HTMLElement\n\n  /**\n   * The options for the tippy instance.\n   * @default {}\n   * @see https://atomiks.github.io/tippyjs/v6/all-props/\n   */\n  tippyOptions?: Partial<Props>\n\n  /**\n   * A function that determines whether the menu should be shown or not.\n   * If this function returns `false`, the menu will be hidden, otherwise it will be shown.\n   * @default null\n   */\n  shouldShow?:\n    | ((props: {\n        editor: Editor\n        view: EditorView\n        state: EditorState\n        oldState?: EditorState\n      }) => boolean)\n    | null\n}\n\nexport type FloatingMenuViewProps = FloatingMenuPluginProps & {\n  /**\n   * The editor view.\n   */\n  view: EditorView\n}\n\nexport class FloatingMenuView {\n  public editor: Editor\n\n  public element: HTMLElement\n\n  public view: EditorView\n\n  public preventHide = false\n\n  public tippy: Instance | undefined\n\n  public tippyOptions?: Partial<Props>\n\n  private getTextContent(node:ProseMirrorNode) {\n    return getText(node, { textSerializers: getTextSerializersFromSchema(this.editor.schema) })\n  }\n\n  public shouldShow: Exclude<FloatingMenuPluginProps['shouldShow'], null> = ({ view, state }) => {\n    const { selection } = state\n    const { $anchor, empty } = selection\n    const isRootDepth = $anchor.depth === 1\n\n    const isEmptyTextBlock = $anchor.parent.isTextblock && !$anchor.parent.type.spec.code && !$anchor.parent.textContent && $anchor.parent.childCount === 0 && !this.getTextContent($anchor.parent)\n\n    if (\n      !view.hasFocus()\n      || !empty\n      || !isRootDepth\n      || !isEmptyTextBlock\n      || !this.editor.isEditable\n    ) {\n      return false\n    }\n\n    return true\n  }\n\n  constructor({\n    editor, element, view, tippyOptions = {}, shouldShow,\n  }: FloatingMenuViewProps) {\n    this.editor = editor\n    this.element = element\n    this.view = view\n\n    if (shouldShow) {\n      this.shouldShow = shouldShow\n    }\n\n    this.element.addEventListener('mousedown', this.mousedownHandler, { capture: true })\n    this.editor.on('focus', this.focusHandler)\n    this.editor.on('blur', this.blurHandler)\n    this.tippyOptions = tippyOptions\n    // Detaches menu content from its current parent\n    this.element.remove()\n    this.element.style.visibility = 'visible'\n  }\n\n  mousedownHandler = () => {\n    this.preventHide = true\n  }\n\n  focusHandler = () => {\n    // we use `setTimeout` to make sure `selection` is already updated\n    setTimeout(() => this.update(this.editor.view))\n  }\n\n  blurHandler = ({ event }: { event: FocusEvent }) => {\n    if (this.preventHide) {\n      this.preventHide = false\n\n      return\n    }\n\n    if (event?.relatedTarget && this.element.parentNode?.contains(event.relatedTarget as Node)) {\n      return\n    }\n\n    if (\n      event?.relatedTarget === this.editor.view.dom\n    ) {\n      return\n    }\n\n    this.hide()\n  }\n\n  tippyBlurHandler = (event: FocusEvent) => {\n    this.blurHandler({ event })\n  }\n\n  createTooltip() {\n    const { element: editorElement } = this.editor.options\n    const editorIsAttached = !!editorElement.parentElement\n\n    this.element.tabIndex = 0\n\n    if (this.tippy || !editorIsAttached) {\n      return\n    }\n\n    this.tippy = tippy(editorElement, {\n      duration: 0,\n      getReferenceClientRect: null,\n      content: this.element,\n      interactive: true,\n      trigger: 'manual',\n      placement: 'right',\n      hideOnClick: 'toggle',\n      ...this.tippyOptions,\n    })\n\n    // maybe we have to hide tippy on its own blur event as well\n    if (this.tippy.popper.firstChild) {\n      (this.tippy.popper.firstChild as HTMLElement).addEventListener('blur', this.tippyBlurHandler)\n    }\n  }\n\n  update(view: EditorView, oldState?: EditorState) {\n    const { state } = view\n    const { doc, selection } = state\n    const { from, to } = selection\n    const isSame = oldState && oldState.doc.eq(doc) && oldState.selection.eq(selection)\n\n    if (isSame) {\n      return\n    }\n\n    this.createTooltip()\n\n    const shouldShow = this.shouldShow?.({\n      editor: this.editor,\n      view,\n      state,\n      oldState,\n    })\n\n    if (!shouldShow) {\n      this.hide()\n\n      return\n    }\n\n    this.tippy?.setProps({\n      getReferenceClientRect:\n        this.tippyOptions?.getReferenceClientRect || (() => posToDOMRect(view, from, to)),\n    })\n\n    this.show()\n  }\n\n  show() {\n    this.tippy?.show()\n  }\n\n  hide() {\n    this.tippy?.hide()\n  }\n\n  destroy() {\n    if (this.tippy?.popper.firstChild) {\n      (this.tippy.popper.firstChild as HTMLElement).removeEventListener(\n        'blur',\n        this.tippyBlurHandler,\n      )\n    }\n    this.tippy?.destroy()\n    this.element.removeEventListener('mousedown', this.mousedownHandler, { capture: true })\n    this.editor.off('focus', this.focusHandler)\n    this.editor.off('blur', this.blurHandler)\n  }\n}\n\nexport const FloatingMenuPlugin = (options: FloatingMenuPluginProps) => {\n  return new Plugin({\n    key:\n      typeof options.pluginKey === 'string' ? new PluginKey(options.pluginKey) : options.pluginKey,\n    view: view => new FloatingMenuView({ view, ...options }),\n  })\n}\n", "import { Extension } from '@tiptap/core'\n\nimport { FloatingMenuPlugin, FloatingMenuPluginProps } from './floating-menu-plugin.js'\n\nexport type FloatingMenuOptions = Omit<FloatingMenuPluginProps, 'editor' | 'element'> & {\n  /**\n   * The DOM element that contains your menu.\n   * @type {HTMLElement}\n   * @default null\n   */\n  element: HTMLElement | null,\n}\n\n/**\n * This extension allows you to create a floating menu.\n * @see https://tiptap.dev/api/extensions/floating-menu\n */\nexport const FloatingMenu = Extension.create<FloatingMenuOptions>({\n  name: 'floatingMenu',\n\n  addOptions() {\n    return {\n      element: null,\n      tippyOptions: {},\n      pluginKey: 'floatingMenu',\n      shouldShow: null,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    if (!this.options.element) {\n      return []\n    }\n\n    return [\n      FloatingMenuPlugin({\n        pluginKey: this.options.pluginKey,\n        editor: this.editor,\n        element: this.options.element,\n        tippyOptions: this.options.tippyOptions,\n        shouldShow: this.options.shouldShow,\n      }),\n    ]\n  },\n})\n", "// THIS FILE IS AUTOMATICALLY GENERATED DO NOT EDIT DIRECTLY\n// See update-tlds.js for encoding/decoding format\n// https://data.iana.org/TLD/tlds-alpha-by-domain.txt\nconst encodedTlds = 'aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos6kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5m\u00F6gensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12b0cam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2';\n// Internationalized domain names containing non-ASCII\nconst encodedUtlds = '\u03B5\u03BB1\u03C52\u0431\u04331\u0435\u043B3\u0434\u0435\u0442\u04384\u0435\u044E2\u043A\u0430\u0442\u043E\u043B\u0438\u043A6\u043E\u043C3\u043C\u043A\u04342\u043E\u043D1\u0441\u043A\u0432\u04306\u043E\u043D\u043B\u0430\u0439\u043D5\u0440\u04333\u0440\u0443\u04412\u04442\u0441\u0430\u0439\u04423\u0440\u04313\u0443\u043A\u04403\u049B\u0430\u04373\u0570\u0561\u05753\u05D9\u05E9\u05E8\u05D0\u05DC5\u05E7\u05D5\u05DD3\u0627\u0628\u0648\u0638\u0628\u064A5\u0631\u0627\u0645\u0643\u06485\u0644\u0627\u0631\u062F\u06464\u0628\u062D\u0631\u064A\u06465\u062C\u0632\u0627\u0626\u06315\u0633\u0639\u0648\u062F\u064A\u06296\u0639\u0644\u064A\u0627\u06465\u0645\u063A\u0631\u06285\u0645\u0627\u0631\u0627\u062A5\u06CC\u0631\u0627\u06465\u0628\u0627\u0631\u062A2\u0632\u0627\u06314\u064A\u062A\u06433\u06BE\u0627\u0631\u062A5\u062A\u0648\u0646\u06334\u0633\u0648\u062F\u0627\u06463\u0631\u064A\u06295\u0634\u0628\u0643\u06294\u0639\u0631\u0627\u06422\u06282\u0645\u0627\u06464\u0641\u0644\u0633\u0637\u064A\u06466\u0642\u0637\u06313\u0643\u0627\u062B\u0648\u0644\u064A\u06436\u0648\u06453\u0645\u0635\u06312\u0644\u064A\u0633\u064A\u06275\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u06277\u0642\u06394\u0647\u0645\u0631\u0627\u06475\u067E\u0627\u06A9\u0633\u062A\u0627\u06467\u0680\u0627\u0631\u062A4\u0915\u0949\u092E3\u0928\u0947\u091F3\u092D\u093E\u0930\u09240\u092E\u094D3\u094B\u09245\u0938\u0902\u0917\u0920\u09285\u09AC\u09BE\u0982\u09B2\u09BE5\u09AD\u09BE\u09B0\u09A42\u09F0\u09A44\u0A2D\u0A3E\u0A30\u0A244\u0AAD\u0ABE\u0AB0\u0AA44\u0B2D\u0B3E\u0B30\u0B244\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE6\u0BB2\u0B99\u0BCD\u0B95\u0BC86\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD11\u0C2D\u0C3E\u0C30\u0C24\u0C4D5\u0CAD\u0CBE\u0CB0\u0CA44\u0D2D\u0D3E\u0D30\u0D24\u0D025\u0DBD\u0D82\u0D9A\u0DCF4\u0E04\u0E2D\u0E213\u0E44\u0E17\u0E223\u0EA5\u0EB2\u0EA73\u10D2\u10D42\u307F\u3093\u306A3\u30A2\u30DE\u30BE\u30F34\u30AF\u30E9\u30A6\u30C94\u30B0\u30FC\u30B0\u30EB4\u30B3\u30E02\u30B9\u30C8\u30A23\u30BB\u30FC\u30EB3\u30D5\u30A1\u30C3\u30B7\u30E7\u30F36\u30DD\u30A4\u30F3\u30C84\u4E16\u754C2\u4E2D\u4FE11\u56FD1\u570B1\u6587\u7F513\u4E9A\u9A6C\u900A3\u4F01\u4E1A2\u4F5B\u5C712\u4FE1\u606F2\u5065\u5EB72\u516B\u53662\u516C\u53F81\u76CA2\u53F0\u6E7E1\u70632\u5546\u57CE1\u5E971\u68072\u5609\u91CC0\u5927\u9152\u5E975\u5728\u7EBF2\u5927\u62FF2\u5929\u4E3B\u65593\u5A31\u4E502\u5BB6\u96FB2\u5E7F\u4E1C2\u5FAE\u535A2\u6148\u55842\u6211\u7231\u4F603\u624B\u673A2\u62DB\u80582\u653F\u52A11\u5E9C2\u65B0\u52A0\u57612\u95FB2\u65F6\u5C1A2\u66F8\u7C4D2\u673A\u67842\u6DE1\u9A6C\u95213\u6E38\u620F2\u6FB3\u95802\u70B9\u770B2\u79FB\u52A82\u7EC4\u7EC7\u673A\u67844\u7F51\u57401\u5E971\u7AD91\u7EDC2\u8054\u901A2\u8C37\u6B4C2\u8D2D\u72692\u901A\u8CA92\u96C6\u56E22\u96FB\u8A0A\u76C8\u79D14\u98DE\u5229\u6D663\u98DF\u54C12\u9910\u53852\u9999\u683C\u91CC\u62C93\u6E2F2\uB2F7\uB1371\uCEF42\uC0BC\uC1312\uD55C\uAD6D2';\n\n/**\n * Finite State Machine generation utilities\n */\n\n/**\n * @template T\n * @typedef {{ [group: string]: T[] }} Collections\n */\n\n/**\n * @typedef {{ [group: string]: true }} Flags\n */\n\n// Keys in scanner Collections instances\nconst numeric = 'numeric';\nconst ascii = 'ascii';\nconst alpha = 'alpha';\nconst asciinumeric = 'asciinumeric';\nconst alphanumeric = 'alphanumeric';\nconst domain = 'domain';\nconst emoji = 'emoji';\nconst scheme = 'scheme';\nconst slashscheme = 'slashscheme';\nconst whitespace = 'whitespace';\n\n/**\n * @template T\n * @param {string} name\n * @param {Collections<T>} groups to register in\n * @returns {T[]} Current list of tokens in the given collection\n */\nfunction registerGroup(name, groups) {\n  if (!(name in groups)) {\n    groups[name] = [];\n  }\n  return groups[name];\n}\n\n/**\n * @template T\n * @param {T} t token to add\n * @param {Collections<T>} groups\n * @param {Flags} flags\n */\nfunction addToGroups(t, flags, groups) {\n  if (flags[numeric]) {\n    flags[asciinumeric] = true;\n    flags[alphanumeric] = true;\n  }\n  if (flags[ascii]) {\n    flags[asciinumeric] = true;\n    flags[alpha] = true;\n  }\n  if (flags[asciinumeric]) {\n    flags[alphanumeric] = true;\n  }\n  if (flags[alpha]) {\n    flags[alphanumeric] = true;\n  }\n  if (flags[alphanumeric]) {\n    flags[domain] = true;\n  }\n  if (flags[emoji]) {\n    flags[domain] = true;\n  }\n  for (const k in flags) {\n    const group = registerGroup(k, groups);\n    if (group.indexOf(t) < 0) {\n      group.push(t);\n    }\n  }\n}\n\n/**\n * @template T\n * @param {T} t token to check\n * @param {Collections<T>} groups\n * @returns {Flags} group flags that contain this token\n */\nfunction flagsForToken(t, groups) {\n  const result = {};\n  for (const c in groups) {\n    if (groups[c].indexOf(t) >= 0) {\n      result[c] = true;\n    }\n  }\n  return result;\n}\n\n/**\n * @template T\n * @typedef {null | T } Transition\n */\n\n/**\n * Define a basic state machine state. j is the list of character transitions,\n * jr is the list of regex-match transitions, jd is the default state to\n * transition to t is the accepting token type, if any. If this is the terminal\n * state, then it does not emit a token.\n *\n * The template type T represents the type of the token this state accepts. This\n * should be a string (such as of the token exports in `text.js`) or a\n * MultiToken subclass (from `multi.js`)\n *\n * @template T\n * @param {T} [token] Token that this state emits\n */\nfunction State(token = null) {\n  // this.n = null; // DEBUG: State name\n  /** @type {{ [input: string]: State<T> }} j */\n  this.j = {}; // IMPLEMENTATION 1\n  // this.j = []; // IMPLEMENTATION 2\n  /** @type {[RegExp, State<T>][]} jr */\n  this.jr = [];\n  /** @type {?State<T>} jd */\n  this.jd = null;\n  /** @type {?T} t */\n  this.t = token;\n}\n\n/**\n * Scanner token groups\n * @type Collections<string>\n */\nState.groups = {};\nState.prototype = {\n  accepts() {\n    return !!this.t;\n  },\n  /**\n   * Follow an existing transition from the given input to the next state.\n   * Does not mutate.\n   * @param {string} input character or token type to transition on\n   * @returns {?State<T>} the next state, if any\n   */\n  go(input) {\n    const state = this;\n    const nextState = state.j[input];\n    if (nextState) {\n      return nextState;\n    }\n    for (let i = 0; i < state.jr.length; i++) {\n      const regex = state.jr[i][0];\n      const nextState = state.jr[i][1]; // note: might be empty to prevent default jump\n      if (nextState && regex.test(input)) {\n        return nextState;\n      }\n    }\n    // Nowhere left to jump! Return default, if any\n    return state.jd;\n  },\n  /**\n   * Whether the state has a transition for the given input. Set the second\n   * argument to true to only look for an exact match (and not a default or\n   * regular-expression-based transition)\n   * @param {string} input\n   * @param {boolean} exactOnly\n   */\n  has(input, exactOnly = false) {\n    return exactOnly ? input in this.j : !!this.go(input);\n  },\n  /**\n   * Short for \"transition all\"; create a transition from the array of items\n   * in the given list to the same final resulting state.\n   * @param {string | string[]} inputs Group of inputs to transition on\n   * @param {Transition<T> | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of token groups\n   */\n  ta(inputs, next, flags, groups) {\n    for (let i = 0; i < inputs.length; i++) {\n      this.tt(inputs[i], next, flags, groups);\n    }\n  },\n  /**\n   * Short for \"take regexp transition\"; defines a transition for this state\n   * when it encounters a token which matches the given regular expression\n   * @param {RegExp} regexp Regular expression transition (populate first)\n   * @param {T | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of token groups\n   * @returns {State<T>} taken after the given input\n   */\n  tr(regexp, next, flags, groups) {\n    groups = groups || State.groups;\n    let nextState;\n    if (next && next.j) {\n      nextState = next;\n    } else {\n      // Token with maybe token groups\n      nextState = new State(next);\n      if (flags && groups) {\n        addToGroups(next, flags, groups);\n      }\n    }\n    this.jr.push([regexp, nextState]);\n    return nextState;\n  },\n  /**\n   * Short for \"take transitions\", will take as many sequential transitions as\n   * the length of the given input and returns the\n   * resulting final state.\n   * @param {string | string[]} input\n   * @param {T | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of token groups\n   * @returns {State<T>} taken after the given input\n   */\n  ts(input, next, flags, groups) {\n    let state = this;\n    const len = input.length;\n    if (!len) {\n      return state;\n    }\n    for (let i = 0; i < len - 1; i++) {\n      state = state.tt(input[i]);\n    }\n    return state.tt(input[len - 1], next, flags, groups);\n  },\n  /**\n   * Short for \"take transition\", this is a method for building/working with\n   * state machines.\n   *\n   * If a state already exists for the given input, returns it.\n   *\n   * If a token is specified, that state will emit that token when reached by\n   * the linkify engine.\n   *\n   * If no state exists, it will be initialized with some default transitions\n   * that resemble existing default transitions.\n   *\n   * If a state is given for the second argument, that state will be\n   * transitioned to on the given input regardless of what that input\n   * previously did.\n   *\n   * Specify a token group flags to define groups that this token belongs to.\n   * The token will be added to corresponding entires in the given groups\n   * object.\n   *\n   * @param {string} input character, token type to transition on\n   * @param {T | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of groups\n   * @returns {State<T>} taken after the given input\n   */\n  tt(input, next, flags, groups) {\n    groups = groups || State.groups;\n    const state = this;\n\n    // Check if existing state given, just a basic transition\n    if (next && next.j) {\n      state.j[input] = next;\n      return next;\n    }\n    const t = next;\n\n    // Take the transition with the usual default mechanisms and use that as\n    // a template for creating the next state\n    let nextState,\n      templateState = state.go(input);\n    if (templateState) {\n      nextState = new State();\n      Object.assign(nextState.j, templateState.j);\n      nextState.jr.push.apply(nextState.jr, templateState.jr);\n      nextState.jd = templateState.jd;\n      nextState.t = templateState.t;\n    } else {\n      nextState = new State();\n    }\n    if (t) {\n      // Ensure newly token is in the same groups as the old token\n      if (groups) {\n        if (nextState.t && typeof nextState.t === 'string') {\n          const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags);\n          addToGroups(t, allFlags, groups);\n        } else if (flags) {\n          addToGroups(t, flags, groups);\n        }\n      }\n      nextState.t = t; // overwrite anything that was previously there\n    }\n    state.j[input] = nextState;\n    return nextState;\n  }\n};\n\n// Helper functions to improve minification (not exported outside linkifyjs module)\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {string | string[]} input\n * @param {Flags} [flags]\n * @param {Collections<T>} [groups]\n */\nconst ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {RegExp} regexp\n * @param {T | State<T>} [next]\n * @param {Flags} [flags]\n * @param {Collections<T>} [groups]\n */\nconst tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups);\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {string | string[]} input\n * @param {T | State<T>} [next]\n * @param {Flags} [flags]\n * @param {Collections<T>} [groups]\n */\nconst ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {string} input\n * @param {T | State<T>} [next]\n * @param {Collections<T>} [groups]\n * @param {Flags} [flags]\n */\nconst tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups);\n\n/******************************************************************************\nText Tokens\nIdentifiers for token outputs from the regexp scanner\n******************************************************************************/\n\n// A valid web domain token\nconst WORD = 'WORD'; // only contains a-z\nconst UWORD = 'UWORD'; // contains letters other than a-z, used for IDN\nconst ASCIINUMERICAL = 'ASCIINUMERICAL'; // contains a-z, 0-9\nconst ALPHANUMERICAL = 'ALPHANUMERICAL'; // contains numbers and letters other than a-z, used for IDN\n\n// Special case of word\nconst LOCALHOST = 'LOCALHOST';\n\n// Valid top-level domain, special case of WORD (see tlds.js)\nconst TLD = 'TLD';\n\n// Valid IDN TLD, special case of UWORD (see tlds.js)\nconst UTLD = 'UTLD';\n\n// The scheme portion of a web URI protocol. Supported types include: `mailto`,\n// `file`, and user-defined custom protocols. Limited to schemes that contain\n// only letters\nconst SCHEME = 'SCHEME';\n\n// Similar to SCHEME, except makes distinction for schemes that must always be\n// followed by `://`, not just `:`. Supported types include `http`, `https`,\n// `ftp`, `ftps`\nconst SLASH_SCHEME = 'SLASH_SCHEME';\n\n// Any sequence of digits 0-9\nconst NUM = 'NUM';\n\n// Any number of consecutive whitespace characters that are not newline\nconst WS = 'WS';\n\n// New line (unix style)\nconst NL = 'NL'; // \\n\n\n// Opening/closing bracket classes\n// TODO: Rename OPEN -> LEFT and CLOSE -> RIGHT in v5 to fit with Unicode names\n// Also rename angle brackes to LESSTHAN and GREATER THAN\nconst OPENBRACE = 'OPENBRACE'; // {\nconst CLOSEBRACE = 'CLOSEBRACE'; // }\nconst OPENBRACKET = 'OPENBRACKET'; // [\nconst CLOSEBRACKET = 'CLOSEBRACKET'; // ]\nconst OPENPAREN = 'OPENPAREN'; // (\nconst CLOSEPAREN = 'CLOSEPAREN'; // )\nconst OPENANGLEBRACKET = 'OPENANGLEBRACKET'; // <\nconst CLOSEANGLEBRACKET = 'CLOSEANGLEBRACKET'; // >\nconst FULLWIDTHLEFTPAREN = 'FULLWIDTHLEFTPAREN'; // \uFF08\nconst FULLWIDTHRIGHTPAREN = 'FULLWIDTHRIGHTPAREN'; // \uFF09\nconst LEFTCORNERBRACKET = 'LEFTCORNERBRACKET'; // \u300C\nconst RIGHTCORNERBRACKET = 'RIGHTCORNERBRACKET'; // \u300D\nconst LEFTWHITECORNERBRACKET = 'LEFTWHITECORNERBRACKET'; // \u300E\nconst RIGHTWHITECORNERBRACKET = 'RIGHTWHITECORNERBRACKET'; // \u300F\nconst FULLWIDTHLESSTHAN = 'FULLWIDTHLESSTHAN'; // \uFF1C\nconst FULLWIDTHGREATERTHAN = 'FULLWIDTHGREATERTHAN'; // \uFF1E\n\n// Various symbols\nconst AMPERSAND = 'AMPERSAND'; // &\nconst APOSTROPHE = 'APOSTROPHE'; // '\nconst ASTERISK = 'ASTERISK'; // *\nconst AT = 'AT'; // @\nconst BACKSLASH = 'BACKSLASH'; // \\\nconst BACKTICK = 'BACKTICK'; // `\nconst CARET = 'CARET'; // ^\nconst COLON = 'COLON'; // :\nconst COMMA = 'COMMA'; // ,\nconst DOLLAR = 'DOLLAR'; // $\nconst DOT = 'DOT'; // .\nconst EQUALS = 'EQUALS'; // =\nconst EXCLAMATION = 'EXCLAMATION'; // !\nconst HYPHEN = 'HYPHEN'; // -\nconst PERCENT = 'PERCENT'; // %\nconst PIPE = 'PIPE'; // |\nconst PLUS = 'PLUS'; // +\nconst POUND = 'POUND'; // #\nconst QUERY = 'QUERY'; // ?\nconst QUOTE = 'QUOTE'; // \"\nconst FULLWIDTHMIDDLEDOT = 'FULLWIDTHMIDDLEDOT'; // \u30FB\n\nconst SEMI = 'SEMI'; // ;\nconst SLASH = 'SLASH'; // /\nconst TILDE = 'TILDE'; // ~\nconst UNDERSCORE = 'UNDERSCORE'; // _\n\n// Emoji symbol\nconst EMOJI$1 = 'EMOJI';\n\n// Default token - anything that is not one of the above\nconst SYM = 'SYM';\n\nvar tk = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tALPHANUMERICAL: ALPHANUMERICAL,\n\tAMPERSAND: AMPERSAND,\n\tAPOSTROPHE: APOSTROPHE,\n\tASCIINUMERICAL: ASCIINUMERICAL,\n\tASTERISK: ASTERISK,\n\tAT: AT,\n\tBACKSLASH: BACKSLASH,\n\tBACKTICK: BACKTICK,\n\tCARET: CARET,\n\tCLOSEANGLEBRACKET: CLOSEANGLEBRACKET,\n\tCLOSEBRACE: CLOSEBRACE,\n\tCLOSEBRACKET: CLOSEBRACKET,\n\tCLOSEPAREN: CLOSEPAREN,\n\tCOLON: COLON,\n\tCOMMA: COMMA,\n\tDOLLAR: DOLLAR,\n\tDOT: DOT,\n\tEMOJI: EMOJI$1,\n\tEQUALS: EQUALS,\n\tEXCLAMATION: EXCLAMATION,\n\tFULLWIDTHGREATERTHAN: FULLWIDTHGREATERTHAN,\n\tFULLWIDTHLEFTPAREN: FULLWIDTHLEFTPAREN,\n\tFULLWIDTHLESSTHAN: FULLWIDTHLESSTHAN,\n\tFULLWIDTHMIDDLEDOT: FULLWIDTHMIDDLEDOT,\n\tFULLWIDTHRIGHTPAREN: FULLWIDTHRIGHTPAREN,\n\tHYPHEN: HYPHEN,\n\tLEFTCORNERBRACKET: LEFTCORNERBRACKET,\n\tLEFTWHITECORNERBRACKET: LEFTWHITECORNERBRACKET,\n\tLOCALHOST: LOCALHOST,\n\tNL: NL,\n\tNUM: NUM,\n\tOPENANGLEBRACKET: OPENANGLEBRACKET,\n\tOPENBRACE: OPENBRACE,\n\tOPENBRACKET: OPENBRACKET,\n\tOPENPAREN: OPENPAREN,\n\tPERCENT: PERCENT,\n\tPIPE: PIPE,\n\tPLUS: PLUS,\n\tPOUND: POUND,\n\tQUERY: QUERY,\n\tQUOTE: QUOTE,\n\tRIGHTCORNERBRACKET: RIGHTCORNERBRACKET,\n\tRIGHTWHITECORNERBRACKET: RIGHTWHITECORNERBRACKET,\n\tSCHEME: SCHEME,\n\tSEMI: SEMI,\n\tSLASH: SLASH,\n\tSLASH_SCHEME: SLASH_SCHEME,\n\tSYM: SYM,\n\tTILDE: TILDE,\n\tTLD: TLD,\n\tUNDERSCORE: UNDERSCORE,\n\tUTLD: UTLD,\n\tUWORD: UWORD,\n\tWORD: WORD,\n\tWS: WS\n});\n\n// Note that these two Unicode ones expand into a really big one with Babel\nconst ASCII_LETTER = /[a-z]/;\n// `\\p{}` property escapes need ICU, which some embedded JS runtimes ship\n// without (e.g. NativeScript's V8). The literal form throws a SyntaxError\n// at parse time \u2014 before any user code can catch it \u2014 so build them\n// dynamically and keep ASCII-range fallbacks for engines without Unicode\n// property escapes.\nlet LETTER = /[a-z]/i; // Any Unicode character with letter data type\nlet EMOJI = /[\\u{1F000}-\\u{1FAFF}\\u{2600}-\\u{27BF}]|\\u{FE0F}/u; // Any Unicode emoji character\n\ntry {\n  LETTER = new RegExp('\\\\p{L}', 'u');\n  EMOJI = new RegExp('\\\\p{Emoji}', 'u');\n} catch {\n  // use ASCII fallbacks\n}\nconst EMOJI_VARIATION$1 = /\\ufe0f/;\nconst DIGIT = /\\d/;\nconst SPACE = /\\s/;\n\nvar regexp = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tASCII_LETTER: ASCII_LETTER,\n\tDIGIT: DIGIT,\n\tget EMOJI () { return EMOJI; },\n\tEMOJI_VARIATION: EMOJI_VARIATION$1,\n\tget LETTER () { return LETTER; },\n\tSPACE: SPACE\n});\n\n/**\n\tThe scanner provides an interface that takes a string of text as input, and\n\toutputs an array of tokens instances that can be used for easy URL parsing.\n*/\n\nconst CR = '\\r'; // carriage-return character\nconst LF = '\\n'; // line-feed character\nconst EMOJI_VARIATION = '\\ufe0f'; // Variation selector, follows heart and others\nconst EMOJI_JOINER = '\\u200d'; // zero-width joiner\nconst OBJECT_REPLACEMENT = '\\ufffc'; // whitespace placeholder that sometimes appears in rich text editors\n\nlet tlds = null,\n  utlds = null; // don't change so only have to be computed once\n\n/**\n * Scanner output token:\n * - `t` is the token name (e.g., 'NUM', 'EMOJI', 'TLD')\n * - `v` is the value of the token (e.g., '123', '\u2764\uFE0F', 'com')\n * - `s` is the start index of the token in the original string\n * - `e` is the end index of the token in the original string\n * @typedef {{t: string, v: string, s: number, e: number}} Token\n */\n\n/**\n * @template T\n * @typedef {{ [collection: string]: T[] }} Collections\n */\n\n/**\n * Initialize the scanner character-based state machine for the given start\n * state\n * @param {[string, boolean][]} customSchemes List of custom schemes, where each\n * item is a length-2 tuple with the first element set to the string scheme, and\n * the second element set to `true` if the `://` after the scheme is optional\n */\nfunction init$2(customSchemes = []) {\n  // Frequently used states (name argument removed during minification)\n  /** @type Collections<string> */\n  const groups = {}; // of tokens\n  State.groups = groups;\n  /** @type State<string> */\n  const Start = new State();\n  if (tlds == null) {\n    tlds = decodeTlds(encodedTlds);\n  }\n  if (utlds == null) {\n    utlds = decodeTlds(encodedUtlds);\n  }\n\n  // States for special URL symbols that accept immediately after start\n  tt(Start, \"'\", APOSTROPHE);\n  tt(Start, '{', OPENBRACE);\n  tt(Start, '}', CLOSEBRACE);\n  tt(Start, '[', OPENBRACKET);\n  tt(Start, ']', CLOSEBRACKET);\n  tt(Start, '(', OPENPAREN);\n  tt(Start, ')', CLOSEPAREN);\n  tt(Start, '<', OPENANGLEBRACKET);\n  tt(Start, '>', CLOSEANGLEBRACKET);\n  tt(Start, '\uFF08', FULLWIDTHLEFTPAREN);\n  tt(Start, '\uFF09', FULLWIDTHRIGHTPAREN);\n  tt(Start, '\u300C', LEFTCORNERBRACKET);\n  tt(Start, '\u300D', RIGHTCORNERBRACKET);\n  tt(Start, '\u300E', LEFTWHITECORNERBRACKET);\n  tt(Start, '\u300F', RIGHTWHITECORNERBRACKET);\n  tt(Start, '\uFF1C', FULLWIDTHLESSTHAN);\n  tt(Start, '\uFF1E', FULLWIDTHGREATERTHAN);\n  tt(Start, '&', AMPERSAND);\n  tt(Start, '*', ASTERISK);\n  tt(Start, '@', AT);\n  tt(Start, '`', BACKTICK);\n  tt(Start, '^', CARET);\n  tt(Start, ':', COLON);\n  tt(Start, ',', COMMA);\n  tt(Start, '$', DOLLAR);\n  tt(Start, '.', DOT);\n  tt(Start, '=', EQUALS);\n  tt(Start, '!', EXCLAMATION);\n  tt(Start, '-', HYPHEN);\n  tt(Start, '%', PERCENT);\n  tt(Start, '|', PIPE);\n  tt(Start, '+', PLUS);\n  tt(Start, '#', POUND);\n  tt(Start, '?', QUERY);\n  tt(Start, '\"', QUOTE);\n  tt(Start, '/', SLASH);\n  tt(Start, ';', SEMI);\n  tt(Start, '~', TILDE);\n  tt(Start, '_', UNDERSCORE);\n  tt(Start, '\\\\', BACKSLASH);\n  tt(Start, '\u30FB', FULLWIDTHMIDDLEDOT);\n  const Num = tr(Start, DIGIT, NUM, {\n    [numeric]: true\n  });\n  tr(Num, DIGIT, Num);\n  const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, {\n    [asciinumeric]: true\n  });\n  const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, {\n    [alphanumeric]: true\n  });\n\n  // State which emits a word token\n  const Word = tr(Start, ASCII_LETTER, WORD, {\n    [ascii]: true\n  });\n  tr(Word, DIGIT, Asciinumeric);\n  tr(Word, ASCII_LETTER, Word);\n  tr(Asciinumeric, DIGIT, Asciinumeric);\n  tr(Asciinumeric, ASCII_LETTER, Asciinumeric);\n\n  // Same as previous, but specific to non-fsm.ascii alphabet words\n  const UWord = tr(Start, LETTER, UWORD, {\n    [alpha]: true\n  });\n  tr(UWord, ASCII_LETTER); // Non-accepting\n  tr(UWord, DIGIT, Alphanumeric);\n  tr(UWord, LETTER, UWord);\n  tr(Alphanumeric, DIGIT, Alphanumeric);\n  tr(Alphanumeric, ASCII_LETTER); // Non-accepting\n  tr(Alphanumeric, LETTER, Alphanumeric); // Non-accepting\n\n  // Whitespace jumps\n  // Tokens of only non-newline whitespace are arbitrarily long\n  // If any whitespace except newline, more whitespace!\n  const Nl = tt(Start, LF, NL, {\n    [whitespace]: true\n  });\n  const Cr = tt(Start, CR, WS, {\n    [whitespace]: true\n  });\n  const Ws = tr(Start, SPACE, WS, {\n    [whitespace]: true\n  });\n  tt(Start, OBJECT_REPLACEMENT, Ws);\n  tt(Cr, LF, Nl); // \\r\\n\n  tt(Cr, OBJECT_REPLACEMENT, Ws);\n  tr(Cr, SPACE, Ws);\n  tt(Ws, CR); // non-accepting state to avoid mixing whitespaces\n  tt(Ws, LF); // non-accepting state to avoid mixing whitespaces\n  tr(Ws, SPACE, Ws);\n  tt(Ws, OBJECT_REPLACEMENT, Ws);\n\n  // Emoji tokens. They are not grouped by the scanner except in cases where a\n  // zero-width joiner is present\n  const Emoji = tr(Start, EMOJI, EMOJI$1, {\n    [emoji]: true\n  });\n  tt(Emoji, '#'); // no transition, emoji regex seems to match #\n  tr(Emoji, EMOJI, Emoji);\n  tt(Emoji, EMOJI_VARIATION, Emoji);\n  // tt(Start, EMOJI_VARIATION, Emoji); // This one is sketchy\n\n  const EmojiJoiner = tt(Emoji, EMOJI_JOINER);\n  tt(EmojiJoiner, '#');\n  tr(EmojiJoiner, EMOJI, Emoji);\n  // tt(EmojiJoiner, EMOJI_VARIATION, Emoji); // also sketchy\n\n  // Generates states for top-level domains\n  // Note that this is most accurate when tlds are in alphabetical order\n  const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];\n  const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];\n  for (let i = 0; i < tlds.length; i++) {\n    fastts(Start, tlds[i], TLD, WORD, wordjr);\n  }\n  for (let i = 0; i < utlds.length; i++) {\n    fastts(Start, utlds[i], UTLD, UWORD, uwordjr);\n  }\n  addToGroups(TLD, {\n    tld: true,\n    ascii: true\n  }, groups);\n  addToGroups(UTLD, {\n    utld: true,\n    alpha: true\n  }, groups);\n\n  // Collect the states generated by different protocols. NOTE: If any new TLDs\n  // get added that are also protocols, set the token to be the same as the\n  // protocol to ensure parsing works as expected.\n  fastts(Start, 'file', SCHEME, WORD, wordjr);\n  fastts(Start, 'mailto', SCHEME, WORD, wordjr);\n  fastts(Start, 'http', SLASH_SCHEME, WORD, wordjr);\n  fastts(Start, 'https', SLASH_SCHEME, WORD, wordjr);\n  fastts(Start, 'ftp', SLASH_SCHEME, WORD, wordjr);\n  fastts(Start, 'ftps', SLASH_SCHEME, WORD, wordjr);\n  addToGroups(SCHEME, {\n    scheme: true,\n    ascii: true\n  }, groups);\n  addToGroups(SLASH_SCHEME, {\n    slashscheme: true,\n    ascii: true\n  }, groups);\n\n  // Register custom schemes. Assumes each scheme is asciinumeric with hyphens\n  customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1);\n  for (let i = 0; i < customSchemes.length; i++) {\n    const sch = customSchemes[i][0];\n    const optionalSlashSlash = customSchemes[i][1];\n    const flags = optionalSlashSlash ? {\n      [scheme]: true\n    } : {\n      [slashscheme]: true\n    };\n    if (sch.indexOf('-') >= 0) {\n      flags[domain] = true;\n    } else if (!ASCII_LETTER.test(sch)) {\n      flags[numeric] = true; // numbers only\n    } else if (DIGIT.test(sch)) {\n      flags[asciinumeric] = true;\n    } else {\n      flags[ascii] = true;\n    }\n    ts(Start, sch, sch, flags);\n  }\n\n  // Localhost token\n  ts(Start, 'localhost', LOCALHOST, {\n    ascii: true\n  });\n\n  // Set default transition for start state (some symbol)\n  Start.jd = new State(SYM);\n  return {\n    start: Start,\n    tokens: Object.assign({\n      groups\n    }, tk)\n  };\n}\n\n/**\n\tGiven a string, returns an array of TOKEN instances representing the\n\tcomposition of that string.\n\n\t@method run\n\t@param {State<string>} start scanner starting state\n\t@param {string} str input string to scan\n\t@return {Token[]} list of tokens, each with a type and value\n*/\nfunction run$1(start, str) {\n  // State machine is not case sensitive, so input is tokenized in lowercased\n  // form (still returns regular case). Uses selective `toLowerCase` because\n  // lowercasing the entire string causes the length and character position to\n  // vary in some non-English strings with V8-based runtimes.\n  const iterable = stringToArray(str.replace(/[A-Z]/g, c => c.toLowerCase()));\n  const charCount = iterable.length; // <= len if there are emojis, etc\n  const tokens = []; // return value\n\n  // cursor through the string itself, accounting for characters that have\n  // width with length 2 such as emojis\n  let cursor = 0;\n\n  // Cursor through the array-representation of the string\n  let charCursor = 0;\n\n  // Tokenize the string\n  while (charCursor < charCount) {\n    let state = start;\n    let nextState = null;\n    let tokenLength = 0;\n    let latestAccepting = null;\n    let sinceAccepts = -1;\n    let charsSinceAccepts = -1;\n    while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {\n      state = nextState;\n\n      // Keep track of the latest accepting state\n      if (state.accepts()) {\n        sinceAccepts = 0;\n        charsSinceAccepts = 0;\n        latestAccepting = state;\n      } else if (sinceAccepts >= 0) {\n        sinceAccepts += iterable[charCursor].length;\n        charsSinceAccepts++;\n      }\n      tokenLength += iterable[charCursor].length;\n      cursor += iterable[charCursor].length;\n      charCursor++;\n    }\n\n    // Roll back to the latest accepting state\n    cursor -= sinceAccepts;\n    charCursor -= charsSinceAccepts;\n    tokenLength -= sinceAccepts;\n\n    // No more jumps, just make a new token from the last accepting one\n    tokens.push({\n      t: latestAccepting.t,\n      // token type/name\n      v: str.slice(cursor - tokenLength, cursor),\n      // string value\n      s: cursor - tokenLength,\n      // start index\n      e: cursor // end index (excluding)\n    });\n  }\n  return tokens;\n}\n\n/**\n * Convert a String to an Array of characters, taking into account that some\n * characters like emojis take up two string indexes.\n *\n * Adapted from core-js (MIT license)\n * https://github.com/zloirock/core-js/blob/2d69cf5f99ab3ea3463c395df81e5a15b68f49d9/packages/core-js/internals/string-multibyte.js\n *\n * @function stringToArray\n * @param {string} str\n * @returns {string[]}\n */\nfunction stringToArray(str) {\n  const result = [];\n  const len = str.length;\n  let index = 0;\n  while (index < len) {\n    let first = str.charCodeAt(index);\n    let second;\n    let char = first < 0xd800 || first > 0xdbff || index + 1 === len || (second = str.charCodeAt(index + 1)) < 0xdc00 || second > 0xdfff ? str[index] // single character\n    : str.slice(index, index + 2); // two-index characters\n    result.push(char);\n    index += char.length;\n  }\n  return result;\n}\n\n/**\n * Fast version of ts function for when transition defaults are well known\n * @param {State<string>} state\n * @param {string} input\n * @param {string} t\n * @param {string} defaultt\n * @param {[RegExp, State<string>][]} jr\n * @returns {State<string>}\n */\nfunction fastts(state, input, t, defaultt, jr) {\n  let next;\n  const len = input.length;\n  for (let i = 0; i < len - 1; i++) {\n    const char = input[i];\n    if (state.j[char]) {\n      next = state.j[char];\n    } else {\n      next = new State(defaultt);\n      next.jr = jr.slice();\n      state.j[char] = next;\n    }\n    state = next;\n  }\n  next = new State(t);\n  next.jr = jr.slice();\n  state.j[input[len - 1]] = next;\n  return next;\n}\n\n/**\n * Converts a string of Top-Level Domain names encoded in update-tlds.js back\n * into a list of strings.\n * @param {str} encoded encoded TLDs string\n * @returns {str[]} original TLDs list\n */\nfunction decodeTlds(encoded) {\n  const words = [];\n  const stack = [];\n  let i = 0;\n  let digits = '0123456789';\n  while (i < encoded.length) {\n    let popDigitCount = 0;\n    while (digits.indexOf(encoded[i + popDigitCount]) >= 0) {\n      popDigitCount++; // encountered some digits, have to pop to go one level up trie\n    }\n    if (popDigitCount > 0) {\n      words.push(stack.join('')); // whatever preceded the pop digits must be a word\n      for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) {\n        stack.pop();\n      }\n      i += popDigitCount;\n    } else {\n      stack.push(encoded[i]); // drop down a level into the trie\n      i++;\n    }\n  }\n  return words;\n}\n\n/**\n * An object where each key is a valid DOM Event Name such as `click` or `focus`\n * and each value is an event handler function.\n *\n * https://developer.mozilla.org/en-US/docs/Web/API/Element#events\n * @typedef {?{ [event: string]: Function }} EventListeners\n */\n\n/**\n * All formatted properties required to render a link, including `tagName`,\n * `attributes`, `content` and `eventListeners`.\n * @typedef {{ tagName: any, attributes: {[attr: string]: any}, content: string,\n * eventListeners: EventListeners }} IntermediateRepresentation\n */\n\n/**\n * Specify either an object described by the template type `O` or a function.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `O`\n * @template O\n * @typedef {O | ((value: string, type: string, token: MultiToken) => O)} OptObj\n */\n\n/**\n * Specify either a function described by template type `F` or an object.\n *\n * Each key in the object should be a link type (`'url'`, `'hashtag`', etc.). Each\n * value should be a function with template type `F` that is called when the\n * corresponding link type is encountered.\n * @template F\n * @typedef {F | { [type: string]: F}} OptFn\n */\n\n/**\n * Specify either a value with template type `V`, a function that returns `V` or\n * an object where each value resolves to `V`.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `V`\n *\n * For the object, each key should be a link type (`'url'`, `'hashtag`', etc.).\n * Each value should either have type `V` or a function that returns V. This\n * function similarly takes a string value and a token.\n *\n * Example valid types for `Opt<string>`:\n *\n * ```js\n * 'hello'\n * (value, type, token) => 'world'\n * { url: 'hello', email: (value, token) => 'world'}\n * ```\n * @template V\n * @typedef {V | ((value: string, type: string, token: MultiToken) => V) | { [type: string]: V | ((value: string, token: MultiToken) => V) }} Opt\n */\n\n/**\n * See available options: https://linkify.js.org/docs/options.html\n * @typedef {{\n * \tdefaultProtocol?: string,\n *  events?: OptObj<EventListeners>,\n * \tformat?: Opt<string>,\n * \tformatHref?: Opt<string>,\n * \tnl2br?: boolean,\n * \ttagName?: Opt<any>,\n * \ttarget?: Opt<string>,\n * \trel?: Opt<string>,\n * \tvalidate?: Opt<boolean>,\n * \ttruncate?: Opt<number>,\n * \tclassName?: Opt<string>,\n * \tattributes?: OptObj<({ [attr: string]: any })>,\n *  ignoreTags?: string[],\n *  ignoreClasses?: string[],\n * \trender?: OptFn<((ir: IntermediateRepresentation) => any)>\n * }} Opts\n */\n\n/**\n * @type Required<Opts>\n */\nconst defaults = {\n  defaultProtocol: 'http',\n  events: null,\n  format: noop,\n  formatHref: noop,\n  nl2br: false,\n  tagName: 'a',\n  target: null,\n  rel: null,\n  validate: true,\n  truncate: Infinity,\n  className: null,\n  attributes: null,\n  ignoreTags: [],\n  ignoreClasses: [],\n  render: null\n};\n\n/**\n * Utility class for linkify interfaces to apply specified\n * {@link Opts formatting and rendering options}.\n *\n * @param {Opts | Options} [opts] Option value overrides.\n * @param {(ir: IntermediateRepresentation) => any} [defaultRender] (For\n *   internal use) default render function that determines how to generate an\n *   HTML element based on a link token's derived tagName, attributes and HTML.\n *   Similar to render option\n */\nfunction Options(opts, defaultRender = null) {\n  let o = Object.assign({}, defaults);\n  if (opts) {\n    o = Object.assign(o, opts instanceof Options ? opts.o : opts);\n  }\n\n  // Ensure all ignored tags are uppercase\n  const ignoredTags = o.ignoreTags;\n  const uppercaseIgnoredTags = [];\n  for (let i = 0; i < ignoredTags.length; i++) {\n    uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase());\n  }\n  /** @protected */\n  this.o = o;\n  if (defaultRender) {\n    this.defaultRender = defaultRender;\n  }\n  this.ignoreTags = uppercaseIgnoredTags;\n  this.ignoreClasses = o.ignoreClasses.slice();\n}\nOptions.prototype = {\n  o: defaults,\n  /**\n   * @type string[]\n   */\n  ignoreTags: [],\n  /**\n   * @type string[]\n   */\n  ignoreClasses: [],\n  /**\n   * Returns whether a whitespace-separated class attribute contains an\n   * ignored class name.\n   * @param {unknown} classNames\n   * @returns {boolean}\n   */\n  isIgnoredClass(classNames) {\n    if (typeof classNames !== 'string' || this.ignoreClasses.length === 0) {\n      return false;\n    }\n    const classes = classNames.split(/\\s+/);\n    for (let i = 0; i < classes.length; i++) {\n      if (this.ignoreClasses.indexOf(classes[i]) >= 0) {\n        return true;\n      }\n    }\n    return false;\n  },\n  /**\n   * @param {IntermediateRepresentation} ir\n   * @returns {any}\n   */\n  defaultRender(ir) {\n    return ir;\n  },\n  /**\n   * Returns true or false based on whether a token should be displayed as a\n   * link based on the user options.\n   * @param {MultiToken} token\n   * @returns {boolean}\n   */\n  check(token) {\n    return this.get('validate', token.toString(), token);\n  },\n  // Private methods\n\n  /**\n   * Resolve an option's value based on the value of the option and the given\n   * params. If operator and token are specified and the target option is\n   * callable, automatically calls the function with the given argument.\n   * @template {keyof Opts} K\n   * @param {K} key Name of option to use\n   * @param {string} [operator] will be passed to the target option if it's a\n   * function. If not specified, RAW function value gets returned\n   * @param {MultiToken} [token] The token from linkify.tokenize\n   * @returns {Opts[K] | any}\n   */\n  get(key, operator, token) {\n    const isCallable = operator != null;\n    let option = this.o[key];\n    if (!option) {\n      return option;\n    }\n    if (typeof option === 'object') {\n      option = token.t in option ? option[token.t] : defaults[key];\n      if (typeof option === 'function' && isCallable) {\n        option = option(operator, token);\n      }\n    } else if (typeof option === 'function' && isCallable) {\n      option = option(operator, token.t, token);\n    }\n    return option;\n  },\n  /**\n   * @template {keyof Opts} L\n   * @param {L} key Name of options object to use\n   * @param {string} [operator]\n   * @param {MultiToken} [token]\n   * @returns {Opts[L] | any}\n   */\n  getObj(key, operator, token) {\n    let obj = this.o[key];\n    if (typeof obj === 'function' && operator != null) {\n      obj = obj(operator, token.t, token);\n    }\n    return obj;\n  },\n  /**\n   * Convert the given token to a rendered element that may be added to the\n   * calling-interface's DOM\n   * @param {MultiToken} token Token to render to an HTML element\n   * @returns {any} Render result; e.g., HTML string, DOM element, React\n   *   Component, etc.\n   */\n  render(token) {\n    const ir = token.render(this); // intermediate representation\n    const renderFn = this.get('render', null, token) || this.defaultRender;\n    return renderFn(ir, token.t, token);\n  }\n};\nfunction noop(val) {\n  return val;\n}\n\nvar options = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tOptions: Options,\n\tdefaults: defaults\n});\n\n/******************************************************************************\n\tMulti-Tokens\n\tTokens composed of arrays of TextTokens\n******************************************************************************/\n\n/**\n * @param {string} value\n * @param {Token[]} tokens\n */\nfunction MultiToken(value, tokens) {\n  this.t = 'token';\n  this.v = value;\n  this.tk = tokens;\n}\n\n/**\n * Abstract class used for manufacturing tokens of text tokens. That is rather\n * than the value for a token being a small string of text, it's value an array\n * of text tokens.\n *\n * Used for grouping together URLs, emails, hashtags, and other potential\n * creations.\n * @class MultiToken\n * @property {string} t\n * @property {string} v\n * @property {Token[]} tk\n * @abstract\n */\nMultiToken.prototype = {\n  isLink: false,\n  /**\n   * Return the string this token represents.\n   * @return {string}\n   */\n  toString() {\n    return this.v;\n  },\n  /**\n   * What should the value for this token be in the `href` HTML attribute?\n   * Returns the `.toString` value by default.\n   * @param {string} [scheme]\n   * @return {string}\n   */\n  toHref(scheme) {\n    return this.toString();\n  },\n  /**\n   * @param {Options} options Formatting options\n   * @returns {string}\n   */\n  toFormattedString(options) {\n    const val = this.toString();\n    const truncate = options.get('truncate', val, this);\n    const formatted = options.get('format', val, this);\n    return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + '\u2026' : formatted;\n  },\n  /**\n   *\n   * @param {Options} options\n   * @returns {string}\n   */\n  toFormattedHref(options) {\n    return options.get('formatHref', this.toHref(options.get('defaultProtocol')), this);\n  },\n  /**\n   * The start index of this token in the original input string\n   * @returns {number}\n   */\n  startIndex() {\n    return this.tk[0].s;\n  },\n  /**\n   * The end index of this token in the original input string (up to this\n   * index but not including it)\n   * @returns {number}\n   */\n  endIndex() {\n    return this.tk[this.tk.length - 1].e;\n  },\n  /**\n  \tReturns an object  of relevant values for this token, which includes keys\n  \t* type - Kind of token ('url', 'email', etc.)\n  \t* value - Original text\n  \t* href - The value that should be added to the anchor tag's href\n  \t\tattribute\n  \t\t@method toObject\n  \t@param {string} [protocol] `'http'` by default\n  */\n  toObject(protocol = defaults.defaultProtocol) {\n    return {\n      type: this.t,\n      value: this.toString(),\n      isLink: this.isLink,\n      href: this.toHref(protocol),\n      start: this.startIndex(),\n      end: this.endIndex()\n    };\n  },\n  /**\n   *\n   * @param {Options} options Formatting option\n   */\n  toFormattedObject(options) {\n    return {\n      type: this.t,\n      value: this.toFormattedString(options),\n      isLink: this.isLink,\n      href: this.toFormattedHref(options),\n      start: this.startIndex(),\n      end: this.endIndex()\n    };\n  },\n  /**\n   * Whether this token should be rendered as a link according to the given options\n   * @param {Options} options\n   * @returns {boolean}\n   */\n  validate(options) {\n    return options.get('validate', this.toString(), this);\n  },\n  /**\n   * Return an object that represents how this link should be rendered.\n   * @param {Options} options Formattinng options\n   */\n  render(options) {\n    const token = this;\n    const href = this.toHref(options.get('defaultProtocol'));\n    const formattedHref = options.get('formatHref', href, this);\n    const tagName = options.get('tagName', href, token);\n    const content = this.toFormattedString(options);\n    const attributes = {};\n    const className = options.get('className', href, token);\n    const target = options.get('target', href, token);\n    const rel = options.get('rel', href, token);\n    const attrs = options.getObj('attributes', href, token);\n    const eventListeners = options.getObj('events', href, token);\n    attributes.href = formattedHref;\n    if (className) {\n      attributes.class = className;\n    }\n    if (target) {\n      attributes.target = target;\n    }\n    if (rel) {\n      attributes.rel = rel;\n    }\n    if (attrs) {\n      Object.assign(attributes, attrs);\n    }\n    return {\n      tagName,\n      attributes,\n      content,\n      eventListeners\n    };\n  }\n};\n\n/**\n * Create a new token that can be emitted by the parser state machine\n * @param {string} type readable type of the token\n * @param {object} props properties to assign or override, including isLink = true or false\n * @returns {new (value: string, tokens: Token[]) => MultiToken} new token class\n */\nfunction createTokenClass(type, props) {\n  class Token extends MultiToken {\n    constructor(value, tokens) {\n      super(value, tokens);\n      this.t = type;\n    }\n  }\n  for (const p in props) {\n    Token.prototype[p] = props[p];\n  }\n  Token.t = type;\n  return Token;\n}\n\n/**\n\tRepresents a list of tokens making up a valid email address\n*/\nconst Email = createTokenClass('email', {\n  isLink: true,\n  toHref() {\n    return 'mailto:' + this.toString();\n  }\n});\n\n/**\n\tRepresents some plain text\n*/\nconst Text = createTokenClass('text');\n\n/**\n\tMulti-linebreak token - represents a line break\n\t@class Nl\n*/\nconst Nl = createTokenClass('nl');\n\n/**\n\tRepresents a list of text tokens making up a valid URL\n\t@class Url\n*/\nconst Url = createTokenClass('url', {\n  isLink: true,\n  /**\n  \tLowercases relevant parts of the domain and adds the protocol if\n  \trequired. Note that this will not escape unsafe HTML characters in the\n  \tURL.\n  \t\t@param {string} [scheme] default scheme (e.g., 'https')\n  \t@return {string} the full href\n  */\n  toHref(scheme = defaults.defaultProtocol) {\n    // Check if already has a prefix scheme\n    return this.hasProtocol() ? this.v : `${scheme}://${this.v}`;\n  },\n  /**\n   * Check whether this URL token has a protocol\n   * @return {boolean}\n   */\n  hasProtocol() {\n    const tokens = this.tk;\n    return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;\n  }\n});\n\nvar multi = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tBase: MultiToken,\n\tEmail: Email,\n\tMultiToken: MultiToken,\n\tNl: Nl,\n\tText: Text,\n\tUrl: Url,\n\tcreateTokenClass: createTokenClass\n});\n\n/**\n\tNot exactly parser, more like the second-stage scanner (although we can\n\ttheoretically hotswap the code here with a real parser in the future... but\n\tfor a little URL-finding utility abstract syntax trees may be a little\n\toverkill).\n\n\tURL format: http://en.wikipedia.org/wiki/URI_scheme\n\tEmail format: http://en.wikipedia.org/wiki/EmailAddress (links to RFC in\n\treference)\n\n\t@module linkify\n\t@submodule parser\n\t@main run\n*/\n\nconst makeState = arg => new State(arg);\n\n/**\n * Generate the parser multi token-based state machine\n * @param {{ groups: Collections<string> }} tokens\n */\nfunction init$1({\n  groups\n}) {\n  // Types of characters the URL can definitely end in\n  const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);\n\n  // Types of tokens that can follow a URL and be part of the query string\n  // but cannot be the very last characters\n  // Characters that cannot appear in the URL at all should be excluded\n  const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];\n\n  // For addresses without the mailto prefix\n  // Tokens allowed in the localpart of the email\n  const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];\n\n  // The universal starting state.\n  /**\n   * @type State<Token>\n   */\n  const Start = makeState();\n  const Localpart = tt(Start, TILDE); // Local part of the email address\n  ta(Localpart, localpartAccepting, Localpart);\n  ta(Localpart, groups.domain, Localpart);\n  const Domain = makeState(),\n    Scheme = makeState(),\n    SlashScheme = makeState();\n  ta(Start, groups.domain, Domain); // parsed string ends with a potential domain name (A)\n  ta(Start, groups.scheme, Scheme); // e.g., 'mailto'\n  ta(Start, groups.slashscheme, SlashScheme); // e.g., 'http'\n\n  ta(Domain, localpartAccepting, Localpart);\n  ta(Domain, groups.domain, Domain);\n  const LocalpartAt = tt(Domain, AT); // Local part of the email address plus @\n\n  tt(Localpart, AT, LocalpartAt); // close to an email address now\n\n  // Local part of an email address can be e.g. 'http' or 'mailto'\n  tt(Scheme, AT, LocalpartAt);\n  tt(SlashScheme, AT, LocalpartAt);\n  const LocalpartDot = tt(Localpart, DOT); // Local part of the email address plus '.' (localpart cannot end in .)\n  ta(LocalpartDot, localpartAccepting, Localpart);\n  ta(LocalpartDot, groups.domain, Localpart);\n  const EmailDomain = makeState();\n  ta(LocalpartAt, groups.domain, EmailDomain); // parsed string starts with local email info + @ with a potential domain name\n  ta(EmailDomain, groups.domain, EmailDomain);\n  const EmailDomainDot = tt(EmailDomain, DOT); // domain followed by DOT\n  ta(EmailDomainDot, groups.domain, EmailDomain);\n  const Email$1 = makeState(Email); // Possible email address (could have more tlds)\n  ta(EmailDomainDot, groups.tld, Email$1);\n  ta(EmailDomainDot, groups.utld, Email$1);\n  tt(LocalpartAt, LOCALHOST, Email$1);\n\n  // Hyphen can jump back to a domain name\n  const EmailDomainHyphen = tt(EmailDomain, HYPHEN); // parsed string starts with local email info + @ with a potential domain name\n  tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);\n  ta(EmailDomainHyphen, groups.domain, EmailDomain);\n  ta(Email$1, groups.domain, EmailDomain);\n  tt(Email$1, DOT, EmailDomainDot);\n  tt(Email$1, HYPHEN, EmailDomainHyphen);\n\n  // Account for dots and hyphens. Hyphens are usually parts of domain names\n  // (but not TLDs)\n  const DomainHyphen = tt(Domain, HYPHEN); // domain followed by hyphen\n  const DomainDot = tt(Domain, DOT); // domain followed by DOT\n  tt(DomainHyphen, HYPHEN, DomainHyphen);\n  ta(DomainHyphen, groups.domain, Domain);\n  ta(DomainDot, localpartAccepting, Localpart);\n  ta(DomainDot, groups.domain, Domain);\n  const DomainDotTld = makeState(Url); // Simplest possible URL with no query string\n  ta(DomainDot, groups.tld, DomainDotTld);\n  ta(DomainDot, groups.utld, DomainDotTld);\n  ta(DomainDotTld, groups.domain, Domain);\n  ta(DomainDotTld, localpartAccepting, Localpart);\n  tt(DomainDotTld, DOT, DomainDot);\n  tt(DomainDotTld, HYPHEN, DomainHyphen);\n  tt(DomainDotTld, AT, LocalpartAt);\n  const DomainDotTldColon = tt(DomainDotTld, COLON); // URL followed by colon (potential port number here)\n  const DomainDotTldColonPort = makeState(Url); // TLD followed by a port number\n  ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);\n\n  // Long URL with optional port and maybe query string\n  const Url$1 = makeState(Url);\n\n  // URL with extra symbols at the end, followed by an opening bracket\n  const UrlNonaccept = makeState(); // URL followed by some symbols (will not be part of the final URL)\n\n  // Query strings\n  ta(Url$1, qsAccepting, Url$1);\n  ta(Url$1, qsNonAccepting, UrlNonaccept);\n  ta(UrlNonaccept, qsAccepting, Url$1);\n  ta(UrlNonaccept, qsNonAccepting, UrlNonaccept);\n\n  // Become real URLs after `SLASH` or `COLON NUM SLASH`\n  // Here works with or without scheme:// prefix\n  tt(DomainDotTld, SLASH, Url$1);\n  tt(DomainDotTldColonPort, SLASH, Url$1);\n\n  // A query string or fragment may also follow the domain (or port) directly,\n  // without a path slash (e.g. `example.com?q=1`, `example.com#frag`). Mirror\n  // how the `Url` state treats these tokens: `?` is non-accepting (a trailing\n  // `?` is trimmed), `#` is accepting.\n  tt(DomainDotTld, QUERY, UrlNonaccept);\n  tt(DomainDotTld, POUND, Url$1);\n  tt(DomainDotTldColonPort, QUERY, UrlNonaccept);\n  tt(DomainDotTldColonPort, POUND, Url$1);\n\n  // Note that domains that begin with schemes are treated slighly differently\n  const SchemeColon = tt(Scheme, COLON); // e.g., 'mailto:'\n  const SlashSchemeColon = tt(SlashScheme, COLON); // e.g., 'http:'\n  const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH); // e.g., 'http:/'\n\n  const UriPrefix = tt(SlashSchemeColonSlash, SLASH); // e.g., 'http://'\n\n  // Scheme states can transition to domain states\n  ta(Scheme, groups.domain, Domain);\n  tt(Scheme, DOT, DomainDot);\n  tt(Scheme, HYPHEN, DomainHyphen);\n  ta(SlashScheme, groups.domain, Domain);\n  tt(SlashScheme, DOT, DomainDot);\n  tt(SlashScheme, HYPHEN, DomainHyphen);\n\n  // Force URL with scheme prefix followed by anything sane\n  ta(SchemeColon, groups.domain, Url$1);\n  tt(SchemeColon, SLASH, Url$1);\n  tt(SchemeColon, QUERY, Url$1);\n  ta(UriPrefix, groups.domain, Url$1);\n  ta(UriPrefix, qsAccepting, Url$1);\n  tt(UriPrefix, SLASH, Url$1);\n  const bracketPairs = [[OPENBRACE, CLOSEBRACE],\n  // {}\n  [OPENBRACKET, CLOSEBRACKET],\n  // []\n  [OPENPAREN, CLOSEPAREN],\n  // ()\n  [OPENANGLEBRACKET, CLOSEANGLEBRACKET],\n  // <>\n  [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],\n  // \uFF08\uFF09\n  [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],\n  // \u300C\u300D\n  [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],\n  // \u300E\u300F\n  [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] // \uFF1C\uFF1E\n  ];\n  for (let i = 0; i < bracketPairs.length; i++) {\n    const [OPEN, CLOSE] = bracketPairs[i];\n    const UrlOpen = tt(Url$1, OPEN); // URL followed by open bracket\n\n    // Continue not accepting for open brackets\n    tt(UrlNonaccept, OPEN, UrlOpen);\n\n    // URL that begins with an opening bracket, followed by a symbols.\n    // Note that the final state can still be `UrlOpen` (if the URL has a\n    // single opening bracket for some reason).\n    const UrlOpenQ = makeState(Url);\n    ta(UrlOpen, qsAccepting, UrlOpenQ);\n    const UrlOpenSyms = makeState(); // UrlOpen followed by some symbols it cannot end it\n    ta(UrlOpen, qsNonAccepting, UrlOpenSyms);\n\n    // Closing bracket component. This character WILL be included in the URL.\n    // Must come after qsNonAccepting (which includes all close-bracket tokens)\n    // so that CLOSE -> Url wins over CLOSE -> UrlOpenSyms.\n    tt(UrlOpen, CLOSE, Url$1);\n\n    // URL that begins with an opening bracket, followed by some symbols\n    ta(UrlOpenQ, qsAccepting, UrlOpenQ);\n    ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms);\n    ta(UrlOpenSyms, qsAccepting, UrlOpenQ);\n    ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);\n\n    // Close brace/bracket to become regular URL\n    tt(UrlOpenQ, CLOSE, Url$1);\n    tt(UrlOpenSyms, CLOSE, Url$1);\n  }\n  tt(Start, LOCALHOST, DomainDotTld); // localhost is a valid URL state\n  tt(Start, NL, Nl); // single new line\n\n  return {\n    start: Start,\n    tokens: tk\n  };\n}\n\n/**\n * Run the parser state machine on a list of scanned string-based tokens to\n * create a list of multi tokens, each of which represents a URL, email address,\n * plain text, etc.\n *\n * @param {State<MultiToken>} start parser start state\n * @param {string} input the original input used to generate the given tokens\n * @param {Token[]} tokens list of scanned tokens\n * @returns {MultiToken[]}\n */\nfunction run(start, input, tokens) {\n  let len = tokens.length;\n  let cursor = 0;\n  let multis = [];\n  let textTokens = [];\n\n  // Memo of parser states that are known not to lead to any accepting state\n  // when reached at a given cursor position. dead[i] is a Set of states that,\n  // once reached right before tokens[i], can never reach another accepting\n  // state. Because the parser is deterministic, a run that reaches one of\n  // these (state, cursor) pairs can stop there with the same result as\n  // continuing. Without this, inputs where every token can extend a\n  // potential link that never completes (e.g., 'a.a.a.a.\u2026') make each\n  // failed attempt rescan to the end of the input, which is quadratic.\n  // See https://github.com/Hypercontext/linkifyjs/issues/568\n  /** @type {Array<Set<State<MultiToken>> | undefined>} */\n  const dead = [];\n  while (cursor < len) {\n    let state = start;\n    let secondState = null;\n    let nextState = null;\n    let multiLength = 0;\n    let latestAccepting = null;\n    let sinceAccepts = -1;\n    // States reached since the latest accepting state (or since the start\n    // of this attempt), in order. visited[k] is the state reached right\n    // before tokens[cursor - visited.length + k + 1]\n    let visited = [];\n    while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {\n      // Starting tokens with nowhere to jump to.\n      // Consider these to be just plain text\n      textTokens.push(tokens[cursor++]);\n    }\n    while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {\n      // Get the next state\n      secondState = null;\n      state = nextState;\n      cursor++;\n      multiLength++;\n\n      // Keep track of the latest accepting state\n      if (state.accepts()) {\n        sinceAccepts = 0;\n        latestAccepting = state;\n        visited = [];\n      } else {\n        if (sinceAccepts >= 0) {\n          sinceAccepts++;\n        }\n        visited.push(state);\n        if (dead[cursor] && dead[cursor].has(state)) {\n          // Already known that no accepting state is reachable from here\n          break;\n        }\n      }\n    }\n\n    // None of the states visited since the latest accepting state lead to\n    // another accepting state; remember them so later attempts that reach\n    // the same state at the same position can stop early.\n    for (let k = 0, pos = cursor - visited.length + 1; k < visited.length; k++, pos++) {\n      (dead[pos] || (dead[pos] = new Set())).add(visited[k]);\n    }\n    if (sinceAccepts < 0) {\n      // No accepting state was found, part of a regular text token add\n      // the first text token to the text tokens array and try again from\n      // the next\n      cursor -= multiLength;\n      if (cursor < len) {\n        textTokens.push(tokens[cursor]);\n        cursor++;\n      }\n    } else {\n      // Accepting state!\n      // First close off the textTokens (if available)\n      if (textTokens.length > 0) {\n        multis.push(initMultiToken(Text, input, textTokens));\n        textTokens = [];\n      }\n\n      // Roll back to the latest accepting state\n      cursor -= sinceAccepts;\n      multiLength -= sinceAccepts;\n\n      // Create a new multitoken\n      const Multi = latestAccepting.t;\n      const subtokens = tokens.slice(cursor - multiLength, cursor);\n      multis.push(initMultiToken(Multi, input, subtokens));\n    }\n  }\n\n  // Finally close off the textTokens (if available)\n  if (textTokens.length > 0) {\n    multis.push(initMultiToken(Text, input, textTokens));\n  }\n  return multis;\n}\n\n/**\n * Utility function for instantiating a new multitoken with all the relevant\n * fields during parsing.\n * @param {new (value: string, tokens: Token[]) => MultiToken} Multi class to instantiate\n * @param {string} input original input string\n * @param {Token[]} tokens consecutive tokens scanned from input string\n * @returns {MultiToken}\n */\nfunction initMultiToken(Multi, input, tokens) {\n  const startIdx = tokens[0].s;\n  const endIdx = tokens[tokens.length - 1].e;\n  const value = input.slice(startIdx, endIdx);\n  return new Multi(value, tokens);\n}\n\nconst warn = typeof console !== 'undefined' && console && console.warn || (() => {});\nconst warnAdvice = 'until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.';\n\n// Side-effect initialization state\nconst INIT = {\n  scanner: null,\n  parser: null,\n  tokenQueue: [],\n  pluginQueue: [],\n  customSchemes: [],\n  initialized: false\n};\n\n/**\n * @typedef {{\n * \tstart: State<string>,\n * \ttokens: { groups: Collections<string> } & typeof tk\n * }} ScannerInit\n */\n\n/**\n * @typedef {{\n * \tstart: State<MultiToken>,\n * \ttokens: typeof multi\n * }} ParserInit\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit }) => void} TokenPlugin\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit, parser: ParserInit }) => void} Plugin\n */\n\n/**\n * De-register all plugins and reset the internal state-machine. Used for\n * testing; not required in practice.\n * @private\n */\nfunction reset() {\n  State.groups = {};\n  INIT.scanner = null;\n  INIT.parser = null;\n  INIT.tokenQueue = [];\n  INIT.pluginQueue = [];\n  INIT.customSchemes = [];\n  INIT.initialized = false;\n  return INIT;\n}\n\n/**\n * Register a token plugin to allow the scanner to recognize additional token\n * types before the parser state machine is constructed from the results.\n * @param {string} name of plugin to register\n * @param {TokenPlugin} plugin function that accepts the scanner state machine\n * and available scanner tokens and collections and extends the state machine to\n * recognize additional tokens or groups.\n */\nfunction registerTokenPlugin(name, plugin) {\n  if (typeof plugin !== 'function') {\n    throw new Error(`linkifyjs: Invalid token plugin ${plugin} (expects function)`);\n  }\n  for (let i = 0; i < INIT.tokenQueue.length; i++) {\n    if (name === INIT.tokenQueue[i][0]) {\n      warn(`linkifyjs: token plugin \"${name}\" already registered - will be overwritten`);\n      INIT.tokenQueue[i] = [name, plugin];\n      return;\n    }\n  }\n  INIT.tokenQueue.push([name, plugin]);\n  if (INIT.initialized) {\n    warn(`linkifyjs: already initialized - will not register token plugin \"${name}\" ${warnAdvice}`);\n  }\n}\n\n/**\n * Register a linkify plugin\n * @param {string} name of plugin to register\n * @param {Plugin} plugin function that accepts the parser state machine and\n * extends the parser to recognize additional link types\n */\nfunction registerPlugin(name, plugin) {\n  if (typeof plugin !== 'function') {\n    throw new Error(`linkifyjs: Invalid plugin ${plugin} (expects function)`);\n  }\n  for (let i = 0; i < INIT.pluginQueue.length; i++) {\n    if (name === INIT.pluginQueue[i][0]) {\n      warn(`linkifyjs: plugin \"${name}\" already registered - will be overwritten`);\n      INIT.pluginQueue[i] = [name, plugin];\n      return;\n    }\n  }\n  INIT.pluginQueue.push([name, plugin]);\n  if (INIT.initialized) {\n    warn(`linkifyjs: already initialized - will not register plugin \"${name}\" ${warnAdvice}`);\n  }\n}\n\n/**\n * Detect URLs with the following additional protocol. Anything with format\n * \"protocol://...\" will be considered a link. If `optionalSlashSlash` is set to\n * `true`, anything with format \"protocol:...\" will be considered a link.\n * @param {string} scheme\n * @param {boolean} [optionalSlashSlash]\n */\nfunction registerCustomProtocol(scheme, optionalSlashSlash = false) {\n  if (INIT.initialized) {\n    warn(`linkifyjs: already initialized - will not register custom scheme \"${scheme}\" ${warnAdvice}`);\n  }\n  if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme)) {\n    throw new Error(`linkifyjs: incorrect scheme format.\n1. Must only contain digits, lowercase ASCII letters or \"-\"\n2. Cannot start or end with \"-\"\n3. \"-\" cannot repeat`);\n  }\n  INIT.customSchemes.push([scheme, optionalSlashSlash]);\n}\n\n/**\n * Initialize the linkify state machine. Called automatically the first time\n * linkify is called on a string, but may be called manually as well.\n */\nfunction init() {\n  // Initialize scanner state machine and plugins\n  INIT.scanner = init$2(INIT.customSchemes);\n  for (let i = 0; i < INIT.tokenQueue.length; i++) {\n    INIT.tokenQueue[i][1]({\n      scanner: INIT.scanner\n    });\n  }\n\n  // Initialize parser state machine and plugins\n  INIT.parser = init$1(INIT.scanner.tokens);\n  for (let i = 0; i < INIT.pluginQueue.length; i++) {\n    INIT.pluginQueue[i][1]({\n      scanner: INIT.scanner,\n      parser: INIT.parser\n    });\n  }\n  INIT.initialized = true;\n  return INIT;\n}\n\n/**\n * Parse a string into tokens that represent linkable and non-linkable sub-components\n * @param {string} str\n * @return {MultiToken[]} tokens\n */\nfunction tokenize(str) {\n  if (!INIT.initialized) {\n    init();\n  }\n  return run(INIT.parser.start, str, run$1(INIT.scanner.start, str));\n}\ntokenize.scan = run$1; // for testing\n\n/**\n * Find a list of linkable items in the given string.\n * @param {string} str string to find links in\n * @param {string | Opts} [type] either formatting options or specific type of\n * links to find, e.g., 'url' or 'email'\n * @param {Opts} [opts] formatting options for final output. Cannot be specified\n * if opts already provided in `type` argument\n */\nfunction find(str, type = null, opts = null) {\n  if (type && typeof type === 'object') {\n    if (opts) {\n      throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);\n    }\n    opts = type;\n    type = null;\n  }\n  const options = new Options(opts);\n  const tokens = tokenize(str);\n  const filtered = [];\n  for (let i = 0; i < tokens.length; i++) {\n    const token = tokens[i];\n    if (token.isLink && (!type || token.t === type) && options.check(token)) {\n      filtered.push(token.toFormattedObject(options));\n    }\n  }\n  return filtered;\n}\n\n/**\n * Is the given string valid linkable text of some sort. Note that this does not\n * trim the text for you.\n *\n * Optionally pass in a second `type` param, which is the type of link to test\n * for.\n *\n * For example,\n *\n *     linkify.test(str, 'email');\n *\n * Returns `true` if str is a valid email.\n * @param {string} str string to test for links\n * @param {string} [type] optional specific link type to look for\n * @returns boolean true/false\n */\nfunction test(str, type = null) {\n  const tokens = tokenize(str);\n  return tokens.length === 1 && tokens[0].isLink && (!type || tokens[0].t === type);\n}\n\nexport { MultiToken, Options, State, createTokenClass, find, init, multi, options, regexp, registerCustomProtocol, registerPlugin, registerTokenPlugin, reset, stringToArray, test, tk as text, tokenize };\n", "// From DOMPurify\n// https://github.com/cure53/DOMPurify/blob/main/src/regexp.ts\nexport const UNICODE_WHITESPACE_PATTERN = '[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]'\n\nexport const UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN)\nexport const UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`)\nexport const UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, 'g')\n", "import {\n  combineTransactionSteps,\n  findChildrenInRange,\n  getChangedRanges,\n  getMarksBetween,\n  NodeWithPos,\n} from '@tiptap/core'\nimport { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { MultiToken, tokenize } from 'linkifyjs'\n\nimport { UNICODE_WHITESPACE_REGEX, UNICODE_WHITESPACE_REGEX_END } from './whitespace.js'\n\n/**\n * Check if the provided tokens form a valid link structure, which can either be a single link token\n * or a link token surrounded by parentheses or square brackets.\n *\n * This ensures that only complete and valid text is hyperlinked, preventing cases where a valid\n * top-level domain (TLD) is immediately followed by an invalid character, like a number. For\n * example, with the `find` method from Linkify, entering `example.com1` would result in\n * `example.com` being linked and the trailing `1` left as plain text. By using the `tokenize`\n * method, we can perform more comprehensive validation on the input text.\n */\nfunction isValidLinkStructure(tokens: Array<ReturnType<MultiToken['toObject']>>) {\n  if (tokens.length === 1) {\n    return tokens[0].isLink\n  }\n\n  if (tokens.length === 3 && tokens[1].isLink) {\n    return ['()', '[]'].includes(tokens[0].value + tokens[2].value)\n  }\n\n  return false\n}\n\ntype AutolinkOptions = {\n  type: MarkType\n  defaultProtocol: string\n  validate: (url: string) => boolean\n  shouldAutoLink: (url: string) => boolean\n}\n\n/**\n * This plugin allows you to automatically add links to your editor.\n * @param options The plugin options\n * @returns The plugin instance\n */\nexport function autolink(options: AutolinkOptions): Plugin {\n  return new Plugin({\n    key: new PluginKey('autolink'),\n    appendTransaction: (transactions, oldState, newState) => {\n      /**\n       * Does the transaction change the document?\n       */\n      const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc)\n\n      /**\n       * Prevent autolink if the transaction is not a document change or if the transaction has the meta `preventAutolink`.\n       */\n      const preventAutolink = transactions.some(transaction => transaction.getMeta('preventAutolink'))\n\n      /**\n       * Prevent autolink if the transaction is not a document change\n       * or if the transaction has the meta `preventAutolink`.\n       */\n      if (!docChanges || preventAutolink) {\n        return\n      }\n\n      const { tr } = newState\n      const transform = combineTransactionSteps(oldState.doc, [...transactions])\n      const changes = getChangedRanges(transform)\n\n      changes.forEach(({ newRange }) => {\n        // Now let’s see if we can add new links.\n        const nodesInChangedRanges = findChildrenInRange(\n          newState.doc,\n          newRange,\n          node => node.isTextblock,\n        )\n\n        let textBlock: NodeWithPos | undefined\n        let textBeforeWhitespace: string | undefined\n\n        if (nodesInChangedRanges.length > 1) {\n          // Grab the first node within the changed ranges (ex. the first of two paragraphs when hitting enter).\n          textBlock = nodesInChangedRanges[0]\n          textBeforeWhitespace = newState.doc.textBetween(\n            textBlock.pos,\n            textBlock.pos + textBlock.node.nodeSize,\n            undefined,\n            ' ',\n          )\n        } else if (nodesInChangedRanges.length) {\n          const endText = newState.doc.textBetween(newRange.from, newRange.to, ' ', ' ')\n\n          if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) {\n            return\n          }\n          textBlock = nodesInChangedRanges[0]\n          textBeforeWhitespace = newState.doc.textBetween(\n            textBlock.pos,\n            newRange.to,\n            undefined,\n            ' ',\n          )\n        }\n\n        if (textBlock && textBeforeWhitespace) {\n          const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean)\n\n          if (wordsBeforeWhitespace.length <= 0) {\n            return false\n          }\n\n          const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]\n          const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace)\n\n          if (!lastWordBeforeSpace) {\n            return false\n          }\n\n          const linksBeforeSpace = tokenize(lastWordBeforeSpace).map(t => t.toObject(options.defaultProtocol))\n\n          if (!isValidLinkStructure(linksBeforeSpace)) {\n            return false\n          }\n\n          linksBeforeSpace\n            .filter(link => link.isLink)\n            // Calculate link position.\n            .map(link => ({\n              ...link,\n              from: lastWordAndBlockOffset + link.start + 1,\n              to: lastWordAndBlockOffset + link.end + 1,\n            }))\n            // ignore link inside code mark\n            .filter(link => {\n              if (!newState.schema.marks.code) {\n                return true\n              }\n\n              return !newState.doc.rangeHasMark(\n                link.from,\n                link.to,\n                newState.schema.marks.code,\n              )\n            })\n            // validate link\n            .filter(link => options.validate(link.value))\n            // check whether should autolink\n            .filter(link => options.shouldAutoLink(link.value))\n            // Add link mark.\n            .forEach(link => {\n              if (getMarksBetween(link.from, link.to, newState.doc).some(item => item.mark.type === options.type)) {\n                return\n              }\n\n              tr.addMark(\n                link.from,\n                link.to,\n                options.type.create({\n                  href: link.href,\n                }),\n              )\n            })\n        }\n      })\n\n      if (!tr.steps.length) {\n        return\n      }\n\n      return tr\n    },\n  })\n}\n", "import { getAttributes } from '@tiptap/core'\nimport { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\ntype ClickHandlerOptions = {\n  type: MarkType;\n}\n\nexport function clickHandler(options: ClickHandlerOptions): Plugin {\n  return new Plugin({\n    key: new PluginKey('handleClickLink'),\n    props: {\n      handleClick: (view, pos, event) => {\n        if (event.button !== 0) {\n          return false\n        }\n\n        if (!view.editable) {\n          return false\n        }\n\n        let a = event.target as HTMLElement\n        const els = []\n\n        while (a.nodeName !== 'DIV') {\n          els.push(a)\n          a = a.parentNode as HTMLElement\n        }\n\n        if (!els.find(value => value.nodeName === 'A')) {\n          return false\n        }\n\n        const attrs = getAttributes(view.state, options.type.name)\n        const link = (event.target as HTMLAnchorElement)\n\n        const href = link?.href ?? attrs.href\n        const target = link?.target ?? attrs.target\n\n        if (link && href) {\n          window.open(href, target)\n\n          return true\n        }\n\n        return false\n      },\n    },\n  })\n}\n", "import { Editor } from '@tiptap/core'\nimport { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { find } from 'linkifyjs'\n\ntype PasteHandlerOptions = {\n  editor: Editor\n  defaultProtocol: string\n  type: MarkType\n}\n\nexport function pasteHandler(options: PasteHandlerOptions): Plugin {\n  return new Plugin({\n    key: new PluginKey('handlePasteLink'),\n    props: {\n      handlePaste: (view, event, slice) => {\n        const { state } = view\n        const { selection } = state\n        const { empty } = selection\n\n        if (empty) {\n          return false\n        }\n\n        let textContent = ''\n\n        slice.content.forEach(node => {\n          textContent += node.textContent\n        })\n\n        const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(item => item.isLink && item.value === textContent)\n\n        if (!textContent || !link) {\n          return false\n        }\n\n        return options.editor.commands.setMark(options.type, {\n          href: link.href,\n        })\n      },\n    },\n  })\n}\n", "import {\n  Mark, markPasteRule, mergeAttributes, PasteRuleMatch,\n} from '@tiptap/core'\nimport { Plugin } from '@tiptap/pm/state'\nimport { find, registerCustomProtocol, reset } from 'linkifyjs'\n\nimport { autolink } from './helpers/autolink.js'\nimport { clickHandler } from './helpers/clickHandler.js'\nimport { pasteHandler } from './helpers/pasteHandler.js'\nimport { UNICODE_WHITESPACE_REGEX_GLOBAL } from './helpers/whitespace.js'\n\nexport interface LinkProtocolOptions {\n  /**\n   * The protocol scheme to be registered.\n   * @default '''\n   * @example 'ftp'\n   * @example 'git'\n   */\n  scheme: string;\n\n  /**\n   * If enabled, it allows optional slashes after the protocol.\n   * @default false\n   * @example true\n   */\n  optionalSlashes?: boolean;\n}\n\nexport const pasteRegex = /https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z]{2,}\\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi\n\n/**\n * @deprecated The default behavior is now to open links when the editor is not editable.\n */\ntype DeprecatedOpenWhenNotEditable = 'whenNotEditable';\n\nexport interface LinkOptions {\n  /**\n   * If enabled, the extension will automatically add links as you type.\n   * @default true\n   * @example false\n   */\n  autolink: boolean;\n\n  /**\n   * An array of custom protocols to be registered with linkifyjs.\n   * @default []\n   * @example ['ftp', 'git']\n   */\n  protocols: Array<LinkProtocolOptions | string>;\n\n  /**\n   * Default protocol to use when no protocol is specified.\n   * @default 'http'\n   */\n  defaultProtocol: string;\n  /**\n   * If enabled, links will be opened on click.\n   * @default true\n   * @example false\n   */\n  openOnClick: boolean | DeprecatedOpenWhenNotEditable;\n  /**\n   * Adds a link to the current selection if the pasted content only contains an url.\n   * @default true\n   * @example false\n   */\n  linkOnPaste: boolean;\n\n  /**\n   * HTML attributes to add to the link element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>;\n\n  /**\n   * @deprecated Use the `shouldAutoLink` option instead.\n   * A validation function that modifies link verification for the auto linker.\n   * @param url - The url to be validated.\n   * @returns - True if the url is valid, false otherwise.\n   */\n  validate: (url: string) => boolean;\n\n  /**\n   * A validation function which is used for configuring link verification for preventing XSS attacks.\n   * Only modify this if you know what you're doing.\n   *\n   * @returns {boolean} `true` if the URL is valid, `false` otherwise.\n   *\n   * @example\n   * isAllowedUri: (url, { defaultValidate, protocols, defaultProtocol }) => {\n   * return url.startsWith('./') || defaultValidate(url)\n   * }\n   */\n  isAllowedUri: (\n    /**\n     * The URL to be validated.\n     */\n    url: string,\n    ctx: {\n      /**\n       * The default validation function.\n       */\n      defaultValidate: (url: string) => boolean;\n      /**\n       * An array of allowed protocols for the URL (e.g., \"http\", \"https\"). As defined in the `protocols` option.\n       */\n      protocols: Array<LinkProtocolOptions | string>;\n      /**\n       * A string that represents the default protocol (e.g., 'http'). As defined in the `defaultProtocol` option.\n       */\n      defaultProtocol: string;\n    }\n  ) => boolean;\n\n  /**\n   * Determines whether a valid link should be automatically linked in the content.\n   *\n   * @param {string} url - The URL that has already been validated.\n   * @returns {boolean} - True if the link should be auto-linked; false if it should not be auto-linked.\n   */\n  shouldAutoLink: (url: string) => boolean;\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    link: {\n      /**\n       * Set a link mark\n       * @param attributes The link attributes\n       * @example editor.commands.setLink({ href: 'https://tiptap.dev' })\n       */\n      setLink: (attributes: {\n        href: string;\n        target?: string | null;\n        rel?: string | null;\n        class?: string | null;\n      }) => ReturnType;\n      /**\n       * Toggle a link mark\n       * @param attributes The link attributes\n       * @example editor.commands.toggleLink({ href: 'https://tiptap.dev' })\n       */\n      toggleLink: (attributes: {\n        href: string;\n        target?: string | null;\n        rel?: string | null;\n        class?: string | null;\n      }) => ReturnType;\n      /**\n       * Unset a link mark\n       * @example editor.commands.unsetLink()\n       */\n      unsetLink: () => ReturnType;\n    };\n  }\n}\n\nexport function isAllowedUri(uri: string | undefined, protocols?: LinkOptions['protocols']) {\n  const allowedProtocols: string[] = [\n    'http',\n    'https',\n    'ftp',\n    'ftps',\n    'mailto',\n    'tel',\n    'callto',\n    'sms',\n    'cid',\n    'xmpp',\n  ]\n\n  if (protocols) {\n    protocols.forEach(protocol => {\n      const nextProtocol = typeof protocol === 'string' ? protocol : protocol.scheme\n\n      if (nextProtocol) {\n        allowedProtocols.push(nextProtocol)\n      }\n    })\n  }\n\n  return (\n    !uri\n    || uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, '').match(\n      new RegExp(\n        // eslint-disable-next-line no-useless-escape\n        `^(?:(?:${allowedProtocols.join('|')}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,\n        'i',\n      ),\n    )\n  )\n}\n\n/**\n * This extension allows you to create links.\n * @see https://www.tiptap.dev/api/marks/link\n */\nexport const Link = Mark.create<LinkOptions>({\n  name: 'link',\n\n  priority: 1000,\n\n  keepOnSplit: false,\n\n  exitable: true,\n\n  onCreate() {\n    if (this.options.validate && !this.options.shouldAutoLink) {\n      // Copy the validate function to the shouldAutoLink option\n      this.options.shouldAutoLink = this.options.validate\n      console.warn(\n        'The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.',\n      )\n    }\n    this.options.protocols.forEach(protocol => {\n      if (typeof protocol === 'string') {\n        registerCustomProtocol(protocol)\n        return\n      }\n      registerCustomProtocol(protocol.scheme, protocol.optionalSlashes)\n    })\n  },\n\n  onDestroy() {\n    reset()\n  },\n\n  inclusive() {\n    return this.options.autolink\n  },\n\n  addOptions() {\n    return {\n      openOnClick: true,\n      linkOnPaste: true,\n      autolink: true,\n      protocols: [],\n      defaultProtocol: 'http',\n      HTMLAttributes: {\n        target: '_blank',\n        rel: 'noopener noreferrer nofollow',\n        class: null,\n      },\n      isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),\n      validate: url => !!url,\n      shouldAutoLink: url => !!url,\n    }\n  },\n\n  addAttributes() {\n    return {\n      href: {\n        default: null,\n        parseHTML(element) {\n          return element.getAttribute('href')\n        },\n      },\n      target: {\n        default: this.options.HTMLAttributes.target,\n      },\n      rel: {\n        default: this.options.HTMLAttributes.rel,\n      },\n      class: {\n        default: this.options.HTMLAttributes.class,\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'a[href]',\n        getAttrs: dom => {\n          const href = (dom as HTMLElement).getAttribute('href')\n\n          // prevent XSS attacks\n          if (\n            !href\n            || !this.options.isAllowedUri(href, {\n              defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n              protocols: this.options.protocols,\n              defaultProtocol: this.options.defaultProtocol,\n            })\n          ) {\n            return false\n          }\n          return null\n        },\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    // prevent XSS attacks\n    if (\n      !this.options.isAllowedUri(HTMLAttributes.href, {\n        defaultValidate: href => !!isAllowedUri(href, this.options.protocols),\n        protocols: this.options.protocols,\n        defaultProtocol: this.options.defaultProtocol,\n      })\n    ) {\n      // strip out the href\n      return [\n        'a',\n        mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: '' }),\n        0,\n      ]\n    }\n\n    return ['a', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setLink:\n        attributes => ({ chain }) => {\n          const { href } = attributes\n\n          if (!this.options.isAllowedUri(href, {\n            defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n            protocols: this.options.protocols,\n            defaultProtocol: this.options.defaultProtocol,\n          })) {\n            return false\n          }\n\n          return chain().setMark(this.name, attributes).setMeta('preventAutolink', true).run()\n        },\n\n      toggleLink:\n        attributes => ({ chain }) => {\n          const { href } = attributes\n\n          if (!this.options.isAllowedUri(href, {\n            defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n            protocols: this.options.protocols,\n            defaultProtocol: this.options.defaultProtocol,\n          })) {\n            return false\n          }\n\n          return chain()\n            .toggleMark(this.name, attributes, { extendEmptyMarkRange: true })\n            .setMeta('preventAutolink', true)\n            .run()\n        },\n\n      unsetLink:\n        () => ({ chain }) => {\n          return chain()\n            .unsetMark(this.name, { extendEmptyMarkRange: true })\n            .setMeta('preventAutolink', true)\n            .run()\n        },\n    }\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: text => {\n          const foundLinks: PasteRuleMatch[] = []\n\n          if (text) {\n            const { protocols, defaultProtocol } = this.options\n            const links = find(text).filter(\n              item => item.isLink\n                && this.options.isAllowedUri(item.value, {\n                  defaultValidate: href => !!isAllowedUri(href, protocols),\n                  protocols,\n                  defaultProtocol,\n                }),\n            )\n\n            if (links.length) {\n              links.forEach(link => foundLinks.push({\n                text: link.value,\n                data: {\n                  href: link.href,\n                },\n                index: link.start,\n              }))\n            }\n          }\n\n          return foundLinks\n        },\n        type: this.type,\n        getAttributes: match => {\n          return {\n            href: match.data?.href,\n          }\n        },\n      }),\n    ]\n  },\n\n  addProseMirrorPlugins() {\n    const plugins: Plugin[] = []\n    const { protocols, defaultProtocol } = this.options\n\n    if (this.options.autolink) {\n      plugins.push(\n        autolink({\n          type: this.type,\n          defaultProtocol: this.options.defaultProtocol,\n          validate: url => this.options.isAllowedUri(url, {\n            defaultValidate: href => !!isAllowedUri(href, protocols),\n            protocols,\n            defaultProtocol,\n          }),\n          shouldAutoLink: this.options.shouldAutoLink,\n        }),\n      )\n    }\n\n    if (this.options.openOnClick === true) {\n      plugins.push(\n        clickHandler({\n          type: this.type,\n        }),\n      )\n    }\n\n    if (this.options.linkOnPaste) {\n      plugins.push(\n        pasteHandler({\n          editor: this.editor,\n          defaultProtocol: this.options.defaultProtocol,\n          type: this.type,\n        }),\n      )\n    }\n\n    return plugins\n  },\n})\n", "import { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nexport interface BlockquoteOptions {\n  /**\n   * HTML attributes to add to the blockquote element\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    blockQuote: {\n      /**\n       * Set a blockquote node\n       */\n      setBlockquote: () => ReturnType,\n      /**\n       * Toggle a blockquote node\n       */\n      toggleBlockquote: () => ReturnType,\n      /**\n       * Unset a blockquote node\n       */\n      unsetBlockquote: () => ReturnType,\n    }\n  }\n}\n\n/**\n * Matches a blockquote to a `>` as input.\n */\nexport const inputRegex = /^\\s*>\\s$/\n\n/**\n * This extension allows you to create blockquotes.\n * @see https://tiptap.dev/api/nodes/blockquote\n */\nexport const Blockquote = Node.create<BlockquoteOptions>({\n\n  name: 'blockquote',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'block+',\n\n  group: 'block',\n\n  defining: true,\n\n  parseHTML() {\n    return [\n      { tag: 'blockquote' },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['blockquote', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setBlockquote: () => ({ commands }) => {\n        return commands.wrapIn(this.name)\n      },\n      toggleBlockquote: () => ({ commands }) => {\n        return commands.toggleWrap(this.name)\n      },\n      unsetBlockquote: () => ({ commands }) => {\n        return commands.lift(this.name)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-b': () => this.editor.commands.toggleBlockquote(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      wrappingInputRule({\n        find: inputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import {\n  Mark,\n  markInputRule,\n  markPasteRule,\n  mergeAttributes,\n} from '@tiptap/core'\n\nexport interface BoldOptions {\n  /**\n   * HTML attributes to add to the bold element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    bold: {\n      /**\n       * Set a bold mark\n       */\n      setBold: () => ReturnType,\n      /**\n       * Toggle a bold mark\n       */\n      toggleBold: () => ReturnType,\n      /**\n       * Unset a bold mark\n       */\n      unsetBold: () => ReturnType,\n    }\n  }\n}\n\n/**\n * Matches bold text via `**` as input.\n */\nexport const starInputRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))$/\n\n/**\n * Matches bold text via `**` while pasting.\n */\nexport const starPasteRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))/g\n\n/**\n * Matches bold text via `__` as input.\n */\nexport const underscoreInputRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))$/\n\n/**\n * Matches bold text via `__` while pasting.\n */\nexport const underscorePasteRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))/g\n\n/**\n * This extension allows you to mark text as bold.\n * @see https://tiptap.dev/api/marks/bold\n */\nexport const Bold = Mark.create<BoldOptions>({\n  name: 'bold',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'strong',\n      },\n      {\n        tag: 'b',\n        getAttrs: node => (node as HTMLElement).style.fontWeight !== 'normal' && null,\n      },\n      {\n        style: 'font-weight=400',\n        clearMark: mark => mark.type.name === this.name,\n      },\n      {\n        style: 'font-weight',\n        getAttrs: value => /^(bold(er)?|[5-9]\\d{2,})$/.test(value as string) && null,\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['strong', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setBold: () => ({ commands }) => {\n        return commands.setMark(this.name)\n      },\n      toggleBold: () => ({ commands }) => {\n        return commands.toggleMark(this.name)\n      },\n      unsetBold: () => ({ commands }) => {\n        return commands.unsetMark(this.name)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-b': () => this.editor.commands.toggleBold(),\n      'Mod-B': () => this.editor.commands.toggleBold(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: starInputRegex,\n        type: this.type,\n      }),\n      markInputRule({\n        find: underscoreInputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: starPasteRegex,\n        type: this.type,\n      }),\n      markPasteRule({\n        find: underscorePasteRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nconst ListItemName = 'listItem'\nconst TextStyleName = 'textStyle'\n\nexport interface BulletListOptions {\n  /**\n   * The node name for the list items\n   * @default 'listItem'\n   * @example 'paragraph'\n   */\n  itemTypeName: string,\n\n  /**\n   * HTML attributes to add to the bullet list element\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n\n  /**\n   * Keep the marks when splitting the list\n   * @default false\n   * @example true\n   */\n  keepMarks: boolean,\n\n  /**\n   * Keep the attributes when splitting the list\n   * @default false\n   * @example true\n   */\n  keepAttributes: boolean,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    bulletList: {\n      /**\n       * Toggle a bullet list\n       */\n      toggleBulletList: () => ReturnType,\n    }\n  }\n}\n\n/**\n * Matches a bullet list to a dash or asterisk.\n */\nexport const inputRegex = /^\\s*([-+*])\\s$/\n\n/**\n * This extension allows you to create bullet lists.\n * This requires the ListItem extension\n * @see https://tiptap.dev/api/nodes/bullet-list\n * @see https://tiptap.dev/api/nodes/list-item.\n */\nexport const BulletList = Node.create<BulletListOptions>({\n  name: 'bulletList',\n\n  addOptions() {\n    return {\n      itemTypeName: 'listItem',\n      HTMLAttributes: {},\n      keepMarks: false,\n      keepAttributes: false,\n    }\n  },\n\n  group: 'block list',\n\n  content() {\n    return `${this.options.itemTypeName}+`\n  },\n\n  parseHTML() {\n    return [\n      { tag: 'ul' },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['ul', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      toggleBulletList: () => ({ commands, chain }) => {\n        if (this.options.keepAttributes) {\n          return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run()\n        }\n        return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-8': () => this.editor.commands.toggleBulletList(),\n    }\n  },\n\n  addInputRules() {\n    let inputRule = wrappingInputRule({\n      find: inputRegex,\n      type: this.type,\n    })\n\n    if (this.options.keepMarks || this.options.keepAttributes) {\n      inputRule = wrappingInputRule({\n        find: inputRegex,\n        type: this.type,\n        keepMarks: this.options.keepMarks,\n        keepAttributes: this.options.keepAttributes,\n        getAttributes: () => { return this.editor.getAttributes(TextStyleName) },\n        editor: this.editor,\n      })\n    }\n    return [\n      inputRule,\n    ]\n  },\n})\n", "import {\n  Mark,\n  markInputRule,\n  markPasteRule,\n  mergeAttributes,\n} from '@tiptap/core'\n\nexport interface CodeOptions {\n  /**\n   * The HTML attributes applied to the code element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    code: {\n      /**\n       * Set a code mark\n       */\n      setCode: () => ReturnType,\n      /**\n       * Toggle inline code\n       */\n      toggleCode: () => ReturnType,\n      /**\n       * Unset a code mark\n       */\n      unsetCode: () => ReturnType,\n    }\n  }\n}\n\n/**\n * Regular expressions to match inline code blocks enclosed in backticks.\n *  It matches:\n *     - An opening backtick, followed by\n *     - Any text that doesn't include a backtick (captured for marking), followed by\n *     - A closing backtick.\n *  This ensures that any text between backticks is formatted as code,\n *  regardless of the surrounding characters (exception being another backtick).\n */\nexport const inputRegex = /(^|[^`])`([^`]+)`(?!`)/\n\n/**\n * Matches inline code while pasting.\n */\nexport const pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g\n\n/**\n * This extension allows you to mark text as inline code.\n * @see https://tiptap.dev/api/marks/code\n */\nexport const Code = Mark.create<CodeOptions>({\n  name: 'code',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  excludes: '_',\n\n  code: true,\n\n  exitable: true,\n\n  parseHTML() {\n    return [\n      { tag: 'code' },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['code', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setCode: () => ({ commands }) => {\n        return commands.setMark(this.name)\n      },\n      toggleCode: () => ({ commands }) => {\n        return commands.toggleMark(this.name)\n      },\n      unsetCode: () => ({ commands }) => {\n        return commands.unsetMark(this.name)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-e': () => this.editor.commands.toggleCode(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: inputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: pasteRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'\nimport {\n  Plugin,\n  PluginKey,\n  Selection,\n  TextSelection,\n} from '@tiptap/pm/state'\n\nexport interface CodeBlockOptions {\n  /**\n   * Adds a prefix to language classes that are applied to code tags.\n   * @default 'language-'\n   */\n  languageClassPrefix: string\n  /**\n   * Define whether the node should be exited on triple enter.\n   * @default true\n   */\n  exitOnTripleEnter: boolean\n  /**\n   * Define whether the node should be exited on arrow down if there is no node after it.\n   * @default true\n   */\n  exitOnArrowDown: boolean\n  /**\n   * The default language.\n   * @default null\n   * @example 'js'\n   */\n  defaultLanguage: string | null | undefined\n  /**\n   * Custom HTML attributes that should be added to the rendered HTML tag.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    codeBlock: {\n      /**\n       * Set a code block\n       * @param attributes Code block attributes\n       * @example editor.commands.setCodeBlock({ language: 'javascript' })\n       */\n      setCodeBlock: (attributes?: { language: string }) => ReturnType\n      /**\n       * Toggle a code block\n       * @param attributes Code block attributes\n       * @example editor.commands.toggleCodeBlock({ language: 'javascript' })\n       */\n      toggleCodeBlock: (attributes?: { language: string }) => ReturnType\n    }\n  }\n}\n\n/**\n * Matches a code block with backticks.\n */\nexport const backtickInputRegex = /^```([a-z]+)?[\\s\\n]$/\n\n/**\n * Matches a code block with tildes.\n */\nexport const tildeInputRegex = /^~~~([a-z]+)?[\\s\\n]$/\n\n/**\n * This extension allows you to create code blocks.\n * @see https://tiptap.dev/api/nodes/code-block\n */\nexport const CodeBlock = Node.create<CodeBlockOptions>({\n  name: 'codeBlock',\n\n  addOptions() {\n    return {\n      languageClassPrefix: 'language-',\n      exitOnTripleEnter: true,\n      exitOnArrowDown: true,\n      defaultLanguage: null,\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'text*',\n\n  marks: '',\n\n  group: 'block',\n\n  code: true,\n\n  defining: true,\n\n  addAttributes() {\n    return {\n      language: {\n        default: this.options.defaultLanguage,\n        parseHTML: element => {\n          const { languageClassPrefix } = this.options\n          const classNames = [...(element.firstElementChild?.classList || [])]\n          const languages = classNames\n            .filter(className => className.startsWith(languageClassPrefix))\n            .map(className => className.replace(languageClassPrefix, ''))\n          const language = languages[0]\n\n          if (!language) {\n            return null\n          }\n\n          return language\n        },\n        rendered: false,\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'pre',\n        preserveWhitespace: 'full',\n      },\n    ]\n  },\n\n  renderHTML({ node, HTMLAttributes }) {\n    return [\n      'pre',\n      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),\n      [\n        'code',\n        {\n          class: node.attrs.language\n            ? this.options.languageClassPrefix + node.attrs.language\n            : null,\n        },\n        0,\n      ],\n    ]\n  },\n\n  addCommands() {\n    return {\n      setCodeBlock:\n        attributes => ({ commands }) => {\n          return commands.setNode(this.name, attributes)\n        },\n      toggleCodeBlock:\n        attributes => ({ commands }) => {\n          return commands.toggleNode(this.name, 'paragraph', attributes)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Alt-c': () => this.editor.commands.toggleCodeBlock(),\n\n      // remove code block when at start of document or code block is empty\n      Backspace: () => {\n        const { empty, $anchor } = this.editor.state.selection\n        const isAtStart = $anchor.pos === 1\n\n        if (!empty || $anchor.parent.type.name !== this.name) {\n          return false\n        }\n\n        if (isAtStart || !$anchor.parent.textContent.length) {\n          return this.editor.commands.clearNodes()\n        }\n\n        return false\n      },\n\n      // exit node on triple enter\n      Enter: ({ editor }) => {\n        if (!this.options.exitOnTripleEnter) {\n          return false\n        }\n\n        const { state } = editor\n        const { selection } = state\n        const { $from, empty } = selection\n\n        if (!empty || $from.parent.type !== this.type) {\n          return false\n        }\n\n        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n        const endsWithDoubleNewline = $from.parent.textContent.endsWith('\\n\\n')\n\n        if (!isAtEnd || !endsWithDoubleNewline) {\n          return false\n        }\n\n        return editor\n          .chain()\n          .command(({ tr }) => {\n            tr.delete($from.pos - 2, $from.pos)\n\n            return true\n          })\n          .exitCode()\n          .run()\n      },\n\n      // exit node on arrow down\n      ArrowDown: ({ editor }) => {\n        if (!this.options.exitOnArrowDown) {\n          return false\n        }\n\n        const { state } = editor\n        const { selection, doc } = state\n        const { $from, empty } = selection\n\n        if (!empty || $from.parent.type !== this.type) {\n          return false\n        }\n\n        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n\n        if (!isAtEnd) {\n          return false\n        }\n\n        const after = $from.after()\n\n        if (after === undefined) {\n          return false\n        }\n\n        const nodeAfter = doc.nodeAt(after)\n\n        if (nodeAfter) {\n          return editor.commands.command(({ tr }) => {\n            tr.setSelection(Selection.near(doc.resolve(after)))\n            return true\n          })\n        }\n\n        return editor.commands.exitCode()\n      },\n    }\n  },\n\n  addInputRules() {\n    return [\n      textblockTypeInputRule({\n        find: backtickInputRegex,\n        type: this.type,\n        getAttributes: match => ({\n          language: match[1],\n        }),\n      }),\n      textblockTypeInputRule({\n        find: tildeInputRegex,\n        type: this.type,\n        getAttributes: match => ({\n          language: match[1],\n        }),\n      }),\n    ]\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      // this plugin creates a code block for pasted content from VS Code\n      // we can also detect the copied code language\n      new Plugin({\n        key: new PluginKey('codeBlockVSCodeHandler'),\n        props: {\n          handlePaste: (view, event) => {\n            if (!event.clipboardData) {\n              return false\n            }\n\n            // don’t create a new code block within code blocks\n            if (this.editor.isActive(this.type.name)) {\n              return false\n            }\n\n            const text = event.clipboardData.getData('text/plain')\n            const vscode = event.clipboardData.getData('vscode-editor-data')\n            const vscodeData = vscode ? JSON.parse(vscode) : undefined\n            const language = vscodeData?.mode\n\n            if (!text || !language) {\n              return false\n            }\n\n            const { tr, schema } = view.state\n\n            // prepare a text node\n            // strip carriage return chars from text pasted as code\n            // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd\n            const textNode = schema.text(text.replace(/\\r\\n?/g, '\\n'))\n\n            // create a code block with the text node\n            // replace selection with the code block\n            tr.replaceSelectionWith(this.type.create({ language }, textNode))\n\n            if (tr.selection.$from.parent.type !== this.type) {\n              // put cursor inside the newly created code block\n              tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))))\n            }\n\n            // store meta information\n            // this is useful for other plugins that depends on the paste event\n            // like the paste rule plugin\n            tr.setMeta('paste', true)\n\n            view.dispatch(tr)\n\n            return true\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Node } from '@tiptap/core'\n\n/**\n * The default document node which represents the top level node of the editor.\n * @see https://tiptap.dev/api/nodes/document\n */\nexport const Document = Node.create({\n  name: 'doc',\n  topNode: true,\n  content: 'block+',\n})\n", "import { Plugin } from 'prosemirror-state';\nimport { dropPoint } from 'prosemirror-transform';\n\n/**\nCreate a plugin that, when added to a ProseMirror instance,\ncauses a decoration to show up at the drop position when something\nis dragged over the editor.\n\nNodes may add a `disableDropCursor` property to their spec to\ncontrol the showing of a drop cursor inside them. This may be a\nboolean or a function, which will be called with a view and a\nposition, and should return a boolean.\n*/\nfunction dropCursor(options = {}) {\n    return new Plugin({\n        view(editorView) { return new DropCursorView(editorView, options); }\n    });\n}\nclass DropCursorView {\n    constructor(editorView, options) {\n        var _a;\n        this.editorView = editorView;\n        this.cursorPos = null;\n        this.element = null;\n        this.timeout = -1;\n        this.lastDragEvent = null;\n        this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1;\n        this.color = options.color === false ? undefined : (options.color || \"black\");\n        this.class = options.class;\n        this.handlers = [\"dragover\", \"dragend\", \"drop\", \"dragleave\"].map(name => {\n            let handler = (e) => { this[name](e); };\n            editorView.dom.addEventListener(name, handler);\n            return { name, handler };\n        });\n    }\n    destroy() {\n        this.setCursor(null);\n        this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));\n    }\n    update(editorView, prevState) {\n        if (this.cursorPos != null && prevState.doc != editorView.state.doc) {\n            // if we currently have an on-going drag event\n            // we need to update the cursor position again and update the overlay\n            if (this.lastDragEvent) {\n                let target = this.computeTarget(this.lastDragEvent);\n                if (target == this.cursorPos)\n                    this.updateOverlay();\n                else\n                    this.setCursor(target);\n            }\n            else {\n                this.updateOverlay();\n            }\n        }\n    }\n    setCursor(pos) {\n        if (pos == this.cursorPos)\n            return;\n        this.cursorPos = pos;\n        if (pos == null) {\n            this.element.parentNode.removeChild(this.element);\n            this.element = null;\n        }\n        else {\n            this.updateOverlay();\n        }\n    }\n    updateOverlay() {\n        let $pos = this.editorView.state.doc.resolve(this.cursorPos);\n        let isBlock = !$pos.parent.inlineContent, rect;\n        let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect();\n        let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight;\n        if (isBlock) {\n            let before = $pos.nodeBefore, after = $pos.nodeAfter;\n            if (before || after) {\n                let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));\n                if (node) {\n                    let nodeRect = node.getBoundingClientRect();\n                    let top = before ? nodeRect.bottom : nodeRect.top;\n                    if (before && after)\n                        top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;\n                    let halfWidth = (this.width / 2) * scaleY;\n                    rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth };\n                }\n            }\n        }\n        if (!rect) {\n            let coords = this.editorView.coordsAtPos(this.cursorPos);\n            let halfWidth = (this.width / 2) * scaleX;\n            rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom };\n        }\n        let parent = this.editorView.dom.offsetParent;\n        if (!this.element) {\n            this.element = parent.appendChild(document.createElement(\"div\"));\n            if (this.class)\n                this.element.className = this.class;\n            this.element.style.cssText = \"position: absolute; z-index: 50; pointer-events: none;\";\n            if (this.color) {\n                this.element.style.backgroundColor = this.color;\n            }\n        }\n        this.element.classList.toggle(\"prosemirror-dropcursor-block\", isBlock);\n        this.element.classList.toggle(\"prosemirror-dropcursor-inline\", !isBlock);\n        let parentLeft, parentTop;\n        if (!parent || parent == document.body && getComputedStyle(parent).position == \"static\") {\n            parentLeft = -pageXOffset;\n            parentTop = -pageYOffset;\n        }\n        else {\n            let rect = parent.getBoundingClientRect();\n            let parentScaleX = rect.width / parent.offsetWidth, parentScaleY = rect.height / parent.offsetHeight;\n            parentLeft = rect.left - parent.scrollLeft * parentScaleX;\n            parentTop = rect.top - parent.scrollTop * parentScaleY;\n        }\n        this.element.style.left = (rect.left - parentLeft) / scaleX + \"px\";\n        this.element.style.top = (rect.top - parentTop) / scaleY + \"px\";\n        this.element.style.width = (rect.right - rect.left) / scaleX + \"px\";\n        this.element.style.height = (rect.bottom - rect.top) / scaleY + \"px\";\n    }\n    scheduleRemoval(timeout) {\n        clearTimeout(this.timeout);\n        this.timeout = setTimeout(() => this.setCursor(null), timeout);\n    }\n    computeTarget(event) {\n        let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });\n        let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);\n        let disableDropCursor = node && node.type.spec.disableDropCursor;\n        let disabled = typeof disableDropCursor == \"function\"\n            ? disableDropCursor(this.editorView, pos, event)\n            : disableDropCursor;\n        if (!pos || disabled)\n            return null;\n        let target = pos.pos;\n        if (this.editorView.dragging && this.editorView.dragging.slice) {\n            let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);\n            if (point != null)\n                target = point;\n        }\n        return target;\n    }\n    dragover(event) {\n        if (!this.editorView.editable)\n            return;\n        this.lastDragEvent = event;\n        let target = this.computeTarget(event);\n        if (target != null) {\n            this.setCursor(target);\n            this.scheduleRemoval(5000);\n        }\n    }\n    dragend() {\n        this.scheduleRemoval(20);\n    }\n    drop() {\n        this.scheduleRemoval(20);\n    }\n    dragleave(event) {\n        if (!this.editorView.dom.contains(event.relatedTarget))\n            this.setCursor(null);\n    }\n}\n\nexport { dropCursor };\n", "import { Extension } from '@tiptap/core'\nimport { dropCursor } from '@tiptap/pm/dropcursor'\n\nexport interface DropcursorOptions {\n  /**\n   * The color of the drop cursor\n   * @default 'currentColor'\n   * @example 'red'\n   */\n  color: string | undefined,\n\n  /**\n   * The width of the drop cursor\n   * @default 1\n   * @example 2\n  */\n  width: number | undefined,\n\n  /**\n   * The class of the drop cursor\n   * @default undefined\n   * @example 'drop-cursor'\n  */\n  class: string | undefined,\n}\n\n/**\n * This extension allows you to add a drop cursor to your editor.\n * A drop cursor is a line that appears when you drag and drop content\n * inbetween nodes.\n * @see https://tiptap.dev/api/extensions/dropcursor\n */\nexport const Dropcursor = Extension.create<DropcursorOptions>({\n  name: 'dropCursor',\n\n  addOptions() {\n    return {\n      color: 'currentColor',\n      width: 1,\n      class: undefined,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      dropCursor(this.options),\n    ]\n  },\n})\n", "import { keydownHandler } from 'prosemirror-keymap';\nimport { Selection, NodeSelection, TextSelection, Plugin } from 'prosemirror-state';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { DecorationSet, Decoration } from 'prosemirror-view';\n\n/**\nGap cursor selections are represented using this class. Its\n`$anchor` and `$head` properties both point at the cursor position.\n*/\nclass GapCursor extends Selection {\n    /**\n    Create a gap cursor.\n    */\n    constructor($pos) {\n        super($pos, $pos);\n    }\n    map(doc, mapping) {\n        let $pos = doc.resolve(mapping.map(this.head));\n        return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n    }\n    content() { return Slice.empty; }\n    eq(other) {\n        return other instanceof GapCursor && other.head == this.head;\n    }\n    toJSON() {\n        return { type: \"gapcursor\", pos: this.head };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(doc, json) {\n        if (typeof json.pos != \"number\")\n            throw new RangeError(\"Invalid input for GapCursor.fromJSON\");\n        return new GapCursor(doc.resolve(json.pos));\n    }\n    /**\n    @internal\n    */\n    getBookmark() { return new GapBookmark(this.anchor); }\n    /**\n    @internal\n    */\n    static valid($pos) {\n        let parent = $pos.parent;\n        if (parent.inlineContent || !closedBefore($pos) || !closedAfter($pos))\n            return false;\n        let override = parent.type.spec.allowGapCursor;\n        if (override != null)\n            return override;\n        let deflt = parent.contentMatchAt($pos.index()).defaultType;\n        return deflt && deflt.isTextblock;\n    }\n    /**\n    @internal\n    */\n    static findGapCursorFrom($pos, dir, mustMove = false) {\n        search: for (;;) {\n            if (!mustMove && GapCursor.valid($pos))\n                return $pos;\n            let pos = $pos.pos, next = null;\n            // Scan up from this position\n            for (let d = $pos.depth;; d--) {\n                let parent = $pos.node(d);\n                if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {\n                    next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);\n                    break;\n                }\n                else if (d == 0) {\n                    return null;\n                }\n                pos += dir;\n                let $cur = $pos.doc.resolve(pos);\n                if (GapCursor.valid($cur))\n                    return $cur;\n            }\n            // And then down into the next node\n            for (;;) {\n                let inside = dir > 0 ? next.firstChild : next.lastChild;\n                if (!inside) {\n                    if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {\n                        $pos = $pos.doc.resolve(pos + next.nodeSize * dir);\n                        mustMove = false;\n                        continue search;\n                    }\n                    break;\n                }\n                next = inside;\n                pos += dir;\n                let $cur = $pos.doc.resolve(pos);\n                if (GapCursor.valid($cur))\n                    return $cur;\n            }\n            return null;\n        }\n    }\n}\nGapCursor.prototype.visible = false;\nGapCursor.findFrom = GapCursor.findGapCursorFrom;\nSelection.jsonID(\"gapcursor\", GapCursor);\nclass GapBookmark {\n    constructor(pos) {\n        this.pos = pos;\n    }\n    map(mapping) {\n        return new GapBookmark(mapping.map(this.pos));\n    }\n    resolve(doc) {\n        let $pos = doc.resolve(this.pos);\n        return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n    }\n}\nfunction needsGap(type) {\n    return type.isAtom || type.spec.isolating || type.spec.createGapCursor;\n}\nfunction closedBefore($pos) {\n    for (let d = $pos.depth; d >= 0; d--) {\n        let index = $pos.index(d), parent = $pos.node(d);\n        // At the start of this parent, look at next one\n        if (index == 0) {\n            if (parent.type.spec.isolating)\n                return true;\n            continue;\n        }\n        // See if the node before (or its first ancestor) is closed\n        for (let before = parent.child(index - 1);; before = before.lastChild) {\n            if ((before.childCount == 0 && !before.inlineContent) || needsGap(before.type))\n                return true;\n            if (before.inlineContent)\n                return false;\n        }\n    }\n    // Hit start of document\n    return true;\n}\nfunction closedAfter($pos) {\n    for (let d = $pos.depth; d >= 0; d--) {\n        let index = $pos.indexAfter(d), parent = $pos.node(d);\n        if (index == parent.childCount) {\n            if (parent.type.spec.isolating)\n                return true;\n            continue;\n        }\n        for (let after = parent.child(index);; after = after.firstChild) {\n            if ((after.childCount == 0 && !after.inlineContent) || needsGap(after.type))\n                return true;\n            if (after.inlineContent)\n                return false;\n        }\n    }\n    return true;\n}\n\n/**\nCreate a gap cursor plugin. When enabled, this will capture clicks\nnear and arrow-key-motion past places that don't have a normally\nselectable position nearby, and create a gap cursor selection for\nthem. The cursor is drawn as an element with class\n`ProseMirror-gapcursor`. You can either include\n`style/gapcursor.css` from the package's directory or add your own\nstyles to make it visible.\n*/\nfunction gapCursor() {\n    return new Plugin({\n        props: {\n            decorations: drawGapCursor,\n            createSelectionBetween(_view, $anchor, $head) {\n                return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;\n            },\n            handleClick,\n            handleKeyDown,\n            handleDOMEvents: { beforeinput: beforeinput }\n        }\n    });\n}\nconst handleKeyDown = keydownHandler({\n    \"ArrowLeft\": arrow(\"horiz\", -1),\n    \"ArrowRight\": arrow(\"horiz\", 1),\n    \"ArrowUp\": arrow(\"vert\", -1),\n    \"ArrowDown\": arrow(\"vert\", 1)\n});\nfunction arrow(axis, dir) {\n    const dirStr = axis == \"vert\" ? (dir > 0 ? \"down\" : \"up\") : (dir > 0 ? \"right\" : \"left\");\n    return function (state, dispatch, view) {\n        let sel = state.selection;\n        let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;\n        if (sel instanceof TextSelection) {\n            if (!view.endOfTextblock(dirStr) || $start.depth == 0)\n                return false;\n            mustMove = false;\n            $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());\n        }\n        let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);\n        if (!$found)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.setSelection(new GapCursor($found)));\n        return true;\n    };\n}\nfunction handleClick(view, pos, event) {\n    if (!view || !view.editable)\n        return false;\n    let $pos = view.state.doc.resolve(pos);\n    if (!GapCursor.valid($pos))\n        return false;\n    let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });\n    if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))\n        return false;\n    view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));\n    return true;\n}\n// This is a hack that, when a composition starts while a gap cursor\n// is active, quickly creates an inline context for the composition to\n// happen in, to avoid it being aborted by the DOM selection being\n// moved into a valid position.\nfunction beforeinput(view, event) {\n    if (event.inputType != \"insertCompositionText\" || !(view.state.selection instanceof GapCursor))\n        return false;\n    let { $from } = view.state.selection;\n    let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);\n    if (!insert)\n        return false;\n    let frag = Fragment.empty;\n    for (let i = insert.length - 1; i >= 0; i--)\n        frag = Fragment.from(insert[i].createAndFill(null, frag));\n    let tr = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));\n    tr.setSelection(TextSelection.near(tr.doc.resolve($from.pos + 1)));\n    view.dispatch(tr);\n    return false;\n}\nfunction drawGapCursor(state) {\n    if (!(state.selection instanceof GapCursor))\n        return null;\n    let node = document.createElement(\"div\");\n    node.className = \"ProseMirror-gapcursor\";\n    return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: \"gapcursor\" })]);\n}\n\nexport { GapCursor, gapCursor };\n", "import {\n  callOrReturn,\n  Extension,\n  getExtensionField,\n  ParentConfig,\n} from '@tiptap/core'\nimport { gapCursor } from '@tiptap/pm/gapcursor'\n\ndeclare module '@tiptap/core' {\n  interface NodeConfig<Options, Storage> {\n    /**\n     * A function to determine whether the gap cursor is allowed at the current position. Must return `true` or `false`.\n     * @default null\n     */\n    allowGapCursor?:\n      | boolean\n      | null\n      | ((this: {\n        name: string,\n        options: Options,\n        storage: Storage,\n        parent: ParentConfig<NodeConfig<Options>>['allowGapCursor'],\n      }) => boolean | null),\n  }\n}\n\n/**\n * This extension allows you to add a gap cursor to your editor.\n * A gap cursor is a cursor that appears when you click on a place\n * where no content is present, for example inbetween nodes.\n * @see https://tiptap.dev/api/extensions/gapcursor\n */\nexport const Gapcursor = Extension.create({\n  name: 'gapCursor',\n\n  addProseMirrorPlugins() {\n    return [\n      gapCursor(),\n    ]\n  },\n\n  extendNodeSchema(extension) {\n    const context = {\n      name: extension.name,\n      options: extension.options,\n      storage: extension.storage,\n    }\n\n    return {\n      allowGapCursor: callOrReturn(getExtensionField(extension, 'allowGapCursor', context)) ?? null,\n    }\n  },\n})\n", "import { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface HardBreakOptions {\n  /**\n   * Controls if marks should be kept after being split by a hard break.\n   * @default true\n   * @example false\n   */\n  keepMarks: boolean,\n\n  /**\n   * HTML attributes to add to the hard break element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    hardBreak: {\n      /**\n       * Add a hard break\n       * @example editor.commands.setHardBreak()\n       */\n      setHardBreak: () => ReturnType,\n    }\n  }\n}\n\n/**\n * This extension allows you to insert hard breaks.\n * @see https://www.tiptap.dev/api/nodes/hard-break\n */\nexport const HardBreak = Node.create<HardBreakOptions>({\n  name: 'hardBreak',\n\n  addOptions() {\n    return {\n      keepMarks: true,\n      HTMLAttributes: {},\n    }\n  },\n\n  inline: true,\n\n  group: 'inline',\n\n  selectable: false,\n\n  linebreakReplacement: true,\n\n  parseHTML() {\n    return [\n      { tag: 'br' },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['br', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]\n  },\n\n  renderText() {\n    return '\\n'\n  },\n\n  addCommands() {\n    return {\n      setHardBreak: () => ({\n        commands,\n        chain,\n        state,\n        editor,\n      }) => {\n        return commands.first([\n          () => commands.exitCode(),\n          () => commands.command(() => {\n            const { selection, storedMarks } = state\n\n            if (selection.$from.parent.type.spec.isolating) {\n              return false\n            }\n\n            const { keepMarks } = this.options\n            const { splittableMarks } = editor.extensionManager\n            const marks = storedMarks\n              || (selection.$to.parentOffset && selection.$from.marks())\n\n            return chain()\n              .insertContent({ type: this.name })\n              .command(({ tr, dispatch }) => {\n                if (dispatch && marks && keepMarks) {\n                  const filteredMarks = marks\n                    .filter(mark => splittableMarks.includes(mark.type.name))\n\n                  tr.ensureMarks(filteredMarks)\n                }\n\n                return true\n              })\n              .run()\n          }),\n        ])\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Enter': () => this.editor.commands.setHardBreak(),\n      'Shift-Enter': () => this.editor.commands.setHardBreak(),\n    }\n  },\n})\n", "import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'\n\n/**\n * The heading level options.\n */\nexport type Level = 1 | 2 | 3 | 4 | 5 | 6\n\nexport interface HeadingOptions {\n  /**\n   * The available heading levels.\n   * @default [1, 2, 3, 4, 5, 6]\n   * @example [1, 2, 3]\n   */\n  levels: Level[],\n\n  /**\n   * The HTML attributes for a heading node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    heading: {\n      /**\n       * Set a heading node\n       * @param attributes The heading attributes\n       * @example editor.commands.setHeading({ level: 1 })\n       */\n      setHeading: (attributes: { level: Level }) => ReturnType,\n      /**\n       * Toggle a heading node\n       * @param attributes The heading attributes\n       * @example editor.commands.toggleHeading({ level: 1 })\n       */\n      toggleHeading: (attributes: { level: Level }) => ReturnType,\n    }\n  }\n}\n\n/**\n * This extension allows you to create headings.\n * @see https://www.tiptap.dev/api/nodes/heading\n */\nexport const Heading = Node.create<HeadingOptions>({\n  name: 'heading',\n\n  addOptions() {\n    return {\n      levels: [1, 2, 3, 4, 5, 6],\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'inline*',\n\n  group: 'block',\n\n  defining: true,\n\n  addAttributes() {\n    return {\n      level: {\n        default: 1,\n        rendered: false,\n      },\n    }\n  },\n\n  parseHTML() {\n    return this.options.levels\n      .map((level: Level) => ({\n        tag: `h${level}`,\n        attrs: { level },\n      }))\n  },\n\n  renderHTML({ node, HTMLAttributes }) {\n    const hasLevel = this.options.levels.includes(node.attrs.level)\n    const level = hasLevel\n      ? node.attrs.level\n      : this.options.levels[0]\n\n    return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setHeading: attributes => ({ commands }) => {\n        if (!this.options.levels.includes(attributes.level)) {\n          return false\n        }\n\n        return commands.setNode(this.name, attributes)\n      },\n      toggleHeading: attributes => ({ commands }) => {\n        if (!this.options.levels.includes(attributes.level)) {\n          return false\n        }\n\n        return commands.toggleNode(this.name, 'paragraph', attributes)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return this.options.levels.reduce((items, level) => ({\n      ...items,\n      ...{\n        [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }),\n      },\n    }), {})\n  },\n\n  addInputRules() {\n    return this.options.levels.map(level => {\n      return textblockTypeInputRule({\n        find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\\\s$`),\n        type: this.type,\n        getAttributes: {\n          level,\n        },\n      })\n    })\n  },\n})\n", "var GOOD_LEAF_SIZE = 200;\n\n// :: class<T> A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence () {};\n\nRopeSequence.prototype.append = function append (other) {\n  if (!other.length) { return this }\n  other = RopeSequence.from(other);\n\n  return (!this.length && other) ||\n    (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||\n    (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||\n    this.appendInner(other)\n};\n\n// :: (union<[T], RopeSequence<T>>) \u2192 RopeSequence<T>\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend (other) {\n  if (!other.length) { return this }\n  return RopeSequence.from(other).append(this)\n};\n\nRopeSequence.prototype.appendInner = function appendInner (other) {\n  return new Append(this, other)\n};\n\n// :: (?number, ?number) \u2192 RopeSequence<T>\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice (from, to) {\n    if ( from === void 0 ) from = 0;\n    if ( to === void 0 ) to = this.length;\n\n  if (from >= to) { return RopeSequence.empty }\n  return this.sliceInner(Math.max(0, from), Math.min(this.length, to))\n};\n\n// :: (number) \u2192 T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get (i) {\n  if (i < 0 || i >= this.length) { return undefined }\n  return this.getInner(i)\n};\n\n// :: ((element: T, index: number) \u2192 ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach (f, from, to) {\n    if ( from === void 0 ) from = 0;\n    if ( to === void 0 ) to = this.length;\n\n  if (from <= to)\n    { this.forEachInner(f, from, to, 0); }\n  else\n    { this.forEachInvertedInner(f, from, to, 0); }\n};\n\n// :: ((element: T, index: number) \u2192 U, ?number, ?number) \u2192 [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map (f, from, to) {\n    if ( from === void 0 ) from = 0;\n    if ( to === void 0 ) to = this.length;\n\n  var result = [];\n  this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);\n  return result\n};\n\n// :: (?union<[T], RopeSequence<T>>) \u2192 RopeSequence<T>\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from (values) {\n  if (values instanceof RopeSequence) { return values }\n  return values && values.length ? new Leaf(values) : RopeSequence.empty\n};\n\nvar Leaf = /*@__PURE__*/(function (RopeSequence) {\n  function Leaf(values) {\n    RopeSequence.call(this);\n    this.values = values;\n  }\n\n  if ( RopeSequence ) Leaf.__proto__ = RopeSequence;\n  Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n  Leaf.prototype.constructor = Leaf;\n\n  var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };\n\n  Leaf.prototype.flatten = function flatten () {\n    return this.values\n  };\n\n  Leaf.prototype.sliceInner = function sliceInner (from, to) {\n    if (from == 0 && to == this.length) { return this }\n    return new Leaf(this.values.slice(from, to))\n  };\n\n  Leaf.prototype.getInner = function getInner (i) {\n    return this.values[i]\n  };\n\n  Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {\n    for (var i = from; i < to; i++)\n      { if (f(this.values[i], start + i) === false) { return false } }\n  };\n\n  Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n    for (var i = from - 1; i >= to; i--)\n      { if (f(this.values[i], start + i) === false) { return false } }\n  };\n\n  Leaf.prototype.leafAppend = function leafAppend (other) {\n    if (this.length + other.length <= GOOD_LEAF_SIZE)\n      { return new Leaf(this.values.concat(other.flatten())) }\n  };\n\n  Leaf.prototype.leafPrepend = function leafPrepend (other) {\n    if (this.length + other.length <= GOOD_LEAF_SIZE)\n      { return new Leaf(other.flatten().concat(this.values)) }\n  };\n\n  prototypeAccessors.length.get = function () { return this.values.length };\n\n  prototypeAccessors.depth.get = function () { return 0 };\n\n  Object.defineProperties( Leaf.prototype, prototypeAccessors );\n\n  return Leaf;\n}(RopeSequence));\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\n\nvar Append = /*@__PURE__*/(function (RopeSequence) {\n  function Append(left, right) {\n    RopeSequence.call(this);\n    this.left = left;\n    this.right = right;\n    this.length = left.length + right.length;\n    this.depth = Math.max(left.depth, right.depth) + 1;\n  }\n\n  if ( RopeSequence ) Append.__proto__ = RopeSequence;\n  Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n  Append.prototype.constructor = Append;\n\n  Append.prototype.flatten = function flatten () {\n    return this.left.flatten().concat(this.right.flatten())\n  };\n\n  Append.prototype.getInner = function getInner (i) {\n    return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)\n  };\n\n  Append.prototype.forEachInner = function forEachInner (f, from, to, start) {\n    var leftLen = this.left.length;\n    if (from < leftLen &&\n        this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)\n      { return false }\n    if (to > leftLen &&\n        this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)\n      { return false }\n  };\n\n  Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n    var leftLen = this.left.length;\n    if (from > leftLen &&\n        this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)\n      { return false }\n    if (to < leftLen &&\n        this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)\n      { return false }\n  };\n\n  Append.prototype.sliceInner = function sliceInner (from, to) {\n    if (from == 0 && to == this.length) { return this }\n    var leftLen = this.left.length;\n    if (to <= leftLen) { return this.left.slice(from, to) }\n    if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }\n    return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))\n  };\n\n  Append.prototype.leafAppend = function leafAppend (other) {\n    var inner = this.right.leafAppend(other);\n    if (inner) { return new Append(this.left, inner) }\n  };\n\n  Append.prototype.leafPrepend = function leafPrepend (other) {\n    var inner = this.left.leafPrepend(other);\n    if (inner) { return new Append(inner, this.right) }\n  };\n\n  Append.prototype.appendInner = function appendInner (other) {\n    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)\n      { return new Append(this.left, new Append(this.right, other)) }\n    return new Append(this, other)\n  };\n\n  return Append;\n}(RopeSequence));\n\nexport default RopeSequence;\n", "import RopeSequence from 'rope-sequence';\nimport { Mapping } from 'prosemirror-transform';\nimport { PluginKey, Plugin } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' \u2014 a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n// Used to schedule history compression\nconst max_empty_items = 500;\nclass Branch {\n    constructor(items, eventCount) {\n        this.items = items;\n        this.eventCount = eventCount;\n    }\n    // Pop the latest event off the branch's history and apply it\n    // to a document transform.\n    popEvent(state, preserveItems) {\n        if (this.eventCount == 0)\n            return null;\n        let end = this.items.length;\n        for (;; end--) {\n            let next = this.items.get(end - 1);\n            if (next.selection) {\n                --end;\n                break;\n            }\n        }\n        let remap, mapFrom;\n        if (preserveItems) {\n            remap = this.remapping(end, this.items.length);\n            mapFrom = remap.maps.length;\n        }\n        let transform = state.tr;\n        let selection, remaining;\n        let addAfter = [], addBefore = [];\n        this.items.forEach((item, i) => {\n            if (!item.step) {\n                if (!remap) {\n                    remap = this.remapping(end, i + 1);\n                    mapFrom = remap.maps.length;\n                }\n                mapFrom--;\n                addBefore.push(item);\n                return;\n            }\n            if (remap) {\n                addBefore.push(new Item(item.map));\n                let step = item.step.map(remap.slice(mapFrom)), map;\n                if (step && transform.maybeStep(step).doc) {\n                    map = transform.mapping.maps[transform.mapping.maps.length - 1];\n                    addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));\n                }\n                mapFrom--;\n                if (map)\n                    remap.appendMap(map, mapFrom);\n            }\n            else {\n                transform.maybeStep(item.step);\n            }\n            if (item.selection) {\n                selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n                remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);\n                return false;\n            }\n        }, this.items.length, 0);\n        return { remaining: remaining, transform, selection: selection };\n    }\n    // Create a new branch with the given transform added.\n    addTransform(transform, selection, histOptions, preserveItems) {\n        let newItems = [], eventCount = this.eventCount;\n        let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n        for (let i = 0; i < transform.steps.length; i++) {\n            let step = transform.steps[i].invert(transform.docs[i]);\n            let item = new Item(transform.mapping.maps[i], step, selection), merged;\n            if (merged = lastItem && lastItem.merge(item)) {\n                item = merged;\n                if (i)\n                    newItems.pop();\n                else\n                    oldItems = oldItems.slice(0, oldItems.length - 1);\n            }\n            newItems.push(item);\n            if (selection) {\n                eventCount++;\n                selection = undefined;\n            }\n            if (!preserveItems)\n                lastItem = item;\n        }\n        let overflow = eventCount - histOptions.depth;\n        if (overflow > DEPTH_OVERFLOW) {\n            oldItems = cutOffEvents(oldItems, overflow);\n            eventCount -= overflow;\n        }\n        return new Branch(oldItems.append(newItems), eventCount);\n    }\n    remapping(from, to) {\n        let maps = new Mapping;\n        this.items.forEach((item, i) => {\n            let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from\n                ? maps.maps.length - item.mirrorOffset : undefined;\n            maps.appendMap(item.map, mirrorPos);\n        }, from, to);\n        return maps;\n    }\n    addMaps(array) {\n        if (this.eventCount == 0)\n            return this;\n        return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount);\n    }\n    // When the collab module receives remote changes, the history has\n    // to know about those, so that it can adjust the steps that were\n    // rebased on top of the remote changes, and include the position\n    // maps for the remote changes in its array of items.\n    rebased(rebasedTransform, rebasedCount) {\n        if (!this.eventCount)\n            return this;\n        rebasedCount = Math.min(this.items.length, rebasedCount);\n        let rebasedItems = [], start = this.items.length - rebasedCount;\n        let mapping = rebasedTransform.mapping;\n        let newUntil = rebasedTransform.steps.length;\n        let eventCount = this.eventCount;\n        this.items.forEach(item => { if (item.selection)\n            eventCount--; }, start);\n        let iRebased = rebasedCount;\n        this.items.forEach(item => {\n            let pos = mapping.getMirror(--iRebased);\n            if (pos == null)\n                return;\n            newUntil = Math.min(newUntil, pos);\n            let map = mapping.maps[pos];\n            if (item.step) {\n                let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n                let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n                if (selection)\n                    eventCount++;\n                rebasedItems.push(new Item(map, step, selection));\n            }\n            else {\n                rebasedItems.push(new Item(map));\n            }\n        }, start);\n        let newMaps = [];\n        for (let i = rebasedCount; i < newUntil; i++)\n            newMaps.push(new Item(mapping.maps[i]));\n        let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n        let branch = new Branch(items, eventCount);\n        if (branch.emptyItemCount() > max_empty_items)\n            branch = branch.compress(this.items.length - rebasedItems.length);\n        return branch;\n    }\n    emptyItemCount() {\n        let count = 0;\n        this.items.forEach(item => { if (!item.step)\n            count++; });\n        return count;\n    }\n    // Compressing a branch means rewriting it to push the air (map-only\n    // items) out. During collaboration, these naturally accumulate\n    // because each remote change adds one. The `upto` argument is used\n    // to ensure that only the items below a given level are compressed,\n    // because `rebased` relies on a clean, untouched set of items in\n    // order to associate old items with rebased steps.\n    compress(upto = this.items.length) {\n        let remap = this.remapping(0, upto), mapFrom = remap.maps.length;\n        let items = [], events = 0;\n        this.items.forEach((item, i) => {\n            if (i >= upto) {\n                items.push(item);\n                if (item.selection)\n                    events++;\n            }\n            else if (item.step) {\n                let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();\n                mapFrom--;\n                if (map)\n                    remap.appendMap(map, mapFrom);\n                if (step) {\n                    let selection = item.selection && item.selection.map(remap.slice(mapFrom));\n                    if (selection)\n                        events++;\n                    let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;\n                    if (merged = items.length && items[last].merge(newItem))\n                        items[last] = merged;\n                    else\n                        items.push(newItem);\n                }\n            }\n            else if (item.map) {\n                mapFrom--;\n            }\n        }, this.items.length, 0);\n        return new Branch(RopeSequence.from(items.reverse()), events);\n    }\n}\nBranch.empty = new Branch(RopeSequence.empty, 0);\nfunction cutOffEvents(items, n) {\n    let cutPoint;\n    items.forEach((item, i) => {\n        if (item.selection && (n-- == 0)) {\n            cutPoint = i;\n            return false;\n        }\n    });\n    return items.slice(cutPoint);\n}\nclass Item {\n    constructor(\n    // The (forward) step map for this item.\n    map, \n    // The inverted step\n    step, \n    // If this is non-null, this item is the start of a group, and\n    // this selection is the starting selection for the group (the one\n    // that was active before the first step was applied)\n    selection, \n    // If this item is the inverse of a previous mapping on the stack,\n    // this points at the inverse's offset\n    mirrorOffset) {\n        this.map = map;\n        this.step = step;\n        this.selection = selection;\n        this.mirrorOffset = mirrorOffset;\n    }\n    merge(other) {\n        if (this.step && other.step && !other.selection) {\n            let step = other.step.merge(this.step);\n            if (step)\n                return new Item(step.getMap().invert(), step, this.selection);\n        }\n    }\n}\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nclass HistoryState {\n    constructor(done, undone, prevRanges, prevTime, prevComposition) {\n        this.done = done;\n        this.undone = undone;\n        this.prevRanges = prevRanges;\n        this.prevTime = prevTime;\n        this.prevComposition = prevComposition;\n    }\n}\nconst DEPTH_OVERFLOW = 20;\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n    let historyTr = tr.getMeta(historyKey), rebased;\n    if (historyTr)\n        return historyTr.historyState;\n    if (tr.getMeta(closeHistoryKey))\n        history = new HistoryState(history.done, history.undone, null, 0, -1);\n    let appended = tr.getMeta(\"appendedTransaction\");\n    if (tr.steps.length == 0) {\n        return history;\n    }\n    else if (appended && appended.getMeta(historyKey)) {\n        if (appended.getMeta(historyKey).redo)\n            return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);\n        else\n            return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);\n    }\n    else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n        // Group transforms that occur in quick succession into one event.\n        let composition = tr.getMeta(\"composition\");\n        let newGroup = history.prevTime == 0 ||\n            (!appended && history.prevComposition != composition &&\n                (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges)));\n        let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);\n        return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);\n    }\n    else if (rebased = tr.getMeta(\"rebased\")) {\n        // Used by the collab module to tell the history that some of its\n        // content has been rebased.\n        return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n    }\n    else {\n        return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n    }\n}\nfunction isAdjacentTo(transform, prevRanges) {\n    if (!prevRanges)\n        return false;\n    if (!transform.docChanged)\n        return true;\n    let adjacent = false;\n    transform.mapping.maps[0].forEach((start, end) => {\n        for (let i = 0; i < prevRanges.length; i += 2)\n            if (start <= prevRanges[i + 1] && end >= prevRanges[i])\n                adjacent = true;\n    });\n    return adjacent;\n}\nfunction rangesFor(maps) {\n    let result = [];\n    for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)\n        maps[i].forEach((_from, _to, from, to) => result.push(from, to));\n    return result;\n}\nfunction mapRanges(ranges, mapping) {\n    if (!ranges)\n        return null;\n    let result = [];\n    for (let i = 0; i < ranges.length; i += 2) {\n        let from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);\n        if (from <= to)\n            result.push(from, to);\n    }\n    return result;\n}\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, redo) {\n    let preserveItems = mustPreserveItems(state);\n    let histOptions = historyKey.get(state).spec.config;\n    let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n    if (!pop)\n        return null;\n    let selection = pop.selection.resolve(pop.transform.doc);\n    let added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);\n    let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);\n    return pop.transform.setSelection(selection).setMeta(historyKey, { redo, historyState: newHist });\n}\nlet cachedPreserveItems = false, cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n    let plugins = state.plugins;\n    if (cachedPreserveItemsPlugins != plugins) {\n        cachedPreserveItems = false;\n        cachedPreserveItemsPlugins = plugins;\n        for (let i = 0; i < plugins.length; i++)\n            if (plugins[i].spec.historyPreserveItems) {\n                cachedPreserveItems = true;\n                break;\n            }\n    }\n    return cachedPreserveItems;\n}\n/**\nSet a flag on the given transaction that will prevent further steps\nfrom being appended to an existing history event (so that they\nrequire a separate undo command to undo).\n*/\nfunction closeHistory(tr) {\n    return tr.setMeta(closeHistoryKey, true);\n}\nconst historyKey = new PluginKey(\"history\");\nconst closeHistoryKey = new PluginKey(\"closeHistory\");\n/**\nReturns a plugin that enables the undo history for an editor. The\nplugin will track undo and redo stacks, which can be used with the\n[`undo`](https://prosemirror.net/docs/ref/#history.undo) and [`redo`](https://prosemirror.net/docs/ref/#history.redo) commands.\n\nYou can set an `\"addToHistory\"` [metadata\nproperty](https://prosemirror.net/docs/ref/#state.Transaction.setMeta) of `false` on a transaction\nto prevent it from being rolled back by undo.\n*/\nfunction history(config = {}) {\n    config = { depth: config.depth || 100,\n        newGroupDelay: config.newGroupDelay || 500 };\n    return new Plugin({\n        key: historyKey,\n        state: {\n            init() {\n                return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);\n            },\n            apply(tr, hist, state) {\n                return applyTransaction(hist, state, tr, config);\n            }\n        },\n        config,\n        props: {\n            handleDOMEvents: {\n                beforeinput(view, e) {\n                    let inputType = e.inputType;\n                    let command = inputType == \"historyUndo\" ? undo : inputType == \"historyRedo\" ? redo : null;\n                    if (!command || !view.editable)\n                        return false;\n                    e.preventDefault();\n                    return command(view.state, view.dispatch);\n                }\n            }\n        }\n    });\n}\nfunction buildCommand(redo, scroll) {\n    return (state, dispatch) => {\n        let hist = historyKey.getState(state);\n        if (!hist || (redo ? hist.undone : hist.done).eventCount == 0)\n            return false;\n        if (dispatch) {\n            let tr = histTransaction(hist, state, redo);\n            if (tr)\n                dispatch(scroll ? tr.scrollIntoView() : tr);\n        }\n        return true;\n    };\n}\n/**\nA command function that undoes the last change, if any.\n*/\nconst undo = buildCommand(false, true);\n/**\nA command function that redoes the last undone change, if any.\n*/\nconst redo = buildCommand(true, true);\n/**\nA command function that undoes the last change. Don't scroll the\nselection into view.\n*/\nconst undoNoScroll = buildCommand(false, false);\n/**\nA command function that redoes the last undone change. Don't\nscroll the selection into view.\n*/\nconst redoNoScroll = buildCommand(true, false);\n/**\nThe amount of undoable events available in a given state.\n*/\nfunction undoDepth(state) {\n    let hist = historyKey.getState(state);\n    return hist ? hist.done.eventCount : 0;\n}\n/**\nThe amount of redoable events available in a given editor state.\n*/\nfunction redoDepth(state) {\n    let hist = historyKey.getState(state);\n    return hist ? hist.undone.eventCount : 0;\n}\n/**\nReturns true if the given transaction was generated by the history\nplugin.\n*/\nfunction isHistoryTransaction(tr) {\n    return tr.getMeta(historyKey) != null;\n}\n\nexport { closeHistory, history, isHistoryTransaction, redo, redoDepth, redoNoScroll, undo, undoDepth, undoNoScroll };\n", "import { Extension } from '@tiptap/core'\nimport { history, redo, undo } from '@tiptap/pm/history'\n\nexport interface HistoryOptions {\n  /**\n   * The amount of history events that are collected before the oldest events are discarded.\n   * @default 100\n   * @example 50\n   */\n  depth: number,\n\n  /**\n   * The delay (in milliseconds) between changes after which a new group should be started.\n   * @default 500\n   * @example 1000\n   */\n  newGroupDelay: number,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    history: {\n      /**\n       * Undo recent changes\n       * @example editor.commands.undo()\n       */\n      undo: () => ReturnType,\n      /**\n       * Reapply reverted changes\n       * @example editor.commands.redo()\n       */\n      redo: () => ReturnType,\n    }\n  }\n}\n\n/**\n * This extension allows you to undo and redo recent changes.\n * @see https://www.tiptap.dev/api/extensions/history\n *\n * **Important**: If the `@tiptap/extension-collaboration` package is used, make sure to remove\n * the `history` extension, as it is not compatible with the `collaboration` extension.\n *\n * `@tiptap/extension-collaboration` uses its own history implementation.\n */\nexport const History = Extension.create<HistoryOptions>({\n  name: 'history',\n\n  addOptions() {\n    return {\n      depth: 100,\n      newGroupDelay: 500,\n    }\n  },\n\n  addCommands() {\n    return {\n      undo: () => ({ state, dispatch }) => {\n        return undo(state, dispatch)\n      },\n      redo: () => ({ state, dispatch }) => {\n        return redo(state, dispatch)\n      },\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      history(this.options),\n    ]\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-z': () => this.editor.commands.undo(),\n      'Shift-Mod-z': () => this.editor.commands.redo(),\n      'Mod-y': () => this.editor.commands.redo(),\n\n      // Russian keyboard layouts\n      'Mod-я': () => this.editor.commands.undo(),\n      'Shift-Mod-я': () => this.editor.commands.redo(),\n    }\n  },\n})\n", "import {\n  canInsertNode, isNodeSelection, mergeAttributes, Node, nodeInputRule,\n} from '@tiptap/core'\nimport { NodeSelection, TextSelection } from '@tiptap/pm/state'\n\nexport interface HorizontalRuleOptions {\n  /**\n   * The HTML attributes for a horizontal rule node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    horizontalRule: {\n      /**\n       * Add a horizontal rule\n       * @example editor.commands.setHorizontalRule()\n       */\n      setHorizontalRule: () => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to insert horizontal rules.\n * @see https://www.tiptap.dev/api/nodes/horizontal-rule\n */\nexport const HorizontalRule = Node.create<HorizontalRuleOptions>({\n  name: 'horizontalRule',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  group: 'block',\n\n  parseHTML() {\n    return [{ tag: 'hr' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['hr', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]\n  },\n\n  addCommands() {\n    return {\n      setHorizontalRule:\n        () => ({ chain, state }) => {\n          // Check if we can insert the node at the current selection\n          if (!canInsertNode(state, state.schema.nodes[this.name])) {\n            return false\n          }\n\n          const { selection } = state\n          const { $from: $originFrom, $to: $originTo } = selection\n\n          const currentChain = chain()\n\n          if ($originFrom.parentOffset === 0) {\n            currentChain.insertContentAt(\n              {\n                from: Math.max($originFrom.pos - 1, 0),\n                to: $originTo.pos,\n              },\n              {\n                type: this.name,\n              },\n            )\n          } else if (isNodeSelection(selection)) {\n            currentChain.insertContentAt($originTo.pos, {\n              type: this.name,\n            })\n          } else {\n            currentChain.insertContent({ type: this.name })\n          }\n\n          return (\n            currentChain\n              // set cursor after horizontal rule\n              .command(({ tr, dispatch }) => {\n                if (dispatch) {\n                  const { $to } = tr.selection\n                  const posAfter = $to.end()\n\n                  if ($to.nodeAfter) {\n                    if ($to.nodeAfter.isTextblock) {\n                      tr.setSelection(TextSelection.create(tr.doc, $to.pos + 1))\n                    } else if ($to.nodeAfter.isBlock) {\n                      tr.setSelection(NodeSelection.create(tr.doc, $to.pos))\n                    } else {\n                      tr.setSelection(TextSelection.create(tr.doc, $to.pos))\n                    }\n                  } else {\n                    // add node after horizontal rule if it’s the end of the document\n                    const node = $to.parent.type.contentMatch.defaultType?.create()\n\n                    if (node) {\n                      tr.insert(posAfter, node)\n                      tr.setSelection(TextSelection.create(tr.doc, posAfter + 1))\n                    }\n                  }\n\n                  tr.scrollIntoView()\n                }\n\n                return true\n              })\n              .run()\n          )\n        },\n    }\n  },\n\n  addInputRules() {\n    return [\n      nodeInputRule({\n        find: /^(?:---|—-|___\\s|\\*\\*\\*\\s)$/,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import {\n  Mark,\n  markInputRule,\n  markPasteRule,\n  mergeAttributes,\n} from '@tiptap/core'\n\nexport interface ItalicOptions {\n  /**\n   * HTML attributes to add to the italic element.\n   * @default {}\n   * @example { class: 'foo' }\n  */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    italic: {\n      /**\n       * Set an italic mark\n       * @example editor.commands.setItalic()\n       */\n      setItalic: () => ReturnType,\n      /**\n       * Toggle an italic mark\n       * @example editor.commands.toggleItalic()\n       */\n      toggleItalic: () => ReturnType,\n      /**\n       * Unset an italic mark\n       * @example editor.commands.unsetItalic()\n       */\n      unsetItalic: () => ReturnType,\n    }\n  }\n}\n\n/**\n * Matches an italic to a *italic* on input.\n */\nexport const starInputRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))$/\n\n/**\n * Matches an italic to a *italic* on paste.\n */\nexport const starPasteRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))/g\n\n/**\n * Matches an italic to a _italic_ on input.\n */\nexport const underscoreInputRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))$/\n\n/**\n * Matches an italic to a _italic_ on paste.\n */\nexport const underscorePasteRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))/g\n\n/**\n * This extension allows you to create italic text.\n * @see https://www.tiptap.dev/api/marks/italic\n */\nexport const Italic = Mark.create<ItalicOptions>({\n  name: 'italic',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'em',\n      },\n      {\n        tag: 'i',\n        getAttrs: node => (node as HTMLElement).style.fontStyle !== 'normal' && null,\n      },\n      {\n        style: 'font-style=normal',\n        clearMark: mark => mark.type.name === this.name,\n      },\n      {\n        style: 'font-style=italic',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['em', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setItalic: () => ({ commands }) => {\n        return commands.setMark(this.name)\n      },\n      toggleItalic: () => ({ commands }) => {\n        return commands.toggleMark(this.name)\n      },\n      unsetItalic: () => ({ commands }) => {\n        return commands.unsetMark(this.name)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-i': () => this.editor.commands.toggleItalic(),\n      'Mod-I': () => this.editor.commands.toggleItalic(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: starInputRegex,\n        type: this.type,\n      }),\n      markInputRule({\n        find: underscoreInputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: starPasteRegex,\n        type: this.type,\n      }),\n      markPasteRule({\n        find: underscorePasteRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface ListItemOptions {\n  /**\n   * The HTML attributes for a list item node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n\n  /**\n   * The node type for bulletList nodes\n   * @default 'bulletList'\n   * @example 'myCustomBulletList'\n   */\n  bulletListTypeName: string\n\n  /**\n   * The node type for orderedList nodes\n   * @default 'orderedList'\n   * @example 'myCustomOrderedList'\n   */\n  orderedListTypeName: string\n}\n\n/**\n * This extension allows you to create list items.\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nexport const ListItem = Node.create<ListItemOptions>({\n  name: 'listItem',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n      bulletListTypeName: 'bulletList',\n      orderedListTypeName: 'orderedList',\n    }\n  },\n\n  content: 'paragraph block*',\n\n  defining: true,\n\n  parseHTML() {\n    return [\n      {\n        tag: 'li',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['li', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      Enter: () => this.editor.commands.splitListItem(this.name),\n      Tab: () => this.editor.commands.sinkListItem(this.name),\n      'Shift-Tab': () => this.editor.commands.liftListItem(this.name),\n    }\n  },\n})\n", "import { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nconst ListItemName = 'listItem'\nconst TextStyleName = 'textStyle'\n\nexport interface OrderedListOptions {\n  /**\n   * The node type name for list items.\n   * @default 'listItem'\n   * @example 'myListItem'\n   */\n  itemTypeName: string,\n\n  /**\n   * The HTML attributes for an ordered list node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n\n  /**\n   * Keep the marks when splitting a list item.\n   * @default false\n   * @example true\n   */\n  keepMarks: boolean,\n\n  /**\n   * Keep the attributes when splitting a list item.\n   * @default false\n   * @example true\n   */\n  keepAttributes: boolean,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    orderedList: {\n      /**\n       * Toggle an ordered list\n       * @example editor.commands.toggleOrderedList()\n       */\n      toggleOrderedList: () => ReturnType,\n    }\n  }\n}\n\n/**\n * Matches an ordered list to a 1. on input (or any number followed by a dot).\n */\nexport const inputRegex = /^(\\d+)\\.\\s$/\n\n/**\n * This extension allows you to create ordered lists.\n * This requires the ListItem extension\n * @see https://www.tiptap.dev/api/nodes/ordered-list\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nexport const OrderedList = Node.create<OrderedListOptions>({\n  name: 'orderedList',\n\n  addOptions() {\n    return {\n      itemTypeName: 'listItem',\n      HTMLAttributes: {},\n      keepMarks: false,\n      keepAttributes: false,\n    }\n  },\n\n  group: 'block list',\n\n  content() {\n    return `${this.options.itemTypeName}+`\n  },\n\n  addAttributes() {\n    return {\n      start: {\n        default: 1,\n        parseHTML: element => {\n          return element.hasAttribute('start')\n            ? parseInt(element.getAttribute('start') || '', 10)\n            : 1\n        },\n      },\n      type: {\n        default: null,\n        parseHTML: element => element.getAttribute('type'),\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'ol',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    const { start, ...attributesWithoutStart } = HTMLAttributes\n\n    return start === 1\n      ? ['ol', mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0]\n      : ['ol', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      toggleOrderedList: () => ({ commands, chain }) => {\n        if (this.options.keepAttributes) {\n          return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run()\n        }\n        return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-7': () => this.editor.commands.toggleOrderedList(),\n    }\n  },\n\n  addInputRules() {\n    let inputRule = wrappingInputRule({\n      find: inputRegex,\n      type: this.type,\n      getAttributes: match => ({ start: +match[1] }),\n      joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1],\n    })\n\n    if (this.options.keepMarks || this.options.keepAttributes) {\n      inputRule = wrappingInputRule({\n        find: inputRegex,\n        type: this.type,\n        keepMarks: this.options.keepMarks,\n        keepAttributes: this.options.keepAttributes,\n        getAttributes: match => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName) }),\n        joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1],\n        editor: this.editor,\n      })\n    }\n    return [\n      inputRule,\n    ]\n  },\n})\n", "import { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface ParagraphOptions {\n  /**\n   * The HTML attributes for a paragraph node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    paragraph: {\n      /**\n       * Toggle a paragraph\n       * @example editor.commands.toggleParagraph()\n       */\n      setParagraph: () => ReturnType,\n    }\n  }\n}\n\n/**\n * This extension allows you to create paragraphs.\n * @see https://www.tiptap.dev/api/nodes/paragraph\n */\nexport const Paragraph = Node.create<ParagraphOptions>({\n  name: 'paragraph',\n\n  priority: 1000,\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  group: 'block',\n\n  content: 'inline*',\n\n  parseHTML() {\n    return [\n      { tag: 'p' },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['p', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setParagraph: () => ({ commands }) => {\n        return commands.setNode(this.name)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Alt-0': () => this.editor.commands.setParagraph(),\n    }\n  },\n})\n", "import {\n  Mark,\n  markInputRule,\n  markPasteRule,\n  mergeAttributes,\n} from '@tiptap/core'\n\nexport interface StrikeOptions {\n  /**\n   * HTML attributes to add to the strike element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>,\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    strike: {\n      /**\n       * Set a strike mark\n       * @example editor.commands.setStrike()\n       */\n      setStrike: () => ReturnType,\n      /**\n       * Toggle a strike mark\n       * @example editor.commands.toggleStrike()\n       */\n      toggleStrike: () => ReturnType,\n      /**\n       * Unset a strike mark\n       * @example editor.commands.unsetStrike()\n       */\n      unsetStrike: () => ReturnType,\n    }\n  }\n}\n\n/**\n * Matches a strike to a ~~strike~~ on input.\n */\nexport const inputRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))$/\n\n/**\n * Matches a strike to a ~~strike~~ on paste.\n */\nexport const pasteRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))/g\n\n/**\n * This extension allows you to create strike text.\n * @see https://www.tiptap.dev/api/marks/strike\n */\nexport const Strike = Mark.create<StrikeOptions>({\n  name: 'strike',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 's',\n      },\n      {\n        tag: 'del',\n      },\n      {\n        tag: 'strike',\n      },\n      {\n        style: 'text-decoration',\n        consuming: false,\n        getAttrs: style => ((style as string).includes('line-through') ? {} : false),\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['s', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setStrike: () => ({ commands }) => {\n        return commands.setMark(this.name)\n      },\n      toggleStrike: () => ({ commands }) => {\n        return commands.toggleMark(this.name)\n      },\n      unsetStrike: () => ({ commands }) => {\n        return commands.unsetMark(this.name)\n      },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-s': () => this.editor.commands.toggleStrike(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: inputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: pasteRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { Node } from '@tiptap/core'\n\n/**\n * This extension allows you to create text nodes.\n * @see https://www.tiptap.dev/api/nodes/text\n */\nexport const Text = Node.create({\n  name: 'text',\n  group: 'inline',\n})\n", "import { Extension } from '@tiptap/core'\nimport { Blockquote, BlockquoteOptions } from '@tiptap/extension-blockquote'\nimport { Bold, BoldOptions } from '@tiptap/extension-bold'\nimport { BulletList, BulletListOptions } from '@tiptap/extension-bullet-list'\nimport { Code, CodeOptions } from '@tiptap/extension-code'\nimport { CodeBlock, CodeBlockOptions } from '@tiptap/extension-code-block'\nimport { Document } from '@tiptap/extension-document'\nimport { Dropcursor, DropcursorOptions } from '@tiptap/extension-dropcursor'\nimport { Gapcursor } from '@tiptap/extension-gapcursor'\nimport { HardBreak, HardBreakOptions } from '@tiptap/extension-hard-break'\nimport { Heading, HeadingOptions } from '@tiptap/extension-heading'\nimport { History, HistoryOptions } from '@tiptap/extension-history'\nimport { HorizontalRule, HorizontalRuleOptions } from '@tiptap/extension-horizontal-rule'\nimport { Italic, ItalicOptions } from '@tiptap/extension-italic'\nimport { ListItem, ListItemOptions } from '@tiptap/extension-list-item'\nimport { OrderedList, OrderedListOptions } from '@tiptap/extension-ordered-list'\nimport { Paragraph, ParagraphOptions } from '@tiptap/extension-paragraph'\nimport { Strike, StrikeOptions } from '@tiptap/extension-strike'\nimport { Text } from '@tiptap/extension-text'\n\nexport interface StarterKitOptions {\n  /**\n   * If set to false, the blockquote extension will not be registered\n   * @example blockquote: false\n   */\n  blockquote: Partial<BlockquoteOptions> | false,\n\n  /**\n   * If set to false, the bold extension will not be registered\n   * @example bold: false\n   */\n  bold: Partial<BoldOptions> | false,\n\n  /**\n   * If set to false, the bulletList extension will not be registered\n   * @example bulletList: false\n   */\n  bulletList: Partial<BulletListOptions> | false,\n\n  /**\n   * If set to false, the code extension will not be registered\n   * @example code: false\n   */\n  code: Partial<CodeOptions> | false,\n\n  /**\n   * If set to false, the codeBlock extension will not be registered\n   * @example codeBlock: false\n   */\n  codeBlock: Partial<CodeBlockOptions> | false,\n\n  /**\n   * If set to false, the document extension will not be registered\n   * @example document: false\n   */\n  document: false,\n\n  /**\n   * If set to false, the dropcursor extension will not be registered\n   * @example dropcursor: false\n   */\n  dropcursor: Partial<DropcursorOptions> | false,\n\n  /**\n   * If set to false, the gapcursor extension will not be registered\n   * @example gapcursor: false\n   */\n  gapcursor: false,\n\n  /**\n   * If set to false, the hardBreak extension will not be registered\n   * @example hardBreak: false\n   */\n  hardBreak: Partial<HardBreakOptions> | false,\n\n  /**\n   * If set to false, the heading extension will not be registered\n   * @example heading: false\n   */\n  heading: Partial<HeadingOptions> | false,\n\n  /**\n   * If set to false, the history extension will not be registered\n   * @example history: false\n   */\n  history: Partial<HistoryOptions> | false,\n\n  /**\n   * If set to false, the horizontalRule extension will not be registered\n   * @example horizontalRule: false\n   */\n  horizontalRule: Partial<HorizontalRuleOptions> | false,\n\n  /**\n   * If set to false, the italic extension will not be registered\n   * @example italic: false\n   */\n  italic: Partial<ItalicOptions> | false,\n\n  /**\n   * If set to false, the listItem extension will not be registered\n   * @example listItem: false\n   */\n  listItem: Partial<ListItemOptions> | false,\n\n  /**\n   * If set to false, the orderedList extension will not be registered\n   * @example orderedList: false\n   */\n  orderedList: Partial<OrderedListOptions> | false,\n\n  /**\n   * If set to false, the paragraph extension will not be registered\n   * @example paragraph: false\n   */\n  paragraph: Partial<ParagraphOptions> | false,\n\n  /**\n   * If set to false, the strike extension will not be registered\n   * @example strike: false\n   */\n  strike: Partial<StrikeOptions> | false,\n\n  /**\n   * If set to false, the text extension will not be registered\n   * @example text: false\n   */\n  text: false,\n}\n\n/**\n * The starter kit is a collection of essential editor extensions.\n *\n * It’s a good starting point for building your own editor.\n */\nexport const StarterKit = Extension.create<StarterKitOptions>({\n  name: 'starterKit',\n\n  addExtensions() {\n    const extensions = []\n\n    if (this.options.bold !== false) {\n      extensions.push(Bold.configure(this.options.bold))\n    }\n\n    if (this.options.blockquote !== false) {\n      extensions.push(Blockquote.configure(this.options.blockquote))\n    }\n\n    if (this.options.bulletList !== false) {\n      extensions.push(BulletList.configure(this.options.bulletList))\n    }\n\n    if (this.options.code !== false) {\n      extensions.push(Code.configure(this.options.code))\n    }\n\n    if (this.options.codeBlock !== false) {\n      extensions.push(CodeBlock.configure(this.options.codeBlock))\n    }\n\n    if (this.options.document !== false) {\n      extensions.push(Document.configure(this.options.document))\n    }\n\n    if (this.options.dropcursor !== false) {\n      extensions.push(Dropcursor.configure(this.options.dropcursor))\n    }\n\n    if (this.options.gapcursor !== false) {\n      extensions.push(Gapcursor.configure(this.options.gapcursor))\n    }\n\n    if (this.options.hardBreak !== false) {\n      extensions.push(HardBreak.configure(this.options.hardBreak))\n    }\n\n    if (this.options.heading !== false) {\n      extensions.push(Heading.configure(this.options.heading))\n    }\n\n    if (this.options.history !== false) {\n      extensions.push(History.configure(this.options.history))\n    }\n\n    if (this.options.horizontalRule !== false) {\n      extensions.push(HorizontalRule.configure(this.options.horizontalRule))\n    }\n\n    if (this.options.italic !== false) {\n      extensions.push(Italic.configure(this.options.italic))\n    }\n\n    if (this.options.listItem !== false) {\n      extensions.push(ListItem.configure(this.options.listItem))\n    }\n\n    if (this.options.orderedList !== false) {\n      extensions.push(OrderedList.configure(this.options.orderedList))\n    }\n\n    if (this.options.paragraph !== false) {\n      extensions.push(Paragraph.configure(this.options.paragraph))\n    }\n\n    if (this.options.strike !== false) {\n      extensions.push(Strike.configure(this.options.strike))\n    }\n\n    if (this.options.text !== false) {\n      extensions.push(Text.configure(this.options.text))\n    }\n\n    return extensions\n  },\n})\n", "import { Extension } from '@tiptap/core';\nimport { Plugin, PluginKey } from 'prosemirror-state';\nimport slugify from 'slugify';\n\nconst isTargetNodeOfType = (node, type) => (node.type === type);\n\nexport const pluginKey = new PluginKey('tableOfContents')\n\nexport const TableOfContents = Extension.create({\n  name: 'tableOfContents',\n\n  addGlobalAttributes() {\n    return [\n      {\n        types: [\n          'heading',\n        ],\n        attributes: {\n          id: {\n            default: null,\n          },\n        },\n        renderHTML: (attributes) => {\n          console.log(\"renderHTML\", attributes);\n          return {\n            id: attributes.id,\n          };\n        },\n        parseHTML: (element) => {\n          console.log(\"parseHTML\", element);\n          return element.id;\n        },\n      },\n    ]\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: pluginKey,\n        appendTransaction: (transactions, _prevState, nextState) => {\n          const tr = nextState.tr;\n          let modified = false;\n\n          if (transactions.some((transaction) => transaction.docChanged)) {\n            // Adds a unique id to a node\n            nextState.doc.descendants((node, pos) => {\n              const { heading } = nextState.schema.nodes;\n              if (isTargetNodeOfType(node, heading)) {\n                const attrs = node.attrs;\n                // TODO: set locale\n                const slug = slugify(node.textContent, { lower: true, strict: true, locale: 'fr' });\n                tr.setNodeMarkup(pos, undefined, {...attrs, ['id']: slug});\n                modified = true;\n              }\n            });\n          }\n\n          return modified ? tr : null;\n        }\n      })\n    ];\n  }\n})\n", "import { Node, mergeAttributes } from '@tiptap/core'\n\nfunction attributesToParams(attributes) {\n  const params = Object.fromEntries(\n    Object.entries(attributes).map(([k, v]) => [`prompt[${k}]`, v])\n  );\n  return new URLSearchParams(params).toString();\n}\n\nexport default Node.create({\n  name: 'promptsBlock',\n  group: 'block',\n  atom: true,\n\n  addAttributes() {\n    return {\n      color: {\n        default: null,\n      },\n      href: {\n        default: null,\n      },\n      target: {\n        default: null,\n      },\n      text: {\n        default: \"\",\n      },\n      title: {\n        default: null,\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'prompts-block',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['prompts-block', mergeAttributes(HTMLAttributes)]\n  },\n\n  addNodeView() {\n    return ({ editor, node, getPos, HTMLAttributes, decorations, extension }) => {\n      const dom = document.createElement('prompts-block');\n      const params = attributesToParams(node.attrs);\n\n      dom.innerHTML = `\n        <button type=\"button\" class=\"color-${node.attrs.color}\" title=\"${node.attrs.title || ''}\" data-action=\"admin--form--content-editor#togglePrompts admin--layout#openPanel\" data-params=\"${params}\">${node.attrs.text}</button>\n      `;\n\n      return {\n        dom,\n      }\n    };\n  },\n})\n", "import { Node, mergeAttributes } from '@tiptap/core'\n\nfunction attributesToParams(attributes) {\n  const params = Object.fromEntries(\n    Object.entries(attributes).map(([k, v]) => [`image[${k}]`, v])\n  );\n  return new URLSearchParams(params).toString();\n}\n\nexport default Node.create({\n  name: 'imageBlock',\n  group: 'block',\n  atom: true,\n\n  addAttributes() {\n    return {\n      alt: {\n        default: null,\n      },\n      credit: {\n        default: null,\n      },\n      file_data: {\n        default: null,\n      },\n      file_url: {\n        default: null,\n      },\n      text: {\n        default: null,\n      },\n      size: {\n        default: null,\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'image-block',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['image-block', mergeAttributes(HTMLAttributes)]\n  },\n\n  addNodeView() {\n    return ({ editor, node, getPos, HTMLAttributes, decorations, extension }) => {\n      const dom = document.createElement('image-block');\n      const params = attributesToParams(node.attrs);\n\n      dom.innerHTML = `\n        <button type=\"button\" data-action=\"admin--form--content-editor#toggleImage admin--layout#openPanel\" data-params=\"${params}\">\n          <span class=\"c-admin--form--content-editor-content-image\" data-size=\"${node.attrs.size}\">\n            <img src=\"${node.attrs.file_url}\" alt=\"${node.attrs.alt}\" />\n          </span>\n          ${node.attrs.text ? `<span>${node.attrs.text}</span>` : ''}\n        </button>\n      `;\n\n      return {\n        dom,\n      }\n    };\n  },\n})\n", "import \"./fieldset_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./group_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./grouped_collection_select_component.css\";\nimport '../../../../../vendor/tom_select/css/tom-select.custom.css';\nimport TomSelect from \"tom-select\";\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  connect() {\n    const config = {\n      plugins: ['checkbox_options'],\n    };\n    this.tomSelect = new TomSelect(this.element, config);\n  }\n\n  disconnect() {\n    this.tomSelect.destroy();\n  }\n}\n", "/**\n * MicroEvent - to make any js object an event emitter\n *\n * - pure javascript - server compatible, browser compatible\n * - dont rely on the browser doms\n * - super simple - you get it immediatly, no mistery, no magic involved\n *\n * @author Jerome Etienne (https://github.com/jeromeetienne)\n */\n\ntype TCallback = (...args:any) => any;\n\n/**\n * Execute callback for each event in space separated list of event names\n *\n */\nfunction forEvents(events:string,callback:(event:string)=>any){\n\tevents.split(/\\s+/).forEach((event) =>{\n\t\tcallback(event);\n\t});\n}\n\nexport default class MicroEvent{\n\n\tpublic _events: {[key:string]:TCallback[]};\n\n\tconstructor(){\n\t\tthis._events = {};\n\t}\n\n\ton(events:string, fct:TCallback){\n\t\tforEvents(events,(event) => {\n\t\t\tconst event_array = this._events[event] || [];\n\t\t\tevent_array.push(fct);\n\t\t\tthis._events[event] = event_array;\n\t\t});\n\t}\n\n\toff(events:string, fct:TCallback){\n\t\tvar n = arguments.length;\n\t\tif( n === 0 ){\n\t\t\tthis._events = {};\n\t\t\treturn;\n\t\t}\n\n\t\tforEvents(events,(event) => {\n\n\t\t\tif (n === 1){\n\t\t\t\tdelete this._events[event];\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst event_array = this._events[event];\n\t\t\tif( event_array === undefined ) return;\n\n\t\t\tevent_array.splice(event_array.indexOf(fct), 1);\n\t\t\tthis._events[event] = event_array;\n\t\t});\n\t}\n\n\ttrigger(events:string, ...args:any){\n\t\tvar self = this;\n\n\t\tforEvents(events,(event) => {\n\t\t\tconst event_array = self._events[event];\n\t\t\tif( event_array === undefined ) return;\n\t\t\tevent_array.forEach(fct => {\n\t\t\t\tfct.apply(self, args );\n\t\t\t});\n\n\t\t});\n\t}\n};\n", "/**\n * microplugin.js\n * Copyright (c) 2013 Brian Reavis & contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * @author Brian Reavis <brian@thirdroute.com>\n */\n\ntype TSettings = {\n\t[key:string]:any\n}\n\ntype TPlugins = {\n\tnames: string[],\n\tsettings: TSettings,\n\trequested: {[key:string]:boolean},\n\tloaded: {[key:string]:any}\n};\n\nexport type TPluginItem = {name:string,options:{}};\nexport type TPluginHash = {[key:string]:{}};\n\n\n\n\nexport default function MicroPlugin(Interface: any ){\n\n\tInterface.plugins = {};\n\n\treturn class extends Interface{\n\n\t\tpublic plugins:TPlugins = {\n\t\t\tnames     : [],\n\t\t\tsettings  : {},\n\t\t\trequested : {},\n\t\t\tloaded    : {}\n\t\t};\n\n\t\t/**\n\t\t * Registers a plugin.\n\t\t *\n\t\t * @param {function} fn\n\t\t */\n\t\tstatic define(name:string, fn:(this:any,settings:TSettings)=>any){\n\t\t\tInterface.plugins[name] = {\n\t\t\t\t'name' : name,\n\t\t\t\t'fn'   : fn\n\t\t\t};\n\t\t}\n\n\n\t\t/**\n\t\t * Initializes the listed plugins (with options).\n\t\t * Acceptable formats:\n\t\t *\n\t\t * List (without options):\n\t\t *   ['a', 'b', 'c']\n\t\t *\n\t\t * List (with options):\n\t\t *   [{'name': 'a', options: {}}, {'name': 'b', options: {}}]\n\t\t *\n\t\t * Hash (with options):\n\t\t *   {'a': { ... }, 'b': { ... }, 'c': { ... }}\n\t\t *\n\t\t * @param {array|object} plugins\n\t\t */\n\t\tinitializePlugins(plugins:string[]|TPluginItem[]|TPluginHash) {\n\t\t\tvar key, name;\n\t\t\tconst self  = this;\n\t\t\tconst queue:string[] = [];\n\n\t\t\tif (Array.isArray(plugins)) {\n\t\t\t\tplugins.forEach((plugin:string|TPluginItem)=>{\n\t\t\t\t\tif (typeof plugin === 'string') {\n\t\t\t\t\t\tqueue.push(plugin);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tself.plugins.settings[plugin.name] = plugin.options;\n\t\t\t\t\t\tqueue.push(plugin.name);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else if (plugins) {\n\t\t\t\tfor (key in plugins) {\n\t\t\t\t\tif (plugins.hasOwnProperty(key)) {\n\t\t\t\t\t\tself.plugins.settings[key] = plugins[key];\n\t\t\t\t\t\tqueue.push(key);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile( name = queue.shift() ){\n\t\t\t\tself.require(name);\n\t\t\t}\n\t\t}\n\n\t\tloadPlugin(name:string) {\n\t\t\tvar self    = this;\n\t\t\tvar plugins = self.plugins;\n\t\t\tvar plugin  = Interface.plugins[name];\n\n\t\t\tif (!Interface.plugins.hasOwnProperty(name)) {\n\t\t\t\tthrow new Error('Unable to find \"' +  name + '\" plugin');\n\t\t\t}\n\n\t\t\tplugins.requested[name] = true;\n\t\t\tplugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);\n\t\t\tplugins.names.push(name);\n\t\t}\n\n\t\t/**\n\t\t * Initializes a plugin.\n\t\t *\n\t\t */\n\t\trequire(name:string) {\n\t\t\tvar self = this;\n\t\t\tvar plugins = self.plugins;\n\n\t\t\tif (!self.plugins.loaded.hasOwnProperty(name)) {\n\t\t\t\tif (plugins.requested[name]) {\n\t\t\t\t\tthrow new Error('Plugin has circular dependency (\"' + name + '\")');\n\t\t\t\t}\n\t\t\t\tself.loadPlugin(name);\n\t\t\t}\n\n\t\t\treturn plugins.loaded[name];\n\t\t}\n\n\t};\n\n}\n", "/**\n * Convert array of strings to a regular expression\n *\tex ['ab','a'] => (?:ab|a)\n * \tex ['a','b'] => [ab]\n */\nexport const arrayToPattern = (chars: string[]): string => {\n\n\tchars = chars.filter( Boolean );\n\n\tif( chars.length < 2 ){\n\t\treturn chars[0] || '';\n\t}\n\n\treturn (maxValueLength(chars) == 1) ? '['+chars.join('')+']' : '(?:'+chars.join('|')+')';\n};\n\nexport const sequencePattern = (array: string[]): string => {\n\n\tif( !hasDuplicates(array) ){\n\t\treturn array.join('');\n\t}\n\n\tlet pattern = '';\n\tlet prev_char_count = 0;\n\n\tconst prev_pattern = ()=>{\n\t\tif( prev_char_count > 1 ){\n\t\t\tpattern += '{'+prev_char_count+'}';\n\t\t}\n\t}\n\n\tarray.forEach((char,i)=>{\n\n\t\tif( char === array[i-1] ){\n\t\t\tprev_char_count++;\n\t\t\treturn;\n\t\t}\n\n\t\tprev_pattern();\n\n\t\tpattern += char;\n\t\tprev_char_count = 1;\n\t});\n\n\tprev_pattern();\n\n\treturn pattern;\n\n}\n\n\n\n/**\n * Convert array of strings to a regular expression\n *\tex ['ab','a'] => (?:ab|a)\n * \tex ['a','b'] => [ab]\n */\nexport const setToPattern = (chars: Set<string>): string => {\n\tlet array = Array.from(chars);\n\treturn arrayToPattern(array);\n}\n\n\n\n/**\n * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values\n */\nexport const hasDuplicates = (array: any[]) => {\n    return (new Set(array)).size !== array.length;\n}\n\n\n/**\n * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error\n */\nexport const escape_regex = (str: string): string => {\n\treturn (str + '').replace(/([\\$\\(\\)\\*\\+\\.\\?\\[\\]\\^\\{\\|\\}\\\\])/gu, '\\\\$1');\n};\n\n/**\n * Return the max length of array values\n */\nexport const maxValueLength = (array: string[]) => {\n\treturn array.reduce( (longest, value) => Math.max(longest,unicodeLength(value)),0);\n}\n\n\nexport const unicodeLength = (str: string) => {\n\treturn Array.from(str).length;\n}\n", "/**\n * Get all possible combinations of substrings that add up to the given string\n * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string\n */\nexport const allSubstrings = (input: string): string[][] => {\n\n    if( input.length === 1) return [[input]];\n\n    let result: string[][] = [];\n\n\tconst start = input.substring(1);\n    const suba = allSubstrings(start);\n\n\tsuba.forEach(function(subresult) {\n        let tmp = subresult.slice(0);\n        tmp[0] = input.charAt(0) + tmp[0];\n        result.push(tmp);\n\n        tmp = subresult.slice(0);\n        tmp.unshift(input.charAt(0));\n        result.push(tmp);\n    });\n\n    return result;\n}\n", "import { setToPattern, arrayToPattern, escape_regex, sequencePattern } from './regex.ts';\nimport { allSubstrings } from './strings.ts';\n\nexport type TUnicodeMap = {[key:string]:string};\nexport type TUnicodeSets = {[key:string]:Set<string>};\nexport type TCodePoints = [number,number][];\nexport type TCodePointObj = {folded:string,composed:string,code_point:number}\nexport type TSequencePart = {start:number,end:number,length:number,substr:string}\n\nexport const code_points: TCodePoints = [[ 0, 65535 ]];\n\n// code_points without blocks that never fold: CJK Unified Ideographs, Yijing,\n// Yi, Lisu, Vai, Hangul, surrogates and private use.\nexport const folding_code_points: TCodePoints = [[ 0x0000, 0x33FF ], [ 0xA640, 0xABFF ], [ 0xF900, 0xFFFF ]];\n\nconst accent_pat = '[\\u0300-\\u036F\\u{b7}\\u{2be}\\u{2bc}]';\n\nexport let unicode_map: TUnicodeMap;\n\nlet multi_char_reg: RegExp;\n\nconst max_char_length = 3;\n\nconst latin_convert: TUnicodeMap = {}\n\nconst latin_condensed: TUnicodeMap = {\n\t'/': '\u2044\u2215',\n\t'0': '\u07C0',\n\t\"a\": \"\u2C65\u0250\u0251\",\n\t\"aa\": \"\uA733\",\n\t\"ae\": \"\u00E6\u01FD\u01E3\",\n\t\"ao\": \"\uA735\",\n\t\"au\": \"\uA737\",\n\t\"av\": \"\uA739\uA73B\",\n\t\"ay\": \"\uA73D\",\n\t\"b\": \"\u0180\u0253\u0183\",\n\t\"c\": \"\uA73F\u0188\u023C\u2184\",\n\t\"d\": \"\u0111\u0257\u0256\u1D05\u018C\uABB7\u0501\u0266\",\n\t\"e\": \"\u025B\u01DD\u1D07\u0247\",\n\t\"f\": \"\uA77C\u0192\",\n\t\"g\": \"\u01E5\u0260\uA7A1\u1D79\uA77F\u0262\",\n\t\"h\": \"\u0127\u2C68\u2C76\u0265\",\n\t\"i\": \"\u0268\u0131\",\n\t\"j\": \"\u0249\u0237\",\n\t\"k\": \"\u0199\u2C6A\uA741\uA743\uA745\uA7A3\",\n\t\"l\": \"\u0142\u019A\u026B\u2C61\uA749\uA747\uA781\u026D\",\n\t\"m\": \"\u0271\u026F\u03FB\",\n\t\"n\": \"\uA7A5\u019E\u0272\uA791\u1D0E\u043B\u0509\",\n\t\"o\": \"\u00F8\u01FF\u0254\u0275\uA74B\uA74D\u1D11\",\n\t\"oe\": \"\u0153\",\n\t\"oi\": \"\u01A3\",\n\t\"oo\": \"\uA74F\",\n\t\"ou\": \"\u0223\",\n\t\"p\": \"\u01A5\u1D7D\uA751\uA753\uA755\u03C1\",\n\t\"q\": \"\uA757\uA759\u024B\",\n\t\"r\": \"\u024D\u027D\uA75B\uA7A7\uA783\",\n\t\"s\": \"\u023F\uA7A9\uA785\u0282\",\n\t\"ss\": \"\u00DF\",\n\t\"t\": \"\u0167\u01AD\u0288\u2C66\uA787\",\n\t\"th\": \"\u00FE\",\n\t\"tz\": \"\uA729\",\n\t\"u\": \"\u0289\",\n\t\"v\": \"\u028B\uA75F\u028C\",\n\t\"vy\": \"\uA761\",\n\t\"w\": \"\u2C73\",\n\t\"y\": \"\u01B4\u024F\u1EFF\",\n\t\"z\": \"\u01B6\u0225\u0240\u2C6C\uA763\",\n\t\"hv\": \"\u0195\"\n}\n\n\nfor( let latin in latin_condensed ){\n\tlet unicode = latin_condensed[latin] || '';\n\tfor( let i = 0; i < unicode.length; i++){\n\t\tlet char\t= unicode.substring(i,i+1);\n\t\tlatin_convert[char] = latin;\n\t}\n}\n\n\nconst convert_pat = new RegExp(Object.keys(latin_convert).join('|')+'|'+accent_pat,'gu');\n\n\n\n/**\n * Initialize the unicode_map from the give code point ranges\n */\nexport const initialize = (_code_points?: TCodePoints) => {\n\tif( unicode_map !== undefined ) return;\n\tunicode_map = generateMap(_code_points || folding_code_points );\n}\n\n\n/**\n * Helper method for normalize a string\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize\n */\nexport const normalize = (str: string, form: string = 'NFKD') => str.normalize(form);\n\n\n\n/**\n * Remove accents without reordering string\n * calling str.normalize('NFKD') on \\u{594}\\u{595}\\u{596} becomes \\u{596}\\u{594}\\u{595}\n * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703\n */\nexport const asciifold = (str: string): string => {\n\n\treturn Array.from(str).reduce(\n\t\t/**\n\t\t * @param {string} result\n\t\t * @param {string} char\n\t\t */\n\t\t(result, char) =>{\n\t\t\treturn result + _asciifold(char)\n\t\t},\n\t\t''\n\t);\n};\n\nexport const _asciifold = (str: string): string => {\n\tstr = normalize(str)\n\t\t.toLowerCase()\n\t\t.replace(convert_pat,(/** @type {string} */ char) => {\n\t\t\treturn latin_convert[char] || '';\n\t\t})\n\n\t//return str;\n\treturn normalize(str,'NFC')\n};\n\n/**\n * Generate a list of unicode variants from the list of code points\n */\nexport function* generator(code_points: TCodePoints): Generator<TCodePointObj> {\n\n\tfor(const [code_point_min, code_point_max] of code_points){\n\t\tfor(let i = code_point_min; i <= code_point_max; i++){\n\n\t\t\t// Skip UTF-16 surrogate code units, which are not valid\n\t\t\t// Unicode scalar values on their own.\n\t\t\tif( i >= 0xD800 && i <= 0xDFFF ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet composed\t\t= String.fromCharCode(i);\n\t\t\tlet folded\t\t\t= asciifold(composed);\n\n\n\t\t\tif( folded == composed.toLowerCase() ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// skip when folded is a string longer than 3 characters long\n\t\t\t// bc the resulting regex patterns will be long\n\t\t\t// eg:\n\t\t\t// folded \u0635\u0644\u0649 \u0627\u0644\u0644\u0647 \u0639\u0644\u064A\u0647 \u0648\u0633\u0644\u0645 length 18 code point 65018\n\t\t\t// folded \u062C\u0644 \u062C\u0644\u0627\u0644\u0647 length 8 code point 65019\n\t\t\tif( folded.length > max_char_length ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif( folded.length == 0 ){\n\t\t\t\tcontinue\n\t\t\t}\n\n\n\t\t\tyield {folded:folded,composed:composed,code_point:i};\n\t\t}\n\t}\n}\n\n\n/**\n * Generate a unicode map from the list of code points\n */\nexport const generateSets = (code_points: TCodePoints): TUnicodeSets => {\n\n\tconst unicode_sets: {[key: string]: Set<string>} = {};\n\n\tconst addMatching = (folded: string, to_add: string) => {\n\n\t\t/** @type {Set<string>} */\n\t\tconst folded_set = unicode_sets[folded] || new Set();\n\n\t\tconst patt = new RegExp( '^'+setToPattern(folded_set)+'$','iu');\n\t\tif( to_add.match(patt) ){\n\t\t\treturn;\n\t\t}\n\n\t\tfolded_set.add(escape_regex(to_add));\n\t\tunicode_sets[folded] = folded_set;\n\t}\n\n\n\tfor( let value of generator(code_points) ){\n\t\taddMatching(value.folded,value.folded);\n\t\taddMatching(value.folded,value.composed);\n\t}\n\n\treturn unicode_sets;\n}\n\n/**\n * Generate a unicode map from the list of code points\n * ae => (?:(?:ae|\u00C6|\u01FC|\u01E2)|(?:A|\u24B6|\uFF21...)(?:E|\u025B|\u24BA...))\n */\nexport const generateMap = (code_points: TCodePoints): TUnicodeMap => {\n\tconst unicode_sets = generateSets(code_points);\n\n\tconst unicode_map: TUnicodeMap = {};\n\n\tlet multi_char: string[] = [];\n\n\tfor( let folded in unicode_sets ){\n\n\t\tlet set = unicode_sets[folded];\n\t\tif( set ){\n\t\t\tunicode_map[folded] = setToPattern(set);\n\t\t}\n\n\t\tif( folded.length > 1 ){\n\t\t\tmulti_char.push(escape_regex(folded));\n\t\t}\n\t}\n\n\tmulti_char.sort((a, b) => b.length - a.length );\n\tconst multi_char_patt = arrayToPattern(multi_char);\n\tmulti_char_reg = new RegExp('^'+multi_char_patt,'u');\n\n\treturn unicode_map;\n}\n\n\n/**\n * Map each element of an array from its folded value to all possible unicode matches\n */\nexport const mapSequence = (strings: string[], min_replacement: number = 1): string =>{\n\tlet chars_replaced = 0;\n\n\tstrings = strings.map((str)=>{\n\t\tif( unicode_map[str] ){\n\t\t\tchars_replaced += str.length;\n\t\t}\n\t\treturn unicode_map[str] || str;\n\t});\n\n\tif( chars_replaced >= min_replacement ){\n\t\treturn sequencePattern(strings);\n\t}\n\n\treturn '';\n}\n\n/**\n * Convert a short string and split it into all possible patterns\n * Keep a pattern only if min_replacement is met\n *\n * 'abc'\n * \t\t=> [['abc'],['ab','c'],['a','bc'],['a','b','c']]\n *\t\t=> ['abc-pattern','ab-c-pattern'...]\n */\nexport const substringsToPattern = (str: string, min_replacement: number = 1): string => {\n\n\tmin_replacement = Math.max(min_replacement,str.length-1);\n\n\treturn arrayToPattern(\n\t\tallSubstrings(str).map( (sub_pat) =>{\n\t\t\treturn mapSequence(sub_pat,min_replacement)\n\t\t})\n\t);\n}\n\n/**\n * Convert an array of sequences into a pattern\n * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)\n */\nconst sequencesToPattern = (sequences: Sequence[], all: boolean = true) => {\n\n\tlet min_replacement = sequences.length > 1 ? 1 : 0;\n\treturn arrayToPattern(\n\t\tsequences.map( (sequence) =>{\n\t\t\tlet seq: string[] = [];\n\t\t\tconst len = all ? sequence.length() : sequence.length() - 1;\n\t\t\tfor( let j = 0; j < len; j++){\n\t\t\t\tseq.push(substringsToPattern(sequence.substrs[j]||'',min_replacement));\n\t\t\t}\n\n\t\t\treturn sequencePattern(seq);\n\t\t})\n\t);\n}\n\n/**\n * Return true if the sequence is already in the sequences\n */\nconst inSequences = (needle_seq: Sequence, sequences: Sequence[]) => {\n\n\tfor(const seq of sequences){\n\n\t\tif( seq.start != needle_seq.start || seq.end != needle_seq.end ){\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( seq.substrs.join('') !== needle_seq.substrs.join('') ){\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tlet needle_parts\t= needle_seq.parts;\n\n\t\tconst filter = (part: TSequencePart) =>{\n\n\t\t\tfor(const needle_part of needle_parts){\n\n\t\t\t\tif( needle_part.start === part.start && needle_part.substr === part.substr ){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tif( part.length == 1 || needle_part.length == 1 ){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\n\t\t\t\t// check for overlapping parts\n\t\t\t\t// a = ['::=','==']\n\t\t\t\t// b = ['::','===']\n\t\t\t\t// a = ['r','sm']\n\t\t\t\t// b = ['rs','m']\n\t\t\t\tif( part.start < needle_part.start && part.end > needle_part.start ){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tif( needle_part.start < part.start && needle_part.end > part.start ){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn false;\n\t\t};\n\n\t\tlet filtered = seq.parts.filter(filter);\n\n\t\tif( filtered.length > 0 ){\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nclass Sequence{\n\tparts: TSequencePart[];\n\tsubstrs: string[];\n\tstart: number;\n\tend: number;\n\n\tconstructor(){\n\t\tthis.parts\t\t= [];\n\t\tthis.substrs\t= [];\n\t\tthis.start\t\t= 0;\n\t\tthis.end\t\t= 0;\n\t}\n\n\tadd(part: TSequencePart|undefined){\n\t\tif( part ){\n\t\t\tthis.parts.push(part);\n\t\t\tthis.substrs.push(part.substr);\n\t\t\tthis.start\t= Math.min(part.start,this.start);\n\t\t\tthis.end\t= Math.max(part.end,this.end);\n\t\t}\n\t}\n\n\tlast(){\n\t\treturn this.parts[this.parts.length-1];\n\t}\n\n\tlength(){\n\t\treturn this.parts.length;\n\t}\n\n\tclone(position: number, last_piece: TSequencePart){\n\t\tlet clone = new Sequence();\n\n\t\tlet parts = JSON.parse(JSON.stringify(this.parts));\n\t\tlet last_part = parts.pop();\n\t\tfor( const part of parts ){\n\t\t\tclone.add(part);\n\t\t}\n\n\t\tlet last_substr = last_piece.substr.substring(0,position-last_part.start);\n\t\tlet clone_last_len = last_substr.length;\n\t\tclone.add({start:last_part.start,end:last_part.start+clone_last_len,length:clone_last_len,substr:last_substr});\n\n\t\treturn clone;\n\t}\n\n}\n\n/**\n * Expand a regular expression pattern to include unicode variants\n * \teg /a/ becomes /a\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250\u0251A\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F/\n *\n * Issue:\n *  \uFE8A\uFE8B [ '\uFE8A = \\\\u{fe8a}', '\uFE8B = \\\\u{fe8b}' ]\n *\tbecomes:\t\u064A\u0654\u064A\u0654 [ '\u064A = \\\\u{64a}', '\u0654 = \\\\u{654}', '\u064A = \\\\u{64a}', '\u0654 = \\\\u{654}' ]\n *\n *\t\u0130\u0132 = IIJ = \u2161J\n *\n * \t1/2/4\n */\nexport const getPattern = (str: string): string => {\n\tinitialize();\n\n\tstr\t\t\t\t\t= asciifold(str);\n\n\tlet pattern\t\t\t= '';\n\tlet sequences\t\t= [new Sequence()];\n\n\tfor( let i = 0; i < str.length; i++ ){\n\n\t\tlet substr\t= str.substring(i);\n\t\tlet match\t= substr.match(multi_char_reg);\n\t\tconst char\t= str.substring(i,i+1);\n\t\tconst match_str = match ? match[0] : null;\n\n\n\t\t// loop through sequences\n\t\t// add either the char or multi_match\n\t\tlet overlapping: Sequence[]\t= [];\n\t\tlet added_types\t\t\t\t\t\t\t= new Set();\n\t\tfor(const sequence of sequences){\n\n\t\t\tconst last_piece\t= sequence.last();\n\n\n\t\t\tif( !last_piece || last_piece.length == 1 || last_piece.end <= i ){\n\n\t\t\t\t// if we have a multi match\n\t\t\t\tif( match_str ){\n\t\t\t\t\tconst len = match_str.length;\n\t\t\t\t\tsequence.add({start:i,end:i+len,length:len,substr:match_str});\n\t\t\t\t\tadded_types.add('1');\n\t\t\t\t}else{\n\t\t\t\t\tsequence.add({start:i,end:i+1,length:1,substr:char});\n\t\t\t\t\tadded_types.add('2');\n\t\t\t\t}\n\n\t\t\t}else if( match_str ){\n\n\t\t\t\tlet clone = sequence.clone(i,last_piece);\n\n\t\t\t\tconst len = match_str.length;\n\t\t\t\tclone.add({start:i,end:i+len,length:len,substr:match_str});\n\n\t\t\t\toverlapping.push(clone);\n\n\t\t\t}else{\n\t\t\t\t// don't add char\n\t\t\t\t// adding would create invalid patterns: 234 => [2,34,4]\n\t\t\t\tadded_types.add('3');\n\t\t\t}\n\n\t\t}\n\n\n\t\t// if we have overlapping\n\t\tif( overlapping.length > 0 ){\n\n\t\t\t// ['ii','iii'] before ['i','i','iii']\n\t\t\toverlapping = overlapping.sort((a,b)=>{\n\t\t\t\treturn a.length() - b.length();\n\t\t\t});\n\n\t\t\tfor( let clone of overlapping){\n\n\t\t\t\t// don't add if we already have an equivalent sequence\n\t\t\t\tif( inSequences(clone, sequences) ){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tsequences.push(clone);\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\n\t\t// if we haven't done anything unique\n\t\t// clean up the patterns\n\t\t// helps keep patterns smaller\n\t\t// if str = 'r\u20A8\u33A7aarss', pattern will be 446 instead of 655\n\t\tif( i > 0 && added_types.size == 1 && !added_types.has('3') ){\n\t\t\tpattern += sequencesToPattern(sequences,false);\n\t\t\tlet new_seq = new Sequence();\n\t\t\tconst old_seq = sequences[0];\n\t\t\tif( old_seq ){\n\t\t\t\tnew_seq.add(old_seq.last());\n\t\t\t}\n\t\t\tsequences = [new_seq];\n\t\t}\n\n\t}\n\n\tpattern += sequencesToPattern(sequences,true);\n\n\treturn pattern;\n}\n\n\nexport { escape_regex };\n", "\nimport { asciifold } from '@orchidjs/unicode-variants';\nimport * as T from './types.ts';\n\n\n/**\n * A property getter resolving dot-notation\n * @param  {Object}  obj     The root object to fetch property on\n * @param  {String}  name    The optionally dotted property name to fetch\n * @return {Object}          The resolved property value\n */\nexport const getAttr = (obj:{[key:string]:any}, name:string ) => {\n    if (!obj ) return;\n    return obj[name];\n};\n\n/**\n * A property getter resolving dot-notation\n * @param  {Object}  obj     The root object to fetch property on\n * @param  {String}  name    The optionally dotted property name to fetch\n * @return {Object}          The resolved property value\n */\nexport const getAttrNesting = (obj:{[key:string]:any}, name:string ) => {\n    if (!obj ) return;\n    var part, names = name.split(\".\");\n\twhile( (part = names.shift()) && (obj = obj[part]));\n    return obj;\n};\n\n/**\n * Calculates how close of a match the\n * given value is against a search token.\n *\n */\nexport const scoreValue = (value:string, token:T.Token, weight:number ):number => {\n\tvar score, pos;\n\n\tif (!value) return 0;\n\n\tvalue = value + '';\n\tif( token.regex == null ) return 0;\n\tpos = value.search(token.regex);\n\tif (pos === -1) return 0;\n\n\tscore = token.string.length / value.length;\n\tif (pos === 0) score += 0.5;\n\n\treturn score * weight;\n};\n\n\n/**\n * Cast object property to an array if it exists and has a value\n *\n */\nexport const propToArray = (obj:{[key:string]:any}, key:string) => {\n\tvar value = obj[key];\n\n\tif( typeof value == 'function' ) return value;\n\n\tif( value && !Array.isArray(value) ){\n\t\tobj[key] = [value];\n\t}\n}\n\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n\n\n\nexport const cmp = (a:number|string, b:number|string) => {\n\tif (typeof a === 'number' && typeof b === 'number') {\n\t\treturn a > b ? 1 : (a < b ? -1 : 0);\n\t}\n\ta = asciifold(a + '').toLowerCase();\n\tb = asciifold(b + '').toLowerCase();\n\tif (a > b) return 1;\n\tif (b > a) return -1;\n\treturn 0;\n};\n", "/**\n * sifter.js\n * Copyright (c) 2013\u20132020 Brian Reavis & contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * @author Brian Reavis <brian@thirdroute.com>\n */\n\nimport { scoreValue, getAttr, getAttrNesting, propToArray, iterate, cmp } from './utils.ts';\nimport { getPattern, escape_regex } from '@orchidjs/unicode-variants';\nimport * as T from './types.ts';\n\nclass Sifter{\n\n\tpublic items: any; // []|{};\n\tpublic settings: T.Settings;\n\n\t/**\n\t * Textually searches arrays and hashes of objects\n\t * by property (or multiple properties). Designed\n\t * specifically for autocomplete.\n\t *\n\t */\n\tconstructor(items:any, settings:T.Settings) {\n\t\tthis.items = items;\n\t\tthis.settings = settings || {diacritics: true};\n\t};\n\n\t/**\n\t * Splits a search string into an array of individual\n\t * regexps to be used to match results.\n\t *\n\t */\n\ttokenize(query:string, respect_word_boundaries?:boolean, weights?:T.Weights ):T.Token[] {\n\t\tif (!query || !query.length) return [];\n\n\t\tconst tokens:T.Token[]\t= [];\n\t\tconst words\t\t\t\t= query.split(/\\s+/);\n\t\tvar field_regex:RegExp;\n\n\t\tif( weights ){\n\t\t\tfield_regex = new RegExp( '^('+ Object.keys(weights).map(escape_regex).join('|')+')\\:(.*)$');\n\t\t}\n\n\t\twords.forEach((word:string) => {\n\t\t\tlet field_match;\n\t\t\tlet field:null|string\t= null;\n\t\t\tlet regex:null|string\t= null;\n\n\t\t\t// look for \"field:query\" tokens\n\t\t\tif( field_regex && (field_match = word.match(field_regex)) ){\n\t\t\t\tfield\t= field_match[1]!;\n\t\t\t\tword\t= field_match[2]!;\n\t\t\t}\n\n\t\t\tif( word.length > 0 ){\n\t\t\t\tif( this.settings.diacritics ){\n\t\t\t\t\tregex = getPattern(word) || null;\n\t\t\t\t}else{\n\t\t\t\t\tregex = escape_regex(word);\n\t\t\t\t}\n\t\t\t\tif( regex && respect_word_boundaries ) regex = \"\\\\b\"+regex;\n\t\t\t}\n\n\t\t\ttokens.push({\n\t\t\t\tstring : word,\n\t\t\t\tregex  : regex ? new RegExp(regex,'iu') : null,\n\t\t\t\tfield  : field,\n\t\t\t});\n\t\t});\n\n\t\treturn tokens;\n\t};\n\n\n\t/**\n\t * Returns a function to be used to score individual results.\n\t *\n\t * Good matches will have a higher score than poor matches.\n\t * If an item is not a match, 0 will be returned by the function.\n\t *\n\t * @returns {T.ScoreFn}\n\t */\n\tgetScoreFunction(query:string, options:T.UserOptions ){\n\t\tvar search = this.prepareSearch(query, options);\n\t\treturn this._getScoreFunction(search);\n\t}\n\n\t/**\n\t * @returns {T.ScoreFn}\n\t *\n\t */\n\t_getScoreFunction(search:T.PrepareObj ){\n\t\tconst tokens\t\t= search.tokens,\n\t\ttoken_count\t\t\t= tokens.length;\n\n\t\tif (!token_count) {\n\t\t\treturn function() { return 0; };\n\t\t}\n\n\t\tconst fields\t= search.options.fields,\n\t\tweights\t\t\t= search.weights,\n\t\tfield_count\t\t= fields.length,\n\t\tgetAttrFn\t\t= search.getAttrFn;\n\n\t\tif (!field_count) {\n\t\t\treturn function() { return 1; };\n\t\t}\n\n\n\t\t/**\n\t\t * Calculates the score of an object\n\t\t * against the search query.\n\t\t *\n\t\t */\n\t\tconst scoreObject = (function() {\n\n\n\t\t\tif (field_count === 1) {\n\t\t\t\treturn function(token:T.Token, data:{}) {\n\t\t\t\t\tconst field = fields[0]!.field;\n\t\t\t\t\treturn scoreValue(getAttrFn(data, field), token, weights[field]||1);\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn function(token:T.Token, data:{}) {\n\t\t\t\tvar sum = 0;\n\n\t\t\t\t// is the token specific to a field?\n\t\t\t\tif( token.field ){\n\n\t\t\t\t\tconst value = getAttrFn(data, token.field);\n\n\t\t\t\t\tif( !token.regex && value ){\n\t\t\t\t\t\tsum += (1/field_count);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tsum += scoreValue(value, token, 1);\n\t\t\t\t\t}\n\n\n\n\t\t\t\t}else{\n\t\t\t\t\titerate(weights, (weight:number, field:string) => {\n\t\t\t\t\t\tsum += scoreValue(getAttrFn(data, field), token, weight);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn sum / field_count;\n\t\t\t};\n\t\t})();\n\n\t\tif (token_count === 1) {\n\t\t\treturn function(data:{}) {\n\t\t\t\treturn scoreObject(tokens[0]!, data);\n\t\t\t};\n\t\t}\n\n\t\tif (search.options.conjunction === 'and') {\n\t\t\treturn function(data:{}) {\n\t\t\t\tvar score, sum = 0;\n\t\t\t\tfor( let token of tokens){\n\t\t\t\t\tscore = scoreObject(token, data);\n\t\t\t\t\tif (score <= 0) return 0;\n\t\t\t\t\tsum += score;\n\t\t\t\t}\n\t\t\t\treturn sum / token_count;\n\t\t\t};\n\t\t} else {\n\t\t\treturn function(data:{}) {\n\t\t\t\tvar sum = 0;\n\t\t\t\titerate(tokens,(token:T.Token)=>{\n\t\t\t\t\tsum += scoreObject(token, data);\n\t\t\t\t});\n\t\t\t\treturn sum / token_count;\n\t\t\t};\n\t\t}\n\t};\n\n\t/**\n\t * Returns a function that can be used to compare two\n\t * results, for sorting purposes. If no sorting should\n\t * be performed, `null` will be returned.\n\t *\n\t * @return function(a,b)\n\t */\n\tgetSortFunction(query:string, options:T.UserOptions) {\n\t\tvar search  = this.prepareSearch(query, options);\n\t\treturn this._getSortFunction(search);\n\t}\n\n\t_getSortFunction(search:T.PrepareObj){\n\t\tvar implicit_score,\n\t\tsort_flds:T.Sort[]\t= [];\n\n\t\tconst self\t= this,\n\t\toptions\t\t= search.options,\n\t\tsort\t\t= (!search.query && options.sort_empty) ? options.sort_empty : options.sort;\n\n\n\t\tif( typeof sort == 'function' ){\n\t\t\treturn sort.bind(this);\n\t\t}\n\n\t\t/**\n\t\t * Fetches the specified sort field value\n\t\t * from a search result item.\n\t\t *\n\t\t */\n\t\tconst get_field = function(name:string, result:T.ResultItem):string|number {\n\t\t\tif (name === '$score') return result.score;\n\t\t\treturn search.getAttrFn(self.items[result.id], name);\n\t\t};\n\n\t\t// parse options\n\t\tif (sort) {\n\t\t\tfor( let s of sort ){\n\t\t\t\tif (search.query || s.field !== '$score') {\n\t\t\t\t\tsort_flds.push(s);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// the \"$score\" field is implied to be the primary\n\t\t// sort field, unless it's manually specified\n\t\tif (search.query) {\n\t\t\timplicit_score = true;\n\t\t\tfor( let fld of sort_flds ){\n\t\t\t\tif( fld.field === '$score' ){\n\t\t\t\t\timplicit_score = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (implicit_score) {\n\t\t\t\tsort_flds.unshift({field: '$score', direction: 'desc'});\n\t\t\t}\n\n\t\t// without a search.query, all items will have the same score\n\t\t} else {\n\t\t\tsort_flds = sort_flds.filter((fld) => fld.field !== '$score' );\n\t\t}\n\n\n\t\t// build function\n\t\tconst sort_flds_count = sort_flds.length;\n\t\tif (!sort_flds_count) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn function(a:T.ResultItem, b:T.ResultItem) {\n\t\t\tvar result, field;\n\t\t\tfor( let sort_fld of sort_flds ){\n\t\t\t\tfield = sort_fld.field;\n\n\t\t\t\tlet\tmultiplier = sort_fld.direction === 'desc' ? -1 : 1;\n\n\t\t\t\tresult = multiplier * cmp(\n\t\t\t\t\tget_field(field, a),\n\t\t\t\t\tget_field(field, b)\n\t\t\t\t);\n\t\t\t\tif (result) return result;\n\t\t\t}\n\t\t\treturn 0;\n\t\t};\n\n\t};\n\n\t/**\n\t * Parses a search query and returns an object\n\t * with tokens and fields ready to be populated\n\t * with results.\n\t *\n\t */\n\tprepareSearch(query:string, optsUser:T.UserOptions):T.PrepareObj {\n\t\tconst weights:T.Weights = {};\n\t\tvar options\t\t= Object.assign({},optsUser) as T.Options;\n\n\t\tpropToArray(options,'sort');\n\t\tpropToArray(options,'sort_empty');\n\n\t\t// convert fields to new format\n\t\tif( options.fields ){\n\t\t\tpropToArray(options,'fields');\n\t\t\tconst fields:T.Field[] = [];\n\t\t\toptions.fields.forEach((field:string|T.Field) => {\n\t\t\t\tif( typeof field == 'string' ){\n\t\t\t\t\tfield = {field:field,weight:1};\n\t\t\t\t}\n\t\t\t\tfields.push(field);\n\t\t\t\tweights[field.field] = ('weight' in field) ? field.weight : 1;\n\t\t\t});\n\t\t\toptions.fields = fields;\n\t\t}\n\n\n\t\treturn {\n\t\t\toptions\t\t: options as T.Options,\n\t\t\tquery\t\t: query.toLowerCase().trim(),\n\t\t\ttokens\t\t: this.tokenize(query, options.respect_word_boundaries, weights),\n\t\t\ttotal\t\t: 0,\n\t\t\titems\t\t: [],\n\t\t\tweights\t\t: weights,\n\t\t\tgetAttrFn\t: (options.nesting) ? getAttrNesting : getAttr,\n\t\t};\n\t};\n\n\t/**\n\t * Searches through all items and returns a sorted array of matches.\n\t *\n\t */\n\tsearch(query:string, options:T.UserOptions) : T.PrepareObj {\n\t\tvar self = this, score, search: T.PrepareObj;\n\n\t\tsearch  = this.prepareSearch(query, options);\n\t\toptions = search.options;\n\t\tquery   = search.query;\n\n\t\t// generate result scoring function\n\t\tconst fn_score:T.ScoreFn = options.score || self._getScoreFunction(search);\n\n\t\t// perform search and sort\n\t\tif (query.length) {\n\t\t\titerate(self.items, (item:T.ResultItem, id:string|number) => {\n\t\t\t\tscore = fn_score(item);\n\t\t\t\tif (options.filter === false || score > 0) {\n\t\t\t\t\tsearch.items.push({'score': score, 'id': id});\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\titerate(self.items, (_:T.ResultItem, id:string|number) => {\n\t\t\t\tsearch.items.push({'score': 1, 'id': id});\n\t\t\t});\n\t\t}\n\n\t\tconst fn_sort = self._getSortFunction(search);\n\t\tif (fn_sort) search.items.sort(fn_sort);\n\n\t\t// apply limits\n\t\tsearch.total = search.items.length;\n\t\tif (typeof options.limit === 'number') {\n\t\t\tsearch.items = search.items.slice(0, options.limit);\n\t\t}\n\n\t\treturn search;\n\t};\n}\n\nexport { Sifter, scoreValue, getAttr, getAttrNesting, propToArray, iterate, cmp, getPattern }\nexport * from './types.ts';\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * highlight v3 | MIT license | Johann Burkard <jb@eaio.com>\n * Highlights arbitrary terms in a node.\n *\n * - Modified by Marshal <beatgates@gmail.com> 2011-6-24 (added regex)\n * - Modified by Brian Reavis <brian@thirdroute.com> 2012-8-27 (cleanup)\n */\n\nimport {replaceNode} from '../vanilla.ts';\n\n\nexport const highlight = (element:HTMLElement, regex:string|RegExp) => {\n\n\tif( regex === null ) return;\n\n\t// convet string to regex\n\tif( typeof regex === 'string' ){\n\n\t\tif( !regex.length ) return;\n\t\tregex = new RegExp(regex, 'i');\n\t}\n\n\n\t// Wrap matching part of text node with highlighting <span>, e.g.\n\t// Soccer  ->  <span class=\"highlight\">Soc</span>cer  for regex = /soc/i\n\tconst highlightText = ( node:Text ):number => {\n\n\t\tvar match = node.data.match(regex);\n\t\tif( match && node.data.length > 0 ){\n\t\t\tvar spannode\t\t= document.createElement('span');\n\t\t\tspannode.className\t= 'highlight';\n\t\t\tvar middlebit\t\t= node.splitText(match.index as number);\n\n\t\t\tmiddlebit.splitText(match[0]!.length);\n\t\t\tvar middleclone\t\t= middlebit.cloneNode(true);\n\n\t\t\tspannode.appendChild(middleclone);\n\t\t\treplaceNode(middlebit, spannode);\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 0;\n\t};\n\n\t// Recurse element node, looking for child text nodes to highlight, unless element\n\t// is childless, <script>, <style>, or already highlighted: <span class=\"hightlight\">\n\tconst highlightChildren = ( node:Element ):void => {\n\t\tif( node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName) && ( node.className !== 'highlight' || node.tagName !== 'SPAN' ) ){\n\t\t\tArray.from(node.childNodes).forEach(element => {\n\t\t\t\thighlightRecursive(element);\n\t\t\t});\n\t\t}\n\t};\n\n\n\tconst highlightRecursive = ( node:Node|Element ):number => {\n\n\t\tif( node.nodeType === 3 ){\n\t\t\treturn highlightText(node as Text);\n\t\t}\n\n\t\thighlightChildren(node as Element);\n\n\t\treturn 0;\n\t};\n\n\thighlightRecursive( element );\n};\n\n/**\n * removeHighlight fn copied from highlight v5 and\n * edited to remove with(), pass js strict mode, and use without jquery\n */\nexport const removeHighlight = (el:HTMLElement) => {\n\tvar elements = el.querySelectorAll(\"span.highlight\");\n\tArray.prototype.forEach.call(elements, function(el:HTMLElement){\n\t\tvar parent = el.parentNode as Node;\n\t\tparent.replaceChild(el.firstChild as Node, el);\n\t\tparent.normalize();\n\t});\n};\n", "export const KEY_A\t\t\t\t= 65;\nexport const KEY_RETURN\t\t\t= 13;\nexport const KEY_ESC\t\t\t= 27;\nexport const KEY_LEFT\t\t\t= 37;\nexport const KEY_UP\t\t\t\t= 38;\nexport const KEY_RIGHT\t\t\t= 39;\nexport const KEY_DOWN\t\t\t= 40;\nexport const KEY_BACKSPACE\t\t= 8;\nexport const KEY_DELETE\t\t\t= 46;\nexport const KEY_TAB\t\t\t= 9;\n\nexport const IS_MAC      \t\t= typeof navigator === 'undefined' ? false : /Mac/.test(navigator.userAgent);\nexport const KEY_SHORTCUT\t\t= IS_MAC ? 'metaKey' : 'ctrlKey'; // ctrl key or apple key for ma\n", "\nexport default {\n\toptions: [],\n\toptgroups: [],\n\n\tplugins: [],\n\tdelimiter: ',',\n\tsplitOn: null, // regexp or string for splitting up values from a paste command\n\tpersist: true,\n\tdiacritics: true,\n\tcreate: null,\n\tcreateOnBlur: false,\n\tcreateFilter: null,\n\tclearAfterSelect: false,\n\thighlight: true,\n\topenOnFocus: true,\n\tshouldOpen: null,\n\tmaxOptions: 50,\n\tmaxItems: null,\n\thideSelected: null,\n\tduplicates: false,\n\taddPrecedence: false,\n\tselectOnTab: false,\n\tpreload: null,\n\tallowEmptyOption: false,\n\t//closeAfterSelect: false,\n\trefreshThrottle: 300,\n\n\n\tloadThrottle: 300,\n\tloadingClass: 'loading',\n\n\tdataAttr: null, //'data-data',\n\toptgroupField: 'optgroup',\n\tvalueField: 'value',\n\tlabelField: 'text',\n\tdisabledField: 'disabled',\n\toptgroupLabelField: 'label',\n\toptgroupValueField: 'value',\n\tlockOptgroupOrder: false,\n\n\tsortField: '$order',\n\tsearchField: ['text'],\n\tsearchConjunction: 'and',\n\n\tmode: null,\n\twrapperClass: 'ts-wrapper',\n\tcontrolClass: 'ts-control',\n\tdropdownClass: 'ts-dropdown',\n\tdropdownContentClass: 'ts-dropdown-content',\n\titemClass: 'item',\n\toptionClass: 'option',\n\n\tdropdownParent: null,\n\tcontrolInput: '<input type=\"text\" autocomplete=\"off\" size=\"1\" />',\n\n\tcopyClassesToDropdown: false,\n\n\tplaceholder: null,\n\thidePlaceholder: null,\n\n\tshouldLoad: function(query:string):boolean{\n\t\treturn query.length > 0;\n\t},\n\n\t/*\n\tload                 : null, // function(query, callback) { ... }\n\tscore                : null, // function(search) { ... }\n\tonInitialize         : null, // function() { ... }\n\tonChange             : null, // function(value) { ... }\n\tonItemAdd            : null, // function(value, $item) { ... }\n\tonItemRemove         : null, // function(value) { ... }\n\tonClear              : null, // function() { ... }\n\tonOptionAdd          : null, // function(value, data) { ... }\n\tonOptionRemove       : null, // function(value) { ... }\n\tonOptionClear        : null, // function() { ... }\n\tonOptionGroupAdd     : null, // function(id, data) { ... }\n\tonOptionGroupRemove  : null, // function(id) { ... }\n\tonOptionGroupClear   : null, // function() { ... }\n\tonDropdownOpen       : null, // function(dropdown) { ... }\n\tonDropdownClose      : null, // function(dropdown) { ... }\n\tonType               : null, // function(str) { ... }\n\tonDelete             : null, // function(values) { ... }\n\t*/\n\n\trender: {\n\t\t/*\n\t\titem: null,\n\t\toptgroup: null,\n\t\toptgroup_header: null,\n\t\toption: null,\n\t\toption_create: null\n\t\t*/\n\t}\n};\n", "import defaults from './defaults.ts';\nimport { hash_key, iterate } from './utils.ts';\nimport { TomOption, TomSettings, RecursivePartial } from './types/index.ts';\nimport { TomInput } from './types/index.ts';\n\n\nexport default function getSettings( input:TomInput, settings_user:RecursivePartial<TomSettings>):TomSettings{\n\tvar settings:TomSettings\t= Object.assign({}, defaults, settings_user);\n\n\tvar attr_data\t\t\t\t= settings.dataAttr;\n\tvar field_label\t\t\t\t= settings.labelField;\n\tvar field_value\t\t\t\t= settings.valueField;\n\tvar field_disabled\t\t\t= settings.disabledField;\n\tvar field_optgroup\t\t\t= settings.optgroupField;\n\tvar field_optgroup_label\t= settings.optgroupLabelField;\n\tvar field_optgroup_value\t= settings.optgroupValueField;\n\n\tvar tag_name\t\t\t\t= input.tagName.toLowerCase();\n\tvar placeholder\t\t\t\t= input.getAttribute('placeholder') || input.getAttribute('data-placeholder');\n\n\tif (!placeholder && !settings.allowEmptyOption) {\n\t\tlet option\t\t= input.querySelector('option[value=\"\"]');\n\t\tif( option ){\n\t\t\tplaceholder = option.textContent;\n\t\t}\n\n\t}\n\n\tvar settings_element:{\n\t\tplaceholder\t: null|string,\n\t\toptions\t\t: TomOption[],\n\t\toptgroups\t: TomOption[],\n\t\titems\t\t: string[],\n\t\tmaxItems\t: null|number,\n\t} = {\n\t\tplaceholder\t: placeholder,\n\t\toptions\t\t: [],\n\t\toptgroups\t: [],\n\t\titems\t\t: [],\n\t\tmaxItems\t: null,\n\t};\n\n\n\t/**\n\t * Initialize from a <select> element.\n\t *\n\t */\n\tvar init_select = () => {\n\t\tvar tagName;\n\t\tvar options = settings_element.options;\n\t\tvar optionsMap:{[key:string]:any} = {};\n\t\tvar group_count = 1;\n\t\tlet $order = 0;\n\n\t\tvar readData = (el:HTMLElement):TomOption => {\n\n\t\t\tvar data\t= Object.assign({},el.dataset); // get plain object from DOMStringMap\n\t\t\tvar json\t= attr_data && data[attr_data];\n\n\t\t\tif( typeof json === 'string' && json.length ){\n\t\t\t\tdata = Object.assign(data,JSON.parse(json));\n\t\t\t}\n\n\t\t\treturn data;\n\t\t};\n\n\t\tvar addOption = (option:HTMLOptionElement, group?:string) => {\n\n\t\t\tvar value = hash_key(option.value);\n\t\t\tif ( value == null ) return;\n\t\t\tif ( !value && !settings.allowEmptyOption) return;\n\n\t\t\t// if the option already exists, it's probably been\n\t\t\t// duplicated in another optgroup. in this case, push\n\t\t\t// the current group to the \"optgroup\" property on the\n\t\t\t// existing option so that it's rendered in both places.\n\t\t\tif (optionsMap.hasOwnProperty(value)) {\n\t\t\t\tif (group) {\n\t\t\t\t\tvar arr = optionsMap[value][field_optgroup];\n\t\t\t\t\tif (!arr) {\n\t\t\t\t\t\toptionsMap[value][field_optgroup] = group;\n\t\t\t\t\t} else if (!Array.isArray(arr)) {\n\t\t\t\t\t\toptionsMap[value][field_optgroup] = [arr, group];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tarr.push(group);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}else{\n\n\t\t\t\tvar option_data             = readData(option);\n\t\t\t\toption_data[field_label]    = option_data[field_label] || option.textContent;\n\t\t\t\toption_data[field_value]    = option_data[field_value] || value;\n\t\t\t\toption_data[field_disabled] = option_data[field_disabled] || option.disabled;\n\t\t\t\toption_data[field_optgroup] = option_data[field_optgroup] || group;\n\t\t\t\toption_data.$option\t\t\t= option;\n\t\t\t\toption_data.$order\t\t\t= option_data.$order || ++$order;\n\n\t\t\t\toptionsMap[value] = option_data;\n\t\t\t\toptions.push(option_data);\n\t\t\t}\n\n\t\t\tif( option.selected ){\n\t\t\t\tsettings_element.items.push(value);\n\t\t\t}\n\t\t};\n\n\t\tvar addGroup = ( optgroup:HTMLOptGroupElement ) => {\n\t\t\tvar id:string, optgroup_data\n\n\t\t\toptgroup_data\t\t\t\t\t\t\t= readData(optgroup);\n\t\t\toptgroup_data[field_optgroup_label]\t\t= optgroup_data[field_optgroup_label] || optgroup.getAttribute('label') || '';\n\t\t\toptgroup_data[field_optgroup_value]\t\t= optgroup_data[field_optgroup_value] || group_count++;\n\t\t\toptgroup_data[field_disabled]\t\t\t= optgroup_data[field_disabled] || optgroup.disabled;\n\t\t\toptgroup_data.$order\t\t\t\t\t= optgroup_data.$order || ++$order;\n\n\t\t\tsettings_element.optgroups.push(optgroup_data);\n\n\t\t\tid = optgroup_data[field_optgroup_value];\n\n\t\t\titerate(optgroup.children, (option)=>{\n\t\t\t\taddOption(option as HTMLOptionElement, id);\n\t\t\t});\n\n\t\t};\n\n\t\tsettings_element.maxItems = input.hasAttribute('multiple') ? null : 1;\n\n\t\titerate(input.children,(child)=>{\n\t\t\ttagName = child.tagName.toLowerCase();\n\t\t\tif (tagName === 'optgroup') {\n\t\t\t\taddGroup(child as HTMLOptGroupElement);\n\t\t\t} else if (tagName === 'option') {\n\t\t\t\taddOption(child as HTMLOptionElement);\n\t\t\t}\n\t\t});\n\n\t};\n\n\n\t/**\n\t * Initialize from a <input type=\"text\"> element.\n\t *\n\t */\n\tvar init_textbox = () => {\n\t\tconst data_raw = input.getAttribute(attr_data);\n\n\t\tif (!data_raw) {\n\t\t\tvar value = input?.value?.trim() ?? '';\n\t\t\tif (!settings.allowEmptyOption && !value.length) return;\n\t\t\tconst values = value.split(settings.delimiter);\n\n\t\t\titerate( values, (value) => {\n\t\t\t\tconst option:TomOption = {};\n\t\t\t\toption[field_label] = value;\n\t\t\t\toption[field_value] = value;\n\t\t\t\tsettings_element.options.push(option);\n\t\t\t});\n\t\t\tsettings_element.items = values;\n\t\t} else {\n\t\t\tsettings_element.options = JSON.parse(data_raw);\n\t\t\titerate( settings_element.options, (opt) => {\n\t\t\t\tsettings_element.items.push(opt[field_value]);\n\t\t\t});\n\t\t}\n\t};\n\n\n\tif (tag_name === 'select') {\n\t\tinit_select();\n\t} else {\n\t\tinit_textbox();\n\t}\n\n\treturn Object.assign( {}, defaults, settings_element, settings_user) as TomSettings;\n};\n", "\nimport MicroEvent from './contrib/microevent.ts';\nimport MicroPlugin from './contrib/microplugin.ts';\nimport { Sifter } from '@orchidjs/sifter';\nimport { escape_regex } from '@orchidjs/unicode-variants';\nimport { TomInput, TomArgObject, TomOption, TomOptions, TomCreateFilter, TomCreateCallback, TomItem, TomSettings, TomTemplateNames, TomClearFilter, RecursivePartial } from './types/index.ts';\nimport {highlight, removeHighlight} from './contrib/highlight.ts';\nimport * as constants from './constants.ts';\nimport getSettings from './getSettings.ts';\nimport {\n\thash_key,\n\tget_hash,\n\tescape_html,\n\tdebounce_events,\n\tgetSelection,\n\tpreventDefault,\n\taddEvent,\n\tloadDebounce,\n\ttimeout,\n\tisKeyDown,\n\tgetId,\n\taddSlashes,\n\tappend,\n\titerate\n} from './utils.ts';\n\nimport {\n\tgetDom,\n\tisHtmlString,\n\tescapeQuery,\n\ttriggerEvent,\n\tapplyCSS,\n\taddClasses,\n\tremoveClasses,\n\tparentMatch,\n\tgetTail,\n\tisEmptyObject,\n\tnodeIndex,\n\tsetAttr,\n\treplaceNode\n} from './vanilla.ts';\n\nvar instance_i = 0;\n\nexport default class TomSelect extends MicroPlugin(MicroEvent){\n\n\tpublic control_input\t\t\t: HTMLInputElement;\n\tpublic wrapper\t\t\t\t\t: HTMLElement;\n\tpublic dropdown\t\t\t\t\t: HTMLElement;\n\tpublic control\t\t\t\t\t: HTMLElement;\n\tpublic dropdown_content\t\t\t: HTMLElement;\n\tpublic focus_node\t\t\t\t: HTMLElement;\n\n\tpublic order\t\t\t\t\t: number = 0;\n\tpublic settings\t\t\t\t\t: TomSettings;\n\tpublic input\t\t\t\t\t: TomInput;\n\tpublic tabIndex\t\t\t\t\t: number;\n\tpublic is_select_tag\t\t\t: boolean;\n\tpublic rtl\t\t\t\t\t\t: boolean;\n\tprivate inputId\t\t\t\t\t: string;\n\n\tprivate _destroy\t\t\t\t!: () => void;\n\tpublic sifter\t\t\t\t\t: Sifter;\n\n\n\tpublic isOpen\t\t\t\t\t: boolean = false;\n\tpublic isDisabled\t\t\t\t: boolean = false;\n\tpublic isReadOnly\t\t\t\t: boolean = false;\n\tpublic isRequired\t\t\t\t: boolean;\n\tpublic isInvalid\t\t\t\t: boolean = false; // @deprecated 1.8\n\tpublic isValid\t\t\t\t\t: boolean = true;\n\tpublic isLocked\t\t\t\t\t: boolean = false;\n\tpublic isFocused\t\t\t\t: boolean = false;\n\tpublic isInputHidden\t\t\t: boolean = false;\n\tpublic isSetup\t\t\t\t\t: boolean = false;\n\tpublic isDropdownContentStale\t: boolean = true;\n\tpublic ignoreFocus\t\t\t\t: boolean = false;\n\tpublic ignoreHover\t\t\t\t: boolean = false;\n\tpublic hasOptions\t\t\t\t: boolean = false;\n\tpublic currentResults\t\t\t?: ReturnType<Sifter['search']>;\n\tpublic lastValue\t\t\t\t: string = '';\n\tpublic caretPos\t\t\t\t\t: number = 0;\n\tpublic loading\t\t\t\t\t: number = 0;\n\tpublic loadedSearches\t\t\t: { [key: string]: boolean } = {};\n\n\tpublic activeOption\t\t\t\t: null|HTMLElement = null;\n\tpublic activeItems\t\t\t\t: TomItem[] = [];\n\n\tpublic optgroups\t\t\t\t: TomOptions = {};\n\tpublic options\t\t\t\t\t: TomOptions = {};\n\tpublic userOptions\t\t\t\t: {[key:string]:boolean} = {};\n\tpublic items\t\t\t\t\t: string[] = [];\n\n\tprivate refreshTimeout\t\t\t: null|number = null;\n\n\n\tconstructor( input_arg: string|TomInput, user_settings:RecursivePartial<TomSettings> ){\n\t\tsuper();\n\n\t\tinstance_i++;\n\n\t\tvar dir;\n\t\tvar input\t\t\t\t= getDom( input_arg ) as TomInput;\n\n\t\tif( input.tomselect ){\n\t\t\tthrow new Error('Tom Select already initialized on this element');\n\t\t}\n\n\t\tinput.tomselect\t\t\t= this;\n\n\t\t// detect rtl environment\n\t\tvar computedStyle\t\t= window.getComputedStyle && window.getComputedStyle(input, null);\n\t\tdir\t\t\t\t\t\t= computedStyle.getPropertyValue('direction');\n\n\t\t// setup default state\n\t\tconst settings\t\t\t= getSettings( input, user_settings );\n\t\tthis.settings\t\t\t= settings;\n\t\tthis.input\t\t\t\t= input;\n\t\tthis.tabIndex\t\t\t= input.tabIndex || 0;\n\t\tthis.is_select_tag\t\t= input.tagName.toLowerCase() === 'select';\n\t\tthis.rtl\t\t\t\t= /rtl/i.test(dir);\n\t\tthis.inputId\t\t\t= getId(input, 'tomselect-'+instance_i);\n\t\tthis.isRequired\t\t\t= input.required;\n\n\n\t\t// search system\n\t\tthis.sifter = new Sifter(this.options, {diacritics: settings.diacritics});\n\n\t\t// option-dependent defaults\n\t\tsettings.mode = settings.mode || (settings.maxItems === 1 ? 'single' : 'multi');\n\t\tif (typeof settings.hideSelected !== 'boolean') {\n\t\t\tsettings.hideSelected = settings.mode === 'multi';\n\t\t}\n\n\t\tif( typeof settings.hidePlaceholder !== 'boolean' ){\n\t\t\tsettings.hidePlaceholder = settings.mode !== 'multi';\n\t\t}\n\n\t\t// set up createFilter callback\n\t\tvar filter = settings.createFilter;\n\t\tif( typeof filter !== 'function' ){\n\n\t\t\tif( typeof filter === 'string' ){\n\t\t\t\tfilter = new RegExp(filter);\n\t\t\t}\n\n\t\t\tif( filter instanceof RegExp ){\n\t\t\t\tsettings.createFilter = (input: string) => (filter as RegExp).test(input);\n\t\t\t}else{\n\t\t\t\tsettings.createFilter = (value: string) => {\n\t\t\t\t\treturn this.settings.duplicates || !this.options[value];\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\n\t\tthis.initializePlugins(settings.plugins);\n\t\tthis.setupCallbacks();\n\t\tthis.setupTemplates();\n\n\n\t\t// Create all elements\n\t\tconst wrapper\t\t\t= getDom('<div>');\n\t\tconst control\t\t\t= getDom('<div>');\n\t\tconst dropdown\t\t\t= this._render('dropdown');\n\t\tconst dropdown_content\t= getDom(`<div role=\"listbox\" tabindex=\"-1\">`);\n\n\t\tconst classes\t\t\t= this.input.getAttribute('class') || '';\n\t\tconst inputMode\t\t\t= settings.mode;\n\n\t\tvar control_input: HTMLInputElement;\n\n\n\t\taddClasses( wrapper, settings.wrapperClass, classes, inputMode);\n\n\n\t\taddClasses(control,settings.controlClass);\n\t\tappend( wrapper, control );\n\n\n\t\taddClasses(dropdown, settings.dropdownClass, inputMode);\n\t\tif( settings.copyClassesToDropdown ){\n\t\t\taddClasses( dropdown, classes);\n\t\t}\n\n\n\t\taddClasses(dropdown_content, settings.dropdownContentClass);\n\t\tappend( dropdown, dropdown_content );\n\n\t\tgetDom( settings.dropdownParent || wrapper ).appendChild( dropdown );\n\n\n\t\t// default controlInput\n\t\tif( isHtmlString(settings.controlInput) ){\n\t\t\tcontrol_input\t\t= getDom(settings.controlInput ) as HTMLInputElement;\n\n\t\t\t// set attributes\n\t\t\tvar attrs = ['autocorrect','autocapitalize','autocomplete','spellcheck','aria-label'];\n\t\t\titerate(attrs,(attr:string) => {\n\t\t\t\tif( input.getAttribute(attr) ){\n\t\t\t\t\tsetAttr(control_input,{[attr]:input.getAttribute(attr)});\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tcontrol_input.tabIndex = -1;\n\t\t\tcontrol.appendChild( control_input );\n\t\t\tthis.focus_node\t\t= control_input;\n\n\t\t// dom element\n\t\t}else if( settings.controlInput ){\n\t\t\tcontrol_input\t\t= getDom( settings.controlInput ) as HTMLInputElement;\n\t\t\tthis.focus_node\t\t= control_input;\n\n\t\t}else{\n\t\t\tcontrol_input\t\t= getDom('<input/>') as HTMLInputElement;\n\t\t\tthis.focus_node\t\t= control;\n\t\t}\n\n\t\tthis.wrapper\t\t\t= wrapper;\n\t\tthis.dropdown\t\t\t= dropdown;\n\t\tthis.dropdown_content\t= dropdown_content;\n\t\tthis.control \t\t\t= control;\n\t\tthis.control_input\t\t= control_input;\n\n\t\tthis.setup();\n\t}\n\n\t/**\n\t * set up event bindings.\n\t *\n\t */\n\tsetup(){\n\n\t\tconst self = this;\n\t\tconst settings\t\t\t\t= self.settings;\n\t\tconst control_input\t\t\t= self.control_input;\n\t\tconst dropdown\t\t\t\t= self.dropdown;\n\t\tconst dropdown_content\t\t= self.dropdown_content;\n\t\tconst wrapper\t\t\t\t= self.wrapper;\n\t\tconst control\t\t\t\t= self.control;\n\t\tconst input\t\t\t\t\t= self.input;\n\t\tconst focus_node\t\t\t= self.focus_node;\n\t\tconst passive_event\t\t\t= { passive: true };\n\t\tconst listboxId\t\t\t\t= self.inputId +'-ts-dropdown';\n\n\n\t\tsetAttr(dropdown_content,{\n\t\t\tid: listboxId\n\t\t});\n\n\t\tsetAttr(focus_node,{\n\t\t\trole:'combobox',\n\t\t\t'aria-haspopup':'listbox',\n\t\t\t'aria-expanded':'false',\n\t\t\t'aria-controls':listboxId\n\t\t});\n\n\t\tconst control_id\t= getId(focus_node,self.inputId + '-ts-control');\n\t\tconst query\t\t\t= \"label[for='\"+escapeQuery(self.inputId)+\"']\";\n\t\tconst label\t\t\t= document.querySelector(query);\n\t\tconst label_click\t= self.focus.bind(self);\n\t\tif( label ){\n\t\t\taddEvent(label,'click', label_click );\n\t\t\tsetAttr(label,{for:control_id});\n\t\t\tconst label_id = getId(label,self.inputId+'-ts-label');\n\t\t\tsetAttr(focus_node,{'aria-labelledby':label_id});\n\t\t\tsetAttr(dropdown_content,{'aria-labelledby':label_id});\n\t\t}\n\n\t\twrapper.style.width = input.style.width;\n        wrapper.style.minWidth = input.style.minWidth;\n        wrapper.style.maxWidth = input.style.maxWidth;\n\n\t\tif (self.plugins.names.length) {\n\t\t\tconst classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');\n\t\t\taddClasses( [wrapper,dropdown], classes_plugins);\n\t\t}\n\n\t\tif ((settings.maxItems === null || settings.maxItems > 1) && self.is_select_tag ){\n\t\t\tsetAttr(input,{multiple:'multiple'});\n\t\t}\n\n\t\tif (settings.placeholder) {\n\t\t\tsetAttr(control_input,{placeholder:settings.placeholder});\n\t\t}\n\n\t\t// if splitOn was not passed in, construct it from the delimiter to allow pasting universally\n\t\tif (!settings.splitOn && settings.delimiter) {\n\t\t\tsettings.splitOn = new RegExp('\\\\s*' + escape_regex(settings.delimiter) + '+\\\\s*');\n\t\t}\n\n\t\t// debounce user defined load() if loadThrottle > 0\n\t\t// after initializePlugins() so plugins can create/modify user defined loaders\n\t\tif( settings.load && settings.loadThrottle ){\n\t\t\tsettings.load = loadDebounce(settings.load,settings.loadThrottle)\n\t\t}\n\n\t\taddEvent(dropdown,'mousemove', () => {\n\t\t\tself.ignoreHover = false;\n\t\t});\n\n\t\taddEvent(dropdown,'mouseenter', (e) => {\n\n\t\t\tvar target_match = parentMatch(e.target as HTMLElement, '[data-selectable]', dropdown);\n\t\t\tif( target_match ) self.onOptionHover( e as MouseEvent, target_match );\n\n\t\t}, {capture:true});\n\n\t\t// clicking on an option should select it\n\t\taddEvent(dropdown,'click',(evt) => {\n\t\t\tconst option = parentMatch(evt.target as HTMLElement, '[data-selectable]');\n\t\t\tif( option ){\n\t\t\t\tself.onOptionSelect( evt as MouseEvent, option );\n\t\t\t\tpreventDefault(evt,true);\n\t\t\t}\n\t\t});\n\n\t\taddEvent(control,'click', (evt) => {\n\n\t\t\tvar target_match = parentMatch( evt.target as HTMLElement, '[data-ts-item]', control);\n\t\t\tif( target_match && self.onItemSelect(evt as MouseEvent, target_match as TomItem) ){\n\t\t\t\tpreventDefault(evt,true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// retain focus (see control_input mousedown)\n\t\t\tif( control_input.value != '' ){\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tself.onClick();\n\t\t\tpreventDefault(evt,true);\n\t\t});\n\n\n\t\t// keydown on focus_node for arrow_down/arrow_up\n\t\taddEvent(focus_node,'keydown',\t\t(e) => self.onKeyDown(e as KeyboardEvent) );\n\n\t\t// keypress and input/keyup\n\t\taddEvent(control_input,'keypress',\t(e) => self.onKeyPress(e as KeyboardEvent) );\n\t\taddEvent(control_input,'input',\t\t(e) => self.onInput(e as KeyboardEvent) );\n\t\taddEvent(focus_node,'blur', \t\t(e) => self.onBlur(e as FocusEvent) );\n\t\taddEvent(focus_node,'focus',\t\t(e) => self.onFocus(e as MouseEvent) );\n\t\taddEvent(control_input,'paste',\t\t(e) => self.onPaste(e as MouseEvent) );\n\n\n\t\tconst doc_mousedown = (evt:Event) => {\n\n\t\t\t// blur if target is outside of this instance\n\t\t\t// dropdown is not always inside wrapper\n\t\t\tconst target = evt.composedPath()[0];\n\t\t\tif( !wrapper.contains(target as HTMLElement) && !dropdown.contains(target as HTMLElement) ){\n\t\t\t\tif (self.isFocused) {\n\t\t\t\t\tself.blur();\n\t\t\t\t}\n\t\t\t\tself.inputState();\n\t\t\t\treturn;\n\t\t\t}\n\n\n\t\t\t// retain focus by preventing native handling. if the\n\t\t\t// event target is the input it should not be modified.\n\t\t\t// otherwise, text selection within the input won't work.\n\t\t\t// Fixes bug #212 which is no covered by tests\n\t\t\tif( target == control_input && self.isOpen ){\n\t\t\t\tevt.stopPropagation();\n\n\t\t\t// clicking anywhere in the control should not blur the control_input (which would close the dropdown)\n\t\t\t}else{\n\t\t\t\tpreventDefault(evt,true);\n\t\t\t}\n\n\t\t};\n\n\t\tconst win_scroll = () => {\n\t\t\tif (self.isOpen) {\n\t\t\t\tself.positionDropdown();\n\t\t\t}\n\t\t};\n\n\t\tconst input_invalid = () => {\n\t\t\tif( self.isValid ){\n\t\t\t\tself.isValid = false;\n\t\t\t\tself.isInvalid = true;\n\t\t\t\tself.refreshState();\n\t\t\t}\n\t\t}\n\n\t\taddEvent(input,'invalid', input_invalid);\n\t\taddEvent(document,'mousedown', doc_mousedown);\n\t\taddEvent(window,'scroll', win_scroll, passive_event);\n\t\taddEvent(window,'resize', win_scroll, passive_event);\n\n\t\tthis._destroy = () => {\n\t\t\tinput.removeEventListener('invalid',input_invalid);\n\t\t\tdocument.removeEventListener('mousedown',doc_mousedown);\n\t\t\twindow.removeEventListener('scroll',win_scroll);\n\t\t\twindow.removeEventListener('resize',win_scroll);\n\t\t\tif( label ) label.removeEventListener('click',label_click);\n\t\t};\n\n\t\t// store original html and tab index so that they can be\n\t\t// restored when the destroy() method is called.\n\t\tthis.revertSettings = {\n\t\t\tinnerHTML : input.innerHTML,\n\t\t\ttabIndex : input.tabIndex\n\t\t};\n\n\n\t\tinput.tabIndex = -1;\n\t\tinput.insertAdjacentElement('afterend', self.wrapper);\n\n\t\tself.sync(false);\n\t\tsettings.items = [];\n\t\tdelete settings.optgroups;\n\t\tdelete settings.options;\n\n\t\tself.refreshItems();\n\t\tself.close(false);\n\t\tself.inputState();\n\t\tself.isSetup = true;\n\n\t\tself.on('change', this.onChange);\n\n\t\taddClasses(input,'tomselected','ts-hidden-accessible');\n\t\tself.trigger('initialize');\n\n\t\t// preload options\n\t\tif (settings.preload === true) {\n\t\t\tself.preload();\n\t\t}\n\n\t}\n\n\n\t/**\n\t * Register options and optgroups\n\t *\n\t */\n\tsetupOptions(options:TomOption[] = [], optgroups:TomOption[] = []){\n\n\t\t// build options table\n\t\tthis.addOptions(options);\n\n\n\t\t// build optgroup table\n\t\titerate( optgroups, (optgroup:TomOption) => {\n\t\t\tthis.registerOptionGroup(optgroup);\n\t\t});\n\t}\n\n\t/**\n\t * Sets up default rendering functions.\n\t */\n\tsetupTemplates() {\n\t\tvar self = this;\n\t\tvar field_label = self.settings.labelField;\n\t\tvar field_optgroup = self.settings.optgroupLabelField;\n\n\t\tvar templates = {\n\t\t\t'optgroup': (data:TomOption) => {\n\t\t\t\tlet optgroup = document.createElement('div');\n\t\t\t\toptgroup.className = 'optgroup';\n\t\t\t\toptgroup.appendChild(data.options);\n\t\t\t\treturn optgroup;\n\n\t\t\t},\n\t\t\t'optgroup_header': (data:TomOption, escape:typeof escape_html) => {\n\t\t\t\treturn '<div class=\"optgroup-header\">' + escape(data[field_optgroup]) + '</div>';\n\t\t\t},\n\t\t\t'option': (data:TomOption, escape:typeof escape_html) => {\n\t\t\t\treturn '<div>' + escape(data[field_label]) + '</div>';\n\t\t\t},\n\t\t\t'item': (data:TomOption, escape:typeof escape_html) => {\n\t\t\t\treturn '<div>' + escape(data[field_label]) + '</div>';\n\t\t\t},\n\t\t\t'option_create': (data:TomOption, escape:typeof escape_html) => {\n\t\t\t\treturn '<div class=\"create\">Add <strong>' + escape(data.input) + '</strong>&hellip;</div>';\n\t\t\t},\n\t\t\t'no_results':() => {\n\t\t\t\treturn '<div class=\"no-results\">No results found</div>';\n\t\t\t},\n\t\t\t'loading':() => {\n\t\t\t\treturn '<div class=\"spinner\"></div>';\n\t\t\t},\n\t\t\t'not_loading':() => {},\n\t\t\t'dropdown':() => {\n\t\t\t\treturn '<div></div>';\n\t\t\t}\n\t\t};\n\n\n\t\tself.settings.render = Object.assign({}, templates, self.settings.render);\n\t}\n\n\t/**\n\t * Maps fired events to callbacks provided\n\t * in the settings used when creating the control.\n\t */\n\tsetupCallbacks() {\n\t\tvar key, fn;\n\t\tvar callbacks:{[key:string]:string} = {\n\t\t\t'initialize'      : 'onInitialize',\n\t\t\t'change'          : 'onChange',\n\t\t\t'item_add'        : 'onItemAdd',\n\t\t\t'item_remove'     : 'onItemRemove',\n\t\t\t'item_select'     : 'onItemSelect',\n\t\t\t'clear'           : 'onClear',\n\t\t\t'option_add'      : 'onOptionAdd',\n\t\t\t'option_remove'   : 'onOptionRemove',\n\t\t\t'option_clear'    : 'onOptionClear',\n\t\t\t'optgroup_add'    : 'onOptionGroupAdd',\n\t\t\t'optgroup_remove' : 'onOptionGroupRemove',\n\t\t\t'optgroup_clear'  : 'onOptionGroupClear',\n\t\t\t'dropdown_open'   : 'onDropdownOpen',\n\t\t\t'dropdown_close'  : 'onDropdownClose',\n\t\t\t'type'            : 'onType',\n\t\t\t'load'            : 'onLoad',\n\t\t\t'focus'           : 'onFocus',\n\t\t\t'blur'            : 'onBlur'\n\t\t};\n\n\t\tfor (key in callbacks) {\n\n\t\t\tfn = this.settings[callbacks[key] as (keyof TomSettings)];\n\t\t\tif (fn) this.on(key, fn);\n\n\t\t}\n\t}\n\n\t/**\n\t * Sync the Tom Select instance with the original input or select\n\t *\n\t */\n\tsync(get_settings:boolean=true):void{\n\t\tconst self\t\t= this;\n\t\tconst settings\t= get_settings ? getSettings( self.input, {delimiter:self.settings.delimiter,allowEmptyOption:self.settings.allowEmptyOption} as RecursivePartial<TomSettings> ) : self.settings;\n\n\t\tself.setupOptions(settings.options,settings.optgroups);\n\n\t\tself.setValue(settings.items||[],true); // silent prevents recursion\n\n\t\tif( self.input.disabled ){\n\t\t\tself.disable();\n\t\t}else if( self.input.readOnly ){\n\t\t\tself.setReadOnly(true);\n\t\t}else{\n\t\t\tself.enable(); //sets tabIndex\n\t\t}\n\n\t\tself.lastQuery = null; // so updated options will be displayed in dropdown\n\t}\n\n\t/**\n\t * Triggered when the main control element\n\t * has a click event.\n\t *\n\t */\n\tonClick():void {\n\t\tvar self = this;\n\n\t\tif( self.activeItems.length > 0 ){\n\t\t\tself.clearActiveItems();\n\t\t\tself.focus();\n\t\t\treturn;\n\t\t}\n\n\t\tif( self.isFocused && self.isOpen ){\n\t\t\tself.blur();\n\t\t} else {\n\t\t\tself.focus();\n\t\t}\n\t}\n\n\t/**\n\t * @deprecated v1.7\n\t *\n\t */\n\tonMouseDown():void {}\n\n\t/**\n\t * Triggered when the value of the control has been changed.\n\t * This should propagate the event to the original DOM\n\t * input / select element.\n\t */\n\tonChange() {\n\t\ttriggerEvent(this.input, 'input');\n\t\ttriggerEvent(this.input, 'change');\n\t}\n\n\t/**\n\t * Triggered on <input> paste.\n\t *\n\t */\n\tonPaste(e:MouseEvent|KeyboardEvent):void {\n\t\tvar self = this;\n\n\t\tif( self.isInputHidden || self.isLocked ){\n\t\t\tpreventDefault(e);\n\t\t\treturn;\n\t\t}\n\n\t\t// If a regex or string is included, this will split the pasted\n\t\t// input and create Items for each separate value\n\t\tif( !self.settings.splitOn ){\n\t\t\treturn;\n\t\t}\n\n\t\t// Wait for pasted text to be recognized in value\n\t\tsetTimeout(() => {\n\t\t\tvar pastedText = self.inputValue();\n\t\t\tif( !pastedText.match(self.settings.splitOn)){\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar splitInput = pastedText.trim().split(self.settings.splitOn);\n\t\t\titerate( splitInput, (piece:string) => {\n\n\t\t\t\tconst hash = hash_key(piece);\n\t\t\t\tif( hash ){\n\t\t\t\t\tif( this.options[piece] ){\n\t\t\t\t\t\tself.addItem(piece);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tself.createItem(piece);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 0);\n\n\t}\n\n\t/**\n\t * Triggered on <input> keypress.\n\t *\n\t */\n\tonKeyPress(e:KeyboardEvent):void {\n\t\tvar self = this;\n\t\tif(self.isLocked){\n\t\t\tpreventDefault(e);\n\t\t\treturn;\n\t\t}\n\t\tvar character = String.fromCharCode(e.keyCode || e.which);\n\t\tif (self.settings.create && self.settings.mode === 'multi' && character === self.settings.delimiter) {\n\t\t\tself.createItem();\n\t\t\tpreventDefault(e);\n\t\t\treturn;\n\t\t}\n\t}\n\n\t/**\n\t * Triggered on <input> keydown.\n\t *\n\t */\n\tonKeyDown(e:KeyboardEvent):void {\n\t\tvar self = this;\n\n\t\tself.ignoreHover = true;\n\n\t\tif (self.isLocked) {\n\t\t\tif (e.keyCode !== constants.KEY_TAB) {\n\t\t\t\tpreventDefault(e);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (e.keyCode) {\n\n\t\t\t// ctrl+A: select all\n\t\t\tcase constants.KEY_A:\n\t\t\t\tif( isKeyDown(constants.KEY_SHORTCUT,e) ){\n\t\t\t\t\tif( self.control_input.value == '' ){\n\t\t\t\t\t\tpreventDefault(e);\n\t\t\t\t\t\tself.selectAll();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t// esc: close dropdown\n\t\t\tcase constants.KEY_ESC:\n\t\t\t\tif (self.isOpen) {\n\t\t\t\t\tpreventDefault(e,true);\n\t\t\t\t\tself.close();\n\t\t\t\t}\n\t\t\t\tself.clearActiveItems();\n\t\t\t\treturn;\n\n\t\t\t// down: open dropdown or move selection down\n\t\t\tcase constants.KEY_DOWN:\n\t\t\t\tif (!self.isOpen && self.hasOptions) {\n\t\t\t\t\tself.open();\n\t\t\t\t} else if (self.activeOption) {\n\t\t\t\t\tlet next = self.getAdjacent(self.activeOption, 1);\n\t\t\t\t\tif (next) self.setActiveOption(next);\n\t\t\t\t}\n\t\t\t\tpreventDefault(e);\n\t\t\t\treturn;\n\n\t\t\t// up: move selection up\n\t\t\tcase constants.KEY_UP:\n\t\t\t\tif (self.activeOption) {\n\t\t\t\t\tlet prev = self.getAdjacent(self.activeOption, -1);\n\t\t\t\t\tif (prev) self.setActiveOption(prev);\n\t\t\t\t}\n\t\t\t\tpreventDefault(e);\n\t\t\t\treturn;\n\n\t\t\t// return: select active option\n\t\t\tcase constants.KEY_RETURN:\n\t\t\t\tif( self.canSelect(self.activeOption) ){\n\t\t\t\t\tself.onOptionSelect(e,self.activeOption!);\n\t\t\t\t\tpreventDefault(e);\n\n\t\t\t\t// if the option_create=null, the dropdown might be closed\n\t\t\t\t}else if (self.settings.create && self.createItem()) {\n\t\t\t\t\tpreventDefault(e);\n\n\t\t\t\t// don't submit form when searching for a value\n\t\t\t\t}else if( document.activeElement == self.control_input && self.isOpen ){\n\t\t\t\t\tpreventDefault(e);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\n\t\t\t// left: modifiy item selection to the left\n\t\t\tcase constants.KEY_LEFT:\n\t\t\t\tself.advanceSelection(-1, e);\n\t\t\t\treturn;\n\n\t\t\t// right: modifiy item selection to the right\n\t\t\tcase constants.KEY_RIGHT:\n\t\t\t\tself.advanceSelection(1, e);\n\t\t\t\treturn;\n\n\t\t\t// tab: select active option and/or create item\n\t\t\tcase constants.KEY_TAB:\n\n\t\t\t\tif( self.settings.selectOnTab ){\n\t\t\t\t\tif( self.canSelect(self.activeOption) ){\n\t\t\t\t\t\tself.onOptionSelect(e,self.activeOption!);\n\n\t\t\t\t\t\t// prevent default [tab] behaviour of jump to the next field\n\t\t\t\t\t\t// if select isFull, then the dropdown won't be open and [tab] will work normally\n\t\t\t\t\t\tpreventDefault(e);\n\t\t\t\t\t}\n\t\t\t\t\telse if(self.settings.create && self.createItem()) {\n\t\t\t\t\t\tpreventDefault(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\n\t\t\t// delete|backspace: delete items\n\t\t\tcase constants.KEY_BACKSPACE:\n\t\t\tcase constants.KEY_DELETE:\n\t\t\t\tself.deleteSelection(e);\n\t\t\t\treturn;\n\t\t}\n\n\t\t// don't enter text in the control_input when active items are selected\n\t\tif( self.isInputHidden && !isKeyDown(constants.KEY_SHORTCUT,e) ){\n\t\t\tpreventDefault(e);\n\t\t}\n\t}\n\n\t/**\n\t * Triggered on <input> keyup.\n\t *\n\t */\n\tonInput(e:MouseEvent|KeyboardEvent):void {\n\n\t\tif( this.isLocked ){\n\t\t\treturn;\n\t\t}\n\n\t\tconst value = this.inputValue();\n\t\tif( this.lastValue === value ) return;\n\t\tthis.lastValue = value;\n\n\t\tif( value == '' ){\n\t\t\tthis._onInput();\n\t\t\treturn;\n\t\t}\n\n\t\tif( this.refreshTimeout ){\n\t\t\twindow.clearTimeout(this.refreshTimeout);\n\t\t}\n\n\t\tthis.refreshTimeout = timeout(()=> {\n\t\t\tthis.refreshTimeout = null;\n\t\t\tthis._onInput();\n\t\t}, this.settings.refreshThrottle);\n\t}\n\n\t_onInput():void {\n\t\tconst value = this.lastValue;\n\n\t\tif( this.settings.shouldLoad.call(this,value) ){\n\t\t\tthis.load(value);\n\t\t}\n\n\t\tthis.refreshOptions();\n\t\tthis.trigger('type', value);\n\t}\n\n\t/**\n\t * Triggered when the user rolls over\n\t * an option in the autocomplete dropdown menu.\n\t *\n\t */\n\tonOptionHover( evt:MouseEvent|KeyboardEvent, option:HTMLElement ):void{\n\t\tif( this.ignoreHover ) return;\n\t\tthis.setActiveOption(option, false);\n\t}\n\n\t/**\n\t * Triggered on <input> focus.\n\t *\n\t */\n\tonFocus(e?:MouseEvent|KeyboardEvent):void {\n\t\tvar self = this;\n\t\tvar wasFocused = self.isFocused;\n\n\t\tif( self.isDisabled || self.isReadOnly ){\n\t\t\tself.blur();\n\t\t\tpreventDefault(e);\n\t\t\treturn;\n\t\t}\n\n\t\tif (self.ignoreFocus) return;\n\t\tself.isFocused = true;\n\t\tif( self.settings.preload === 'focus' ) self.preload();\n\n\t\tif (!wasFocused) self.trigger('focus');\n\n\t\tif (!self.activeItems.length) {\n\t\t\tself.inputState();\n\t\t\tself.refreshOptions(!!self.settings.openOnFocus);\n\t\t}\n\n\t\tself.refreshState();\n\t}\n\n\t/**\n\t * Triggered on <input> blur.\n\t *\n\t */\n\tonBlur(e?:FocusEvent):void {\n\n\t\tif( document.hasFocus() === false ) return;\n\n\t\tvar self = this;\n\t\tif (!self.isFocused) return;\n\t\tself.isFocused = false;\n\t\tself.ignoreFocus = false;\n\n\t\tvar deactivate = () => {\n\t\t\tself.close();\n\t\t\tself.setActiveItem();\n\t\t\tself.setCaret(self.items.length);\n\t\t\tself.trigger('blur');\n\t\t};\n\n\t\tif (self.settings.create && self.settings.createOnBlur) {\n\t\t\tself.createItem(null, deactivate);\n\t\t} else {\n\t\t\tdeactivate();\n\t\t}\n\t}\n\n\n\t/**\n\t * Triggered when the user clicks on an option\n\t * in the autocomplete dropdown menu.\n\t *\n\t */\n\tonOptionSelect( evt:MouseEvent|KeyboardEvent, option:HTMLElement ){\n\t\tvar value, self = this;\n\n\n\t\t// should not be possible to trigger a option under a disabled optgroup\n\t\tif( option.parentElement && option.parentElement.matches('[data-disabled]') ){\n\t\t\treturn;\n\t\t}\n\n\n\t\tif( option.classList.contains('create') ){\n\t\t\tself.createItem(null, () => {\n\t\t\t\tif (self.settings.closeAfterSelect) {\n\t\t\t\t\tself.close();\n\t\t\t\t} else if(self.settings.clearAfterSelect) {\n\t\t\t\t\tself.setTextboxValue();\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tvalue = option.dataset.value;\n\t\t\tif (typeof value !== 'undefined') {\n\t\t\t\tself.isDropdownContentStale = self.settings.hideSelected;\n\t\t\t\tself.addItem(value);\n\t\t\t\tif (self.settings.closeAfterSelect) {\n\t\t\t\t\tself.close();\n\t\t\t\t} else if(self.settings.clearAfterSelect) {\n\t\t\t\t\tself.setTextboxValue();\n\t\t\t\t}\n\n\t\t\t\tif( !self.settings.hideSelected && evt.type && /click/.test(evt.type) ){\n\t\t\t\t\tself.setActiveOption(option);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Return true if the given option can be selected\n\t *\n\t */\n\tcanSelect(option:HTMLElement|null):boolean{\n\n\t\tif( this.isOpen && option && this.dropdown_content.contains(option) ) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Triggered when the user clicks on an item\n\t * that has been selected.\n\t *\n\t */\n\tonItemSelect( evt?:MouseEvent, item?:TomItem ):boolean{\n\t\tvar self = this;\n\n\t\tif( !self.isLocked && self.settings.mode === 'multi' ){\n\t\t\tpreventDefault(evt);\n\t\t\tself.setActiveItem(item, evt);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Determines whether or not to invoke\n\t * the user-provided option provider / loader\n\t *\n\t * Note, there is a subtle difference between\n\t * this.canLoad() and this.settings.shouldLoad();\n\t *\n\t *\t- settings.shouldLoad() is a user-input validator.\n\t *\tWhen false is returned, the not_loading template\n\t *\twill be added to the dropdown\n\t *\n\t *\t- canLoad() is lower level validator that checks\n\t * \tthe Tom Select instance. There is no inherent user\n\t *\tfeedback when canLoad returns false\n\t *\n\t */\n\tcanLoad(value:string):boolean{\n\n\t\tif( !this.settings.load ) return false;\n\t\tif( this.loadedSearches.hasOwnProperty(value) ) return false;\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Invokes the user-provided option provider / loader.\n\t *\n\t */\n\tload(value:string):void {\n\t\tconst self = this;\n\n\t\tif( !self.canLoad(value) ) return;\n\n\t\taddClasses(self.wrapper,self.settings.loadingClass);\n\t\tself.loading++;\n\n\t\tconst callback = self.loadCallback.bind(self);\n\t\tself.settings.load.call(self, value, callback);\n\t}\n\n\t/**\n\t * Invoked by the user-provided option provider\n\t *\n\t */\n\tloadCallback( options:TomOption[], optgroups:TomOption[] ):void{\n\t\tconst self = this;\n\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\tself.isDropdownContentStale = true;\n\n\t\tself.clearActiveOption(); // when new results load, focus should be on first option\n\t\tself.setupOptions(options,optgroups);\n\n\t\tself.refreshOptions(self.isFocused && !self.isInputHidden);\n\n\t\tif (!self.loading) {\n\t\t\tremoveClasses(self.wrapper,self.settings.loadingClass);\n\t\t}\n\n\t\tself.trigger('load', options, optgroups);\n\t}\n\n\tpreload():void{\n\t\tvar classList = this.wrapper.classList;\n\t\tif( classList.contains('preloaded') ) return;\n\t\tclassList.add('preloaded');\n\t\tthis.load('');\n\t}\n\n\n\t/**\n\t * Sets the input field of the control to the specified value.\n\t *\n\t */\n\tsetTextboxValue(value:string = '') {\n\t\tvar input = this.control_input;\n\t\tvar changed = input.value !== value;\n\t\tif (changed) {\n\t\t\tinput.value = value;\n\t\t\ttriggerEvent(input,'update');\n\t\t\tthis.lastValue = value;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the value of the control. If multiple items\n\t * can be selected (e.g. <select multiple>), this returns\n\t * an array. If only one item can be selected, this\n\t * returns a string.\n\t *\n\t */\n\tgetValue():string|string[] {\n\n\t\tif( this.is_select_tag && this.input.hasAttribute('multiple')) {\n\t\t\treturn this.items;\n\t\t}\n\n\t\treturn this.items.join(this.settings.delimiter);\n\t}\n\n\t/**\n\t * Resets the selected items to the given value.\n\t *\n\t */\n\tsetValue( value:string|string[], silent?:boolean ):void{\n\t\tvar events = silent ? [] : ['change'];\n\n\t\tdebounce_events(this, events,() => {\n\t\t\tthis.clear(silent);\n\t\t\tthis.addItems(value, silent);\n\t\t});\n\t}\n\n\n\t/**\n\t * Resets the number of max items to the given value\n\t *\n\t */\n\tsetMaxItems(value:null|number){\n\t\tif(value === 0) value = null; //reset to unlimited items.\n\t\tthis.settings.maxItems = value;\n\t\tthis.refreshState();\n\t}\n\n\t/**\n\t * Sets the selected item.\n\t *\n\t */\n\tsetActiveItem( item?:TomItem, e?:MouseEvent|KeyboardEvent ){\n\t\tvar self = this;\n\t\tvar eventName;\n\t\tvar i, begin, end, swap;\n\t\tvar last;\n\n\t\tif (self.settings.mode === 'single') return;\n\n\t\t// clear the active selection\n\t\tif( !item ){\n\t\t\tself.clearActiveItems();\n\t\t\tif (self.isFocused) {\n\t\t\t\tself.inputState();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// modify selection\n\t\teventName = e && e.type.toLowerCase();\n\n\t\tif (eventName === 'click' && isKeyDown('shiftKey',e) && self.activeItems.length) {\n\t\t\tlast\t= self.getLastActive();\n\t\t\tbegin\t= Array.prototype.indexOf.call(self.control.children, last);\n\t\t\tend\t\t= Array.prototype.indexOf.call(self.control.children, item);\n\n\t\t\tif (begin > end) {\n\t\t\t\tswap  = begin;\n\t\t\t\tbegin = end;\n\t\t\t\tend   = swap;\n\t\t\t}\n\t\t\tfor (i = begin; i <= end; i++) {\n\t\t\t\titem = self.control.children[i] as TomItem;\n\t\t\t\tif (self.activeItems.indexOf(item) === -1) {\n\t\t\t\t\tself.setActiveItemClass(item);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpreventDefault(e);\n\t\t} else if ((eventName === 'click' && isKeyDown(constants.KEY_SHORTCUT,e) ) || (eventName === 'keydown' && isKeyDown('shiftKey',e))) {\n\t\t\tif( item.classList.contains('active') ){\n\t\t\t\tself.removeActiveItem( item );\n\t\t\t} else {\n\t\t\t\tself.setActiveItemClass(item);\n\t\t\t}\n\t\t} else {\n\t\t\tself.clearActiveItems();\n\t\t\tself.setActiveItemClass(item);\n\t\t}\n\n\t\t// ensure control has focus\n\t\tself.inputState();\n\t\tif (!self.isFocused) {\n\t\t\tself.focus();\n\t\t}\n\t}\n\n\t/**\n\t * Set the active and last-active classes\n\t *\n\t */\n\tsetActiveItemClass( item:TomItem ){\n\t\tconst self = this;\n\t\tconst last_active = self.control.querySelector('.last-active');\n\t\tif( last_active ) removeClasses(last_active as HTMLElement,'last-active');\n\n\t\taddClasses(item,'active last-active');\n\t\tself.trigger('item_select', item);\n\t\tif( self.activeItems.indexOf(item) == -1 ){\n\t\t\tself.activeItems.push( item );\n\t\t}\n\t}\n\n\t/**\n\t * Remove active item\n\t *\n\t */\n\tremoveActiveItem( item:TomItem ){\n\t\tvar idx = this.activeItems.indexOf(item);\n\t\tthis.activeItems.splice(idx, 1);\n\t\tremoveClasses(item,'active');\n\t}\n\n\t/**\n\t * Clears all the active items\n\t *\n\t */\n\tclearActiveItems(){\n\t\tremoveClasses(this.activeItems,'active');\n\t\tthis.activeItems = [];\n\t}\n\n\t/**\n\t * Sets the selected item in the dropdown menu\n\t * of available options.\n\t *\n\t */\n\tsetActiveOption( option:null|HTMLElement,scroll:boolean=true ):void{\n\n\t\tif( option === this.activeOption ){\n\t\t\treturn;\n\t\t}\n\n\t\tthis.clearActiveOption();\n\t\tif( !option ) return;\n\n\t\tthis.activeOption = option;\n\t\tsetAttr(this.focus_node,{'aria-activedescendant':option.getAttribute('id')});\n\t\tsetAttr(option,{'aria-selected':'true'});\n\t\taddClasses(option,'active');\n\t\tif( scroll ) this.scrollToOption(option);\n\t}\n\n\t/**\n\t * Sets the dropdown_content scrollTop to display the option\n\t *\n\t */\n\tscrollToOption( option:null|HTMLElement, behavior?:string ):void{\n\n\t\tif( !option ) return;\n\n\t\tconst content\t\t= this.dropdown_content;\n\t\tconst height_menu\t= content.clientHeight;\n\t\tconst scrollTop\t\t= content.scrollTop || 0;\n\t\tconst height_item\t= option.offsetHeight;\n\t\tconst y\t\t\t\t= option.getBoundingClientRect().top - content.getBoundingClientRect().top + scrollTop;\n\n\t\tif (y + height_item > height_menu + scrollTop) {\n\t\t\tthis.scroll(y - height_menu + height_item, behavior);\n\n\t\t} else if (y < scrollTop) {\n\t\t\tthis.scroll(y, behavior);\n\t\t}\n\t}\n\n\t/**\n\t * Scroll the dropdown to the given position\n\t *\n\t */\n\tscroll( scrollTop:number, behavior?:string ):void{\n\t\tconst content = this.dropdown_content;\n\t\tif( behavior ){\n\t\t\tcontent.style.scrollBehavior = behavior;\n\t\t}\n\t\tcontent.scrollTop = scrollTop;\n\t\tcontent.style.scrollBehavior = '';\n\t}\n\n\t/**\n\t * Clears the active option\n\t *\n\t */\n\tclearActiveOption(){\n\t\tif( this.activeOption ){\n\t\t\tremoveClasses(this.activeOption,'active');\n\t\t\tsetAttr(this.activeOption,{'aria-selected':null});\n\t\t}\n\t\tthis.activeOption = null;\n\t\tsetAttr(this.focus_node,{'aria-activedescendant':null});\n\t}\n\n\n\t/**\n\t * Selects all items (CTRL + A).\n\t */\n\tselectAll() {\n\t\tconst self = this;\n\n\t\tif (self.settings.mode === 'single') return;\n\n\t\tconst activeItems = self.controlChildren();\n\n\t\tif( !activeItems.length ) return;\n\n\t\tself.inputState();\n\t\tself.close();\n\n\t\tself.activeItems = activeItems;\n\t\titerate( activeItems, (item:TomItem) => {\n\t\t\tself.setActiveItemClass(item);\n\t\t});\n\n\t}\n\n\t/**\n\t * Determines if the control_input should be in a hidden or visible state\n\t *\n\t */\n\tinputState(){\n\t\tvar self = this;\n\n\t\tif( !self.control.contains(self.control_input) ) return;\n\n\t\tsetAttr(self.control_input,{placeholder:self.settings.placeholder});\n\n\t\tif( self.activeItems.length > 0 || (!self.isFocused && self.settings.hidePlaceholder && self.items.length > 0) ){\n\t\t\tself.setTextboxValue();\n\t\t\tself.isInputHidden = true;\n\n\t\t}else{\n\n\t\t\tif( self.settings.hidePlaceholder && self.items.length > 0 ){\n\t\t\t\tsetAttr(self.control_input,{placeholder:''});\n\t\t\t}\n\t\t\tself.isInputHidden = false;\n\t\t}\n\n\t\tself.wrapper.classList.toggle('input-hidden', self.isInputHidden );\n\t}\n\n\t/**\n\t * Get the input value\n\t */\n\tinputValue(){\n\t\treturn this.control_input.value.trim();\n\t}\n\n\t/**\n\t * Gives the control focus.\n\t */\n\tfocus() {\n\t\tvar self = this;\n\t\tif( self.isDisabled || self.isReadOnly) return;\n\n\t\tself.ignoreFocus = true;\n\n\t\tconst focusTarget = this.control_input.offsetWidth ? this.control_input : this.focus_node;\n    \tfocusTarget.focus();\n\n\t\tsetTimeout(() => {\n\t\t\tself.ignoreFocus = false;\n\t\t\t// Fix https://github.com/orchidjs/tom-select/issues/806\n\t\t\t// Only proceed if this instance's element is still the active element. If Edge autofill\n\t\t\t// (or anything else) has moved focus to a different element in the interim, calling\n\t\t\t// onFocus() here would steal focus back and restart the cascade loop.\n\t\t\tconst root = focusTarget.getRootNode() as Document | ShadowRoot;\n\t\t\tif (root.activeElement !== focusTarget) {\n        \t\treturn;\n      \t\t}\n\n\t\t\tthis.onFocus();\n\t\t}, 0);\n\t}\n\n\t/**\n\t * Forces the control out of focus.\n\t *\n\t */\n\tblur():void {\n\t\tthis.focus_node.blur();\n\t\tthis.onBlur();\n\t}\n\n\t/**\n\t * Returns a function that scores an object\n\t * to show how good of a match it is to the\n\t * provided query.\n\t *\n\t * @return {function}\n\t */\n\tgetScoreFunction(query:string) {\n\t\treturn this.sifter.getScoreFunction(query, this.getSearchOptions());\n\t}\n\n\t/**\n\t * Returns search options for sifter (the system\n\t * for scoring and sorting results).\n\t *\n\t * @see https://github.com/orchidjs/sifter.js\n\t * @return {object}\n\t */\n\tgetSearchOptions() {\n\t\tvar settings = this.settings;\n\n\t\tvar fields = typeof settings.searchField === 'string'\n\t\t\t? [settings.searchField]\n\t\t\t: settings.searchField;\n\n\t\tvar sort = typeof settings.sortField === 'string'\n\t\t\t? [{field: settings.sortField}]\n\t\t\t: settings.sortField;\n\n\t\treturn {\n\t\t\tfields      : fields,\n\t\t\tconjunction : settings.searchConjunction,\n\t\t\tsort        : sort,\n\t\t\tnesting     : settings.nesting\n\t\t};\n\t}\n\n\t/**\n\t * Searches through available options and returns\n\t * a sorted array of matches.\n\t *\n\t */\n\tsearch(query:string) : ReturnType<Sifter['search']>{\n\t\tvar result, calculateScore;\n\t\tvar self     = this;\n\t\tvar options  = this.getSearchOptions();\n\n\t\t// validate user-provided result scoring function\n\t\tif ( self.settings.score ){\n\t\t\tcalculateScore = self.settings.score.call(self,query);\n\t\t\tif (typeof calculateScore !== 'function') {\n\t\t\t\tthrow new Error('Tom Select \"score\" setting must be a function that returns a function');\n\t\t\t}\n\t\t}\n\n\t\t// perform search\n\t\tif (self.isDropdownContentStale || query !== self.lastQuery) {\n\t\t\tself.lastQuery\t\t\t= query;\n\t\t\t// temp fix for https://github.com/orchidjs/tom-select/issues/987\n\t\t\t// UI crashed when more than 30 same chars in a row, prevent search and return empt result\n\t\t\tif (/(.)\\1{15,}/.test(query)) {\n\t\t\t\tquery \t\t\t\t= '';\n\t\t\t}\n\t\t\tresult \t\t\t\t\t= self.sifter.search(query, Object.assign(options, { score: calculateScore }));\n\t\t\tself.currentResults\t\t= result;\n\t\t} else {\n\t\t\tresult\t\t\t\t\t= Object.assign( {}, self.currentResults);\n\t\t}\n\n\t\t// filter out selected items\n\t\tif( self.settings.hideSelected ){\n\t\t\tresult.items = result.items.filter((item) => {\n\t\t\t\tlet hashed = hash_key(item.id);\n\t\t\t\treturn !(hashed !== null && self.items.indexOf(hashed) !== -1 );\n\t\t\t});\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Refreshes the list of available options shown\n\t * in the autocomplete dropdown menu.\n\t *\n\t */\n\trefreshOptions( triggerDropdown:boolean = true ){\n\t\tvar i, j, k, n, optgroup, optgroups, html:DocumentFragment, has_create_option, active_group;\n\t\tvar create;\n\n\t\ttype Group = {fragment:DocumentFragment,order:number,optgroup:string}\n\t\tconst groups: {[key:string]:number} = {};\n\t\tconst groups_order:Group[]\t= [];\n\n\t\tvar self\t\t\t\t\t= this;\n\t\tvar query\t\t\t\t\t= self.inputValue();\n\t\tconst same_query\t\t\t= query === self.lastQuery || (query == '' && self.lastQuery == null);\n\t\tvar results\t\t\t\t\t= self.search(query);\n\t\tvar active_option:HTMLElement|null = null;\n\t\tvar show_dropdown\t\t\t= self.settings.shouldOpen || false;\n\t\tvar dropdown_content\t\t= self.dropdown_content;\n\n\n\t\tif( same_query ){\n\t\t\tactive_option\t\t\t= self.activeOption;\n\n\t\t\tif( active_option ){\n\t\t\t\tactive_group = active_option.closest('[data-group]') as HTMLElement;\n\t\t\t}\n\t\t}\n\n\t\t// build markup\n\t\tn = results.items.length;\n\t\tif (typeof self.settings.maxOptions === 'number') {\n\t\t\tn = Math.min(n, self.settings.maxOptions);\n\t\t}\n\n\t\tif( n > 0 ){\n\t\t\tshow_dropdown = true;\n\t\t}\n\n\t\t// get fragment for group and the position of the group in group_order\n\t\tconst getGroupFragment = (optgroup:string,order:number):[number,DocumentFragment] => {\n\n\t\t\tlet group_order_i = groups[optgroup];\n\n\t\t\tif( group_order_i !== undefined ){\n\t\t\t\tlet order_group = groups_order[group_order_i];\n\t\t\t\tif( order_group !== undefined ){\n\t\t\t\t\treturn [group_order_i,order_group.fragment];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet group_fragment = document.createDocumentFragment();\n\t\t\tgroup_order_i = groups_order.length;\n\t\t\tgroups_order.push({fragment:group_fragment,order,optgroup});\n\n\t\t\treturn [group_order_i,group_fragment]\n\t\t}\n\n\t\t// render and group available options individually\n\t\tfor (i = 0; i < n; i++) {\n\n\t\t\t// get option dom element\n\t\t\tlet item\t\t\t= results.items[i];\n\t\t\tif( !item ) continue;\n\n\t\t\tlet opt_value\t\t= item.id;\n\t\t\tlet option\t\t\t= self.options[opt_value];\n\n\t\t\tif( option === undefined ) continue;\n\n\t\t\tlet opt_hash\t\t= get_hash(opt_value);\n\t\t\tlet option_el\t\t= self.getOption(opt_hash,true) as HTMLElement;\n\n\t\t\t// toggle 'selected' class\n\t\t\tif( !self.settings.hideSelected ){\n\t\t\t\toption_el.classList.toggle('selected', self.items.includes(opt_hash) );\n\t\t\t}\n\n\t\t\toptgroup    = option[self.settings.optgroupField] || '';\n\t\t\toptgroups   = Array.isArray(optgroup) ? optgroup : [optgroup];\n\n\n\t\t\tfor (j = 0, k = optgroups && optgroups.length; j < k; j++) {\n\t\t\t\toptgroup = optgroups[j];\n\n\t\t\t\tlet order = option.$order;\n\t\t\t\tlet self_optgroup = self.optgroups[optgroup];\n\t\t\t\tif (self_optgroup === undefined && typeof self.settings.optionGroupRegister === 'function') {\n\t          \t\tvar regGroup;\n\t\t\t\t\tif (regGroup = self.settings.optionGroupRegister.apply(self, [optgroup])) {\n\t\t\t\t\t\tself.registerOptionGroup(regGroup);\n\t\t\t\t\t}\n\t        \t}\n\t\t\t\tself_optgroup = self.optgroups[optgroup];\n\t\t\t\tif( self_optgroup === undefined ){\t\t\t\t\t\n\t\t\t\t\toptgroup = '';\n\t\t\t\t}else{\n\t\t\t\t\torder = self_optgroup.$order;\n\t\t\t\t}\n\n\t\t\t\tconst [group_order_i,group_fragment] = getGroupFragment(optgroup,order);\n\n\n\t\t\t\t// nodes can only have one parent, so if the option is in mutple groups, we need a clone\n\t\t\t\tif( j > 0 ){\n\t\t\t\t\toption_el = option_el.cloneNode(true) as HTMLElement;\n\t\t\t\t\tsetAttr(option_el,{id: option.$id+'-clone-'+j,'aria-selected':null});\n\t\t\t\t\toption_el.classList.add('ts-cloned');\n\t\t\t\t\tremoveClasses(option_el,'active');\n\n\n\t\t\t\t\t// make sure we keep the activeOption in the same group\n\t\t\t\t\tif( self.activeOption && self.activeOption.dataset.value == opt_value ){\n\t\t\t\t\t\tif( active_group && active_group.dataset.group === optgroup.toString() ){\n\t\t\t\t\t\t\tactive_option = option_el;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tgroup_fragment.appendChild(option_el);\n\t\t\t\tif( optgroup != '' ){\n\t\t\t\t\tgroups[optgroup] = group_order_i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// sort optgroups\n\t\tif( self.settings.lockOptgroupOrder ){\n\t\t\tgroups_order.sort((a, b) => {\n\t\t\t\treturn a.order - b.order;\n\t\t\t});\n\t\t}\n\n\t\t// render optgroup headers & join groups\n\t\thtml = document.createDocumentFragment();\n\t\titerate( groups_order, (group_order:Group) => {\n\n\t\t\tlet group_fragment = group_order.fragment;\n\t\t\tlet optgroup = group_order.optgroup\n\n\t\t\tif( !group_fragment || !group_fragment.children.length ) return;\n\n\t\t\tlet group_heading = self.optgroups[optgroup];\n\n\t\t\tif( group_heading !== undefined ){\n\n\t\t\t\tlet group_options = document.createDocumentFragment();\n\t\t\t\tlet header = self.render('optgroup_header', group_heading);\n\t\t\t\tappend( group_options, header );\n\t\t\t\tappend( group_options, group_fragment );\n\n\t\t\t\tlet group_html = self.render('optgroup', {group:group_heading,options:group_options} );\n\n\t\t\t\tappend( html, group_html );\n\n\t\t\t} else {\n\t\t\t\tappend( html, group_fragment );\n\t\t\t}\n\t\t});\n\n\t\tdropdown_content.innerHTML = '';\n\t\tappend( dropdown_content, html );\n\t\tself.isDropdownContentStale = false;\n\n\t\t// highlight matching terms inline\n\t\tif (self.settings.highlight) {\n\t\t\tremoveHighlight( dropdown_content );\n\t\t\tif (results.query.length && results.tokens.length) {\n\t\t\t\titerate( results.tokens, (tok) => {\n\t\t\t\t\thighlight( dropdown_content, tok.regex);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// helper method for adding templates to dropdown\n\t\tvar add_template = (template:TomTemplateNames) => {\n\t\t\tlet content = self.render(template,{input:query});\n\t\t\tif( content ){\n\t\t\t\tshow_dropdown = true;\n\t\t\t\tdropdown_content.insertBefore(content, dropdown_content.firstChild);\n\t\t\t}\n\t\t\treturn content;\n\t\t};\n\n\n\t\t// add loading message\n\t\tif( self.loading ){\n\t\t\tadd_template('loading');\n\n\t\t// invalid query\n\t\t}else if( !self.settings.shouldLoad.call(self,query) ){\n\t\t\tadd_template('not_loading');\n\n\t\t// add no_results message\n\t\t}else if( results.items.length === 0 ){\n\t\t\tadd_template('no_results');\n\n\t\t}\n\n\n\n\t\t// add create option\n\t\thas_create_option = self.canCreate(query);\n\t\tif (has_create_option) {\n\t\t\tcreate = add_template('option_create');\n\t\t}\n\n\n\t\t// activate\n\t\tself.hasOptions = results.items.length > 0 || has_create_option;\n\t\tif( show_dropdown ){\n\n\t\t\tif (results.items.length > 0) {\n\n\t\t\t\tif( !active_option && self.settings.mode === 'single' && self.items[0] != undefined ){\n\t\t\t\t\tactive_option = self.getOption(self.items[0]);\n\t\t\t\t}\n\n\t\t\t\tif( !dropdown_content.contains(active_option)  ){\n\n\t\t\t\t\tlet active_index = 0;\n\t\t\t\t\tif( create && !self.settings.addPrecedence ){\n\t\t\t\t\t\tactive_index = 1;\n\t\t\t\t\t}\n\t\t\t\t\tactive_option = self.selectable()[active_index] as HTMLElement;\n\t\t\t\t}\n\n\t\t\t}else if( create ){\n\t\t\t\tactive_option = create;\n\t\t\t}\n\n\t\t\tif( triggerDropdown && !self.isOpen ){\n\t\t\t\tself.open();\n\t\t\t\tself.scrollToOption(active_option,'auto');\n\t\t\t}\n\t\t\tself.setActiveOption(active_option);\n\n\t\t}else{\n\t\t\tself.clearActiveOption();\n\t\t\tif( triggerDropdown && self.isOpen ){\n\t\t\t\tself.close(false); // if create_option=null, we want the dropdown to close but not reset the textbox value\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Return list of selectable options\n\t *\n\t */\n\tselectable():NodeList{\n\t\treturn this.dropdown_content.querySelectorAll('[data-selectable]');\n\t}\n\n\n\n\t/**\n\t * Adds an available option. If it already exists,\n\t * nothing will happen. Note: this does not refresh\n\t * the options list dropdown (use `refreshOptions`\n\t * for that).\n\t *\n\t * Usage:\n\t *\n\t *   this.addOption(data)\n\t *\n\t */\n\taddOption( data:TomOption, user_created = false ):false|string {\n\t\tconst self = this;\n\n\t\t// @deprecated 1.7.7\n\t\t// use addOptions( array, user_created ) for adding multiple options\n\t\tif( Array.isArray(data) ){\n\t\t\tself.addOptions( data, user_created);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst key = hash_key(data[self.settings.valueField]);\n\t\tif( key === null || self.options.hasOwnProperty(key) ){\n\t\t\tself.updateOption(data[self.settings.valueField], data);\n\t\t\treturn false;\n\t\t}\n\n\t\tdata.$order\t\t\t\t\t= data.$order || ++self.order;\n\t\tself.order\t\t\t\t\t= Math.max(self.order, data.$order); // options parsed from the <select> are numbered separately\n\t\tdata.$id\t\t\t\t\t= self.inputId + '-opt-' + data.$order;\n\t\tself.options[key]\t\t\t= data;\n\t\tself.isDropdownContentStale\t= true;\n\n\t\tif( user_created ){\n\t\t\tself.userOptions[key] = user_created;\n\t\t\tself.trigger('option_add', key, data);\n\t\t}\n\n\t\treturn key;\n\t}\n\n\t/**\n\t * Add multiple options\n\t *\n\t */\n\taddOptions( data:TomOption[], user_created = false ):void{\n\t\titerate( data, (dat:TomOption) => {\n\t\t\tthis.addOption(dat, user_created);\n\t\t});\n\t}\n\n\t/**\n\t * @deprecated 1.7.7\n\t */\n\tregisterOption( data:TomOption ):false|string {\n\t\treturn this.addOption(data);\n\t}\n\n\t/**\n\t * Registers an option group to the pool of option groups.\n\t *\n\t * @return {boolean|string}\n\t */\n\tregisterOptionGroup(data:TomOption) {\n\t\tvar key = hash_key(data[this.settings.optgroupValueField]);\n\n\t\tif ( key === null ) return false;\n\n\t\tdata.$order = data.$order || ++this.order;\n\t\tthis.order = Math.max(this.order, data.$order);\n\t\tthis.optgroups[key] = data;\n\t\treturn key;\n\t}\n\n\t/**\n\t * Registers a new optgroup for options\n\t * to be bucketed into.\n\t *\n\t */\n\taddOptionGroup(id:string, data:TomOption) {\n\t\tvar hashed_id;\n\t\tdata[this.settings.optgroupValueField] = id;\n\n\t\tif( hashed_id = this.registerOptionGroup(data) ){\n\t\t\tthis.trigger('optgroup_add', hashed_id, data);\n\t\t}\n\t}\n\n\t/**\n\t * Removes an existing option group.\n\t *\n\t */\n\tremoveOptionGroup(id:string) {\n\t\tif (this.optgroups.hasOwnProperty(id)) {\n\t\t\tdelete this.optgroups[id];\n\t\t\tthis.clearCache();\n\t\t\tthis.trigger('optgroup_remove', id);\n\t\t}\n\t}\n\n\t/**\n\t * Clears all existing option groups.\n\t */\n\tclearOptionGroups() {\n\t\tthis.optgroups = {};\n\t\tthis.clearCache();\n\t\tthis.trigger('optgroup_clear');\n\t}\n\n\t/**\n\t * Updates an option available for selection. If\n\t * it is visible in the selected items or options\n\t * dropdown, it will be re-rendered automatically.\n\t *\n\t */\n\tupdateOption(value:string, data:TomOption) {\n\t\tconst self = this;\n\t\tvar item_new;\n\t\tvar index_item;\n\n\t\tconst value_old\t\t= hash_key(value);\n\t\tconst value_new\t\t= hash_key(data[self.settings.valueField]);\n\n\t\t// sanity checks\n\t\tif( value_old === null ) return;\n\n\t\tconst data_old\t\t= self.options[value_old];\n\n\t\tif( data_old == undefined ) return;\n\t\tif( typeof value_new !== 'string' ) throw new Error('Value must be set in option data');\n\n\n\t\tconst option\t\t= self.getOption(value_old);\n\t\tconst item\t\t\t= self.getItem(value_old);\n\n\n\t\tdata.$order = data.$order || data_old.$order;\n\t\tdelete self.options[value_old];\n\n\t\t// invalidate render cache\n\t\t// don't remove existing node yet, we'll remove it after replacing it\n\t\tself.uncacheValue(value_new);\n\n\t\tself.options[value_new] = data;\n\n\t\t// update the option if it's in the dropdown\n\t\tif( option ){\n\t\t\tif( self.dropdown_content.contains(option) ){\n\n\t\t\t\tconst option_new\t= self._render('option', data);\n\t\t\t\treplaceNode(option, option_new);\n\n\t\t\t\tif( self.activeOption === option ){\n\t\t\t\t\tself.setActiveOption(option_new);\n\t\t\t\t}\n\t\t\t}\n\t\t\toption.remove();\n\t\t}\n\n\t\t// update the item if we have one\n\t\tif( item ){\n\t\t\tindex_item = self.items.indexOf(value_old);\n\t\t\tif (index_item !== -1) {\n\t\t\t\tself.items.splice(index_item, 1, value_new);\n\t\t\t}\n\n\t\t\titem_new\t= self._render('item', data);\n\n\t\t\tif( item.classList.contains('active') ) addClasses(item_new,'active');\n\n\t\t\treplaceNode( item, item_new);\n\t\t}\n\n\t\t// we might have updated the sortField\n\t\tself.isDropdownContentStale = true;\n\t}\n\n\t/**\n\t * Removes a single option.\n\t *\n\t */\n\tremoveOption(value:string, silent?:boolean):void {\n\t\tconst self = this;\n\t\tvalue = get_hash(value);\n\n\t\tself.uncacheValue(value);\n\n\t\tdelete self.userOptions[value];\n\t\tdelete self.options[value];\n\t\tself.isDropdownContentStale = true;\n\t\tself.trigger('option_remove', value);\n\t\tself.removeItem(value, silent);\n\t}\n\n\t/**\n\t * Clears all options.\n\t */\n\tclearOptions(filter?:TomClearFilter ) {\n\n\t\tconst boundFilter = (filter || this.clearFilter).bind(this);\n\n\t\tthis.loadedSearches\t\t= {};\n\t\tthis.userOptions\t\t= {};\n\t\tthis.clearCache();\n\n\t\tconst selected:TomOptions\t= {};\n\t\titerate(this.options,(option:TomOption,key:string)=>{\n\t\t\tif( boundFilter(option,key as string) ){\n\t\t\t\tselected[key] = option;\n\t\t\t}\n\t\t});\n\n\t\tthis.options = this.sifter.items = selected;\n\t\tthis.isDropdownContentStale = true;\n\t\tthis.trigger('option_clear');\n\t}\n\n\t/**\n\t * Used by clearOptions() to decide whether or not an option should be removed\n\t * Return true to keep an option, false to remove\n\t *\n\t */\n\tclearFilter(option:TomOption,value:string){\n\t\tif( this.items.indexOf(value) >= 0 ){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns the dom element of the option\n\t * matching the given value.\n\t *\n\t */\n\tgetOption(value:undefined|null|boolean|string|number, create:boolean=false):null|HTMLElement {\n\n\t\tconst hashed = hash_key(value);\n\t\tif( hashed === null ) return null;\n\n\t\tconst option = this.options[hashed];\n\t\tif( option != undefined ){\n\n\t\t\tif( option.$div ){\n\t\t\t\treturn option.$div;\n\t\t\t}\n\n\t\t\tif( create ){\n\t\t\t\treturn this._render('option', option);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns the dom element of the next or previous dom element of the same type\n\t * Note: adjacent options may not be adjacent DOM elements (optgroups)\n\t *\n\t */\n\tgetAdjacent( option:null|HTMLElement, direction:number, type:string = 'option' ) : HTMLElement|null{\n\t\tvar self = this, all;\n\n\t\tif( !option ){\n\t\t\treturn null;\n\t\t}\n\n\t\tif( type == 'item' ){\n\t\t\tall\t\t\t= self.controlChildren();\n\t\t}else{\n\t\t\tall\t\t\t= self.dropdown_content.querySelectorAll('[data-selectable]');\n\t\t}\n\n\t\tfor( let i = 0; i < all.length; i++ ){\n\t\t\tif( all[i] != option ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif( direction > 0 ){\n\t\t\t\treturn all[i+1] as HTMLElement;\n\t\t\t}\n\n\t\t\treturn all[i-1] as HTMLElement;\n\t\t}\n\t\treturn null;\n\t}\n\n\n\t/**\n\t * Returns the dom element of the item\n\t * matching the given value.\n\t *\n\t */\n\tgetItem(item:string|TomItem|null):null|TomItem {\n\n\t\tif( typeof item == 'object' ){\n\t\t\treturn item;\n\t\t}\n\n\t\tvar value = hash_key(item);\n\t\treturn value !== null\n\t\t\t? this.control.querySelector(`[data-value=\"${addSlashes(value)}\"]`)\n\t\t\t: null;\n\t}\n\n\t/**\n\t * \"Selects\" multiple items at once. Adds them to the list\n\t * at the current caret position.\n\t *\n\t */\n\taddItems( values:string|string[], silent?:boolean ):void{\n\t\tvar self = this;\n\n\t\tvar items = Array.isArray(values) ? values : [values];\n\t\titems = items.filter(x => self.items.indexOf(x) === -1);\n\t\tconst last_item = items[items.length - 1];\n\t\titems.forEach(item => {\n\t\t\tself.isPending = (item !== last_item);\n\t\t\tself.addItem(item, silent);\n\t\t});\n\t}\n\n\t/**\n\t * \"Selects\" an item. Adds it to the list\n\t * at the current caret position.\n\t *\n\t */\n\taddItem( value:string, silent?:boolean ):void{\n\t\tvar events = silent ? [] : ['change','dropdown_close'];\n\n\t\tdebounce_events(this, events, () => {\n\t\t\tvar item, wasFull;\n\t\t\tconst self = this;\n\t\t \tconst inputMode = self.settings.mode;\n\t\t\tconst hashed = hash_key(value);\n\n\t\t\tif( hashed && self.items.indexOf(hashed) !== -1 ){\n\n\t\t\t\tif( inputMode === 'single' ){\n\t\t\t\t\tself.close();\n\t\t\t\t}\n\n\t\t\t\tif( inputMode === 'single' || !self.settings.duplicates ){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hashed === null || !self.options.hasOwnProperty(hashed)) return;\n\t\t\tif (inputMode === 'single') self.clear(silent);\n\t\t\tif (inputMode === 'multi' && self.isFull()) return;\n\n\t\t\titem = self._render('item', self.options[hashed]);\n\n\t\t\tif( self.control.contains(item) ){ // duplicates\n\t\t\t\titem = item.cloneNode(true) as HTMLElement;\n\t\t\t}\n\n\t\t\twasFull = self.isFull();\n\t\t\tself.items.splice(self.caretPos, 0, hashed);\n\t\t\tself.insertAtCaret(item);\n\n\t\t\tif (self.isSetup) {\n\n\t\t\t\t// update menu / remove the option (if this is not one item being added as part of series)\n\t\t\t\tif( !self.isPending && self.settings.hideSelected ){\n\t\t\t\t\tlet option = self.getOption(hashed);\n\t\t\t\t\tlet next = self.getAdjacent(option, 1);\n\t\t\t\t\tif( next ){\n\t\t\t\t\t\tself.setActiveOption(next);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//remove input value when enabled\n\t\t\t\tif(self.settings.clearAfterSelect) {\n\t\t\t\t\tself.setTextboxValue();\n\t\t\t\t}\n\n\t\t\t\t// refreshOptions after setActiveOption(),\n\t\t\t\t// otherwise setActiveOption() will be called by refreshOptions() with the wrong value\n\t\t\t\tif( !self.isPending && !self.settings.closeAfterSelect ){\n\t\t\t\t\tself.refreshOptions(self.isFocused && inputMode !== 'single');\n\t\t\t\t}\n\n\t\t\t\t// hide the menu if the maximum number of items have been selected or no options are left\n\t\t\t\tif( self.settings.closeAfterSelect != false && self.isFull() ){\n\t\t\t\t\tself.close();\n\t\t\t\t} else if (!self.isPending) {\n\t\t\t\t\tself.positionDropdown();\n\t\t\t\t}\n\n\t\t\t\tself.trigger('item_add', hashed, item);\n\n\t\t\t\tif (!self.isPending) {\n\t\t\t\t\tself.updateOriginalInput({silent: silent});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!self.isPending || (!wasFull && self.isFull())) {\n\t\t\t\tself.inputState();\n\t\t\t\tself.refreshState();\n\t\t\t}\n\n\t\t});\n\t}\n\n\t/**\n\t * Removes the selected item matching\n\t * the provided value.\n\t *\n\t */\n\tremoveItem( item:string|TomItem|null=null, silent?:boolean ){\n\t\tconst self\t\t= this;\n\t\titem\t\t\t= self.getItem(item);\n\n\t\tif( !item ) return;\n\n\t\tvar i,idx;\n\t\tconst value\t= item.dataset.value;\n\t\ti = nodeIndex(item, '.item');\n\n\t\titem.remove();\n\t\tif( item.classList.contains('active') ){\n\t\t\tidx = self.activeItems.indexOf(item);\n\t\t\tself.activeItems.splice(idx, 1);\n\t\t\tremoveClasses(item,'active');\n\t\t}\n\n\t\tself.items.splice(i, 1);\n\t\tself.isDropdownContentStale = true;\n\t\tif (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {\n\t\t\tself.removeOption(value, silent);\n\t\t}\n\n\t\tif (i < self.caretPos) {\n\t\t\tself.setCaret(self.caretPos - 1);\n\t\t}\n\n\t\tself.updateOriginalInput({silent: silent});\n\t\tself.refreshState();\n\t\tself.positionDropdown();\n\t\tself.trigger('item_remove', value, item);\n\n\t}\n\n\t/**\n\t * Invokes the `create` method provided in the\n\t * TomSelect options that should provide the data\n\t * for the new item, given the user input.\n\t *\n\t * Once this completes, it will be added\n\t * to the item list.\n\t *\n\t */\n\tcreateItem( input:null|string=null, callback:TomCreateCallback = ()=>{} ):boolean{\n\n\t\t// triggerDropdown parameter @deprecated 2.1.1\n\t\tif( arguments.length === 3 ){\n\t\t\tcallback = arguments[2];\n\t\t}\n\t\tif( typeof callback != 'function' ){\n\t\t\tcallback = () => {};\n\t\t}\n\n\t\tvar self  = this;\n\t\tvar caret = self.caretPos;\n\t\tvar output;\n\t\tinput = input || self.inputValue();\n\n\t\tif (!self.canCreate(input)) {\n\t\t\tconst hash = hash_key(input);\n\t\t\t\tif( hash ){\n\t\t\t\t\tif( this.options[input] ){\n\t\t\t\t\t\tself.addItem(input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcallback();\n\t\t\treturn false;\n\t\t}\n\n\t\tself.lock();\n\n\t\tvar created = false;\n\t\tvar create = (data?:boolean|TomOption) => {\n\t\t\tself.unlock();\n\n\t\t\tif (!data || typeof data !== 'object') return callback();\n\t\t\tvar value = hash_key(data[self.settings.valueField]);\n\t\t\tif( typeof value !== 'string' ){\n\t\t\t\treturn callback();\n\t\t\t}\n\n\t\t\tself.setTextboxValue();\n\t\t\tself.addOption(data,true);\n\t\t\tself.setCaret(caret);\n\t\t\tself.addItem(value);\n\t\t\tcallback(data);\n\t\t\tcreated = true;\n\t\t};\n\n\t\tif( typeof self.settings.create === 'function' ){\n\t\t\toutput = self.settings.create.call(this, input, create);\n\t\t}else{\n\t\t\toutput = {\n\t\t\t\t[self.settings.labelField]: input,\n\t\t\t\t[self.settings.valueField]: input,\n\t\t\t};\n\t\t}\n\n\t\tif( !created ){\n\t\t\tcreate(output);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Re-renders the selected item lists.\n\t */\n\trefreshItems() {\n\t\tvar self = this;\n\t\tself.isDropdownContentStale = true;\n\n\t\tif (self.isSetup) {\n\t\t\tself.addItems(self.items);\n\t\t}\n\n\t\tself.updateOriginalInput();\n\t\tself.refreshState();\n\t}\n\n\t/**\n\t * Updates all state-dependent attributes\n\t * and CSS classes.\n\t */\n\trefreshState() {\n\t\tconst self     = this;\n\n\t\tself.refreshValidityState();\n\n\t\tconst isFull\t= self.isFull();\n\t\tconst isLocked\t= self.isLocked;\n\n\t\tself.wrapper.classList.toggle('rtl',self.rtl);\n\n\n\t\tconst wrap_classList = self.wrapper.classList;\n\n\t\twrap_classList.toggle('focus', self.isFocused)\n\t\twrap_classList.toggle('disabled', self.isDisabled)\n\t\twrap_classList.toggle('readonly', self.isReadOnly)\n\t\twrap_classList.toggle('required', self.isRequired)\n\t\twrap_classList.toggle('invalid', !self.isValid)\n\t\twrap_classList.toggle('locked', isLocked)\n\t\twrap_classList.toggle('full', isFull)\n\t\twrap_classList.toggle('input-active', self.isFocused && !self.isInputHidden)\n\t\twrap_classList.toggle('dropdown-active', self.isOpen)\n\t\twrap_classList.toggle('has-options', isEmptyObject(self.options) )\n\t\twrap_classList.toggle('has-items', self.items.length > 0);\n\t}\n\n\t/**\n\t * Update the `required` attribute of both input and control input.\n\t *\n\t * The `required` property needs to be activated on the control input\n\t * for the error to be displayed at the right place. `required` also\n\t * needs to be temporarily deactivated on the input since the input is\n\t * hidden and can't show errors.\n\t */\n\trefreshValidityState() {\n\t\tvar self = this;\n\n\t\tif( !self.input.validity ){\n\t\t\treturn;\n\t\t}\n\n\t\tself.isValid = self.input.validity.valid;\n\t\tself.isInvalid = !self.isValid;\n\t}\n\n\t/**\n\t * Determines whether or not more items can be added\n\t * to the control without exceeding the user-defined maximum.\n\t *\n\t * @returns {boolean}\n\t */\n\tisFull() {\n\t\treturn this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;\n\t}\n\n\t/**\n\t * Refreshes the original <select> or <input>\n\t * element to reflect the current state.\n\t *\n\t */\n\tupdateOriginalInput( opts:TomArgObject = {} ){\n\t\tconst self = this;\n\t\tvar option, label;\n\n\t\tconst empty_option = self.input.querySelector('option[value=\"\"]') as HTMLOptionElement;\n\n\t\tif( self.is_select_tag ){\n\n\t\t\tconst selected:HTMLOptionElement[]\t\t= [];\n\t\t\tconst has_selected:number\t\t\t\t= self.input.querySelectorAll('option:checked').length;\n\n\t\t\tfunction AddSelected(option_el:HTMLOptionElement|null, value:string, label:string):HTMLOptionElement{\n\n\t\t\t\tif( !option_el ){\n\t\t\t\t\toption_el = getDom('<option value=\"' + escape_html(value) + '\">' + escape_html(label) + '</option>') as HTMLOptionElement;\n\t\t\t\t}\n\n\t\t\t\tif( !value ){\n\t\t\t\t\tself.input.prepend(option_el);\n\t\t\t\t} else {\n\t\t\t\t\tself.input.append(option_el);\n\t\t\t\t}\n\n\t\t\t\tselected.push(option_el);\n\n\t\t\t\t// marking empty option as selected can break validation\n\t\t\t\t// fixes https://github.com/orchidjs/tom-select/issues/303\n\t\t\t\tif( option_el != empty_option || has_selected > 0 || self.settings.mode == 'multi' ){\n\t\t\t\t\toption_el.selected = true;\n\t\t\t\t}\n\n\t\t\t\treturn option_el;\n\t\t\t}\n\n\t\t\t// unselect all selected options\n\t\t\tself.input.querySelectorAll('option:checked').forEach((option_el:Element) => {\n\t\t\t\t(<HTMLOptionElement>option_el).selected = false;\n\t\t\t});\n\n\n\t\t\t// nothing selected?\n\t\t\tif( self.items.length == 0 && self.settings.mode == 'single' ){\n\n\t\t\t\tAddSelected(empty_option, \"\", \"\");\n\n\t\t\t// order selected <option> tags for values in self.items\n\t\t\t}else{\n\n\t\t\t\tself.items.forEach((value)=>{\n\t\t\t\t\toption\t\t\t= self.options[value]!;\n\t\t\t\t\tlabel\t\t\t= option[self.settings.labelField] || '';\n\n\t\t\t\t\tif( selected.includes(option.$option) ){\n\t\t\t\t\t\tconst reuse_opt = self.input.querySelector(`option[value=\"${addSlashes(value)}\"]:not(:checked)`) as HTMLOptionElement;\n\t\t\t\t\t\tAddSelected(reuse_opt, value, label);\n\t\t\t\t\t}else{\n\t\t\t\t\t\toption.$option\t= AddSelected(option.$option, value, label);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t}\n\n\t\t} else {\n\t\t\tself.input.value = self.getValue() as string;\n\t\t}\n\n\t\tif (self.isSetup) {\n\t\t\tif (!opts.silent) {\n\t\t\t\tself.trigger('change', self.getValue() );\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Shows the autocomplete dropdown containing\n\t * the available options.\n\t */\n\topen() {\n\t\tvar self = this;\n\n\t\tif (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return;\n\t\tself.isOpen = true;\n\t\tsetAttr(self.focus_node,{'aria-expanded': 'true'});\n\t\tself.refreshState();\n\t\tapplyCSS(self.dropdown,{visibility: 'hidden', display: 'block'});\n\t\tself.positionDropdown();\n\t\tapplyCSS(self.dropdown,{visibility: 'visible', display: 'block'});\n\t\tself.focus();\n\t\tself.trigger('dropdown_open', self.dropdown);\n\t}\n\n\t/**\n\t * Closes the autocomplete dropdown menu.\n\t */\n\tclose(setTextboxValue=true) {\n\t\tvar self = this;\n\t\tvar trigger = self.isOpen;\n\n\t\tif( setTextboxValue ){\n\n\t\t\t// before blur() to prevent form onchange event\n\t\t\tself.setTextboxValue();\n\n\t\t\tif (self.settings.mode === 'single' && self.items.length) {\n\t\t\t\tself.inputState();\n\t\t\t}\n\t\t}\n\n\t\tself.isOpen = false;\n\t\tsetAttr(self.focus_node,{'aria-expanded': 'false'});\n\t\tapplyCSS(self.dropdown,{display: 'none'});\n\t\tif( self.settings.hideSelected ){\n\t\t\tself.clearActiveOption();\n\t\t}\n\t\tself.refreshState();\n\n\t\tif (trigger) self.trigger('dropdown_close', self.dropdown);\n\t}\n\n\t/**\n\t * Calculates and applies the appropriate\n\t * position of the dropdown if dropdownParent = 'body'.\n\t * Otherwise, position is determined by css\n\t */\n\tpositionDropdown(){\n\n\t\tif( this.settings.dropdownParent !== 'body' ){\n\t\t\treturn;\n\t\t}\n\n\t\tvar context\t\t\t= this.control;\n\t\tvar rect\t\t\t= context.getBoundingClientRect();\n\t\tvar top\t\t\t\t= context.offsetHeight + rect.top  + window.scrollY;\n\t\tvar left\t\t\t= rect.left + window.scrollX;\n\n\n\t\tapplyCSS(this.dropdown,{\n\t\t\twidth : rect.width + 'px',\n\t\t\ttop   : top + 'px',\n\t\t\tleft  : left + 'px'\n\t\t});\n\n\t}\n\n\t/**\n\t * Resets / clears all selected items\n\t * from the control.\n\t *\n\t */\n\tclear(silent?:boolean) {\n\t\tvar self = this;\n\n\t\tif (!self.items.length) return;\n\n\t\tvar items = self.controlChildren();\n\t\titerate(items,(item:TomItem)=>{\n\t\t\tself.removeItem(item,true);\n\t\t});\n\n\t\tself.inputState();\n\t\tif( !silent ) self.updateOriginalInput();\n\t\tself.trigger('clear');\n\t}\n\n\t/**\n\t * A helper method for inserting an element\n\t * at the current caret position.\n\t *\n\t */\n\tinsertAtCaret(el:HTMLElement) {\n\t\tconst self\t\t= this;\n\t\tconst caret\t\t= self.caretPos;\n\t\tconst target\t= self.control;\n\n\t\ttarget.insertBefore(el, target.children[caret] || null);\n\t\tself.setCaret(caret + 1);\n\t}\n\n\t/**\n\t * Removes the current selected item(s).\n\t *\n\t */\n\tdeleteSelection(e:KeyboardEvent):boolean {\n\t\tvar direction, selection, caret, tail;\n\t\tvar self = this;\n\n\t\tdirection = (e && e.keyCode === constants.KEY_BACKSPACE) ? -1 : 1;\n\t\tselection = getSelection(self.control_input);\n\n\n\t\t// determine items that will be removed\n\t\tconst rm_items:TomItem[]\t= [];\n\n\t\tif (self.activeItems.length) {\n\n\t\t\ttail = getTail(self.activeItems, direction);\n\t\t\tcaret = nodeIndex(tail);\n\n\t\t\tif (direction > 0) { caret++; }\n\n\t\t\titerate(self.activeItems, (item:TomItem) => rm_items.push(item) );\n\n\t\t} else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {\n\t\t\tconst items = self.controlChildren();\n\t\t\tlet rm_item;\n\t\t\tif( direction < 0 && selection.start === 0 && selection.length === 0 ){\n\t\t\t\trm_item = items[self.caretPos - 1];\n\n\t\t\t}else if( direction > 0 && selection.start === self.inputValue().length ){\n\t\t\t\trm_item = items[self.caretPos];\n\t\t\t}\n\n\t\t\tif( rm_item !== undefined ){\n\t\t\t\trm_items.push( rm_item );\n\t\t\t}\n\t\t}\n\n\t\tif( !self.shouldDelete(rm_items,e) ){\n\t\t\treturn false;\n\t\t}\n\n\t\tpreventDefault(e,true);\n\n\t\t// perform removal\n\t\tif (typeof caret !== 'undefined') {\n\t\t\tself.setCaret(caret);\n\t\t}\n\n\t\twhile( rm_items.length ){\n\t\t\tself.removeItem(rm_items.pop());\n\t\t}\n\n\t\tself.inputState();\n\t\tself.positionDropdown();\n\t\tself.refreshOptions(false);\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Return true if the items should be deleted\n\t */\n\tshouldDelete(items:TomItem[],evt:MouseEvent|KeyboardEvent){\n\n\t\tconst values = items.map(item => item.dataset.value);\n\n\t\t// allow the callback to abort\n\t\tif( !values.length || (typeof this.settings.onDelete === 'function' && this.settings.onDelete.call(this,values,evt) === false) ){\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Selects the previous / next item (depending on the `direction` argument).\n\t *\n\t * > 0 - right\n\t * < 0 - left\n\t *\n\t */\n\tadvanceSelection(direction:number, e?:MouseEvent|KeyboardEvent) {\n\t\tvar last_active, adjacent, self = this;\n\n\t\tif (self.rtl) direction *= -1;\n\t\tif( self.inputValue().length ) return;\n\n\n\t\t// add or remove to active items\n\t\tif( isKeyDown(constants.KEY_SHORTCUT,e) || isKeyDown('shiftKey',e) ){\n\n\t\t\tlast_active\t\t\t= self.getLastActive(direction);\n\t\t\tif( last_active ){\n\n\t\t\t\tif( !last_active.classList.contains('active') ){\n\t\t\t\t\tadjacent\t\t\t= last_active;\n\t\t\t\t}else{\n\t\t\t\t\tadjacent\t\t\t= self.getAdjacent(last_active,direction,'item');\n\t\t\t\t}\n\n\t\t\t// if no active item, get items adjacent to the control input\n\t\t\t}else if( direction > 0 ){\n\t\t\t\tadjacent\t\t\t= self.control_input.nextElementSibling;\n\t\t\t}else{\n\t\t\t\tadjacent\t\t\t= self.control_input.previousElementSibling;\n\t\t\t}\n\n\n\t\t\tif( adjacent ){\n\t\t\t\tif( adjacent.classList.contains('active') ){\n\t\t\t\t\tself.removeActiveItem(last_active);\n\t\t\t\t}\n\t\t\t\tself.setActiveItemClass(adjacent); // mark as last_active !! after removeActiveItem() on last_active\n\t\t\t}\n\n\t\t// move caret to the left or right\n\t\t}else{\n\t\t\tself.moveCaret(direction);\n\t\t}\n\t}\n\n\tmoveCaret(direction:number){}\n\n\t/**\n\t * Get the last active item\n\t *\n\t */\n\tgetLastActive(direction?:number){\n\n\t\tlet last_active = this.control.querySelector('.last-active');\n\t\tif( last_active ){\n\t\t\treturn last_active;\n\t\t}\n\n\n\t\tvar result = this.control.querySelectorAll('.active');\n\t\tif( result ){\n\t\t\treturn getTail(result,direction);\n\t\t}\n\t}\n\n\n\t/**\n\t * Moves the caret to the specified index.\n\t *\n\t * The input must be moved by leaving it in place and moving the\n\t * siblings, due to the fact that focus cannot be restored once lost\n\t * on mobile webkit devices\n\t *\n\t */\n\tsetCaret(new_pos:number) {\n\t\tthis.caretPos = this.items.length;\n\t}\n\n\t/**\n\t * Return list of item dom elements\n\t *\n\t */\n\tcontrolChildren():TomItem[]{\n\t\treturn Array.from( this.control.querySelectorAll('[data-ts-item]') ) as TomItem[];\n\t}\n\n\t/**\n\t * Disables user input on the control. Used while\n\t * items are being asynchronously created.\n\t */\n\tlock() {\n\t\tthis.setLocked(true);\n\t}\n\n\t/**\n\t * Re-enables user input on the control.\n\t */\n\tunlock() {\n\t\tthis.setLocked(false);\n\t}\n\n\t/**\n\t * Disable or enable user input on the control\n\t */\n\tsetLocked( lock:boolean = this.isReadOnly || this.isDisabled ){\n\t\tthis.isLocked = lock;\n\t\tthis.refreshState();\n\t}\n\n\t/**\n\t * Disables user input on the control completely.\n\t * While disabled, it cannot receive focus.\n\t */\n\tdisable() {\n\t\tthis.setDisabled(true);\n\t\tthis.close();\n\t}\n\n\t/**\n\t * Enables the control so that it can respond\n\t * to focus and user input.\n\t */\n\tenable() {\n\t\tthis.setDisabled(false);\n\t}\n\n\tsetDisabled(disabled:boolean){\n\t\tthis.focus_node.tabIndex\t\t= disabled ? -1 : this.tabIndex;\n\t\tthis.isDisabled\t\t\t\t\t= disabled;\n\t\tthis.input.disabled\t\t\t\t= disabled;\n\t\tthis.control_input.disabled\t\t= disabled;\n\t\tthis.setLocked();\n\t}\n\n\tsetReadOnly(isReadOnly:boolean){\n\t\tthis.isReadOnly\t\t\t\t\t= isReadOnly;\n\t\tthis.input.readOnly\t\t\t\t= isReadOnly;\n\t\tthis.control_input.readOnly\t\t= isReadOnly;\n\t\tthis.setLocked();\n\t}\n\n\t/**\n\t * Completely destroys the control and\n\t * unbinds all event listeners so that it can\n\t * be garbage collected.\n\t */\n\tdestroy() {\n\t\tvar self = this;\n\t\tvar revertSettings = self.revertSettings;\n\n\t\tself.trigger('destroy');\n\t\tself.off();\n\t\tself.wrapper.remove();\n\t\tself.dropdown.remove();\n\n\t\tself.input.innerHTML = revertSettings.innerHTML;\n\t\tself.input.tabIndex = revertSettings.tabIndex;\n\n\t\tremoveClasses(self.input,'tomselected','ts-hidden-accessible');\n\n\t\tself._destroy();\n\n\t\tdelete self.input.tomselect;\n\t}\n\n\t/**\n\t * A helper method for rendering \"item\" and\n\t * \"option\" templates, given the data.\n\t *\n\t */\n\trender( templateName:TomTemplateNames, data?:any ):null|HTMLElement{\n\t\tvar id, html;\n\t\tconst self = this;\n\n\t\tif( typeof this.settings.render[templateName] !== 'function' ){\n\t\t\treturn null;\n\t\t}\n\n\t\t// render markup\n\t\thtml = self.settings.render[templateName].call(this, data, escape_html);\n\n\t\tif( !html ){\n\t\t\treturn null;\n\t\t}\n\n\t\thtml = getDom( html );\n\n\t\t// add mandatory attributes\n\t\tif (templateName === 'option' || templateName === 'option_create') {\n\n\t\t\tif( data[self.settings.disabledField] ){\n\t\t\t\tsetAttr(html,{'aria-disabled':'true'});\n\t\t\t}else{\n\t\t\t\tsetAttr(html,{'data-selectable': ''});\n\t\t\t}\n\n\t\t}else if (templateName === 'optgroup') {\n\t\t\tid = data.group[self.settings.optgroupValueField];\n\t\t\tsetAttr(html,{'data-group': id});\n\t\t\tif(data.group[self.settings.disabledField]) {\n\t\t\t\tsetAttr(html,{'data-disabled': ''});\n\t\t\t}\n\t\t}\n\n\t\tif (templateName === 'option' || templateName === 'item') {\n\t\t\tconst value\t= get_hash(data[self.settings.valueField]);\n\t\t\tsetAttr(html,{'data-value': value });\n\n\n\t\t\t// make sure we have some classes if a template is overwritten\n\t\t\tif( templateName === 'item' ){\n\t\t\t\taddClasses(html,self.settings.itemClass);\n\t\t\t\tsetAttr(html,{'data-ts-item':''});\n\t\t\t}else{\n\t\t\t\taddClasses(html,self.settings.optionClass);\n\t\t\t\tsetAttr(html,{\n\t\t\t\t\trole:'option',\n\t\t\t\t\tid:data.$id\n\t\t\t\t});\n\n\t\t\t\t// update cache\n\t\t\t\tdata.$div = html;\n\t\t\t\tself.options[value] = data;\n\t\t\t}\n\n\n\t\t}\n\n\t\treturn html;\n\n\t}\n\n\n\t/**\n\t * Type guarded rendering\n\t *\n\t */\n\t_render( templateName:TomTemplateNames, data?:any ):HTMLElement{\n\t\tconst html = this.render(templateName, data);\n\n\t\tif( html == null ){\n\t\t\tthrow 'HTMLElement expected';\n\t\t}\n\t\treturn html;\n\t}\n\n\n\t/**\n\t * Clears the render cache for a template. If\n\t * no template is given, clears all render\n\t * caches.\n\t *\n\t */\n\tclearCache():void{\n\n\t\titerate(this.options, (option:TomOption)=>{\n\t\t\tif( option.$div ){\n\t\t\t\toption.$div.remove();\n\t\t\t\tdelete option.$div;\n\t\t\t}\n\t\t});\n\n\t}\n\n\t/**\n\t * Removes a value from item and option caches\n\t *\n\t */\n\tuncacheValue(value:string){\n\n\t\tconst option_el\t\t\t= this.getOption(value);\n\t\tif( option_el ) option_el.remove();\n\n\t}\n\n\t/**\n\t * Determines whether or not to display the\n\t * create item prompt, given a user input.\n\t *\n\t */\n\tcanCreate( input:string ):boolean {\n\t\treturn this.settings.create && (input.length > 0) && (this.settings.createFilter as TomCreateFilter ).call(this, input);\n\t}\n\n\n\t/**\n\t * Wraps this.`method` so that `new_fn` can be invoked 'before', 'after', or 'instead' of the original method\n\t *\n\t * this.hook('instead','onKeyDown',function( arg1, arg2 ...){\n\t *\n\t * });\n\t */\n\thook( when:string, method:string, new_fn:any ){\n\t\tvar self = this;\n\t\tvar orig_method = self[method];\n\n\n\t\tself[method] = function(){\n\t\t\tvar result, result_new;\n\n\t\t\tif( when === 'after' ){\n\t\t\t\tresult = orig_method.apply(self, arguments);\n\t\t\t}\n\n\t\t\tresult_new = new_fn.apply(self, arguments );\n\n\t\t\tif( when === 'instead' ){\n\t\t\t\treturn result_new;\n\t\t\t}\n\n\t\t\tif( when === 'before' ){\n\t\t\t\tresult = orig_method.apply(self, arguments);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t};\n\n\t}\n\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "/**\n * Plugin: \"change_listener\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { addEvent } from '../../utils.ts';\n\nexport default function(this:TomSelect) {\n\taddEvent(this.input,'change',()=>{\n\t\tthis.sync();\n\t});\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"checkbox_options\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { TomTemplate } from '../../types/index.ts';\nimport { preventDefault, hash_key } from '../../utils.ts';\nimport { getDom } from '../../vanilla.ts';\nimport { CBOptions } from './types.ts';\n\n\nexport default function(this:TomSelect, userOptions:CBOptions) {\n\tvar self = this;\n\tvar orig_onOptionSelect = self.onOptionSelect;\n\n\tself.settings.hideSelected = false;\n\n\tconst cbOptions : CBOptions = Object.assign({\n\t\t// so that the user may add different ones as well\n\t\tclassName             : \"tomselect-checkbox\",\n\n\t\t// the following default to the historic plugin's values\n\t\tcheckedClassNames     : undefined,\n\t\tuncheckedClassNames   : undefined,\n\t}, userOptions);\n\n\n\tvar UpdateChecked = function(checkbox:HTMLInputElement, toCheck : boolean) {\n\t\tif( toCheck ){\n\t\t\tcheckbox.checked = true;\n\t\t\tif (cbOptions.uncheckedClassNames) {\n\t\t\t\tcheckbox.classList.remove(...cbOptions.uncheckedClassNames);\n\t\t\t}\n\t\t\tif (cbOptions.checkedClassNames) {\n\t\t\t\tcheckbox.classList.add(...cbOptions.checkedClassNames);\n\t\t\t}\n\t\t}else{\n\t\t\tcheckbox.checked = false;\n\t\t\tif (cbOptions.checkedClassNames) {\n\t\t\t\tcheckbox.classList.remove(...cbOptions.checkedClassNames);\n\t\t\t}\n\t\t\tif (cbOptions.uncheckedClassNames) {\n\t\t\t\tcheckbox.classList.add(...cbOptions.uncheckedClassNames);\n\t\t\t}\n\t\t}\n\t}\n\n\t// update the checkbox for an option\n\tvar UpdateCheckbox = function(option:HTMLElement){\n\t\tsetTimeout(()=>{\n\t\t\tvar checkbox = option.querySelector('input.' + cbOptions.className);\n\t\t\tif( checkbox instanceof HTMLInputElement ){\n\t\t\t\tUpdateChecked(checkbox, option.classList.contains('selected'));\n\t\t\t}\n\t\t},1);\n\t};\n\n\t// add checkbox to option template\n\tself.hook('after','setupTemplates',() => {\n\n\t\tvar orig_render_option = self.settings.render.option;\n\n\t\tself.settings.render.option = ((data, escape_html) => {\n\t\t\tvar rendered = getDom(orig_render_option.call(self, data, escape_html));\n\t\t\tvar checkbox = document.createElement('input');\n\t\t\tif (cbOptions.className) {\n\t\t\t\tcheckbox.classList.add(cbOptions.className);\n\t\t\t}\n\t\t\tcheckbox.addEventListener('click',function(evt){\n\t\t\t\tpreventDefault(evt);\n\t\t\t});\n\n\t\t\tcheckbox.type = 'checkbox';\n\t\t\tconst hashed = hash_key(data[self.settings.valueField]);\n\n\t\t\tUpdateChecked(checkbox, !!(hashed && self.items.indexOf(hashed) > -1) );\n\n\t\t\trendered.prepend(checkbox);\n\t\t\treturn rendered;\n\t\t}) satisfies TomTemplate;\n\t});\n\n\t// uncheck when item removed\n\tself.on('item_remove',(value:string) => {\n\t\tvar option = self.getOption(value);\n\n\t\tif( option ){ // if dropdown hasn't been opened yet, the option won't exist\n\t\t\toption.classList.remove('selected'); // selected class won't be removed yet\n\t\t\tUpdateCheckbox(option);\n\t\t}\n\t});\n\n\t// check when item added\n\tself.on('item_add',(value:string) => {\n\t\tvar option = self.getOption(value);\n\n\t\tif( option ){ // if dropdown hasn't been opened yet, the option won't exist\n\t\t\tUpdateCheckbox(option);\n\t\t}\n\t});\n\n\n\t// remove items when selected option is clicked\n\tself.hook('instead','onOptionSelect',( evt:KeyboardEvent, option:HTMLElement )=>{\n\n\t\tif( option.classList.contains('selected') ){\n\t\t\toption.classList.remove('selected')\n\t\t\tself.removeItem(option.dataset.value);\n\t\t\tself.refreshOptions();\n\t\t\tpreventDefault(evt,true);\n\t\t\treturn;\n        }\n\n\t\torig_onOptionSelect.call(self, evt, option);\n\n\t\tUpdateCheckbox(option);\n\t});\n\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"dropdown_header\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { getDom } from '../../vanilla.ts';\nimport { CBOptions } from './types.ts';\n\nexport default function(this:TomSelect, userOptions:CBOptions) {\n\tconst self = this;\n\n\tconst options = Object.assign({\n\t\tclassName: 'clear-button',\n\t\ttitle: 'Clear All',\n\t\trole: 'button',\n\t\ttabindex: 0,\n\t\thtml: (data:CBOptions) => {\n\n\t\treturn `<div class=\"${data.className}\" title=\"${data.title}\" role=\"${data.role}\" tabindex=\"${data.tabindex}\">&times;</div>`;\n\t\t}\n\t}, userOptions);\n\n\tself.on('initialize',()=>{\n\t\tvar button = getDom(options.html(options));\n\t\tbutton.addEventListener('click',(evt)=>{\n\n\t\t\tif( self.isLocked ) return;\n\n\t\t\tself.clear();\n\n\t\t\tif( self.settings.mode === 'single' && self.settings.allowEmptyOption ){\n\t\t\t\tself.addItem('');\n\t\t\t}\n\t\t\t\n\t\t\tself.refreshOptions(false);\n\n\t\t\tevt.preventDefault();\n\t\t\tevt.stopPropagation();\n\t\t});\n\t\tself.control.appendChild(button);\n\t});\n\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"drag_drop\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { TomOption, TomItem } from '../../types/index.ts';\nimport { escape_html, preventDefault, addEvent } from '../../utils.ts';\nimport { getDom, setAttr } from '../../vanilla.ts';\n\n\nconst insertAfter = (referenceNode:Element, newNode:Element) => {\n\treferenceNode.parentNode?.insertBefore(newNode, referenceNode.nextSibling);\n}\n\nconst insertBefore = (referenceNode:Element, newNode:Element) => {\n\treferenceNode.parentNode?.insertBefore(newNode, referenceNode);\n}\n\nconst isBefore = (referenceNode:Element|undefined|null, newNode:Element|undefined|null) =>{\n\t\n\tdo{\n\t\tnewNode = newNode?.previousElementSibling;\n\n\t\tif( referenceNode == newNode ){\n\t\t\treturn true;\n\t\t}\n\n\t}while( newNode && newNode.previousElementSibling );\n\n\treturn false;\n}\n\nexport default function(this:TomSelect) {\n\tvar self = this;\n\tif (self.settings.mode !== 'multi') return;\n\n\tvar orig_lock\t\t= self.lock;\n\tvar orig_unlock\t\t= self.unlock;\n\tlet sortable = true;\n\t\tlet drag_item:TomItem|undefined;\n\n\n\t/**\n\t * Add draggable attribute to item\n\t */\n\tself.hook('after','setupTemplates',() => {\n\n\t\tvar orig_render_item = self.settings.render.item;\n\n\t\tself.settings.render.item = (data:TomOption, escape:typeof escape_html) => {\n\t\t\tconst item = getDom(orig_render_item.call(self, data, escape)) as TomItem;\n\t\t\tsetAttr(item,{'draggable':'true'});\n\n\n\t\t\t// prevent doc_mousedown (see tom-select.ts)\n\t\t\tconst mousedown = (evt:Event) => {\n\t\t\t\tif( !sortable ) preventDefault(evt);\n\t\t\t\tevt.stopPropagation();\n\t\t\t}\n\n\t\t\tconst dragStart = (evt:Event) => {\n\t\t\t\tdrag_item = item;\n\t\t\t\t\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\titem.classList.add('ts-dragging');\n\t\t\t\t}, 0);\n\t\t\t\t\n\t\t\t}\n\n\t\t\tconst dragOver = (evt:Event) =>{\n\t\t\t\tevt.preventDefault();\n\t\t\t\titem.classList.add('ts-drag-over');\n\t\t\t\tmoveitem(item,drag_item);\n\t\t\t}\n\n\t\t\tconst dragLeave = () => {\n\t\t\t\titem.classList.remove('ts-drag-over');\n\t\t\t}\n\n\t\t\tconst moveitem = (targetitem:TomItem, dragitem:TomItem|undefined) => {\n\t\t\t\tif( dragitem === undefined ) return;\n\t\t\t\t\n\t\t\t\tif( isBefore(dragitem,item) ){\n\t\t\t\t\tinsertAfter(targetitem,dragitem);\n\t\t\t\t}else{\n\t\t\t\t\tinsertBefore(targetitem,dragitem);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst dragend = () => {\n\t\t\t\tdocument.querySelectorAll('.ts-drag-over').forEach(el=> el.classList.remove('ts-drag-over'));\n\t\t\t\tdrag_item?.classList.remove('ts-dragging');\n\t\t\t\tdrag_item = undefined;\n\n\t\t\t\tvar values:string[] = [];\n\t\t\t\tself.control.querySelectorAll(`[data-value]`).forEach((el:Element)=> {\n\t\t\t\t\tif( (<HTMLOptionElement>el).dataset.value ){\n\t\t\t\t\t\tlet value = (<HTMLOptionElement>el).dataset.value;\n\t\t\t\t\t\tif( value ){\n\t\t\t\t\t\t\tvalues.push(value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tself.setValue(values);\n\t\t\t}\t\n\n\n\t\t\taddEvent(item,'mousedown', mousedown);\n\t\t\taddEvent(item,'dragstart', dragStart);\n\t\t\taddEvent(item,'dragenter', dragOver)\n\t\t\taddEvent(item,'dragover', dragOver);\n\t\t\taddEvent(item,'dragleave', dragLeave);\n\t\t\taddEvent(item,'dragend', dragend);\n\t\t\t\t\n\t\t\treturn item;\n\t\t}\t\n\t});\n\n\n\n\tself.hook('instead','lock',()=>{\n\t\tsortable = false;\n\t\treturn orig_lock.call(self);\n\t});\n\n\tself.hook('instead','unlock',()=>{\n\t\tsortable = true;\n\t\treturn orig_unlock.call(self);\n\t});\n\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"dropdown_header\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { getDom } from '../../vanilla.ts';\nimport { preventDefault } from '../../utils.ts';\nimport { DHOptions } from './types.ts';\n\nexport default function(this:TomSelect, userOptions:DHOptions) {\n\tconst self = this;\n\n\tconst options = Object.assign({\n\t\ttitle         : 'Untitled',\n\t\theaderClass   : 'dropdown-header',\n\t\ttitleRowClass : 'dropdown-header-title',\n\t\tlabelClass    : 'dropdown-header-label',\n\t\tcloseClass    : 'dropdown-header-close',\n\n\t\thtml: (data:DHOptions) => {\n\t\t\treturn (\n\t\t\t\t'<div class=\"' + data.headerClass + '\">' +\n\t\t\t\t\t'<div class=\"' + data.titleRowClass + '\">' +\n\t\t\t\t\t\t'<span class=\"' + data.labelClass + '\">' + data.title + '</span>' +\n\t\t\t\t\t\t'<a class=\"' + data.closeClass + '\">&times;</a>' +\n\t\t\t\t\t'</div>' +\n\t\t\t\t'</div>'\n\t\t\t);\n\t\t}\n\t}, userOptions);\n\n\tself.on('initialize',()=>{\n\t\tvar header = getDom(options.html(options));\n\n\t\tvar close_link = header.querySelector('.'+options.closeClass);\n\t\tif( close_link ){\n\t\t\tclose_link.addEventListener('click',(evt)=>{\n\t\t\t\tpreventDefault(evt,true);\n\t\t\t\tself.close();\n\t\t\t});\n\t\t}\n\n\t\tself.dropdown.insertBefore(header, self.dropdown.firstChild);\n\t});\n\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"dropdown_input\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { nodeIndex, removeClasses } from '../../vanilla.ts';\n\n\nexport default function(this:TomSelect) {\n\tvar self = this;\n\n\t/**\n\t * Moves the caret to the specified index.\n\t *\n\t * The input must be moved by leaving it in place and moving the\n\t * siblings, due to the fact that focus cannot be restored once lost\n\t * on mobile webkit devices\n\t *\n\t */\n\tself.hook('instead','setCaret',(new_pos:number) => {\n\n\t\tif( self.settings.mode === 'single' || !self.control.contains(self.control_input) ) {\n\t\t\tnew_pos = self.items.length;\n\t\t} else {\n\t\t\tnew_pos = Math.max(0, Math.min(self.items.length, new_pos));\n\n\t\t\tif( new_pos != self.caretPos && !self.isPending ){\n\n\t\t\t\tself.controlChildren().forEach((child,j) => {\n\t\t\t\t\tif( j < new_pos ){\n\t\t\t\t\t\tself.control_input.insertAdjacentElement('beforebegin', child );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tself.control.appendChild( child );\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tself.caretPos = new_pos;\n\t});\n\n\tself.hook('instead','moveCaret',(direction:number) => {\n\n\t\tif( !self.isFocused ) return;\n\n\t\t// move caret before or after selected items\n\t\tconst last_active\t\t= self.getLastActive(direction);\n\t\tif( last_active ){\n\t\t\tconst idx = nodeIndex(last_active);\n\t\t\tself.setCaret(direction > 0 ? idx + 1: idx);\n\t\t\tself.setActiveItem();\n\t\t\tremoveClasses(last_active as HTMLElement,'last-active');\n\n\t\t// move caret left or right of current position\n\t\t}else{\n\t\t\tself.setCaret(self.caretPos + direction);\n\n\t\t}\n\n\t});\n\n};\n", "export const KEY_A\t\t\t\t= 65;\nexport const KEY_RETURN\t\t\t= 13;\nexport const KEY_ESC\t\t\t= 27;\nexport const KEY_LEFT\t\t\t= 37;\nexport const KEY_UP\t\t\t\t= 38;\nexport const KEY_RIGHT\t\t\t= 39;\nexport const KEY_DOWN\t\t\t= 40;\nexport const KEY_BACKSPACE\t\t= 8;\nexport const KEY_DELETE\t\t\t= 46;\nexport const KEY_TAB\t\t\t= 9;\n\nexport const IS_MAC      \t\t= typeof navigator === 'undefined' ? false : /Mac/.test(navigator.userAgent);\nexport const KEY_SHORTCUT\t\t= IS_MAC ? 'metaKey' : 'ctrlKey'; // ctrl key or apple key for ma\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"dropdown_input\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport * as constants from '../../constants.ts';\nimport { getDom, addClasses } from '../../vanilla.ts';\nimport { addEvent, preventDefault } from '../../utils.ts';\n\n\nexport default function(this:TomSelect) {\n\tconst self = this;\n\n\tself.settings.shouldOpen = true; // make sure the input is shown even if there are no options to display in the dropdown\n\n\tself.hook('before','setup',()=>{\n\t\tself.focus_node\t\t= self.control;\n\n\t\taddClasses( self.control_input, 'dropdown-input');\n\n\t \tconst div = getDom('<div class=\"dropdown-input-wrap\">');\n\t\tdiv.append(self.control_input);\n\t\tself.dropdown.insertBefore(div, self.dropdown.firstChild);\n\n\t\t// set a placeholder in the select control\n\t\tconst placeholder = getDom('<input class=\"items-placeholder\" tabindex=\"-1\" />') as HTMLInputElement;\n\t\tplaceholder.placeholder = self.settings.placeholder ||'';\n\t\tself.control.append(placeholder);\n\t\t/**\n\t\t * TomSelect renders a custom control with a focusable <input class=\"items-placeholder\">.\n\t\t * The source <select>'s aria-label is not automatically propagated to that input,\n\t\t * which triggers \"Missing form label\" accessibility warnings.\n\t\t * This helper copies the label from the <select> onto the generated input.\n\t\t */\n\t\tconst label = self.input?.getAttribute('aria-label');\n\t\tif (!label) return;\n\t\tplaceholder.setAttribute('aria-label', label);\n\t});\n\n\tself.on('initialize',()=>{\n\t\t// set tabIndex on control to -1, otherwise [shift+tab] will put focus right back on control_input\n\t\tself.control_input.addEventListener('keydown',(evt:KeyboardEvent) =>{\n\t\t//addEvent(self.control_input,'keydown' as const,(evt:KeyboardEvent) =>{\n\t\t\tswitch( evt.keyCode ){\n\t\t\t\tcase constants.KEY_ESC:\n\t\t\t\t\tif (self.isOpen) {\n\t\t\t\t\t\tpreventDefault(evt,true);\n\t\t\t\t\t\tself.close();\n\t\t\t\t\t}\n\t\t\t\t\tself.clearActiveItems();\n\t\t\t\treturn;\n\t\t\t\tcase constants.KEY_TAB:\n\t\t\t\t\tself.focus_node.tabIndex = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn self.onKeyDown.call(self,evt);\n\t\t});\n\n\t\tself.on('blur',()=>{\n\t\t\tself.focus_node.tabIndex = self.isDisabled ? -1 : self.tabIndex;\n\t\t});\n\n\n\t\t// give the control_input focus when the dropdown is open\n\t\tself.on('dropdown_open',() =>{\n\t\t\tself.control_input.focus();\n\t\t});\n\n\t\t// prevent onBlur from closing when focus is on the control_input\n\t\tconst orig_onBlur = self.onBlur;\n\t\tself.hook('instead','onBlur',(evt?:FocusEvent)=>{\n\t\t\tif( evt && evt.relatedTarget == self.control_input ) return;\n\t\t\treturn orig_onBlur.call(self);\n\t\t});\n\n\t\taddEvent(self.control_input,'blur', () => self.onBlur() );\n\n\t\t// return focus to control to allow further keyboard input\n\t\tself.hook('before','close',() =>{\n\n\t\t\tif( !self.isOpen ) return;\n\t\t\tself.focus_node.focus({preventScroll: true});\n\t\t});\n\n\t});\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "/**\n * Plugin: \"input_autogrow\" (Tom Select)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { addEvent } from '../../utils.ts';\n\nexport default function(this:TomSelect) {\n\tvar self\t\t\t\t\t= this;\n\n\tself.on('initialize',()=>{\n\n\n\t\tvar test_input\t\t\t\t= document.createElement('span');\n\t\tvar control\t\t\t\t\t= self.control_input;\n\t\ttest_input.style.cssText\t= 'position:absolute; top:-99999px; left:-99999px; width:auto; padding:0; white-space:pre; ';\n\n\t\tself.wrapper.appendChild(test_input);\n\n\n\t\tvar transfer_styles\t\t\t= [ 'letterSpacing', 'fontSize', 'fontFamily', 'fontWeight', 'textTransform' ];\n\n\t\tfor( const style_name of transfer_styles ){\n\t\t\t// @ts-ignore TS7015 https://stackoverflow.com/a/50506154/697576\n\t\t\ttest_input.style[style_name] = control.style[style_name];\n\t\t}\n\n\n\t\t/**\n\t\t * Set the control width\n\t\t *\n\t\t */\n\t\tvar resize = ()=>{\n\t\t\ttest_input.textContent\t= control.value;\n\t\t\tcontrol.style.width\t\t= test_input.clientWidth+'px';\n\t\t};\n\n\t\tresize();\n\t\tself.on('update item_add item_remove',resize);\n\t\taddEvent(control,'input', resize );\n\t\taddEvent(control,'keyup', resize );\n\t\taddEvent(control,'blur', resize );\n\t\taddEvent(control,'update', resize );\n\t});\n\n};\n", "/**\n * Plugin: \"input_autogrow\" (Tom Select)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\n\nexport default function(this:TomSelect) {\n\tvar self = this;\n\tvar orig_deleteSelection = self.deleteSelection;\n\n\tthis.hook('instead','deleteSelection',(evt:KeyboardEvent) => {\n\n\t\tif( self.activeItems.length ){\n\t\t\treturn orig_deleteSelection.call(self, evt);\n\t\t}\n\n\t\treturn false;\n\t});\n\n};\n", "/**\n * Plugin: \"no_active_items\" (Tom Select)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\n\nexport default function(this:TomSelect) {\n\tthis.hook('instead','setActiveItem',() => {});\n\tthis.hook('instead','selectAll',() => {});\n};\n", "export const KEY_A\t\t\t\t= 65;\nexport const KEY_RETURN\t\t\t= 13;\nexport const KEY_ESC\t\t\t= 27;\nexport const KEY_LEFT\t\t\t= 37;\nexport const KEY_UP\t\t\t\t= 38;\nexport const KEY_RIGHT\t\t\t= 39;\nexport const KEY_DOWN\t\t\t= 40;\nexport const KEY_BACKSPACE\t\t= 8;\nexport const KEY_DELETE\t\t\t= 46;\nexport const KEY_TAB\t\t\t= 9;\n\nexport const IS_MAC      \t\t= typeof navigator === 'undefined' ? false : /Mac/.test(navigator.userAgent);\nexport const KEY_SHORTCUT\t\t= IS_MAC ? 'metaKey' : 'ctrlKey'; // ctrl key or apple key for ma\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"optgroup_columns\" (Tom Select.js)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport * as constants from '../../constants.ts';\nimport { parentMatch, nodeIndex } from '../../vanilla.ts';\n\nexport default function(this:TomSelect) {\n\tvar self = this;\n\n\tvar orig_keydown = self.onKeyDown;\n\n\tself.hook('instead','onKeyDown',(evt:KeyboardEvent)=>{\n\t\tvar index, option, options, optgroup;\n\n\t\tif( !self.isOpen || !(evt.keyCode === constants.KEY_LEFT || evt.keyCode === constants.KEY_RIGHT)) {\n\t\t\treturn orig_keydown.call(self,evt);\n\t\t}\n\n\t\tself.ignoreHover\t= true;\n\t\toptgroup\t\t\t= parentMatch(self.activeOption,'[data-group]');\n\t\tindex\t\t\t\t= nodeIndex(self.activeOption,'[data-selectable]');\n\n\t\tif( !optgroup ){\n\t\t\treturn;\n\t\t}\n\n\t\tif( evt.keyCode === constants.KEY_LEFT ){\n\t\t\toptgroup = optgroup.previousSibling;\n\t\t} else {\n\t\t\toptgroup = optgroup.nextSibling;\n\t\t}\n\n\t\tif( !optgroup ){\n\t\t\treturn;\n\t\t}\n\n\t\toptions\t\t\t\t= (<HTMLOptGroupElement>optgroup).querySelectorAll('[data-selectable]');\n\t\toption\t\t\t\t= options[ Math.min(options.length - 1, index) ] as HTMLElement;\n\n\t\tif( option ){\n\t\t\tself.setActiveOption(option);\n\t\t}\n\n\t});\n\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"remove_button\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { getDom } from '../../vanilla.ts';\nimport { escape_html, preventDefault, addEvent } from '../../utils.ts';\nimport { TomOption, TomItem } from '../../types/index.ts';\nimport { RBOptions } from './types.ts';\n\nexport default function(this:TomSelect, userOptions:RBOptions) {\n\tconst self = this;\n\n\tconst options = Object.assign({\n\t\t\tlabel     : '×',\n\t\t\ttitle     : 'Remove',\n\t\t\tclassName : 'remove',\n\t\t\ttabindex  : -1,\n\t\t\trole      : 'button',\n\t\t\thtml      : (data:RBOptions) => {\n\t\t\t\tconst el = document.createElement('div');\n\n\t\t\t\tel.className = data.className || '';\n\t\t\t\tel.title = data.title || '';\n\t\t\t\tel.setAttribute('role', data.role || 'button');\n\t\t\t\tel.tabIndex = data.tabindex ?? -1;\n\t\t\t\tel.textContent = data.label || '';\n\n\t\t\t\treturn el;\n\t\t\t}\n\t\t}, userOptions);\n\n\n\tself.hook('after','setupTemplates',() => {\n\n\t\tvar orig_render_item = self.settings.render.item;\n\n\t\tself.settings.render.item = (data:TomOption, escape:typeof escape_html) => {\n\n\t\t\tvar item = getDom(orig_render_item.call(self, data, escape)) as TomItem;\n\n\t\t\tvar close_button = getDom(options.html(options));\n\t\t\titem.appendChild(close_button);\n\n\t\t\taddEvent(close_button,'mousedown',(evt) => {\n\t\t\t\tpreventDefault(evt,true);\n\t\t\t});\n\n\t\t\taddEvent(close_button,'click',(evt) => {\n\n\t\t\t\tif( self.isLocked ) return;\n\n\t\t\t\t// propagating will trigger the dropdown to show for single mode\n\t\t\t\tpreventDefault(evt,true);\n\n\t\t\t\tif( self.isLocked ) return;\n\t\t\t\tif( !self.shouldDelete([item],evt as MouseEvent) ) return;\n\n\t\t\t\tself.removeItem(item);\n\t\t\t\tself.refreshOptions(false);\n\t\t\t\tself.inputState();\n\t\t\t});\n\n\t\t\treturn item;\n\t\t};\n\n\t});\n\n\n};\n", "/**\n * Plugin: \"restore_on_backspace\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\nimport type TomSelect from '../../tom-select.ts';\nimport { TomOption } from '../../types/index.ts';\n\ntype TPluginOptions = {\n\ttext?:(option:TomOption)=>string,\n};\n\nexport default function(this:TomSelect, userOptions:TPluginOptions) {\n\tconst self = this;\n\n\tconst options = Object.assign({\n\t\ttext: (option:TomOption) => {\n\t\t\treturn option[self.settings.labelField];\n\t\t}\n\t},userOptions);\n\n\tself.on('item_remove',function(value:string){\n\t\tif( !self.isFocused ){\n\t\t\treturn;\n\t\t}\n\n\t\tif( self.control_input.value.trim() === '' ){\n\t\t\tvar option = self.options[value];\n\t\t\tif( option ){\n\t\t\t\tself.setTextboxValue(options.text.call(self, option));\n\t\t\t}\n\t\t}\n\t});\n\n};\n", "\nimport type TomSelect from './tom-select.ts';\nimport { TomLoadCallback } from './types/index.ts';\n\n\n/**\n * Converts a scalar to its best string representation\n * for hash keys and HTML attribute values.\n *\n * Transformations:\n *   'str'     -> 'str'\n *   null      -> ''\n *   undefined -> ''\n *   true      -> '1'\n *   false     -> '0'\n *   0         -> '0'\n *   1         -> '1'\n *\n */\nexport const hash_key = (value:undefined|null|boolean|string|number):string|null => {\n\tif (typeof value === 'undefined' || value === null) return null;\n\treturn get_hash(value);\n};\n\nexport const get_hash = (value:boolean|string|number):string => {\n\tif (typeof value === 'boolean') return value ? '1' : '0';\n\treturn value + '';\n};\n\n/**\n * Escapes a string for use within HTML.\n *\n */\nexport const escape_html = (str:string):string => {\n\treturn (str + '')\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n};\n\n\n/**\n * use setTimeout if timeout > 0 \n */\nexport const timeout = (fn:()=>void,timeout:number): number | null => {\n\tif( timeout > 0 ){\n\t\treturn window.setTimeout(fn,timeout);\n\t}\n\n\tfn.call(null);\n\treturn null;\n}\n\n/**\n * Debounce the user provided load function\n *\n */\nexport const loadDebounce = (fn:(value:string,callback:TomLoadCallback) => void,delay:number) => {\n\tvar timeout: null|ReturnType<typeof setTimeout>;\n\treturn function(this:TomSelect, value:string,callback:TomLoadCallback) {\n\t\tvar self = this;\n\n\t\tif( timeout ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\ttimeout = setTimeout(function() {\n\t\t\ttimeout = null;\n\t\t\tself.loadedSearches[value] = true;\n\t\t\tfn.call(self, value, callback);\n\n\t\t}, delay);\n\t};\n};\n\n\n/**\n * Debounce all fired events types listed in `types`\n * while executing the provided `fn`.\n *\n */\nexport const debounce_events = ( self:TomSelect, types:string[], fn:() => void ) => {\n\tvar type:string;\n\tvar trigger = self.trigger;\n\tvar event_args:{ [key: string]: any } = {};\n\n\t// override trigger method\n\tself.trigger = function(){\n\t\tvar type = arguments[0];\n\t\tif (types.indexOf(type) !== -1) {\n\t\t\tevent_args[type] = arguments;\n\t\t} else {\n\t\t\treturn trigger.apply(self, arguments);\n\t\t}\n\t};\n\n\t// invoke provided function\n\tfn.apply(self, []);\n\tself.trigger = trigger;\n\n\t// trigger queued events\n\tfor( type of types ){\n\t\tif( type in event_args ){\n\t\t\ttrigger.apply(self, event_args[type]);\n\t\t}\n\t}\n};\n\n\n/**\n * Determines the current selection within a text input control.\n * Returns an object containing:\n *   - start\n *   - length\n *\n * Note: \"selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password\"\n * \t- https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n */\nexport const getSelection = (input:HTMLInputElement):{ start: number; length: number } => {\n\treturn {\n\t\tstart\t: input.selectionStart || 0,\n\t\tlength\t: (input.selectionEnd||0) - (input.selectionStart||0),\n\t};\n};\n\n\n/**\n * Prevent default\n *\n */\nexport const preventDefault = (evt?:Event, stop:boolean=false):void => {\n\tif( evt ){\n\t\tevt.preventDefault();\n\t\tif( stop ){\n\t\t\tevt.stopPropagation();\n\t\t}\n\t}\n}\n\n\n/**\n * Add event helper\n *\n */\nexport const addEvent = (target:EventTarget, type:string, callback:EventListenerOrEventListenerObject, options?:object):void => {\n\ttarget.addEventListener(type,callback,options);\n};\n\n\n/**\n * Return true if the requested key is down\n * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )\n * The current evt may not always set ( eg calling advanceSelection() )\n *\n */\nexport const isKeyDown = ( key_name:keyof (KeyboardEvent|MouseEvent), evt?:KeyboardEvent|MouseEvent ) => {\n\n\tif( !evt ){\n\t\treturn false;\n\t}\n\n\tif( !evt[key_name] ){\n\t\treturn false;\n\t}\n\n\tvar count = (evt.altKey?1:0) + (evt.ctrlKey?1:0) + (evt.shiftKey?1:0) + (evt.metaKey?1:0);\n\n\tif( count === 1 ){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n\n/**\n * Get the id of an element\n * If the id attribute is not set, set the attribute with the given id\n *\n */\nexport const getId = (el:Element,id:string) => {\n\tconst existing_id = el.getAttribute('id');\n\tif( existing_id ){\n\t\treturn existing_id;\n\t}\n\n\tel.setAttribute('id',id);\n\treturn id;\n};\n\n\n/**\n * Returns a string with backslashes added before characters that need to be escaped.\n */\nexport const addSlashes = (str:string):string => {\n\treturn str.replace(/[\\\\\"']/g, '\\\\$&');\n};\n\n/**\n *\n */\nexport const append = ( parent:Element|DocumentFragment, node: string|Node|null|undefined ):void =>{\n\tif( node ) parent.append(node);\n};\n\n/**\n * Iterates over arrays and hashes.\n *\n * ```\n * iterate(this.items, function(item, id) {\n *    // invoked for each item\n * });\n * ```\n *\n */\nexport const iterate = (object:[]|{[key:string]:any}, callback:(value:any,key:any)=>any) => {\n\n\tif ( Array.isArray(object)) {\n\t\tobject.forEach(callback);\n\n\t}else{\n\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)) {\n\t\t\t\tcallback(object[key], key);\n\t\t\t}\n\t\t}\n\t}\n};\n", "\nimport { iterate } from './utils.ts';\n\n/**\n * Return a dom element from either a dom query string, jQuery object, a dom element or html string\n * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518\n *\n * param query should be {}\n */\nexport const getDom = ( query:any ):HTMLElement => {\n\n\tif( query.jquery ){\n\t\treturn query[0];\n\t}\n\n\tif( query instanceof HTMLElement ){\n\t\treturn query;\n\t}\n\n\tif( isHtmlString(query) ){\n\t\tvar tpl = document.createElement('template');\n\t\ttpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result\n\t\treturn tpl.content.firstChild as HTMLElement;\n\t}\n\n\treturn document.querySelector(query);\n};\n\nexport const isHtmlString = (arg:any): boolean => {\n\tif( typeof arg === 'string' && arg.indexOf('<') > -1 ){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport const escapeQuery = (query:string):string => {\n\treturn query.replace(/['\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Dispatch an event\n *\n */\nexport const triggerEvent = ( dom_el:HTMLElement, event_name:string ):void => {\n\tvar event = document.createEvent('HTMLEvents');\n\tevent.initEvent(event_name, true, false);\n\tdom_el.dispatchEvent(event)\n};\n\n/**\n * Apply CSS rules to a dom element\n *\n */\nexport const applyCSS = ( dom_el:HTMLElement, css:{ [key: string]: string|number }):void => {\n\tObject.assign(dom_el.style, css);\n}\n\n\n/**\n * Add css classes\n *\n */\nexport const addClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n\tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map( cls => {\n\t\t\tel.classList.add( cls );\n\t\t});\n\t});\n}\n\n/**\n * Remove css classes\n *\n */\n export const removeClasses = ( elmts:HTMLElement|HTMLElement[], ...classes:string[]|string[][] ) => {\n\n \tvar norm_classes \t= classesArray(classes);\n\telmts\t\t\t\t= castAsArray(elmts);\n\n\telmts.map( el => {\n\t\tnorm_classes.map(cls => {\n\t \t\tel.classList.remove( cls );\n\t\t});\n \t});\n }\n\n\n/**\n * Return arguments\n *\n */\nexport const classesArray = (args:string[]|string[][]):string[] => {\n\tvar classes:string[] = [];\n\titerate( args, (_classes) =>{\n\t\tif( typeof _classes === 'string' ){\n\t\t\t_classes = _classes.trim().split(/[\\t\\n\\f\\r\\s]/);\n\t\t}\n\t\tif( Array.isArray(_classes) ){\n\t\t\tclasses = classes.concat(_classes);\n\t\t}\n\t});\n\n\treturn classes.filter(Boolean);\n}\n\n\n/**\n * Create an array from arg if it's not already an array\n *\n */\nexport const castAsArray = (arg:any):Array<any> => {\n\tif( !Array.isArray(arg) ){\n \t\targ = [arg];\n \t}\n\treturn arg;\n}\n\n\n/**\n * Get the closest node to the evt.target matching the selector\n * Stops at wrapper\n *\n */\nexport const parentMatch = ( target:null|HTMLElement, selector:string, wrapper?:HTMLElement ):HTMLElement|void => {\n\n\tif( wrapper && !wrapper.contains(target) ){\n\t\treturn;\n\t}\n\n\twhile( target && target.matches ){\n\n\t\tif( target.matches(selector) ){\n\t\t\treturn target;\n\t\t}\n\n\t\ttarget = target.parentNode as HTMLElement;\n\t}\n}\n\n\n/**\n * Get the first or last item from an array\n *\n * > 0 - right (last)\n * <= 0 - left (first)\n *\n */\nexport const getTail = ( list:Array<any>|NodeList, direction:number=0 ):any => {\n\n\tif( direction > 0 ){\n\t\treturn list[list.length-1];\n\t}\n\n\treturn list[0];\n}\n\n/**\n * Return true if an object is empty\n *\n */\nexport const isEmptyObject = (obj:object):boolean => {\n\treturn (Object.keys(obj).length === 0);\n}\n\n\n/**\n * Get the index of an element amongst sibling nodes of the same type\n *\n */\nexport const nodeIndex = ( el:null|Element, amongst?:string ):number => {\n\tif (!el) return -1;\n\n\tamongst = amongst || el.nodeName;\n\n\tvar i = 0;\n\twhile( el = el.previousElementSibling ){\n\n\t\tif( el.matches(amongst) ){\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\n\n\n/**\n * Set attributes of an element\n *\n */\nexport const setAttr = (el:Element,attrs:{ [key: string]: null|string|number }) => {\n\titerate( attrs,(val,attr) => {\n\t\tif( val == null ){\n\t\t\tel.removeAttribute(attr as string);\n\t\t}else{\n\t\t\tel.setAttribute(attr as string, ''+val);\n\t\t}\n\t});\n}\n\n\n/**\n * Replace a node\n */\nexport const replaceNode = ( existing:Node, replacement:Node ) => {\n\tif( existing.parentNode ) existing.parentNode.replaceChild(replacement, existing);\n}\n", "/**\n * Plugin: \"virtual_scroll\" (Tom Select)\n * Copyright (c) contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this\n * file except in compliance with the License. You may obtain a copy of the License at:\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n * ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n */\n\nimport type TomSelect from '../../tom-select.ts';\nimport { TomOption } from '../../types/index.ts';\nimport { addClasses, removeClasses } from '../../vanilla.ts';\n\nexport default function(this:TomSelect) {\n\tconst self\t\t\t\t\t\t\t= this;\n\tconst orig_canLoad\t\t\t\t\t= self.canLoad;\n\tconst orig_clearActiveOption\t\t= self.clearActiveOption;\n\tconst orig_loadCallback\t\t\t\t= self.loadCallback;\n\tconst orig_load\t\t\t\t\t\t= self.load;\n\n\tvar pagination:{[key:string]:any}\t= {};\n\tvar dropdown_content:HTMLElement;\n\tvar loading_more\t\t\t\t\t= false;\n\tvar load_more_opt:HTMLElement;\n\tvar default_values: string[]\t\t= [];\n\tvar default_values_loaded\t\t\t= false;\n\tvar default_pagination:any;\n\tvar default_options: TomOption[]\t= [];\n\tvar html_values: string[]\t\t\t= [];\n\tvar preload_requested\t\t\t\t= false;\n\n\tif( !self.settings.shouldLoadMore ){\n\n\t\t// return true if additional results should be loaded\n\t\tself.settings.shouldLoadMore = ():boolean=>{\n\n\t\t\tconst scroll_percent = dropdown_content.clientHeight / (dropdown_content.scrollHeight - dropdown_content.scrollTop);\n\t\t\tif( scroll_percent > 0.9 ){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif( self.activeOption ){\n\t\t\t\tvar selectable\t= self.selectable();\n\t\t\t\tvar index\t\t= Array.from(selectable).indexOf(self.activeOption);\n\t\t\t\tif( index >= (selectable.length-2) ){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\t}\n\n\n\tif( !self.settings.firstUrl ){\n\t\tthrow 'virtual_scroll plugin requires a firstUrl() method';\n\t}\n\n\n\t// in order for virtual scrolling to work,\n\t// options need to be ordered the same way they're returned from the remote data source\n\tself.settings.sortField\t\t\t= [{field:'$order'},{field:'$score'}];\n\n\n\t// can we load more results for given query?\n\tconst canLoadMore = (query:string):boolean => {\n\n\t\tif( self.settings.maxOptions !== null\n\t\t\t&& typeof self.settings.maxOptions === 'number'\n\t\t\t&& dropdown_content.children.length >= self.settings.maxOptions\n\t\t){\n\t\t\treturn false;\n\t\t}\n\n\t\tif( (query in pagination) && pagination[query] ){\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\tconst clearFilter = (option:TomOption, value:string):boolean => {\n\t\tif( self.items.indexOf(value) >= 0 || default_values.indexOf(value) >= 0 ){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t};\n\n\n\t// set the next url that will be\n\tself.setNextUrl = (value:string,next_url:any):void => {\n\t\tpagination[value] = next_url;\n\t};\n\n\t// getUrl() to be used in settings.load()\n\tself.getUrl = (query:string):any =>{\n\n\t\tif( query in pagination ){\n\t\t\tconst next_url = pagination[query];\n\t\t\tpagination[query] = false;\n\t\t\treturn next_url;\n\t\t}\n\n\t\t// if the user goes back to a previous query\n\t\t// we need to load the first page again\n\t\tself.clearPagination();\n\n\t\treturn self.settings.firstUrl.call(self,query);\n\t};\n\n\t// clear pagination\n\tself.clearPagination = ():void =>{\n\t\tpagination = {};\n\t};\n\n\t// don't clear the active option (and cause unwanted dropdown scroll)\n\t// while loading more results\n\tself.hook('instead','clearActiveOption',()=>{\n\n\t\tif( loading_more ){\n\t\t\treturn;\n\t\t}\n\n\t\treturn orig_clearActiveOption.call(self);\n\t});\n\n\t// override the canLoad method\n\tself.hook('instead','canLoad',(query:string)=>{\n\n\t\t// first time the query has been seen\n\t\tif( !(query in pagination) ){\n\t\t\treturn orig_canLoad.call(self,query);\n\t\t}\n\n\t\treturn canLoadMore(query);\n\t});\n\n\n\t// handle a load() response, knowing which query the request was originally issued for\n\tconst loadCallbackForQuery = ( query:string, was_loading_more:boolean, options:TomOption[], optgroups:TomOption[] ):void => {\n\n\t\tloading_more = was_loading_more;\n\n\t\t// The response belongs to a query the user has since changed, so applying it would\n\t\t// overwrite the options displayed for the active query. Discard it, performing only the\n\t\t// loading bookkeeping loadCallback() would otherwise do. Reset the stored pagination for\n\t\t// the abandoned query - the load function may have already advanced it past pages that\n\t\t// were never applied - so a later request for the same query starts from the first page.\n\t\tif( query !== self.lastValue ){\n\t\t\tself.loading = Math.max(self.loading - 1, 0);\n\t\t\tif( !self.loading ){\n\t\t\t\tremoveClasses(self.wrapper,self.settings.loadingClass);\n\t\t\t}\n\t\t\tpagination[query] = self.settings.firstUrl.call(self,query);\n\n\t\t\t// if the discarded response was the preload, allow preload() to run again\n\t\t\tif( query === '' && !default_values_loaded ){\n\t\t\t\tself.wrapper.classList.remove('preloaded');\n\t\t\t}\n\n\t\t\tloading_more = false;\n\t\t\treturn;\n\t\t}\n\n\t\tif( !loading_more ){\n\t\t\t// When searching (non-empty query), keep selected items and HTML default options,\n\t\t\t// but remove preloaded remote options so they don't bleed into search results.\n\t\t\t// For empty query, use clearFilter (keeps default_values + items).\n\t\t\tconst activeFilter = query !== ''\n\t\t\t\t? (_option: TomOption, value: string) => self.items.indexOf(value) >= 0 || html_values.indexOf(value) >= 0\n\t\t\t\t: clearFilter;\n\t\t\tself.clearOptions(activeFilter);\n\t\t}else if( load_more_opt ){\n\t\t\tconst first_option = options[0];\n\t\t\tif( first_option !== undefined ){\n\t\t\t\tload_more_opt.dataset.value\t\t= first_option[self.settings.valueField];\n\t\t\t}\n\t\t}\n\n\t\torig_loadCallback.call( self, options, optgroups);\n\n\t\t// After the initial preload (empty query), snapshot default_values and option objects\n\t\t// so they can be restored when the user clears their search.\n\t\tif( !loading_more && !default_values_loaded && query === '' ){\n\t\t\tdefault_values_loaded = true;\n\t\t\tdefault_values = Object.keys(self.options);\n\t\t\tdefault_pagination = pagination[''];\n\t\t\tdefault_options = Object.values(self.options);\n\t\t}\n\n\t\tloading_more = false;\n\n\t\t// A page can add nothing new to the dropdown (e.g. when all of its options are already\n\t\t// selected), leaving it too short to scroll. No scroll event would then request the\n\t\t// next page, so check straight away.\n\t\tif( self.isOpen ){\n\t\t\tloadMoreIfNeeded();\n\t\t}\n\t};\n\n\t// load the next page if the dropdown is scrolled near its end\n\tconst loadMoreIfNeeded = ():void => {\n\n\t\tif( !self.settings.shouldLoadMore.call(self) ){\n\t\t\treturn;\n\t\t}\n\n\t\t// !important: this will get checked again in load() but we still need to check here otherwise loading_more will be set to true\n\t\tif( !canLoadMore(self.lastValue) ){\n\t\t\treturn;\n\t\t}\n\n\t\t// don't call load() too much\n\t\tif( loading_more ) return;\n\n\n\t\tloading_more = true;\n\t\tself.load.call(self,self.lastValue);\n\t};\n\n\t// bind the query (and whether this request is loading more results) into the callback of\n\t// each load() request - loadCallback() alone cannot tell which request a response answers\n\tself.hook('instead','load',(query:string)=>{\n\t\tconst was_loading_more\t= loading_more;\n\t\tconst outer_callback\t= self.loadCallback;\n\t\tself.loadCallback = ( options:TomOption[], optgroups:TomOption[] ):void => {\n\t\t\tloadCallbackForQuery( query, was_loading_more, options, optgroups );\n\t\t};\n\t\ttry{\n\t\t\treturn orig_load.call( self, query );\n\t\t}finally{\n\t\t\tself.loadCallback = outer_callback;\n\t\t}\n\t});\n\n\t// fallback for loadCallback() invoked directly rather than through a load() request\n\tself.hook('instead','loadCallback',( options:TomOption[], optgroups:TomOption[])=>{\n\t\tloadCallbackForQuery( self.lastValue, loading_more, options, optgroups );\n\t});\n\n\t// track that a preload was requested, so recovery from a discarded preload response\n\t// doesn't issue empty-query requests when preloading was never enabled\n\tself.hook('before','preload',()=>{\n\t\tpreload_requested = true;\n\t});\n\n\n\t// as the “loading_more” element will be removed from the dropdown,\n\t// we activate the previous option if needed\n\t// to avoid the dropdown being scrolled back to the first one\n\tself.hook('before','refreshOptions',()=>{\n\n\t\tif (self.activeOption && \"option\" !== self.activeOption.getAttribute(\"role\")) {\n\t\t\tself.setActiveOption(self.activeOption.previousElementSibling as HTMLElement);\n\t\t}\n\n\t});\n\n\n\t// add templates to dropdown\n\t//\tloading_more if we have another url in the queue\n\t//\tno_more_results if we don't have another url in the queue\n\tself.hook('after','refreshOptions',()=>{\n\n\t\tconst query\t\t= self.lastValue;\n\t\tvar option;\n\n\t\tif( canLoadMore(query) ){\n\n\t\t\toption = self.render('loading_more',{query:query});\n\t\t\tif( option ){\n\t\t\t\toption.setAttribute('data-selectable',''); // so that navigating dropdown with [down] keypresses can navigate to this node\n\t\t\t\tload_more_opt = option;\n\t\t\t}\n\n\t\t}else if( (query in pagination) && !dropdown_content.querySelector('.no-results') ){\n\t\t\toption = self.render('no_more_results',{query:query});\n\t\t}\n\n\t\tif( option ){\n\t\t\taddClasses(option,self.settings.optionClass);\n\t\t\tdropdown_content.append( option );\n\t\t}\n\n\t});\n\n\n\t// Restore preloaded options and pagination when clearing search\n\tconst restoreDefaults = ():void => {\n\t\tif( !default_values_loaded ) {\n\t\t\t// There is nothing to restore. If a preload was requested but its response was\n\t\t\t// discarded as stale (which removes the 'preloaded' class), request it again so the\n\t\t\t// first page is fetched; if a preload is still in flight, or was never requested at\n\t\t\t// all, do nothing - clearing the search must not issue requests of its own.\n\t\t\tif( preload_requested && !self.wrapper.classList.contains('preloaded') && self.isFocused ){\n\t\t\t\tself.preload();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t// Re-add preloaded option objects (clearOptions can only remove, not restore)\n\t\tself.addOptions(default_options);\n\t\t// Remove any search results that are not part of the preloaded defaults\n\t\tself.clearOptions(clearFilter);\n\t\tif( default_pagination ) {\n\t\t\tpagination[''] = default_pagination;\n\t\t}\n\t};\n\n\tself.on('type',(query:string) => {\n\t\tif( query === '' ){\n\t\t\trestoreDefaults();\n\t\t\tself.refreshOptions(false);\n\t\t}\n\t});\n\n\tself.on('dropdown_close', restoreDefaults);\n\n\t// add scroll listener and default templates\n\tself.on('initialize',()=>{\n\t\thtml_values = Object.keys(self.options);\n\t\tdefault_values = Object.keys(self.options);\n\t\tdropdown_content = self.dropdown_content;\n\n\t\t// default templates\n\t\tself.settings.render = Object.assign({}, {\n\t\t\tloading_more:() => {\n\t\t\t\treturn `<div class=\"loading-more-results\">Loading more results ... </div>`;\n\t\t\t},\n\t\t\tno_more_results:() =>{\n\t\t\t\treturn `<div class=\"no-more-results\">No more results</div>`;\n\t\t\t}\n\t\t},self.settings.render);\n\n\n\t\t// watch dropdown content scroll position\n\t\tdropdown_content.addEventListener('scroll',loadMoreIfNeeded);\n\t});\n\n};\n", "import TomSelect from './tom-select.ts';\n\nimport change_listener from './plugins/change_listener/plugin.ts';\nimport checkbox_options from './plugins/checkbox_options/plugin.ts';\nimport clear_button from './plugins/clear_button/plugin.ts';\nimport drag_drop from './plugins/drag_drop/plugin.ts';\nimport dropdown_header from './plugins/dropdown_header/plugin.ts';\nimport caret_position from './plugins/caret_position/plugin.ts';\nimport dropdown_input from './plugins/dropdown_input/plugin.ts';\nimport input_autogrow from './plugins/input_autogrow/plugin.ts';\nimport no_backspace_delete from './plugins/no_backspace_delete/plugin.ts';\nimport no_active_items from './plugins/no_active_items/plugin.ts';\nimport optgroup_columns from './plugins/optgroup_columns/plugin.ts';\nimport remove_button from './plugins/remove_button/plugin.ts';\nimport restore_on_backspace from './plugins/restore_on_backspace/plugin.ts';\nimport virtual_scroll from './plugins/virtual_scroll/plugin.ts';\n\nTomSelect.define('change_listener', change_listener);\nTomSelect.define('checkbox_options', checkbox_options);\nTomSelect.define('clear_button', clear_button);\nTomSelect.define('drag_drop', drag_drop);\nTomSelect.define('dropdown_header', dropdown_header);\nTomSelect.define('caret_position', caret_position);\nTomSelect.define('dropdown_input', dropdown_input);\nTomSelect.define('input_autogrow', input_autogrow);\nTomSelect.define('no_backspace_delete', no_backspace_delete);\nTomSelect.define('no_active_items', no_active_items);\nTomSelect.define('optgroup_columns', optgroup_columns);\nTomSelect.define('remove_button', remove_button);\nTomSelect.define('restore_on_backspace', restore_on_backspace);\nTomSelect.define('virtual_scroll', virtual_scroll);\n\nexport default TomSelect;\n", "import \"./image_field_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\nimport {\n  Core,\n  ThumbnailGenerator,\n  XHRUpload,\n} from 'uppy';\nimport French from '@uppy/locales/lib/fr_FR';\nimport 'uppy/dist/uppy.min.css';\n\nexport class Controller extends BaseController {\n  static targets = [\"content\", \"fileInput\", \"hiddenInput\", \"preview\"];\n\n  connect() {\n    this.uppy = new Core({\n      allowMultipleUploadBatches: false,\n      autoProceed: true,\n      locale: French,\n      maxNumberOfFiles: 1,\n      // TODO: add restrictions\n      // see https://uppy.io/docs/uppy/#restrictions\n      // restrictions: []\n    })\n    .use(ThumbnailGenerator, {\n      thumbnailHeight: 113,\n      thumbnailWidth: 248,\n    })\n    .use(XHRUpload, {\n      endpoint: '/admin/upload',\n    });\n\n    this.uppy.on('thumbnail:generated', (file, preview) => {\n      while (this.previewTarget.firstChild) {\n        this.previewTarget.removeChild(this.previewTarget.firstChild);\n      }\n\n      if (preview) {\n        const previewImage = document.createElement(\"img\");\n        previewImage.src = preview;\n        this.previewTarget.appendChild(previewImage);\n      }\n    });\n\n    this.uppy.on('upload-success', (file, response) => {\n      const uploadedFileData = response.body['data'];\n\n      this.hiddenInputTarget.value = JSON.stringify(uploadedFileData);\n    });\n\n    this.uppy.on('file-removed', () => {\n      this.fileInputTarget.value = null;\n    });\n\n    this.uppy.on('complete', () => {\n      this.fileInputTarget.value = null;\n    });\n  }\n\n  disconnect() {\n    this.uppy.close();\n    this.uppy = null;\n  }\n\n  addFiles(event) {\n    const files = Array.from(event.target.files);\n\n    this.uppy.reset();\n\n    files.forEach((file) => {\n      try {\n        this.uppy.addFile({\n          source: 'file input',\n          name: file.name,\n          type: file.type,\n          data: file,\n        })\n      } catch (err) {\n        if (err.isRestriction) {\n          // handle restrictions\n          console.log('Restriction error:', err);\n        } else {\n          // handle other errors\n          console.error(err);\n        }\n      }\n    });\n  }\n}\n", "// Core\nexport { default as Core, debugLogger } from '@uppy/core'\n\n// Utilities\nexport { default as server } from '@uppy/companion-client'\n/* eslint-disable */\nimport ProviderView from '@uppy/provider-views'\nexport var views = { ProviderView }\n/* eslint-enable */\n\n// Stores\nexport { default as DefaultStore } from '@uppy/store-default'\nexport { default as ReduxStore } from '@uppy/store-redux'\n\n// UI plugins\nexport { default as Dashboard } from '@uppy/dashboard'\nexport { default as DragDrop } from '@uppy/drag-drop'\nexport { default as DropTarget } from '@uppy/drop-target'\nexport { default as FileInput } from '@uppy/file-input'\nexport { default as ImageEditor } from '@uppy/image-editor'\nexport { default as Informer } from '@uppy/informer'\nexport { default as ProgressBar } from '@uppy/progress-bar'\nexport { default as StatusBar } from '@uppy/status-bar'\n\n// Acquirers\nexport { default as Audio } from '@uppy/audio'\nexport { default as Box } from '@uppy/box'\nexport { default as Dropbox } from '@uppy/dropbox'\nexport { default as Facebook } from '@uppy/facebook'\nexport { default as GoogleDrive } from '@uppy/google-drive'\nexport { default as Instagram } from '@uppy/instagram'\nexport { default as OneDrive } from '@uppy/onedrive'\nexport { default as RemoteSources } from '@uppy/remote-sources'\nexport { default as ScreenCapture } from '@uppy/screen-capture'\nexport { default as Unsplash } from '@uppy/unsplash'\nexport { default as Url } from '@uppy/url'\nexport { default as Webcam } from '@uppy/webcam'\nexport { default as Zoom } from '@uppy/zoom'\n\n// Uploaders\nexport { default as AwsS3 } from '@uppy/aws-s3'\nexport { default as AwsS3Multipart } from '@uppy/aws-s3-multipart'\nexport { default as Transloadit } from '@uppy/transloadit'\nexport { default as Tus } from '@uppy/tus'\nexport { default as XHRUpload } from '@uppy/xhr-upload'\n\n// Miscellaneous\nexport { default as Compressor } from '@uppy/compressor'\nexport { default as Form } from '@uppy/form'\nexport { default as GoldenRetriever } from '@uppy/golden-retriever'\nexport { default as ReduxDevTools } from '@uppy/redux-dev-tools'\nexport { default as ThumbnailGenerator } from '@uppy/thumbnail-generator'\n\nexport const locales = {}\n", "import \"./link_select_component.css\";\nimport '../../../../../vendor/tom_select/css/tom-select.custom.css';\nimport TomSelect from \"tom-select\";\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  connect() {\n    const urlPattern = /^https?:\\/\\/[^ \"]+$/;\n    const config = {\n      addPrecedence: false,\n      create: true,\n      createFilter: urlPattern,\n    };\n    this.tomSelect = new TomSelect(this.element, config);\n  }\n\n  disconnect() {\n    this.tomSelect.destroy();\n  }\n}\n", "import \"./switch_box_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static targets = [\"input\"];\n\n  connect() {\n    this.change();\n  }\n\n  change() {\n    this.conditionalElement.hidden = !this.inputTarget.checked;\n  }\n\n  get conditionalElement() {\n    const selector = this.element.dataset.conditionalElement;\n    return document.querySelector(selector);\n  }\n}\n", "import \"./text_field_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./gate_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./header_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  toggleTheme() {\n    const dark = document.documentElement.classList.toggle(\"dark-theme\");\n    document.documentElement.classList.toggle(\"light-theme\");\n\n    // TODO: save theme to user account\n    console.log(dark ? \"dark\" : \"light\");\n  }\n}\n", "import \"./heading_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./layout_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\nimport { useClickOutside } from 'stimulus-use';\n\nexport class Controller extends BaseController {\n  static classes = [\"open\"];\n  static targets = [\"panel\", \"panelFrame\", \"panelCloser\"];\n\n  connect() {\n    useClickOutside(this, { element: this.panelTarget })\n  }\n\n  disconnect() {\n  }\n\n  panelCloserTargetConnected() {\n    this.closePanel();\n  }\n\n  openPanelWhenLoaded() {\n    this.panelFrameTarget.loaded.then(() => this.openPanel());\n  }\n\n  openPanel() {\n    this.panelTarget.classList.add(this.openClass);\n  }\n\n  closePanel() {\n    this.panelTarget.classList.remove(this.openClass);\n    this.emptyFrame();\n  }\n\n  clickOutside(e) {\n    if (e.target.dataset.action && e.target.dataset.action.includes(\"admin--layout#openPanel\")) return;\n    this.closePanel();\n  }\n\n  emptyFrame() {\n    while(this.panelFrameTarget.firstChild) {\n      this.panelFrameTarget.removeChild(this.panelFrameTarget.firstChild);\n    }\n  }\n}\n", "const isff: boolean =\n  typeof navigator !== 'undefined'\n    ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0\n    : false;\n\n/** Bind event */\nfunction addEvent(\n  object: HTMLElement | Document | Window,\n  event: string,\n  method: EventListenerOrEventListenerObject,\n  useCapture?: boolean\n): void {\n  if (object.addEventListener) {\n    object.addEventListener(event, method, useCapture);\n    // @ts-expect-error - attachEvent is only available on IE\n  } else if (object.attachEvent) {\n    // @ts-expect-error - attachEvent is only available on IE\n    object.attachEvent(`on${event}`, method);\n  }\n}\n\nfunction removeEvent(\n  object: HTMLElement | Document | Window | null,\n  event: string,\n  method: EventListenerOrEventListenerObject,\n  useCapture?: boolean\n): void {\n  if (!object) return;\n  if (object.removeEventListener) {\n    object.removeEventListener(event, method, useCapture);\n    // @ts-expect-error - removeEvent is only available on IE\n  } else if (object.detachEvent) {\n    // @ts-expect-error - detachEvent is only available on IE\n    object.detachEvent(`on${event}`, method);\n  }\n}\n\n/** Convert modifier keys to their corresponding key codes */\nfunction getMods(modifier: Record<string, number>, key: string[]): number[] {\n  const modsKeys = key.slice(0, key.length - 1);\n  const modsCodes: number[] = [];\n  for (let i = 0; i < modsKeys.length; i++) {\n    modsCodes.push(modifier[modsKeys[i].toLowerCase()]);\n  }\n  return modsCodes;\n}\n\n/** Process the input key string and convert it to an array */\nfunction getKeys(key: string | undefined): string[] {\n  if (typeof key !== 'string') key = '';\n  key = key.replace(/\\s/g, ''); // Match any whitespace character, including spaces, tabs, form feeds, etc.\n  const keys = key.split(','); // Allow multiple shortcuts separated by ','\n  let index = keys.lastIndexOf('');\n\n  // Shortcut may include ',' — special handling needed\n  for (; index >= 0; ) {\n    keys[index - 1] += ',';\n    keys.splice(index, 1);\n    index = keys.lastIndexOf('');\n  }\n\n  return keys;\n}\n\n/** Compare arrays of modifier keys */\nfunction compareArray(a1: number[], a2: number[]): boolean {\n  const arr1 = a1.length >= a2.length ? a1 : a2;\n  const arr2 = a1.length >= a2.length ? a2 : a1;\n  let isIndex = true;\n\n  for (let i = 0; i < arr1.length; i++) {\n    if (arr2.indexOf(arr1[i]) === -1) isIndex = false;\n  }\n  return isIndex;\n}\n\n/**\n * Get a normalized key code from keyboard event.\n *\n * For Latin letters, prefer `event.key` so alternate Latin layouts such as\n * Dvorak/Colemak match the typed character.\n *\n * For non-Latin layouts, fall back to `event.code` for KeyA-KeyZ so bindings\n * like `ctrl+m` still work on Cyrillic/Greek keyboards.\n */\nfunction getLayoutIndependentKeyCode(\n  event: KeyboardEvent,\n  keyMap: Record<string, number>,\n  modifierMap: Record<string, number>\n): number {\n  let key = event.keyCode || event.which || event.charCode;\n\n  // Numpad keys share `key` with the main row ('0', '.', '-', '/'), so keep their key code.\n  if (key && event.code && /^Numpad/.test(event.code)) {\n    return key;\n  }\n\n  if (event.key) {\n    const eventKey = event.key.toLowerCase();\n    if (eventKey in keyMap) {\n      return keyMap[eventKey];\n    }\n\n    if (eventKey in modifierMap) {\n      return modifierMap[eventKey];\n    }\n\n    if (/^[0-9]$/.test(event.key)) {\n      return event.key.charCodeAt(0);\n    }\n\n    if (/^[a-z]$/i.test(event.key)) {\n      return event.key.toUpperCase().charCodeAt(0);\n    }\n  }\n\n  // Convert physical key code (KeyA-KeyZ) to corresponding ASCII code (65-90)\n  // when the typed character is not a Latin letter.\n  if (event.code && /^Key[A-Z]$/.test(event.code)) {\n    key = event.code.charCodeAt(3); // \"KeyA\"[3] = \"A\" -> 65\n  }\n\n  return key;\n}\n\nexport {\n  isff,\n  getMods,\n  getKeys,\n  addEvent,\n  removeEvent,\n  compareArray,\n  getLayoutIndependentKeyCode,\n};\n", "import { HotkeysEvent } from './types';\nimport { isff } from './utils';\n\n// Special Keys\nconst _keyMap: Record<string, number> = {\n  backspace: 8,\n  '⌫': 8,\n  tab: 9,\n  clear: 12,\n  enter: 13,\n  '↩': 13,\n  return: 13,\n  esc: 27,\n  escape: 27,\n  space: 32,\n  left: 37,\n  up: 38,\n  right: 39,\n  down: 40,\n  /// https://w3c.github.io/uievents/#events-keyboard-key-location\n  arrowup: 38,\n  arrowdown: 40,\n  arrowleft: 37,\n  arrowright: 39,\n  del: 46,\n  delete: 46,\n  ins: 45,\n  insert: 45,\n  home: 36,\n  end: 35,\n  pageup: 33,\n  pagedown: 34,\n  capslock: 20,\n  num_0: 96,\n  num_1: 97,\n  num_2: 98,\n  num_3: 99,\n  num_4: 100,\n  num_5: 101,\n  num_6: 102,\n  num_7: 103,\n  num_8: 104,\n  num_9: 105,\n  num_multiply: 106,\n  num_add: 107,\n  num_enter: 108,\n  num_subtract: 109,\n  num_decimal: 110,\n  num_divide: 111,\n  '⇪': 20,\n  ',': 188,\n  '.': 190,\n  '/': 191,\n  '`': 192,\n  '-': isff ? 173 : 189,\n  '=': isff ? 61 : 187,\n  ';': isff ? 59 : 186,\n  '\\'': 222,\n  '{': 219,\n  '}': 221,\n  '[': 219,\n  ']': 221,\n  '\\\\': 220,\n};\n\n// Modifier Keys\nconst _modifier: Record<string, number> = {\n  // shiftKey\n  '⇧': 16,\n  shift: 16,\n  // altKey\n  '⌥': 18,\n  alt: 18,\n  option: 18,\n  // ctrlKey\n  '⌃': 17,\n  ctrl: 17,\n  control: 17,\n  // metaKey\n  '⌘': 91,\n  cmd: 91,\n  meta: 91,\n  command: 91,\n};\n\nconst modifierMap: Record<string | number, number | string> = {\n  16: 'shiftKey',\n  18: 'altKey',\n  17: 'ctrlKey',\n  91: 'metaKey',\n\n  shiftKey: 16,\n  ctrlKey: 17,\n  altKey: 18,\n  metaKey: 91,\n};\n\nconst _mods: Record<number, boolean> = {\n  16: false,\n  18: false,\n  17: false,\n  91: false,\n};\n\nconst _handlers: Record<string | number, HotkeysEvent[]> = {};\n\n// F1~F12 special key\nfor (let k = 1; k < 20; k++) {\n  _keyMap[`f${k}`] = 111 + k;\n}\n\nexport { _keyMap, _modifier, modifierMap, _mods, _handlers };\n", "import {\n  KeyCodeInfo,\n  HotkeysEvent,\n  UnbindInfo,\n  HotkeysOptions,\n  KeyHandler,\n  HotkeysInterface,\n  SetScope,\n  GetScope,\n  GetPressedKeyCodes,\n  GetPressedKeyString,\n  GetAllKeyCodes,\n  Filter,\n  IsPressed,\n  DeleteScope,\n  Unbind,\n  HotkeysAPI,\n} from './types';\nimport { addEvent, removeEvent, getMods, getKeys, compareArray, getLayoutIndependentKeyCode } from './utils';\nimport { _keyMap, _modifier, modifierMap, _mods, _handlers } from './var';\n\n/** Record the pressed keys */\nlet _downKeys: number[] = [];\n/** Whether the window has already listened to focus changes */\nlet winListendFocus: { listener: EventListener; capture: boolean } | null =\n  null;\n/** Whether we already listen to fullscreen change (to clear stuck _downKeys) */\nlet winListendFullscreen: { fullscreen: EventListener; webkit: EventListener } | null = null;\n/** Whether the window has already listened to the afterprint event (to clear stuck _downKeys) */\nlet winListendPrint: EventListener | null = null;\n/** Default hotkey scope */\nlet _scope: string = 'all';\n/** Map to record elements with bound events */\nconst elementEventMap = new Map<\n  HTMLElement | Document,\n  {\n    keydownListener: EventListener;\n    keyupListenr: EventListener;\n    capture: boolean;\n  }\n>();\n\n/** Return key code */\nconst code = (x: string): number =>\n  _keyMap[x.toLowerCase()] ||\n  _modifier[x.toLowerCase()] ||\n  x.toUpperCase().charCodeAt(0);\n\nconst getKey = (x: number): string | undefined =>\n  Object.keys(_keyMap).find((k) => _keyMap[k] === x);\nconst getModifier = (x: number): string | undefined =>\n  Object.keys(_modifier).find((k) => _modifier[k] === x);\n\n/** Set or get the current scope (defaults to 'all') */\nconst setScope: SetScope = (scope) => {\n  _scope = scope || 'all';\n};\n/** Get the current scope */\nconst getScope: GetScope = () => {\n  return _scope || 'all';\n};\n/** Get the key codes of the currently pressed keys */\nconst getPressedKeyCodes: GetPressedKeyCodes = () => {\n  return _downKeys.slice(0);\n};\n\nconst getPressedKeyString: GetPressedKeyString = () => {\n  return _downKeys.map(\n    (c) => getKey(c) || getModifier(c) || String.fromCharCode(c)\n  );\n};\n\nconst getAllKeyCodes: GetAllKeyCodes = () => {\n  const result: KeyCodeInfo[] = [];\n  Object.keys(_handlers).forEach((k) => {\n    _handlers[k].forEach(({ key, scope, mods, shortcut, splitKey }) => {\n      result.push({\n        scope,\n        shortcut,\n        mods,\n        keys: key.split(splitKey).map((v) => code(v)),\n      });\n    });\n  });\n  return result;\n};\n\n/** hotkey is effective only when filter return true */\nconst filter: Filter = (event) => {\n  // Shadow DOM retargets event.target to the host; composedPath()[0] is the inner element when the root is open.\n  const target = ((event.composedPath && event.composedPath()[0]) ||\n    event.target ||\n    event.srcElement) as HTMLElement;\n  const { tagName } = target;\n  let flag = true;\n  const isInput =\n    tagName === 'INPUT' &&\n    ![\n      'checkbox',\n      'radio',\n      'range',\n      'button',\n      'file',\n      'reset',\n      'submit',\n      'color',\n    ].includes((target as HTMLInputElement).type);\n  // ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>\n  if (\n    target.isContentEditable ||\n    ((isInput || tagName === 'TEXTAREA' || tagName === 'SELECT') &&\n      !(target as HTMLInputElement | HTMLTextAreaElement).readOnly)\n  ) {\n    flag = false;\n  }\n  return flag;\n};\n\n/** Determine whether the pressed key matches a specific key, returns true or false */\nconst isPressed: IsPressed = (keyCode) => {\n  if (typeof keyCode === 'string') {\n    keyCode = code(keyCode); // Convert to key code\n  }\n  return _downKeys.indexOf(keyCode) !== -1;\n};\n\n/** Loop through and delete all handlers with the specified scope */\nconst deleteScope: DeleteScope = (scope, newScope) => {\n  let handlers: HotkeysEvent[];\n  let i: number;\n\n  // If no scope is specified, get the current scope\n  if (!scope) scope = getScope();\n\n  for (const key in _handlers) {\n    if (Object.prototype.hasOwnProperty.call(_handlers, key)) {\n      handlers = _handlers[key];\n      for (i = 0; i < handlers.length; ) {\n        if (handlers[i].scope === scope) {\n          const deleteItems = handlers.splice(i, 1);\n          deleteItems.forEach(({ element }) => removeKeyEvent(element));\n        } else {\n          i++;\n        }\n      }\n    }\n  }\n\n  // If the current scope has been deleted, reset the scope to 'all'\n  if (getScope() === scope) setScope(newScope || 'all');\n};\n\n/** Clear modifier keys */\nfunction clearModifier(event: KeyboardEvent): void {\n  let key = getLayoutIndependentKeyCode(event, _keyMap, _modifier);\n\n  if (event.key && event.key.toLowerCase() === 'capslock') {\n    // Ensure that when capturing keystrokes in modern browsers,\n    // uppercase and lowercase letters (such as R and r) return the same key value.\n    // https://github.com/jaywcjlove/hotkeys-js/pull/514\n    // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\n    key = code(event.key);\n  }\n  const i = _downKeys.indexOf(key);\n\n  // Remove the pressed key from the list\n  if (i >= 0) {\n    _downKeys.splice(i, 1);\n  }\n  // Special handling for the command key: fix the issue where keyup only triggers once for command combos\n  if (event.key && event.key.toLowerCase() === 'meta') {\n    _downKeys.splice(0, _downKeys.length);\n  }\n\n  // Clear modifier keys: shiftKey, altKey, ctrlKey, (command || metaKey)\n  if (key === 93 || key === 224) key = 91;\n  if (key in _mods) {\n    _mods[key] = false;\n\n    // Reset the modifier key status to false\n    for (const k in _modifier)\n      if (_modifier[k] === key) (hotkeys as any)[k] = false;\n  }\n}\n\nconst unbind: Unbind = (\n  keysInfo?: string | UnbindInfo | UnbindInfo[],\n  ...args: any[]\n): void => {\n  // unbind(), unbind all keys\n  if (typeof keysInfo === 'undefined') {\n    Object.keys(_handlers).forEach((key) => {\n      if (Array.isArray(_handlers[key])) {\n        _handlers[key].forEach((info) => eachUnbind(info));\n      }\n      delete _handlers[key];\n    });\n    removeKeyEvent(null);\n  } else if (Array.isArray(keysInfo)) {\n    // support like : unbind([{key: 'ctrl+a', scope: 's1'}, {key: 'ctrl-a', scope: 's2', splitKey: '-'}])\n    keysInfo.forEach((info) => {\n      if (info.key) eachUnbind(info);\n    });\n  } else if (typeof keysInfo === 'object') {\n    // support like unbind({key: 'ctrl+a, ctrl+b', scope:'abc'})\n    if (keysInfo.key) eachUnbind(keysInfo);\n  } else if (typeof keysInfo === 'string') {\n    // support old method\n    let [scope, method] = args;\n    if (typeof scope === 'function') {\n      method = scope;\n      scope = '';\n    }\n    eachUnbind({\n      key: keysInfo,\n      scope,\n      method,\n      splitKey: '+',\n    });\n  }\n};\n\n/** Unbind hotkeys for a specific scope */\nconst eachUnbind = ({\n  key,\n  scope,\n  method,\n  splitKey = '+',\n}: UnbindInfo): void => {\n  const multipleKeys = getKeys(key);\n  multipleKeys.forEach((originKey) => {\n    const unbindKeys = originKey.split(splitKey);\n    const len = unbindKeys.length;\n    const lastKey = unbindKeys[len - 1];\n    const keyCode = lastKey === '*' ? '*' : code(lastKey);\n    if (!_handlers[keyCode]) return;\n    // If scope is not provided, get the current scope\n    if (!scope) scope = getScope();\n    const keyCodes = unbindKeys.map(code);\n    const unbindElements: (HTMLElement | Document)[] = [];\n    _handlers[keyCode] = _handlers[keyCode].filter((record) => {\n      // Check if the method matches; if method is provided, must be equal to unbind\n      const isMatchingMethod = method ? record.method === method : true;\n      const isUnbind =\n        isMatchingMethod &&\n        record.scope === scope &&\n        compareArray(record.key.split(record.splitKey).map(code), keyCodes);\n      if (isUnbind) unbindElements.push(record.element);\n      return !isUnbind;\n    });\n    unbindElements.forEach((element) => removeKeyEvent(element));\n  });\n};\n\n/** Handle the callback function for the corresponding hotkey */\nfunction eventHandler(\n  event: KeyboardEvent,\n  handler: HotkeysEvent,\n  scope: string,\n  element: HTMLElement | Document\n): void {\n  if (handler.element !== element) {\n    return;\n  }\n  let modifiersMatch: boolean;\n\n  // Check if it is within the current scope\n  if (handler.scope === scope || handler.scope === 'all') {\n    // Check whether modifier keys match (returns true if they do)\n    modifiersMatch = handler.mods.length > 0;\n\n    for (const y in _mods) {\n      if (Object.prototype.hasOwnProperty.call(_mods, y)) {\n        if (\n          (!_mods[y] && handler.mods.indexOf(+y) > -1) ||\n          (_mods[y] && handler.mods.indexOf(+y) === -1)\n        ) {\n          modifiersMatch = false;\n        }\n      }\n    }\n\n    // Call the handler function; ignore if it's only a modifier key\n    if (\n      (handler.mods.length === 0 &&\n        !_mods[16] &&\n        !_mods[18] &&\n        !_mods[17] &&\n        !_mods[91]) ||\n      modifiersMatch ||\n      handler.shortcut === '*'\n    ) {\n      handler.keys = [];\n      handler.keys = handler.keys.concat(_downKeys);\n      if (handler.method(event, handler) === false) {\n        if (event.preventDefault) event.preventDefault();\n        else event.returnValue = false;\n        if (event.stopPropagation) event.stopPropagation();\n        if (event.cancelBubble) event.cancelBubble = true;\n      }\n    }\n  }\n}\n\n/** Handle the keydown event */\nfunction dispatch(\n  this: any,\n  event: KeyboardEvent,\n  element: HTMLElement | Document\n): void {\n  const asterisk = _handlers['*'];\n  let key = getLayoutIndependentKeyCode(event, _keyMap, _modifier);\n\n  // Ensure that when capturing keystrokes in modern browsers,\n  // uppercase and lowercase letters (such as R and r) return the same key value.\n  // https://github.com/jaywcjlove/hotkeys-js/pull/514\n  // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\n  // CapsLock key\n  // There's an issue where `keydown` and `keyup` events are not triggered after CapsLock is enabled to activate uppercase.\n  if (event.key && event.key.toLowerCase() === 'capslock') {\n    return;\n  }\n  // Form control filter: by default, shortcut keys are not triggered in form elements\n  const filterFn = (hotkeys as any).filter || filter;\n  if (!filterFn.call(this, event)) return;\n\n  // In Gecko (Firefox), the command key code is 224; unify it with WebKit (Chrome)\n  // In WebKit, left and right command keys have different codes\n  if (key === 93 || key === 224) key = 91;\n\n  /**\n   * Collect bound keys\n   * If an Input Method Editor is processing key input and the event is keydown, return 229.\n   * https://stackoverflow.com/questions/25043934/is-it-ok-to-ignore-keydown-events-with-keycode-229\n   * http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html\n   */\n  if (_downKeys.indexOf(key) === -1 && key !== 229) _downKeys.push(key);\n  /**\n   * Jest test cases are required.\n   * ===============================\n   */\n  ['metaKey', 'ctrlKey', 'altKey', 'shiftKey'].forEach((keyName) => {\n    const keyNum = (modifierMap as any)[keyName] as number;\n    if ((event as any)[keyName] && _downKeys.indexOf(keyNum) === -1) {\n      _downKeys.push(keyNum);\n    } else if (!(event as any)[keyName] && _downKeys.indexOf(keyNum) > -1) {\n      _downKeys.splice(_downKeys.indexOf(keyNum), 1);\n    } else if (keyName === 'metaKey' && (event as any)[keyName]) {\n      // If the command key is pressed, clear all non-modifier keys except the current event key.\n      // This is because keyup for non-modifier keys will NEVER be triggered when command is pressed.\n      // This is a known browser limitation.\n      _downKeys = _downKeys.filter((k) => k in modifierMap || k === key);\n    }\n  });\n  /**\n   * -------------------------------\n   */\n  if (key in _mods) {\n    _mods[key] = true;\n    // Register special modifier keys to the `hotkeys` object\n    for (const k in _modifier) {\n      if (Object.prototype.hasOwnProperty.call(_modifier, k)) {\n        const eventKey = (modifierMap as any)[_modifier[k]] as string;\n        (hotkeys as any)[k] = (event as any)[eventKey];\n      }\n    }\n\n    if (!asterisk) return;\n  }\n\n  // Bind the modifier keys in modifierMap to the event\n  for (const e in _mods) {\n    if (Object.prototype.hasOwnProperty.call(_mods, e)) {\n      _mods[e] = (event as any)[(modifierMap as any)[e]];\n    }\n  }\n  /**\n   * https://github.com/jaywcjlove/hotkeys/pull/129\n   * This solves the issue in Firefox on Windows where hotkeys corresponding to special characters would not trigger.\n   * An example of this is ctrl+alt+m on a Swedish keyboard which is used to type μ.\n   * Browser support: https://caniuse.com/#feat=keyboardevent-getmodifierstate\n   */\n  if (\n    event.getModifierState &&\n    !(event.altKey && !event.ctrlKey) &&\n    event.getModifierState('AltGraph')\n  ) {\n    if (_downKeys.indexOf(17) === -1) {\n      _downKeys.push(17);\n    }\n\n    if (_downKeys.indexOf(18) === -1) {\n      _downKeys.push(18);\n    }\n\n    _mods[17] = true;\n    _mods[18] = true;\n  }\n\n  // Get the current scope (defaults to 'all')\n  const scope = getScope();\n  // Handle any hotkeys registered as '*'\n  if (asterisk) {\n    for (let i = 0; i < asterisk.length; i++) {\n      if (\n        (event.type === 'keydown' && asterisk[i].keydown) ||\n        (event.type === 'keyup' && asterisk[i].keyup)\n      ) {\n        eventHandler(event, asterisk[i], scope, element);\n      }\n    }\n  }\n  // If the key is not registered, return\n  if (!(key in _handlers)) return;\n\n  const handlerKey = _handlers[key];\n  const keyLen = handlerKey.length;\n  for (let i = 0; i < keyLen; i++) {\n    if (\n      (event.type === 'keydown' && handlerKey[i].keydown) ||\n      (event.type === 'keyup' && handlerKey[i].keyup)\n    ) {\n      if (handlerKey[i].key) {\n        const record = handlerKey[i];\n        const { splitKey } = record;\n        const keyShortcut = record.key.split(splitKey);\n        const _downKeysCurrent: number[] = []; // Store the current key codes\n        for (let a = 0; a < keyShortcut.length; a++) {\n          _downKeysCurrent.push(code(keyShortcut[a]));\n        }\n        if (_downKeysCurrent.sort().join('') === _downKeys.sort().join('')) {\n          // Match found, call the handler\n          eventHandler(event, record, scope, element);\n        }\n      }\n    }\n  }\n}\n\nconst hotkeys = function hotkeys(\n  key: string,\n  option?: string | HotkeysOptions | KeyHandler,\n  method?: KeyHandler\n): void {\n  _downKeys = [];\n  /** List of hotkeys to handle */\n  const keys = getKeys(key);\n  let mods: number[] = [];\n  /** Default scope is 'all', meaning effective in all scopes */\n  let scope: string = 'all';\n  /** Element to which the hotkey events are bound */\n  let element: HTMLElement | Document = document;\n  let i = 0;\n  let keyup = false;\n  let keydown = true;\n  let splitKey = '+';\n  let capture = false;\n  /** Allow only a single callback */\n  let single = false;\n\n  // Determine if the second argument is a function (no options provided)\n  if (method === undefined && typeof option === 'function') {\n    method = option;\n  }\n\n  // Parse options object\n  if (Object.prototype.toString.call(option) === '[object Object]') {\n    const opts = option as HotkeysOptions;\n    if (opts.scope) scope = opts.scope; // Set scope\n    if (opts.element) element = opts.element; // Set binding element\n    if (opts.keyup) keyup = opts.keyup;\n    if (opts.keydown !== undefined) keydown = opts.keydown;\n    if (opts.capture !== undefined) capture = opts.capture;\n    if (typeof opts.splitKey === 'string') splitKey = opts.splitKey;\n    if (opts.single === true) single = true;\n  }\n\n  if (typeof option === 'string') scope = option;\n\n  // If only one callback is allowed, unbind the existing one first\n  if (single) unbind({ key, scope, splitKey });\n\n  // Handle each hotkey\n  for (; i < keys.length; i++) {\n    const currentKey = keys[i].split(splitKey); // Split into individual keys\n    mods = [];\n\n    // If it's a combination, extract modifier keys\n    if (currentKey.length > 1) mods = getMods(_modifier, currentKey);\n\n    // Convert non-modifier key to key code\n    let finalKey: string | number = currentKey[currentKey.length - 1];\n    finalKey = finalKey === '*' ? '*' : code(finalKey); // '*' means match all hotkeys\n\n    // Initialize handler array if this key has no handlers yet\n    if (!(finalKey in _handlers)) _handlers[finalKey] = [];\n\n    _handlers[finalKey].push({\n      keyup,\n      keydown,\n      scope,\n      mods,\n      shortcut: keys[i],\n      method: method!,\n      key: keys[i],\n      splitKey,\n      element,\n    });\n  }\n  // Register hotkey event listeners on the global document\n  if (typeof element !== 'undefined' && typeof window !== 'undefined') {\n    if (!elementEventMap.has(element)) {\n      // @ts-expect-error - window.event is deprecated IE property\n      const keydownListener = (event: Event = window.event) =>\n        dispatch(event as KeyboardEvent, element);\n      // @ts-expect-error - window.event is deprecated IE property\n      const keyupListenr = (event: Event = window.event) => {\n        dispatch(event as KeyboardEvent, element);\n        clearModifier(event as KeyboardEvent);\n      };\n      elementEventMap.set(element, { keydownListener, keyupListenr, capture });\n      addEvent(element, 'keydown', keydownListener, capture);\n      addEvent(element, 'keyup', keyupListenr, capture);\n    }\n    // Clear keys and modifiers when focus changes because keyup may happen outside the page.\n    if (!winListendFocus) {\n      const listener = (event: Event) => {\n        if (event.target !== window) return;\n        _downKeys = [];\n        for (const k in _mods) _mods[k] = false;\n        for (const k in _modifier) (hotkeys as any)[k] = false;\n      };\n      winListendFocus = { listener, capture };\n      addEvent(window, 'focus', listener, capture);\n      addEvent(window, 'blur', listener, capture);\n    }\n    // Register fullscreen change once: keyup can be lost when entering fullscreen (e.g. Alt+F), so clear stuck keys\n    if (!winListendFullscreen && typeof document !== 'undefined') {\n      const onFullscreenChange = () => {\n        _downKeys = [];\n        for (const k in _mods) _mods[k] = false;\n        for (const k in _modifier) (hotkeys as any)[k] = false;\n      };\n      const fullscreenListener = onFullscreenChange as EventListener;\n      const webkitListener = onFullscreenChange as EventListener;\n      document.addEventListener('fullscreenchange', fullscreenListener);\n      document.addEventListener('webkitfullscreenchange', webkitListener);\n      winListendFullscreen = { fullscreen: fullscreenListener, webkit: webkitListener };\n    }\n    // Register afterprint once: the print dialog swallows keyup and Chrome sends no focus event after it, so clear stuck keys\n    if (!winListendPrint) {\n      winListendPrint = () => {\n        _downKeys = [];\n        for (const k in _mods) _mods[k] = false;\n        for (const k in _modifier) (hotkeys as any)[k] = false;\n      };\n      addEvent(window, 'afterprint', winListendPrint);\n    }\n  }\n} as HotkeysInterface;\n\nfunction trigger(shortcut: string, scope: string = 'all'): void {\n  Object.keys(_handlers).forEach((key) => {\n    const dataList = _handlers[key].filter(\n      (item) => item.scope === scope && (item.shortcut === shortcut || item.shortcut === '*')\n    );\n    dataList.forEach((data) => {\n      if (data && data.method) {\n        data.method({} as KeyboardEvent, data);\n      }\n    });\n  });\n}\n\n/** Clean up event listeners. After unbinding, check whether the element still has any hotkeys bound. If not, remove its event listeners. */\nfunction removeKeyEvent(element: HTMLElement | Document | null): void {\n  const values = Object.values(_handlers).flat();\n  const findindex = values.findIndex(({ element: el }) => el === element);\n\n  // Full teardown must see the map before the per-element delete. Removing the\n  // last element first left this sweep with an empty map.\n  if (values.length <= 0 || elementEventMap.size <= 0) {\n    // Remove all event listeners from all elements\n    const eventKeys = Array.from(elementEventMap.keys());\n    eventKeys.forEach((el) => {\n      const { keydownListener, keyupListenr, capture } =\n        elementEventMap.get(el) || {};\n      if (keydownListener && keyupListenr) {\n        removeEvent(el, 'keyup', keyupListenr, capture);\n        removeEvent(el, 'keydown', keydownListener, capture);\n        elementEventMap.delete(el);\n      }\n    });\n    // Clear the elementEventMap\n    elementEventMap.clear();\n    // Clear all handlers\n    Object.keys(_handlers).forEach((key) => delete _handlers[key]);\n    // Remove the global window focus listeners\n    if (winListendFocus) {\n      const { listener, capture } = winListendFocus;\n      removeEvent(window, 'focus', listener, capture);\n      removeEvent(window, 'blur', listener, capture);\n      winListendFocus = null;\n    }\n    // Remove fullscreen change listeners\n    if (winListendFullscreen && typeof document !== 'undefined') {\n      document.removeEventListener('fullscreenchange', winListendFullscreen.fullscreen);\n      document.removeEventListener('webkitfullscreenchange', winListendFullscreen.webkit);\n      winListendFullscreen = null;\n    }\n    // Remove the afterprint listener\n    if (winListendPrint) {\n      removeEvent(window, 'afterprint', winListendPrint);\n      winListendPrint = null;\n    }\n    return;\n  }\n\n  if (findindex < 0 && element) {\n    const { keydownListener, keyupListenr, capture } =\n      elementEventMap.get(element) || {};\n    if (keydownListener && keyupListenr) {\n      removeEvent(element, 'keyup', keyupListenr, capture);\n      removeEvent(element, 'keydown', keydownListener, capture);\n      elementEventMap.delete(element);\n    }\n  }\n}\n\nconst _api: Omit<HotkeysAPI, 'noConflict'> = {\n  getPressedKeyString,\n  setScope,\n  getScope,\n  deleteScope,\n  getPressedKeyCodes,\n  getAllKeyCodes,\n  isPressed,\n  filter,\n  trigger,\n  unbind,\n  keyMap: _keyMap,\n  modifier: _modifier,\n  modifierMap,\n};\n\nfor (const a in _api) {\n  const key = a as keyof typeof _api;\n  if (Object.prototype.hasOwnProperty.call(_api, key)) {\n    (hotkeys as any)[key] = _api[key];\n  }\n}\n\nif (typeof window !== 'undefined') {\n  const _hotkeys = (window as any).hotkeys;\n  (hotkeys as HotkeysInterface).noConflict = (deep?: boolean) => {\n    if (deep && (window as any).hotkeys === hotkeys) {\n      (window as any).hotkeys = _hotkeys;\n    }\n    return hotkeys as HotkeysInterface;\n  };\n  (window as any).hotkeys = hotkeys;\n}\n\n// Export for both ESM and CommonJS\nexport default hotkeys as HotkeysInterface;\nexport type { KeyHandler, HotkeysEvent };\n", "/*\nStimulus-Use 0.50.0-2\n*/\nimport { Controller } from '@hotwired/stimulus';\nimport hotkeys from 'hotkeys-js';\n\nconst method = (controller, methodName) => {\n    const method = controller[methodName];\n    if (typeof method == 'function') {\n        return method;\n    }\n    else {\n        return (...args) => { };\n    }\n};\nconst composeEventName = (name, controller, eventPrefix) => {\n    let composedName = name;\n    if (eventPrefix === true) {\n        composedName = `${controller.identifier}:${name}`;\n    }\n    else if (typeof eventPrefix === 'string') {\n        composedName = `${eventPrefix}:${name}`;\n    }\n    return composedName;\n};\nconst extendedEvent = (type, event, detail) => {\n    const { bubbles, cancelable, composed } = event || { bubbles: true, cancelable: true, composed: true };\n    if (event) {\n        Object.assign(detail, { originalEvent: event });\n    }\n    const customEvent = new CustomEvent(type, {\n        bubbles,\n        cancelable,\n        composed,\n        detail\n    });\n    return customEvent;\n};\nfunction isElementInViewport(el) {\n    const rect = el.getBoundingClientRect();\n    const windowHeight = window.innerHeight || document.documentElement.clientHeight;\n    const windowWidth = window.innerWidth || document.documentElement.clientWidth;\n    const vertInView = rect.top <= windowHeight && rect.top + rect.height >= 0;\n    const horInView = rect.left <= windowWidth && rect.left + rect.width >= 0;\n    return vertInView && horInView;\n}\nfunction camelize(value) {\n    return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n}\n\nconst defaultOptions$7 = {\n    dispatchEvent: true,\n    eventPrefix: true\n};\nconst useIntersection = (controller, options = {}) => {\n    const { dispatchEvent, eventPrefix } = Object.assign({}, defaultOptions$7, options);\n    const targetElement = (options === null || options === void 0 ? void 0 : options.element) || controller.element;\n    const callback = (entries) => {\n        const [entry] = entries;\n        if (entry.isIntersecting) {\n            dispatchAppear(entry);\n        }\n        else if (controller.isVisible) {\n            dispatchDisappear(entry);\n        }\n    };\n    const dispatchAppear = (entry) => {\n        controller.isVisible = true;\n        method(controller, 'appear').call(controller, entry);\n        if (dispatchEvent) {\n            const eventName = composeEventName('appear', controller, eventPrefix);\n            const appearEvent = extendedEvent(eventName, null, { controller, entry });\n            targetElement.dispatchEvent(appearEvent);\n        }\n    };\n    const dispatchDisappear = (entry) => {\n        controller.isVisible = false;\n        method(controller, 'disappear').call(controller, entry);\n        if (dispatchEvent) {\n            const eventName = composeEventName('disappear', controller, eventPrefix);\n            const disappearEvent = extendedEvent(eventName, null, { controller, entry });\n            targetElement.dispatchEvent(disappearEvent);\n        }\n    };\n    const controllerDisconnect = controller.disconnect.bind(controller);\n    const observer = new IntersectionObserver(callback, options);\n    const observe = () => {\n        observer.observe(targetElement);\n    };\n    const unobserve = () => {\n        observer.unobserve(targetElement);\n    };\n    Object.assign(controller, {\n        isVisible: false,\n        disconnect() {\n            unobserve();\n            controllerDisconnect();\n        }\n    });\n    observe();\n    return [observe, unobserve];\n};\n\nclass IntersectionComposableController extends Controller {\n    constructor() {\n        super(...arguments);\n        this.isVisible = false;\n    }\n}\nclass IntersectionController extends IntersectionComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useIntersection(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nconst useLazyLoad = (controller, options) => {\n    const callback = (entries) => {\n        const [entry] = entries;\n        if (entry.isIntersecting && !controller.isLoaded) {\n            handleAppear();\n        }\n    };\n    const handleAppear = (entry) => {\n        const src = controller.data.get('src');\n        if (!src)\n            return;\n        const imageElement = controller.element;\n        controller.isLoading = true;\n        method(controller, 'loading').call(controller, src);\n        imageElement.onload = () => {\n            handleLoaded(src);\n        };\n        imageElement.src = src;\n    };\n    const handleLoaded = (src) => {\n        controller.isLoading = false;\n        controller.isLoaded = true;\n        method(controller, 'loaded').call(controller, src);\n    };\n    const controllerDisconnect = controller.disconnect.bind(controller);\n    const observer = new IntersectionObserver(callback, options);\n    const observe = () => {\n        observer.observe(controller.element);\n    };\n    const unobserve = () => {\n        observer.unobserve(controller.element);\n    };\n    Object.assign(controller, {\n        isVisible: false,\n        disconnect() {\n            unobserve();\n            controllerDisconnect();\n        }\n    });\n    observe();\n    return [observe, unobserve];\n};\n\nclass LazyLoadComposableController extends Controller {\n    constructor() {\n        super(...arguments);\n        this.isLoading = false;\n        this.isLoaded = false;\n    }\n}\nclass LazyLoadController extends LazyLoadComposableController {\n    constructor(context) {\n        super(context);\n        this.options = { rootMargin: '10%' };\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useLazyLoad(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nconst defaultOptions$6 = {\n    dispatchEvent: true,\n    eventPrefix: true\n};\nconst useResize = (controller, options = {}) => {\n    const { dispatchEvent, eventPrefix } = Object.assign({}, defaultOptions$6, options);\n    const targetElement = (options === null || options === void 0 ? void 0 : options.element) || controller.element;\n    const callback = (entries) => {\n        const [entry] = entries;\n        method(controller, 'resize').call(controller, entry.contentRect);\n        if (dispatchEvent) {\n            const eventName = composeEventName('resize', controller, eventPrefix);\n            const appearEvent = extendedEvent(eventName, null, {\n                controller,\n                entry\n            });\n            targetElement.dispatchEvent(appearEvent);\n        }\n    };\n    const controllerDisconnect = controller.disconnect.bind(controller);\n    const observer = new ResizeObserver(callback);\n    const observe = () => {\n        observer.observe(targetElement);\n    };\n    const unobserve = () => {\n        observer.unobserve(targetElement);\n    };\n    Object.assign(controller, {\n        disconnect() {\n            unobserve();\n            controllerDisconnect();\n        }\n    });\n    observe();\n    return [observe, unobserve];\n};\n\nclass ResizeComposableController extends Controller {\n}\nclass ResizeController extends ResizeComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useResize(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nconst defaultOptions$5 = {\n    events: ['click', 'touchend'],\n    onlyVisible: true,\n    dispatchEvent: true,\n    eventPrefix: true\n};\nconst useClickOutside = (controller, options = {}) => {\n    const { onlyVisible, dispatchEvent, events, eventPrefix } = Object.assign({}, defaultOptions$5, options);\n    const onEvent = (event) => {\n        const targetElement = (options === null || options === void 0 ? void 0 : options.element) || controller.element;\n        if (targetElement.contains(event.target) || (!isElementInViewport(targetElement) && onlyVisible)) {\n            return;\n        }\n        if (controller.clickOutside) {\n            controller.clickOutside(event);\n        }\n        if (dispatchEvent) {\n            const eventName = composeEventName('click:outside', controller, eventPrefix);\n            const clickOutsideEvent = extendedEvent(eventName, event, { controller });\n            targetElement.dispatchEvent(clickOutsideEvent);\n        }\n    };\n    const observe = () => {\n        events === null || events === void 0 ? void 0 : events.forEach(event => {\n            window.addEventListener(event, onEvent, false);\n        });\n    };\n    const unobserve = () => {\n        events === null || events === void 0 ? void 0 : events.forEach(event => {\n            window.removeEventListener(event, onEvent, false);\n        });\n    };\n    const controllerDisconnect = controller.disconnect.bind(controller);\n    Object.assign(controller, {\n        disconnect() {\n            unobserve();\n            controllerDisconnect();\n        }\n    });\n    observe();\n    return [observe, unobserve];\n};\n\nclass ClickOutsideComposableController extends Controller {\n}\nclass ClickOutsideController extends ClickOutsideComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useClickOutside(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\n\nconst defaultOptions$4 = {\n    debug: false,\n    logger: console,\n    dispatchEvent: true,\n    eventPrefix: true\n};\nclass StimulusUse {\n    constructor(controller, options = {}) {\n        var _a, _b, _c;\n        this.log = (functionName, args) => {\n            if (!this.debug)\n                return;\n            this.logger.groupCollapsed(`%c${this.controller.identifier} %c#${functionName}`, 'color: #3B82F6', 'color: unset');\n            this.logger.log(Object.assign({ controllerId: this.controllerId }, args));\n            this.logger.groupEnd();\n        };\n        this.dispatch = (eventName, details = {}) => {\n            if (this.dispatchEvent) {\n                const { event } = details, eventDetails = __rest(details, [\"event\"]);\n                const customEvent = this.extendedEvent(eventName, event || null, eventDetails);\n                this.targetElement.dispatchEvent(customEvent);\n                this.log('dispatchEvent', Object.assign({ eventName: customEvent.type }, eventDetails));\n            }\n        };\n        this.call = (methodName, args = {}) => {\n            const method = this.controller[methodName];\n            if (typeof method == 'function') {\n                return method.call(this.controller, args);\n            }\n        };\n        this.extendedEvent = (name, event, detail) => {\n            const { bubbles, cancelable, composed } = event || { bubbles: true, cancelable: true, composed: true };\n            if (event) {\n                Object.assign(detail, { originalEvent: event });\n            }\n            const customEvent = new CustomEvent(this.composeEventName(name), {\n                bubbles,\n                cancelable,\n                composed,\n                detail\n            });\n            return customEvent;\n        };\n        this.composeEventName = (name) => {\n            let composedName = name;\n            if (this.eventPrefix === true) {\n                composedName = `${this.controller.identifier}:${name}`;\n            }\n            else if (typeof this.eventPrefix === 'string') {\n                composedName = `${this.eventPrefix}:${name}`;\n            }\n            return composedName;\n        };\n        this.debug = (_b = (_a = options === null || options === void 0 ? void 0 : options.debug) !== null && _a !== void 0 ? _a : controller.application.stimulusUseDebug) !== null && _b !== void 0 ? _b : defaultOptions$4.debug;\n        this.logger = (_c = options === null || options === void 0 ? void 0 : options.logger) !== null && _c !== void 0 ? _c : defaultOptions$4.logger;\n        this.controller = controller;\n        this.controllerId = controller.element.id || controller.element.dataset.id;\n        this.targetElement = (options === null || options === void 0 ? void 0 : options.element) || controller.element;\n        const { dispatchEvent, eventPrefix } = Object.assign({}, defaultOptions$4, options);\n        Object.assign(this, { dispatchEvent, eventPrefix });\n        this.controllerInitialize = controller.initialize.bind(controller);\n        this.controllerConnect = controller.connect.bind(controller);\n        this.controllerDisconnect = controller.disconnect.bind(controller);\n    }\n}\n\nconst defaultOptions$3 = {\n    eventPrefix: true,\n    bubbles: true,\n    cancelable: true\n};\nclass UseDispatch extends StimulusUse {\n    constructor(controller, options = {}) {\n        var _a, _b, _c, _d;\n        super(controller, options);\n        this.dispatch = (eventName, detail = {}) => {\n            const { controller, targetElement, eventPrefix, bubbles, cancelable, log } = this;\n            Object.assign(detail, { controller });\n            const eventNameWithPrefix = composeEventName(eventName, this.controller, eventPrefix);\n            const event = new CustomEvent(eventNameWithPrefix, {\n                detail,\n                bubbles,\n                cancelable\n            });\n            targetElement.dispatchEvent(event);\n            log('dispatch', { eventName: eventNameWithPrefix, detail, bubbles, cancelable });\n            return event;\n        };\n        this.targetElement = (_a = options.element) !== null && _a !== void 0 ? _a : controller.element;\n        this.eventPrefix = (_b = options.eventPrefix) !== null && _b !== void 0 ? _b : defaultOptions$3.eventPrefix;\n        this.bubbles = (_c = options.bubbles) !== null && _c !== void 0 ? _c : defaultOptions$3.bubbles;\n        this.cancelable = (_d = options.cancelable) !== null && _d !== void 0 ? _d : defaultOptions$3.cancelable;\n        this.enhanceController();\n    }\n    enhanceController() {\n        Object.assign(this.controller, { dispatch: this.dispatch });\n    }\n}\nconst useDispatch = (controller, options = {}) => {\n    return new UseDispatch(controller, options);\n};\n\nconst useApplication = (controller, options = {}) => {\n    Object.defineProperty(controller, 'isPreview', {\n        get() {\n            return (document.documentElement.hasAttribute('data-turbolinks-preview') ||\n                document.documentElement.hasAttribute('data-turbo-preview'));\n        }\n    });\n    Object.defineProperty(controller, 'isConnected', {\n        get() {\n            return !!Array.from(this.context.module.connectedContexts).find(c => c === this.context);\n        }\n    });\n    Object.defineProperty(controller, 'csrfToken', {\n        get() {\n            return this.metaValue('csrf-token');\n        }\n    });\n    useDispatch(controller, options);\n    Object.assign(controller, {\n        metaValue(name) {\n            const element = document.head.querySelector(`meta[name=\"${name}\"]`);\n            return element && element.getAttribute('content');\n        }\n    });\n};\n\nclass ApplicationController extends Controller {\n    constructor(context) {\n        super(context);\n        this.isPreview = false;\n        this.isConnected = false;\n        this.csrfToken = '';\n        useApplication(this, this.options);\n    }\n}\n\nconst defaultEvents = ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel'];\nconst oneMinute = 60e3;\nconst defaultOptions$2 = {\n    ms: oneMinute,\n    initialState: false,\n    events: defaultEvents,\n    dispatchEvent: true,\n    eventPrefix: true\n};\nconst useIdle = (controller, options = {}) => {\n    const { ms, initialState, events, dispatchEvent, eventPrefix } = Object.assign({}, defaultOptions$2, options);\n    let isIdle = initialState;\n    let timeout = setTimeout(() => {\n        isIdle = true;\n        dispatchAway();\n    }, ms);\n    const dispatchAway = (event) => {\n        const eventName = composeEventName('away', controller, eventPrefix);\n        controller.isIdle = true;\n        method(controller, 'away').call(controller, event);\n        if (dispatchEvent) {\n            const clickOutsideEvent = extendedEvent(eventName, event || null, { controller });\n            controller.element.dispatchEvent(clickOutsideEvent);\n        }\n    };\n    const dispatchBack = (event) => {\n        const eventName = composeEventName('back', controller, eventPrefix);\n        controller.isIdle = false;\n        method(controller, 'back').call(controller, event);\n        if (dispatchEvent) {\n            const clickOutsideEvent = extendedEvent(eventName, event || null, { controller });\n            controller.element.dispatchEvent(clickOutsideEvent);\n        }\n    };\n    const onEvent = (event) => {\n        if (isIdle)\n            dispatchBack(event);\n        isIdle = false;\n        clearTimeout(timeout);\n        timeout = setTimeout(() => {\n            isIdle = true;\n            dispatchAway(event);\n        }, ms);\n    };\n    const onVisibility = (event) => {\n        if (!document.hidden)\n            onEvent(event);\n    };\n    if (isIdle) {\n        dispatchAway();\n    }\n    else {\n        dispatchBack();\n    }\n    const controllerDisconnect = controller.disconnect.bind(controller);\n    const observe = () => {\n        events.forEach(event => {\n            window.addEventListener(event, onEvent);\n        });\n        document.addEventListener('visibilitychange', onVisibility);\n    };\n    const unobserve = () => {\n        clearTimeout(timeout);\n        events.forEach(event => {\n            window.removeEventListener(event, onEvent);\n        });\n        document.removeEventListener('visibilitychange', onVisibility);\n    };\n    Object.assign(controller, {\n        disconnect() {\n            unobserve();\n            controllerDisconnect();\n        }\n    });\n    observe();\n    return [observe, unobserve];\n};\n\nclass IdleComposableController extends Controller {\n    constructor() {\n        super(...arguments);\n        this.isIdle = false;\n    }\n}\nclass IdleController extends IdleComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useIdle(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nclass UseVisibility extends StimulusUse {\n    constructor(controller, options = {}) {\n        super(controller, options);\n        this.observe = () => {\n            this.controller.isVisible = !document.hidden;\n            document.addEventListener('visibilitychange', this.handleVisibilityChange);\n            this.handleVisibilityChange();\n        };\n        this.unobserve = () => {\n            document.removeEventListener('visibilitychange', this.handleVisibilityChange);\n        };\n        this.becomesInvisible = (event) => {\n            this.controller.isVisible = false;\n            this.call('invisible', event);\n            this.log('invisible', { isVisible: false });\n            this.dispatch('invisible', { event, isVisible: false });\n        };\n        this.becomesVisible = (event) => {\n            this.controller.isVisible = true;\n            this.call('visible', event);\n            this.log('visible', { isVisible: true });\n            this.dispatch('visible', { event, isVisible: true });\n        };\n        this.handleVisibilityChange = (event) => {\n            if (document.hidden) {\n                this.becomesInvisible(event);\n            }\n            else {\n                this.becomesVisible(event);\n            }\n        };\n        this.controller = controller;\n        this.enhanceController();\n        this.observe();\n    }\n    enhanceController() {\n        const controllerDisconnect = this.controllerDisconnect;\n        const disconnect = () => {\n            this.unobserve();\n            controllerDisconnect();\n        };\n        Object.assign(this.controller, { disconnect });\n    }\n}\nconst useVisibility = (controller, options = {}) => {\n    const observer = new UseVisibility(controller, options);\n    return [observer.observe, observer.unobserve];\n};\n\nclass VisibilityComposableController extends Controller {\n    constructor() {\n        super(...arguments);\n        this.isVisible = false;\n    }\n}\nclass VisibilityController extends VisibilityComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useVisibility(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nclass UseHover extends StimulusUse {\n    constructor(controller, options = {}) {\n        super(controller, options);\n        this.observe = () => {\n            this.targetElement.addEventListener('mouseenter', this.onEnter);\n            this.targetElement.addEventListener('mouseleave', this.onLeave);\n        };\n        this.unobserve = () => {\n            this.targetElement.removeEventListener('mouseenter', this.onEnter);\n            this.targetElement.removeEventListener('mouseleave', this.onLeave);\n        };\n        this.onEnter = (event) => {\n            this.call('mouseEnter', event);\n            this.log('mouseEnter', { hover: true });\n            this.dispatch('mouseEnter', { hover: false });\n        };\n        this.onLeave = (event) => {\n            this.call('mouseLeave', event);\n            this.log('mouseLeave', { hover: false });\n            this.dispatch('mouseLeave', { hover: false });\n        };\n        this.controller = controller;\n        this.enhanceController();\n        this.observe();\n    }\n    enhanceController() {\n        const controllerDisconnect = this.controller.disconnect.bind(this.controller);\n        const disconnect = () => {\n            this.unobserve();\n            controllerDisconnect();\n        };\n        Object.assign(this.controller, { disconnect });\n    }\n}\nconst useHover = (controller, options = {}) => {\n    const observer = new UseHover(controller, options);\n    return [observer.observe, observer.unobserve];\n};\n\nclass HoverComposableController extends Controller {\n}\nclass HoverController extends HoverComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useHover(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nclass UseMutation extends StimulusUse {\n    constructor(controller, options = {}) {\n        super(controller, options);\n        this.observe = () => {\n            try {\n                this.observer.observe(this.targetElement, this.options);\n            }\n            catch (error) {\n                this.controller.application.handleError(error, 'At a minimum, one of childList, attributes, and/or characterData must be true', {});\n            }\n        };\n        this.unobserve = () => {\n            this.observer.disconnect();\n        };\n        this.mutation = (entries) => {\n            this.call('mutate', entries);\n            this.log('mutate', { entries });\n            this.dispatch('mutate', { entries });\n        };\n        this.targetElement = (options === null || options === void 0 ? void 0 : options.element) || controller.element;\n        this.controller = controller;\n        this.options = options;\n        this.observer = new MutationObserver(this.mutation);\n        this.enhanceController();\n        this.observe();\n    }\n    enhanceController() {\n        const controllerDisconnect = this.controller.disconnect.bind(this.controller);\n        const disconnect = () => {\n            this.unobserve();\n            controllerDisconnect();\n        };\n        Object.assign(this.controller, { disconnect });\n    }\n}\nconst useMutation = (controller, options = {}) => {\n    const observer = new UseMutation(controller, options);\n    return [observer.observe, observer.unobserve];\n};\n\nclass MutationComposableController extends Controller {\n}\nclass MutationController extends MutationComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useMutation(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nclass UseTargetMutation extends StimulusUse {\n    constructor(controller, options = {}) {\n        super(controller, options);\n        this.observe = () => {\n            this.observer.observe(this.targetElement, {\n                subtree: true,\n                characterData: true,\n                childList: true,\n                attributes: true,\n                attributeOldValue: true,\n                attributeFilter: [this.targetSelector, this.scopedTargetSelector]\n            });\n        };\n        this.unobserve = () => {\n            this.observer.disconnect();\n        };\n        this.mutation = (entries) => {\n            for (const mutation of entries) {\n                switch (mutation.type) {\n                    case 'attributes':\n                        let newValue = mutation.target.getAttribute(mutation.attributeName);\n                        let oldValue = mutation.oldValue;\n                        if (mutation.attributeName === this.targetSelector || mutation.attributeName === this.scopedTargetSelector) {\n                            let oldTargets = this.targetsUsedByThisController(oldValue);\n                            let newTargets = this.targetsUsedByThisController(newValue);\n                            let removedTargets = oldTargets.filter(target => !newTargets.includes(target));\n                            let addedTargets = newTargets.filter(target => !oldTargets.includes(target));\n                            removedTargets.forEach(target => this.targetRemoved(this.stripIdentifierPrefix(target), mutation.target, 'attributeChange'));\n                            addedTargets.forEach(target => this.targetAdded(this.stripIdentifierPrefix(target), mutation.target, 'attributeChange'));\n                        }\n                        break;\n                    case 'characterData':\n                        let nodule = this.findTargetInAncestry(mutation.target);\n                        if (nodule == null) {\n                            return;\n                        }\n                        else {\n                            let supportedTargets = this.targetsUsedByThisControllerFromNode(nodule);\n                            supportedTargets.forEach((target) => {\n                                this.targetChanged(this.stripIdentifierPrefix(target), nodule, 'domMutation');\n                            });\n                        }\n                        break;\n                    case 'childList':\n                        let { addedNodes, removedNodes } = mutation;\n                        addedNodes.forEach((node) => this.processNodeDOMMutation(node, this.targetAdded));\n                        removedNodes.forEach((node) => this.processNodeDOMMutation(node, this.targetRemoved));\n                        break;\n                }\n            }\n        };\n        this.controller = controller;\n        this.options = options;\n        this.targetElement = controller.element;\n        this.identifier = controller.scope.identifier;\n        this.identifierPrefix = `${this.identifier}.`;\n        this.targetSelector = controller.scope.schema.targetAttribute;\n        this.scopedTargetSelector = `data-${this.identifier}-target`;\n        this.targets = options.targets || controller.constructor.targets;\n        this.prefixedTargets = this.targets.map(target => `${this.identifierPrefix}${target}`);\n        this.observer = new MutationObserver(this.mutation);\n        this.enhanceController();\n        this.observe();\n    }\n    processNodeDOMMutation(node, initialChangeModeAssumption) {\n        let nodule = node;\n        let change = initialChangeModeAssumption;\n        let supportedTargets = [];\n        if (nodule.nodeName == '#text' || this.targetsUsedByThisControllerFromNode(nodule).length == 0) {\n            change = this.targetChanged;\n            nodule = this.findTargetInAncestry(node);\n        }\n        else {\n            supportedTargets = this.targetsUsedByThisControllerFromNode(nodule);\n        }\n        if (nodule == null) {\n            return;\n        }\n        else if (supportedTargets.length == 0) {\n            supportedTargets = this.targetsUsedByThisControllerFromNode(nodule);\n        }\n        supportedTargets.forEach((target) => {\n            change.call(this, this.stripIdentifierPrefix(target), nodule, 'domMutation');\n        });\n    }\n    findTargetInAncestry(node) {\n        let nodule = node;\n        let supportedTargets = [];\n        if (nodule.nodeName != '#text') {\n            supportedTargets = this.targetsUsedByThisControllerFromNode(nodule);\n        }\n        while (nodule.parentNode !== null && nodule.parentNode != this.targetElement && supportedTargets.length == 0) {\n            nodule = nodule.parentNode;\n            if (nodule.nodeName !== '#text') {\n                let supportedTargets = this.targetsUsedByThisControllerFromNode(nodule);\n                if (supportedTargets.length > 0) {\n                    return nodule;\n                }\n            }\n        }\n        if (nodule.nodeName == '#text') {\n            return null;\n        }\n        if (nodule.parentNode == null) {\n            return null;\n        }\n        if (nodule.parentNode == this.targetElement) {\n            if (this.targetsUsedByThisControllerFromNode(nodule).length > 0) {\n                return nodule;\n            }\n            return null;\n        }\n        return null;\n    }\n    targetAdded(name, node, trigger) {\n        let targetCallback = `${name}TargetAdded`;\n        this.controller[targetCallback] && method(this.controller, targetCallback).call(this.controller, node);\n        this.log('targetAdded', { target: name, node, trigger });\n    }\n    targetRemoved(name, node, trigger) {\n        let targetCallback = `${name}TargetRemoved`;\n        this.controller[targetCallback] && method(this.controller, targetCallback).call(this.controller, node);\n        this.log('targetRemoved', { target: name, node, trigger });\n    }\n    targetChanged(name, node, trigger) {\n        let targetCallback = `${name}TargetChanged`;\n        this.controller[targetCallback] && method(this.controller, targetCallback).call(this.controller, node);\n        this.log('targetChanged', { target: name, node, trigger });\n    }\n    targetsUsedByThisControllerFromNode(node) {\n        if (node.nodeName == '#text' || node.nodeName == '#comment') {\n            return [];\n        }\n        let nodeElement = node;\n        return this.targetsUsedByThisController(nodeElement.getAttribute(this.scopedTargetSelector) || nodeElement.getAttribute(this.targetSelector));\n    }\n    targetsUsedByThisController(targetStr) {\n        targetStr = targetStr || '';\n        let targetsToCheck = this.stripIdentifierPrefix(targetStr).split(' ');\n        return this.targets.filter(n => targetsToCheck.indexOf(n) !== -1);\n    }\n    stripIdentifierPrefix(target) {\n        return target.replace(new RegExp(this.identifierPrefix, 'g'), '');\n    }\n    enhanceController() {\n        const controllerDisconnect = this.controller.disconnect.bind(this.controller);\n        const disconnect = () => {\n            this.unobserve();\n            controllerDisconnect();\n        };\n        Object.assign(this.controller, { disconnect });\n    }\n}\nconst useTargetMutation = (controller, options = {}) => {\n    const observer = new UseTargetMutation(controller, options);\n    return [observer.observe, observer.unobserve];\n};\n\nclass TargetMutationComposableController extends Controller {\n}\nclass TargetMutationController extends TargetMutationComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useTargetMutation(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nconst useWindowResize = (controller) => {\n    const callback = (event) => {\n        const { innerWidth, innerHeight } = window;\n        const payload = {\n            height: innerHeight || Infinity,\n            width: innerWidth || Infinity,\n            event\n        };\n        method(controller, 'windowResize').call(controller, payload);\n    };\n    const controllerDisconnect = controller.disconnect.bind(controller);\n    const observe = () => {\n        window.addEventListener('resize', callback);\n        callback();\n    };\n    const unobserve = () => {\n        window.removeEventListener('resize', callback);\n    };\n    Object.assign(controller, {\n        disconnect() {\n            unobserve();\n            controllerDisconnect();\n        }\n    });\n    observe();\n    return [observe, unobserve];\n};\n\nclass WindowResizeComposableController extends Controller {\n}\nclass WindowResizeController extends WindowResizeComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useWindowResize(this);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nconst memoize = (controller, name, value) => {\n    Object.defineProperty(controller, name, { value });\n    return value;\n};\nconst useMemo = (controller) => {\n    var _a;\n    (_a = controller.constructor.memos) === null || _a === void 0 ? void 0 : _a.forEach((getter) => {\n        memoize(controller, getter, controller[getter]);\n    });\n};\n\nclass DebounceController extends Controller {\n}\nDebounceController.debounces = [];\nconst defaultWait$1 = 200;\nconst debounce = (fn, wait = defaultWait$1) => {\n    let timeoutId = null;\n    return function () {\n        const args = arguments;\n        const context = this;\n        const callback = () => fn.apply(context, args);\n        if (timeoutId) {\n            clearTimeout(timeoutId);\n        }\n        timeoutId = setTimeout(callback, wait);\n    };\n};\nconst useDebounce = (controller, options) => {\n    var _a;\n    const constructor = controller.constructor;\n    (_a = constructor.debounces) === null || _a === void 0 ? void 0 : _a.forEach((func) => {\n        if (typeof func === 'string') {\n            controller[func] = debounce(controller[func], options === null || options === void 0 ? void 0 : options.wait);\n        }\n        if (typeof func === 'object') {\n            const { name, wait } = func;\n            if (!name)\n                return;\n            controller[name] = debounce(controller[name], wait || (options === null || options === void 0 ? void 0 : options.wait));\n        }\n    });\n};\n\nclass ThrottleController extends Controller {\n}\nThrottleController.throttles = [];\nconst defaultWait = 200;\nfunction throttle(func, wait = defaultWait) {\n    let inThrottle;\n    return function () {\n        const args = arguments;\n        const context = this;\n        if (!inThrottle) {\n            inThrottle = true;\n            func.apply(context, args);\n            setTimeout(() => (inThrottle = false), wait);\n        }\n    };\n}\nconst useThrottle = (controller, options = {}) => {\n    var _a;\n    const constructor = controller.constructor;\n    (_a = constructor.throttles) === null || _a === void 0 ? void 0 : _a.forEach((func) => {\n        if (typeof func === 'string') {\n            controller[func] = throttle(controller[func], options === null || options === void 0 ? void 0 : options.wait);\n        }\n        if (typeof func === 'object') {\n            const { name, wait } = func;\n            if (!name)\n                return;\n            controller[name] = throttle(controller[name], wait || (options === null || options === void 0 ? void 0 : options.wait));\n        }\n    });\n};\n\nconst defineMetaGetter = (controller, metaName, suffix) => {\n    const getterName = suffix ? `${camelize(metaName)}Meta` : camelize(metaName);\n    Object.defineProperty(controller, getterName, {\n        get() {\n            return typeCast(metaValue(metaName));\n        }\n    });\n};\nfunction metaValue(name) {\n    const element = document.head.querySelector(`meta[name=\"${name}\"]`);\n    return element && element.getAttribute('content');\n}\nfunction typeCast(value) {\n    try {\n        return JSON.parse(value);\n    }\n    catch (o_O) {\n        return value;\n    }\n}\nconst useMeta = (controller, options = { suffix: true }) => {\n    const metaNames = controller.constructor.metaNames;\n    const suffix = options.suffix;\n    metaNames === null || metaNames === void 0 ? void 0 : metaNames.forEach((metaName) => {\n        defineMetaGetter(controller, metaName, suffix);\n    });\n    Object.defineProperty(controller, 'metas', {\n        get() {\n            const result = {};\n            metaNames === null || metaNames === void 0 ? void 0 : metaNames.forEach((metaName) => {\n                const value = typeCast(metaValue(metaName));\n                if (value !== undefined && value !== null) {\n                    result[camelize(metaName)] = value;\n                }\n            });\n            return result;\n        }\n    });\n};\n\nconst alpineNames = {\n    enterFromClass: 'enter',\n    enterActiveClass: 'enterStart',\n    enterToClass: 'enterEnd',\n    leaveFromClass: 'leave',\n    leaveActiveClass: 'leaveStart',\n    leaveToClass: 'leaveEnd'\n};\nconst defaultOptions$1 = {\n    transitioned: false,\n    hiddenClass: 'hidden',\n    preserveOriginalClass: true,\n    removeToClasses: true\n};\nconst useTransition = (controller, options = {}) => {\n    var _a, _b, _c;\n    const targetName = controller.element.dataset.transitionTarget;\n    let targetFromAttribute;\n    if (targetName) {\n        targetFromAttribute = controller[`${targetName}Target`];\n    }\n    const targetElement = (options === null || options === void 0 ? void 0 : options.element) || targetFromAttribute || controller.element;\n    if (!(targetElement instanceof HTMLElement || targetElement instanceof SVGElement))\n        return;\n    const dataset = targetElement.dataset;\n    const leaveAfter = parseInt(dataset.leaveAfter || '') || options.leaveAfter || 0;\n    const { transitioned, hiddenClass, preserveOriginalClass, removeToClasses } = Object.assign(defaultOptions$1, options);\n    const controllerEnter = (_a = controller.enter) === null || _a === void 0 ? void 0 : _a.bind(controller);\n    const controllerLeave = (_b = controller.leave) === null || _b === void 0 ? void 0 : _b.bind(controller);\n    const controllerToggleTransition = (_c = controller.toggleTransition) === null || _c === void 0 ? void 0 : _c.bind(controller);\n    async function enter(event) {\n        if (controller.transitioned)\n            return;\n        controller.transitioned = true;\n        controllerEnter && controllerEnter(event);\n        const enterFromClasses = getAttribute('enterFrom', options, dataset);\n        const enterActiveClasses = getAttribute('enterActive', options, dataset);\n        const enterToClasses = getAttribute('enterTo', options, dataset);\n        const leaveToClasses = getAttribute('leaveTo', options, dataset);\n        if (!!hiddenClass) {\n            targetElement.classList.remove(hiddenClass);\n        }\n        if (!removeToClasses) {\n            removeClasses(targetElement, leaveToClasses);\n        }\n        await transition(targetElement, enterFromClasses, enterActiveClasses, enterToClasses, hiddenClass, preserveOriginalClass, removeToClasses);\n        if (leaveAfter > 0) {\n            setTimeout(() => {\n                leave(event);\n            }, leaveAfter);\n        }\n    }\n    async function leave(event) {\n        if (!controller.transitioned)\n            return;\n        controller.transitioned = false;\n        controllerLeave && controllerLeave(event);\n        const leaveFromClasses = getAttribute('leaveFrom', options, dataset);\n        const leaveActiveClasses = getAttribute('leaveActive', options, dataset);\n        const leaveToClasses = getAttribute('leaveTo', options, dataset);\n        const enterToClasses = getAttribute('enterTo', options, dataset);\n        if (!removeToClasses) {\n            removeClasses(targetElement, enterToClasses);\n        }\n        await transition(targetElement, leaveFromClasses, leaveActiveClasses, leaveToClasses, hiddenClass, preserveOriginalClass, removeToClasses);\n        if (!!hiddenClass) {\n            targetElement.classList.add(hiddenClass);\n        }\n    }\n    function toggleTransition(event) {\n        controllerToggleTransition && controllerToggleTransition(event);\n        if (controller.transitioned) {\n            leave();\n        }\n        else {\n            enter();\n        }\n    }\n    async function transition(element, initialClasses, activeClasses, endClasses, hiddenClass, preserveOriginalClass, removeEndClasses) {\n        const stashedClasses = [];\n        if (preserveOriginalClass) {\n            initialClasses.forEach(cls => element.classList.contains(cls) && cls !== hiddenClass && stashedClasses.push(cls));\n            activeClasses.forEach(cls => element.classList.contains(cls) && cls !== hiddenClass && stashedClasses.push(cls));\n            endClasses.forEach(cls => element.classList.contains(cls) && cls !== hiddenClass && stashedClasses.push(cls));\n        }\n        addClasses(element, initialClasses);\n        removeClasses(element, stashedClasses);\n        addClasses(element, activeClasses);\n        await nextAnimationFrame();\n        removeClasses(element, initialClasses);\n        addClasses(element, endClasses);\n        await afterTransition(element);\n        removeClasses(element, activeClasses);\n        if (removeEndClasses) {\n            removeClasses(element, endClasses);\n        }\n        addClasses(element, stashedClasses);\n    }\n    function initialState() {\n        controller.transitioned = transitioned;\n        if (transitioned) {\n            if (!!hiddenClass) {\n                targetElement.classList.remove(hiddenClass);\n            }\n            enter();\n        }\n        else {\n            if (!!hiddenClass) {\n                targetElement.classList.add(hiddenClass);\n            }\n            leave();\n        }\n    }\n    function addClasses(element, classes) {\n        if (classes.length > 0) {\n            element.classList.add(...classes);\n        }\n    }\n    function removeClasses(element, classes) {\n        if (classes.length > 0) {\n            element.classList.remove(...classes);\n        }\n    }\n    initialState();\n    Object.assign(controller, { enter, leave, toggleTransition });\n    return [enter, leave, toggleTransition];\n};\nfunction getAttribute(name, options, dataset) {\n    const datasetName = `transition${name[0].toUpperCase()}${name.substr(1)}`;\n    const datasetAlpineName = alpineNames[name];\n    const classes = options[name] || dataset[datasetName] || dataset[datasetAlpineName] || ' ';\n    return isEmpty(classes) ? [] : classes.split(' ');\n}\nasync function afterTransition(element) {\n    return new Promise(resolve => {\n        const duration = Number(getComputedStyle(element).transitionDuration.split(',')[0].replace('s', '')) * 1000;\n        setTimeout(() => {\n            resolve(duration);\n        }, duration);\n    });\n}\nasync function nextAnimationFrame() {\n    return new Promise(resolve => {\n        requestAnimationFrame(() => {\n            requestAnimationFrame(resolve);\n        });\n    });\n}\nfunction isEmpty(str) {\n    return str.length === 0 || !str.trim();\n}\n\nclass TransitionComposableController extends Controller {\n    constructor() {\n        super(...arguments);\n        this.transitioned = false;\n    }\n}\nclass TransitionController extends TransitionComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            useTransition(this, this.options);\n        });\n    }\n}\n\nclass UseHotkeys extends StimulusUse {\n    constructor(controller, hotkeysOptions) {\n        super(controller, hotkeysOptions);\n        this.bind = () => {\n            for (const [hotkey, definition] of Object.entries(this.hotkeysOptions.hotkeys)) {\n                const handler = definition.handler.bind(this.controller);\n                hotkeys(hotkey, definition.options, (e) => handler(e, e));\n            }\n        };\n        this.unbind = () => {\n            for (const hotkey in this.hotkeysOptions.hotkeys) {\n                hotkeys.unbind(hotkey);\n            }\n        };\n        this.controller = controller;\n        this.hotkeysOptions = hotkeysOptions;\n        this.enhanceController();\n        this.bind();\n    }\n    enhanceController() {\n        if (this.hotkeysOptions.filter) {\n            hotkeys.filter = this.hotkeysOptions.filter;\n        }\n        const controllerDisconnect = this.controller.disconnect.bind(this.controller);\n        const disconnect = () => {\n            this.unbind();\n            controllerDisconnect();\n        };\n        Object.assign(this.controller, { disconnect });\n    }\n}\nconst convertSimpleHotkeyDefinition = (definition) => {\n    return {\n        handler: definition[0],\n        options: {\n            element: definition[1]\n        }\n    };\n};\nconst coerceOptions = (options) => {\n    if (!options.hotkeys) {\n        const hotkeys = {};\n        Object.entries(options).forEach(([hotkey, definition]) => {\n            Object.defineProperty(hotkeys, hotkey, {\n                value: convertSimpleHotkeyDefinition(definition),\n                writable: false,\n                enumerable: true\n            });\n        });\n        options = {\n            hotkeys\n        };\n    }\n    return options;\n};\nconst useHotkeys = (controller, options) => {\n    return new UseHotkeys(controller, coerceOptions(options));\n};\n\nconst defaultOptions = {\n    mediaQueries: {},\n    dispatchEvent: true,\n    eventPrefix: true,\n    debug: false\n};\nclass UseMatchMedia extends StimulusUse {\n    constructor(controller, options = {}) {\n        var _a, _b, _c, _d;\n        super(controller, options);\n        this.matches = [];\n        this.callback = (event) => {\n            const name = Object.keys(this.mediaQueries).find(name => this.mediaQueries[name] === event.media);\n            if (!name)\n                return;\n            const { media, matches } = event;\n            this.changed({ name, media, matches, event });\n        };\n        this.changed = (payload) => {\n            const { name } = payload;\n            if (payload.event) {\n                this.call(camelize(`${name}_changed`), payload);\n                this.dispatch(`${name}:changed`, payload);\n                this.log(`media query \"${name}\" changed`, payload);\n            }\n            if (payload.matches) {\n                this.call(camelize(`is_${name}`), payload);\n                this.dispatch(`is:${name}`, payload);\n            }\n            else {\n                this.call(camelize(`not_${name}`), payload);\n                this.dispatch(`not:${name}`, payload);\n            }\n        };\n        this.observe = () => {\n            Object.keys(this.mediaQueries).forEach(name => {\n                const media = this.mediaQueries[name];\n                const match = window.matchMedia(media);\n                match.addListener(this.callback);\n                this.matches.push(match);\n                this.changed({ name, media, matches: match.matches });\n            });\n        };\n        this.unobserve = () => {\n            this.matches.forEach(match => match.removeListener(this.callback));\n        };\n        this.controller = controller;\n        this.mediaQueries = (_a = options.mediaQueries) !== null && _a !== void 0 ? _a : defaultOptions.mediaQueries;\n        this.dispatchEvent = (_b = options.dispatchEvent) !== null && _b !== void 0 ? _b : defaultOptions.dispatchEvent;\n        this.eventPrefix = (_c = options.eventPrefix) !== null && _c !== void 0 ? _c : defaultOptions.eventPrefix;\n        this.debug = (_d = options.debug) !== null && _d !== void 0 ? _d : defaultOptions.debug;\n        if (!window.matchMedia) {\n            console.error('window.matchMedia() is not available');\n            return;\n        }\n        this.enhanceController();\n        this.observe();\n    }\n    enhanceController() {\n        const controllerDisconnect = this.controller.disconnect.bind(this.controller);\n        const disconnect = () => {\n            this.unobserve();\n            controllerDisconnect();\n        };\n        Object.assign(this.controller, { disconnect });\n    }\n}\nconst useMatchMedia = (controller, options = {}) => {\n    const observer = new UseMatchMedia(controller, options);\n    return [observer.observe, observer.unobserve];\n};\n\nclass UseWindowFocus extends StimulusUse {\n    constructor(controller, options = {}) {\n        super(controller, options);\n        this.observe = () => {\n            if (document.hasFocus()) {\n                this.becomesFocused();\n            }\n            else {\n                console.log('i should be there');\n                this.becomesUnfocused();\n            }\n            this.interval = setInterval(() => {\n                this.handleWindowFocusChange();\n            }, this.intervalDuration);\n        };\n        this.unobserve = () => {\n            clearInterval(this.interval);\n        };\n        this.becomesUnfocused = (event) => {\n            this.controller.hasFocus = false;\n            this.call('unfocus', event);\n            this.log('unfocus', { hasFocus: false });\n            this.dispatch('unfocus', { event, hasFocus: false });\n        };\n        this.becomesFocused = (event) => {\n            this.controller.hasFocus = true;\n            this.call('focus', event);\n            this.log('focus', { hasFocus: true });\n            this.dispatch('focus', { event, hasFocus: true });\n        };\n        this.handleWindowFocusChange = (event) => {\n            if (document.hasFocus() && !this.controller.hasFocus) {\n                this.becomesFocused(event);\n            }\n            else if (!document.hasFocus() && this.controller.hasFocus) {\n                this.becomesUnfocused(event);\n            }\n        };\n        this.controller = controller;\n        this.intervalDuration = options.interval || 200;\n        this.enhanceController();\n        this.observe();\n    }\n    enhanceController() {\n        const controllerDisconnect = this.controllerDisconnect;\n        const disconnect = () => {\n            this.unobserve();\n            controllerDisconnect();\n        };\n        Object.assign(this.controller, { disconnect });\n    }\n}\nconst useWindowFocus = (controller, options = {}) => {\n    const observer = new UseWindowFocus(controller, options);\n    return [observer.observe, observer.unobserve];\n};\n\nclass WindowFocusComposableController extends Controller {\n    constructor() {\n        super(...arguments);\n        this.hasFocus = false;\n    }\n}\nclass WindowFocusController extends WindowFocusComposableController {\n    constructor(context) {\n        super(context);\n        requestAnimationFrame(() => {\n            const [observe, unobserve] = useWindowFocus(this, this.options);\n            Object.assign(this, { observe, unobserve });\n        });\n    }\n}\n\nexport { ApplicationController, ClickOutsideController, HoverController, IdleController, IntersectionController, LazyLoadController, MutationController, ResizeController, TargetMutationController, TransitionController, UseHover, UseMutation, UseTargetMutation, UseVisibility, VisibilityController, WindowFocusController, WindowResizeController, useApplication, useClickOutside, useDebounce, useDispatch, useHotkeys, useHover, useIdle, useIntersection, useLazyLoad, useMatchMedia, useMemo, useMeta, useMutation, useResize, useTargetMutation, useThrottle, useTransition, useVisibility, useWindowFocus, useWindowResize };\n", "import \"./item_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./item_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./tree_component.css\";\nimport Sortable from 'sortablejs';\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static targets = [\"subtree\"];\n  static values = { reorderable: Boolean };\n\n  connect() {\n    if (this.reorderableValue) {\n      this.connectReorderable();\n    }\n  }\n\n  connectReorderable() {\n    this.sortables = [];\n\n    this.subtreeTargets.forEach(subtree => {\n      this.sortables.push(\n        Sortable.create(\n          subtree,\n          {\n            animation: 150,\n            draggable: \".c-admin--list--tree--item-root\",\n            fallbackOnBody: true,\n            group: this.identifier,\n            swapThreshold: 0.65,\n            onMove: e => {\n              // prevent dropping above first item content\n              if (e.related.classList.contains('c-admin--list--tree--item-content')) return false;\n            }\n          }\n        )\n      );\n    });\n  }\n\n  disconnect() {\n    if (this.reorderableValue) {\n      this.disconnectReorderable();\n    }\n  }\n\n  disconnectReorderable() {\n    this.sortable.destroy();\n  }\n}\n", "/**!\n * Sortable 1.15.7\n * @author\tRubaXa   <trash@rubaxa.org>\n * @author\towenm    <owen23355@gmail.com>\n * @license MIT\n */\nfunction _arrayLikeToArray(r, a) {\n  (null == a || a > r.length) && (a = r.length);\n  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n  return n;\n}\nfunction _arrayWithoutHoles(r) {\n  if (Array.isArray(r)) return _arrayLikeToArray(r);\n}\nfunction _defineProperty(e, r, t) {\n  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n    value: t,\n    enumerable: !0,\n    configurable: !0,\n    writable: !0\n  }) : e[r] = t, e;\n}\nfunction _extends() {\n  return _extends = Object.assign ? Object.assign.bind() : function (n) {\n    for (var e = 1; e < arguments.length; e++) {\n      var t = arguments[e];\n      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n    }\n    return n;\n  }, _extends.apply(null, arguments);\n}\nfunction _iterableToArray(r) {\n  if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nfunction _nonIterableSpread() {\n  throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction ownKeys(e, r) {\n  var t = Object.keys(e);\n  if (Object.getOwnPropertySymbols) {\n    var o = Object.getOwnPropertySymbols(e);\n    r && (o = o.filter(function (r) {\n      return Object.getOwnPropertyDescriptor(e, r).enumerable;\n    })), t.push.apply(t, o);\n  }\n  return t;\n}\nfunction _objectSpread2(e) {\n  for (var r = 1; r < arguments.length; r++) {\n    var t = null != arguments[r] ? arguments[r] : {};\n    r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n      _defineProperty(e, r, t[r]);\n    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n      Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n    });\n  }\n  return e;\n}\nfunction _objectWithoutProperties(e, t) {\n  if (null == e) return {};\n  var o,\n    r,\n    i = _objectWithoutPropertiesLoose(e, t);\n  if (Object.getOwnPropertySymbols) {\n    var n = Object.getOwnPropertySymbols(e);\n    for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);\n  }\n  return i;\n}\nfunction _objectWithoutPropertiesLoose(r, e) {\n  if (null == r) return {};\n  var t = {};\n  for (var n in r) if ({}.hasOwnProperty.call(r, n)) {\n    if (-1 !== e.indexOf(n)) continue;\n    t[n] = r[n];\n  }\n  return t;\n}\nfunction _toConsumableArray(r) {\n  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();\n}\nfunction _toPrimitive(t, r) {\n  if (\"object\" != typeof t || !t) return t;\n  var e = t[Symbol.toPrimitive];\n  if (void 0 !== e) {\n    var i = e.call(t, r || \"default\");\n    if (\"object\" != typeof i) return i;\n    throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n  }\n  return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n  var i = _toPrimitive(t, \"string\");\n  return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _typeof(o) {\n  \"@babel/helpers - typeof\";\n\n  return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n    return typeof o;\n  } : function (o) {\n    return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n  }, _typeof(o);\n}\nfunction _unsupportedIterableToArray(r, a) {\n  if (r) {\n    if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n    var t = {}.toString.call(r).slice(8, -1);\n    return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n  }\n}\n\nvar version = \"1.15.7\";\n\nfunction userAgent(pattern) {\n  if (typeof window !== 'undefined' && window.navigator) {\n    return !! /*@__PURE__*/navigator.userAgent.match(pattern);\n  }\n}\nvar IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\\.|msie|iemobile|Windows Phone)/i);\nvar Edge = userAgent(/Edge/i);\nvar FireFox = userAgent(/firefox/i);\nvar Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);\nvar IOS = userAgent(/iP(ad|od|hone)/i);\nvar ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);\n\nvar captureMode = {\n  capture: false,\n  passive: false\n};\nfunction on(el, event, fn) {\n  el.addEventListener(event, fn, !IE11OrLess && captureMode);\n}\nfunction off(el, event, fn) {\n  el.removeEventListener(event, fn, !IE11OrLess && captureMode);\n}\nfunction matches( /**HTMLElement*/el, /**String*/selector) {\n  if (!selector) return;\n  selector[0] === '>' && (selector = selector.substring(1));\n  if (el) {\n    try {\n      if (el.matches) {\n        return el.matches(selector);\n      } else if (el.msMatchesSelector) {\n        return el.msMatchesSelector(selector);\n      } else if (el.webkitMatchesSelector) {\n        return el.webkitMatchesSelector(selector);\n      }\n    } catch (_) {\n      return false;\n    }\n  }\n  return false;\n}\nfunction getParentOrHost(el) {\n  return el.host && el !== document && el.host.nodeType && el.host !== el ? el.host : el.parentNode;\n}\nfunction closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) {\n  if (el) {\n    ctx = ctx || document;\n    do {\n      if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {\n        return el;\n      }\n      if (el === ctx) break;\n      /* jshint boss:true */\n    } while (el = getParentOrHost(el));\n  }\n  return null;\n}\nvar R_SPACE = /\\s+/g;\nfunction toggleClass(el, name, state) {\n  if (el && name) {\n    if (el.classList) {\n      el.classList[state ? 'add' : 'remove'](name);\n    } else {\n      var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');\n      el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');\n    }\n  }\n}\nfunction css(el, prop, val) {\n  var style = el && el.style;\n  if (style) {\n    if (val === void 0) {\n      if (document.defaultView && document.defaultView.getComputedStyle) {\n        val = document.defaultView.getComputedStyle(el, '');\n      } else if (el.currentStyle) {\n        val = el.currentStyle;\n      }\n      return prop === void 0 ? val : val[prop];\n    } else {\n      if (!(prop in style) && prop.indexOf('webkit') === -1) {\n        prop = '-webkit-' + prop;\n      }\n      style[prop] = val + (typeof val === 'string' ? '' : 'px');\n    }\n  }\n}\nfunction matrix(el, selfOnly) {\n  var appliedTransforms = '';\n  if (typeof el === 'string') {\n    appliedTransforms = el;\n  } else {\n    do {\n      var transform = css(el, 'transform');\n      if (transform && transform !== 'none') {\n        appliedTransforms = transform + ' ' + appliedTransforms;\n      }\n      /* jshint boss:true */\n    } while (!selfOnly && (el = el.parentNode));\n  }\n  var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix;\n  /*jshint -W056 */\n  return matrixFn && new matrixFn(appliedTransforms);\n}\nfunction find(ctx, tagName, iterator) {\n  if (ctx) {\n    var list = ctx.getElementsByTagName(tagName),\n      i = 0,\n      n = list.length;\n    if (iterator) {\n      for (; i < n; i++) {\n        iterator(list[i], i);\n      }\n    }\n    return list;\n  }\n  return [];\n}\nfunction getWindowScrollingElement() {\n  var scrollingElement = document.scrollingElement;\n  if (scrollingElement) {\n    return scrollingElement;\n  } else {\n    return document.documentElement;\n  }\n}\n\n/**\r\n * Returns the \"bounding client rect\" of given element\r\n * @param  {HTMLElement} el                       The element whose boundingClientRect is wanted\r\n * @param  {[Boolean]} relativeToContainingBlock  Whether the rect should be relative to the containing block of (including) the container\r\n * @param  {[Boolean]} relativeToNonStaticParent  Whether the rect should be relative to the relative parent of (including) the contaienr\r\n * @param  {[Boolean]} undoScale                  Whether the container's scale() should be undone\r\n * @param  {[HTMLElement]} container              The parent the element will be placed in\r\n * @return {Object}                               The boundingClientRect of el, with specified adjustments\r\n */\nfunction getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {\n  if (!el.getBoundingClientRect && el !== window) return;\n  var elRect, top, left, bottom, right, height, width;\n  if (el !== window && el.parentNode && el !== getWindowScrollingElement()) {\n    elRect = el.getBoundingClientRect();\n    top = elRect.top;\n    left = elRect.left;\n    bottom = elRect.bottom;\n    right = elRect.right;\n    height = elRect.height;\n    width = elRect.width;\n  } else {\n    top = 0;\n    left = 0;\n    bottom = window.innerHeight;\n    right = window.innerWidth;\n    height = window.innerHeight;\n    width = window.innerWidth;\n  }\n  if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {\n    // Adjust for translate()\n    container = container || el.parentNode;\n\n    // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)\n    // Not needed on <= IE11\n    if (!IE11OrLess) {\n      do {\n        if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {\n          var containerRect = container.getBoundingClientRect();\n\n          // Set relative to edges of padding box of container\n          top -= containerRect.top + parseInt(css(container, 'border-top-width'));\n          left -= containerRect.left + parseInt(css(container, 'border-left-width'));\n          bottom = top + elRect.height;\n          right = left + elRect.width;\n          break;\n        }\n        /* jshint boss:true */\n      } while (container = container.parentNode);\n    }\n  }\n  if (undoScale && el !== window) {\n    // Adjust for scale()\n    var elMatrix = matrix(container || el),\n      scaleX = elMatrix && elMatrix.a,\n      scaleY = elMatrix && elMatrix.d;\n    if (elMatrix) {\n      top /= scaleY;\n      left /= scaleX;\n      width /= scaleX;\n      height /= scaleY;\n      bottom = top + height;\n      right = left + width;\n    }\n  }\n  return {\n    top: top,\n    left: left,\n    bottom: bottom,\n    right: right,\n    width: width,\n    height: height\n  };\n}\n\n/**\r\n * Checks if a side of an element is scrolled past a side of its parents\r\n * @param  {HTMLElement}  el           The element who's side being scrolled out of view is in question\r\n * @param  {String}       elSide       Side of the element in question ('top', 'left', 'right', 'bottom')\r\n * @param  {String}       parentSide   Side of the parent in question ('top', 'left', 'right', 'bottom')\r\n * @return {HTMLElement}               The parent scroll element that the el's side is scrolled past, or null if there is no such element\r\n */\nfunction isScrolledPast(el, elSide, parentSide) {\n  var parent = getParentAutoScrollElement(el, true),\n    elSideVal = getRect(el)[elSide];\n\n  /* jshint boss:true */\n  while (parent) {\n    var parentSideVal = getRect(parent)[parentSide],\n      visible = void 0;\n    if (parentSide === 'top' || parentSide === 'left') {\n      visible = elSideVal >= parentSideVal;\n    } else {\n      visible = elSideVal <= parentSideVal;\n    }\n    if (!visible) return parent;\n    if (parent === getWindowScrollingElement()) break;\n    parent = getParentAutoScrollElement(parent, false);\n  }\n  return false;\n}\n\n/**\r\n * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)\r\n * and non-draggable elements\r\n * @param  {HTMLElement} el       The parent element\r\n * @param  {Number} childNum      The index of the child\r\n * @param  {Object} options       Parent Sortable's options\r\n * @return {HTMLElement}          The child at index childNum, or null if not found\r\n */\nfunction getChild(el, childNum, options, includeDragEl) {\n  var currentChild = 0,\n    i = 0,\n    children = el.children;\n  while (i < children.length) {\n    if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) {\n      if (currentChild === childNum) {\n        return children[i];\n      }\n      currentChild++;\n    }\n    i++;\n  }\n  return null;\n}\n\n/**\r\n * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)\r\n * @param  {HTMLElement} el       Parent element\r\n * @param  {selector} selector    Any other elements that should be ignored\r\n * @return {HTMLElement}          The last child, ignoring ghostEl\r\n */\nfunction lastChild(el, selector) {\n  var last = el.lastElementChild;\n  while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {\n    last = last.previousElementSibling;\n  }\n  return last || null;\n}\n\n/**\r\n * Returns the index of an element within its parent for a selected set of\r\n * elements\r\n * @param  {HTMLElement} el\r\n * @param  {selector} selector\r\n * @return {number}\r\n */\nfunction index(el, selector) {\n  var index = 0;\n  if (!el || !el.parentNode) {\n    return -1;\n  }\n\n  /* jshint boss:true */\n  while (el = el.previousElementSibling) {\n    if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {\n      index++;\n    }\n  }\n  return index;\n}\n\n/**\r\n * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.\r\n * The value is returned in real pixels.\r\n * @param  {HTMLElement} el\r\n * @return {Array}             Offsets in the format of [left, top]\r\n */\nfunction getRelativeScrollOffset(el) {\n  var offsetLeft = 0,\n    offsetTop = 0,\n    winScroller = getWindowScrollingElement();\n  if (el) {\n    do {\n      var elMatrix = matrix(el),\n        scaleX = elMatrix.a,\n        scaleY = elMatrix.d;\n      offsetLeft += el.scrollLeft * scaleX;\n      offsetTop += el.scrollTop * scaleY;\n    } while (el !== winScroller && (el = el.parentNode));\n  }\n  return [offsetLeft, offsetTop];\n}\n\n/**\r\n * Returns the index of the object within the given array\r\n * @param  {Array} arr   Array that may or may not hold the object\r\n * @param  {Object} obj  An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find\r\n * @return {Number}      The index of the object in the array, or -1\r\n */\nfunction indexOfObject(arr, obj) {\n  for (var i in arr) {\n    if (!arr.hasOwnProperty(i)) continue;\n    for (var key in obj) {\n      if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);\n    }\n  }\n  return -1;\n}\nfunction getParentAutoScrollElement(el, includeSelf) {\n  // skip to window\n  if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();\n  var elem = el;\n  var gotSelf = false;\n  do {\n    // we don't need to get elem css if it isn't even overflowing in the first place (performance)\n    if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {\n      var elemCSS = css(elem);\n      if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {\n        if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();\n        if (gotSelf || includeSelf) return elem;\n        gotSelf = true;\n      }\n    }\n    /* jshint boss:true */\n  } while (elem = elem.parentNode);\n  return getWindowScrollingElement();\n}\nfunction extend(dst, src) {\n  if (dst && src) {\n    for (var key in src) {\n      if (src.hasOwnProperty(key)) {\n        dst[key] = src[key];\n      }\n    }\n  }\n  return dst;\n}\nfunction isRectEqual(rect1, rect2) {\n  return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);\n}\nvar _throttleTimeout;\nfunction throttle(callback, ms) {\n  return function () {\n    if (!_throttleTimeout) {\n      var args = arguments,\n        _this = this;\n      if (args.length === 1) {\n        callback.call(_this, args[0]);\n      } else {\n        callback.apply(_this, args);\n      }\n      _throttleTimeout = setTimeout(function () {\n        _throttleTimeout = void 0;\n      }, ms);\n    }\n  };\n}\nfunction cancelThrottle() {\n  clearTimeout(_throttleTimeout);\n  _throttleTimeout = void 0;\n}\nfunction scrollBy(el, x, y) {\n  el.scrollLeft += x;\n  el.scrollTop += y;\n}\nfunction clone(el) {\n  var Polymer = window.Polymer;\n  var $ = window.jQuery || window.Zepto;\n  if (Polymer && Polymer.dom) {\n    return Polymer.dom(el).cloneNode(true);\n  } else if ($) {\n    return $(el).clone(true)[0];\n  } else {\n    return el.cloneNode(true);\n  }\n}\nfunction setRect(el, rect) {\n  css(el, 'position', 'absolute');\n  css(el, 'top', rect.top);\n  css(el, 'left', rect.left);\n  css(el, 'width', rect.width);\n  css(el, 'height', rect.height);\n}\nfunction unsetRect(el) {\n  css(el, 'position', '');\n  css(el, 'top', '');\n  css(el, 'left', '');\n  css(el, 'width', '');\n  css(el, 'height', '');\n}\nfunction getChildContainingRectFromElement(container, options, ghostEl) {\n  var rect = {};\n  Array.from(container.children).forEach(function (child) {\n    var _rect$left, _rect$top, _rect$right, _rect$bottom;\n    if (!closest(child, options.draggable, container, false) || child.animated || child === ghostEl) return;\n    var childRect = getRect(child);\n    rect.left = Math.min((_rect$left = rect.left) !== null && _rect$left !== void 0 ? _rect$left : Infinity, childRect.left);\n    rect.top = Math.min((_rect$top = rect.top) !== null && _rect$top !== void 0 ? _rect$top : Infinity, childRect.top);\n    rect.right = Math.max((_rect$right = rect.right) !== null && _rect$right !== void 0 ? _rect$right : -Infinity, childRect.right);\n    rect.bottom = Math.max((_rect$bottom = rect.bottom) !== null && _rect$bottom !== void 0 ? _rect$bottom : -Infinity, childRect.bottom);\n  });\n  rect.width = rect.right - rect.left;\n  rect.height = rect.bottom - rect.top;\n  rect.x = rect.left;\n  rect.y = rect.top;\n  return rect;\n}\nvar expando = 'Sortable' + new Date().getTime();\n\nfunction AnimationStateManager() {\n  var animationStates = [],\n    animationCallbackId;\n  return {\n    captureAnimationState: function captureAnimationState() {\n      animationStates = [];\n      if (!this.options.animation) return;\n      var children = [].slice.call(this.el.children);\n      children.forEach(function (child) {\n        if (css(child, 'display') === 'none' || child === Sortable.ghost) return;\n        animationStates.push({\n          target: child,\n          rect: getRect(child)\n        });\n        var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect);\n\n        // If animating: compensate for current animation\n        if (child.thisAnimationDuration) {\n          var childMatrix = matrix(child, true);\n          if (childMatrix) {\n            fromRect.top -= childMatrix.f;\n            fromRect.left -= childMatrix.e;\n          }\n        }\n        child.fromRect = fromRect;\n      });\n    },\n    addAnimationState: function addAnimationState(state) {\n      animationStates.push(state);\n    },\n    removeAnimationState: function removeAnimationState(target) {\n      animationStates.splice(indexOfObject(animationStates, {\n        target: target\n      }), 1);\n    },\n    animateAll: function animateAll(callback) {\n      var _this = this;\n      if (!this.options.animation) {\n        clearTimeout(animationCallbackId);\n        if (typeof callback === 'function') callback();\n        return;\n      }\n      var animating = false,\n        animationTime = 0;\n      animationStates.forEach(function (state) {\n        var time = 0,\n          target = state.target,\n          fromRect = target.fromRect,\n          toRect = getRect(target),\n          prevFromRect = target.prevFromRect,\n          prevToRect = target.prevToRect,\n          animatingRect = state.rect,\n          targetMatrix = matrix(target, true);\n        if (targetMatrix) {\n          // Compensate for current animation\n          toRect.top -= targetMatrix.f;\n          toRect.left -= targetMatrix.e;\n        }\n        target.toRect = toRect;\n        if (target.thisAnimationDuration) {\n          // Could also check if animatingRect is between fromRect and toRect\n          if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) &&\n          // Make sure animatingRect is on line between toRect & fromRect\n          (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {\n            // If returning to same place as started from animation and on same axis\n            time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);\n          }\n        }\n\n        // if fromRect != toRect: animate\n        if (!isRectEqual(toRect, fromRect)) {\n          target.prevFromRect = fromRect;\n          target.prevToRect = toRect;\n          if (!time) {\n            time = _this.options.animation;\n          }\n          _this.animate(target, animatingRect, toRect, time);\n        }\n        if (time) {\n          animating = true;\n          animationTime = Math.max(animationTime, time);\n          clearTimeout(target.animationResetTimer);\n          target.animationResetTimer = setTimeout(function () {\n            target.animationTime = 0;\n            target.prevFromRect = null;\n            target.fromRect = null;\n            target.prevToRect = null;\n            target.thisAnimationDuration = null;\n          }, time);\n          target.thisAnimationDuration = time;\n        }\n      });\n      clearTimeout(animationCallbackId);\n      if (!animating) {\n        if (typeof callback === 'function') callback();\n      } else {\n        animationCallbackId = setTimeout(function () {\n          if (typeof callback === 'function') callback();\n        }, animationTime);\n      }\n      animationStates = [];\n    },\n    animate: function animate(target, currentRect, toRect, duration) {\n      if (duration) {\n        css(target, 'transition', '');\n        css(target, 'transform', '');\n        var elMatrix = matrix(this.el),\n          scaleX = elMatrix && elMatrix.a,\n          scaleY = elMatrix && elMatrix.d,\n          translateX = (currentRect.left - toRect.left) / (scaleX || 1),\n          translateY = (currentRect.top - toRect.top) / (scaleY || 1);\n        target.animatingX = !!translateX;\n        target.animatingY = !!translateY;\n        css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');\n        this.forRepaintDummy = repaint(target); // repaint\n\n        css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));\n        css(target, 'transform', 'translate3d(0,0,0)');\n        typeof target.animated === 'number' && clearTimeout(target.animated);\n        target.animated = setTimeout(function () {\n          css(target, 'transition', '');\n          css(target, 'transform', '');\n          target.animated = false;\n          target.animatingX = false;\n          target.animatingY = false;\n        }, duration);\n      }\n    }\n  };\n}\nfunction repaint(target) {\n  return target.offsetWidth;\n}\nfunction calculateRealTime(animatingRect, fromRect, toRect, options) {\n  return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;\n}\n\nvar plugins = [];\nvar defaults = {\n  initializeByDefault: true\n};\nvar PluginManager = {\n  mount: function mount(plugin) {\n    // Set default static properties\n    for (var option in defaults) {\n      if (defaults.hasOwnProperty(option) && !(option in plugin)) {\n        plugin[option] = defaults[option];\n      }\n    }\n    plugins.forEach(function (p) {\n      if (p.pluginName === plugin.pluginName) {\n        throw \"Sortable: Cannot mount plugin \".concat(plugin.pluginName, \" more than once\");\n      }\n    });\n    plugins.push(plugin);\n  },\n  pluginEvent: function pluginEvent(eventName, sortable, evt) {\n    var _this = this;\n    this.eventCanceled = false;\n    evt.cancel = function () {\n      _this.eventCanceled = true;\n    };\n    var eventNameGlobal = eventName + 'Global';\n    plugins.forEach(function (plugin) {\n      if (!sortable[plugin.pluginName]) return;\n      // Fire global events if it exists in this sortable\n      if (sortable[plugin.pluginName][eventNameGlobal]) {\n        sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({\n          sortable: sortable\n        }, evt));\n      }\n\n      // Only fire plugin event if plugin is enabled in this sortable,\n      // and plugin has event defined\n      if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {\n        sortable[plugin.pluginName][eventName](_objectSpread2({\n          sortable: sortable\n        }, evt));\n      }\n    });\n  },\n  initializePlugins: function initializePlugins(sortable, el, defaults, options) {\n    plugins.forEach(function (plugin) {\n      var pluginName = plugin.pluginName;\n      if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;\n      var initialized = new plugin(sortable, el, sortable.options);\n      initialized.sortable = sortable;\n      initialized.options = sortable.options;\n      sortable[pluginName] = initialized;\n\n      // Add default options from plugin\n      _extends(defaults, initialized.defaults);\n    });\n    for (var option in sortable.options) {\n      if (!sortable.options.hasOwnProperty(option)) continue;\n      var modified = this.modifyOption(sortable, option, sortable.options[option]);\n      if (typeof modified !== 'undefined') {\n        sortable.options[option] = modified;\n      }\n    }\n  },\n  getEventProperties: function getEventProperties(name, sortable) {\n    var eventProperties = {};\n    plugins.forEach(function (plugin) {\n      if (typeof plugin.eventProperties !== 'function') return;\n      _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name));\n    });\n    return eventProperties;\n  },\n  modifyOption: function modifyOption(sortable, name, value) {\n    var modifiedValue;\n    plugins.forEach(function (plugin) {\n      // Plugin must exist on the Sortable\n      if (!sortable[plugin.pluginName]) return;\n\n      // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin\n      if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {\n        modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);\n      }\n    });\n    return modifiedValue;\n  }\n};\n\nfunction dispatchEvent(_ref) {\n  var sortable = _ref.sortable,\n    rootEl = _ref.rootEl,\n    name = _ref.name,\n    targetEl = _ref.targetEl,\n    cloneEl = _ref.cloneEl,\n    toEl = _ref.toEl,\n    fromEl = _ref.fromEl,\n    oldIndex = _ref.oldIndex,\n    newIndex = _ref.newIndex,\n    oldDraggableIndex = _ref.oldDraggableIndex,\n    newDraggableIndex = _ref.newDraggableIndex,\n    originalEvent = _ref.originalEvent,\n    putSortable = _ref.putSortable,\n    extraEventProperties = _ref.extraEventProperties;\n  sortable = sortable || rootEl && rootEl[expando];\n  if (!sortable) return;\n  var evt,\n    options = sortable.options,\n    onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);\n  // Support for new CustomEvent feature\n  if (window.CustomEvent && !IE11OrLess && !Edge) {\n    evt = new CustomEvent(name, {\n      bubbles: true,\n      cancelable: true\n    });\n  } else {\n    evt = document.createEvent('Event');\n    evt.initEvent(name, true, true);\n  }\n  evt.to = toEl || rootEl;\n  evt.from = fromEl || rootEl;\n  evt.item = targetEl || rootEl;\n  evt.clone = cloneEl;\n  evt.oldIndex = oldIndex;\n  evt.newIndex = newIndex;\n  evt.oldDraggableIndex = oldDraggableIndex;\n  evt.newDraggableIndex = newDraggableIndex;\n  evt.originalEvent = originalEvent;\n  evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;\n  var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable));\n  for (var option in allEventProperties) {\n    evt[option] = allEventProperties[option];\n  }\n  if (rootEl) {\n    rootEl.dispatchEvent(evt);\n  }\n  if (options[onName]) {\n    options[onName].call(sortable, evt);\n  }\n}\n\nvar _excluded = [\"evt\"];\nvar pluginEvent = function pluginEvent(eventName, sortable) {\n  var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},\n    originalEvent = _ref.evt,\n    data = _objectWithoutProperties(_ref, _excluded);\n  PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({\n    dragEl: dragEl,\n    parentEl: parentEl,\n    ghostEl: ghostEl,\n    rootEl: rootEl,\n    nextEl: nextEl,\n    lastDownEl: lastDownEl,\n    cloneEl: cloneEl,\n    cloneHidden: cloneHidden,\n    dragStarted: moved,\n    putSortable: putSortable,\n    activeSortable: Sortable.active,\n    originalEvent: originalEvent,\n    oldIndex: oldIndex,\n    oldDraggableIndex: oldDraggableIndex,\n    newIndex: newIndex,\n    newDraggableIndex: newDraggableIndex,\n    hideGhostForTarget: _hideGhostForTarget,\n    unhideGhostForTarget: _unhideGhostForTarget,\n    cloneNowHidden: function cloneNowHidden() {\n      cloneHidden = true;\n    },\n    cloneNowShown: function cloneNowShown() {\n      cloneHidden = false;\n    },\n    dispatchSortableEvent: function dispatchSortableEvent(name) {\n      _dispatchEvent({\n        sortable: sortable,\n        name: name,\n        originalEvent: originalEvent\n      });\n    }\n  }, data));\n};\nfunction _dispatchEvent(info) {\n  dispatchEvent(_objectSpread2({\n    putSortable: putSortable,\n    cloneEl: cloneEl,\n    targetEl: dragEl,\n    rootEl: rootEl,\n    oldIndex: oldIndex,\n    oldDraggableIndex: oldDraggableIndex,\n    newIndex: newIndex,\n    newDraggableIndex: newDraggableIndex\n  }, info));\n}\nvar dragEl,\n  parentEl,\n  ghostEl,\n  rootEl,\n  nextEl,\n  lastDownEl,\n  cloneEl,\n  cloneHidden,\n  oldIndex,\n  newIndex,\n  oldDraggableIndex,\n  newDraggableIndex,\n  activeGroup,\n  putSortable,\n  awaitingDragStarted = false,\n  ignoreNextClick = false,\n  sortables = [],\n  tapEvt,\n  touchEvt,\n  lastDx,\n  lastDy,\n  tapDistanceLeft,\n  tapDistanceTop,\n  moved,\n  lastTarget,\n  lastDirection,\n  pastFirstInvertThresh = false,\n  isCircumstantialInvert = false,\n  targetMoveDistance,\n  // For positioning ghost absolutely\n  ghostRelativeParent,\n  ghostRelativeParentInitialScroll = [],\n  // (left, top)\n\n  _silent = false,\n  savedInputChecked = [];\n\n/** @const */\nvar documentExists = typeof document !== 'undefined',\n  PositionGhostAbsolutely = IOS,\n  CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',\n  // This will not pass for IE9, because IE9 DnD only works on anchors\n  supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),\n  supportCssPointerEvents = function () {\n    if (!documentExists) return;\n    // false when <= IE11\n    if (IE11OrLess) {\n      return false;\n    }\n    var el = document.createElement('x');\n    el.style.cssText = 'pointer-events:auto';\n    return el.style.pointerEvents === 'auto';\n  }(),\n  _detectDirection = function _detectDirection(el, options) {\n    var elCSS = css(el),\n      elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),\n      child1 = getChild(el, 0, options),\n      child2 = getChild(el, 1, options),\n      firstChildCSS = child1 && css(child1),\n      secondChildCSS = child2 && css(child2),\n      firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,\n      secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;\n    if (elCSS.display === 'flex') {\n      return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';\n    }\n    if (elCSS.display === 'grid') {\n      return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';\n    }\n    if (child1 && firstChildCSS[\"float\"] && firstChildCSS[\"float\"] !== 'none') {\n      var touchingSideChild2 = firstChildCSS[\"float\"] === 'left' ? 'left' : 'right';\n      return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';\n    }\n    return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';\n  },\n  _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {\n    var dragElS1Opp = vertical ? dragRect.left : dragRect.top,\n      dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,\n      dragElOppLength = vertical ? dragRect.width : dragRect.height,\n      targetS1Opp = vertical ? targetRect.left : targetRect.top,\n      targetS2Opp = vertical ? targetRect.right : targetRect.bottom,\n      targetOppLength = vertical ? targetRect.width : targetRect.height;\n    return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;\n  },\n  /**\r\n   * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.\r\n   * @param  {Number} x      X position\r\n   * @param  {Number} y      Y position\r\n   * @return {HTMLElement}   Element of the first found nearest Sortable\r\n   */\n  _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {\n    var ret;\n    sortables.some(function (sortable) {\n      var threshold = sortable[expando].options.emptyInsertThreshold;\n      if (!threshold || lastChild(sortable)) return;\n      var rect = getRect(sortable),\n        insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,\n        insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;\n      if (insideHorizontally && insideVertically) {\n        return ret = sortable;\n      }\n    });\n    return ret;\n  },\n  _prepareGroup = function _prepareGroup(options) {\n    function toFn(value, pull) {\n      return function (to, from, dragEl, evt) {\n        var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;\n        if (value == null && (pull || sameGroup)) {\n          // Default pull value\n          // Default pull and put value if same group\n          return true;\n        } else if (value == null || value === false) {\n          return false;\n        } else if (pull && value === 'clone') {\n          return value;\n        } else if (typeof value === 'function') {\n          return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);\n        } else {\n          var otherGroup = (pull ? to : from).options.group.name;\n          return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;\n        }\n      };\n    }\n    var group = {};\n    var originalGroup = options.group;\n    if (!originalGroup || _typeof(originalGroup) != 'object') {\n      originalGroup = {\n        name: originalGroup\n      };\n    }\n    group.name = originalGroup.name;\n    group.checkPull = toFn(originalGroup.pull, true);\n    group.checkPut = toFn(originalGroup.put);\n    group.revertClone = originalGroup.revertClone;\n    options.group = group;\n  },\n  _hideGhostForTarget = function _hideGhostForTarget() {\n    if (!supportCssPointerEvents && ghostEl) {\n      css(ghostEl, 'display', 'none');\n    }\n  },\n  _unhideGhostForTarget = function _unhideGhostForTarget() {\n    if (!supportCssPointerEvents && ghostEl) {\n      css(ghostEl, 'display', '');\n    }\n  };\n\n// #1184 fix - Prevent click event on fallback if dragged but item not changed position\nif (documentExists && !ChromeForAndroid) {\n  document.addEventListener('click', function (evt) {\n    if (ignoreNextClick) {\n      evt.preventDefault();\n      evt.stopPropagation && evt.stopPropagation();\n      evt.stopImmediatePropagation && evt.stopImmediatePropagation();\n      ignoreNextClick = false;\n      return false;\n    }\n  }, true);\n}\nvar nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {\n  if (dragEl) {\n    evt = evt.touches ? evt.touches[0] : evt;\n    var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);\n    if (nearest) {\n      // Create imitation event\n      var event = {};\n      for (var i in evt) {\n        if (evt.hasOwnProperty(i)) {\n          event[i] = evt[i];\n        }\n      }\n      event.target = event.rootEl = nearest;\n      event.preventDefault = void 0;\n      event.stopPropagation = void 0;\n      nearest[expando]._onDragOver(event);\n    }\n  }\n};\nvar _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {\n  if (dragEl) {\n    dragEl.parentNode[expando]._isOutsideThisEl(evt.target);\n  }\n};\n\n/**\r\n * @class  Sortable\r\n * @param  {HTMLElement}  el\r\n * @param  {Object}       [options]\r\n */\nfunction Sortable(el, options) {\n  if (!(el && el.nodeType && el.nodeType === 1)) {\n    throw \"Sortable: `el` must be an HTMLElement, not \".concat({}.toString.call(el));\n  }\n  this.el = el; // root element\n  this.options = options = _extends({}, options);\n\n  // Export instance\n  el[expando] = this;\n  var defaults = {\n    group: null,\n    sort: true,\n    disabled: false,\n    store: null,\n    handle: null,\n    draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',\n    swapThreshold: 1,\n    // percentage; 0 <= x <= 1\n    invertSwap: false,\n    // invert always\n    invertedSwapThreshold: null,\n    // will be set to same as swapThreshold if default\n    removeCloneOnHide: true,\n    direction: function direction() {\n      return _detectDirection(el, this.options);\n    },\n    ghostClass: 'sortable-ghost',\n    chosenClass: 'sortable-chosen',\n    dragClass: 'sortable-drag',\n    ignore: 'a, img',\n    filter: null,\n    preventOnFilter: true,\n    animation: 0,\n    easing: null,\n    setData: function setData(dataTransfer, dragEl) {\n      dataTransfer.setData('Text', dragEl.textContent);\n    },\n    dropBubble: false,\n    dragoverBubble: false,\n    dataIdAttr: 'data-id',\n    delay: 0,\n    delayOnTouchOnly: false,\n    touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,\n    forceFallback: false,\n    fallbackClass: 'sortable-fallback',\n    fallbackOnBody: false,\n    fallbackTolerance: 0,\n    fallbackOffset: {\n      x: 0,\n      y: 0\n    },\n    // Disabled on Safari: #1571; Enabled on Safari IOS: #2244\n    supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && (!Safari || IOS),\n    emptyInsertThreshold: 5\n  };\n  PluginManager.initializePlugins(this, el, defaults);\n\n  // Set default options\n  for (var name in defaults) {\n    !(name in options) && (options[name] = defaults[name]);\n  }\n  _prepareGroup(options);\n\n  // Bind all private methods\n  for (var fn in this) {\n    if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n      this[fn] = this[fn].bind(this);\n    }\n  }\n\n  // Setup drag mode\n  this.nativeDraggable = options.forceFallback ? false : supportDraggable;\n  if (this.nativeDraggable) {\n    // Touch start threshold cannot be greater than the native dragstart threshold\n    this.options.touchStartThreshold = 1;\n  }\n\n  // Bind events\n  if (options.supportPointer) {\n    on(el, 'pointerdown', this._onTapStart);\n  } else {\n    on(el, 'mousedown', this._onTapStart);\n    on(el, 'touchstart', this._onTapStart);\n  }\n  if (this.nativeDraggable) {\n    on(el, 'dragover', this);\n    on(el, 'dragenter', this);\n  }\n  sortables.push(this.el);\n\n  // Restore sorting\n  options.store && options.store.get && this.sort(options.store.get(this) || []);\n\n  // Add animation state manager\n  _extends(this, AnimationStateManager());\n}\nSortable.prototype = /** @lends Sortable.prototype */{\n  constructor: Sortable,\n  _isOutsideThisEl: function _isOutsideThisEl(target) {\n    if (!this.el.contains(target) && target !== this.el) {\n      lastTarget = null;\n    }\n  },\n  _getDirection: function _getDirection(evt, target) {\n    return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;\n  },\n  _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) {\n    if (!evt.cancelable) return;\n    var _this = this,\n      el = this.el,\n      options = this.options,\n      preventOnFilter = options.preventOnFilter,\n      type = evt.type,\n      touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt,\n      target = (touch || evt).target,\n      originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,\n      filter = options.filter;\n    _saveInputCheckedState(el);\n\n    // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.\n    if (dragEl) {\n      return;\n    }\n    if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {\n      return; // only left button and enabled\n    }\n\n    // cancel dnd if original target is content editable\n    if (originalTarget.isContentEditable) {\n      return;\n    }\n\n    // Safari ignores further event handling after mousedown\n    if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') {\n      return;\n    }\n    target = closest(target, options.draggable, el, false);\n    if (target && target.animated) {\n      return;\n    }\n    if (lastDownEl === target) {\n      // Ignoring duplicate `down`\n      return;\n    }\n\n    // Get the index of the dragged element within its parent\n    oldIndex = index(target);\n    oldDraggableIndex = index(target, options.draggable);\n\n    // Check filter\n    if (typeof filter === 'function') {\n      if (filter.call(this, evt, target, this)) {\n        _dispatchEvent({\n          sortable: _this,\n          rootEl: originalTarget,\n          name: 'filter',\n          targetEl: target,\n          toEl: el,\n          fromEl: el\n        });\n        pluginEvent('filter', _this, {\n          evt: evt\n        });\n        preventOnFilter && evt.preventDefault();\n        return; // cancel dnd\n      }\n    } else if (filter) {\n      filter = filter.split(',').some(function (criteria) {\n        criteria = closest(originalTarget, criteria.trim(), el, false);\n        if (criteria) {\n          _dispatchEvent({\n            sortable: _this,\n            rootEl: criteria,\n            name: 'filter',\n            targetEl: target,\n            fromEl: el,\n            toEl: el\n          });\n          pluginEvent('filter', _this, {\n            evt: evt\n          });\n          return true;\n        }\n      });\n      if (filter) {\n        preventOnFilter && evt.preventDefault();\n        return; // cancel dnd\n      }\n    }\n    if (options.handle && !closest(originalTarget, options.handle, el, false)) {\n      return;\n    }\n\n    // Prepare `dragstart`\n    this._prepareDragStart(evt, touch, target);\n  },\n  _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) {\n    var _this = this,\n      el = _this.el,\n      options = _this.options,\n      ownerDocument = el.ownerDocument,\n      dragStartFn;\n    if (target && !dragEl && target.parentNode === el) {\n      var dragRect = getRect(target);\n      rootEl = el;\n      dragEl = target;\n      parentEl = dragEl.parentNode;\n      nextEl = dragEl.nextSibling;\n      lastDownEl = target;\n      activeGroup = options.group;\n      Sortable.dragged = dragEl;\n      tapEvt = {\n        target: dragEl,\n        clientX: (touch || evt).clientX,\n        clientY: (touch || evt).clientY\n      };\n      tapDistanceLeft = tapEvt.clientX - dragRect.left;\n      tapDistanceTop = tapEvt.clientY - dragRect.top;\n      this._lastX = (touch || evt).clientX;\n      this._lastY = (touch || evt).clientY;\n      dragEl.style['will-change'] = 'all';\n      dragStartFn = function dragStartFn() {\n        pluginEvent('delayEnded', _this, {\n          evt: evt\n        });\n        if (Sortable.eventCanceled) {\n          _this._onDrop();\n          return;\n        }\n        // Delayed drag has been triggered\n        // we can re-enable the events: touchmove/mousemove\n        _this._disableDelayedDragEvents();\n        if (!FireFox && _this.nativeDraggable) {\n          dragEl.draggable = true;\n        }\n\n        // Bind the events: dragstart/dragend\n        _this._triggerDragStart(evt, touch);\n\n        // Drag start event\n        _dispatchEvent({\n          sortable: _this,\n          name: 'choose',\n          originalEvent: evt\n        });\n\n        // Chosen item\n        toggleClass(dragEl, options.chosenClass, true);\n      };\n\n      // Disable \"draggable\"\n      options.ignore.split(',').forEach(function (criteria) {\n        find(dragEl, criteria.trim(), _disableDraggable);\n      });\n      on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);\n      on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);\n      on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);\n      if (options.supportPointer) {\n        on(ownerDocument, 'pointerup', _this._onDrop);\n        // Native D&D triggers pointercancel\n        !this.nativeDraggable && on(ownerDocument, 'pointercancel', _this._onDrop);\n      } else {\n        on(ownerDocument, 'mouseup', _this._onDrop);\n        on(ownerDocument, 'touchend', _this._onDrop);\n        on(ownerDocument, 'touchcancel', _this._onDrop);\n      }\n\n      // Make dragEl draggable (must be before delay for FireFox)\n      if (FireFox && this.nativeDraggable) {\n        this.options.touchStartThreshold = 4;\n        dragEl.draggable = true;\n      }\n      pluginEvent('delayStart', this, {\n        evt: evt\n      });\n\n      // Delay is impossible for native DnD in Edge or IE\n      if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {\n        if (Sortable.eventCanceled) {\n          this._onDrop();\n          return;\n        }\n        // If the user moves the pointer or let go the click or touch\n        // before the delay has been reached:\n        // disable the delayed drag\n        if (options.supportPointer) {\n          on(ownerDocument, 'pointerup', _this._disableDelayedDrag);\n          on(ownerDocument, 'pointercancel', _this._disableDelayedDrag);\n        } else {\n          on(ownerDocument, 'mouseup', _this._disableDelayedDrag);\n          on(ownerDocument, 'touchend', _this._disableDelayedDrag);\n          on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);\n        }\n        on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);\n        on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);\n        options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);\n        _this._dragStartTimer = setTimeout(dragStartFn, options.delay);\n      } else {\n        dragStartFn();\n      }\n    }\n  },\n  _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) {\n    var touch = e.touches ? e.touches[0] : e;\n    if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {\n      this._disableDelayedDrag();\n    }\n  },\n  _disableDelayedDrag: function _disableDelayedDrag() {\n    dragEl && _disableDraggable(dragEl);\n    clearTimeout(this._dragStartTimer);\n    this._disableDelayedDragEvents();\n  },\n  _disableDelayedDragEvents: function _disableDelayedDragEvents() {\n    var ownerDocument = this.el.ownerDocument;\n    off(ownerDocument, 'mouseup', this._disableDelayedDrag);\n    off(ownerDocument, 'touchend', this._disableDelayedDrag);\n    off(ownerDocument, 'touchcancel', this._disableDelayedDrag);\n    off(ownerDocument, 'pointerup', this._disableDelayedDrag);\n    off(ownerDocument, 'pointercancel', this._disableDelayedDrag);\n    off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);\n    off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);\n    off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);\n  },\n  _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) {\n    touch = touch || evt.pointerType == 'touch' && evt;\n    if (!this.nativeDraggable || touch) {\n      if (this.options.supportPointer) {\n        on(document, 'pointermove', this._onTouchMove);\n      } else if (touch) {\n        on(document, 'touchmove', this._onTouchMove);\n      } else {\n        on(document, 'mousemove', this._onTouchMove);\n      }\n    } else {\n      on(dragEl, 'dragend', this);\n      on(rootEl, 'dragstart', this._onDragStart);\n    }\n    try {\n      if (document.selection) {\n        _nextTick(function () {\n          document.selection.empty();\n        });\n      } else {\n        window.getSelection().removeAllRanges();\n      }\n    } catch (err) {}\n  },\n  _dragStarted: function _dragStarted(fallback, evt) {\n    awaitingDragStarted = false;\n    if (rootEl && dragEl) {\n      pluginEvent('dragStarted', this, {\n        evt: evt\n      });\n      if (this.nativeDraggable) {\n        on(document, 'dragover', _checkOutsideTargetEl);\n      }\n      var options = this.options;\n\n      // Apply effect\n      !fallback && toggleClass(dragEl, options.dragClass, false);\n      toggleClass(dragEl, options.ghostClass, true);\n      Sortable.active = this;\n      fallback && this._appendGhost();\n\n      // Drag start event\n      _dispatchEvent({\n        sortable: this,\n        name: 'start',\n        originalEvent: evt\n      });\n    } else {\n      this._nulling();\n    }\n  },\n  _emulateDragOver: function _emulateDragOver() {\n    if (touchEvt) {\n      this._lastX = touchEvt.clientX;\n      this._lastY = touchEvt.clientY;\n      _hideGhostForTarget();\n      var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);\n      var parent = target;\n      while (target && target.shadowRoot) {\n        target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);\n        if (target === parent) break;\n        parent = target;\n      }\n      dragEl.parentNode[expando]._isOutsideThisEl(target);\n      if (parent) {\n        do {\n          if (parent[expando]) {\n            var inserted = void 0;\n            inserted = parent[expando]._onDragOver({\n              clientX: touchEvt.clientX,\n              clientY: touchEvt.clientY,\n              target: target,\n              rootEl: parent\n            });\n            if (inserted && !this.options.dragoverBubble) {\n              break;\n            }\n          }\n          target = parent; // store last element\n        }\n        /* jshint boss:true */ while (parent = getParentOrHost(parent));\n      }\n      _unhideGhostForTarget();\n    }\n  },\n  _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) {\n    if (tapEvt) {\n      var options = this.options,\n        fallbackTolerance = options.fallbackTolerance,\n        fallbackOffset = options.fallbackOffset,\n        touch = evt.touches ? evt.touches[0] : evt,\n        ghostMatrix = ghostEl && matrix(ghostEl, true),\n        scaleX = ghostEl && ghostMatrix && ghostMatrix.a,\n        scaleY = ghostEl && ghostMatrix && ghostMatrix.d,\n        relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),\n        dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),\n        dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1);\n\n      // only set the status to dragging, when we are actually dragging\n      if (!Sortable.active && !awaitingDragStarted) {\n        if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {\n          return;\n        }\n        this._onDragStart(evt, true);\n      }\n      if (ghostEl) {\n        if (ghostMatrix) {\n          ghostMatrix.e += dx - (lastDx || 0);\n          ghostMatrix.f += dy - (lastDy || 0);\n        } else {\n          ghostMatrix = {\n            a: 1,\n            b: 0,\n            c: 0,\n            d: 1,\n            e: dx,\n            f: dy\n          };\n        }\n        var cssMatrix = \"matrix(\".concat(ghostMatrix.a, \",\").concat(ghostMatrix.b, \",\").concat(ghostMatrix.c, \",\").concat(ghostMatrix.d, \",\").concat(ghostMatrix.e, \",\").concat(ghostMatrix.f, \")\");\n        css(ghostEl, 'webkitTransform', cssMatrix);\n        css(ghostEl, 'mozTransform', cssMatrix);\n        css(ghostEl, 'msTransform', cssMatrix);\n        css(ghostEl, 'transform', cssMatrix);\n        lastDx = dx;\n        lastDy = dy;\n        touchEvt = touch;\n      }\n      evt.cancelable && evt.preventDefault();\n    }\n  },\n  _appendGhost: function _appendGhost() {\n    // Bug if using scale(): https://stackoverflow.com/questions/2637058\n    // Not being adjusted for\n    if (!ghostEl) {\n      var container = this.options.fallbackOnBody ? document.body : rootEl,\n        rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),\n        options = this.options;\n\n      // Position absolutely\n      if (PositionGhostAbsolutely) {\n        // Get relatively positioned parent\n        ghostRelativeParent = container;\n        while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {\n          ghostRelativeParent = ghostRelativeParent.parentNode;\n        }\n        if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {\n          if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();\n          rect.top += ghostRelativeParent.scrollTop;\n          rect.left += ghostRelativeParent.scrollLeft;\n        } else {\n          ghostRelativeParent = getWindowScrollingElement();\n        }\n        ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);\n      }\n      ghostEl = dragEl.cloneNode(true);\n      toggleClass(ghostEl, options.ghostClass, false);\n      toggleClass(ghostEl, options.fallbackClass, true);\n      toggleClass(ghostEl, options.dragClass, true);\n      css(ghostEl, 'transition', '');\n      css(ghostEl, 'transform', '');\n      css(ghostEl, 'box-sizing', 'border-box');\n      css(ghostEl, 'margin', 0);\n      css(ghostEl, 'top', rect.top);\n      css(ghostEl, 'left', rect.left);\n      css(ghostEl, 'width', rect.width);\n      css(ghostEl, 'height', rect.height);\n      css(ghostEl, 'opacity', '0.8');\n      css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');\n      css(ghostEl, 'zIndex', '100000');\n      css(ghostEl, 'pointerEvents', 'none');\n      Sortable.ghost = ghostEl;\n      container.appendChild(ghostEl);\n\n      // Set transform-origin\n      css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%');\n    }\n  },\n  _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) {\n    var _this = this;\n    var dataTransfer = evt.dataTransfer;\n    var options = _this.options;\n    pluginEvent('dragStart', this, {\n      evt: evt\n    });\n    if (Sortable.eventCanceled) {\n      this._onDrop();\n      return;\n    }\n    pluginEvent('setupClone', this);\n    if (!Sortable.eventCanceled) {\n      cloneEl = clone(dragEl);\n      cloneEl.removeAttribute(\"id\");\n      cloneEl.draggable = false;\n      cloneEl.style['will-change'] = '';\n      this._hideClone();\n      toggleClass(cloneEl, this.options.chosenClass, false);\n      Sortable.clone = cloneEl;\n    }\n\n    // #1143: IFrame support workaround\n    _this.cloneId = _nextTick(function () {\n      pluginEvent('clone', _this);\n      if (Sortable.eventCanceled) return;\n      if (!_this.options.removeCloneOnHide) {\n        rootEl.insertBefore(cloneEl, dragEl);\n      }\n      _this._hideClone();\n      _dispatchEvent({\n        sortable: _this,\n        name: 'clone'\n      });\n    });\n    !fallback && toggleClass(dragEl, options.dragClass, true);\n\n    // Set proper drop events\n    if (fallback) {\n      ignoreNextClick = true;\n      _this._loopId = setInterval(_this._emulateDragOver, 50);\n    } else {\n      // Undo what was set in _prepareDragStart before drag started\n      off(document, 'mouseup', _this._onDrop);\n      off(document, 'touchend', _this._onDrop);\n      off(document, 'touchcancel', _this._onDrop);\n      if (dataTransfer) {\n        dataTransfer.effectAllowed = 'move';\n        options.setData && options.setData.call(_this, dataTransfer, dragEl);\n      }\n      on(document, 'drop', _this);\n\n      // #1276 fix:\n      css(dragEl, 'transform', 'translateZ(0)');\n    }\n    awaitingDragStarted = true;\n    _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));\n    on(document, 'selectstart', _this);\n    moved = true;\n    window.getSelection().removeAllRanges();\n    if (Safari) {\n      css(document.body, 'user-select', 'none');\n    }\n  },\n  // Returns true - if no further action is needed (either inserted or another condition)\n  _onDragOver: function _onDragOver( /**Event*/evt) {\n    var el = this.el,\n      target = evt.target,\n      dragRect,\n      targetRect,\n      revert,\n      options = this.options,\n      group = options.group,\n      activeSortable = Sortable.active,\n      isOwner = activeGroup === group,\n      canSort = options.sort,\n      fromSortable = putSortable || activeSortable,\n      vertical,\n      _this = this,\n      completedFired = false;\n    if (_silent) return;\n    function dragOverEvent(name, extra) {\n      pluginEvent(name, _this, _objectSpread2({\n        evt: evt,\n        isOwner: isOwner,\n        axis: vertical ? 'vertical' : 'horizontal',\n        revert: revert,\n        dragRect: dragRect,\n        targetRect: targetRect,\n        canSort: canSort,\n        fromSortable: fromSortable,\n        target: target,\n        completed: completed,\n        onMove: function onMove(target, after) {\n          return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);\n        },\n        changed: changed\n      }, extra));\n    }\n\n    // Capture animation state\n    function capture() {\n      dragOverEvent('dragOverAnimationCapture');\n      _this.captureAnimationState();\n      if (_this !== fromSortable) {\n        fromSortable.captureAnimationState();\n      }\n    }\n\n    // Return invocation when dragEl is inserted (or completed)\n    function completed(insertion) {\n      dragOverEvent('dragOverCompleted', {\n        insertion: insertion\n      });\n      if (insertion) {\n        // Clones must be hidden before folding animation to capture dragRectAbsolute properly\n        if (isOwner) {\n          activeSortable._hideClone();\n        } else {\n          activeSortable._showClone(_this);\n        }\n        if (_this !== fromSortable) {\n          // Set ghost class to new sortable's ghost class\n          toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);\n          toggleClass(dragEl, options.ghostClass, true);\n        }\n        if (putSortable !== _this && _this !== Sortable.active) {\n          putSortable = _this;\n        } else if (_this === Sortable.active && putSortable) {\n          putSortable = null;\n        }\n\n        // Animation\n        if (fromSortable === _this) {\n          _this._ignoreWhileAnimating = target;\n        }\n        _this.animateAll(function () {\n          dragOverEvent('dragOverAnimationComplete');\n          _this._ignoreWhileAnimating = null;\n        });\n        if (_this !== fromSortable) {\n          fromSortable.animateAll();\n          fromSortable._ignoreWhileAnimating = null;\n        }\n      }\n\n      // Null lastTarget if it is not inside a previously swapped element\n      if (target === dragEl && !dragEl.animated || target === el && !target.animated) {\n        lastTarget = null;\n      }\n\n      // no bubbling and not fallback\n      if (!options.dragoverBubble && !evt.rootEl && target !== document) {\n        dragEl.parentNode[expando]._isOutsideThisEl(evt.target);\n\n        // Do not detect for empty insert if already inserted\n        !insertion && nearestEmptyInsertDetectEvent(evt);\n      }\n      !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();\n      return completedFired = true;\n    }\n\n    // Call when dragEl has been inserted\n    function changed() {\n      newIndex = index(dragEl);\n      newDraggableIndex = index(dragEl, options.draggable);\n      _dispatchEvent({\n        sortable: _this,\n        name: 'change',\n        toEl: el,\n        newIndex: newIndex,\n        newDraggableIndex: newDraggableIndex,\n        originalEvent: evt\n      });\n    }\n    if (evt.preventDefault !== void 0) {\n      evt.cancelable && evt.preventDefault();\n    }\n    target = closest(target, options.draggable, el, true);\n    dragOverEvent('dragOver');\n    if (Sortable.eventCanceled) return completedFired;\n    if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {\n      return completed(false);\n    }\n    ignoreNextClick = false;\n    if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list\n    : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {\n      vertical = this._getDirection(evt, target) === 'vertical';\n      dragRect = getRect(dragEl);\n      dragOverEvent('dragOverValid');\n      if (Sortable.eventCanceled) return completedFired;\n      if (revert) {\n        parentEl = rootEl; // actualization\n        capture();\n        this._hideClone();\n        dragOverEvent('revert');\n        if (!Sortable.eventCanceled) {\n          if (nextEl) {\n            rootEl.insertBefore(dragEl, nextEl);\n          } else {\n            rootEl.appendChild(dragEl);\n          }\n        }\n        return completed(true);\n      }\n      var elLastChild = lastChild(el, options.draggable);\n      if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {\n        // Insert to end of list\n\n        // If already at end of list: Do not insert\n        if (elLastChild === dragEl) {\n          return completed(false);\n        }\n\n        // if there is a last element, it is the target\n        if (elLastChild && el === evt.target) {\n          target = elLastChild;\n        }\n        if (target) {\n          targetRect = getRect(target);\n        }\n        if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {\n          capture();\n          if (elLastChild && elLastChild.nextSibling) {\n            // the last draggable element is not the last node\n            el.insertBefore(dragEl, elLastChild.nextSibling);\n          } else {\n            el.appendChild(dragEl);\n          }\n          parentEl = el; // actualization\n\n          changed();\n          return completed(true);\n        }\n      } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) {\n        // Insert to start of list\n        var firstChild = getChild(el, 0, options, true);\n        if (firstChild === dragEl) {\n          return completed(false);\n        }\n        target = firstChild;\n        targetRect = getRect(target);\n        if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {\n          capture();\n          el.insertBefore(dragEl, firstChild);\n          parentEl = el; // actualization\n\n          changed();\n          return completed(true);\n        }\n      } else if (target.parentNode === el) {\n        targetRect = getRect(target);\n        var direction = 0,\n          targetBeforeFirstSwap,\n          differentLevel = dragEl.parentNode !== el,\n          differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),\n          side1 = vertical ? 'top' : 'left',\n          scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'),\n          scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;\n        if (lastTarget !== target) {\n          targetBeforeFirstSwap = targetRect[side1];\n          pastFirstInvertThresh = false;\n          isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;\n        }\n        direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);\n        var sibling;\n        if (direction !== 0) {\n          // Check if target is beside dragEl in respective direction (ignoring hidden elements)\n          var dragIndex = index(dragEl);\n          do {\n            dragIndex -= direction;\n            sibling = parentEl.children[dragIndex];\n          } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));\n        }\n        // If dragEl is already beside target: Do not insert\n        if (direction === 0 || sibling === target) {\n          return completed(false);\n        }\n        lastTarget = target;\n        lastDirection = direction;\n        var nextSibling = target.nextElementSibling,\n          after = false;\n        after = direction === 1;\n        var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);\n        if (moveVector !== false) {\n          if (moveVector === 1 || moveVector === -1) {\n            after = moveVector === 1;\n          }\n          _silent = true;\n          setTimeout(_unsilent, 30);\n          capture();\n          if (after && !nextSibling) {\n            el.appendChild(dragEl);\n          } else {\n            target.parentNode.insertBefore(dragEl, after ? nextSibling : target);\n          }\n\n          // Undo chrome's scroll adjustment (has no effect on other browsers)\n          if (scrolledPastTop) {\n            scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);\n          }\n          parentEl = dragEl.parentNode; // actualization\n\n          // must be done before animation\n          if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {\n            targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);\n          }\n          changed();\n          return completed(true);\n        }\n      }\n      if (el.contains(dragEl)) {\n        return completed(false);\n      }\n    }\n    return false;\n  },\n  _ignoreWhileAnimating: null,\n  _offMoveEvents: function _offMoveEvents() {\n    off(document, 'mousemove', this._onTouchMove);\n    off(document, 'touchmove', this._onTouchMove);\n    off(document, 'pointermove', this._onTouchMove);\n    off(document, 'dragover', nearestEmptyInsertDetectEvent);\n    off(document, 'mousemove', nearestEmptyInsertDetectEvent);\n    off(document, 'touchmove', nearestEmptyInsertDetectEvent);\n  },\n  _offUpEvents: function _offUpEvents() {\n    var ownerDocument = this.el.ownerDocument;\n    off(ownerDocument, 'mouseup', this._onDrop);\n    off(ownerDocument, 'touchend', this._onDrop);\n    off(ownerDocument, 'pointerup', this._onDrop);\n    off(ownerDocument, 'pointercancel', this._onDrop);\n    off(ownerDocument, 'touchcancel', this._onDrop);\n    off(document, 'selectstart', this);\n  },\n  _onDrop: function _onDrop( /**Event*/evt) {\n    var el = this.el,\n      options = this.options;\n\n    // Get the index of the dragged element within its parent\n    newIndex = index(dragEl);\n    newDraggableIndex = index(dragEl, options.draggable);\n    pluginEvent('drop', this, {\n      evt: evt\n    });\n    parentEl = dragEl && dragEl.parentNode;\n\n    // Get again after plugin event\n    newIndex = index(dragEl);\n    newDraggableIndex = index(dragEl, options.draggable);\n    if (Sortable.eventCanceled) {\n      this._nulling();\n      return;\n    }\n    awaitingDragStarted = false;\n    isCircumstantialInvert = false;\n    pastFirstInvertThresh = false;\n    clearInterval(this._loopId);\n    clearTimeout(this._dragStartTimer);\n    _cancelNextTick(this.cloneId);\n    _cancelNextTick(this._dragStartId);\n\n    // Unbind events\n    if (this.nativeDraggable) {\n      off(document, 'drop', this);\n      off(el, 'dragstart', this._onDragStart);\n    }\n    this._offMoveEvents();\n    this._offUpEvents();\n    if (Safari) {\n      css(document.body, 'user-select', '');\n    }\n    css(dragEl, 'transform', '');\n    if (evt) {\n      if (moved) {\n        evt.cancelable && evt.preventDefault();\n        !options.dropBubble && evt.stopPropagation();\n      }\n      ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);\n      if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {\n        // Remove clone(s)\n        cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);\n      }\n      if (dragEl) {\n        if (this.nativeDraggable) {\n          off(dragEl, 'dragend', this);\n        }\n        _disableDraggable(dragEl);\n        dragEl.style['will-change'] = '';\n\n        // Remove classes\n        // ghostClass is added in dragStarted\n        if (moved && !awaitingDragStarted) {\n          toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);\n        }\n        toggleClass(dragEl, this.options.chosenClass, false);\n\n        // Drag stop event\n        _dispatchEvent({\n          sortable: this,\n          name: 'unchoose',\n          toEl: parentEl,\n          newIndex: null,\n          newDraggableIndex: null,\n          originalEvent: evt\n        });\n        if (rootEl !== parentEl) {\n          if (newIndex >= 0) {\n            // Add event\n            _dispatchEvent({\n              rootEl: parentEl,\n              name: 'add',\n              toEl: parentEl,\n              fromEl: rootEl,\n              originalEvent: evt\n            });\n\n            // Remove event\n            _dispatchEvent({\n              sortable: this,\n              name: 'remove',\n              toEl: parentEl,\n              originalEvent: evt\n            });\n\n            // drag from one list and drop into another\n            _dispatchEvent({\n              rootEl: parentEl,\n              name: 'sort',\n              toEl: parentEl,\n              fromEl: rootEl,\n              originalEvent: evt\n            });\n            _dispatchEvent({\n              sortable: this,\n              name: 'sort',\n              toEl: parentEl,\n              originalEvent: evt\n            });\n          }\n          putSortable && putSortable.save();\n        } else {\n          if (newIndex !== oldIndex) {\n            if (newIndex >= 0) {\n              // drag & drop within the same list\n              _dispatchEvent({\n                sortable: this,\n                name: 'update',\n                toEl: parentEl,\n                originalEvent: evt\n              });\n              _dispatchEvent({\n                sortable: this,\n                name: 'sort',\n                toEl: parentEl,\n                originalEvent: evt\n              });\n            }\n          }\n        }\n        if (Sortable.active) {\n          /* jshint eqnull:true */\n          if (newIndex == null || newIndex === -1) {\n            newIndex = oldIndex;\n            newDraggableIndex = oldDraggableIndex;\n          }\n          _dispatchEvent({\n            sortable: this,\n            name: 'end',\n            toEl: parentEl,\n            originalEvent: evt\n          });\n\n          // Save sorting\n          this.save();\n        }\n      }\n    }\n    this._nulling();\n  },\n  _nulling: function _nulling() {\n    pluginEvent('nulling', this);\n    rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;\n    var el = this.el;\n    savedInputChecked.forEach(function (checkEl) {\n      if (el.contains(checkEl)) {\n        checkEl.checked = true;\n      }\n    });\n    savedInputChecked.length = lastDx = lastDy = 0;\n  },\n  handleEvent: function handleEvent( /**Event*/evt) {\n    switch (evt.type) {\n      case 'drop':\n      case 'dragend':\n        this._onDrop(evt);\n        break;\n      case 'dragenter':\n      case 'dragover':\n        if (dragEl) {\n          this._onDragOver(evt);\n          _globalDragOver(evt);\n        }\n        break;\n      case 'selectstart':\n        evt.preventDefault();\n        break;\n    }\n  },\n  /**\r\n   * Serializes the item into an array of string.\r\n   * @returns {String[]}\r\n   */\n  toArray: function toArray() {\n    var order = [],\n      el,\n      children = this.el.children,\n      i = 0,\n      n = children.length,\n      options = this.options;\n    for (; i < n; i++) {\n      el = children[i];\n      if (closest(el, options.draggable, this.el, false)) {\n        order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));\n      }\n    }\n    return order;\n  },\n  /**\r\n   * Sorts the elements according to the array.\r\n   * @param  {String[]}  order  order of the items\r\n   */\n  sort: function sort(order, useAnimation) {\n    var items = {},\n      rootEl = this.el;\n    this.toArray().forEach(function (id, i) {\n      var el = rootEl.children[i];\n      if (closest(el, this.options.draggable, rootEl, false)) {\n        items[id] = el;\n      }\n    }, this);\n    useAnimation && this.captureAnimationState();\n    order.forEach(function (id) {\n      if (items[id]) {\n        rootEl.removeChild(items[id]);\n        rootEl.appendChild(items[id]);\n      }\n    });\n    useAnimation && this.animateAll();\n  },\n  /**\r\n   * Save the current sorting\r\n   */\n  save: function save() {\n    var store = this.options.store;\n    store && store.set && store.set(this);\n  },\n  /**\r\n   * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.\r\n   * @param   {HTMLElement}  el\r\n   * @param   {String}       [selector]  default: `options.draggable`\r\n   * @returns {HTMLElement|null}\r\n   */\n  closest: function closest$1(el, selector) {\n    return closest(el, selector || this.options.draggable, this.el, false);\n  },\n  /**\r\n   * Set/get option\r\n   * @param   {string} name\r\n   * @param   {*}      [value]\r\n   * @returns {*}\r\n   */\n  option: function option(name, value) {\n    var options = this.options;\n    if (value === void 0) {\n      return options[name];\n    } else {\n      var modifiedValue = PluginManager.modifyOption(this, name, value);\n      if (typeof modifiedValue !== 'undefined') {\n        options[name] = modifiedValue;\n      } else {\n        options[name] = value;\n      }\n      if (name === 'group') {\n        _prepareGroup(options);\n      }\n    }\n  },\n  /**\r\n   * Destroy\r\n   */\n  destroy: function destroy() {\n    pluginEvent('destroy', this);\n    var el = this.el;\n    el[expando] = null;\n    off(el, 'mousedown', this._onTapStart);\n    off(el, 'touchstart', this._onTapStart);\n    off(el, 'pointerdown', this._onTapStart);\n    if (this.nativeDraggable) {\n      off(el, 'dragover', this);\n      off(el, 'dragenter', this);\n    }\n    // Remove draggable attributes\n    Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {\n      el.removeAttribute('draggable');\n    });\n    this._onDrop();\n    this._disableDelayedDragEvents();\n    sortables.splice(sortables.indexOf(this.el), 1);\n    this.el = el = null;\n  },\n  _hideClone: function _hideClone() {\n    if (!cloneHidden) {\n      pluginEvent('hideClone', this);\n      if (Sortable.eventCanceled) return;\n      css(cloneEl, 'display', 'none');\n      if (this.options.removeCloneOnHide && cloneEl.parentNode) {\n        cloneEl.parentNode.removeChild(cloneEl);\n      }\n      cloneHidden = true;\n    }\n  },\n  _showClone: function _showClone(putSortable) {\n    if (putSortable.lastPutMode !== 'clone') {\n      this._hideClone();\n      return;\n    }\n    if (cloneHidden) {\n      pluginEvent('showClone', this);\n      if (Sortable.eventCanceled) return;\n\n      // show clone at dragEl or original position\n      if (dragEl.parentNode == rootEl && !this.options.group.revertClone) {\n        rootEl.insertBefore(cloneEl, dragEl);\n      } else if (nextEl) {\n        rootEl.insertBefore(cloneEl, nextEl);\n      } else {\n        rootEl.appendChild(cloneEl);\n      }\n      if (this.options.group.revertClone) {\n        this.animate(dragEl, cloneEl);\n      }\n      css(cloneEl, 'display', '');\n      cloneHidden = false;\n    }\n  }\n};\nfunction _globalDragOver( /**Event*/evt) {\n  if (evt.dataTransfer) {\n    evt.dataTransfer.dropEffect = 'move';\n  }\n  evt.cancelable && evt.preventDefault();\n}\nfunction _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {\n  var evt,\n    sortable = fromEl[expando],\n    onMoveFn = sortable.options.onMove,\n    retVal;\n  // Support for new CustomEvent feature\n  if (window.CustomEvent && !IE11OrLess && !Edge) {\n    evt = new CustomEvent('move', {\n      bubbles: true,\n      cancelable: true\n    });\n  } else {\n    evt = document.createEvent('Event');\n    evt.initEvent('move', true, true);\n  }\n  evt.to = toEl;\n  evt.from = fromEl;\n  evt.dragged = dragEl;\n  evt.draggedRect = dragRect;\n  evt.related = targetEl || toEl;\n  evt.relatedRect = targetRect || getRect(toEl);\n  evt.willInsertAfter = willInsertAfter;\n  evt.originalEvent = originalEvent;\n  fromEl.dispatchEvent(evt);\n  if (onMoveFn) {\n    retVal = onMoveFn.call(sortable, evt, originalEvent);\n  }\n  return retVal;\n}\nfunction _disableDraggable(el) {\n  el.draggable = false;\n}\nfunction _unsilent() {\n  _silent = false;\n}\nfunction _ghostIsFirst(evt, vertical, sortable) {\n  var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true));\n  var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);\n  var spacer = 10;\n  return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left;\n}\nfunction _ghostIsLast(evt, vertical, sortable) {\n  var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable));\n  var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl);\n  var spacer = 10;\n  return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top;\n}\nfunction _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {\n  var mouseOnAxis = vertical ? evt.clientY : evt.clientX,\n    targetLength = vertical ? targetRect.height : targetRect.width,\n    targetS1 = vertical ? targetRect.top : targetRect.left,\n    targetS2 = vertical ? targetRect.bottom : targetRect.right,\n    invert = false;\n  if (!invertSwap) {\n    // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold\n    if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {\n      // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2\n      // check if past first invert threshold on side opposite of lastDirection\n      if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {\n        // past first invert threshold, do not restrict inverted threshold to dragEl shadow\n        pastFirstInvertThresh = true;\n      }\n      if (!pastFirstInvertThresh) {\n        // dragEl shadow (target move distance shadow)\n        if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow\n        : mouseOnAxis > targetS2 - targetMoveDistance) {\n          return -lastDirection;\n        }\n      } else {\n        invert = true;\n      }\n    } else {\n      // Regular\n      if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {\n        return _getInsertDirection(target);\n      }\n    }\n  }\n  invert = invert || invertSwap;\n  if (invert) {\n    // Invert of regular\n    if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {\n      return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;\n    }\n  }\n  return 0;\n}\n\n/**\r\n * Gets the direction dragEl must be swapped relative to target in order to make it\r\n * seem that dragEl has been \"inserted\" into that element's position\r\n * @param  {HTMLElement} target       The target whose position dragEl is being inserted at\r\n * @return {Number}                   Direction dragEl must be swapped\r\n */\nfunction _getInsertDirection(target) {\n  if (index(dragEl) < index(target)) {\n    return 1;\n  } else {\n    return -1;\n  }\n}\n\n/**\r\n * Generate id\r\n * @param   {HTMLElement} el\r\n * @returns {String}\r\n * @private\r\n */\nfunction _generateId(el) {\n  var str = el.tagName + el.className + el.src + el.href + el.textContent,\n    i = str.length,\n    sum = 0;\n  while (i--) {\n    sum += str.charCodeAt(i);\n  }\n  return sum.toString(36);\n}\nfunction _saveInputCheckedState(root) {\n  savedInputChecked.length = 0;\n  var inputs = root.getElementsByTagName('input');\n  var idx = inputs.length;\n  while (idx--) {\n    var el = inputs[idx];\n    el.checked && savedInputChecked.push(el);\n  }\n}\nfunction _nextTick(fn) {\n  return setTimeout(fn, 0);\n}\nfunction _cancelNextTick(id) {\n  return clearTimeout(id);\n}\n\n// Fixed #973:\nif (documentExists) {\n  on(document, 'touchmove', function (evt) {\n    if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {\n      evt.preventDefault();\n    }\n  });\n}\n\n// Export utils\nSortable.utils = {\n  on: on,\n  off: off,\n  css: css,\n  find: find,\n  is: function is(el, selector) {\n    return !!closest(el, selector, el, false);\n  },\n  extend: extend,\n  throttle: throttle,\n  closest: closest,\n  toggleClass: toggleClass,\n  clone: clone,\n  index: index,\n  nextTick: _nextTick,\n  cancelNextTick: _cancelNextTick,\n  detectDirection: _detectDirection,\n  getChild: getChild,\n  expando: expando\n};\n\n/**\r\n * Get the Sortable instance of an element\r\n * @param  {HTMLElement} element The element\r\n * @return {Sortable|undefined}         The instance of Sortable\r\n */\nSortable.get = function (element) {\n  return element[expando];\n};\n\n/**\r\n * Mount a plugin to Sortable\r\n * @param  {...SortablePlugin|SortablePlugin[]} plugins       Plugins being mounted\r\n */\nSortable.mount = function () {\n  for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {\n    plugins[_key] = arguments[_key];\n  }\n  if (plugins[0].constructor === Array) plugins = plugins[0];\n  plugins.forEach(function (plugin) {\n    if (!plugin.prototype || !plugin.prototype.constructor) {\n      throw \"Sortable: Mounted plugin must be a constructor function, not \".concat({}.toString.call(plugin));\n    }\n    if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils);\n    PluginManager.mount(plugin);\n  });\n};\n\n/**\r\n * Create sortable instance\r\n * @param {HTMLElement}  el\r\n * @param {Object}      [options]\r\n */\nSortable.create = function (el, options) {\n  return new Sortable(el, options);\n};\n\n// Export\nSortable.version = version;\n\nvar autoScrolls = [],\n  scrollEl,\n  scrollRootEl,\n  scrolling = false,\n  lastAutoScrollX,\n  lastAutoScrollY,\n  touchEvt$1,\n  pointerElemChangedInterval;\nfunction AutoScrollPlugin() {\n  function AutoScroll() {\n    this.defaults = {\n      scroll: true,\n      forceAutoScrollFallback: false,\n      scrollSensitivity: 30,\n      scrollSpeed: 10,\n      bubbleScroll: true\n    };\n\n    // Bind all private methods\n    for (var fn in this) {\n      if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n        this[fn] = this[fn].bind(this);\n      }\n    }\n  }\n  AutoScroll.prototype = {\n    dragStarted: function dragStarted(_ref) {\n      var originalEvent = _ref.originalEvent;\n      if (this.sortable.nativeDraggable) {\n        on(document, 'dragover', this._handleAutoScroll);\n      } else {\n        if (this.options.supportPointer) {\n          on(document, 'pointermove', this._handleFallbackAutoScroll);\n        } else if (originalEvent.touches) {\n          on(document, 'touchmove', this._handleFallbackAutoScroll);\n        } else {\n          on(document, 'mousemove', this._handleFallbackAutoScroll);\n        }\n      }\n    },\n    dragOverCompleted: function dragOverCompleted(_ref2) {\n      var originalEvent = _ref2.originalEvent;\n      // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)\n      if (!this.options.dragOverBubble && !originalEvent.rootEl) {\n        this._handleAutoScroll(originalEvent);\n      }\n    },\n    drop: function drop() {\n      if (this.sortable.nativeDraggable) {\n        off(document, 'dragover', this._handleAutoScroll);\n      } else {\n        off(document, 'pointermove', this._handleFallbackAutoScroll);\n        off(document, 'touchmove', this._handleFallbackAutoScroll);\n        off(document, 'mousemove', this._handleFallbackAutoScroll);\n      }\n      clearPointerElemChangedInterval();\n      clearAutoScrolls();\n      cancelThrottle();\n    },\n    nulling: function nulling() {\n      touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;\n      autoScrolls.length = 0;\n    },\n    _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {\n      this._handleAutoScroll(evt, true);\n    },\n    _handleAutoScroll: function _handleAutoScroll(evt, fallback) {\n      var _this = this;\n      var x = (evt.touches ? evt.touches[0] : evt).clientX,\n        y = (evt.touches ? evt.touches[0] : evt).clientY,\n        elem = document.elementFromPoint(x, y);\n      touchEvt$1 = evt;\n\n      // IE does not seem to have native autoscroll,\n      // Edge's autoscroll seems too conditional,\n      // MACOS Safari does not have autoscroll,\n      // Firefox and Chrome are good\n      if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) {\n        autoScroll(evt, this.options, elem, fallback);\n\n        // Listener for pointer element change\n        var ogElemScroller = getParentAutoScrollElement(elem, true);\n        if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {\n          pointerElemChangedInterval && clearPointerElemChangedInterval();\n          // Detect for pointer elem change, emulating native DnD behaviour\n          pointerElemChangedInterval = setInterval(function () {\n            var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);\n            if (newElem !== ogElemScroller) {\n              ogElemScroller = newElem;\n              clearAutoScrolls();\n            }\n            autoScroll(evt, _this.options, newElem, fallback);\n          }, 10);\n          lastAutoScrollX = x;\n          lastAutoScrollY = y;\n        }\n      } else {\n        // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll\n        if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {\n          clearAutoScrolls();\n          return;\n        }\n        autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);\n      }\n    }\n  };\n  return _extends(AutoScroll, {\n    pluginName: 'scroll',\n    initializeByDefault: true\n  });\n}\nfunction clearAutoScrolls() {\n  autoScrolls.forEach(function (autoScroll) {\n    clearInterval(autoScroll.pid);\n  });\n  autoScrolls = [];\n}\nfunction clearPointerElemChangedInterval() {\n  clearInterval(pointerElemChangedInterval);\n}\nvar autoScroll = throttle(function (evt, options, rootEl, isFallback) {\n  // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521\n  if (!options.scroll) return;\n  var x = (evt.touches ? evt.touches[0] : evt).clientX,\n    y = (evt.touches ? evt.touches[0] : evt).clientY,\n    sens = options.scrollSensitivity,\n    speed = options.scrollSpeed,\n    winScroller = getWindowScrollingElement();\n  var scrollThisInstance = false,\n    scrollCustomFn;\n\n  // New scroll root, set scrollEl\n  if (scrollRootEl !== rootEl) {\n    scrollRootEl = rootEl;\n    clearAutoScrolls();\n    scrollEl = options.scroll;\n    scrollCustomFn = options.scrollFn;\n    if (scrollEl === true) {\n      scrollEl = getParentAutoScrollElement(rootEl, true);\n    }\n  }\n  var layersOut = 0;\n  var currentParent = scrollEl;\n  do {\n    var el = currentParent,\n      rect = getRect(el),\n      top = rect.top,\n      bottom = rect.bottom,\n      left = rect.left,\n      right = rect.right,\n      width = rect.width,\n      height = rect.height,\n      canScrollX = void 0,\n      canScrollY = void 0,\n      scrollWidth = el.scrollWidth,\n      scrollHeight = el.scrollHeight,\n      elCSS = css(el),\n      scrollPosX = el.scrollLeft,\n      scrollPosY = el.scrollTop;\n    if (el === winScroller) {\n      canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');\n      canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');\n    } else {\n      canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');\n      canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');\n    }\n    var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX);\n    var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY);\n    if (!autoScrolls[layersOut]) {\n      for (var i = 0; i <= layersOut; i++) {\n        if (!autoScrolls[i]) {\n          autoScrolls[i] = {};\n        }\n      }\n    }\n    if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {\n      autoScrolls[layersOut].el = el;\n      autoScrolls[layersOut].vx = vx;\n      autoScrolls[layersOut].vy = vy;\n      clearInterval(autoScrolls[layersOut].pid);\n      if (vx != 0 || vy != 0) {\n        scrollThisInstance = true;\n        /* jshint loopfunc:true */\n        autoScrolls[layersOut].pid = setInterval(function () {\n          // emulate drag over during autoscroll (fallback), emulating native DnD behaviour\n          if (isFallback && this.layer === 0) {\n            Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely\n          }\n          var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;\n          var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;\n          if (typeof scrollCustomFn === 'function') {\n            if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {\n              return;\n            }\n          }\n          scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);\n        }.bind({\n          layer: layersOut\n        }), 24);\n      }\n    }\n    layersOut++;\n  } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));\n  scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not\n}, 30);\n\nvar drop = function drop(_ref) {\n  var originalEvent = _ref.originalEvent,\n    putSortable = _ref.putSortable,\n    dragEl = _ref.dragEl,\n    activeSortable = _ref.activeSortable,\n    dispatchSortableEvent = _ref.dispatchSortableEvent,\n    hideGhostForTarget = _ref.hideGhostForTarget,\n    unhideGhostForTarget = _ref.unhideGhostForTarget;\n  if (!originalEvent) return;\n  var toSortable = putSortable || activeSortable;\n  hideGhostForTarget();\n  var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent;\n  var target = document.elementFromPoint(touch.clientX, touch.clientY);\n  unhideGhostForTarget();\n  if (toSortable && !toSortable.el.contains(target)) {\n    dispatchSortableEvent('spill');\n    this.onSpill({\n      dragEl: dragEl,\n      putSortable: putSortable\n    });\n  }\n};\nfunction Revert() {}\nRevert.prototype = {\n  startIndex: null,\n  dragStart: function dragStart(_ref2) {\n    var oldDraggableIndex = _ref2.oldDraggableIndex;\n    this.startIndex = oldDraggableIndex;\n  },\n  onSpill: function onSpill(_ref3) {\n    var dragEl = _ref3.dragEl,\n      putSortable = _ref3.putSortable;\n    this.sortable.captureAnimationState();\n    if (putSortable) {\n      putSortable.captureAnimationState();\n    }\n    var nextSibling = getChild(this.sortable.el, this.startIndex, this.options);\n    if (nextSibling) {\n      this.sortable.el.insertBefore(dragEl, nextSibling);\n    } else {\n      this.sortable.el.appendChild(dragEl);\n    }\n    this.sortable.animateAll();\n    if (putSortable) {\n      putSortable.animateAll();\n    }\n  },\n  drop: drop\n};\n_extends(Revert, {\n  pluginName: 'revertOnSpill'\n});\nfunction Remove() {}\nRemove.prototype = {\n  onSpill: function onSpill(_ref4) {\n    var dragEl = _ref4.dragEl,\n      putSortable = _ref4.putSortable;\n    var parentSortable = putSortable || this.sortable;\n    parentSortable.captureAnimationState();\n    dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);\n    parentSortable.animateAll();\n  },\n  drop: drop\n};\n_extends(Remove, {\n  pluginName: 'removeOnSpill'\n});\n\nvar lastSwapEl;\nfunction SwapPlugin() {\n  function Swap() {\n    this.defaults = {\n      swapClass: 'sortable-swap-highlight'\n    };\n  }\n  Swap.prototype = {\n    dragStart: function dragStart(_ref) {\n      var dragEl = _ref.dragEl;\n      lastSwapEl = dragEl;\n    },\n    dragOverValid: function dragOverValid(_ref2) {\n      var completed = _ref2.completed,\n        target = _ref2.target,\n        onMove = _ref2.onMove,\n        activeSortable = _ref2.activeSortable,\n        changed = _ref2.changed,\n        cancel = _ref2.cancel;\n      if (!activeSortable.options.swap) return;\n      var el = this.sortable.el,\n        options = this.options;\n      if (target && target !== el) {\n        var prevSwapEl = lastSwapEl;\n        if (onMove(target) !== false) {\n          toggleClass(target, options.swapClass, true);\n          lastSwapEl = target;\n        } else {\n          lastSwapEl = null;\n        }\n        if (prevSwapEl && prevSwapEl !== lastSwapEl) {\n          toggleClass(prevSwapEl, options.swapClass, false);\n        }\n      }\n      changed();\n      completed(true);\n      cancel();\n    },\n    drop: function drop(_ref3) {\n      var activeSortable = _ref3.activeSortable,\n        putSortable = _ref3.putSortable,\n        dragEl = _ref3.dragEl;\n      var toSortable = putSortable || this.sortable;\n      var options = this.options;\n      lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);\n      if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {\n        if (dragEl !== lastSwapEl) {\n          toSortable.captureAnimationState();\n          if (toSortable !== activeSortable) activeSortable.captureAnimationState();\n          swapNodes(dragEl, lastSwapEl);\n          toSortable.animateAll();\n          if (toSortable !== activeSortable) activeSortable.animateAll();\n        }\n      }\n    },\n    nulling: function nulling() {\n      lastSwapEl = null;\n    }\n  };\n  return _extends(Swap, {\n    pluginName: 'swap',\n    eventProperties: function eventProperties() {\n      return {\n        swapItem: lastSwapEl\n      };\n    }\n  });\n}\nfunction swapNodes(n1, n2) {\n  var p1 = n1.parentNode,\n    p2 = n2.parentNode,\n    i1,\n    i2;\n  if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;\n  i1 = index(n1);\n  i2 = index(n2);\n  if (p1.isEqualNode(p2) && i1 < i2) {\n    i2++;\n  }\n  p1.insertBefore(n2, p1.children[i1]);\n  p2.insertBefore(n1, p2.children[i2]);\n}\n\nvar multiDragElements = [],\n  multiDragClones = [],\n  lastMultiDragSelect,\n  // for selection with modifier key down (SHIFT)\n  multiDragSortable,\n  initialFolding = false,\n  // Initial multi-drag fold when drag started\n  folding = false,\n  // Folding any other time\n  dragStarted = false,\n  dragEl$1,\n  clonesFromRect,\n  clonesHidden;\nfunction MultiDragPlugin() {\n  function MultiDrag(sortable) {\n    // Bind all private methods\n    for (var fn in this) {\n      if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {\n        this[fn] = this[fn].bind(this);\n      }\n    }\n    if (!sortable.options.avoidImplicitDeselect) {\n      if (sortable.options.supportPointer) {\n        on(document, 'pointerup', this._deselectMultiDrag);\n      } else {\n        on(document, 'mouseup', this._deselectMultiDrag);\n        on(document, 'touchend', this._deselectMultiDrag);\n      }\n    }\n    on(document, 'keydown', this._checkKeyDown);\n    on(document, 'keyup', this._checkKeyUp);\n    this.defaults = {\n      selectedClass: 'sortable-selected',\n      multiDragKey: null,\n      avoidImplicitDeselect: false,\n      setData: function setData(dataTransfer, dragEl) {\n        var data = '';\n        if (multiDragElements.length && multiDragSortable === sortable) {\n          multiDragElements.forEach(function (multiDragElement, i) {\n            data += (!i ? '' : ', ') + multiDragElement.textContent;\n          });\n        } else {\n          data = dragEl.textContent;\n        }\n        dataTransfer.setData('Text', data);\n      }\n    };\n  }\n  MultiDrag.prototype = {\n    multiDragKeyDown: false,\n    isMultiDrag: false,\n    delayStartGlobal: function delayStartGlobal(_ref) {\n      var dragged = _ref.dragEl;\n      dragEl$1 = dragged;\n    },\n    delayEnded: function delayEnded() {\n      this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1);\n    },\n    setupClone: function setupClone(_ref2) {\n      var sortable = _ref2.sortable,\n        cancel = _ref2.cancel;\n      if (!this.isMultiDrag) return;\n      for (var i = 0; i < multiDragElements.length; i++) {\n        multiDragClones.push(clone(multiDragElements[i]));\n        multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex;\n        multiDragClones[i].draggable = false;\n        multiDragClones[i].style['will-change'] = '';\n        toggleClass(multiDragClones[i], this.options.selectedClass, false);\n        multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false);\n      }\n      sortable._hideClone();\n      cancel();\n    },\n    clone: function clone(_ref3) {\n      var sortable = _ref3.sortable,\n        rootEl = _ref3.rootEl,\n        dispatchSortableEvent = _ref3.dispatchSortableEvent,\n        cancel = _ref3.cancel;\n      if (!this.isMultiDrag) return;\n      if (!this.options.removeCloneOnHide) {\n        if (multiDragElements.length && multiDragSortable === sortable) {\n          insertMultiDragClones(true, rootEl);\n          dispatchSortableEvent('clone');\n          cancel();\n        }\n      }\n    },\n    showClone: function showClone(_ref4) {\n      var cloneNowShown = _ref4.cloneNowShown,\n        rootEl = _ref4.rootEl,\n        cancel = _ref4.cancel;\n      if (!this.isMultiDrag) return;\n      insertMultiDragClones(false, rootEl);\n      multiDragClones.forEach(function (clone) {\n        css(clone, 'display', '');\n      });\n      cloneNowShown();\n      clonesHidden = false;\n      cancel();\n    },\n    hideClone: function hideClone(_ref5) {\n      var _this = this;\n      var sortable = _ref5.sortable,\n        cloneNowHidden = _ref5.cloneNowHidden,\n        cancel = _ref5.cancel;\n      if (!this.isMultiDrag) return;\n      multiDragClones.forEach(function (clone) {\n        css(clone, 'display', 'none');\n        if (_this.options.removeCloneOnHide && clone.parentNode) {\n          clone.parentNode.removeChild(clone);\n        }\n      });\n      cloneNowHidden();\n      clonesHidden = true;\n      cancel();\n    },\n    dragStartGlobal: function dragStartGlobal(_ref6) {\n      var sortable = _ref6.sortable;\n      if (!this.isMultiDrag && multiDragSortable) {\n        multiDragSortable.multiDrag._deselectMultiDrag();\n      }\n      multiDragElements.forEach(function (multiDragElement) {\n        multiDragElement.sortableIndex = index(multiDragElement);\n      });\n\n      // Sort multi-drag elements\n      multiDragElements = multiDragElements.sort(function (a, b) {\n        return a.sortableIndex - b.sortableIndex;\n      });\n      dragStarted = true;\n    },\n    dragStarted: function dragStarted(_ref7) {\n      var _this2 = this;\n      var sortable = _ref7.sortable;\n      if (!this.isMultiDrag) return;\n      if (this.options.sort) {\n        // Capture rects,\n        // hide multi drag elements (by positioning them absolute),\n        // set multi drag elements rects to dragRect,\n        // show multi drag elements,\n        // animate to rects,\n        // unset rects & remove from DOM\n\n        sortable.captureAnimationState();\n        if (this.options.animation) {\n          multiDragElements.forEach(function (multiDragElement) {\n            if (multiDragElement === dragEl$1) return;\n            css(multiDragElement, 'position', 'absolute');\n          });\n          var dragRect = getRect(dragEl$1, false, true, true);\n          multiDragElements.forEach(function (multiDragElement) {\n            if (multiDragElement === dragEl$1) return;\n            setRect(multiDragElement, dragRect);\n          });\n          folding = true;\n          initialFolding = true;\n        }\n      }\n      sortable.animateAll(function () {\n        folding = false;\n        initialFolding = false;\n        if (_this2.options.animation) {\n          multiDragElements.forEach(function (multiDragElement) {\n            unsetRect(multiDragElement);\n          });\n        }\n\n        // Remove all auxiliary multidrag items from el, if sorting enabled\n        if (_this2.options.sort) {\n          removeMultiDragElements();\n        }\n      });\n    },\n    dragOver: function dragOver(_ref8) {\n      var target = _ref8.target,\n        completed = _ref8.completed,\n        cancel = _ref8.cancel;\n      if (folding && ~multiDragElements.indexOf(target)) {\n        completed(false);\n        cancel();\n      }\n    },\n    revert: function revert(_ref9) {\n      var fromSortable = _ref9.fromSortable,\n        rootEl = _ref9.rootEl,\n        sortable = _ref9.sortable,\n        dragRect = _ref9.dragRect;\n      if (multiDragElements.length > 1) {\n        // Setup unfold animation\n        multiDragElements.forEach(function (multiDragElement) {\n          sortable.addAnimationState({\n            target: multiDragElement,\n            rect: folding ? getRect(multiDragElement) : dragRect\n          });\n          unsetRect(multiDragElement);\n          multiDragElement.fromRect = dragRect;\n          fromSortable.removeAnimationState(multiDragElement);\n        });\n        folding = false;\n        insertMultiDragElements(!this.options.removeCloneOnHide, rootEl);\n      }\n    },\n    dragOverCompleted: function dragOverCompleted(_ref10) {\n      var sortable = _ref10.sortable,\n        isOwner = _ref10.isOwner,\n        insertion = _ref10.insertion,\n        activeSortable = _ref10.activeSortable,\n        parentEl = _ref10.parentEl,\n        putSortable = _ref10.putSortable;\n      var options = this.options;\n      if (insertion) {\n        // Clones must be hidden before folding animation to capture dragRectAbsolute properly\n        if (isOwner) {\n          activeSortable._hideClone();\n        }\n        initialFolding = false;\n        // If leaving sort:false root, or already folding - Fold to new location\n        if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) {\n          // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible\n          var dragRectAbsolute = getRect(dragEl$1, false, true, true);\n          multiDragElements.forEach(function (multiDragElement) {\n            if (multiDragElement === dragEl$1) return;\n            setRect(multiDragElement, dragRectAbsolute);\n\n            // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted\n            // while folding, and so that we can capture them again because old sortable will no longer be fromSortable\n            parentEl.appendChild(multiDragElement);\n          });\n          folding = true;\n        }\n\n        // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out\n        if (!isOwner) {\n          // Only remove if not folding (folding will remove them anyways)\n          if (!folding) {\n            removeMultiDragElements();\n          }\n          if (multiDragElements.length > 1) {\n            var clonesHiddenBefore = clonesHidden;\n            activeSortable._showClone(sortable);\n\n            // Unfold animation for clones if showing from hidden\n            if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) {\n              multiDragClones.forEach(function (clone) {\n                activeSortable.addAnimationState({\n                  target: clone,\n                  rect: clonesFromRect\n                });\n                clone.fromRect = clonesFromRect;\n                clone.thisAnimationDuration = null;\n              });\n            }\n          } else {\n            activeSortable._showClone(sortable);\n          }\n        }\n      }\n    },\n    dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) {\n      var dragRect = _ref11.dragRect,\n        isOwner = _ref11.isOwner,\n        activeSortable = _ref11.activeSortable;\n      multiDragElements.forEach(function (multiDragElement) {\n        multiDragElement.thisAnimationDuration = null;\n      });\n      if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) {\n        clonesFromRect = _extends({}, dragRect);\n        var dragMatrix = matrix(dragEl$1, true);\n        clonesFromRect.top -= dragMatrix.f;\n        clonesFromRect.left -= dragMatrix.e;\n      }\n    },\n    dragOverAnimationComplete: function dragOverAnimationComplete() {\n      if (folding) {\n        folding = false;\n        removeMultiDragElements();\n      }\n    },\n    drop: function drop(_ref12) {\n      var evt = _ref12.originalEvent,\n        rootEl = _ref12.rootEl,\n        parentEl = _ref12.parentEl,\n        sortable = _ref12.sortable,\n        dispatchSortableEvent = _ref12.dispatchSortableEvent,\n        oldIndex = _ref12.oldIndex,\n        putSortable = _ref12.putSortable;\n      var toSortable = putSortable || this.sortable;\n      if (!evt) return;\n      var options = this.options,\n        children = parentEl.children;\n\n      // Multi-drag selection\n      if (!dragStarted) {\n        if (options.multiDragKey && !this.multiDragKeyDown) {\n          this._deselectMultiDrag();\n        }\n        toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1));\n        if (!~multiDragElements.indexOf(dragEl$1)) {\n          multiDragElements.push(dragEl$1);\n          dispatchEvent({\n            sortable: sortable,\n            rootEl: rootEl,\n            name: 'select',\n            targetEl: dragEl$1,\n            originalEvent: evt\n          });\n\n          // Modifier activated, select from last to dragEl\n          if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) {\n            var lastIndex = index(lastMultiDragSelect),\n              currentIndex = index(dragEl$1);\n            if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) {\n              (function () {\n                // Must include lastMultiDragSelect (select it), in case modified selection from no selection\n                // (but previous selection existed)\n                var n, i;\n                if (currentIndex > lastIndex) {\n                  i = lastIndex;\n                  n = currentIndex;\n                } else {\n                  i = currentIndex;\n                  n = lastIndex + 1;\n                }\n                var filter = options.filter;\n                for (; i < n; i++) {\n                  if (~multiDragElements.indexOf(children[i])) continue;\n                  // Check if element is draggable\n                  if (!closest(children[i], options.draggable, parentEl, false)) continue;\n                  // Check if element is filtered\n                  var filtered = filter && (typeof filter === 'function' ? filter.call(sortable, evt, children[i], sortable) : filter.split(',').some(function (criteria) {\n                    return closest(children[i], criteria.trim(), parentEl, false);\n                  }));\n                  if (filtered) continue;\n                  toggleClass(children[i], options.selectedClass, true);\n                  multiDragElements.push(children[i]);\n                  dispatchEvent({\n                    sortable: sortable,\n                    rootEl: rootEl,\n                    name: 'select',\n                    targetEl: children[i],\n                    originalEvent: evt\n                  });\n                }\n              })();\n            }\n          } else {\n            lastMultiDragSelect = dragEl$1;\n          }\n          multiDragSortable = toSortable;\n        } else {\n          multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1);\n          lastMultiDragSelect = null;\n          dispatchEvent({\n            sortable: sortable,\n            rootEl: rootEl,\n            name: 'deselect',\n            targetEl: dragEl$1,\n            originalEvent: evt\n          });\n        }\n      }\n\n      // Multi-drag drop\n      if (dragStarted && this.isMultiDrag) {\n        folding = false;\n        // Do not \"unfold\" after around dragEl if reverted\n        if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) {\n          var dragRect = getRect(dragEl$1),\n            multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')');\n          if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null;\n          toSortable.captureAnimationState();\n          if (!initialFolding) {\n            if (options.animation) {\n              dragEl$1.fromRect = dragRect;\n              multiDragElements.forEach(function (multiDragElement) {\n                multiDragElement.thisAnimationDuration = null;\n                if (multiDragElement !== dragEl$1) {\n                  var rect = folding ? getRect(multiDragElement) : dragRect;\n                  multiDragElement.fromRect = rect;\n\n                  // Prepare unfold animation\n                  toSortable.addAnimationState({\n                    target: multiDragElement,\n                    rect: rect\n                  });\n                }\n              });\n            }\n\n            // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert\n            // properly they must all be removed\n            removeMultiDragElements();\n            multiDragElements.forEach(function (multiDragElement) {\n              if (children[multiDragIndex]) {\n                parentEl.insertBefore(multiDragElement, children[multiDragIndex]);\n              } else {\n                parentEl.appendChild(multiDragElement);\n              }\n              multiDragIndex++;\n            });\n\n            // If initial folding is done, the elements may have changed position because they are now\n            // unfolding around dragEl, even though dragEl may not have his index changed, so update event\n            // must be fired here as Sortable will not.\n            if (oldIndex === index(dragEl$1)) {\n              var update = false;\n              multiDragElements.forEach(function (multiDragElement) {\n                if (multiDragElement.sortableIndex !== index(multiDragElement)) {\n                  update = true;\n                  return;\n                }\n              });\n              if (update) {\n                dispatchSortableEvent('update');\n                dispatchSortableEvent('sort');\n              }\n            }\n          }\n\n          // Must be done after capturing individual rects (scroll bar)\n          multiDragElements.forEach(function (multiDragElement) {\n            unsetRect(multiDragElement);\n          });\n          toSortable.animateAll();\n        }\n        multiDragSortable = toSortable;\n      }\n\n      // Remove clones if necessary\n      if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {\n        multiDragClones.forEach(function (clone) {\n          clone.parentNode && clone.parentNode.removeChild(clone);\n        });\n      }\n    },\n    nullingGlobal: function nullingGlobal() {\n      this.isMultiDrag = dragStarted = false;\n      multiDragClones.length = 0;\n    },\n    destroyGlobal: function destroyGlobal() {\n      this._deselectMultiDrag();\n      off(document, 'pointerup', this._deselectMultiDrag);\n      off(document, 'mouseup', this._deselectMultiDrag);\n      off(document, 'touchend', this._deselectMultiDrag);\n      off(document, 'keydown', this._checkKeyDown);\n      off(document, 'keyup', this._checkKeyUp);\n    },\n    _deselectMultiDrag: function _deselectMultiDrag(evt) {\n      if (typeof dragStarted !== \"undefined\" && dragStarted) return;\n\n      // Only deselect if selection is in this sortable\n      if (multiDragSortable !== this.sortable) return;\n\n      // Only deselect if target is not item in this sortable\n      if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return;\n\n      // Only deselect if left click\n      if (evt && evt.button !== 0) return;\n      while (multiDragElements.length) {\n        var el = multiDragElements[0];\n        toggleClass(el, this.options.selectedClass, false);\n        multiDragElements.shift();\n        dispatchEvent({\n          sortable: this.sortable,\n          rootEl: this.sortable.el,\n          name: 'deselect',\n          targetEl: el,\n          originalEvent: evt\n        });\n      }\n    },\n    _checkKeyDown: function _checkKeyDown(evt) {\n      if (evt.key === this.options.multiDragKey) {\n        this.multiDragKeyDown = true;\n      }\n    },\n    _checkKeyUp: function _checkKeyUp(evt) {\n      if (evt.key === this.options.multiDragKey) {\n        this.multiDragKeyDown = false;\n      }\n    }\n  };\n  return _extends(MultiDrag, {\n    // Static methods & properties\n    pluginName: 'multiDrag',\n    utils: {\n      /**\r\n       * Selects the provided multi-drag item\r\n       * @param  {HTMLElement} el    The element to be selected\r\n       */\n      select: function select(el) {\n        var sortable = el.parentNode[expando];\n        if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return;\n        if (multiDragSortable && multiDragSortable !== sortable) {\n          multiDragSortable.multiDrag._deselectMultiDrag();\n          multiDragSortable = sortable;\n        }\n        toggleClass(el, sortable.options.selectedClass, true);\n        multiDragElements.push(el);\n      },\n      /**\r\n       * Deselects the provided multi-drag item\r\n       * @param  {HTMLElement} el    The element to be deselected\r\n       */\n      deselect: function deselect(el) {\n        var sortable = el.parentNode[expando],\n          index = multiDragElements.indexOf(el);\n        if (!sortable || !sortable.options.multiDrag || !~index) return;\n        toggleClass(el, sortable.options.selectedClass, false);\n        multiDragElements.splice(index, 1);\n      }\n    },\n    eventProperties: function eventProperties() {\n      var _this3 = this;\n      var oldIndicies = [],\n        newIndicies = [];\n      multiDragElements.forEach(function (multiDragElement) {\n        oldIndicies.push({\n          multiDragElement: multiDragElement,\n          index: multiDragElement.sortableIndex\n        });\n\n        // multiDragElements will already be sorted if folding\n        var newIndex;\n        if (folding && multiDragElement !== dragEl$1) {\n          newIndex = -1;\n        } else if (folding) {\n          newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')');\n        } else {\n          newIndex = index(multiDragElement);\n        }\n        newIndicies.push({\n          multiDragElement: multiDragElement,\n          index: newIndex\n        });\n      });\n      return {\n        items: _toConsumableArray(multiDragElements),\n        clones: [].concat(multiDragClones),\n        oldIndicies: oldIndicies,\n        newIndicies: newIndicies\n      };\n    },\n    optionListeners: {\n      multiDragKey: function multiDragKey(key) {\n        key = key.toLowerCase();\n        if (key === 'ctrl') {\n          key = 'Control';\n        } else if (key.length > 1) {\n          key = key.charAt(0).toUpperCase() + key.substr(1);\n        }\n        return key;\n      }\n    }\n  });\n}\nfunction insertMultiDragElements(clonesInserted, rootEl) {\n  multiDragElements.forEach(function (multiDragElement, i) {\n    var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)];\n    if (target) {\n      rootEl.insertBefore(multiDragElement, target);\n    } else {\n      rootEl.appendChild(multiDragElement);\n    }\n  });\n}\n\n/**\r\n * Insert multi-drag clones\r\n * @param  {[Boolean]} elementsInserted  Whether the multi-drag elements are inserted\r\n * @param  {HTMLElement} rootEl\r\n */\nfunction insertMultiDragClones(elementsInserted, rootEl) {\n  multiDragClones.forEach(function (clone, i) {\n    var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)];\n    if (target) {\n      rootEl.insertBefore(clone, target);\n    } else {\n      rootEl.appendChild(clone);\n    }\n  });\n}\nfunction removeMultiDragElements() {\n  multiDragElements.forEach(function (multiDragElement) {\n    if (multiDragElement === dragEl$1) return;\n    multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement);\n  });\n}\n\nSortable.mount(new AutoScrollPlugin());\nSortable.mount(Remove, Revert);\n\nexport default Sortable;\nexport { MultiDragPlugin as MultiDrag, Sortable, SwapPlugin as Swap };\n", "import \"./list_component.css\";\nimport Sortable from 'sortablejs';\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static targets = [ \"orderInput\" ];\n  static values = { reorderable: Boolean };\n\n  connect() {\n    if (this.reorderableValue) {\n      this.connectReorderable();\n    }\n  }\n\n  connectReorderable() {\n    this.sortable = Sortable.create(\n      this.element,\n      {\n        animation: 150,\n        draggable: \".c-admin--list--item-root\",\n        fallbackOnBody: true,\n        group: this.identifier,\n        swapThreshold: 0.65,\n        store: {\n          set: this.updateOrder.bind(this),\n        }\n      }\n    );\n  }\n\n  updateOrder(sortable) {\n    const order = sortable.toArray();\n    const orderHash = order.reduce((hash, id, index) => {\n      hash[id] = index;\n      return hash;\n    }, {});\n    this.orderInputTarget.value = JSON.stringify(orderHash);\n  }\n\n  disconnect() {\n    if (this.reorderableValue) {\n      this.disconnectReorderable();\n    }\n  }\n\n  disconnectReorderable() {\n    this.sortable.destroy();\n  }\n}\n", "import \"./menu_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./activities_grid_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./agenda_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./features_grid_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./hero_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./slate_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./tabs_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static targets = [\"tablist\"];\n\n  connect() {\n    this.cache = {};\n\n    Array.prototype.forEach.call(this.tabs, tab => {\n      this.cache[tab.hash] = [\n        tab,\n        document.getElementById(tab.getAttribute(\"aria-controls\"))\n      ];\n\n      if (tab.getAttribute(\"aria-selected\") === \"true\") {\n        this.last = this.cache[tab.hash];\n        this.cache[\"\"] = this.last;\n      } else {\n        tab.setAttribute(\"tabindex\", -1);\n      }\n    });\n\n    window.addEventListener(\"hashchange\", () => this.onHashChange());\n    this.onHashChange();\n  }\n\n  focusTab(tab) {\n    if (!tab) return;\n    window.location.hash = tab.hash;\n    tab.focus();\n  }\n\n  onTabKeydown(e) {\n    let move;\n\n    if (e.keyCode === 37) {\n      move = -1;\n    } else if (e.keyCode === 39) {\n      move = 1;\n    }\n\n    if (!move) return;\n    const index = Array.prototype.indexOf.call(this.tabs, e.target);\n    const next = this.tabs[index + move];\n    this.focusTab(next);\n  }\n\n  onHashChange() {\n    const tab = this.cache[window.location.hash];\n\n    if (tab) {\n      if (this.last) {\n        this.last[0].removeAttribute(\"aria-selected\");\n        this.last[0].setAttribute(\"tabindex\", -1);\n        this.last[1].setAttribute(\"hidden\", \"\");\n      }\n\n      tab[0].setAttribute(\"aria-selected\", \"true\");\n      tab[0].removeAttribute(\"tabindex\");\n      tab[1].removeAttribute(\"hidden\", \"\");\n\n      this.last = tab;\n    }\n  }\n\n  get tabs() {\n    return this.tablistTarget.querySelectorAll('[href^=\"#\"][role=\"tab\"]');\n  }\n}\n", "import \"./toast_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  connect() {\n    if (this.element.classList.contains(\"c-admin--toaster--toast-hidden\")) {\n      setTimeout(this.reveal.bind(this), 100);\n      setTimeout(this.close.bind(this), 4500);\n    }\n  }\n\n  close(e) {\n    if (e) e.preventDefault();\n    this.hide();\n    setTimeout(this.destroy.bind(this), 500);\n  }\n\n  reveal() {\n    this.element.classList.remove(\"c-admin--toaster--toast-hidden\");\n  }\n\n  hide() {\n    this.element.classList.add(\"c-admin--toaster--toast-closed\");\n  }\n\n  destroy() {\n    this.element.parentNode.removeChild(this.element);\n  }\n}\n", "import \"./toaster_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./article_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./button_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./figure_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./gallery_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./map_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\nimport maplibregl from \"../../../javascript/lib/maplibre\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\n\nexport class Controller extends BaseController {\n  static targets = [\"map\"];\n  static values = { coordinates: { type: Array, default: [2.8094, 45.5750] } };\n\n  connect() {\n    this.map = new maplibregl.Map({\n      center: this.coordinatesValue,\n      container: this.mapTarget,\n      locale: document.documentElement.lang,\n      style: 'https://api.maptiler.com/maps/da255326-71c7-42aa-ae18-2c472015e169/style.json?key=xJfyVrC29wRP9anAe2jn',\n      zoom: 14,\n    });\n\n    this.addNavControl();\n    this.enableZoomOnClick();\n    this.addMarker();\n  }\n\n  disconnect() {\n    this.map.remove();\n  }\n\n  addNavControl() {\n    this.map.addControl(new maplibregl.NavigationControl());\n  }\n\n  enableZoomOnClick() {\n    this.map.scrollZoom.disable();\n\n    this.map.on('click', (_) => {\n      this.map.scrollZoom.enable();\n    });\n  }\n\n  addMarker() {\n    const marker = new maplibregl.Marker({\n      color: \"#1CB1CD\",\n    })\n    .setLngLat(this.coordinatesValue)\n    .addTo(this.map);\n  }\n}\n", "", "/**\n * A standalone point geometry with useful accessor, comparison, and\n * modification methods.\n *\n * @class\n * @param {number} x the x-coordinate. This could be longitude or screen pixels, or any other sort of unit.\n * @param {number} y the y-coordinate. This could be latitude or screen pixels, or any other sort of unit.\n *\n * @example\n * const point = new Point(-77, 38);\n */\nexport default function Point(x, y) {\n    this.x = x;\n    this.y = y;\n}\n\nPoint.prototype = {\n    /**\n     * Clone this point, returning a new point that can be modified\n     * without affecting the old one.\n     * @return {Point} the clone\n     */\n    clone() { return new Point(this.x, this.y); },\n\n    /**\n     * Add this point's x & y coordinates to another point,\n     * yielding a new point.\n     * @param {Point} p the other point\n     * @return {Point} output point\n     */\n    add(p) { return this.clone()._add(p); },\n\n    /**\n     * Subtract this point's x & y coordinates to from point,\n     * yielding a new point.\n     * @param {Point} p the other point\n     * @return {Point} output point\n     */\n    sub(p) { return this.clone()._sub(p); },\n\n    /**\n     * Multiply this point's x & y coordinates by point,\n     * yielding a new point.\n     * @param {Point} p the other point\n     * @return {Point} output point\n     */\n    multByPoint(p) { return this.clone()._multByPoint(p); },\n\n    /**\n     * Divide this point's x & y coordinates by point,\n     * yielding a new point.\n     * @param {Point} p the other point\n     * @return {Point} output point\n     */\n    divByPoint(p) { return this.clone()._divByPoint(p); },\n\n    /**\n     * Multiply this point's x & y coordinates by a factor,\n     * yielding a new point.\n     * @param {number} k factor\n     * @return {Point} output point\n     */\n    mult(k) { return this.clone()._mult(k); },\n\n    /**\n     * Divide this point's x & y coordinates by a factor,\n     * yielding a new point.\n     * @param {number} k factor\n     * @return {Point} output point\n     */\n    div(k) { return this.clone()._div(k); },\n\n    /**\n     * Rotate this point around the 0, 0 origin by an angle a,\n     * given in radians\n     * @param {number} a angle to rotate around, in radians\n     * @return {Point} output point\n     */\n    rotate(a) { return this.clone()._rotate(a); },\n\n    /**\n     * Rotate this point around p point by an angle a,\n     * given in radians\n     * @param {number} a angle to rotate around, in radians\n     * @param {Point} p Point to rotate around\n     * @return {Point} output point\n     */\n    rotateAround(a, p) { return this.clone()._rotateAround(a, p); },\n\n    /**\n     * Multiply this point by a 4x1 transformation matrix\n     * @param {[number, number, number, number]} m transformation matrix\n     * @return {Point} output point\n     */\n    matMult(m) { return this.clone()._matMult(m); },\n\n    /**\n     * Calculate this point but as a unit vector from 0, 0, meaning\n     * that the distance from the resulting point to the 0, 0\n     * coordinate will be equal to 1 and the angle from the resulting\n     * point to the 0, 0 coordinate will be the same as before.\n     * @return {Point} unit vector point\n     */\n    unit() { return this.clone()._unit(); },\n\n    /**\n     * Compute a perpendicular point, where the new y coordinate\n     * is the old x coordinate and the new x coordinate is the old y\n     * coordinate multiplied by -1\n     * @return {Point} perpendicular point\n     */\n    perp() { return this.clone()._perp(); },\n\n    /**\n     * Return a version of this point with the x & y coordinates\n     * rounded to integers.\n     * @return {Point} rounded point\n     */\n    round() { return this.clone()._round(); },\n\n    /**\n     * Return the magnitude of this point: this is the Euclidean\n     * distance from the 0, 0 coordinate to this point's x and y\n     * coordinates.\n     * @return {number} magnitude\n     */\n    mag() {\n        return Math.sqrt(this.x * this.x + this.y * this.y);\n    },\n\n    /**\n     * Judge whether this point is equal to another point, returning\n     * true or false.\n     * @param {Point} other the other point\n     * @return {boolean} whether the points are equal\n     */\n    equals(other) {\n        return this.x === other.x &&\n               this.y === other.y;\n    },\n\n    /**\n     * Calculate the distance from this point to another point\n     * @param {Point} p the other point\n     * @return {number} distance\n     */\n    dist(p) {\n        return Math.sqrt(this.distSqr(p));\n    },\n\n    /**\n     * Calculate the distance from this point to another point,\n     * without the square root step. Useful if you're comparing\n     * relative distances.\n     * @param {Point} p the other point\n     * @return {number} distance\n     */\n    distSqr(p) {\n        const dx = p.x - this.x,\n            dy = p.y - this.y;\n        return dx * dx + dy * dy;\n    },\n\n    /**\n     * Get the angle from the 0, 0 coordinate to this point, in radians\n     * coordinates.\n     * @return {number} angle\n     */\n    angle() {\n        return Math.atan2(this.y, this.x);\n    },\n\n    /**\n     * Get the angle from this point to another point, in radians\n     * @param {Point} b the other point\n     * @return {number} angle\n     */\n    angleTo(b) {\n        return Math.atan2(this.y - b.y, this.x - b.x);\n    },\n\n    /**\n     * Get the angle between this point and another point, in radians\n     * @param {Point} b the other point\n     * @return {number} angle\n     */\n    angleWith(b) {\n        return this.angleWithSep(b.x, b.y);\n    },\n\n    /**\n     * Find the angle of the two vectors, solving the formula for\n     * the cross product a x b = |a||b|sin(θ) for θ.\n     * @param {number} x the x-coordinate\n     * @param {number} y the y-coordinate\n     * @return {number} the angle in radians\n     */\n    angleWithSep(x, y) {\n        return Math.atan2(\n            this.x * y - this.y * x,\n            this.x * x + this.y * y);\n    },\n\n    /** @param {[number, number, number, number]} m */\n    _matMult(m) {\n        const x = m[0] * this.x + m[1] * this.y,\n            y = m[2] * this.x + m[3] * this.y;\n        this.x = x;\n        this.y = y;\n        return this;\n    },\n\n    /** @param {Point} p */\n    _add(p) {\n        this.x += p.x;\n        this.y += p.y;\n        return this;\n    },\n\n    /** @param {Point} p */\n    _sub(p) {\n        this.x -= p.x;\n        this.y -= p.y;\n        return this;\n    },\n\n    /** @param {number} k */\n    _mult(k) {\n        this.x *= k;\n        this.y *= k;\n        return this;\n    },\n\n    /** @param {number} k */\n    _div(k) {\n        this.x /= k;\n        this.y /= k;\n        return this;\n    },\n\n    /** @param {Point} p */\n    _multByPoint(p) {\n        this.x *= p.x;\n        this.y *= p.y;\n        return this;\n    },\n\n    /** @param {Point} p */\n    _divByPoint(p) {\n        this.x /= p.x;\n        this.y /= p.y;\n        return this;\n    },\n\n    _unit() {\n        this._div(this.mag());\n        return this;\n    },\n\n    _perp() {\n        const y = this.y;\n        this.y = this.x;\n        this.x = -y;\n        return this;\n    },\n\n    /** @param {number} angle */\n    _rotate(angle) {\n        const cos = Math.cos(angle),\n            sin = Math.sin(angle),\n            x = cos * this.x - sin * this.y,\n            y = sin * this.x + cos * this.y;\n        this.x = x;\n        this.y = y;\n        return this;\n    },\n\n    /**\n     * @param {number} angle\n     * @param {Point} p\n     */\n    _rotateAround(angle, p) {\n        const cos = Math.cos(angle),\n            sin = Math.sin(angle),\n            x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y),\n            y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);\n        this.x = x;\n        this.y = y;\n        return this;\n    },\n\n    _round() {\n        this.x = Math.round(this.x);\n        this.y = Math.round(this.y);\n        return this;\n    },\n\n    constructor: Point\n};\n\n/**\n * Construct a point from an array if necessary, otherwise if the input\n * is already a Point, return it unchanged.\n * @param {Point | [number, number] | {x: number, y: number}} p input value\n * @return {Point} constructed point.\n * @example\n * // this\n * var point = Point.convert([0, 1]);\n * // is equivalent to\n * var point = new Point(0, 1);\n */\nPoint.convert = function (p) {\n    if (p instanceof Point) {\n        return /** @type {Point} */ (p);\n    }\n    if (Array.isArray(p)) {\n        return new Point(+p[0], +p[1]);\n    }\n    if (p.x !== undefined && p.y !== undefined) {\n        return new Point(+p.x, +p.y);\n    }\n    throw new Error('Expected [x, y] or {x, y} point format');\n};\n", "\nexport default function unitBezier(p1x, p1y, p2x, p2y) {\n    // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).\n    const cx = 3 * p1x;\n    const bx = 3 * (p2x - p1x) - cx;\n    const ax = 1 - cx - bx;\n\n    const cy = 3 * p1y;\n    const by = 3 * (p2y - p1y) - cy;\n    const ay = 1 - cy - by;\n\n    return function solve(x, epsilon = 1e-6) {\n        if (x <= 0) return 0;\n        if (x >= 1) return 1;\n\n        let t = x;\n\n        // First try a few iterations of Newton's method - normally very fast.\n        // `ax t^3 + bx t^2 + cx t` expanded using Horner's rule.\n        for (let i = 0; i < 8; i++) {\n            const x2 = ((ax * t + bx) * t + cx) * t - x;\n            if (Math.abs(x2) < epsilon) return ((ay * t + by) * t + cy) * t;\n\n            const d2 = (3 * ax * t + 2 * bx) * t + cx;\n            if (Math.abs(d2) < 1e-6) break;\n\n            t -= x2 / d2;\n        }\n\n        // Fall back to the bisection method for reliability.\n        let t0 = 0;\n        let t1 = 1;\n        t = x;\n\n        for (let i = 0; i < 20; i++) {\n            const x2 = ((ax * t + bx) * t + cx) * t;\n            if (Math.abs(x2 - x) < epsilon) break;\n\n            if (x > x2) t0 = t;\n            else t1 = t;\n\n            t = (t0 + t1) * 0.5;\n        }\n\n        return ((ay * t + by) * t + cy) * t;\n    };\n}\n", "let supportsOffscreenCanvas: boolean;\n\n/**\n * @returns true if the browser can rasterise into an `OffscreenCanvas`, false otherwise.\n *\n * The browser is probed once and the answer cached. The `getContext` result has to be coerced to a\n * boolean for that: it is null when there is no 2d context, and `??=` reads a cached null as\n * \"not probed yet\".\n */\nexport function offscreenCanvasSupported(): boolean {\n    supportsOffscreenCanvas ??= typeof OffscreenCanvas !== 'undefined' &&\n            !!new OffscreenCanvas(1, 1).getContext('2d') &&\n            typeof createImageBitmap === 'function';\n\n    return supportsOffscreenCanvas;\n}\n", "import {offscreenCanvasSupported} from './offscreen_canvas_supported.ts';\n\nlet offscreenCanvasDistorted: boolean;\n\n/**\n * Some browsers don't return the exact pixels from a canvas to prevent user fingerprinting (see #3185).\n * This function writes pixels to an OffscreenCanvas and reads them back using getImageData, returning false\n * if they don't match.\n *\n * @returns true if the browser supports OffscreenCanvas but it distorts getImageData results, false otherwise.\n */\nexport function isOffscreenCanvasDistorted(): boolean {\n    if (offscreenCanvasDistorted == null) {\n        offscreenCanvasDistorted = false;\n        if (offscreenCanvasSupported()) {\n            const size = 5;\n            const canvas = new OffscreenCanvas(size, size);\n            const context = canvas.getContext('2d', {willReadFrequently: true});\n            if (context) {\n                // fill each pixel with an RGB value that should make the byte at index i equal to i (except alpha channel):\n                // [0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255, ...]\n                for (let i = 0; i < size * size; i++) {\n                    const base = i * 4;\n                    context.fillStyle = `rgb(${base},${base + 1},${base + 2})`;\n                    context.fillRect(i % size, Math.floor(i / size), 1, 1);\n                }\n                const data = context.getImageData(0, 0, size, size).data;\n                for (let i = 0; i < size * size * 4; i++) {\n                    if (i % 4 !== 3 && data[i] !== i) {\n                        offscreenCanvasDistorted = true;\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    return offscreenCanvasDistorted || false;\n}\n", "/**\n * Common utilities\n * @module glMatrix\n */\n\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== \"undefined\" ? Float32Array : Array;\nexport var RANDOM = Math.random;\nexport var ANGLE_ORDER = \"zyx\";\n\n/**\n * Symmetric round\n * see https://www.npmjs.com/package/round-half-up-symmetric#user-content-detailed-background\n *\n * @param {Number} a value to round\n */\nexport function round(a) {\n  if (a >= 0) return Math.round(a);\n  return a % 0.5 === 0 ? Math.floor(a) : Math.round(a);\n}\n\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\nexport function setMatrixArrayType(type) {\n  ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\nvar radian = 180 / Math.PI;\n\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\nexport function toRadian(a) {\n  return a * degree;\n}\n\n/**\n * Convert Radian To Degree\n *\n * @param {Number} a Angle in Radians\n */\nexport function toDegree(a) {\n  return a * radian;\n}\n\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a          The first number to test.\n * @param {Number} b          The second number to test.\n * @param {Number} tolerance  Absolute or relative tolerance (default glMatrix.EPSILON)\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\nexport function equals(a, b) {\n  var tolerance = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EPSILON;\n  return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));\n}", "import * as glMatrix from \"./common.js\";\n\n/**\n * 2x2 Matrix\n * @module mat2\n */\n\n/**\n * Creates a new identity mat2\n *\n * @returns {mat2} a new 2x2 matrix\n */\nexport function create() {\n  var out = new glMatrix.ARRAY_TYPE(4);\n  if (glMatrix.ARRAY_TYPE != Float32Array) {\n    out[1] = 0;\n    out[2] = 0;\n  }\n  out[0] = 1;\n  out[3] = 1;\n  return out;\n}\n\n/**\n * Creates a new mat2 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat2} a matrix to clone\n * @returns {mat2} a new 2x2 matrix\n */\nexport function clone(a) {\n  var out = new glMatrix.ARRAY_TYPE(4);\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  return out;\n}\n\n/**\n * Copy the values from one mat2 to another\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2} out\n */\nexport function copy(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  return out;\n}\n\n/**\n * Set a mat2 to the identity matrix\n *\n * @param {mat2} out the receiving matrix\n * @returns {mat2} out\n */\nexport function identity(out) {\n  out[0] = 1;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 1;\n  return out;\n}\n\n/**\n * Create a new mat2 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m10 Component in column 1, row 0 position (index 2)\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\n * @returns {mat2} out A new 2x2 matrix\n */\nexport function fromValues(m00, m01, m10, m11) {\n  var out = new glMatrix.ARRAY_TYPE(4);\n  out[0] = m00;\n  out[1] = m01;\n  out[2] = m10;\n  out[3] = m11;\n  return out;\n}\n\n/**\n * Set the components of a mat2 to the given values\n *\n * @param {mat2} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m10 Component in column 1, row 0 position (index 2)\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\n * @returns {mat2} out\n */\nexport function set(out, m00, m01, m10, m11) {\n  out[0] = m00;\n  out[1] = m01;\n  out[2] = m10;\n  out[3] = m11;\n  return out;\n}\n\n/**\n * Transpose the values of a mat2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2} out\n */\nexport function transpose(out, a) {\n  // If we are transposing ourselves we can skip a few steps but have to cache\n  // some values\n  if (out === a) {\n    var a1 = a[1];\n    out[1] = a[2];\n    out[2] = a1;\n  } else {\n    out[0] = a[0];\n    out[1] = a[2];\n    out[2] = a[1];\n    out[3] = a[3];\n  }\n  return out;\n}\n\n/**\n * Inverts a mat2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2 | null} out, or null if source matrix is not invertible\n */\nexport function invert(out, a) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n\n  // Calculate the determinant\n  var det = a0 * a3 - a2 * a1;\n  if (!det) {\n    return null;\n  }\n  det = 1.0 / det;\n  out[0] = a3 * det;\n  out[1] = -a1 * det;\n  out[2] = -a2 * det;\n  out[3] = a0 * det;\n  return out;\n}\n\n/**\n * Calculates the adjugate of a mat2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the source matrix\n * @returns {mat2} out\n */\nexport function adjoint(out, a) {\n  // Caching this value is necessary if out == a\n  var a0 = a[0];\n  out[0] = a[3];\n  out[1] = -a[1];\n  out[2] = -a[2];\n  out[3] = a0;\n  return out;\n}\n\n/**\n * Calculates the determinant of a mat2\n *\n * @param {ReadonlyMat2} a the source matrix\n * @returns {Number} determinant of a\n */\nexport function determinant(a) {\n  return a[0] * a[3] - a[2] * a[1];\n}\n\n/**\n * Multiplies two mat2's\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @returns {mat2} out\n */\nexport function multiply(out, a, b) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n  var b0 = b[0],\n    b1 = b[1],\n    b2 = b[2],\n    b3 = b[3];\n  out[0] = a0 * b0 + a2 * b1;\n  out[1] = a1 * b0 + a3 * b1;\n  out[2] = a0 * b2 + a2 * b3;\n  out[3] = a1 * b2 + a3 * b3;\n  return out;\n}\n\n/**\n * Rotates a mat2 by the given angle\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat2} out\n */\nexport function rotate(out, a, rad) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n  out[0] = a0 * c + a2 * s;\n  out[1] = a1 * c + a3 * s;\n  out[2] = a0 * -s + a2 * c;\n  out[3] = a1 * -s + a3 * c;\n  return out;\n}\n\n/**\n * Scales the mat2 by the dimensions in the given vec2\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat2} out\n **/\nexport function scale(out, a, v) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n  var v0 = v[0],\n    v1 = v[1];\n  out[0] = a0 * v0;\n  out[1] = a1 * v0;\n  out[2] = a2 * v1;\n  out[3] = a3 * v1;\n  return out;\n}\n\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n *     mat2.identity(dest);\n *     mat2.rotate(dest, dest, rad);\n *\n * @param {mat2} out mat2 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat2} out\n */\nexport function fromRotation(out, rad) {\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n  out[0] = c;\n  out[1] = s;\n  out[2] = -s;\n  out[3] = c;\n  return out;\n}\n\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n *     mat2.identity(dest);\n *     mat2.scale(dest, dest, vec);\n *\n * @param {mat2} out mat2 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat2} out\n */\nexport function fromScaling(out, v) {\n  out[0] = v[0];\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = v[1];\n  return out;\n}\n\n/**\n * Returns a string representation of a mat2\n *\n * @param {ReadonlyMat2} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\nexport function str(a) {\n  return \"mat2(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n\n/**\n * Returns Frobenius norm of a mat2\n *\n * @param {ReadonlyMat2} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\nexport function frob(a) {\n  return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]);\n}\n\n/**\n * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix\n * @param {ReadonlyMat2} L the lower triangular matrix\n * @param {ReadonlyMat2} D the diagonal matrix\n * @param {ReadonlyMat2} U the upper triangular matrix\n * @param {ReadonlyMat2} a the input matrix to factorize\n */\n\nexport function LDU(L, D, U, a) {\n  L[2] = a[2] / a[0];\n  U[0] = a[0];\n  U[1] = a[1];\n  U[3] = a[3] - L[2] * U[1];\n  return [L, D, U];\n}\n\n/**\n * Adds two mat2's\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @returns {mat2} out\n */\nexport function add(out, a, b) {\n  out[0] = a[0] + b[0];\n  out[1] = a[1] + b[1];\n  out[2] = a[2] + b[2];\n  out[3] = a[3] + b[3];\n  return out;\n}\n\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @returns {mat2} out\n */\nexport function subtract(out, a, b) {\n  out[0] = a[0] - b[0];\n  out[1] = a[1] - b[1];\n  out[2] = a[2] - b[2];\n  out[3] = a[3] - b[3];\n  return out;\n}\n\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat2} a The first matrix.\n * @param {ReadonlyMat2} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat2} a The first matrix.\n * @param {ReadonlyMat2} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function equals(a, b) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n  var b0 = b[0],\n    b1 = b[1],\n    b2 = b[2],\n    b3 = b[3];\n  return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat2} out the receiving matrix\n * @param {ReadonlyMat2} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat2} out\n */\nexport function multiplyScalar(out, a, b) {\n  out[0] = a[0] * b;\n  out[1] = a[1] * b;\n  out[2] = a[2] * b;\n  out[3] = a[3] * b;\n  return out;\n}\n\n/**\n * Adds two mat2's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat2} out the receiving vector\n * @param {ReadonlyMat2} a the first operand\n * @param {ReadonlyMat2} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat2} out\n */\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n  out[0] = a[0] + b[0] * scale;\n  out[1] = a[1] + b[1] * scale;\n  out[2] = a[2] + b[2] * scale;\n  out[3] = a[3] + b[3] * scale;\n  return out;\n}\n\n/**\n * Alias for {@link mat2.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link mat2.subtract}\n * @function\n */\nexport var sub = subtract;", "import * as glMatrix from \"./common.js\";\n\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\nexport function create() {\n  var out = new glMatrix.ARRAY_TYPE(9);\n  if (glMatrix.ARRAY_TYPE != Float32Array) {\n    out[1] = 0;\n    out[2] = 0;\n    out[3] = 0;\n    out[5] = 0;\n    out[6] = 0;\n    out[7] = 0;\n  }\n  out[0] = 1;\n  out[4] = 1;\n  out[8] = 1;\n  return out;\n}\n\n/**\n * Copies the upper-left 3x3 values into the given mat3.\n *\n * @param {mat3} out the receiving 3x3 matrix\n * @param {ReadonlyMat4} a   the source 4x4 matrix\n * @returns {mat3} out\n */\nexport function fromMat4(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[4];\n  out[4] = a[5];\n  out[5] = a[6];\n  out[6] = a[8];\n  out[7] = a[9];\n  out[8] = a[10];\n  return out;\n}\n\n/**\n * Creates a new mat3 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat3} a matrix to clone\n * @returns {mat3} a new 3x3 matrix\n */\nexport function clone(a) {\n  var out = new glMatrix.ARRAY_TYPE(9);\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  out[4] = a[4];\n  out[5] = a[5];\n  out[6] = a[6];\n  out[7] = a[7];\n  out[8] = a[8];\n  return out;\n}\n\n/**\n * Copy the values from one mat3 to another\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\nexport function copy(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  out[4] = a[4];\n  out[5] = a[5];\n  out[6] = a[6];\n  out[7] = a[7];\n  out[8] = a[8];\n  return out;\n}\n\n/**\n * Create a new mat3 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} A new mat3\n */\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n  var out = new glMatrix.ARRAY_TYPE(9);\n  out[0] = m00;\n  out[1] = m01;\n  out[2] = m02;\n  out[3] = m10;\n  out[4] = m11;\n  out[5] = m12;\n  out[6] = m20;\n  out[7] = m21;\n  out[8] = m22;\n  return out;\n}\n\n/**\n * Set the components of a mat3 to the given values\n *\n * @param {mat3} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} out\n */\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n  out[0] = m00;\n  out[1] = m01;\n  out[2] = m02;\n  out[3] = m10;\n  out[4] = m11;\n  out[5] = m12;\n  out[6] = m20;\n  out[7] = m21;\n  out[8] = m22;\n  return out;\n}\n\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\nexport function identity(out) {\n  out[0] = 1;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 1;\n  out[5] = 0;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 1;\n  return out;\n}\n\n/**\n * Transpose the values of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\nexport function transpose(out, a) {\n  // If we are transposing ourselves we can skip a few steps but have to cache some values\n  if (out === a) {\n    var a01 = a[1],\n      a02 = a[2],\n      a12 = a[5];\n    out[1] = a[3];\n    out[2] = a[6];\n    out[3] = a01;\n    out[5] = a[7];\n    out[6] = a02;\n    out[7] = a12;\n  } else {\n    out[0] = a[0];\n    out[1] = a[3];\n    out[2] = a[6];\n    out[3] = a[1];\n    out[4] = a[4];\n    out[5] = a[7];\n    out[6] = a[2];\n    out[7] = a[5];\n    out[8] = a[8];\n  }\n  return out;\n}\n\n/**\n * Inverts a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3 | null} out, or null if source matrix is not invertible\n */\nexport function invert(out, a) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2];\n  var a10 = a[3],\n    a11 = a[4],\n    a12 = a[5];\n  var a20 = a[6],\n    a21 = a[7],\n    a22 = a[8];\n  var b01 = a22 * a11 - a12 * a21;\n  var b11 = -a22 * a10 + a12 * a20;\n  var b21 = a21 * a10 - a11 * a20;\n\n  // Calculate the determinant\n  var det = a00 * b01 + a01 * b11 + a02 * b21;\n  if (!det) {\n    return null;\n  }\n  det = 1.0 / det;\n  out[0] = b01 * det;\n  out[1] = (-a22 * a01 + a02 * a21) * det;\n  out[2] = (a12 * a01 - a02 * a11) * det;\n  out[3] = b11 * det;\n  out[4] = (a22 * a00 - a02 * a20) * det;\n  out[5] = (-a12 * a00 + a02 * a10) * det;\n  out[6] = b21 * det;\n  out[7] = (-a21 * a00 + a01 * a20) * det;\n  out[8] = (a11 * a00 - a01 * a10) * det;\n  return out;\n}\n\n/**\n * Calculates the adjugate of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\nexport function adjoint(out, a) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2];\n  var a10 = a[3],\n    a11 = a[4],\n    a12 = a[5];\n  var a20 = a[6],\n    a21 = a[7],\n    a22 = a[8];\n  out[0] = a11 * a22 - a12 * a21;\n  out[1] = a02 * a21 - a01 * a22;\n  out[2] = a01 * a12 - a02 * a11;\n  out[3] = a12 * a20 - a10 * a22;\n  out[4] = a00 * a22 - a02 * a20;\n  out[5] = a02 * a10 - a00 * a12;\n  out[6] = a10 * a21 - a11 * a20;\n  out[7] = a01 * a20 - a00 * a21;\n  out[8] = a00 * a11 - a01 * a10;\n  return out;\n}\n\n/**\n * Calculates the determinant of a mat3\n *\n * @param {ReadonlyMat3} a the source matrix\n * @returns {Number} determinant of a\n */\nexport function determinant(a) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2];\n  var a10 = a[3],\n    a11 = a[4],\n    a12 = a[5];\n  var a20 = a[6],\n    a21 = a[7],\n    a22 = a[8];\n  return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\nexport function multiply(out, a, b) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2];\n  var a10 = a[3],\n    a11 = a[4],\n    a12 = a[5];\n  var a20 = a[6],\n    a21 = a[7],\n    a22 = a[8];\n  var b00 = b[0],\n    b01 = b[1],\n    b02 = b[2];\n  var b10 = b[3],\n    b11 = b[4],\n    b12 = b[5];\n  var b20 = b[6],\n    b21 = b[7],\n    b22 = b[8];\n  out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n  out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n  out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n  out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n  out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n  out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n  out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n  out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n  out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n  return out;\n}\n\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\nexport function translate(out, a, v) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2],\n    a10 = a[3],\n    a11 = a[4],\n    a12 = a[5],\n    a20 = a[6],\n    a21 = a[7],\n    a22 = a[8],\n    x = v[0],\n    y = v[1];\n  out[0] = a00;\n  out[1] = a01;\n  out[2] = a02;\n  out[3] = a10;\n  out[4] = a11;\n  out[5] = a12;\n  out[6] = x * a00 + y * a10 + a20;\n  out[7] = x * a01 + y * a11 + a21;\n  out[8] = x * a02 + y * a12 + a22;\n  return out;\n}\n\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\nexport function rotate(out, a, rad) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2],\n    a10 = a[3],\n    a11 = a[4],\n    a12 = a[5],\n    a20 = a[6],\n    a21 = a[7],\n    a22 = a[8],\n    s = Math.sin(rad),\n    c = Math.cos(rad);\n  out[0] = c * a00 + s * a10;\n  out[1] = c * a01 + s * a11;\n  out[2] = c * a02 + s * a12;\n  out[3] = c * a10 - s * a00;\n  out[4] = c * a11 - s * a01;\n  out[5] = c * a12 - s * a02;\n  out[6] = a20;\n  out[7] = a21;\n  out[8] = a22;\n  return out;\n}\n\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to scale\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\nexport function scale(out, a, v) {\n  var x = v[0],\n    y = v[1];\n  out[0] = x * a[0];\n  out[1] = x * a[1];\n  out[2] = x * a[2];\n  out[3] = y * a[3];\n  out[4] = y * a[4];\n  out[5] = y * a[5];\n  out[6] = a[6];\n  out[7] = a[7];\n  out[8] = a[8];\n  return out;\n}\n\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n *     mat3.identity(dest);\n *     mat3.translate(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Translation vector\n * @returns {mat3} out\n */\nexport function fromTranslation(out, v) {\n  out[0] = 1;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 1;\n  out[5] = 0;\n  out[6] = v[0];\n  out[7] = v[1];\n  out[8] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n *     mat3.identity(dest);\n *     mat3.rotate(dest, dest, rad);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\nexport function fromRotation(out, rad) {\n  var s = Math.sin(rad),\n    c = Math.cos(rad);\n  out[0] = c;\n  out[1] = s;\n  out[2] = 0;\n  out[3] = -s;\n  out[4] = c;\n  out[5] = 0;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n *     mat3.identity(dest);\n *     mat3.scale(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat3} out\n */\nexport function fromScaling(out, v) {\n  out[0] = v[0];\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = v[1];\n  out[5] = 0;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 1;\n  return out;\n}\n\n/**\n * Copies the values from a mat2d into a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat2d} a the matrix to copy\n * @returns {mat3} out\n **/\nexport function fromMat2d(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = 0;\n  out[3] = a[2];\n  out[4] = a[3];\n  out[5] = 0;\n  out[6] = a[4];\n  out[7] = a[5];\n  out[8] = 1;\n  return out;\n}\n\n/**\n * Calculates a 3x3 matrix from the given quaternion\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat3} out\n */\nexport function fromQuat(out, q) {\n  var x = q[0],\n    y = q[1],\n    z = q[2],\n    w = q[3];\n  var x2 = x + x;\n  var y2 = y + y;\n  var z2 = z + z;\n  var xx = x * x2;\n  var yx = y * x2;\n  var yy = y * y2;\n  var zx = z * x2;\n  var zy = z * y2;\n  var zz = z * z2;\n  var wx = w * x2;\n  var wy = w * y2;\n  var wz = w * z2;\n  out[0] = 1 - yy - zz;\n  out[3] = yx - wz;\n  out[6] = zx + wy;\n  out[1] = yx + wz;\n  out[4] = 1 - xx - zz;\n  out[7] = zy - wx;\n  out[2] = zx - wy;\n  out[5] = zy + wx;\n  out[8] = 1 - xx - yy;\n  return out;\n}\n\n/**\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from\n *\n * @returns {mat3} out\n */\nexport function normalFromMat4(out, a) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2],\n    a03 = a[3];\n  var a10 = a[4],\n    a11 = a[5],\n    a12 = a[6],\n    a13 = a[7];\n  var a20 = a[8],\n    a21 = a[9],\n    a22 = a[10],\n    a23 = a[11];\n  var a30 = a[12],\n    a31 = a[13],\n    a32 = a[14],\n    a33 = a[15];\n  var b00 = a00 * a11 - a01 * a10;\n  var b01 = a00 * a12 - a02 * a10;\n  var b02 = a00 * a13 - a03 * a10;\n  var b03 = a01 * a12 - a02 * a11;\n  var b04 = a01 * a13 - a03 * a11;\n  var b05 = a02 * a13 - a03 * a12;\n  var b06 = a20 * a31 - a21 * a30;\n  var b07 = a20 * a32 - a22 * a30;\n  var b08 = a20 * a33 - a23 * a30;\n  var b09 = a21 * a32 - a22 * a31;\n  var b10 = a21 * a33 - a23 * a31;\n  var b11 = a22 * a33 - a23 * a32;\n\n  // Calculate the determinant\n  var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n  if (!det) {\n    return null;\n  }\n  det = 1.0 / det;\n  out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n  out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n  out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n  out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n  out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n  out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n  out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n  out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n  out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n  return out;\n}\n\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\nexport function projection(out, width, height) {\n  out[0] = 2 / width;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = -2 / height;\n  out[5] = 0;\n  out[6] = -1;\n  out[7] = 1;\n  out[8] = 1;\n  return out;\n}\n\n/**\n * Returns a string representation of a mat3\n *\n * @param {ReadonlyMat3} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\nexport function str(a) {\n  return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n\n/**\n * Returns Frobenius norm of a mat3\n *\n * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\nexport function frob(a) {\n  return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * a[5] + a[6] * a[6] + a[7] * a[7] + a[8] * a[8]);\n}\n\n/**\n * Adds two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\nexport function add(out, a, b) {\n  out[0] = a[0] + b[0];\n  out[1] = a[1] + b[1];\n  out[2] = a[2] + b[2];\n  out[3] = a[3] + b[3];\n  out[4] = a[4] + b[4];\n  out[5] = a[5] + b[5];\n  out[6] = a[6] + b[6];\n  out[7] = a[7] + b[7];\n  out[8] = a[8] + b[8];\n  return out;\n}\n\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\nexport function subtract(out, a, b) {\n  out[0] = a[0] - b[0];\n  out[1] = a[1] - b[1];\n  out[2] = a[2] - b[2];\n  out[3] = a[3] - b[3];\n  out[4] = a[4] - b[4];\n  out[5] = a[5] - b[5];\n  out[6] = a[6] - b[6];\n  out[7] = a[7] - b[7];\n  out[8] = a[8] - b[8];\n  return out;\n}\n\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat3} out\n */\nexport function multiplyScalar(out, a, b) {\n  out[0] = a[0] * b;\n  out[1] = a[1] * b;\n  out[2] = a[2] * b;\n  out[3] = a[3] * b;\n  out[4] = a[4] * b;\n  out[5] = a[5] * b;\n  out[6] = a[6] * b;\n  out[7] = a[7] * b;\n  out[8] = a[8] * b;\n  return out;\n}\n\n/**\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat3} out the receiving vector\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat3} out\n */\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n  out[0] = a[0] + b[0] * scale;\n  out[1] = a[1] + b[1] * scale;\n  out[2] = a[2] + b[2] * scale;\n  out[3] = a[3] + b[3] * scale;\n  out[4] = a[4] + b[4] * scale;\n  out[5] = a[5] + b[5] * scale;\n  out[6] = a[6] + b[6] * scale;\n  out[7] = a[7] + b[7] * scale;\n  out[8] = a[8] + b[8] * scale;\n  return out;\n}\n\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function equals(a, b) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3],\n    a4 = a[4],\n    a5 = a[5],\n    a6 = a[6],\n    a7 = a[7],\n    a8 = a[8];\n  var b0 = b[0],\n    b1 = b[1],\n    b2 = b[2],\n    b3 = b[3],\n    b4 = b[4],\n    b5 = b[5],\n    b6 = b[6],\n    b7 = b[7],\n    b8 = b[8];\n  return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n\n/**\n * Alias for {@link mat3.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link mat3.subtract}\n * @function\n */\nexport var sub = subtract;", "import * as glMatrix from \"./common.js\";\n\n/**\n * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\nexport function create() {\n  var out = new glMatrix.ARRAY_TYPE(16);\n  if (glMatrix.ARRAY_TYPE != Float32Array) {\n    out[1] = 0;\n    out[2] = 0;\n    out[3] = 0;\n    out[4] = 0;\n    out[6] = 0;\n    out[7] = 0;\n    out[8] = 0;\n    out[9] = 0;\n    out[11] = 0;\n    out[12] = 0;\n    out[13] = 0;\n    out[14] = 0;\n  }\n  out[0] = 1;\n  out[5] = 1;\n  out[10] = 1;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\nexport function clone(a) {\n  var out = new glMatrix.ARRAY_TYPE(16);\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  out[4] = a[4];\n  out[5] = a[5];\n  out[6] = a[6];\n  out[7] = a[7];\n  out[8] = a[8];\n  out[9] = a[9];\n  out[10] = a[10];\n  out[11] = a[11];\n  out[12] = a[12];\n  out[13] = a[13];\n  out[14] = a[14];\n  out[15] = a[15];\n  return out;\n}\n\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function copy(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  out[4] = a[4];\n  out[5] = a[5];\n  out[6] = a[6];\n  out[7] = a[7];\n  out[8] = a[8];\n  out[9] = a[9];\n  out[10] = a[10];\n  out[11] = a[11];\n  out[12] = a[12];\n  out[13] = a[13];\n  out[14] = a[14];\n  out[15] = a[15];\n  return out;\n}\n\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n  var out = new glMatrix.ARRAY_TYPE(16);\n  out[0] = m00;\n  out[1] = m01;\n  out[2] = m02;\n  out[3] = m03;\n  out[4] = m10;\n  out[5] = m11;\n  out[6] = m12;\n  out[7] = m13;\n  out[8] = m20;\n  out[9] = m21;\n  out[10] = m22;\n  out[11] = m23;\n  out[12] = m30;\n  out[13] = m31;\n  out[14] = m32;\n  out[15] = m33;\n  return out;\n}\n\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n  out[0] = m00;\n  out[1] = m01;\n  out[2] = m02;\n  out[3] = m03;\n  out[4] = m10;\n  out[5] = m11;\n  out[6] = m12;\n  out[7] = m13;\n  out[8] = m20;\n  out[9] = m21;\n  out[10] = m22;\n  out[11] = m23;\n  out[12] = m30;\n  out[13] = m31;\n  out[14] = m32;\n  out[15] = m33;\n  return out;\n}\n\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\nexport function identity(out) {\n  out[0] = 1;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = 1;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[10] = 1;\n  out[11] = 0;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = 0;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function transpose(out, a) {\n  // If we are transposing ourselves we can skip a few steps but have to cache some values\n  if (out === a) {\n    var a01 = a[1],\n      a02 = a[2],\n      a03 = a[3];\n    var a12 = a[6],\n      a13 = a[7];\n    var a23 = a[11];\n    out[1] = a[4];\n    out[2] = a[8];\n    out[3] = a[12];\n    out[4] = a01;\n    out[6] = a[9];\n    out[7] = a[13];\n    out[8] = a02;\n    out[9] = a12;\n    out[11] = a[14];\n    out[12] = a03;\n    out[13] = a13;\n    out[14] = a23;\n  } else {\n    out[0] = a[0];\n    out[1] = a[4];\n    out[2] = a[8];\n    out[3] = a[12];\n    out[4] = a[1];\n    out[5] = a[5];\n    out[6] = a[9];\n    out[7] = a[13];\n    out[8] = a[2];\n    out[9] = a[6];\n    out[10] = a[10];\n    out[11] = a[14];\n    out[12] = a[3];\n    out[13] = a[7];\n    out[14] = a[11];\n    out[15] = a[15];\n  }\n  return out;\n}\n\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4 | null} out, or null if source matrix is not invertible\n */\nexport function invert(out, a) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2],\n    a03 = a[3];\n  var a10 = a[4],\n    a11 = a[5],\n    a12 = a[6],\n    a13 = a[7];\n  var a20 = a[8],\n    a21 = a[9],\n    a22 = a[10],\n    a23 = a[11];\n  var a30 = a[12],\n    a31 = a[13],\n    a32 = a[14],\n    a33 = a[15];\n  var b00 = a00 * a11 - a01 * a10;\n  var b01 = a00 * a12 - a02 * a10;\n  var b02 = a00 * a13 - a03 * a10;\n  var b03 = a01 * a12 - a02 * a11;\n  var b04 = a01 * a13 - a03 * a11;\n  var b05 = a02 * a13 - a03 * a12;\n  var b06 = a20 * a31 - a21 * a30;\n  var b07 = a20 * a32 - a22 * a30;\n  var b08 = a20 * a33 - a23 * a30;\n  var b09 = a21 * a32 - a22 * a31;\n  var b10 = a21 * a33 - a23 * a31;\n  var b11 = a22 * a33 - a23 * a32;\n\n  // Calculate the determinant\n  var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n  if (!det) {\n    return null;\n  }\n  det = 1.0 / det;\n  out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n  out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n  out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n  out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n  out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n  out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n  out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n  out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n  out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n  out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n  out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n  out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n  out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n  out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n  out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n  out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n  return out;\n}\n\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function adjoint(out, a) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2],\n    a03 = a[3];\n  var a10 = a[4],\n    a11 = a[5],\n    a12 = a[6],\n    a13 = a[7];\n  var a20 = a[8],\n    a21 = a[9],\n    a22 = a[10],\n    a23 = a[11];\n  var a30 = a[12],\n    a31 = a[13],\n    a32 = a[14],\n    a33 = a[15];\n  var b00 = a00 * a11 - a01 * a10;\n  var b01 = a00 * a12 - a02 * a10;\n  var b02 = a00 * a13 - a03 * a10;\n  var b03 = a01 * a12 - a02 * a11;\n  var b04 = a01 * a13 - a03 * a11;\n  var b05 = a02 * a13 - a03 * a12;\n  var b06 = a20 * a31 - a21 * a30;\n  var b07 = a20 * a32 - a22 * a30;\n  var b08 = a20 * a33 - a23 * a30;\n  var b09 = a21 * a32 - a22 * a31;\n  var b10 = a21 * a33 - a23 * a31;\n  var b11 = a22 * a33 - a23 * a32;\n  out[0] = a11 * b11 - a12 * b10 + a13 * b09;\n  out[1] = a02 * b10 - a01 * b11 - a03 * b09;\n  out[2] = a31 * b05 - a32 * b04 + a33 * b03;\n  out[3] = a22 * b04 - a21 * b05 - a23 * b03;\n  out[4] = a12 * b08 - a10 * b11 - a13 * b07;\n  out[5] = a00 * b11 - a02 * b08 + a03 * b07;\n  out[6] = a32 * b02 - a30 * b05 - a33 * b01;\n  out[7] = a20 * b05 - a22 * b02 + a23 * b01;\n  out[8] = a10 * b10 - a11 * b08 + a13 * b06;\n  out[9] = a01 * b08 - a00 * b10 - a03 * b06;\n  out[10] = a30 * b04 - a31 * b02 + a33 * b00;\n  out[11] = a21 * b02 - a20 * b04 - a23 * b00;\n  out[12] = a11 * b07 - a10 * b09 - a12 * b06;\n  out[13] = a00 * b09 - a01 * b07 + a02 * b06;\n  out[14] = a31 * b01 - a30 * b03 - a32 * b00;\n  out[15] = a20 * b03 - a21 * b01 + a22 * b00;\n  return out;\n}\n\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\nexport function determinant(a) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2],\n    a03 = a[3];\n  var a10 = a[4],\n    a11 = a[5],\n    a12 = a[6],\n    a13 = a[7];\n  var a20 = a[8],\n    a21 = a[9],\n    a22 = a[10],\n    a23 = a[11];\n  var a30 = a[12],\n    a31 = a[13],\n    a32 = a[14],\n    a33 = a[15];\n  var b0 = a00 * a11 - a01 * a10;\n  var b1 = a00 * a12 - a02 * a10;\n  var b2 = a01 * a12 - a02 * a11;\n  var b3 = a20 * a31 - a21 * a30;\n  var b4 = a20 * a32 - a22 * a30;\n  var b5 = a21 * a32 - a22 * a31;\n  var b6 = a00 * b5 - a01 * b4 + a02 * b3;\n  var b7 = a10 * b5 - a11 * b4 + a12 * b3;\n  var b8 = a20 * b2 - a21 * b1 + a22 * b0;\n  var b9 = a30 * b2 - a31 * b1 + a32 * b0;\n\n  // Calculate the determinant\n  return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9;\n}\n\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function multiply(out, a, b) {\n  var a00 = a[0],\n    a01 = a[1],\n    a02 = a[2],\n    a03 = a[3];\n  var a10 = a[4],\n    a11 = a[5],\n    a12 = a[6],\n    a13 = a[7];\n  var a20 = a[8],\n    a21 = a[9],\n    a22 = a[10],\n    a23 = a[11];\n  var a30 = a[12],\n    a31 = a[13],\n    a32 = a[14],\n    a33 = a[15];\n\n  // Cache only the current line of the second matrix\n  var b0 = b[0],\n    b1 = b[1],\n    b2 = b[2],\n    b3 = b[3];\n  out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n  out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n  out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n  out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n  b0 = b[4];\n  b1 = b[5];\n  b2 = b[6];\n  b3 = b[7];\n  out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n  out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n  out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n  out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n  b0 = b[8];\n  b1 = b[9];\n  b2 = b[10];\n  b3 = b[11];\n  out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n  out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n  out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n  out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n  b0 = b[12];\n  b1 = b[13];\n  b2 = b[14];\n  b3 = b[15];\n  out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n  out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n  out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n  out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n  return out;\n}\n\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\nexport function translate(out, a, v) {\n  var x = v[0],\n    y = v[1],\n    z = v[2];\n  var a00, a01, a02, a03;\n  var a10, a11, a12, a13;\n  var a20, a21, a22, a23;\n  if (a === out) {\n    out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n    out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n    out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n    out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n  } else {\n    a00 = a[0];\n    a01 = a[1];\n    a02 = a[2];\n    a03 = a[3];\n    a10 = a[4];\n    a11 = a[5];\n    a12 = a[6];\n    a13 = a[7];\n    a20 = a[8];\n    a21 = a[9];\n    a22 = a[10];\n    a23 = a[11];\n    out[0] = a00;\n    out[1] = a01;\n    out[2] = a02;\n    out[3] = a03;\n    out[4] = a10;\n    out[5] = a11;\n    out[6] = a12;\n    out[7] = a13;\n    out[8] = a20;\n    out[9] = a21;\n    out[10] = a22;\n    out[11] = a23;\n    out[12] = a00 * x + a10 * y + a20 * z + a[12];\n    out[13] = a01 * x + a11 * y + a21 * z + a[13];\n    out[14] = a02 * x + a12 * y + a22 * z + a[14];\n    out[15] = a03 * x + a13 * y + a23 * z + a[15];\n  }\n  return out;\n}\n\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\nexport function scale(out, a, v) {\n  var x = v[0],\n    y = v[1],\n    z = v[2];\n  out[0] = a[0] * x;\n  out[1] = a[1] * x;\n  out[2] = a[2] * x;\n  out[3] = a[3] * x;\n  out[4] = a[4] * y;\n  out[5] = a[5] * y;\n  out[6] = a[6] * y;\n  out[7] = a[7] * y;\n  out[8] = a[8] * z;\n  out[9] = a[9] * z;\n  out[10] = a[10] * z;\n  out[11] = a[11] * z;\n  out[12] = a[12];\n  out[13] = a[13];\n  out[14] = a[14];\n  out[15] = a[15];\n  return out;\n}\n\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function rotate(out, a, rad, axis) {\n  var x = axis[0],\n    y = axis[1],\n    z = axis[2];\n  var len = Math.sqrt(x * x + y * y + z * z);\n  var s, c, t;\n  var a00, a01, a02, a03;\n  var a10, a11, a12, a13;\n  var a20, a21, a22, a23;\n  var b00, b01, b02;\n  var b10, b11, b12;\n  var b20, b21, b22;\n  if (len < glMatrix.EPSILON) {\n    return null;\n  }\n  len = 1 / len;\n  x *= len;\n  y *= len;\n  z *= len;\n  s = Math.sin(rad);\n  c = Math.cos(rad);\n  t = 1 - c;\n  a00 = a[0];\n  a01 = a[1];\n  a02 = a[2];\n  a03 = a[3];\n  a10 = a[4];\n  a11 = a[5];\n  a12 = a[6];\n  a13 = a[7];\n  a20 = a[8];\n  a21 = a[9];\n  a22 = a[10];\n  a23 = a[11];\n\n  // Construct the elements of the rotation matrix\n  b00 = x * x * t + c;\n  b01 = y * x * t + z * s;\n  b02 = z * x * t - y * s;\n  b10 = x * y * t - z * s;\n  b11 = y * y * t + c;\n  b12 = z * y * t + x * s;\n  b20 = x * z * t + y * s;\n  b21 = y * z * t - x * s;\n  b22 = z * z * t + c;\n\n  // Perform rotation-specific matrix multiplication\n  out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n  out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n  out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n  out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n  out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n  out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n  out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n  out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n  out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n  out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n  out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n  out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n  if (a !== out) {\n    // If the source and destination differ, copy the unchanged last row\n    out[12] = a[12];\n    out[13] = a[13];\n    out[14] = a[14];\n    out[15] = a[15];\n  }\n  return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateX(out, a, rad) {\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n  var a10 = a[4];\n  var a11 = a[5];\n  var a12 = a[6];\n  var a13 = a[7];\n  var a20 = a[8];\n  var a21 = a[9];\n  var a22 = a[10];\n  var a23 = a[11];\n  if (a !== out) {\n    // If the source and destination differ, copy the unchanged rows\n    out[0] = a[0];\n    out[1] = a[1];\n    out[2] = a[2];\n    out[3] = a[3];\n    out[12] = a[12];\n    out[13] = a[13];\n    out[14] = a[14];\n    out[15] = a[15];\n  }\n\n  // Perform axis-specific matrix multiplication\n  out[4] = a10 * c + a20 * s;\n  out[5] = a11 * c + a21 * s;\n  out[6] = a12 * c + a22 * s;\n  out[7] = a13 * c + a23 * s;\n  out[8] = a20 * c - a10 * s;\n  out[9] = a21 * c - a11 * s;\n  out[10] = a22 * c - a12 * s;\n  out[11] = a23 * c - a13 * s;\n  return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateY(out, a, rad) {\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n  var a00 = a[0];\n  var a01 = a[1];\n  var a02 = a[2];\n  var a03 = a[3];\n  var a20 = a[8];\n  var a21 = a[9];\n  var a22 = a[10];\n  var a23 = a[11];\n  if (a !== out) {\n    // If the source and destination differ, copy the unchanged rows\n    out[4] = a[4];\n    out[5] = a[5];\n    out[6] = a[6];\n    out[7] = a[7];\n    out[12] = a[12];\n    out[13] = a[13];\n    out[14] = a[14];\n    out[15] = a[15];\n  }\n\n  // Perform axis-specific matrix multiplication\n  out[0] = a00 * c - a20 * s;\n  out[1] = a01 * c - a21 * s;\n  out[2] = a02 * c - a22 * s;\n  out[3] = a03 * c - a23 * s;\n  out[8] = a00 * s + a20 * c;\n  out[9] = a01 * s + a21 * c;\n  out[10] = a02 * s + a22 * c;\n  out[11] = a03 * s + a23 * c;\n  return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateZ(out, a, rad) {\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n  var a00 = a[0];\n  var a01 = a[1];\n  var a02 = a[2];\n  var a03 = a[3];\n  var a10 = a[4];\n  var a11 = a[5];\n  var a12 = a[6];\n  var a13 = a[7];\n  if (a !== out) {\n    // If the source and destination differ, copy the unchanged last row\n    out[8] = a[8];\n    out[9] = a[9];\n    out[10] = a[10];\n    out[11] = a[11];\n    out[12] = a[12];\n    out[13] = a[13];\n    out[14] = a[14];\n    out[15] = a[15];\n  }\n\n  // Perform axis-specific matrix multiplication\n  out[0] = a00 * c + a10 * s;\n  out[1] = a01 * c + a11 * s;\n  out[2] = a02 * c + a12 * s;\n  out[3] = a03 * c + a13 * s;\n  out[4] = a10 * c - a00 * s;\n  out[5] = a11 * c - a01 * s;\n  out[6] = a12 * c - a02 * s;\n  out[7] = a13 * c - a03 * s;\n  return out;\n}\n\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromTranslation(out, v) {\n  out[0] = 1;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = 1;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[10] = 1;\n  out[11] = 0;\n  out[12] = v[0];\n  out[13] = v[1];\n  out[14] = v[2];\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\nexport function fromScaling(out, v) {\n  out[0] = v[0];\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = v[1];\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[10] = v[2];\n  out[11] = 0;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = 0;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function fromRotation(out, rad, axis) {\n  var x = axis[0],\n    y = axis[1],\n    z = axis[2];\n  var len = Math.sqrt(x * x + y * y + z * z);\n  var s, c, t;\n  if (len < glMatrix.EPSILON) {\n    return null;\n  }\n  len = 1 / len;\n  x *= len;\n  y *= len;\n  z *= len;\n  s = Math.sin(rad);\n  c = Math.cos(rad);\n  t = 1 - c;\n\n  // Perform rotation-specific matrix multiplication\n  out[0] = x * x * t + c;\n  out[1] = y * x * t + z * s;\n  out[2] = z * x * t - y * s;\n  out[3] = 0;\n  out[4] = x * y * t - z * s;\n  out[5] = y * y * t + c;\n  out[6] = z * y * t + x * s;\n  out[7] = 0;\n  out[8] = x * z * t + y * s;\n  out[9] = y * z * t - x * s;\n  out[10] = z * z * t + c;\n  out[11] = 0;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = 0;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromXRotation(out, rad) {\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n\n  // Perform axis-specific matrix multiplication\n  out[0] = 1;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = c;\n  out[6] = s;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = -s;\n  out[10] = c;\n  out[11] = 0;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = 0;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromYRotation(out, rad) {\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n\n  // Perform axis-specific matrix multiplication\n  out[0] = c;\n  out[1] = 0;\n  out[2] = -s;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = 1;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = s;\n  out[9] = 0;\n  out[10] = c;\n  out[11] = 0;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = 0;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromZRotation(out, rad) {\n  var s = Math.sin(rad);\n  var c = Math.cos(rad);\n\n  // Perform axis-specific matrix multiplication\n  out[0] = c;\n  out[1] = s;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = -s;\n  out[5] = c;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[10] = 1;\n  out[11] = 0;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = 0;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.translate(dest, dest, vec);\n *     let quatMat = mat4.create();\n *     mat4.fromQuat(quatMat, quat);\n *     mat4.multiply(dest, dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslation(out, q, v) {\n  // Quaternion math\n  var x = q[0],\n    y = q[1],\n    z = q[2],\n    w = q[3];\n  var x2 = x + x;\n  var y2 = y + y;\n  var z2 = z + z;\n  var xx = x * x2;\n  var xy = x * y2;\n  var xz = x * z2;\n  var yy = y * y2;\n  var yz = y * z2;\n  var zz = z * z2;\n  var wx = w * x2;\n  var wy = w * y2;\n  var wz = w * z2;\n  out[0] = 1 - (yy + zz);\n  out[1] = xy + wz;\n  out[2] = xz - wy;\n  out[3] = 0;\n  out[4] = xy - wz;\n  out[5] = 1 - (xx + zz);\n  out[6] = yz + wx;\n  out[7] = 0;\n  out[8] = xz + wy;\n  out[9] = yz - wx;\n  out[10] = 1 - (xx + yy);\n  out[11] = 0;\n  out[12] = v[0];\n  out[13] = v[1];\n  out[14] = v[2];\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\nexport function fromQuat2(out, a) {\n  var translation = new glMatrix.ARRAY_TYPE(3);\n  var bx = -a[0],\n    by = -a[1],\n    bz = -a[2],\n    bw = a[3],\n    ax = a[4],\n    ay = a[5],\n    az = a[6],\n    aw = a[7];\n  var magnitude = bx * bx + by * by + bz * bz + bw * bw;\n  //Only scale if it makes sense\n  if (magnitude > 0) {\n    translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n    translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n    translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n  } else {\n    translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n    translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n    translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n  }\n  fromRotationTranslation(out, a, translation);\n  return out;\n}\n\n/**\n * Returns the translation vector component of a transformation\n *  matrix. If a matrix is built with fromRotationTranslation,\n *  the returned vector will be the same as the translation vector\n *  originally supplied.\n * @param  {vec3} out Vector to receive translation component\n * @param  {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getTranslation(out, mat) {\n  out[0] = mat[12];\n  out[1] = mat[13];\n  out[2] = mat[14];\n  return out;\n}\n\n/**\n * Returns the scaling factor component of a transformation\n *  matrix. If a matrix is built with fromRotationTranslationScale\n *  with a normalized Quaternion parameter, the returned vector will be\n *  the same as the scaling vector\n *  originally supplied.\n * @param  {vec3} out Vector to receive scaling factor component\n * @param  {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getScaling(out, mat) {\n  var m11 = mat[0];\n  var m12 = mat[1];\n  var m13 = mat[2];\n  var m21 = mat[4];\n  var m22 = mat[5];\n  var m23 = mat[6];\n  var m31 = mat[8];\n  var m32 = mat[9];\n  var m33 = mat[10];\n  out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n  out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n  out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n  return out;\n}\n\n/**\n * Returns a quaternion representing the rotational component\n *  of a transformation matrix. If a matrix is built with\n *  fromRotationTranslation, the returned quaternion will be the\n *  same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\nexport function getRotation(out, mat) {\n  var scaling = new glMatrix.ARRAY_TYPE(3);\n  getScaling(scaling, mat);\n  var is1 = 1 / scaling[0];\n  var is2 = 1 / scaling[1];\n  var is3 = 1 / scaling[2];\n  var sm11 = mat[0] * is1;\n  var sm12 = mat[1] * is2;\n  var sm13 = mat[2] * is3;\n  var sm21 = mat[4] * is1;\n  var sm22 = mat[5] * is2;\n  var sm23 = mat[6] * is3;\n  var sm31 = mat[8] * is1;\n  var sm32 = mat[9] * is2;\n  var sm33 = mat[10] * is3;\n  var trace = sm11 + sm22 + sm33;\n  var S = 0;\n  if (trace > 0) {\n    S = Math.sqrt(trace + 1.0) * 2;\n    out[3] = 0.25 * S;\n    out[0] = (sm23 - sm32) / S;\n    out[1] = (sm31 - sm13) / S;\n    out[2] = (sm12 - sm21) / S;\n  } else if (sm11 > sm22 && sm11 > sm33) {\n    S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n    out[3] = (sm23 - sm32) / S;\n    out[0] = 0.25 * S;\n    out[1] = (sm12 + sm21) / S;\n    out[2] = (sm31 + sm13) / S;\n  } else if (sm22 > sm33) {\n    S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n    out[3] = (sm31 - sm13) / S;\n    out[0] = (sm12 + sm21) / S;\n    out[1] = 0.25 * S;\n    out[2] = (sm23 + sm32) / S;\n  } else {\n    S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n    out[3] = (sm12 - sm21) / S;\n    out[0] = (sm31 + sm13) / S;\n    out[1] = (sm23 + sm32) / S;\n    out[2] = 0.25 * S;\n  }\n  return out;\n}\n\n/**\n * Decomposes a transformation matrix into its rotation, translation\n * and scale components. Returns only the rotation component\n * @param  {quat} out_r Quaternion to receive the rotation component\n * @param  {vec3} out_t Vector to receive the translation vector\n * @param  {vec3} out_s Vector to receive the scaling factor\n * @param  {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @returns {quat} out_r\n */\nexport function decompose(out_r, out_t, out_s, mat) {\n  out_t[0] = mat[12];\n  out_t[1] = mat[13];\n  out_t[2] = mat[14];\n  var m11 = mat[0];\n  var m12 = mat[1];\n  var m13 = mat[2];\n  var m21 = mat[4];\n  var m22 = mat[5];\n  var m23 = mat[6];\n  var m31 = mat[8];\n  var m32 = mat[9];\n  var m33 = mat[10];\n  out_s[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n  out_s[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n  out_s[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n  var is1 = 1 / out_s[0];\n  var is2 = 1 / out_s[1];\n  var is3 = 1 / out_s[2];\n  var sm11 = m11 * is1;\n  var sm12 = m12 * is2;\n  var sm13 = m13 * is3;\n  var sm21 = m21 * is1;\n  var sm22 = m22 * is2;\n  var sm23 = m23 * is3;\n  var sm31 = m31 * is1;\n  var sm32 = m32 * is2;\n  var sm33 = m33 * is3;\n  var trace = sm11 + sm22 + sm33;\n  var S = 0;\n  if (trace > 0) {\n    S = Math.sqrt(trace + 1.0) * 2;\n    out_r[3] = 0.25 * S;\n    out_r[0] = (sm23 - sm32) / S;\n    out_r[1] = (sm31 - sm13) / S;\n    out_r[2] = (sm12 - sm21) / S;\n  } else if (sm11 > sm22 && sm11 > sm33) {\n    S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n    out_r[3] = (sm23 - sm32) / S;\n    out_r[0] = 0.25 * S;\n    out_r[1] = (sm12 + sm21) / S;\n    out_r[2] = (sm31 + sm13) / S;\n  } else if (sm22 > sm33) {\n    S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n    out_r[3] = (sm31 - sm13) / S;\n    out_r[0] = (sm12 + sm21) / S;\n    out_r[1] = 0.25 * S;\n    out_r[2] = (sm23 + sm32) / S;\n  } else {\n    S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n    out_r[3] = (sm12 - sm21) / S;\n    out_r[0] = (sm31 + sm13) / S;\n    out_r[1] = (sm23 + sm32) / S;\n    out_r[2] = 0.25 * S;\n  }\n  return out_r;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.translate(dest, dest, vec);\n *     let quatMat = mat4.create();\n *     mat4.fromQuat(quatMat, quat);\n *     mat4.multiply(dest, dest, quatMat);\n *     mat4.scale(dest, dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScale(out, q, v, s) {\n  // Quaternion math\n  var x = q[0],\n    y = q[1],\n    z = q[2],\n    w = q[3];\n  var x2 = x + x;\n  var y2 = y + y;\n  var z2 = z + z;\n  var xx = x * x2;\n  var xy = x * y2;\n  var xz = x * z2;\n  var yy = y * y2;\n  var yz = y * z2;\n  var zz = z * z2;\n  var wx = w * x2;\n  var wy = w * y2;\n  var wz = w * z2;\n  var sx = s[0];\n  var sy = s[1];\n  var sz = s[2];\n  out[0] = (1 - (yy + zz)) * sx;\n  out[1] = (xy + wz) * sx;\n  out[2] = (xz - wy) * sx;\n  out[3] = 0;\n  out[4] = (xy - wz) * sy;\n  out[5] = (1 - (xx + zz)) * sy;\n  out[6] = (yz + wx) * sy;\n  out[7] = 0;\n  out[8] = (xz + wy) * sz;\n  out[9] = (yz - wx) * sz;\n  out[10] = (1 - (xx + yy)) * sz;\n  out[11] = 0;\n  out[12] = v[0];\n  out[13] = v[1];\n  out[14] = v[2];\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n *     mat4.identity(dest);\n *     mat4.translate(dest, dest, vec);\n *     mat4.translate(dest, dest, origin);\n *     let quatMat = mat4.create();\n *     mat4.fromQuat(quatMat, quat);\n *     mat4.multiply(dest, dest, quatMat);\n *     mat4.scale(dest, dest, scale)\n *     mat4.translate(dest, dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n  // Quaternion math\n  var x = q[0],\n    y = q[1],\n    z = q[2],\n    w = q[3];\n  var x2 = x + x;\n  var y2 = y + y;\n  var z2 = z + z;\n  var xx = x * x2;\n  var xy = x * y2;\n  var xz = x * z2;\n  var yy = y * y2;\n  var yz = y * z2;\n  var zz = z * z2;\n  var wx = w * x2;\n  var wy = w * y2;\n  var wz = w * z2;\n  var sx = s[0];\n  var sy = s[1];\n  var sz = s[2];\n  var ox = o[0];\n  var oy = o[1];\n  var oz = o[2];\n  var out0 = (1 - (yy + zz)) * sx;\n  var out1 = (xy + wz) * sx;\n  var out2 = (xz - wy) * sx;\n  var out4 = (xy - wz) * sy;\n  var out5 = (1 - (xx + zz)) * sy;\n  var out6 = (yz + wx) * sy;\n  var out8 = (xz + wy) * sz;\n  var out9 = (yz - wx) * sz;\n  var out10 = (1 - (xx + yy)) * sz;\n  out[0] = out0;\n  out[1] = out1;\n  out[2] = out2;\n  out[3] = 0;\n  out[4] = out4;\n  out[5] = out5;\n  out[6] = out6;\n  out[7] = 0;\n  out[8] = out8;\n  out[9] = out9;\n  out[10] = out10;\n  out[11] = 0;\n  out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n  out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n  out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\nexport function fromQuat(out, q) {\n  var x = q[0],\n    y = q[1],\n    z = q[2],\n    w = q[3];\n  var x2 = x + x;\n  var y2 = y + y;\n  var z2 = z + z;\n  var xx = x * x2;\n  var yx = y * x2;\n  var yy = y * y2;\n  var zx = z * x2;\n  var zy = z * y2;\n  var zz = z * z2;\n  var wx = w * x2;\n  var wy = w * y2;\n  var wz = w * z2;\n  out[0] = 1 - yy - zz;\n  out[1] = yx + wz;\n  out[2] = zx - wy;\n  out[3] = 0;\n  out[4] = yx - wz;\n  out[5] = 1 - xx - zz;\n  out[6] = zy + wx;\n  out[7] = 0;\n  out[8] = zx + wy;\n  out[9] = zy - wx;\n  out[10] = 1 - xx - yy;\n  out[11] = 0;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = 0;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function frustum(out, left, right, bottom, top, near, far) {\n  var rl = 1 / (right - left);\n  var tb = 1 / (top - bottom);\n  var nf = 1 / (near - far);\n  out[0] = near * 2 * rl;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = near * 2 * tb;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = (right + left) * rl;\n  out[9] = (top + bottom) * tb;\n  out[10] = (far + near) * nf;\n  out[11] = -1;\n  out[12] = 0;\n  out[13] = 0;\n  out[14] = far * near * 2 * nf;\n  out[15] = 0;\n  return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n  var f = 1.0 / Math.tan(fovy / 2);\n  out[0] = f / aspect;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = f;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[11] = -1;\n  out[12] = 0;\n  out[13] = 0;\n  out[15] = 0;\n  if (far != null && far !== Infinity) {\n    var nf = 1 / (near - far);\n    out[10] = (far + near) * nf;\n    out[14] = 2 * far * near * nf;\n  } else {\n    out[10] = -1;\n    out[14] = -2 * near;\n  }\n  return out;\n}\n\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\nexport var perspective = perspectiveNO;\n\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n  var f = 1.0 / Math.tan(fovy / 2);\n  out[0] = f / aspect;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = f;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[11] = -1;\n  out[12] = 0;\n  out[13] = 0;\n  out[15] = 0;\n  if (far != null && far !== Infinity) {\n    var nf = 1 / (near - far);\n    out[10] = far * nf;\n    out[14] = far * near * nf;\n  } else {\n    out[10] = -1;\n    out[14] = -near;\n  }\n  return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n  var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n  var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n  var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n  var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n  var xScale = 2.0 / (leftTan + rightTan);\n  var yScale = 2.0 / (upTan + downTan);\n  out[0] = xScale;\n  out[1] = 0.0;\n  out[2] = 0.0;\n  out[3] = 0.0;\n  out[4] = 0.0;\n  out[5] = yScale;\n  out[6] = 0.0;\n  out[7] = 0.0;\n  out[8] = -((leftTan - rightTan) * xScale * 0.5);\n  out[9] = (upTan - downTan) * yScale * 0.5;\n  out[10] = far / (near - far);\n  out[11] = -1.0;\n  out[12] = 0.0;\n  out[13] = 0.0;\n  out[14] = far * near / (near - far);\n  out[15] = 0.0;\n  return out;\n}\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n  var lr = 1 / (left - right);\n  var bt = 1 / (bottom - top);\n  var nf = 1 / (near - far);\n  out[0] = -2 * lr;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = -2 * bt;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[10] = 2 * nf;\n  out[11] = 0;\n  out[12] = (left + right) * lr;\n  out[13] = (top + bottom) * bt;\n  out[14] = (far + near) * nf;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\nexport var ortho = orthoNO;\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n  var lr = 1 / (left - right);\n  var bt = 1 / (bottom - top);\n  var nf = 1 / (near - far);\n  out[0] = -2 * lr;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 0;\n  out[5] = -2 * bt;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 0;\n  out[9] = 0;\n  out[10] = nf;\n  out[11] = 0;\n  out[12] = (left + right) * lr;\n  out[13] = (top + bottom) * bt;\n  out[14] = near * nf;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function lookAt(out, eye, center, up) {\n  var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n  var eyex = eye[0];\n  var eyey = eye[1];\n  var eyez = eye[2];\n  var upx = up[0];\n  var upy = up[1];\n  var upz = up[2];\n  var centerx = center[0];\n  var centery = center[1];\n  var centerz = center[2];\n  if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n    return identity(out);\n  }\n  z0 = eyex - centerx;\n  z1 = eyey - centery;\n  z2 = eyez - centerz;\n  len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);\n  z0 *= len;\n  z1 *= len;\n  z2 *= len;\n  x0 = upy * z2 - upz * z1;\n  x1 = upz * z0 - upx * z2;\n  x2 = upx * z1 - upy * z0;\n  len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);\n  if (!len) {\n    x0 = 0;\n    x1 = 0;\n    x2 = 0;\n  } else {\n    len = 1 / len;\n    x0 *= len;\n    x1 *= len;\n    x2 *= len;\n  }\n  y0 = z1 * x2 - z2 * x1;\n  y1 = z2 * x0 - z0 * x2;\n  y2 = z0 * x1 - z1 * x0;\n  len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);\n  if (!len) {\n    y0 = 0;\n    y1 = 0;\n    y2 = 0;\n  } else {\n    len = 1 / len;\n    y0 *= len;\n    y1 *= len;\n    y2 *= len;\n  }\n  out[0] = x0;\n  out[1] = y0;\n  out[2] = z0;\n  out[3] = 0;\n  out[4] = x1;\n  out[5] = y1;\n  out[6] = z1;\n  out[7] = 0;\n  out[8] = x2;\n  out[9] = y2;\n  out[10] = z2;\n  out[11] = 0;\n  out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n  out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n  out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} target Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function targetTo(out, eye, target, up) {\n  var eyex = eye[0],\n    eyey = eye[1],\n    eyez = eye[2],\n    upx = up[0],\n    upy = up[1],\n    upz = up[2];\n  var z0 = eyex - target[0],\n    z1 = eyey - target[1],\n    z2 = eyez - target[2];\n  var len = z0 * z0 + z1 * z1 + z2 * z2;\n  if (len > 0) {\n    len = 1 / Math.sqrt(len);\n    z0 *= len;\n    z1 *= len;\n    z2 *= len;\n  }\n  var x0 = upy * z2 - upz * z1,\n    x1 = upz * z0 - upx * z2,\n    x2 = upx * z1 - upy * z0;\n  len = x0 * x0 + x1 * x1 + x2 * x2;\n  if (len > 0) {\n    len = 1 / Math.sqrt(len);\n    x0 *= len;\n    x1 *= len;\n    x2 *= len;\n  }\n  out[0] = x0;\n  out[1] = x1;\n  out[2] = x2;\n  out[3] = 0;\n  out[4] = z1 * x2 - z2 * x1;\n  out[5] = z2 * x0 - z0 * x2;\n  out[6] = z0 * x1 - z1 * x0;\n  out[7] = 0;\n  out[8] = z0;\n  out[9] = z1;\n  out[10] = z2;\n  out[11] = 0;\n  out[12] = eyex;\n  out[13] = eyey;\n  out[14] = eyez;\n  out[15] = 1;\n  return out;\n}\n\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\nexport function str(a) {\n  return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\nexport function frob(a) {\n  return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * a[5] + a[6] * a[6] + a[7] * a[7] + a[8] * a[8] + a[9] * a[9] + a[10] * a[10] + a[11] * a[11] + a[12] * a[12] + a[13] * a[13] + a[14] * a[14] + a[15] * a[15]);\n}\n\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function add(out, a, b) {\n  out[0] = a[0] + b[0];\n  out[1] = a[1] + b[1];\n  out[2] = a[2] + b[2];\n  out[3] = a[3] + b[3];\n  out[4] = a[4] + b[4];\n  out[5] = a[5] + b[5];\n  out[6] = a[6] + b[6];\n  out[7] = a[7] + b[7];\n  out[8] = a[8] + b[8];\n  out[9] = a[9] + b[9];\n  out[10] = a[10] + b[10];\n  out[11] = a[11] + b[11];\n  out[12] = a[12] + b[12];\n  out[13] = a[13] + b[13];\n  out[14] = a[14] + b[14];\n  out[15] = a[15] + b[15];\n  return out;\n}\n\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function subtract(out, a, b) {\n  out[0] = a[0] - b[0];\n  out[1] = a[1] - b[1];\n  out[2] = a[2] - b[2];\n  out[3] = a[3] - b[3];\n  out[4] = a[4] - b[4];\n  out[5] = a[5] - b[5];\n  out[6] = a[6] - b[6];\n  out[7] = a[7] - b[7];\n  out[8] = a[8] - b[8];\n  out[9] = a[9] - b[9];\n  out[10] = a[10] - b[10];\n  out[11] = a[11] - b[11];\n  out[12] = a[12] - b[12];\n  out[13] = a[13] - b[13];\n  out[14] = a[14] - b[14];\n  out[15] = a[15] - b[15];\n  return out;\n}\n\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\nexport function multiplyScalar(out, a, b) {\n  out[0] = a[0] * b;\n  out[1] = a[1] * b;\n  out[2] = a[2] * b;\n  out[3] = a[3] * b;\n  out[4] = a[4] * b;\n  out[5] = a[5] * b;\n  out[6] = a[6] * b;\n  out[7] = a[7] * b;\n  out[8] = a[8] * b;\n  out[9] = a[9] * b;\n  out[10] = a[10] * b;\n  out[11] = a[11] * b;\n  out[12] = a[12] * b;\n  out[13] = a[13] * b;\n  out[14] = a[14] * b;\n  out[15] = a[15] * b;\n  return out;\n}\n\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n  out[0] = a[0] + b[0] * scale;\n  out[1] = a[1] + b[1] * scale;\n  out[2] = a[2] + b[2] * scale;\n  out[3] = a[3] + b[3] * scale;\n  out[4] = a[4] + b[4] * scale;\n  out[5] = a[5] + b[5] * scale;\n  out[6] = a[6] + b[6] * scale;\n  out[7] = a[7] + b[7] * scale;\n  out[8] = a[8] + b[8] * scale;\n  out[9] = a[9] + b[9] * scale;\n  out[10] = a[10] + b[10] * scale;\n  out[11] = a[11] + b[11] * scale;\n  out[12] = a[12] + b[12] * scale;\n  out[13] = a[13] + b[13] * scale;\n  out[14] = a[14] + b[14] * scale;\n  out[15] = a[15] + b[15] * scale;\n  return out;\n}\n\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function equals(a, b) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n  var a4 = a[4],\n    a5 = a[5],\n    a6 = a[6],\n    a7 = a[7];\n  var a8 = a[8],\n    a9 = a[9],\n    a10 = a[10],\n    a11 = a[11];\n  var a12 = a[12],\n    a13 = a[13],\n    a14 = a[14],\n    a15 = a[15];\n  var b0 = b[0],\n    b1 = b[1],\n    b2 = b[2],\n    b3 = b[3];\n  var b4 = b[4],\n    b5 = b[5],\n    b6 = b[6],\n    b7 = b[7];\n  var b8 = b[8],\n    b9 = b[9],\n    b10 = b[10],\n    b11 = b[11];\n  var b12 = b[12],\n    b13 = b[13],\n    b14 = b[14],\n    b15 = b[15];\n  return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\nexport var sub = subtract;", "import * as glMatrix from \"./common.js\";\n\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\nexport function create() {\n  var out = new glMatrix.ARRAY_TYPE(3);\n  if (glMatrix.ARRAY_TYPE != Float32Array) {\n    out[0] = 0;\n    out[1] = 0;\n    out[2] = 0;\n  }\n  return out;\n}\n\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\nexport function clone(a) {\n  var out = new glMatrix.ARRAY_TYPE(3);\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  return out;\n}\n\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n  var x = a[0];\n  var y = a[1];\n  var z = a[2];\n  return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\nexport function fromValues(x, y, z) {\n  var out = new glMatrix.ARRAY_TYPE(3);\n  out[0] = x;\n  out[1] = y;\n  out[2] = z;\n  return out;\n}\n\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\nexport function copy(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  return out;\n}\n\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\nexport function set(out, x, y, z) {\n  out[0] = x;\n  out[1] = y;\n  out[2] = z;\n  return out;\n}\n\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function add(out, a, b) {\n  out[0] = a[0] + b[0];\n  out[1] = a[1] + b[1];\n  out[2] = a[2] + b[2];\n  return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function subtract(out, a, b) {\n  out[0] = a[0] - b[0];\n  out[1] = a[1] - b[1];\n  out[2] = a[2] - b[2];\n  return out;\n}\n\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function multiply(out, a, b) {\n  out[0] = a[0] * b[0];\n  out[1] = a[1] * b[1];\n  out[2] = a[2] * b[2];\n  return out;\n}\n\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function divide(out, a, b) {\n  out[0] = a[0] / b[0];\n  out[1] = a[1] / b[1];\n  out[2] = a[2] / b[2];\n  return out;\n}\n\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\nexport function ceil(out, a) {\n  out[0] = Math.ceil(a[0]);\n  out[1] = Math.ceil(a[1]);\n  out[2] = Math.ceil(a[2]);\n  return out;\n}\n\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\nexport function floor(out, a) {\n  out[0] = Math.floor(a[0]);\n  out[1] = Math.floor(a[1]);\n  out[2] = Math.floor(a[2]);\n  return out;\n}\n\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function min(out, a, b) {\n  out[0] = Math.min(a[0], b[0]);\n  out[1] = Math.min(a[1], b[1]);\n  out[2] = Math.min(a[2], b[2]);\n  return out;\n}\n\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function max(out, a, b) {\n  out[0] = Math.max(a[0], b[0]);\n  out[1] = Math.max(a[1], b[1]);\n  out[2] = Math.max(a[2], b[2]);\n  return out;\n}\n\n/**\n * symmetric round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\nexport function round(out, a) {\n  out[0] = glMatrix.round(a[0]);\n  out[1] = glMatrix.round(a[1]);\n  out[2] = glMatrix.round(a[2]);\n  return out;\n}\n\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\nexport function scale(out, a, b) {\n  out[0] = a[0] * b;\n  out[1] = a[1] * b;\n  out[2] = a[2] * b;\n  return out;\n}\n\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n  out[0] = a[0] + b[0] * scale;\n  out[1] = a[1] + b[1] * scale;\n  out[2] = a[2] + b[2] * scale;\n  return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n  var x = b[0] - a[0];\n  var y = b[1] - a[1];\n  var z = b[2] - a[2];\n  return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n  var x = b[0] - a[0];\n  var y = b[1] - a[1];\n  var z = b[2] - a[2];\n  return x * x + y * y + z * z;\n}\n\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n  var x = a[0];\n  var y = a[1];\n  var z = a[2];\n  return x * x + y * y + z * z;\n}\n\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\nexport function negate(out, a) {\n  out[0] = -a[0];\n  out[1] = -a[1];\n  out[2] = -a[2];\n  return out;\n}\n\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\nexport function inverse(out, a) {\n  out[0] = 1.0 / a[0];\n  out[1] = 1.0 / a[1];\n  out[2] = 1.0 / a[2];\n  return out;\n}\n\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\nexport function normalize(out, a) {\n  var x = a[0];\n  var y = a[1];\n  var z = a[2];\n  var len = x * x + y * y + z * z;\n  if (len > 0) {\n    //TODO: evaluate use of glm_invsqrt here?\n    len = 1 / Math.sqrt(len);\n  }\n  out[0] = a[0] * len;\n  out[1] = a[1] * len;\n  out[2] = a[2] * len;\n  return out;\n}\n\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function cross(out, a, b) {\n  var ax = a[0],\n    ay = a[1],\n    az = a[2];\n  var bx = b[0],\n    by = b[1],\n    bz = b[2];\n  out[0] = ay * bz - az * by;\n  out[1] = az * bx - ax * bz;\n  out[2] = ax * by - ay * bx;\n  return out;\n}\n\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function lerp(out, a, b, t) {\n  var ax = a[0];\n  var ay = a[1];\n  var az = a[2];\n  out[0] = ax + t * (b[0] - ax);\n  out[1] = ay + t * (b[1] - ay);\n  out[2] = az + t * (b[2] - az);\n  return out;\n}\n\n/**\n * Performs a spherical linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function slerp(out, a, b, t) {\n  var angle = Math.acos(Math.min(Math.max(dot(a, b), -1), 1));\n  var sinTotal = Math.sin(angle);\n  var ratioA = Math.sin((1 - t) * angle) / sinTotal;\n  var ratioB = Math.sin(t * angle) / sinTotal;\n  out[0] = ratioA * a[0] + ratioB * b[0];\n  out[1] = ratioA * a[1] + ratioB * b[1];\n  out[2] = ratioA * a[2] + ratioB * b[2];\n  return out;\n}\n\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function hermite(out, a, b, c, d, t) {\n  var factorTimes2 = t * t;\n  var factor1 = factorTimes2 * (2 * t - 3) + 1;\n  var factor2 = factorTimes2 * (t - 2) + t;\n  var factor3 = factorTimes2 * (t - 1);\n  var factor4 = factorTimes2 * (3 - 2 * t);\n  out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n  out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n  out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n  return out;\n}\n\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function bezier(out, a, b, c, d, t) {\n  var inverseFactor = 1 - t;\n  var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n  var factorTimes2 = t * t;\n  var factor1 = inverseFactorTimesTwo * inverseFactor;\n  var factor2 = 3 * t * inverseFactorTimesTwo;\n  var factor3 = 3 * factorTimes2 * inverseFactor;\n  var factor4 = factorTimes2 * t;\n  out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n  out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n  out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n  return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec3} out\n */\nexport function random(out, scale) {\n  scale = scale === undefined ? 1.0 : scale;\n  var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n  var z = glMatrix.RANDOM() * 2.0 - 1.0;\n  var zScale = Math.sqrt(1.0 - z * z) * scale;\n  out[0] = Math.cos(r) * zScale;\n  out[1] = Math.sin(r) * zScale;\n  out[2] = z * scale;\n  return out;\n}\n\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat4(out, a, m) {\n  var x = a[0],\n    y = a[1],\n    z = a[2];\n  var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n  w = w || 1.0;\n  out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n  out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n  out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n  return out;\n}\n\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat3(out, a, m) {\n  var x = a[0],\n    y = a[1],\n    z = a[2];\n  out[0] = x * m[0] + y * m[3] + z * m[6];\n  out[1] = x * m[1] + y * m[4] + z * m[7];\n  out[2] = x * m[2] + y * m[5] + z * m[8];\n  return out;\n}\n\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q normalized quaternion to transform with\n * @returns {vec3} out\n */\nexport function transformQuat(out, a, q) {\n  // Fast Vector Rotation using Quaternions by Robert Eisele\n  // https://raw.org/proof/vector-rotation-using-quaternions/\n\n  var qx = q[0],\n    qy = q[1],\n    qz = q[2],\n    qw = q[3];\n  var vx = a[0],\n    vy = a[1],\n    vz = a[2];\n\n  // t = q x v\n  var tx = qy * vz - qz * vy;\n  var ty = qz * vx - qx * vz;\n  var tz = qx * vy - qy * vx;\n\n  // t = 2t\n  tx = tx + tx;\n  ty = ty + ty;\n  tz = tz + tz;\n\n  // v + w t + q x t\n  out[0] = vx + qw * tx + qy * tz - qz * ty;\n  out[1] = vy + qw * ty + qz * tx - qx * tz;\n  out[2] = vz + qw * tz + qx * ty - qy * tx;\n  return out;\n}\n\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateX(out, a, b, rad) {\n  var p = [],\n    r = [];\n  //Translate point to the origin\n  p[0] = a[0] - b[0];\n  p[1] = a[1] - b[1];\n  p[2] = a[2] - b[2];\n\n  //perform rotation\n  r[0] = p[0];\n  r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n  r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad);\n\n  //translate to correct position\n  out[0] = r[0] + b[0];\n  out[1] = r[1] + b[1];\n  out[2] = r[2] + b[2];\n  return out;\n}\n\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateY(out, a, b, rad) {\n  var p = [],\n    r = [];\n  //Translate point to the origin\n  p[0] = a[0] - b[0];\n  p[1] = a[1] - b[1];\n  p[2] = a[2] - b[2];\n\n  //perform rotation\n  r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n  r[1] = p[1];\n  r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad);\n\n  //translate to correct position\n  out[0] = r[0] + b[0];\n  out[1] = r[1] + b[1];\n  out[2] = r[2] + b[2];\n  return out;\n}\n\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateZ(out, a, b, rad) {\n  var p = [],\n    r = [];\n  //Translate point to the origin\n  p[0] = a[0] - b[0];\n  p[1] = a[1] - b[1];\n  p[2] = a[2] - b[2];\n\n  //perform rotation\n  r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n  r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n  r[2] = p[2];\n\n  //translate to correct position\n  out[0] = r[0] + b[0];\n  out[1] = r[1] + b[1];\n  out[2] = r[2] + b[2];\n  return out;\n}\n\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\nexport function angle(a, b) {\n  var ax = a[0],\n    ay = a[1],\n    az = a[2],\n    bx = b[0],\n    by = b[1],\n    bz = b[2],\n    mag = Math.sqrt((ax * ax + ay * ay + az * az) * (bx * bx + by * by + bz * bz)),\n    cosine = mag && dot(a, b) / mag;\n  return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\nexport function zero(out) {\n  out[0] = 0.0;\n  out[1] = 0.0;\n  out[2] = 0.0;\n  return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n  return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2];\n  var b0 = b[0],\n    b1 = b[1],\n    b2 = b[2];\n  return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\nexport var sub = subtract;\n\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\nexport var div = divide;\n\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\nexport var dist = distance;\n\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\nexport var sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec3.length}\n * @function\n */\nexport var len = length;\n\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\nexport var sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport var forEach = function () {\n  var vec = create();\n  return function (a, stride, offset, count, fn, arg) {\n    var i, l;\n    if (!stride) {\n      stride = 3;\n    }\n    if (!offset) {\n      offset = 0;\n    }\n    if (count) {\n      l = Math.min(count * stride + offset, a.length);\n    } else {\n      l = a.length;\n    }\n    for (i = offset; i < l; i += stride) {\n      vec[0] = a[i];\n      vec[1] = a[i + 1];\n      vec[2] = a[i + 2];\n      fn(vec, vec, arg);\n      a[i] = vec[0];\n      a[i + 1] = vec[1];\n      a[i + 2] = vec[2];\n    }\n    return a;\n  };\n}();", "import * as glMatrix from \"./common.js\";\n\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\nexport function create() {\n  var out = new glMatrix.ARRAY_TYPE(4);\n  if (glMatrix.ARRAY_TYPE != Float32Array) {\n    out[0] = 0;\n    out[1] = 0;\n    out[2] = 0;\n    out[3] = 0;\n  }\n  return out;\n}\n\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\nexport function clone(a) {\n  var out = new glMatrix.ARRAY_TYPE(4);\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  return out;\n}\n\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\nexport function fromValues(x, y, z, w) {\n  var out = new glMatrix.ARRAY_TYPE(4);\n  out[0] = x;\n  out[1] = y;\n  out[2] = z;\n  out[3] = w;\n  return out;\n}\n\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\nexport function copy(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  out[2] = a[2];\n  out[3] = a[3];\n  return out;\n}\n\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\nexport function set(out, x, y, z, w) {\n  out[0] = x;\n  out[1] = y;\n  out[2] = z;\n  out[3] = w;\n  return out;\n}\n\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function add(out, a, b) {\n  out[0] = a[0] + b[0];\n  out[1] = a[1] + b[1];\n  out[2] = a[2] + b[2];\n  out[3] = a[3] + b[3];\n  return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function subtract(out, a, b) {\n  out[0] = a[0] - b[0];\n  out[1] = a[1] - b[1];\n  out[2] = a[2] - b[2];\n  out[3] = a[3] - b[3];\n  return out;\n}\n\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function multiply(out, a, b) {\n  out[0] = a[0] * b[0];\n  out[1] = a[1] * b[1];\n  out[2] = a[2] * b[2];\n  out[3] = a[3] * b[3];\n  return out;\n}\n\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function divide(out, a, b) {\n  out[0] = a[0] / b[0];\n  out[1] = a[1] / b[1];\n  out[2] = a[2] / b[2];\n  out[3] = a[3] / b[3];\n  return out;\n}\n\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\nexport function ceil(out, a) {\n  out[0] = Math.ceil(a[0]);\n  out[1] = Math.ceil(a[1]);\n  out[2] = Math.ceil(a[2]);\n  out[3] = Math.ceil(a[3]);\n  return out;\n}\n\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\nexport function floor(out, a) {\n  out[0] = Math.floor(a[0]);\n  out[1] = Math.floor(a[1]);\n  out[2] = Math.floor(a[2]);\n  out[3] = Math.floor(a[3]);\n  return out;\n}\n\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function min(out, a, b) {\n  out[0] = Math.min(a[0], b[0]);\n  out[1] = Math.min(a[1], b[1]);\n  out[2] = Math.min(a[2], b[2]);\n  out[3] = Math.min(a[3], b[3]);\n  return out;\n}\n\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function max(out, a, b) {\n  out[0] = Math.max(a[0], b[0]);\n  out[1] = Math.max(a[1], b[1]);\n  out[2] = Math.max(a[2], b[2]);\n  out[3] = Math.max(a[3], b[3]);\n  return out;\n}\n\n/**\n * symmetric round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\nexport function round(out, a) {\n  out[0] = glMatrix.round(a[0]);\n  out[1] = glMatrix.round(a[1]);\n  out[2] = glMatrix.round(a[2]);\n  out[3] = glMatrix.round(a[3]);\n  return out;\n}\n\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\nexport function scale(out, a, b) {\n  out[0] = a[0] * b;\n  out[1] = a[1] * b;\n  out[2] = a[2] * b;\n  out[3] = a[3] * b;\n  return out;\n}\n\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n  out[0] = a[0] + b[0] * scale;\n  out[1] = a[1] + b[1] * scale;\n  out[2] = a[2] + b[2] * scale;\n  out[3] = a[3] + b[3] * scale;\n  return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n  var x = b[0] - a[0];\n  var y = b[1] - a[1];\n  var z = b[2] - a[2];\n  var w = b[3] - a[3];\n  return Math.sqrt(x * x + y * y + z * z + w * w);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n  var x = b[0] - a[0];\n  var y = b[1] - a[1];\n  var z = b[2] - a[2];\n  var w = b[3] - a[3];\n  return x * x + y * y + z * z + w * w;\n}\n\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n  var x = a[0];\n  var y = a[1];\n  var z = a[2];\n  var w = a[3];\n  return Math.sqrt(x * x + y * y + z * z + w * w);\n}\n\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n  var x = a[0];\n  var y = a[1];\n  var z = a[2];\n  var w = a[3];\n  return x * x + y * y + z * z + w * w;\n}\n\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\nexport function negate(out, a) {\n  out[0] = -a[0];\n  out[1] = -a[1];\n  out[2] = -a[2];\n  out[3] = -a[3];\n  return out;\n}\n\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\nexport function inverse(out, a) {\n  out[0] = 1.0 / a[0];\n  out[1] = 1.0 / a[1];\n  out[2] = 1.0 / a[2];\n  out[3] = 1.0 / a[3];\n  return out;\n}\n\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\nexport function normalize(out, a) {\n  var x = a[0];\n  var y = a[1];\n  var z = a[2];\n  var w = a[3];\n  var len = x * x + y * y + z * z + w * w;\n  if (len > 0) {\n    len = 1 / Math.sqrt(len);\n  }\n  out[0] = x * len;\n  out[1] = y * len;\n  out[2] = z * len;\n  out[3] = w * len;\n  return out;\n}\n\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} out the receiving vector\n * @param {ReadonlyVec4} u the first vector\n * @param {ReadonlyVec4} v the second vector\n * @param {ReadonlyVec4} w the third vector\n * @returns {vec4} result\n */\nexport function cross(out, u, v, w) {\n  var A = v[0] * w[1] - v[1] * w[0],\n    B = v[0] * w[2] - v[2] * w[0],\n    C = v[0] * w[3] - v[3] * w[0],\n    D = v[1] * w[2] - v[2] * w[1],\n    E = v[1] * w[3] - v[3] * w[1],\n    F = v[2] * w[3] - v[3] * w[2];\n  var G = u[0];\n  var H = u[1];\n  var I = u[2];\n  var J = u[3];\n  out[0] = H * F - I * E + J * D;\n  out[1] = -(G * F) + I * C - J * B;\n  out[2] = G * E - H * C + J * A;\n  out[3] = -(G * D) + H * B - I * A;\n  return out;\n}\n\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\nexport function lerp(out, a, b, t) {\n  var ax = a[0];\n  var ay = a[1];\n  var az = a[2];\n  var aw = a[3];\n  out[0] = ax + t * (b[0] - ax);\n  out[1] = ay + t * (b[1] - ay);\n  out[2] = az + t * (b[2] - az);\n  out[3] = aw + t * (b[3] - aw);\n  return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec4} out\n */\nexport function random(out, scale) {\n  scale = scale === undefined ? 1.0 : scale;\n\n  // Marsaglia, George. Choosing a Point from the Surface of a\n  // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n  // http://projecteuclid.org/euclid.aoms/1177692644;\n  var v1, v2, v3, v4;\n  var s1, s2;\n  var rand;\n  rand = glMatrix.RANDOM();\n  v1 = rand * 2 - 1;\n  v2 = (4 * glMatrix.RANDOM() - 2) * Math.sqrt(rand * -rand + rand);\n  s1 = v1 * v1 + v2 * v2;\n  rand = glMatrix.RANDOM();\n  v3 = rand * 2 - 1;\n  v4 = (4 * glMatrix.RANDOM() - 2) * Math.sqrt(rand * -rand + rand);\n  s2 = v3 * v3 + v4 * v4;\n  var d = Math.sqrt((1 - s1) / s2);\n  out[0] = scale * v1;\n  out[1] = scale * v2;\n  out[2] = scale * v3 * d;\n  out[3] = scale * v4 * d;\n  return out;\n}\n\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\nexport function transformMat4(out, a, m) {\n  var x = a[0],\n    y = a[1],\n    z = a[2],\n    w = a[3];\n  out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n  out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n  out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n  out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n  return out;\n}\n\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q normalized quaternion to transform with\n * @returns {vec4} out\n */\nexport function transformQuat(out, a, q) {\n  // Fast Vector Rotation using Quaternions by Robert Eisele\n  // https://raw.org/proof/vector-rotation-using-quaternions/\n\n  var qx = q[0],\n    qy = q[1],\n    qz = q[2],\n    qw = q[3];\n  var vx = a[0],\n    vy = a[1],\n    vz = a[2];\n\n  // t = q x v\n  var tx = qy * vz - qz * vy;\n  var ty = qz * vx - qx * vz;\n  var tz = qx * vy - qy * vx;\n\n  // t = 2t\n  tx = tx + tx;\n  ty = ty + ty;\n  tz = tz + tz;\n\n  // v + w t + q x t\n  out[0] = vx + qw * tx + qy * tz - qz * ty;\n  out[1] = vy + qw * ty + qz * tx - qx * tz;\n  out[2] = vz + qw * tz + qx * ty - qy * tx;\n  out[3] = a[3];\n  return out;\n}\n\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\nexport function zero(out) {\n  out[0] = 0.0;\n  out[1] = 0.0;\n  out[2] = 0.0;\n  out[3] = 0.0;\n  return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n  return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n  return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n  var b0 = b[0],\n    b1 = b[1],\n    b2 = b[2],\n    b3 = b[3];\n  return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\nexport var sub = subtract;\n\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\nexport var div = divide;\n\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\nexport var dist = distance;\n\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\nexport var sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec4.length}\n * @function\n */\nexport var len = length;\n\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\nexport var sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport var forEach = function () {\n  var vec = create();\n  return function (a, stride, offset, count, fn, arg) {\n    var i, l;\n    if (!stride) {\n      stride = 4;\n    }\n    if (!offset) {\n      offset = 0;\n    }\n    if (count) {\n      l = Math.min(count * stride + offset, a.length);\n    } else {\n      l = a.length;\n    }\n    for (i = offset; i < l; i += stride) {\n      vec[0] = a[i];\n      vec[1] = a[i + 1];\n      vec[2] = a[i + 2];\n      vec[3] = a[i + 3];\n      fn(vec, vec, arg);\n      a[i] = vec[0];\n      a[i + 1] = vec[1];\n      a[i + 2] = vec[2];\n      a[i + 3] = vec[3];\n    }\n    return a;\n  };\n}();", "import * as glMatrix from \"./common.js\";\nimport * as mat3 from \"./mat3.js\";\nimport * as vec3 from \"./vec3.js\";\nimport * as vec4 from \"./vec4.js\";\n\n/**\n * Quaternion in the format XYZW\n * @module quat\n */\n\n/**\n * Creates a new identity quat\n *\n * @returns {quat} a new quaternion\n */\nexport function create() {\n  var out = new glMatrix.ARRAY_TYPE(4);\n  if (glMatrix.ARRAY_TYPE != Float32Array) {\n    out[0] = 0;\n    out[1] = 0;\n    out[2] = 0;\n  }\n  out[3] = 1;\n  return out;\n}\n\n/**\n * Set a quat to the identity quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\nexport function identity(out) {\n  out[0] = 0;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 1;\n  return out;\n}\n\n/**\n * Sets a quat from the given angle and rotation axis,\n * then returns it.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyVec3} axis the axis around which to rotate\n * @param {Number} rad the angle in radians\n * @returns {quat} out\n **/\nexport function setAxisAngle(out, axis, rad) {\n  rad = rad * 0.5;\n  var s = Math.sin(rad);\n  out[0] = s * axis[0];\n  out[1] = s * axis[1];\n  out[2] = s * axis[2];\n  out[3] = Math.cos(rad);\n  return out;\n}\n\n/**\n * Gets the rotation axis and angle for a given\n *  quaternion. If a quaternion is created with\n *  setAxisAngle, this method will return the same\n *  values as providied in the original parameter list\n *  OR functionally equivalent values.\n * Example: The quaternion formed by axis [0, 0, 1] and\n *  angle -90 is the same as the quaternion formed by\n *  [0, 0, 1] and 270. This method favors the latter.\n * @param  {vec3} out_axis  Vector receiving the axis of rotation\n * @param  {ReadonlyQuat} q     Quaternion to be decomposed\n * @return {Number}     Angle, in radians, of the rotation\n */\nexport function getAxisAngle(out_axis, q) {\n  var rad = Math.acos(q[3]) * 2.0;\n  var s = Math.sin(rad / 2.0);\n  if (s > glMatrix.EPSILON) {\n    out_axis[0] = q[0] / s;\n    out_axis[1] = q[1] / s;\n    out_axis[2] = q[2] / s;\n  } else {\n    // If s is zero, return any axis (no rotation - axis does not matter)\n    out_axis[0] = 1;\n    out_axis[1] = 0;\n    out_axis[2] = 0;\n  }\n  return rad;\n}\n\n/**\n * Gets the angular distance between two unit quaternions\n *\n * @param  {ReadonlyQuat} a     Origin unit quaternion\n * @param  {ReadonlyQuat} b     Destination unit quaternion\n * @return {Number}     Angle, in radians, between the two quaternions\n */\nexport function getAngle(a, b) {\n  var dotproduct = dot(a, b);\n  return Math.acos(2 * dotproduct * dotproduct - 1);\n}\n\n/**\n * Multiplies two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n */\nexport function multiply(out, a, b) {\n  var ax = a[0],\n    ay = a[1],\n    az = a[2],\n    aw = a[3];\n  var bx = b[0],\n    by = b[1],\n    bz = b[2],\n    bw = b[3];\n  out[0] = ax * bw + aw * bx + ay * bz - az * by;\n  out[1] = ay * bw + aw * by + az * bx - ax * bz;\n  out[2] = az * bw + aw * bz + ax * by - ay * bx;\n  out[3] = aw * bw - ax * bx - ay * by - az * bz;\n  return out;\n}\n\n/**\n * Rotates a quaternion by the given angle about the X axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\nexport function rotateX(out, a, rad) {\n  rad *= 0.5;\n  var ax = a[0],\n    ay = a[1],\n    az = a[2],\n    aw = a[3];\n  var bx = Math.sin(rad),\n    bw = Math.cos(rad);\n  out[0] = ax * bw + aw * bx;\n  out[1] = ay * bw + az * bx;\n  out[2] = az * bw - ay * bx;\n  out[3] = aw * bw - ax * bx;\n  return out;\n}\n\n/**\n * Rotates a quaternion by the given angle about the Y axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\nexport function rotateY(out, a, rad) {\n  rad *= 0.5;\n  var ax = a[0],\n    ay = a[1],\n    az = a[2],\n    aw = a[3];\n  var by = Math.sin(rad),\n    bw = Math.cos(rad);\n  out[0] = ax * bw - az * by;\n  out[1] = ay * bw + aw * by;\n  out[2] = az * bw + ax * by;\n  out[3] = aw * bw - ay * by;\n  return out;\n}\n\n/**\n * Rotates a quaternion by the given angle about the Z axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\nexport function rotateZ(out, a, rad) {\n  rad *= 0.5;\n  var ax = a[0],\n    ay = a[1],\n    az = a[2],\n    aw = a[3];\n  var bz = Math.sin(rad),\n    bw = Math.cos(rad);\n  out[0] = ax * bw + ay * bz;\n  out[1] = ay * bw - ax * bz;\n  out[2] = az * bw + aw * bz;\n  out[3] = aw * bw - az * bz;\n  return out;\n}\n\n/**\n * Calculates the W component of a quat from the X, Y, and Z components.\n * Assumes that quaternion is 1 unit in length.\n * Any existing W component will be ignored.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate W component of\n * @returns {quat} out\n */\nexport function calculateW(out, a) {\n  var x = a[0],\n    y = a[1],\n    z = a[2];\n  out[0] = x;\n  out[1] = y;\n  out[2] = z;\n  out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));\n  return out;\n}\n\n/**\n * Calculate the exponential of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\nexport function exp(out, a) {\n  var x = a[0],\n    y = a[1],\n    z = a[2],\n    w = a[3];\n  var r = Math.sqrt(x * x + y * y + z * z);\n  var et = Math.exp(w);\n  var s = r > 0 ? et * Math.sin(r) / r : 0;\n  out[0] = x * s;\n  out[1] = y * s;\n  out[2] = z * s;\n  out[3] = et * Math.cos(r);\n  return out;\n}\n\n/**\n * Calculate the natural logarithm of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\nexport function ln(out, a) {\n  var x = a[0],\n    y = a[1],\n    z = a[2],\n    w = a[3];\n  var r = Math.sqrt(x * x + y * y + z * z);\n  var t = r > 0 ? Math.atan2(r, w) / r : 0;\n  out[0] = x * t;\n  out[1] = y * t;\n  out[2] = z * t;\n  out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);\n  return out;\n}\n\n/**\n * Calculate the scalar power of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @param {Number} b amount to scale the quaternion by\n * @returns {quat} out\n */\nexport function pow(out, a, b) {\n  ln(out, a);\n  scale(out, out, b);\n  exp(out, out);\n  return out;\n}\n\n/**\n * Performs a spherical linear interpolation between two quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\nexport function slerp(out, a, b, t) {\n  // benchmarks:\n  //    http://jsperf.com/quaternion-slerp-implementations\n  var ax = a[0],\n    ay = a[1],\n    az = a[2],\n    aw = a[3];\n  var bx = b[0],\n    by = b[1],\n    bz = b[2],\n    bw = b[3];\n  var omega, cosom, sinom, scale0, scale1;\n\n  // calc cosine\n  cosom = ax * bx + ay * by + az * bz + aw * bw;\n  // adjust signs (if necessary)\n  if (cosom < 0.0) {\n    cosom = -cosom;\n    bx = -bx;\n    by = -by;\n    bz = -bz;\n    bw = -bw;\n  }\n  // calculate coefficients\n  if (1.0 - cosom > glMatrix.EPSILON) {\n    // standard case (slerp)\n    omega = Math.acos(cosom);\n    sinom = Math.sin(omega);\n    scale0 = Math.sin((1.0 - t) * omega) / sinom;\n    scale1 = Math.sin(t * omega) / sinom;\n  } else {\n    // \"from\" and \"to\" quaternions are very close\n    //  ... so we can do a linear interpolation\n    scale0 = 1.0 - t;\n    scale1 = t;\n  }\n  // calculate final values\n  out[0] = scale0 * ax + scale1 * bx;\n  out[1] = scale0 * ay + scale1 * by;\n  out[2] = scale0 * az + scale1 * bz;\n  out[3] = scale0 * aw + scale1 * bw;\n  return out;\n}\n\n/**\n * Generates a random unit quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\nexport function random(out) {\n  // Implementation of http://planning.cs.uiuc.edu/node198.html\n  // TODO: Calling random 3 times is probably not the fastest solution\n  var u1 = glMatrix.RANDOM();\n  var u2 = glMatrix.RANDOM();\n  var u3 = glMatrix.RANDOM();\n  var sqrt1MinusU1 = Math.sqrt(1 - u1);\n  var sqrtU1 = Math.sqrt(u1);\n  out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2);\n  out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2);\n  out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3);\n  out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3);\n  return out;\n}\n\n/**\n * Calculates the inverse of a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate inverse of\n * @returns {quat} out\n */\nexport function invert(out, a) {\n  var a0 = a[0],\n    a1 = a[1],\n    a2 = a[2],\n    a3 = a[3];\n  var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n  var invDot = dot ? 1.0 / dot : 0;\n\n  // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0\n\n  out[0] = -a0 * invDot;\n  out[1] = -a1 * invDot;\n  out[2] = -a2 * invDot;\n  out[3] = a3 * invDot;\n  return out;\n}\n\n/**\n * Calculates the conjugate of a quat\n * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate conjugate of\n * @returns {quat} out\n */\nexport function conjugate(out, a) {\n  out[0] = -a[0];\n  out[1] = -a[1];\n  out[2] = -a[2];\n  out[3] = a[3];\n  return out;\n}\n\n/**\n * Creates a quaternion from the given 3x3 rotation matrix.\n *\n * NOTE: The resultant quaternion is not normalized, so you should be sure\n * to renormalize the quaternion yourself where necessary.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyMat3} m rotation matrix\n * @returns {quat} out\n * @function\n */\nexport function fromMat3(out, m) {\n  // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n  // article \"Quaternion Calculus and Fast Animation\".\n  var fTrace = m[0] + m[4] + m[8];\n  var fRoot;\n  if (fTrace > 0.0) {\n    // |w| > 1/2, may as well choose w > 1/2\n    fRoot = Math.sqrt(fTrace + 1.0); // 2w\n    out[3] = 0.5 * fRoot;\n    fRoot = 0.5 / fRoot; // 1/(4w)\n    out[0] = (m[5] - m[7]) * fRoot;\n    out[1] = (m[6] - m[2]) * fRoot;\n    out[2] = (m[1] - m[3]) * fRoot;\n  } else {\n    // |w| <= 1/2\n    var i = 0;\n    if (m[4] > m[0]) i = 1;\n    if (m[8] > m[i * 3 + i]) i = 2;\n    var j = (i + 1) % 3;\n    var k = (i + 2) % 3;\n    fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);\n    out[i] = 0.5 * fRoot;\n    fRoot = 0.5 / fRoot;\n    out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;\n    out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;\n    out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;\n  }\n  return out;\n}\n\n/**\n * Creates a quaternion from the given euler angle x, y, z using the provided intrinsic order for the conversion.\n *\n * @param {quat} out the receiving quaternion\n * @param {Number} x Angle to rotate around X axis in degrees.\n * @param {Number} y Angle to rotate around Y axis in degrees.\n * @param {Number} z Angle to rotate around Z axis in degrees.\n * @param {'xyz'|'xzy'|'yxz'|'yzx'|'zxy'|'zyx'} order Intrinsic order for conversion, default is zyx.\n * @returns {quat} out\n * @function\n */\nexport function fromEuler(out, x, y, z) {\n  var order = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : glMatrix.ANGLE_ORDER;\n  var halfToRad = Math.PI / 360;\n  x *= halfToRad;\n  z *= halfToRad;\n  y *= halfToRad;\n  var sx = Math.sin(x);\n  var cx = Math.cos(x);\n  var sy = Math.sin(y);\n  var cy = Math.cos(y);\n  var sz = Math.sin(z);\n  var cz = Math.cos(z);\n  switch (order) {\n    case \"xyz\":\n      out[0] = sx * cy * cz + cx * sy * sz;\n      out[1] = cx * sy * cz - sx * cy * sz;\n      out[2] = cx * cy * sz + sx * sy * cz;\n      out[3] = cx * cy * cz - sx * sy * sz;\n      break;\n    case \"xzy\":\n      out[0] = sx * cy * cz - cx * sy * sz;\n      out[1] = cx * sy * cz - sx * cy * sz;\n      out[2] = cx * cy * sz + sx * sy * cz;\n      out[3] = cx * cy * cz + sx * sy * sz;\n      break;\n    case \"yxz\":\n      out[0] = sx * cy * cz + cx * sy * sz;\n      out[1] = cx * sy * cz - sx * cy * sz;\n      out[2] = cx * cy * sz - sx * sy * cz;\n      out[3] = cx * cy * cz + sx * sy * sz;\n      break;\n    case \"yzx\":\n      out[0] = sx * cy * cz + cx * sy * sz;\n      out[1] = cx * sy * cz + sx * cy * sz;\n      out[2] = cx * cy * sz - sx * sy * cz;\n      out[3] = cx * cy * cz - sx * sy * sz;\n      break;\n    case \"zxy\":\n      out[0] = sx * cy * cz - cx * sy * sz;\n      out[1] = cx * sy * cz + sx * cy * sz;\n      out[2] = cx * cy * sz + sx * sy * cz;\n      out[3] = cx * cy * cz - sx * sy * sz;\n      break;\n    case \"zyx\":\n      out[0] = sx * cy * cz - cx * sy * sz;\n      out[1] = cx * sy * cz + sx * cy * sz;\n      out[2] = cx * cy * sz - sx * sy * cz;\n      out[3] = cx * cy * cz + sx * sy * sz;\n      break;\n    default:\n      throw new Error('Unknown angle order ' + order);\n  }\n  return out;\n}\n\n/**\n * Returns a string representation of a quaternion\n *\n * @param {ReadonlyQuat} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n  return \"quat(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n\n/**\n * Creates a new quat initialized with values from an existing quaternion\n *\n * @param {ReadonlyQuat} a quaternion to clone\n * @returns {quat} a new quaternion\n * @function\n */\nexport var clone = vec4.clone;\n\n/**\n * Creates a new quat initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} a new quaternion\n * @function\n */\nexport var fromValues = vec4.fromValues;\n\n/**\n * Copy the values from one quat to another\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the source quaternion\n * @returns {quat} out\n * @function\n */\nexport var copy = vec4.copy;\n\n/**\n * Set the components of a quat to the given values\n *\n * @param {quat} out the receiving quaternion\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} out\n * @function\n */\nexport var set = vec4.set;\n\n/**\n * Adds two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n * @function\n */\nexport var add = vec4.add;\n\n/**\n * Alias for {@link quat.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Scales a quat by a scalar number\n *\n * @param {quat} out the receiving vector\n * @param {ReadonlyQuat} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {quat} out\n * @function\n */\nexport var scale = vec4.scale;\n\n/**\n * Calculates the dot product of two quat's\n *\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {Number} dot product of a and b\n * @function\n */\nexport var dot = vec4.dot;\n\n/**\n * Performs a linear interpolation between two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n * @function\n */\nexport var lerp = vec4.lerp;\n\n/**\n * Calculates the length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport var length = vec4.length;\n\n/**\n * Alias for {@link quat.length}\n * @function\n */\nexport var len = length;\n\n/**\n * Calculates the squared length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate squared length of\n * @returns {Number} squared length of a\n * @function\n */\nexport var squaredLength = vec4.squaredLength;\n\n/**\n * Alias for {@link quat.squaredLength}\n * @function\n */\nexport var sqrLen = squaredLength;\n\n/**\n * Normalize a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quaternion to normalize\n * @returns {quat} out\n * @function\n */\nexport var normalize = vec4.normalize;\n\n/**\n * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyQuat} a The first quaternion.\n * @param {ReadonlyQuat} b The second quaternion.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport var exactEquals = vec4.exactEquals;\n\n/**\n * Returns whether or not the quaternions point approximately to the same direction.\n *\n * Both quaternions are assumed to be unit length.\n *\n * @param {ReadonlyQuat} a The first unit quaternion.\n * @param {ReadonlyQuat} b The second unit quaternion.\n * @returns {Boolean} True if the quaternions are equal, false otherwise.\n */\nexport function equals(a, b) {\n  return Math.abs(vec4.dot(a, b)) >= 1 - glMatrix.EPSILON;\n}\n\n/**\n * Sets a quaternion to represent the shortest rotation from one\n * vector to another.\n *\n * Both vectors are assumed to be unit length.\n *\n * @param {quat} out the receiving quaternion.\n * @param {ReadonlyVec3} a the initial vector\n * @param {ReadonlyVec3} b the destination vector\n * @returns {quat} out\n */\nexport var rotationTo = function () {\n  var tmpvec3 = vec3.create();\n  var xUnitVec3 = vec3.fromValues(1, 0, 0);\n  var yUnitVec3 = vec3.fromValues(0, 1, 0);\n  return function (out, a, b) {\n    var dot = vec3.dot(a, b);\n    if (dot < -0.999999) {\n      vec3.cross(tmpvec3, xUnitVec3, a);\n      if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);\n      vec3.normalize(tmpvec3, tmpvec3);\n      setAxisAngle(out, tmpvec3, Math.PI);\n      return out;\n    } else if (dot > 0.999999) {\n      out[0] = 0;\n      out[1] = 0;\n      out[2] = 0;\n      out[3] = 1;\n      return out;\n    } else {\n      vec3.cross(tmpvec3, a, b);\n      out[0] = tmpvec3[0];\n      out[1] = tmpvec3[1];\n      out[2] = tmpvec3[2];\n      out[3] = 1 + dot;\n      return normalize(out, out);\n    }\n  };\n}();\n\n/**\n * Performs a spherical linear interpolation with two control points\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {ReadonlyQuat} c the third operand\n * @param {ReadonlyQuat} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\nexport var sqlerp = function () {\n  var temp1 = create();\n  var temp2 = create();\n  return function (out, a, b, c, d, t) {\n    slerp(temp1, a, d, t);\n    slerp(temp2, b, c, t);\n    slerp(out, temp1, temp2, 2 * t * (1 - t));\n    return out;\n  };\n}();\n\n/**\n * Sets the specified quaternion with values corresponding to the given\n * axes. Each axis is a vec3 and is expected to be unit length and\n * perpendicular to all other specified axes.\n *\n * @param {ReadonlyVec3} view  the vector representing the viewing direction\n * @param {ReadonlyVec3} right the vector representing the local \"right\" direction\n * @param {ReadonlyVec3} up    the vector representing the local \"up\" direction\n * @returns {quat} out\n */\nexport var setAxes = function () {\n  var matr = mat3.create();\n  return function (out, view, right, up) {\n    matr[0] = right[0];\n    matr[3] = right[1];\n    matr[6] = right[2];\n    matr[1] = up[0];\n    matr[4] = up[1];\n    matr[7] = up[2];\n    matr[2] = -view[0];\n    matr[5] = -view[1];\n    matr[8] = -view[2];\n    return normalize(out, fromMat3(out, matr));\n  };\n}();", "import * as glMatrix from \"./common.js\";\n\n/**\n * 2 Dimensional Vector\n * @module vec2\n */\n\n/**\n * Creates a new, empty vec2\n *\n * @returns {vec2} a new 2D vector\n */\nexport function create() {\n  var out = new glMatrix.ARRAY_TYPE(2);\n  if (glMatrix.ARRAY_TYPE != Float32Array) {\n    out[0] = 0;\n    out[1] = 0;\n  }\n  return out;\n}\n\n/**\n * Creates a new vec2 initialized with values from an existing vector\n *\n * @param {ReadonlyVec2} a vector to clone\n * @returns {vec2} a new 2D vector\n */\nexport function clone(a) {\n  var out = new glMatrix.ARRAY_TYPE(2);\n  out[0] = a[0];\n  out[1] = a[1];\n  return out;\n}\n\n/**\n * Creates a new vec2 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {vec2} a new 2D vector\n */\nexport function fromValues(x, y) {\n  var out = new glMatrix.ARRAY_TYPE(2);\n  out[0] = x;\n  out[1] = y;\n  return out;\n}\n\n/**\n * Copy the values from one vec2 to another\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the source vector\n * @returns {vec2} out\n */\nexport function copy(out, a) {\n  out[0] = a[0];\n  out[1] = a[1];\n  return out;\n}\n\n/**\n * Set the components of a vec2 to the given values\n *\n * @param {vec2} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {vec2} out\n */\nexport function set(out, x, y) {\n  out[0] = x;\n  out[1] = y;\n  return out;\n}\n\n/**\n * Adds two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\nexport function add(out, a, b) {\n  out[0] = a[0] + b[0];\n  out[1] = a[1] + b[1];\n  return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\nexport function subtract(out, a, b) {\n  out[0] = a[0] - b[0];\n  out[1] = a[1] - b[1];\n  return out;\n}\n\n/**\n * Multiplies two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\nexport function multiply(out, a, b) {\n  out[0] = a[0] * b[0];\n  out[1] = a[1] * b[1];\n  return out;\n}\n\n/**\n * Divides two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\nexport function divide(out, a, b) {\n  out[0] = a[0] / b[0];\n  out[1] = a[1] / b[1];\n  return out;\n}\n\n/**\n * Math.ceil the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to ceil\n * @returns {vec2} out\n */\nexport function ceil(out, a) {\n  out[0] = Math.ceil(a[0]);\n  out[1] = Math.ceil(a[1]);\n  return out;\n}\n\n/**\n * Math.floor the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to floor\n * @returns {vec2} out\n */\nexport function floor(out, a) {\n  out[0] = Math.floor(a[0]);\n  out[1] = Math.floor(a[1]);\n  return out;\n}\n\n/**\n * Returns the minimum of two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\nexport function min(out, a, b) {\n  out[0] = Math.min(a[0], b[0]);\n  out[1] = Math.min(a[1], b[1]);\n  return out;\n}\n\n/**\n * Returns the maximum of two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\nexport function max(out, a, b) {\n  out[0] = Math.max(a[0], b[0]);\n  out[1] = Math.max(a[1], b[1]);\n  return out;\n}\n\n/**\n * symmetric round the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to round\n * @returns {vec2} out\n */\nexport function round(out, a) {\n  out[0] = glMatrix.round(a[0]);\n  out[1] = glMatrix.round(a[1]);\n  return out;\n}\n\n/**\n * Scales a vec2 by a scalar number\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec2} out\n */\nexport function scale(out, a, b) {\n  out[0] = a[0] * b;\n  out[1] = a[1] * b;\n  return out;\n}\n\n/**\n * Adds two vec2's after scaling the second operand by a scalar value\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec2} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n  out[0] = a[0] + b[0] * scale;\n  out[1] = a[1] + b[1] * scale;\n  return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n  var x = b[0] - a[0],\n    y = b[1] - a[1];\n  return Math.sqrt(x * x + y * y);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n  var x = b[0] - a[0],\n    y = b[1] - a[1];\n  return x * x + y * y;\n}\n\n/**\n * Calculates the length of a vec2\n *\n * @param {ReadonlyVec2} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n  var x = a[0],\n    y = a[1];\n  return Math.sqrt(x * x + y * y);\n}\n\n/**\n * Calculates the squared length of a vec2\n *\n * @param {ReadonlyVec2} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n  var x = a[0],\n    y = a[1];\n  return x * x + y * y;\n}\n\n/**\n * Negates the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to negate\n * @returns {vec2} out\n */\nexport function negate(out, a) {\n  out[0] = -a[0];\n  out[1] = -a[1];\n  return out;\n}\n\n/**\n * Returns the inverse of the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to invert\n * @returns {vec2} out\n */\nexport function inverse(out, a) {\n  out[0] = 1.0 / a[0];\n  out[1] = 1.0 / a[1];\n  return out;\n}\n\n/**\n * Normalize a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to normalize\n * @returns {vec2} out\n */\nexport function normalize(out, a) {\n  var x = a[0],\n    y = a[1];\n  var len = x * x + y * y;\n  if (len > 0) {\n    //TODO: evaluate use of glm_invsqrt here?\n    len = 1 / Math.sqrt(len);\n  }\n  out[0] = a[0] * len;\n  out[1] = a[1] * len;\n  return out;\n}\n\n/**\n * Calculates the dot product of two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n  return a[0] * b[0] + a[1] * b[1];\n}\n\n/**\n * Computes the cross product of two vec2's\n * Note that the cross product must by definition produce a 3D vector\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec3} out\n */\nexport function cross(out, a, b) {\n  var z = a[0] * b[1] - a[1] * b[0];\n  out[0] = out[1] = 0;\n  out[2] = z;\n  return out;\n}\n\n/**\n * Performs a linear interpolation between two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec2} out\n */\nexport function lerp(out, a, b, t) {\n  var ax = a[0],\n    ay = a[1];\n  out[0] = ax + t * (b[0] - ax);\n  out[1] = ay + t * (b[1] - ay);\n  return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec2} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec2} out\n */\nexport function random(out, scale) {\n  scale = scale === undefined ? 1.0 : scale;\n  var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n  out[0] = Math.cos(r) * scale;\n  out[1] = Math.sin(r) * scale;\n  return out;\n}\n\n/**\n * Transforms the vec2 with a mat2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat2} m matrix to transform with\n * @returns {vec2} out\n */\nexport function transformMat2(out, a, m) {\n  var x = a[0],\n    y = a[1];\n  out[0] = m[0] * x + m[2] * y;\n  out[1] = m[1] * x + m[3] * y;\n  return out;\n}\n\n/**\n * Transforms the vec2 with a mat2d\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat2d} m matrix to transform with\n * @returns {vec2} out\n */\nexport function transformMat2d(out, a, m) {\n  var x = a[0],\n    y = a[1];\n  out[0] = m[0] * x + m[2] * y + m[4];\n  out[1] = m[1] * x + m[3] * y + m[5];\n  return out;\n}\n\n/**\n * Transforms the vec2 with a mat3\n * 3rd vector component is implicitly '1'\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat3} m matrix to transform with\n * @returns {vec2} out\n */\nexport function transformMat3(out, a, m) {\n  var x = a[0],\n    y = a[1];\n  out[0] = m[0] * x + m[3] * y + m[6];\n  out[1] = m[1] * x + m[4] * y + m[7];\n  return out;\n}\n\n/**\n * Transforms the vec2 with a mat4\n * 3rd vector component is implicitly '0'\n * 4th vector component is implicitly '1'\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec2} out\n */\nexport function transformMat4(out, a, m) {\n  var x = a[0];\n  var y = a[1];\n  out[0] = m[0] * x + m[4] * y + m[12];\n  out[1] = m[1] * x + m[5] * y + m[13];\n  return out;\n}\n\n/**\n * Rotate a 2D vector\n * @param {vec2} out The receiving vec2\n * @param {ReadonlyVec2} a The vec2 point to rotate\n * @param {ReadonlyVec2} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec2} out\n */\nexport function rotate(out, a, b, rad) {\n  //Translate point to the origin\n  var p0 = a[0] - b[0],\n    p1 = a[1] - b[1],\n    sinC = Math.sin(rad),\n    cosC = Math.cos(rad);\n\n  //perform rotation and translate to correct position\n  out[0] = p0 * cosC - p1 * sinC + b[0];\n  out[1] = p0 * sinC + p1 * cosC + b[1];\n  return out;\n}\n\n/**\n * Get the smallest angle between two 2D vectors\n * @param {ReadonlyVec2} a The first operand\n * @param {ReadonlyVec2} b The second operand\n * @returns {Number} The angle in radians\n */\nexport function angle(a, b) {\n  var ax = a[0],\n    ay = a[1],\n    bx = b[0],\n    by = b[1];\n  return Math.abs(Math.atan2(ay * bx - ax * by, ax * bx + ay * by));\n}\n\n/**\n * Get the signed angle in the interval [-pi,pi] between two 2D vectors (positive if `a` is to the right of `b`)\n * \n * @param {ReadonlyVec2} a The first vector\n * @param {ReadonlyVec2} b The second vector\n * @returns {number} The signed angle in radians\n */\nexport function signedAngle(a, b) {\n  var ax = a[0],\n    ay = a[1],\n    bx = b[0],\n    by = b[1];\n  return Math.atan2(ax * by - ay * bx, ax * bx + ay * by);\n}\n\n/**\n * Set the components of a vec2 to zero\n *\n * @param {vec2} out the receiving vector\n * @returns {vec2} out\n */\nexport function zero(out) {\n  out[0] = 0.0;\n  out[1] = 0.0;\n  return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec2} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n  return \"vec2(\" + a[0] + \", \" + a[1] + \")\";\n}\n\n/**\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec2} a The first vector.\n * @param {ReadonlyVec2} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n  return a[0] === b[0] && a[1] === b[1];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec2} a The first vector.\n * @param {ReadonlyVec2} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n  var a0 = a[0],\n    a1 = a[1];\n  var b0 = b[0],\n    b1 = b[1];\n  return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1));\n}\n\n/**\n * Alias for {@link vec2.length}\n * @function\n */\nexport var len = length;\n\n/**\n * Alias for {@link vec2.subtract}\n * @function\n */\nexport var sub = subtract;\n\n/**\n * Alias for {@link vec2.multiply}\n * @function\n */\nexport var mul = multiply;\n\n/**\n * Alias for {@link vec2.divide}\n * @function\n */\nexport var div = divide;\n\n/**\n * Alias for {@link vec2.distance}\n * @function\n */\nexport var dist = distance;\n\n/**\n * Alias for {@link vec2.squaredDistance}\n * @function\n */\nexport var sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec2.squaredLength}\n * @function\n */\nexport var sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec2s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport var forEach = function () {\n  var vec = create();\n  return function (a, stride, offset, count, fn, arg) {\n    var i, l;\n    if (!stride) {\n      stride = 2;\n    }\n    if (!offset) {\n      offset = 0;\n    }\n    if (count) {\n      l = Math.min(count * stride + offset, a.length);\n    } else {\n      l = a.length;\n    }\n    for (i = offset; i < l; i += stride) {\n      vec[0] = a[i];\n      vec[1] = a[i + 1];\n      fn(vec, vec, arg);\n      a[i] = vec[0];\n      a[i + 1] = vec[1];\n    }\n    return a;\n  };\n}();", "/**\n * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of\n * all source features normalized to this extent upon load.\n *\n * The value is a consequence of the following:\n *\n * * Vertex buffer store positions as signed 16 bit integers.\n * * One bit is lost for signedness to support tile buffers.\n * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int.\n * * One bit is lost to support features extending past the extent on the right edge of the tile.\n * * This leaves us with 2^13 = 8192\n */\nexport const EXTENT = 8192;", "import {EXTENT} from '../data/extent.ts';\n\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\n\n/**\n * Converts a pixel value at a the given zoom level to tile units.\n *\n * The shaders mostly calculate everything in tile units so style\n * properties need to be converted from pixels to tile units using this.\n *\n * For example, a translation by 30 pixels at zoom 6.5 will be a\n * translation by pixelsToTileUnits(30, 6.5) tile units.\n *\n * @returns value in tile units\n */\nexport function pixelsToTileUnits(\n    tile: {\n        tileID: OverscaledTileID;\n        tileSize: number;\n    },\n    pixelValue: number,\n    z: number\n): number {\n    return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));\n}\n", "import Point from '@mapbox/point-geometry';\nimport unitBezierFactory from '@mapbox/unitbezier';\nimport {isOffscreenCanvasDistorted} from './offscreen_canvas_distorted.ts';\nimport {mat3, mat4, quat, vec2, vec3, type vec4} from 'gl-matrix';\nimport {pixelsToTileUnits} from '../source/pixels_to_tile_units.ts';\n\nimport type {Size} from './image.ts';\nimport type {WorkerGlobalScopeInterface} from './web_worker.ts';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\nimport type {Event} from './evented.ts';\n\n/**\n * A 4x4 gl-matrix matrix backed by 32-bit floats.\n */\nexport type Mat4f32 = mat4 & Float32Array;\n/**\n * A 4x4 gl-matrix matrix backed by 64-bit floats.\n */\nexport type Mat4f64 = mat4 & Float64Array;\n\nexport const JSON_PREFIX = '__$json__:';\n\n/**\n * Ensures that a value is an `Error` instance.\n * If the value is already an `Error`, it is returned as-is.\n * Otherwise, a new `Error` is created from its string representation.\n */\nexport function ensureError(e: unknown): Error {\n    if (e instanceof Error) return e;\n    return new Error(typeof e === 'string' ? e : String(e));\n}\n\n/**\n * Returns a new 64 bit float vec4 of zeroes.\n */\nexport function createVec4f64(): vec4 { return new Float64Array(4); }\n/**\n * Returns a new 64 bit float vec3 of zeroes.\n */\nexport function createVec3f64(): vec3 { return new Float64Array(3); }\n/**\n * Returns a new 64 bit float mat4 of zeroes.\n */\nexport function createMat4f64(): Mat4f64 { return new Float64Array(16); }\n/**\n * Returns a new 32 bit float mat4 of zeroes.\n */\nexport function createMat4f32(): Mat4f32 { return new Float32Array(16); }\n/**\n * Returns a new 64 bit float mat4 set to identity.\n */\nexport function createIdentityMat4f64(): Mat4f64 {\n    const m: Mat4f64 = new Float64Array(16);\n    mat4.identity(m);\n    return m;\n}\n/**\n * Returns a new 32 bit float mat4 set to identity.\n */\nexport function createIdentityMat4f32(): Mat4f32 {\n    const m: Mat4f32 = new Float32Array(16);\n    mat4.identity(m);\n    return m;\n}\n\n/**\n * Returns a translation in tile units that correctly incorporates the view angle and the *-translate and *-translate-anchor properties.\n * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units.\n */\nexport function translatePosition(\n    transform: { bearingInRadians: number; zoom: number },\n    tile: { tileID: OverscaledTileID; tileSize: number },\n    translate: [number, number],\n    translateAnchor: 'map' | 'viewport',\n    inViewportPixelUnitsUnits: boolean = false\n): [number, number] {\n    if (!translate[0] && !translate[1]) return [0, 0];\n\n    const angle = inViewportPixelUnitsUnits ?\n        (translateAnchor === 'map' ? -transform.bearingInRadians : 0) :\n        (translateAnchor === 'viewport' ? transform.bearingInRadians : 0);\n\n    if (angle) {\n        const sinA = Math.sin(angle);\n        const cosA = Math.cos(angle);\n        translate = [\n            translate[0] * cosA - translate[1] * sinA,\n            translate[0] * sinA + translate[1] * cosA\n        ];\n    }\n\n    return [\n        inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], transform.zoom),\n        inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], transform.zoom)];\n}\n\n/**\n * Returns the signed distance between a point and a plane.\n * @param plane - The plane equation, in the form where the first three components are the normal and the fourth component is the plane's distance from origin along normal.\n * @param point - The point whose distance from plane is returned.\n * @returns Signed distance of the point from the plane. Positive distances are in the half space where the plane normal points to, negative otherwise.\n */\nexport function pointPlaneSignedDistance(\n    plane: vec4 | [number, number, number, number],\n    point: vec3 | [number, number, number]\n): number {\n    return plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3];\n}\n\n/**\n * Finds an intersection points of three planes. Returns `null` if no such (single) point exists.\n * The planes *must* be in Hessian normal form - their xyz components must form a unit vector.\n */\nexport function threePlaneIntersection(plane0: vec4, plane1: vec4, plane2: vec4): vec3 | null {\n    // https://mathworld.wolfram.com/Plane-PlaneIntersection.html\n    const det = mat3.determinant([\n        plane0[0], plane0[1], plane0[2],\n        plane1[0], plane1[1], plane1[2],\n        plane2[0], plane2[1], plane2[2]\n    ] as mat3);\n    if (det === 0) {\n        return null;\n    }\n    const cross12 = vec3.cross([], [plane1[0], plane1[1], plane1[2]], [plane2[0], plane2[1], plane2[2]]);\n    const cross20 = vec3.cross([], [plane2[0], plane2[1], plane2[2]], [plane0[0], plane0[1], plane0[2]]);\n    const cross01 = vec3.cross([], [plane0[0], plane0[1], plane0[2]], [plane1[0], plane1[1], plane1[2]]);\n    const sum = vec3.scale([], cross12, -plane0[3]);\n    vec3.add(sum, sum, vec3.scale([], cross20, -plane1[3]));\n    vec3.add(sum, sum, vec3.scale([], cross01, -plane2[3]));\n    vec3.scale(sum, sum, 1.0 / det);\n    return sum;\n}\n\n/**\n * Returns a parameter `t` such that the point obtained by\n * `origin + direction * t` lies on the given plane.\n * If the ray is parallel to the plane, returns null.\n * Returns a negative value if the ray is pointing away from the plane.\n * Direction does not need to be normalized.\n */\nexport function rayPlaneIntersection(origin: vec3, direction: vec3, plane: vec4): number | null {\n    const dotOriginPlane = origin[0] * plane[0] + origin[1] * plane[1] + origin[2] * plane[2];\n    const dotDirectionPlane = direction[0] * plane[0] + direction[1] * plane[1] + direction[2] * plane[2];\n    if (dotDirectionPlane === 0) {\n        return null;\n    }\n    return (-dotOriginPlane -plane[3]) / dotDirectionPlane;\n}\n\n/**\n * Solves a quadratic equation in the form ax^2 + bx + c = 0 and returns its roots in no particular order.\n * Returns null if the equation has no roots or if it has infinitely many roots.\n */\nexport function solveQuadratic(a: number, b: number, c: number): {\n    t0: number;\n    t1: number;\n} {\n    const d = b * b - 4 * a * c;\n    if (d < 0 || (a === 0 && b === 0)) {\n        return null;\n    }\n\n    // Uses a more precise solution from the book Ray Tracing Gems, chapter 7.\n    // https://www.realtimerendering.com/raytracinggems/rtg/index.html\n    const q = -0.5 * (b + Math.sign(b) * Math.sqrt(d));\n    if (Math.abs(q) > 1e-12) {\n        return {\n            t0: c / q,\n            t1: q / a\n        };\n    } else {\n        // Use the schoolbook way if q is too small\n        return {\n            t0: (-b + Math.sqrt(d)) * 0.5 / a,\n            t1: (-b + Math.sqrt(d)) * 0.5 / a\n        };\n    }\n}\n\n/**\n * Returns the angle in radians between two 2D vectors.\n * The angle is signed and describes how much the first vector would need to be be rotated clockwise\n * (assuming X is right and Y is down) so that it points in the same direction as the second vector.\n * @param vec1x - The X component of the first vector.\n * @param vec1y - The Y component of the first vector.\n * @param vec2x - The X component of the second vector.\n * @param vec2y - The Y component of the second vector.\n * @returns The signed angle between the two vectors, in range -PI..PI.\n */\nexport function angleToRotateBetweenVectors2D(vec1x: number, vec1y: number, vec2x: number, vec2y: number): number {\n    // Normalize both vectors\n    const length1 = Math.sqrt(vec1x * vec1x + vec1y * vec1y);\n    const length2 = Math.sqrt(vec2x * vec2x + vec2y * vec2y);\n    vec1x /= length1;\n    vec1y /= length1;\n    vec2x /= length2;\n    vec2y /= length2;\n    const dot = vec1x * vec2x + vec1y * vec2y;\n    const angle = Math.acos(dot);\n    // dot second vector with vector to the right of first (-vec1y, vec1x)\n    const isVec2RightOfVec1 = (-vec1y * vec2x + vec1x * vec2y) > 0;\n    if (isVec2RightOfVec1) {\n        return angle;\n    } else {\n        return -angle;\n    }\n}\n\n/**\n * For two angles in degrees, returns how many degrees to add to the first angle in order to obtain the second angle.\n * The returned difference value is always the shorted of the two - its absolute value is never greater than 180°.\n */\nexport function differenceOfAnglesDegrees(degreesA: number, degreesB: number): number {\n    const a = mod(degreesA, 360);\n    const b = mod(degreesB, 360);\n    const diff1 = b - a;\n    const diff2 = (b > a) ? (diff1 - 360) : (diff1 + 360);\n    if (Math.abs(diff1) < Math.abs(diff2)) {\n        return diff1;\n    } else {\n        return diff2;\n    }\n}\n\n/**\n * For two angles in radians, returns how many radians to add to the first angle in order to obtain the second angle.\n * The returned difference value is always the shorted of the two - its absolute value is never greater than PI.\n */\nexport function differenceOfAnglesRadians(degreesA: number, degreesB: number): number {\n    const a = mod(degreesA, Math.PI * 2);\n    const b = mod(degreesB, Math.PI * 2);\n    const diff1 = b - a;\n    const diff2 = (b > a) ? (diff1 - Math.PI * 2) : (diff1 + Math.PI * 2);\n    if (Math.abs(diff1) < Math.abs(diff2)) {\n        return diff1;\n    } else {\n        return diff2;\n    }\n}\n\n/**\n * When given two angles in degrees, returns the angular distance between them - the shorter one of the two possible arcs.\n */\nexport function distanceOfAnglesDegrees(degreesA: number, degreesB: number): number {\n    const a = mod(degreesA, 360);\n    const b = mod(degreesB, 360);\n    return Math.min(\n        Math.abs(a - b),\n        Math.abs(a - b + 360),\n        Math.abs(a - b - 360)\n    );\n}\n\n/**\n * When given two angles in radians, returns the angular distance between them - the shorter one of the two possible arcs.\n */\nexport function distanceOfAnglesRadians(radiansA: number, radiansB: number): number {\n    const a = mod(radiansA, Math.PI * 2);\n    const b = mod(radiansB, Math.PI * 2);\n    return Math.min(\n        Math.abs(a - b),\n        Math.abs(a - b + Math.PI * 2),\n        Math.abs(a - b - Math.PI * 2)\n    );\n}\n\n/**\n * Modulo function, as opposed to javascript's `%`, which is a remainder.\n * This functions will return positive values, even if the first operand is negative.\n */\nexport function mod(n: number, m: number): number {\n    return ((n % m) + m) % m;\n}\n\n/**\n * Takes a value in *old range*, linearly maps that range to *new range*, and returns the value in that new range.\n * Additionally, if the value is outside *old range*, it is clamped inside it.\n * Also works if one of the ranges is flipped (its `min` being larger than `max`).\n */\nexport function remapSaturate(value: number, oldRangeMin: number, oldRangeMax: number, newRangeMin: number, newRangeMax: number): number {\n    const inOldRange = clamp((value - oldRangeMin) / (oldRangeMax - oldRangeMin), 0.0, 1.0);\n    return lerp(newRangeMin, newRangeMax, inOldRange);\n}\n\n/**\n * Linearly interpolate between two values, similar to `mix` function from GLSL. No clamping is done.\n * @param a - The first value to interpolate. This value is returned when mix=0.\n * @param b - The second value to interpolate. This value is returned when mix=1.\n * @param mix - The interpolation factor. Range 0..1 interpolates between `a` and `b`, but values outside this range are also accepted.\n */\nexport function lerp(a: number, b: number, mix: number): number {\n    return a * (1.0 - mix) + b * mix;\n}\n\n/**\n * For a given collection of 2D points, returns their axis-aligned bounding box,\n * in the format [minX, minY, maxX, maxY].\n */\nexport function getAABB(points: Point[]): [number, number, number, number] {\n    let tlX = Infinity;\n    let tlY = Infinity;\n    let brX = -Infinity;\n    let brY = -Infinity;\n\n    for (const p of points) {\n        tlX = Math.min(tlX, p.x);\n        tlY = Math.min(tlY, p.y);\n        brX = Math.max(brX, p.x);\n        brY = Math.max(brY, p.y);\n    }\n\n    return [tlX, tlY, brX, brY];\n}\n\n/**\n * For a given set of tile ids, returns the edge tile ids for the bounding box.\n */\nexport function getEdgeTiles(tileIDs: OverscaledTileID[]): Set<OverscaledTileID> {\n    if (!tileIDs.length) return new Set<OverscaledTileID>();\n\n    // set a common zoom for calculation (highest zoom) to reproject all tiles to this same zoom\n    const targetZ = Math.max(...tileIDs.map(id => id.canonical.z));\n\n    // vars to store the min and max tile x/y coordinates for edge finding\n    let minX = Infinity, maxX = -Infinity;\n    let minY = Infinity, maxY = -Infinity;\n\n    // project all tiles to targetZ while maintaining the reference to the original tile\n    const projected: Array<{id: OverscaledTileID; x: number; y: number}> = [];\n    for (const id of tileIDs) {\n        const {x, y, z} = id.canonical;\n        const scale = Math.pow(2, targetZ - z);\n        const px = x * scale;\n        const py = y * scale;\n\n        projected.push({id, x: px, y: py});\n\n        if (px < minX) minX = px;\n        if (px > maxX) maxX = px;\n        if (py < minY) minY = py;\n        if (py > maxY) maxY = py;\n    }\n\n    // find edge tiles using the reprojected tile ids\n    const edgeTiles: Set<OverscaledTileID> = new Set<OverscaledTileID>();\n    for (const p of projected) {\n        if (p.x === minX || p.x === maxX || p.y === minY || p.y === maxY) {\n            edgeTiles.add(p.id);\n        }\n    }\n\n    return edgeTiles;\n}\n\n/**\n * Given a value `t` that varies between 0 and 1, return\n * an interpolation function that eases between 0 and 1 in a pleasing\n * cubic in-out fashion.\n */\nexport function easeCubicInOut(t: number): number {\n    if (t <= 0) return 0;\n    if (t >= 1) return 1;\n    const t2 = t * t,\n        t3 = t2 * t;\n    return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75);\n}\n\n/**\n * Given given (x, y), (x1, y1) control points for a bezier curve,\n * return a function that interpolates along that curve.\n *\n * @param p1x - control point 1 x coordinate\n * @param p1y - control point 1 y coordinate\n * @param p2x - control point 2 x coordinate\n * @param p2y - control point 2 y coordinate\n */\nexport function bezier(p1x: number, p1y: number, p2x: number, p2y: number): (t: number) => number {\n    return unitBezierFactory(p1x, p1y, p2x, p2y);\n}\n\n/**\n * A default bezier-curve powered easing function with\n * control points (0.25, 0.1) and (0.25, 1)\n */\nexport const defaultEasing: (t: number) => number = bezier(0.25, 0.1, 0.25, 1);\n\n/**\n * constrain n to the given range via min + max\n *\n * @param n - value\n * @param min - the minimum value to be returned\n * @param max - the maximum value to be returned\n * @returns the clamped value\n */\nexport function clamp(n: number, min: number, max: number): number {\n    return Math.min(max, Math.max(min, n));\n}\n\n/**\n * constrain n to the given range, excluding the minimum, via modular arithmetic\n *\n * @param n - value\n * @param min - the minimum value to be returned, exclusive\n * @param max - the maximum value to be returned, inclusive\n * @returns constrained number\n */\nexport function wrap(n: number, min: number, max: number): number {\n    const d = max - min;\n    const w = ((n - min) % d + d) % d + min;\n    return (w === min) ? max : w;\n}\n\n/**\n * Compute the difference between the keys in one object and the keys\n * in another object.\n *\n * @returns keys difference\n */\nexport function keysDifference<S, T>(\n    obj: {[key: string]: S},\n    other: {[key: string]: T}\n): string[] {\n    const difference = [];\n    for (const i in obj) {\n        if (!(i in other)) {\n            difference.push(i);\n        }\n    }\n    return difference;\n}\n\n/**\n * Given a destination object and optionally many source objects,\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param dest - destination object\n * @param sources - sources from which properties are pulled\n */\nexport function extend<T extends {}, U>(dest: T, source: U): T & U;\nexport function extend<T extends {}, U, V>(dest: T, source1: U, source2: V): T & U & V;\nexport function extend<T extends {}, U, V, W>(dest: T, source1: U, source2: V, source3: W): T & U & V & W;\nexport function extend(dest: object, ...sources: any[]): any;\nexport function extend(dest: object, ...sources: any[]): any {\n    for (const src of sources) {\n        for (const k in src) {\n            dest[k] = src[k];\n        }\n    }\n    return dest;\n}\n\n// See https://stackoverflow.com/questions/49401866/all-possible-keys-of-an-union-type\ntype KeysOfUnion<T> = T extends T ? keyof T: never;\n\n/**\n * Given an object and a number of properties as strings, return version\n * of that object with only those properties.\n *\n * @param src - the object\n * @param properties - an array of property names chosen\n * to appear on the resulting object.\n * @returns object with limited properties.\n * @example\n * ```ts\n * let foo = { name: 'Charlie', age: 10 };\n * let justName = pick(foo, ['name']); // justName = { name: 'Charlie' }\n * ```\n */\nexport function pick<T extends object>(src: T, properties: Array<KeysOfUnion<T>>): Partial<T> {\n    const result: Partial<T> = {};\n    for (const k of properties) {\n        if (k in src) {\n            result[k] = src[k];\n        }\n    }\n    return result;\n}\n\nlet id = 1;\n\n/**\n * Return a unique numeric id, starting at 1 and incrementing with\n * each call.\n *\n * @returns unique numeric id.\n */\nexport function uniqueId(): number {\n    return id++;\n}\n\n/**\n * Return whether a given value is a power of two\n */\nexport function isPowerOfTwo(value: number): boolean {\n    return (Math.log(value) / Math.LN2) % 1 === 0;\n}\n\n/**\n * Return the next power of two, or the input value if already a power of two\n */\nexport function nextPowerOfTwo(value: number): number {\n    if (value <= 1) return 1;\n    return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));\n}\n\n/**\n * Computes scaling from zoom level.\n */\nexport function zoomScale(zoom: number): number { return Math.pow(2, zoom); }\n\n/**\n * Computes zoom level from scaling.\n */\nexport function scaleZoom(scale: number): number { return Math.log(scale) / Math.LN2; }\n\n/**\n * Evaluates the snapped zoom level based on zoomSnap. If zoomSnap is 0 or less, the zoom level is returned unchanged.\n * If delta is provided, it performs directional snapping (ceil for zoom-in, floor for zoom-out).\n * @param zoom - The input zoom level\n * @param zoomSnap - The grid interval to snap to, e.g. 1.0 for 1.0 zoom levels, 0.5 for 0.5 zoom levels, etc.\n * @param delta - Optional scroll delta or direction. If positive, snaps up; if negative, snaps down.\n * @returns The snapped zoom level\n */\nexport function evaluateZoomSnap(zoom: number, zoomSnap: number, delta?: number): number {\n    if (zoomSnap <= 0) return zoom;\n    const inv = 1 / zoomSnap;\n    if (delta === undefined || Math.abs(delta) < 1e-10) {\n        return Math.round(zoom * inv) / inv;\n    }\n    return (delta > 0 ? Math.ceil(zoom * inv - 1e-9) : Math.floor(zoom * inv + 1e-10)) / inv;\n}\n\n/**\n * Create an object by mapping all the values of an existing object while\n * preserving their keys.\n */\nexport function mapObject<Input extends object, Output>(\n    input: Input,\n    iterator: (value: Input[keyof Input], key: Extract<keyof Input, string>, input: Input) => Output,\n    context?: unknown\n): {[K in keyof Input]: Output} {\n    const output = {} as {[K in keyof Input]: Output};\n    for (const key in input) {\n        output[key] = iterator.call(context || this, input[key], key, input);\n    }\n    return output;\n}\n\n/**\n * Create an object by filtering out values of an existing object.\n */\nexport function filterObject(input: any, iterator: Function, context?: any): any {\n    const output = {};\n    for (const key in input) {\n        if (iterator.call(context || this, input[key], key, input)) {\n            output[key] = input[key];\n        }\n    }\n    return output;\n}\n\n/**\n * Deeply compares two object literals.\n * @param a - first object literal to be compared\n * @param b - second object literal to be compared\n * @returns true if the two object literals are deeply equal, false otherwise\n */\nexport function deepEqual(a?: unknown | null, b?: unknown | null): 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\n/**\n * Deeply clones two objects.\n */\nexport function clone<T>(input: T): T {\n    if (Array.isArray(input)) {\n        return input.map(clone) as any as T;\n    } else if (typeof input === 'object' && input) {\n        return mapObject(input, clone) as T;\n    } else {\n        return input;\n    }\n}\n\n/**\n * Check if two arrays have at least one common element.\n */\nexport function arraysIntersect<T>(a: T[], b: T[]): boolean {\n    for (const element of a) {\n        if (b.includes(element)) return true;\n    }\n    return false;\n}\n\n/**\n * Print a warning message to the console and ensure duplicate warning messages\n * are not printed.\n */\nconst warnOnceHistory: {[key: string]: boolean} = {};\n\nexport function warnOnce(message: string): void {\n    if (!warnOnceHistory[message]) {\n        // console isn't defined in some WebWorkers, see #2558\n        if (typeof console !== 'undefined') console.warn(message);\n        warnOnceHistory[message] = true;\n    }\n}\n\n/**\n * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order\n *\n * @returns true for a counter clockwise set of points\n */\n// https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/\nexport function isCounterClockwise(a: Point, b: Point, c: Point): boolean {\n    return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);\n}\n\n/**\n * For two lines a and b in 2d space, defined by any two points along the lines,\n * find the intersection point, or return null if the lines are parallel\n *\n * @param a1 - First point on line a\n * @param a2 - Second point on line a\n * @param b1 - First point on line b\n * @param b2 - Second point on line b\n *\n * @returns the intersection point of the two lines or null if they are parallel\n */\nexport function findLineIntersection(a1: Point, a2: Point, b1: Point, b2: Point): Point | null {\n    const aDeltaY = a2.y - a1.y;\n    const aDeltaX = a2.x - a1.x;\n    const bDeltaY = b2.y - b1.y;\n    const bDeltaX = b2.x - b1.x;\n\n    const denominator = (bDeltaY * aDeltaX) - (bDeltaX * aDeltaY);\n\n    if (denominator === 0) {\n        // Lines are parallel\n        return null;\n    }\n\n    const originDeltaY = a1.y - b1.y;\n    const originDeltaX = a1.x - b1.x;\n    const aInterpolation = (bDeltaX * originDeltaY - bDeltaY * originDeltaX) / denominator;\n\n    // Find intersection by projecting out from origin of first segment\n    return new Point(a1.x + (aInterpolation * aDeltaX), a1.y + (aInterpolation * aDeltaY));\n}\n\n/**\n * Converts spherical coordinates to cartesian coordinates.\n *\n * @param spherical - Spherical coordinates, in [radial, azimuthal, polar]\n * @returns cartesian coordinates in [x, y, z]\n */\nexport function sphericalToCartesian([r, azimuthal, polar]: [number, number, number]): vec3 {\n    // We abstract \"north\"/\"up\" (compass-wise) to be 0° when really this is 90° (π/2):\n    // correct for that here\n    azimuthal += 90;\n\n    // Convert azimuthal and polar angles to radians\n    azimuthal *= Math.PI / 180;\n    polar *= Math.PI / 180;\n\n    return [\n        r * Math.cos(azimuthal) * Math.sin(polar),\n        r * Math.sin(azimuthal) * Math.sin(polar),\n        r * Math.cos(polar)\n    ];\n}\n\n/**\n *  Returns true if the when run in the web-worker context.\n *\n * @returns `true` if the when run in the web-worker context.\n */\nexport function isWorker(self: any): self is WorkerGlobalScopeInterface {\n    // @ts-ignore\n    return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope;\n}\n\n/**\n * Parses data from 'Cache-Control' headers.\n *\n * @param cacheControl - Value of 'Cache-Control' header\n * @returns object containing parsed header info.\n */\n\nexport function parseCacheControl(cacheControl: string): any {\n    // Taken from [Wreck](https://github.com/hapijs/wreck)\n    const re = /(?:^|(?:\\s*\\,\\s*))([^\\x00-\\x20\\(\\)<>@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)(?:\\=(?:([^\\x00-\\x20\\(\\)<>@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)|(?:\\\"((?:[^\"\\\\]|\\\\.)*)\\\")))?/g;\n\n    const header = {};\n    cacheControl.replace(re, ($0, $1, $2, $3) => {\n        const value = $2 || $3;\n        header[$1] = value ? value.toLowerCase() : true;\n        return '';\n    });\n\n    if (header['max-age']) {\n        const maxAge = parseInt(header['max-age'], 10);\n        if (isNaN(maxAge)) delete header['max-age'];\n        else header['max-age'] = maxAge;\n    }\n\n    return header;\n}\n\nlet _isSafari = null;\n\n/**\n * Returns true when run in WebKit derived browsers.\n * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to\n * transfer data between WebWorkers and the main thread.\n * https://github.com/mapbox/mapbox-gl-js/issues/8771\n *\n * This should be removed once the underlying Safari issue is fixed.\n *\n * @param scope - Since this function is used both on the main thread and WebWorker context,\n *      let the calling scope pass in the global scope object.\n * @returns `true` when run in WebKit derived browsers.\n */\nexport function isSafari(scope: any): boolean {\n    if (_isSafari == null) {\n        const userAgent = scope.navigator ? scope.navigator.userAgent : null;\n        _isSafari = !!scope.safari ||\n        !!(userAgent && (/\\b(iPad|iPhone|iPod)\\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome'))));\n    }\n    return _isSafari;\n}\n\n// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem\n//Unicode compliant base64 encoder for strings\nexport function b64EncodeUnicode(str: string): string {\n    return btoa(\n        encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n            (match, p1) => {\n                return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line\n            }\n        )\n    );\n}\n\n// Unicode compliant decoder for base64-encoded strings\nexport function b64DecodeUnicode(str: string): string {\n    return decodeURIComponent(atob(str).split('').map((c) => {\n        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line\n    }).join(''));\n}\n\nexport function isImageBitmap(image: any): image is ImageBitmap {\n    return typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap;\n}\n\n/**\n * Converts an ArrayBuffer to an ImageBitmap.\n *\n * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work\n * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting\n * ArrayBuffers.\n *\n * @param data - Data to convert\n * @returns - A  promise resolved when the conversion is finished\n */\nexport const arrayBufferToImageBitmap = async (data: ArrayBuffer, options?: ImageBitmapOptions): Promise<ImageBitmap> => {\n    const blob: Blob = new Blob([new Uint8Array(data)], {type: 'image/png'});\n    try {\n        return createImageBitmap(blob, options);\n    } catch (e) {\n        throw new Error(`Could not load image because of ${ensureError(e).message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`);\n    }\n};\n\nconst transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';\n\n/**\n * Converts an ArrayBuffer to an HTMLImageElement.\n *\n * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work\n * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting\n * ArrayBuffers.\n *\n * @param data - Data to convert\n * @returns - A promise resolved when the conversion is finished\n */\nexport const arrayBufferToImage = (data: ArrayBuffer): Promise<HTMLImageElement> => {\n    return new Promise((resolve, reject) => {\n        const img: HTMLImageElement = new Image();\n        img.onload = () => {\n            resolve(img);\n            URL.revokeObjectURL(img.src);\n            // prevent image dataURI memory leak in Safari;\n            // but don't free the image immediately because it might be uploaded in the next frame\n            // https://github.com/mapbox/mapbox-gl-js/issues/10226\n            img.onload = null;\n            window.requestAnimationFrame(() => img.src = transparentPngUrl);\n        };\n        img.onerror = () => reject(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.'));\n        const blob: Blob = new Blob([new Uint8Array(data)], {type: 'image/png'});\n        img.src = URL.createObjectURL(blob);\n    });\n};\n\n/**\n * Computes the webcodecs VideoFrame API options to select a rectangle out of\n * an image and write it into the destination rectangle.\n *\n * Rect (x/y/width/height) select the overlapping rectangle from the source image\n * and layout (offset/stride) write that overlapping rectangle to the correct place\n * in the destination image.\n *\n * Offset is the byte offset in the dest image that the first pixel appears at\n * and stride is the number of bytes to the start of the next row:\n * ┌───────────┐\n * │  dest     │\n * │       ┌───┼───────┐\n * │offset→│▓▓▓│ source│\n * │       │▓▓▓│       │\n * │       └───┼───────┘\n * │stride ⇠╌╌╌│\n * │╌╌╌╌╌╌→    │\n * └───────────┘\n *\n * @param image - source image containing a width and height attribute\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns the layout and rect options to pass into VideoFrame API\n */\nfunction computeVideoFrameParameters(image: Size, x: number, y: number, width: number, height: number): VideoFrameCopyToOptions {\n    const destRowOffset = Math.max(-x, 0) * 4;\n    const firstSourceRow = Math.max(0, y);\n    const firstDestRow = firstSourceRow - y;\n    const offset = firstDestRow * width * 4 + destRowOffset;\n    const stride = width * 4;\n\n    const sourceLeft = Math.max(0, x);\n    const sourceTop = Math.max(0, y);\n    const sourceRight = Math.min(image.width, x + width);\n    const sourceBottom = Math.min(image.height, y + height);\n    return {\n        rect: {\n            x: sourceLeft,\n            y: sourceTop,\n            width: sourceRight - sourceLeft,\n            height: sourceBottom - sourceTop\n        },\n        layout: [{offset, stride}]\n    };\n}\n\n/**\n * Reads pixels from an ImageBitmap/Image/canvas using webcodec VideoFrame API.\n *\n * @param data - image, imagebitmap, or canvas to parse\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred\n */\nexport async function readImageUsingVideoFrame(\n    image: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas,\n    x: number, y: number, width: number, height: number\n): Promise<Uint8ClampedArray> {\n    if (typeof VideoFrame === 'undefined') {\n        throw new Error('VideoFrame not supported');\n    }\n    const frame = new VideoFrame(image, {timestamp: 0});\n    try {\n        const format = frame?.format;\n        if (!format || !(format.startsWith('BGR') || format.startsWith('RGB'))) {\n            throw new Error(`Unrecognized format ${format}`);\n        }\n        const swapBR = format.startsWith('BGR');\n        const result = new Uint8ClampedArray(width * height * 4);\n        await frame.copyTo(result, computeVideoFrameParameters(image, x, y, width, height));\n        if (swapBR) {\n            for (let i = 0; i < result.length; i += 4) {\n                const tmp = result[i];\n                result[i] = result[i + 2];\n                result[i + 2] = tmp;\n            }\n        }\n        return result;\n    } finally {\n        frame.close();\n    }\n}\n\nlet offscreenCanvas: OffscreenCanvas;\nlet offscreenCanvasContext: OffscreenCanvasRenderingContext2D;\n\n/**\n * Reads pixels from an ImageBitmap/Image/canvas using OffscreenCanvas\n *\n * @param data - image, imagebitmap, or canvas to parse\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred\n */\nexport function readImageDataUsingOffscreenCanvas(\n    imgBitmap: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas,\n    x: number, y: number, width: number, height: number\n): Uint8ClampedArray {\n    const origWidth = imgBitmap.width;\n    const origHeight = imgBitmap.height;\n    // Lazily initialize OffscreenCanvas\n    if (!offscreenCanvas || !offscreenCanvasContext) {\n        // Dem tiles are typically 256x256\n        offscreenCanvas = new OffscreenCanvas(origWidth, origHeight);\n        offscreenCanvasContext = offscreenCanvas.getContext('2d', {willReadFrequently: true});\n    }\n\n    offscreenCanvas.width = origWidth;\n    offscreenCanvas.height = origHeight;\n\n    offscreenCanvasContext.drawImage(imgBitmap, 0, 0, origWidth, origHeight);\n    const imgData = offscreenCanvasContext.getImageData(x, y, width, height);\n    offscreenCanvasContext.clearRect(0, 0, origWidth, origHeight);\n    return imgData.data;\n}\n\n/**\n * Reads RGBA pixels from an preferring OffscreenCanvas, but falling back to VideoFrame if supported and\n * the browser is mangling OffscreenCanvas getImageData results.\n *\n * @param data - image, imagebitmap, or canvas to parse\n * @param x - top-left x coordinate to read from the image\n * @param y - top-left y coordinate to read from the image\n * @param width - width of the rectangle to read from the image\n * @param height - height of the rectangle to read from the image\n * @returns a promise containing the parsed RGBA pixel values of the image\n */\nexport async function getImageData(\n    image: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas,\n    x: number, y: number, width: number, height: number\n): Promise<Uint8ClampedArray> {\n    if (isOffscreenCanvasDistorted()) {\n        try {\n            return await readImageUsingVideoFrame(image, x, y, width, height);\n        } catch {\n            // fall back to OffscreenCanvas\n        }\n    }\n    return readImageDataUsingOffscreenCanvas(image, x, y, width, height);\n}\n\n/**\n * Allows to unsubscribe from events without the need to store the method reference.\n */\nexport interface Subscription {\n    /**\n     * Unsubscribes from the event.\n     */\n    unsubscribe(): void;\n}\n\nexport interface Subscriber {\n    addEventListener: typeof window.addEventListener;\n    removeEventListener: typeof window.removeEventListener;\n}\n\n/**\n * This method is used in order to register an event listener using a lambda function.\n * The return value will allow unsubscribing from the event, without the need to store the method reference.\n * @param target - The target\n * @param message - The message\n * @param listener - The listener\n * @param options - The options\n * @returns a subscription object that can be used to unsubscribe from the event\n */\nexport function subscribe(target: Subscriber, message: keyof WindowEventMap, listener: (...args: any) => void, options: boolean | AddEventListenerOptions): Subscription {\n    target.addEventListener(message, listener, options);\n    return {\n        unsubscribe: () => {\n            target.removeEventListener(message, listener, options);\n        }\n    };\n}\n\n/**\n * This method converts degrees to radians.\n * The return value is the radian value.\n * @param degrees - The number of degrees\n * @returns radians\n */\nexport function degreesToRadians(degrees: number): number {\n    return degrees * Math.PI / 180;\n}\n\n/**\n * This method converts radians to degrees.\n * The return value is the degrees value.\n * @param degrees - The number of radians\n * @returns degrees\n */\nexport function radiansToDegrees(degrees: number): number {\n    return degrees / Math.PI * 180;\n}\n\nexport type RollPitchBearing = {\n    roll: number;\n    pitch: number;\n    bearing: number;\n};\n\nexport function rollPitchBearingEqual(a: RollPitchBearing, b: RollPitchBearing): boolean {\n    return a.roll == b.roll && a.pitch == b.pitch && a.bearing == b.bearing;\n}\n\n/**\n * This method converts a rotation quaternion to roll, pitch, and bearing angles in degrees.\n * @param rotation - The rotation quaternion\n * @returns roll, pitch, and bearing angles in degrees\n */\nexport function getRollPitchBearing(rotation: quat): RollPitchBearing {\n    const m: mat3 = new Float64Array(9);\n    mat3.fromQuat(m, rotation);\n\n    const xAngle = radiansToDegrees(-Math.asin(clamp(m[2], -1, 1)));\n    let roll: number;\n    let bearing: number;\n    if (Math.hypot(m[5], m[8]) < 1.0e-3) {\n        roll = 0.0;\n        bearing = -radiansToDegrees(Math.atan2(m[3], m[4]));\n    } else {\n        roll = radiansToDegrees((m[5] === 0.0 && m[8] === 0.0) ? 0.0 :  Math.atan2(m[5], m[8]));\n        bearing = radiansToDegrees((m[1] === 0.0 && m[0] === 0.0) ? 0.0 : Math.atan2(m[1], m[0]));\n    }\n\n    return {roll, pitch: xAngle + 90.0, bearing};\n}\n\nexport function getAngleDelta(lastPoint: Point, currentPoint: Point, center: Point): number {\n    const pointVect = vec2.fromValues(currentPoint.x - center.x, currentPoint.y - center.y);\n    const lastPointVec = vec2.fromValues(lastPoint.x - center.x, lastPoint.y - center.y);\n\n    const crossProduct = pointVect[0] * lastPointVec[1] - pointVect[1] * lastPointVec[0];\n    const angleRadians = Math.atan2(crossProduct, vec2.dot(pointVect, lastPointVec));\n    return radiansToDegrees(angleRadians);\n}\n\n/**\n * This method converts roll, pitch, and bearing angles in degrees to a rotation quaternion.\n * @param roll - Roll angle in degrees\n * @param pitch - Pitch angle in degrees\n * @param bearing - Bearing angle in degrees\n * @returns The rotation quaternion\n */\nexport function rollPitchBearingToQuat(roll: number, pitch: number, bearing: number): quat {\n    const rotation: quat = new Float64Array(4);\n    quat.fromEuler(rotation, roll, pitch - 90.0, bearing);\n    return rotation;\n}\n\n/**\n * Makes optional keys required and add the the undefined type.\n *\n * ```\n * interface Test {\n *  foo: number;\n *  bar?: number;\n *  baz: number | undefined;\n * }\n *\n * Complete<Test> {\n *  foo: number;\n *  bar: number | undefined;\n *  baz: number | undefined;\n * }\n *\n * ```\n *\n * See https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585\n */\n\nexport type Complete<T> = {\n    [P in keyof Required<T>]: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : (T[P] | undefined);\n};\n\n/**\n * A helper to allow require of at least one property\n */\nexport type RequireAtLeastOne<T> = { [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>; }[keyof T];\n\n/**\n* A helper to allow require exactly one one property\n */\nexport type ExactlyOne<T, Keys extends keyof T = keyof T> = {\n    [K in Keys]: Required<Pick<T, K>> & { [P in Exclude<Keys, K>]?: never }\n}[Keys];\n\nexport type TileJSON = {\n    tilejson: '2.2.0' | '2.1.0' | '2.0.1' | '2.0.0' | '1.0.0';\n    name?: string;\n    description?: string;\n    version?: string;\n    attribution?: string;\n    template?: string;\n    tiles: string[];\n    grids?: string[];\n    data?: string[];\n    minzoom?: number;\n    maxzoom?: number;\n    bounds?: [number, number, number, number];\n    center?: [number, number, number];\n    vector_layers: [{id: string}]; // this is partial but enough for what we need\n    sparse?: boolean; // not in the TileJSON spec, read by a vector source as its sparse option\n};\n\n/**\n * The maximum world tile zoom (Z).\n * In other words, the upper bound supported for tile zoom.\n */\nexport const MAX_TILE_ZOOM = 25;\n\n/**\n * The minimum world tile zoom (Z).\n * In other words, the lower bound supported for tile zoom.\n */\nexport const MIN_TILE_ZOOM = 0;\n\nexport const MAX_VALID_LATITUDE = 85.051129;\n\nconst touchableEvents = {\n    touchstart: true,\n    touchmove: true,\n    touchmoveWindow: true,\n    touchend: true,\n    touchcancel: true\n};\n\nconst pointableEvents = {\n    dblclick: true,\n    click: true,\n    mouseover: true,\n    mouseout: true,\n    mousedown: true,\n    mousemove: true,\n    mousemoveWindow: true,\n    mouseup: true,\n    mouseupWindow: true,\n    contextmenu: true,\n    wheel: true\n};\n\nexport function isTouchableEvent(event: Event, eventType: string): event is TouchEvent {\n    return touchableEvents[eventType] && 'touches' in event;\n}\n\n/**\n * Checks if an event is a pointable event (mouse or wheel event).\n * Uses the event target's window context for cross-window support.\n */\nexport function isPointableEvent(event: Event, eventType: string): event is MouseEvent {\n    if (!pointableEvents[eventType]) return false;\n\n    // Get the window context from the event target to use the correct constructor.\n    const domEvent = event as globalThis.Event;\n    const target = domEvent?.target as Element | null;\n    const targetWindow = target?.ownerDocument?.defaultView || window;\n    return domEvent instanceof targetWindow.MouseEvent || domEvent instanceof targetWindow.WheelEvent;\n}\n\nexport function isTouchableOrPointableType(eventType: string): boolean {\n    return touchableEvents[eventType] || pointableEvents[eventType];\n}\n", "/**\n * An error message to use when an operation is aborted\n */\nexport const ABORT_ERROR = 'AbortError';\n\nexport class AbortError extends Error {\n    name: string = ABORT_ERROR;\n\n    constructor(messageOrError: string | Error = ABORT_ERROR) {\n        super(messageOrError instanceof Error ? messageOrError.message : messageOrError);\n        if (messageOrError instanceof Error && messageOrError.stack) {\n            this.stack = messageOrError.stack;\n        }\n    }\n}\n\n/**\n * Check if an error is an abort error\n * @param error - An error object\n * @returns - true if the error is an abort error\n */\nexport function isAbortError(error: unknown): boolean {\n    return error instanceof Error && error.name === ABORT_ERROR;\n}\n\n/**\n * Throws an AbortError if the provided abort signal has already been aborted.\n *\n * @param signal - The abort signal to check.\n * @throws AbortError If the signal is aborted.\n */\nexport function throwIfAborted(signal: AbortSignal): void {\n    if (signal.aborted) {\n        throw new AbortError(signal.reason);\n    }\n}\n", "import {AbortError} from './abort_error.ts';\nimport {offscreenCanvasSupported} from './offscreen_canvas_supported.ts';\nimport {isOffscreenCanvasDistorted} from './offscreen_canvas_distorted.ts';\nimport {subscribe} from './util.ts';\n\nlet linkEl;\n\nlet reducedMotionQuery: MediaQueryList;\nlet reducedMotionOverride: boolean | undefined;\n\n/** */\nexport const browser = {\n    /**\n     * Schedules a callback to be invoked on the next animation frame.\n     * @param abortController - Controller to abort the scheduled frame.\n     * @param fn - Callback to invoke with the paint start timestamp.\n     * @param reject - Callback to invoke if the frame is aborted.\n     * @param targetWindow - Optional window to use for requestAnimationFrame.\n     *   When the map is rendered in a popup window or iframe, pass the owning\n     *   window to ensure animation frames continue even when the main window\n     *   is not focused.\n     */\n    frame(abortController: AbortController, fn: (paintStartTimestamp: number) => void, reject: (error: Error) => void, targetWindow?: Window): void {\n        const win = targetWindow || window;\n        const frameId = win.requestAnimationFrame((paintStartTimestamp)=>{\n            unsubscribe();\n            fn(paintStartTimestamp);\n        });\n\n        const {unsubscribe} = subscribe(abortController.signal, 'abort', () => {\n            unsubscribe();\n            win.cancelAnimationFrame(frameId);\n            reject(new AbortError(abortController.signal.reason));\n        }, false);\n    },\n\n    /**\n     * Returns a promise that resolves on the next animation frame.\n     * @param abortController - Controller to abort the scheduled frame.\n     * @param targetWindow - Optional window to use for requestAnimationFrame.\n     * @see {@link browser.frame}\n     */\n    frameAsync(abortController: AbortController, targetWindow?: Window): Promise<number> {\n        return new Promise((resolve, reject) => {\n            this.frame(abortController, resolve, reject, targetWindow);\n        });\n    },\n\n    getImageData(img:  HTMLImageElement | ImageBitmap, padding: number = 0): ImageData {\n        const context = this.getImageCanvasContext(img);\n        return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding);\n    },\n\n    /**\n     * Draws an image into a 2D canvas whose pixels can be read back cheaply. An `OffscreenCanvas`\n     * is used where the browser has one that reads back faithfully: drawing a GPU-backed\n     * `ImageBitmap` into a document canvas opened with `willReadFrequently` stalls the main thread\n     * for tens of milliseconds on GPU-accelerated browsers, an `OffscreenCanvas` does not.\n     */\n    getImageCanvasContext(img: HTMLImageElement | ImageBitmap): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D {\n        let context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null;\n        if (offscreenCanvasSupported() && !isOffscreenCanvasDistorted()) {\n            context = new OffscreenCanvas(img.width, img.height).getContext('2d', {willReadFrequently: true});\n        } else {\n            const canvas = window.document.createElement('canvas');\n            canvas.width = img.width;\n            canvas.height = img.height;\n            context = canvas.getContext('2d', {willReadFrequently: true});\n        }\n        if (!context) {\n            throw new Error('failed to create canvas 2d context');\n        }\n        context.drawImage(img, 0, 0, img.width, img.height);\n        return context;\n    },\n\n    resolveURL(path: string): string {\n        linkEl ||= document.createElement('a');\n        linkEl.href = path;\n        return linkEl.href;\n    },\n\n    get hardwareConcurrency(): number {\n        return (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4;\n    },\n\n    get prefersReducedMotion(): boolean {\n        if (reducedMotionOverride !== undefined) return reducedMotionOverride;\n        // In case your test crashes when checking matchMedia, call setMatchMedia from 'src/util/test/util'\n        if (!matchMedia) return false;\n        //Lazily initialize media query\n        reducedMotionQuery ??= matchMedia('(prefers-reduced-motion: reduce)');\n        return reducedMotionQuery.matches;\n    },\n\n    set prefersReducedMotion(value: boolean) {\n        reducedMotionOverride = value;\n    }\n};\n", "/**\n * Manages time flow with optional freezing capability for deterministic rendering.\n */\nclass TimeManager {\n    private _frozenAt: number | null = null;\n\n    /**\n     * Gets the current time, either real or frozen.\n     * @returns Current time in milliseconds\n     */\n    getCurrentTime(): number {\n        return this._frozenAt !== null ? this._frozenAt : performance.now();\n    }\n\n    /**\n     * Sets time at a specific timestamp.\n     * @param timestamp - Time in milliseconds to set\n     */\n    setNow(timestamp: number): void {\n        this._frozenAt = timestamp;\n    }\n\n    /**\n     * Restores normal time flow.\n     */\n    restoreNow(): void {\n        this._frozenAt = null;\n    }\n\n    /**\n     * Returns whether time is currently frozen.\n     * @returns True if time is frozen, false otherwise\n     */\n    isFrozen(): boolean {\n        return this._frozenAt !== null;\n    }\n}\n\nconst timeManager = new TimeManager();\n\n/**\n * Returns the current time in milliseconds.\n * When time is frozen via setNow(), returns the frozen timestamp.\n * Otherwise returns real browser time via performance.now().\n *\n * @returns Current time in milliseconds\n * @example\n * ```ts\n * // Measure elapsed time\n * const start = maplibregl.now();\n * // ... later ...\n * const elapsed = maplibregl.now() - start;\n *\n * // During frozen time\n * maplibregl.setNow(16.67);\n * console.log(maplibregl.now()); // 16.67\n * maplibregl.restoreNow();\n * console.log(maplibregl.now()); // real time\n * ```\n */\nexport function now(): number {\n    return timeManager.getCurrentTime();\n}\n\n/**\n * Freezes time at a specific timestamp for deterministic rendering.\n * Useful for frame-by-frame video capture where each frame needs\n * a consistent time value.\n *\n * @param timestamp - Time in milliseconds to freeze at\n * @example\n * ```ts\n * // Freeze time for video export at 60fps\n * setNow(0);           // First frame\n * // ... render frame ...\n * setNow(16.67);       // Second frame\n * // ... render frame ...\n * setNow(33.34);       // Third frame\n * // ... done ...\n * restoreNow();        // Resume normal time\n * ```\n */\nexport function setNow(timestamp: number): void {\n    timeManager.setNow(timestamp);\n}\n\n/**\n * Restores normal time flow after freezing with setNow().\n * Call this after finishing deterministic rendering operations.\n *\n * @example\n * ```ts\n * // After video export, resume normal time\n * setNow(0);\n * // ... export frames ...\n * restoreNow(); // Map animations resume normally\n * ```\n */\nexport function restoreNow(): void {\n    timeManager.restoreNow();\n}\n\n/**\n * Returns whether time is currently frozen.\n * @returns True if time is frozen via setNow(), false otherwise\n * @example\n * ```ts\n * setNow(1000);\n * console.log(isTimeFrozen()); // true\n * restoreNow();\n * console.log(isTimeFrozen()); // false\n * ```\n */\nexport function isTimeFrozen(): boolean {\n    return timeManager.isFrozen();\n}", "import Point from '@mapbox/point-geometry';\n\ntype ScaleReturnValue = {\n    x: number;\n    y: number;\n    boundingClientRect: DOMRect;\n};\n\nconst HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n\nconst ALLOWED_TAGS = new Set([\n    'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'code', 'del', 'div', 'em', 'i', 'img', 'ins', 'kbd', 'li',\n    'mark', 'ol', 'p', 'q', 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'ul', 'var', 'wbr'\n]);\n\nconst ALLOWED_ATTRIBUTES = new Set([\n    'alt', 'class', 'datetime', 'dir', 'height', 'href', 'hreflang', 'lang', 'referrerpolicy', 'rel', 'role',\n    'src', 'target', 'title', 'translate', 'type', 'width'\n]);\n\nconst URL_ATTRIBUTES = new Set(['href', 'src']);\n\nconst ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);\n\n/**\n * Relative URLs have to resolve against something before their protocol can be read. Only the protocol of the\n * result is used, so the base never leaks into the sanitized markup.\n */\nconst RELATIVE_URL_BASE = 'https://maplibre.invalid/';\n\ntype ElementInternals = {\n    /** Only ever called with a name `getAttributeNames` just returned, so the attribute is always there. */\n    getAttribute: (this: Element, qualifiedName: string) => string;\n    getAttributeNames: Element['getAttributeNames'];\n    querySelectorAll: (this: Element, selectors: string) => NodeListOf<Element>;\n    remove: Element['remove'];\n    removeAttribute: Element['removeAttribute'];\n    localName: (this: Element) => string;\n    namespaceURI: (this: Element) => string;\n};\n\nlet elementInternals: ElementInternals;\n\n/**\n * The `Element` members the sanitizer uses, read off the prototype rather than off the element it is looking at.\n * A form control named `children`, `remove` or `localName` shadows the same-named property of its own form element,\n * which would otherwise let untrusted markup pick what the sanitizer walking that tree sees.\n *\n * They are read on first use rather than when this module is loaded, since the module is also imported where there\n * is no DOM at all, such as during server side rendering.\n */\nfunction getElementInternals(): ElementInternals {\n    elementInternals ??= {\n        getAttribute: Element.prototype.getAttribute,\n        getAttributeNames: Element.prototype.getAttributeNames,\n        querySelectorAll: Element.prototype.querySelectorAll,\n        remove: Element.prototype.remove,\n        removeAttribute: Element.prototype.removeAttribute,\n        localName: Object.getOwnPropertyDescriptor(Element.prototype, 'localName').get as () => string,\n        namespaceURI: Object.getOwnPropertyDescriptor(Element.prototype, 'namespaceURI').get as () => string\n    };\n    return elementInternals;\n}\n\nexport class DOM {\n    private static readonly docStyle = typeof window !== 'undefined' && window.document?.documentElement.style;\n\n    private static userSelect: string;\n\n    private static selectProp = !DOM.docStyle || 'userSelect' in DOM.docStyle ? 'userSelect' : 'webkitUserSelect';\n\n    public static create<K extends keyof HTMLElementTagNameMap>(tagName: K, className?: string, container?: HTMLElement): HTMLElementTagNameMap[K] {\n        const el = window.document.createElement(tagName);\n        if (className !== undefined) el.className = className;\n        if (container) container.appendChild(el);\n        return el;\n    }\n\n    public static createNS(namespaceURI: string, tagName: string): Element {\n        return window.document.createElementNS(namespaceURI, tagName);\n    }\n\n    public static disableDrag(): void {\n        if (DOM.docStyle && DOM.selectProp) {\n            DOM.userSelect = DOM.docStyle[DOM.selectProp];\n            DOM.docStyle[DOM.selectProp] = 'none';\n        }\n    }\n\n    public static enableDrag(): void {\n        if (DOM.docStyle && DOM.selectProp) {\n            DOM.docStyle[DOM.selectProp] = DOM.userSelect;\n        }\n    }\n\n    // Suppress the next click, but only if it's immediate.\n    private static suppressClickInternal(e) {\n        e.preventDefault();\n        e.stopPropagation();\n        window.removeEventListener('click', DOM.suppressClickInternal, true);\n    }\n\n    public static suppressClick(): void {\n        window.addEventListener('click', DOM.suppressClickInternal, true);\n        window.setTimeout(() => {\n            window.removeEventListener('click', DOM.suppressClickInternal, true);\n        }, 0);\n    }\n\n    private static getScale(element: HTMLElement): ScaleReturnValue {\n        const rect = element.getBoundingClientRect();\n        return {\n            x: (rect.width / element.offsetWidth) || 1,\n            y: (rect.height / element.offsetHeight) || 1,\n            boundingClientRect: rect,\n        };\n    }\n\n    private static getPoint(el: HTMLElement, scale: ScaleReturnValue, e: MouseEvent | Touch): Point {\n        const rect = scale.boundingClientRect;\n        return new Point(\n            // rect.left/top values are in page scale (like clientX/Y),\n            // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).\n            ((e.clientX - rect.left) / scale.x) - el.clientLeft,\n            ((e.clientY - rect.top) / scale.y) - el.clientTop\n        );\n    }\n\n    public static mousePos(el: HTMLElement, e: MouseEvent | Touch): Point {\n        const scale = DOM.getScale(el);\n        return DOM.getPoint(el, scale, e);\n    }\n\n    public static touchPos(el: HTMLElement, touches: TouchList): Point[] {\n        const points: Point[] = [];\n        const scale = DOM.getScale(el);\n        for (const touch of touches) {\n            points.push(DOM.getPoint(el, scale, touch));\n        }\n        return points;\n    }\n\n    /**\n     * Sanitize an untrusted HTML string, such as the attribution a remote TileJSON asks the map to display.\n     *\n     * Only the elements in `ALLOWED_TAGS` and the attributes in `ALLOWED_ATTRIBUTES` survive; anything else is\n     * dropped along with its subtree. An allow list is used rather than a list of known-dangerous markup because\n     * the latter silently permits whatever it has not heard of yet, including markup added to HTML after it was\n     * written.\n     *\n     * The sanitized nodes are returned rather than a string: serializing and re-parsing is not a round trip, so\n     * a string result lets carefully nested markup mutate into a different - and no longer sanitized - tree.\n     */\n    public static sanitize(str: string): DocumentFragment {\n        const parser = new DOMParser();\n        const doc = parser.parseFromString(str, 'text/html');\n        const body = doc.body;\n\n        const {querySelectorAll, remove} = getElementInternals();\n        for (const element of Array.from<Element>(querySelectorAll.call(body, '*'))) {\n            if (DOM.isAllowedElement(element)) {\n                DOM.removeDisallowedAttributes(element);\n            } else {\n                remove.call(element);\n            }\n        }\n\n        const fragment = document.createDocumentFragment();\n        fragment.append(...body.childNodes);\n        return fragment;\n    }\n\n    /**\n     * An element is allowed only when it is plain HTML markup on the allow list. Elements in the SVG and MathML\n     * namespaces are rejected even when their local name is allowed, since foreign content follows different\n     * parsing rules and is what makes most mutation attacks possible in the first place.\n     */\n    private static isAllowedElement(element: Element): boolean {\n        const {namespaceURI, localName} = getElementInternals();\n        return namespaceURI.call(element) === HTML_NAMESPACE && ALLOWED_TAGS.has(localName.call(element));\n    }\n\n    private static removeDisallowedAttributes(element: Element) {\n        const {getAttributeNames, getAttribute, removeAttribute} = getElementInternals();\n        for (const name of getAttributeNames.call(element)) {\n            if (DOM.isAllowedAttribute(name, getAttribute.call(element, name))) continue;\n            removeAttribute.call(element, name);\n        }\n    }\n\n    /**\n     * `href` and `src` are further restricted to the protocols in `ALLOWED_PROTOCOLS`, so that `javascript:` and\n     * `data:` URLs cannot turn an otherwise harmless link or image into a script. The protocol is taken from a\n     * parsed URL rather than matched against the raw string, since the URL parser is what the browser will apply\n     * and it ignores tabs, newlines and leading control characters that a string comparison would trip over.\n     */\n    private static isAllowedAttribute(name: string, value: string): boolean {\n        if (!ALLOWED_ATTRIBUTES.has(name) && !name.startsWith('aria-')) return false;\n        if (!URL_ATTRIBUTES.has(name)) return true;\n        try {\n            return ALLOWED_PROTOCOLS.has(new URL(value, RELATIVE_URL_BASE).protocol);\n        } catch {\n            return false;\n        }\n    }\n}\n", "import type {RequestParameters, GetResourceResponse} from './ajax.ts';\n\n/**\n * The `data` a protocol handler resolves with. Which member is expected follows `RequestParameters.type`:\n *\n * - `'arrayBuffer'`: an `ArrayBuffer`, for example a non-compressed pbf vector tile.\n * - `'json'`: the parsed JSON value.\n * - `'string'`: a string.\n * - `'image'`: an `ImageBitmap` or `HTMLImageElement`, used as is, or an `ArrayBuffer` of encoded image\n *   bytes, which are decoded first. A handler that already holds decoded pixels should return them as an\n *   `ImageBitmap`, since encoding them only makes the library decode them again.\n */\nexport type AddProtocolResponseData = ArrayBuffer | ImageBitmap | HTMLImageElement | string | object;\n\n/**\n * This method type is used to register a protocol handler.\n * Use the abort controller for aborting requests.\n * Return a promise with the relevant resource response, see {@link AddProtocolResponseData} for what `data` may hold.\n */\nexport type AddProtocolAction = (requestParameters: RequestParameters, abortController: AbortController) => Promise<GetResourceResponse<AddProtocolResponseData>>;\n\n/**\n * This is a global config object used to store the configuration\n * It is available in the workers as well.\n * Only serializable data should be stored in it.\n */\ntype Config = {\n    MAX_PARALLEL_IMAGE_REQUESTS: number;\n    MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: number;\n    MAX_TILE_CACHE_ZOOM_LEVELS: number;\n    REGISTERED_PROTOCOLS: {[x: string]: AddProtocolAction };\n    WORKER_URL: string;\n};\n\nexport const config: Config = {\n    MAX_PARALLEL_IMAGE_REQUESTS: 16,\n    MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8,\n    MAX_TILE_CACHE_ZOOM_LEVELS: 5,\n    REGISTERED_PROTOCOLS: {},\n    WORKER_URL: ''\n};\n", "import {type AddProtocolAction, config} from '../util/config.ts';\n\nexport function getProtocol(url: string): AddProtocolAction {\n    return config.REGISTERED_PROTOCOLS[url.substring(0, url.indexOf('://'))];\n}\n/**\n * Adds a custom load resource function that will be called when using a URL that starts with a custom url schema.\n * This will happen in the main thread, and workers might call it if they don't know how to handle the protocol.\n * The example below will be triggered for custom:// urls defined in the sources list in the style definitions.\n * The function passed will receive the request parameters and should return with the resulting resource.\n * `requestParameters.type` says which kind of resource is expected. A tile is an `ArrayBuffer`, for example\n * a non-compressed pbf vector tile. An image is either its encoded bytes or an `ImageBitmap`/`HTMLImageElement`,\n * which is used without decoding. See {@link AddProtocolResponseData} for every accepted shape.\n *\n * @param customProtocol - the protocol to hook, for example 'custom'\n * @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol\n * @example\n * ```ts\n * // This will fetch a file using the fetch API (this is obviously a non interesting example...)\n * addProtocol('custom', async (params, abortController) => {\n *      const t = await fetch(`https://${params.url.split(\"://\")[1]}`);\n *      if (t.status == 200) {\n *          const buffer = await t.arrayBuffer();\n *          return {data: buffer}\n *      } else {\n *          throw new Error(`Tile fetch error: ${t.statusText}`);\n *      }\n *  });\n * // the following is an example of a way to return an error when trying to load a tile\n * addProtocol('custom2', async (params, abortController) => {\n *      throw new Error('someErrorMessage');\n * });\n * // An image handler that draws or computes its tiles can return them decoded, as an ImageBitmap.\n * addProtocol('drawn', async (params, abortController) => {\n *      const canvas = new OffscreenCanvas(256, 256);\n *      // ... draw the tile ...\n *      return {data: await createImageBitmap(canvas)};\n * });\n * ```\n * @see [Add a COG raster source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-cog-raster-source/)\n * @see [Add Contour Lines](https://maplibre.org/maplibre-gl-js/docs/examples/add-contour-lines/)\n * @see [PMTiles source and protocol](https://maplibre.org/maplibre-gl-js/docs/examples/pmtiles-source-and-protocol/)\n * @see [Use addProtocol to Transform Feature Properties](https://maplibre.org/maplibre-gl-js/docs/examples/use-addprotocol-to-transform-feature-properties/)\n */\nexport function addProtocol(customProtocol: string, loadFn: AddProtocolAction): void {\n    config.REGISTERED_PROTOCOLS[customProtocol] = loadFn;\n}\n\n/**\n * Removes a previously added protocol in the main thread.\n *\n * @param customProtocol - the custom protocol to remove registration for\n * @example\n * ```ts\n * removeProtocol('custom');\n * ```\n */\nexport function removeProtocol(customProtocol: string): void {\n    delete config.REGISTERED_PROTOCOLS[customProtocol];\n}\n", "import {ensureError, extend, isWorker} from './util.ts';\nimport {AbortError, isAbortError, throwIfAborted} from './abort_error.ts';\nimport {getProtocol} from '../source/protocol_crud.ts';\nimport {MessageType} from './actor_messages.ts';\n\n/**\n * This is used to identify the global dispatcher id when sending a message from the worker without a target map id.\n */\nexport const GLOBAL_DISPATCHER_ID = 'global-dispatcher';\n\n/**\n * A type used to store the tile's expiration date and cache control definition\n */\nexport type ExpiryData = {cacheControl?: string | null; expires?: Date | string | null; etag?: string};\n\n/**\n * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks.\n * @example\n * ```ts\n * // use transformRequest to modify requests that begin with `http://myHost`\n * transformRequest: function(url, resourceType) {\n *  if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {\n *    return {\n *      url: url.replace('http', 'https'),\n *      headers: { 'my-custom-header': true },\n *      credentials: 'include'  // Include cookies for cross-origin requests\n *    }\n *   }\n * }\n * ```\n */\nexport type RequestParameters = {\n    /**\n     * The URL to be requested.\n     */\n    url: string;\n    /**\n     * The headers to be sent with the request.\n     */\n    headers?: any;\n    /**\n     * Request method `'GET' | 'POST' | 'PUT'`.\n     */\n    method?: 'GET' | 'POST' | 'PUT';\n    /**\n     * Request body.\n     */\n    body?: string;\n    /**\n     * Response body type to be returned.\n     */\n    type?: 'string' | 'json' | 'arrayBuffer' | 'image';\n    /**\n     * `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.\n     */\n    credentials?: 'same-origin' | 'include';\n    /**\n     * If `true`, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events.\n     */\n    collectResourceTiming?: boolean;\n    /**\n     * Parameters supported only by browser fetch API. Property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache. (https://developer.mozilla.org/en-US/docs/Web/API/Request/cache)\n     */\n    cache?: RequestCache;\n    /**\n     * The referrer policy to use for the request. Controls how much referrer information is sent. (https://developer.mozilla.org/en-US/docs/Web/API/Request/referrerPolicy)\n     */\n    referrerPolicy?: ReferrerPolicy;\n};\n\n/**\n * The response object returned from a successful AJAx request\n */\nexport type GetResourceResponse<T> = ExpiryData & {\n    data: T;\n};\n\n/**\n * The response callback used in various places\n */\nexport type ResponseCallback<T> = (\n    error?: Error | null,\n    data?: T | null,\n    cacheControl?: string | null,\n    expires?: string | Date | null\n) => void;\n\n/**\n * An error thrown when a HTTP request results in an error response.\n */\nexport class AJAXError extends Error {\n    /**\n     * The response's HTTP status code.\n     */\n    status: number;\n\n    /**\n     * The response's HTTP status text.\n     */\n    statusText: string;\n\n    /**\n     * The request's URL.\n     */\n    url: string;\n\n    /**\n     * The response's body.\n     */\n    body: Blob;\n\n    /**\n     * @param status - The response's HTTP status code.\n     * @param statusText - The response's HTTP status text.\n     * @param url - The request's URL.\n     * @param body - The response's body.\n     */\n    constructor(status: number, statusText: string, url: string, body: Blob) {\n        super(`AJAXError: ${statusText} (${status}): ${url}`);\n        this.status = status;\n        this.statusText = statusText;\n        this.url = url;\n        this.body = body;\n    }\n}\n\n/**\n * Ensure that we're sending the correct referrer from blob URL worker bundles.\n * For files loaded from the local file system, `location.origin` will be set\n * to the string(!) \"null\" (Firefox), or \"file://\" (Chrome, Safari, Edge),\n * and we will set an empty referrer. Otherwise, we're using the document's URL.\n * If we're on a blob URL and parent window is cross-origin, parent.location throws\n * SecurityError DOMException, this means we are probably not in blob URL worker bundle.\n */\nexport function getReferrer(): string {\n    if (isWorker(self)) return self.worker?.referrer;\n    if (window.location.protocol === 'blob:') {\n        try {\n            return window.parent.location.href;\n        } catch {}\n    }\n    return window.location.href;\n}\n\n/**\n * Determines whether a URL is a file:// URL. This is obviously the case if it begins\n * with file://. Relative URLs are also file:// URLs iff the original document was loaded\n * via a file:// URL.\n * @param url - The URL to check\n * @returns `true` if the URL is a file:// URL, `false` otherwise\n */\nconst isFileURL = url => url.startsWith('file:') || (getReferrer()?.startsWith('file:') && !/^\\w+:/.test(url));\n\nasync function makeFetchRequest(requestParameters: RequestParameters, abortController: AbortController): Promise<GetResourceResponse<any>> {\n    const request = new Request(requestParameters.url, {\n        method: requestParameters.method || 'GET',\n        body: requestParameters.body,\n        credentials: requestParameters.credentials,\n        headers: requestParameters.headers,\n        cache: requestParameters.cache,\n        referrer: getReferrer(),\n        referrerPolicy: requestParameters.referrerPolicy,\n        signal: abortController.signal\n    });\n\n    // If the user has already set an Accept header, do not overwrite it here\n    if (requestParameters.type === 'json' && !request.headers.has('Accept')) {\n        request.headers.set('Accept', 'application/json');\n    }\n\n    let response: Response;\n    try {\n        response = await fetch(request);\n    } catch (e) {\n        // Pass through AbortErrors for upstream handling\n        if (isAbortError(e)) {\n            throw e;\n        }\n\n        // When the error is due to CORS policy, DNS issue or malformed URL, the fetch call does not resolve but throws a generic TypeError instead.\n        // It is preferable to throw an AJAXError so that the Map event \"error\" can catch it and still have\n        // access to the faulty url. In such case, we provide the arbitrary HTTP error code of `0`.\n        throw new AJAXError(0, ensureError(e).message, requestParameters.url, new Blob());\n    }\n\n    if (!response.ok) {\n        const body = await response.blob();\n        throw new AJAXError(response.status, response.statusText, requestParameters.url, body);\n    }\n    let parsePromise: Promise<any>;\n    if ((requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image')) {\n        parsePromise = response.arrayBuffer();\n    } else if (requestParameters.type === 'json') {\n        parsePromise = response.json();\n    } else {\n        parsePromise = response.text();\n    }\n    const result = await parsePromise;\n    throwIfAborted(abortController.signal);\n    return {data: result, cacheControl: response.headers.get('Cache-Control'), expires: response.headers.get('Expires'), etag: response.headers.get('ETag')};\n}\n\nfunction makeXMLHttpRequest(requestParameters: RequestParameters, abortController: AbortController): Promise<GetResourceResponse<any>> {\n    return new Promise((resolve, reject) => {\n        const xhr: XMLHttpRequest = new XMLHttpRequest();\n\n        xhr.open(requestParameters.method || 'GET', requestParameters.url, true);\n        if (requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image') {\n            xhr.responseType = 'arraybuffer';\n        }\n        for (const k in requestParameters.headers) {\n            xhr.setRequestHeader(k, requestParameters.headers[k]);\n        }\n        if (requestParameters.type === 'json') {\n            xhr.responseType = 'text';\n            // Do not overwrite the user-provided Accept header\n            if (!requestParameters.headers?.Accept) {\n                xhr.setRequestHeader('Accept', 'application/json');\n            }\n        }\n        xhr.withCredentials = requestParameters.credentials === 'include';\n        xhr.onerror = () => {\n            reject(new Error(xhr.statusText));\n        };\n        xhr.onload = () => {\n            if (abortController.signal.aborted) {\n                return;\n            }\n            if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) {\n                let data: unknown = xhr.response;\n                if (requestParameters.type === 'json') {\n                    // We're manually parsing JSON here to get better error messages.\n                    try {\n                        data = JSON.parse(xhr.response);\n                    } catch (err) {\n                        reject(err);\n                        return;\n                    }\n                }\n                resolve({data, cacheControl: xhr.getResponseHeader('Cache-Control'), expires: xhr.getResponseHeader('Expires'), etag: xhr.getResponseHeader('ETag')});\n            } else {\n                const body = new Blob([xhr.response], {type: xhr.getResponseHeader('Content-Type')});\n                reject(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body));\n            }\n        };\n        abortController.signal.addEventListener('abort', () => {\n            xhr.abort();\n            reject(new AbortError(abortController.signal.reason));\n        });\n        xhr.send(requestParameters.body);\n    });\n}\n\n/**\n * We're trying to use the Fetch API if possible. However, requests for resources with the file:// URI scheme don't work with the Fetch API.\n * In this case we unconditionally use XHR on the current thread since referrers don't matter.\n * This method can also use the registered method if `addProtocol` was called.\n * @param requestParameters - The request parameters\n * @param abortController - The abort controller allowing to cancel the request\n * @returns a promise resolving to the response, including cache control and expiry data\n */\nexport const makeRequest = async function(requestParameters: RequestParameters, abortController: AbortController): Promise<GetResourceResponse<any>> {\n    if (requestParameters.url.includes('://') && !(/^https?:|^file:/.test(requestParameters.url))) {\n        const protocolLoadFn = getProtocol(requestParameters.url);\n        if (protocolLoadFn) {\n            const response = await protocolLoadFn(requestParameters, abortController);\n            if (!response.data && requestParameters.type === 'arrayBuffer') {\n                // A successful array buffer request should always return data even if empty\n                return extend(response, {data: new ArrayBuffer(0)});\n            }\n            return response;\n        }\n        if (isWorker(self) && self.worker?.actor) {\n            return self.worker.actor.sendAsync({type: MessageType.getResource, data: requestParameters, targetMapId: GLOBAL_DISPATCHER_ID}, abortController);\n        }\n    }\n    if (!isFileURL(requestParameters.url)) {\n        if (fetch && Request && AbortController && Object.hasOwn(Request.prototype, 'signal')) {\n            return makeFetchRequest(requestParameters, abortController);\n        }\n        if (isWorker(self) && self.worker?.actor) {\n            return self.worker.actor.sendAsync({type: MessageType.getResource, data: requestParameters, mustQueue: true, targetMapId: GLOBAL_DISPATCHER_ID}, abortController);\n        }\n    }\n    return makeXMLHttpRequest(requestParameters, abortController);\n};\n\nexport const getJSON = <T>(requestParameters: RequestParameters, abortController: AbortController): Promise<{data: T} & ExpiryData> => {\n    return makeRequest(extend(requestParameters, {type: 'json'}), abortController);\n};\n\nexport const getArrayBuffer = (requestParameters: RequestParameters, abortController: AbortController): Promise<{data: ArrayBuffer} & ExpiryData> => {\n    return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), abortController);\n};\n\n/** \n * Determines whether a URL is same origin as the current location. Supports relative URLs too.\n * \n * A relative URL \"/foo\" or \"./foo\" will throw exception in URL's ctor,\n * try-catch is expansive so just use a heuristic check to avoid it\n * \n * - Relative URL and empty URL are always same origin.\n * - data URL containing an image is always same origin.\n * - blob URL is checked using `URL` constructor by its parent URL; opaque blob URL is never same origin.\n * - Absolute URL is checked using `URL` constructor.\n * \n * Checks blob URL before relative URL because opaque blob URL does not contain `://` too.\n * \n * @param inComingUrl - The URL to check\n * @returns `true` if the URL is same origin as current location, `false` otherwise\n */\nexport function sameOrigin(inComingUrl: string): boolean {\n    if (!inComingUrl) return true; // empty URL\n    if (inComingUrl.startsWith('data:image/')) return true; // data image URL\n    if (inComingUrl.startsWith('blob:')) { // blob URL\n        inComingUrl = inComingUrl.slice(5);\n        if (inComingUrl.startsWith('null')) return false; // opaque blob URL\n    }\n    if (inComingUrl.indexOf('://') <= 0) return true; // relative URL\n    const urlObj = new URL(inComingUrl);\n    const locationObj = window.location;\n    return urlObj.protocol === locationObj.protocol && urlObj.host === locationObj.host;\n}\n\nexport const getVideo = (urls: string[]): Promise<HTMLVideoElement> => {\n    const video: HTMLVideoElement = window.document.createElement('video');\n    video.muted = true;\n    return new Promise((resolve) => {\n        video.onloadstart = () => {\n            resolve(video);\n        };\n        for (const url of urls) {\n            const s: HTMLSourceElement = window.document.createElement('source');\n            if (!sameOrigin(url)) {\n                video.crossOrigin = 'Anonymous';\n            }\n            s.src = url;\n            video.appendChild(s);\n        }\n    });\n};\n", "import {extend, type Subscription} from './util.ts';\n\n/**\n * A listener method used as a callback to events\n */\nexport type Listener<E extends Event = Event> = (event: E) => any;\n\n/**\n * A mapping between event names and the event each of them carries.\n */\nexport type EventTypeMap = Record<string, Event>;\n\n/**\n * The event names of an {@link EventTypeMap}.\n */\nexport type EventNames<EventType extends EventTypeMap> = Extract<keyof EventType, string>;\n\n/**\n * Properties merged into every event bubbled up to an evented parent.\n */\nexport type EventedParentData = Record<string, unknown>;\n\ntype Listeners<EventType extends EventTypeMap> = {[K in keyof EventType]?: Array<Listener<EventType[K]>>};\n\nfunction _addEventListener<T extends EventTypeMap, K extends EventNames<T>>(type: K, listener: Listener<T[K]>, listenerList: Listeners<T>) {\n    const listenerExists = listenerList[type]?.includes(listener);\n    if (!listenerExists) {\n        listenerList[type] ||= [];\n        listenerList[type].push(listener);\n    }\n}\n\nfunction _removeEventListener<T extends EventTypeMap, K extends EventNames<T>>(type: K, listener: Listener<T[K]>, listenerList: Listeners<T>) {\n    if (listenerList?.[type]) {\n        const index = listenerList[type].indexOf(listener);\n        if (index !== -1) {\n            listenerList[type].splice(index, 1);\n        }\n    }\n}\n\n/**\n * The event class\n */\nexport class Event<TType extends string = string> {\n    readonly type: TType;\n    /**\n     * The object that fired the event. Set when the event is fired, and narrowed to a more\n     * specific type (e.g. `Map`, `Marker`) by the event subclasses.\n     */\n    target?: unknown;\n\n    constructor(type: TType, data: object = {}) {\n        extend(this, data);\n        this.type = type;\n    }\n}\n\ntype ErrorLike = {\n    message: string;\n};\n\n/**\n * An error event\n */\nexport class ErrorEvent extends Event<'error'> {\n    error: ErrorLike;\n\n    constructor(error: ErrorLike, data: object = {}) {\n        super('error', extend({error}, data));\n    }\n}\n\n/**\n * The event map of an {@link Evented} that only reports errors.\n */\nexport type ErrorEventType = {\n    error: ErrorEvent;\n};\n\n/**\n * Methods mixed in to other classes for event capabilities.\n *\n * @group Event Related\n */\nexport abstract class Evented<EventType extends EventTypeMap = EventTypeMap> {\n    _listeners?: Listeners<EventType>;\n    _oneTimeListeners?: Listeners<EventType>;\n    _eventedParent?: Evented;\n    _eventedParentData?: EventedParentData | (() => EventedParentData);\n\n    /**\n     * Adds a listener to a specified event type.\n     *\n     * @param type - The event type to add a listen for.\n     * @param listener - The function to be called when the event is fired.\n     * The listener function is called with the data object passed to `fire`,\n     * extended with `target` and `type` properties.\n     */\n    on<T extends EventNames<EventType>>(type: T, listener: (event: EventType[T]) => void): Subscription {\n        this._listeners ||= {};\n        _addEventListener(type, listener, this._listeners);\n\n        return {\n            unsubscribe: () => {\n                this.off(type, listener);\n            }\n        };\n    }\n\n    /**\n     * Removes a previously registered event listener.\n     *\n     * @param type - The event type to remove listeners for.\n     * @param listener - The listener function to remove.\n     */\n    off<T extends EventNames<EventType>>(type: T, listener: (event: EventType[T]) => void): this {\n        _removeEventListener(type, listener, this._listeners);\n        _removeEventListener(type, listener, this._oneTimeListeners);\n\n        return this;\n    }\n\n    /**\n     * Adds a listener that will be called only once to a specified event type.\n     *\n     * The listener will be called first time the event fires after the listener is registered.\n     *\n     * @param type - The event type to listen for.\n     * @returns a promise that resolves with the event\n     */\n    once<T extends EventNames<EventType>>(type: T): Promise<EventType[T]>;\n    /**\n     * Adds a listener that will be called only once to a specified event type.\n     *\n     * The listener will be called first time the event fires after the listener is registered.\n     *\n     * @param type - The event type to listen for.\n     * @param listener - The function to be called when the event is fired the first time.\n     * @returns `this` when a listener is provided\n     */\n    once<T extends EventNames<EventType>>(type: T, listener: (event: EventType[T]) => void): this;\n    once<T extends EventNames<EventType>>(type: T, listener?: (event: EventType[T]) => void): this | Promise<EventType[T]> {\n        if (!listener) {\n            return new Promise((resolve) => this.once(type, resolve));\n        }\n        this._oneTimeListeners ||= {};\n        _addEventListener(type, listener, this._oneTimeListeners);\n\n        return this;\n    }\n\n    /**\n     * Calls every listener registered for the event's type.\n     */\n    fire(event: EventType[EventNames<EventType>]): this;\n    /**\n     * Compatibility with the (type: string, properties: Object) signature from previous versions.\n     * See https://github.com/mapbox/mapbox-gl-js/issues/6522,\n     *     https://github.com/mapbox/mapbox-gl-draw/issues/766\n     */\n    fire(type: EventNames<EventType>, properties?: object): this;\n    fire(event: EventType[EventNames<EventType>] | EventNames<EventType>, properties?: object): this {\n        const firedEvent: Event = typeof event === 'string' ? new Event(event, properties || {}) : event;\n        const type = firedEvent.type as EventNames<EventType>;\n\n        if (this.listens(type)) {\n            firedEvent.target = this;\n\n            // make sure adding or removing listeners inside other listeners won't cause an infinite loop\n            const listeners = this._listeners?.[type]?.slice() ?? [];\n            for (const listener of listeners) {\n                listener.call(this, firedEvent);\n            }\n\n            const oneTimeListeners = this._oneTimeListeners?.[type]?.slice() ?? [];\n            for (const listener of oneTimeListeners) {\n                _removeEventListener(type, listener, this._oneTimeListeners);\n                listener.call(this, firedEvent);\n            }\n\n            const parent = this._eventedParent;\n            if (parent) {\n                extend(\n                    firedEvent,\n                    typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData\n                );\n                parent.fire(firedEvent);\n            }\n\n        // To ensure that no error events are dropped, print them to the\n        // console if they have no listeners.\n        } else if (firedEvent instanceof ErrorEvent) {\n            console.error(firedEvent.error);\n        }\n\n        return this;\n    }\n\n    /**\n     * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type.\n     *\n     * @param type - The event type\n     * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise\n     */\n    listens(type: EventNames<EventType>): boolean {\n        return Boolean(\n            this._listeners?.[type]?.length ||\n            this._oneTimeListeners?.[type]?.length ||\n            this._eventedParent?.listens(type)\n        );\n    }\n\n    /**\n     * Bubble all events fired by this instance of Evented to this parent instance of Evented.\n     */\n    setEventedParent(parent?: Evented | null, data?: EventedParentData | (() => EventedParentData)): this {\n        this._eventedParent = parent;\n        this._eventedParentData = data;\n\n        return this;\n    }\n}\n", "/*\nThis file was copied from https://github.com/mapbox/grid-index and was\nmigrated from JavaScript to TypeScript.\n\nCopyright (c) 2016, Mapbox\n\nPermission to use, copy, modify, and/or distribute this software for any purpose\nwith or without fee is hereby granted, provided that the above copyright notice\nand this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\nOF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\nTHIS SOFTWARE.\n*/\n\nconst NUM_PARAMS = 3;\n\nexport type SerializedGrid = {\n    buffer: ArrayBuffer;\n};\n\nexport class TransferableGridIndex {\n    cells: number[][];\n    arrayBuffer: ArrayBuffer;\n    d: number;\n    keys: number[];\n    bboxes: number[];\n    n: number;\n    extent: number;\n    padding: number;\n    scale: any;\n    uid: number;\n    min: number;\n    max: number;\n\n    constructor(extent: number | ArrayBuffer, n?: number, padding?: number) {\n        const cells = this.cells = [];\n\n        if (extent instanceof ArrayBuffer) {\n            this.arrayBuffer = extent;\n            const array = new Int32Array(this.arrayBuffer);\n            extent = array[0];\n            n = array[1];\n            padding = array[2];\n\n            this.d = n + 2 * padding;\n            for (let k = 0; k < this.d * this.d; k++) {\n                const start = array[NUM_PARAMS + k];\n                const end = array[NUM_PARAMS + k + 1];\n                cells.push(start === end ? null : array.subarray(start, end));\n            }\n            const keysOffset = array[NUM_PARAMS + cells.length];\n            const bboxesOffset = array[NUM_PARAMS + cells.length + 1];\n            this.keys = array.subarray(keysOffset, bboxesOffset) as any as number[];\n            this.bboxes = array.subarray(bboxesOffset) as any as number[];\n\n            this.insert = this._insertReadonly;\n\n        } else {\n            this.d = n + 2 * padding;\n            for (let i = 0; i < this.d * this.d; i++) {\n                cells.push([]);\n            }\n            this.keys = [];\n            this.bboxes = [];\n        }\n\n        this.n = n;\n        this.extent = extent;\n        this.padding = padding;\n        this.scale = n / extent;\n        this.uid = 0;\n\n        const p = (padding / n) * extent;\n        this.min = -p;\n        this.max = extent + p;\n    }\n\n    insert(key: number, x1: number, y1: number, x2: number, y2: number): void {\n        this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++, undefined, undefined);\n        this.keys.push(key);\n        this.bboxes.push(x1);\n        this.bboxes.push(y1);\n        this.bboxes.push(x2);\n        this.bboxes.push(y2);\n    }\n\n    _insertReadonly(): void {\n        throw new Error('Cannot insert into a GridIndex created from an ArrayBuffer.');\n    }\n\n    _insertCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number): void {\n        this.cells[cellIndex].push(uid);\n    }\n\n    query(x1: number, y1: number, x2: number, y2: number, intersectionTest?: (x1: number, y1: number, x2: number, y2: number) => boolean): number[] {\n        const min = this.min;\n        const max = this.max;\n        if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) {\n            return [...this.keys];\n\n        } else {\n            const result = [];\n            const seenUids = {};\n            this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest);\n            return result;\n        }\n    }\n\n    _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: number[], seenUids: Record<number, boolean>, intersectionTest: (x1: number, y1: number, x2: number, y2: number) => boolean): void {\n        const cell = this.cells[cellIndex];\n        if (cell !== null) {\n            const keys = this.keys;\n            const bboxes = this.bboxes;\n            for (const uid of cell) {\n                if (seenUids[uid] === undefined) {\n                    const offset = uid * 4;\n                    if (intersectionTest ?\n                        intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) :\n                        ((x1 <= bboxes[offset + 2]) &&\n                        (y1 <= bboxes[offset + 3]) &&\n                        (x2 >= bboxes[offset + 0]) &&\n                        (y2 >= bboxes[offset + 1]))) {\n                        seenUids[uid] = true;\n                        result.push(keys[uid]);\n                    } else {\n                        seenUids[uid] = false;\n                    }\n                }\n            }\n        }\n    }\n\n    _forEachCell(x1: number, y1: number, x2: number, y2: number, fn: Function, arg1: unknown, arg2: unknown, intersectionTest?: (x1: number, y1: number, x2: number, y2: number) => boolean): void {\n        const cx1 = this._convertToCellCoord(x1);\n        const cy1 = this._convertToCellCoord(y1);\n        const cx2 = this._convertToCellCoord(x2);\n        const cy2 = this._convertToCellCoord(y2);\n        for (let x = cx1; x <= cx2; x++) {\n            for (let y = cy1; y <= cy2; y++) {\n                const cellIndex = this.d * y + x;\n                if (intersectionTest && !intersectionTest(\n                    this._convertFromCellCoord(x),\n                    this._convertFromCellCoord(y),\n                    this._convertFromCellCoord(x + 1),\n                    this._convertFromCellCoord(y + 1))) continue;\n                if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) return;\n            }\n        }\n    }\n\n    _convertFromCellCoord(x: number): number {\n        return (x - this.padding) / this.scale;\n    }\n\n    _convertToCellCoord(x: number): number {\n        return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding));\n    }\n\n    toArrayBuffer(): ArrayBuffer {\n        if (this.arrayBuffer) return this.arrayBuffer;\n\n        const cells = this.cells;\n\n        const metadataLength = NUM_PARAMS + this.cells.length + 1 + 1;\n        let totalCellLength = 0;\n        for (const cell of this.cells) {\n            totalCellLength += cell.length;\n        }\n\n        const array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length);\n        array[0] = this.extent;\n        array[1] = this.n;\n        array[2] = this.padding;\n\n        let offset = metadataLength;\n        for (let k = 0; k < cells.length; k++) {\n            const cell = cells[k];\n            array[NUM_PARAMS + k] = offset;\n            array.set(cell, offset);\n            offset += cell.length;\n        }\n\n        array[NUM_PARAMS + cells.length] = offset;\n        array.set(this.keys, offset);\n        offset += this.keys.length;\n\n        array[NUM_PARAMS + cells.length + 1] = offset;\n        array.set(this.bboxes, offset);\n        offset += this.bboxes.length;\n\n        return array.buffer;\n    }\n\n    public static serialize(grid: TransferableGridIndex, transferables?: Transferable[]): SerializedGrid {\n        const buffer = grid.toArrayBuffer();\n        if (transferables) {\n            transferables.push(buffer);\n        }\n        return {buffer};\n    }\n\n    public static deserialize(serialized: SerializedGrid): TransferableGridIndex {\n        return new TransferableGridIndex(serialized.buffer);\n    }\n}\n", "// src/reference/v8.json\nvar v8_default = {\n\t$version: 8,\n\t$root: {\n\t\t\"version\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": [8]\n\t\t},\n\t\t\"name\": { \"type\": \"string\" },\n\t\t\"metadata\": { \"type\": \"*\" },\n\t\t\"center\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2\n\t\t},\n\t\t\"centerAltitude\": { \"type\": \"number\" },\n\t\t\"zoom\": { \"type\": \"number\" },\n\t\t\"bearing\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"period\": 360,\n\t\t\t\"units\": \"degrees\"\n\t\t},\n\t\t\"pitch\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"units\": \"degrees\"\n\t\t},\n\t\t\"roll\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"units\": \"degrees\"\n\t\t},\n\t\t\"state\": {\n\t\t\t\"type\": \"state\",\n\t\t\t\"default\": {}\n\t\t},\n\t\t\"light\": { \"type\": \"light\" },\n\t\t\"sky\": { \"type\": \"sky\" },\n\t\t\"projection\": { \"type\": \"projection\" },\n\t\t\"terrain\": { \"type\": \"terrain\" },\n\t\t\"sources\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"sources\"\n\t\t},\n\t\t\"sprite\": { \"type\": \"sprite\" },\n\t\t\"glyphs\": { \"type\": \"string\" },\n\t\t\"font-faces\": { \"type\": \"fontFaces\" },\n\t\t\"transition\": { \"type\": \"transition\" },\n\t\t\"layers\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"layer\"\n\t\t}\n\t},\n\tsources: { \"*\": { \"type\": \"source\" } },\n\tsource: [\n\t\t\"source_vector\",\n\t\t\"source_raster\",\n\t\t\"source_raster_dem\",\n\t\t\"source_geojson\",\n\t\t\"source_video\",\n\t\t\"source_image\"\n\t],\n\tsource_vector: {\n\t\t\"type\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": { \"vector\": {} }\n\t\t},\n\t\t\"url\": { \"type\": \"string\" },\n\t\t\"tiles\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"string\"\n\t\t},\n\t\t\"bounds\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 4,\n\t\t\t\"default\": [\n\t\t\t\t-180,\n\t\t\t\t-85.051129,\n\t\t\t\t180,\n\t\t\t\t85.051129\n\t\t\t]\n\t\t},\n\t\t\"scheme\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"xyz\": {},\n\t\t\t\t\"tms\": {}\n\t\t\t},\n\t\t\t\"default\": \"xyz\"\n\t\t},\n\t\t\"emptyResponse\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"blank\": {},\n\t\t\t\t\"missing\": {}\n\t\t\t},\n\t\t\t\"default\": \"blank\"\n\t\t},\n\t\t\"minzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0\n\t\t},\n\t\t\"maxzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 22\n\t\t},\n\t\t\"attribution\": { \"type\": \"string\" },\n\t\t\"promoteId\": { \"type\": \"promoteId\" },\n\t\t\"volatile\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false\n\t\t},\n\t\t\"encoding\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"mvt\": {},\n\t\t\t\t\"mlt\": {}\n\t\t\t},\n\t\t\t\"default\": \"mvt\"\n\t\t},\n\t\t\"*\": { \"type\": \"*\" }\n\t},\n\tsource_raster: {\n\t\t\"type\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": { \"raster\": {} }\n\t\t},\n\t\t\"url\": { \"type\": \"string\" },\n\t\t\"tiles\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"string\"\n\t\t},\n\t\t\"bounds\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 4,\n\t\t\t\"default\": [\n\t\t\t\t-180,\n\t\t\t\t-85.051129,\n\t\t\t\t180,\n\t\t\t\t85.051129\n\t\t\t]\n\t\t},\n\t\t\"minzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0\n\t\t},\n\t\t\"maxzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 22\n\t\t},\n\t\t\"tileSize\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 512,\n\t\t\t\"units\": \"pixels\"\n\t\t},\n\t\t\"scheme\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"xyz\": {},\n\t\t\t\t\"tms\": {}\n\t\t\t},\n\t\t\t\"default\": \"xyz\"\n\t\t},\n\t\t\"emptyResponse\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"blank\": {},\n\t\t\t\t\"missing\": {}\n\t\t\t},\n\t\t\t\"default\": \"blank\"\n\t\t},\n\t\t\"attribution\": { \"type\": \"string\" },\n\t\t\"volatile\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false\n\t\t},\n\t\t\"*\": { \"type\": \"*\" }\n\t},\n\tsource_raster_dem: {\n\t\t\"type\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": { \"raster-dem\": {} }\n\t\t},\n\t\t\"url\": { \"type\": \"string\" },\n\t\t\"tiles\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"string\"\n\t\t},\n\t\t\"bounds\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 4,\n\t\t\t\"default\": [\n\t\t\t\t-180,\n\t\t\t\t-85.051129,\n\t\t\t\t180,\n\t\t\t\t85.051129\n\t\t\t]\n\t\t},\n\t\t\"minzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0\n\t\t},\n\t\t\"maxzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 22\n\t\t},\n\t\t\"tileSize\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 512,\n\t\t\t\"units\": \"pixels\"\n\t\t},\n\t\t\"emptyResponse\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"blank\": {},\n\t\t\t\t\"missing\": {}\n\t\t\t},\n\t\t\t\"default\": \"blank\"\n\t\t},\n\t\t\"attribution\": { \"type\": \"string\" },\n\t\t\"encoding\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"terrarium\": {},\n\t\t\t\t\"mapbox\": {},\n\t\t\t\t\"custom\": {}\n\t\t\t},\n\t\t\t\"default\": \"mapbox\"\n\t\t},\n\t\t\"redFactor\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1\n\t\t},\n\t\t\"blueFactor\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1\n\t\t},\n\t\t\"greenFactor\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1\n\t\t},\n\t\t\"baseShift\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0\n\t\t},\n\t\t\"volatile\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false\n\t\t},\n\t\t\"*\": { \"type\": \"*\" }\n\t},\n\tsource_geojson: {\n\t\t\"type\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": { \"geojson\": {} }\n\t\t},\n\t\t\"data\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"*\"\n\t\t},\n\t\t\"maxzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 18\n\t\t},\n\t\t\"attribution\": { \"type\": \"string\" },\n\t\t\"buffer\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 128,\n\t\t\t\"maximum\": 512,\n\t\t\t\"minimum\": 0\n\t\t},\n\t\t\"filter\": { \"type\": \"filter\" },\n\t\t\"tolerance\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": .375\n\t\t},\n\t\t\"cluster\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false\n\t\t},\n\t\t\"clusterRadius\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 50,\n\t\t\t\"minimum\": 0\n\t\t},\n\t\t\"clusterMaxZoom\": { \"type\": \"number\" },\n\t\t\"clusterMinPoints\": { \"type\": \"number\" },\n\t\t\"clusterProperties\": { \"type\": \"*\" },\n\t\t\"lineMetrics\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false\n\t\t},\n\t\t\"generateId\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false\n\t\t},\n\t\t\"promoteId\": { \"type\": \"promoteId\" }\n\t},\n\tsource_video: {\n\t\t\"type\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": { \"video\": {} }\n\t\t},\n\t\t\"urls\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"string\"\n\t\t},\n\t\t\"coordinates\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"array\",\n\t\t\t\"length\": 4,\n\t\t\t\"value\": {\n\t\t\t\t\"type\": \"array\",\n\t\t\t\t\"length\": 2,\n\t\t\t\t\"value\": \"number\"\n\t\t\t}\n\t\t}\n\t},\n\tsource_image: {\n\t\t\"type\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": { \"image\": {} }\n\t\t},\n\t\t\"url\": { \"type\": \"string\" },\n\t\t\"coordinates\": {\n\t\t\t\"required\": true,\n\t\t\t\"type\": \"array\",\n\t\t\t\"length\": 4,\n\t\t\t\"value\": {\n\t\t\t\t\"type\": \"array\",\n\t\t\t\t\"length\": 2,\n\t\t\t\t\"value\": \"number\"\n\t\t\t}\n\t\t}\n\t},\n\tlayer: {\n\t\t\"id\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"required\": true\n\t\t},\n\t\t\"type\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"fill\": {},\n\t\t\t\t\"line\": {},\n\t\t\t\t\"symbol\": {},\n\t\t\t\t\"circle\": {},\n\t\t\t\t\"heatmap\": {},\n\t\t\t\t\"fill-extrusion\": {},\n\t\t\t\t\"raster\": {},\n\t\t\t\t\"hillshade\": {},\n\t\t\t\t\"color-relief\": {},\n\t\t\t\t\"background\": {}\n\t\t\t},\n\t\t\t\"required\": true\n\t\t},\n\t\t\"metadata\": { \"type\": \"*\" },\n\t\t\"source\": { \"type\": \"string\" },\n\t\t\"source-layer\": { \"type\": \"string\" },\n\t\t\"minzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 24\n\t\t},\n\t\t\"maxzoom\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 24\n\t\t},\n\t\t\"filter\": { \"type\": \"filter\" },\n\t\t\"layout\": { \"type\": \"layout\" },\n\t\t\"paint\": { \"type\": \"paint\" }\n\t},\n\tlayout: [\n\t\t\"layout_fill\",\n\t\t\"layout_line\",\n\t\t\"layout_circle\",\n\t\t\"layout_heatmap\",\n\t\t\"layout_fill-extrusion\",\n\t\t\"layout_symbol\",\n\t\t\"layout_raster\",\n\t\t\"layout_hillshade\",\n\t\t\"layout_color-relief\",\n\t\t\"layout_background\"\n\t],\n\tlayout_background: { \"visibility\": {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"visible\": {},\n\t\t\t\"none\": {}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"expression\": {\n\t\t\t\"interpolated\": false,\n\t\t\t\"parameters\": [\"global-state\"]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t} },\n\tlayout_fill: {\n\t\t\"fill-sort-key\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"visibility\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"visible\": {},\n\t\t\t\t\"none\": {}\n\t\t\t},\n\t\t\t\"default\": \"visible\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"global-state\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tlayout_circle: {\n\t\t\"circle-sort-key\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"visibility\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"visible\": {},\n\t\t\t\t\"none\": {}\n\t\t\t},\n\t\t\t\"default\": \"visible\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"global-state\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tlayout_heatmap: { \"visibility\": {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"visible\": {},\n\t\t\t\"none\": {}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"expression\": {\n\t\t\t\"interpolated\": false,\n\t\t\t\"parameters\": [\"global-state\"]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t} },\n\t\"layout_fill-extrusion\": {\n\t\t\"visibility\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"visible\": {},\n\t\t\t\t\"none\": {}\n\t\t\t},\n\t\t\t\"default\": \"visible\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"global-state\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-extrusion-rounded-corner-distance\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"units\": \"meters\",\n\t\t\t\"property-type\": \"constant\"\n\t\t}\n\t},\n\tlayout_line: {\n\t\t\"line-cap\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"butt\": {},\n\t\t\t\t\"round\": {},\n\t\t\t\t\"square\": {}\n\t\t\t},\n\t\t\t\"default\": \"butt\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-join\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"bevel\": {},\n\t\t\t\t\"round\": {},\n\t\t\t\t\"miter\": {}\n\t\t\t},\n\t\t\t\"default\": \"miter\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-miter-limit\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 2,\n\t\t\t\"requires\": [{ \"line-join\": \"miter\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-round-limit\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1.05,\n\t\t\t\"requires\": [{ \"line-join\": \"round\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-sort-key\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"visibility\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"visible\": {},\n\t\t\t\t\"none\": {}\n\t\t\t},\n\t\t\t\"default\": \"visible\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"global-state\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tlayout_symbol: {\n\t\t\"symbol-placement\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"point\": {},\n\t\t\t\t\"line\": {},\n\t\t\t\t\"line-center\": {}\n\t\t\t},\n\t\t\t\"default\": \"point\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"symbol-spacing\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 250,\n\t\t\t\"minimum\": 1,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [{ \"symbol-placement\": \"line\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"symbol-avoid-edges\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"symbol-sort-key\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"symbol-z-order\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"auto\": {},\n\t\t\t\t\"viewport-y\": {},\n\t\t\t\t\"source\": {}\n\t\t\t},\n\t\t\t\"default\": \"auto\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-allow-overlap\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"requires\": [\"icon-image\", { \"!\": \"icon-overlap\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-overlap\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"never\": {},\n\t\t\t\t\"always\": {},\n\t\t\t\t\"cooperative\": {}\n\t\t\t},\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-ignore-placement\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-optional\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"requires\": [\"icon-image\", \"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-rotation-alignment\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {},\n\t\t\t\t\"auto\": {}\n\t\t\t},\n\t\t\t\"default\": \"auto\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-size\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"units\": \"factor of the original icon size\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-text-fit\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"none\": {},\n\t\t\t\t\"width\": {},\n\t\t\t\t\"height\": {},\n\t\t\t\t\"both\": {}\n\t\t\t},\n\t\t\t\"default\": \"none\",\n\t\t\t\"requires\": [\"icon-image\", \"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-text-fit-padding\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 4,\n\t\t\t\"default\": [\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t0\n\t\t\t],\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\n\t\t\t\t\"icon-image\",\n\t\t\t\t\"text-field\",\n\t\t\t\t{ \"icon-text-fit\": [\n\t\t\t\t\t\"both\",\n\t\t\t\t\t\"width\",\n\t\t\t\t\t\"height\"\n\t\t\t\t] }\n\t\t\t],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-image\": {\n\t\t\t\"type\": \"resolvedImage\",\n\t\t\t\"tokens\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-rotate\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"period\": 360,\n\t\t\t\"units\": \"degrees\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-padding\": {\n\t\t\t\"type\": \"padding\",\n\t\t\t\"default\": [2],\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-keep-upright\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"requires\": [\n\t\t\t\t\"icon-image\",\n\t\t\t\t{ \"icon-rotation-alignment\": \"map\" },\n\t\t\t\t{ \"symbol-placement\": [\"line\", \"line-center\"] }\n\t\t\t],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-offset\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"center\": {},\n\t\t\t\t\"left\": {},\n\t\t\t\t\"right\": {},\n\t\t\t\t\"top\": {},\n\t\t\t\t\"bottom\": {},\n\t\t\t\t\"top-left\": {},\n\t\t\t\t\"top-right\": {},\n\t\t\t\t\"bottom-left\": {},\n\t\t\t\t\"bottom-right\": {}\n\t\t\t},\n\t\t\t\"default\": \"center\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-pitch-alignment\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {},\n\t\t\t\t\"auto\": {}\n\t\t\t},\n\t\t\t\"default\": \"auto\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-pitch-alignment\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {},\n\t\t\t\t\"auto\": {}\n\t\t\t},\n\t\t\t\"default\": \"auto\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-rotation-alignment\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {},\n\t\t\t\t\"viewport-glyph\": {},\n\t\t\t\t\"auto\": {}\n\t\t\t},\n\t\t\t\"default\": \"auto\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-field\": {\n\t\t\t\"type\": \"formatted\",\n\t\t\t\"default\": \"\",\n\t\t\t\"tokens\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-font\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"string\",\n\t\t\t\"default\": [\"Open Sans Regular\", \"Arial Unicode MS Regular\"],\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-size\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 16,\n\t\t\t\"minimum\": 0,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-max-width\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 10,\n\t\t\t\"minimum\": 0,\n\t\t\t\"units\": \"ems\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-line-height\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1.2,\n\t\t\t\"units\": \"ems\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-letter-spacing\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"units\": \"ems\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-justify\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"auto\": {},\n\t\t\t\t\"left\": {},\n\t\t\t\t\"center\": {},\n\t\t\t\t\"right\": {}\n\t\t\t},\n\t\t\t\"default\": \"center\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-radial-offset\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"units\": \"ems\",\n\t\t\t\"default\": 0,\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"property-type\": \"data-driven\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t}\n\t\t},\n\t\t\"text-variable-anchor\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"center\": {},\n\t\t\t\t\"left\": {},\n\t\t\t\t\"right\": {},\n\t\t\t\t\"top\": {},\n\t\t\t\t\"bottom\": {},\n\t\t\t\t\"top-left\": {},\n\t\t\t\t\"top-right\": {},\n\t\t\t\t\"bottom-left\": {},\n\t\t\t\t\"bottom-right\": {}\n\t\t\t},\n\t\t\t\"requires\": [\"text-field\", { \"symbol-placement\": [\"point\"] }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-variable-anchor-offset\": {\n\t\t\t\"type\": \"variableAnchorOffsetCollection\",\n\t\t\t\"requires\": [\"text-field\", { \"symbol-placement\": [\"point\"] }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"center\": {},\n\t\t\t\t\"left\": {},\n\t\t\t\t\"right\": {},\n\t\t\t\t\"top\": {},\n\t\t\t\t\"bottom\": {},\n\t\t\t\t\"top-left\": {},\n\t\t\t\t\"top-right\": {},\n\t\t\t\t\"bottom-left\": {},\n\t\t\t\t\"bottom-right\": {}\n\t\t\t},\n\t\t\t\"default\": \"center\",\n\t\t\t\"requires\": [\"text-field\", { \"!\": \"text-variable-anchor\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-max-angle\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 45,\n\t\t\t\"units\": \"degrees\",\n\t\t\t\"requires\": [\"text-field\", { \"symbol-placement\": [\"line\", \"line-center\"] }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-writing-mode\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"horizontal\": {},\n\t\t\t\t\"vertical\": {}\n\t\t\t},\n\t\t\t\"requires\": [\"text-field\", { \"symbol-placement\": [\"point\"] }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-rotate\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"period\": 360,\n\t\t\t\"units\": \"degrees\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-padding\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 2,\n\t\t\t\"minimum\": 0,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-keep-upright\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": true,\n\t\t\t\"requires\": [\n\t\t\t\t\"text-field\",\n\t\t\t\t{ \"text-rotation-alignment\": \"map\" },\n\t\t\t\t{ \"symbol-placement\": [\"line\", \"line-center\"] }\n\t\t\t],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-transform\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"none\": {},\n\t\t\t\t\"uppercase\": {},\n\t\t\t\t\"lowercase\": {}\n\t\t\t},\n\t\t\t\"default\": \"none\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-offset\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"units\": \"ems\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"requires\": [\"text-field\", { \"!\": \"text-radial-offset\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-allow-overlap\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"requires\": [\"text-field\", { \"!\": \"text-overlap\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-overlap\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"never\": {},\n\t\t\t\t\"always\": {},\n\t\t\t\t\"cooperative\": {}\n\t\t\t},\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-ignore-placement\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-optional\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": false,\n\t\t\t\"requires\": [\"text-field\", \"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"symbol-height-offset\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"units\": \"meters\",\n\t\t\t\"requires\": [{ \"symbol-placement\": [\"point\"] }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"symbol-height-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"ground\": {},\n\t\t\t\t\"absolute\": {}\n\t\t\t},\n\t\t\t\"default\": \"ground\",\n\t\t\t\"requires\": [\"symbol-height-offset\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"visibility\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"visible\": {},\n\t\t\t\t\"none\": {}\n\t\t\t},\n\t\t\t\"default\": \"visible\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"global-state\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tlayout_raster: { \"visibility\": {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"visible\": {},\n\t\t\t\"none\": {}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"expression\": {\n\t\t\t\"interpolated\": false,\n\t\t\t\"parameters\": [\"global-state\"]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t} },\n\tlayout_hillshade: { \"visibility\": {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"visible\": {},\n\t\t\t\"none\": {}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"expression\": {\n\t\t\t\"interpolated\": false,\n\t\t\t\"parameters\": [\"global-state\"]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t} },\n\t\"layout_color-relief\": { \"visibility\": {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"visible\": {},\n\t\t\t\"none\": {}\n\t\t},\n\t\t\"default\": \"visible\",\n\t\t\"expression\": {\n\t\t\t\"interpolated\": false,\n\t\t\t\"parameters\": [\"global-state\"]\n\t\t},\n\t\t\"property-type\": \"data-constant\"\n\t} },\n\tfilter: {\n\t\t\"type\": \"boolean\",\n\t\t\"expression\": {\n\t\t\t\"interpolated\": false,\n\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t},\n\t\t\"property-type\": \"data-driven\"\n\t},\n\tfilter_operator: {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"==\": {},\n\t\t\t\"!=\": {},\n\t\t\t\">\": {},\n\t\t\t\">=\": {},\n\t\t\t\"<\": {},\n\t\t\t\"<=\": {},\n\t\t\t\"in\": {},\n\t\t\t\"!in\": {},\n\t\t\t\"all\": {},\n\t\t\t\"any\": {},\n\t\t\t\"none\": {},\n\t\t\t\"has\": {},\n\t\t\t\"!has\": {}\n\t\t}\n\t},\n\tgeometry_type: {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"Point\": {},\n\t\t\t\"LineString\": {},\n\t\t\t\"Polygon\": {}\n\t\t}\n\t},\n\t\"function\": {\n\t\t\"expression\": { \"type\": \"expression\" },\n\t\t\"stops\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"function_stop\"\n\t\t},\n\t\t\"base\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0\n\t\t},\n\t\t\"property\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"default\": \"$zoom\"\n\t\t},\n\t\t\"type\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"identity\": {},\n\t\t\t\t\"exponential\": {},\n\t\t\t\t\"interval\": {},\n\t\t\t\t\"categorical\": {}\n\t\t\t},\n\t\t\t\"default\": \"exponential\"\n\t\t},\n\t\t\"colorSpace\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"rgb\": {},\n\t\t\t\t\"lab\": {},\n\t\t\t\t\"hcl\": {}\n\t\t\t},\n\t\t\t\"default\": \"rgb\"\n\t\t},\n\t\t\"default\": {\n\t\t\t\"type\": \"*\",\n\t\t\t\"required\": false\n\t\t}\n\t},\n\tfunction_stop: {\n\t\t\"type\": \"array\",\n\t\t\"minimum\": 0,\n\t\t\"maximum\": 24,\n\t\t\"value\": [\"number\", \"color\"],\n\t\t\"length\": 2\n\t},\n\texpression: {\n\t\t\"type\": \"array\",\n\t\t\"value\": \"expression_name\",\n\t\t\"minimum\": 1\n\t},\n\tlight: {\n\t\t\"anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"default\": \"viewport\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"transition\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t}\n\t\t},\n\t\t\"position\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"default\": [\n\t\t\t\t1.15,\n\t\t\t\t210,\n\t\t\t\t30\n\t\t\t],\n\t\t\t\"length\": 3,\n\t\t\t\"value\": \"number\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t}\n\t\t},\n\t\t\"color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": \"#ffffff\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t},\n\t\t\"intensity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": .5,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t}\n\t},\n\tsky: {\n\t\t\"sky-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": \"#88C6FC\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t},\n\t\t\"horizon-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": \"#ffffff\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t},\n\t\t\"fog-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": \"#ffffff\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t},\n\t\t\"fog-ground-blend\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": .5,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t},\n\t\t\"horizon-fog-blend\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": .8,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t},\n\t\t\"sky-horizon-blend\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": .8,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t},\n\t\t\"atmosphere-blend\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"property-type\": \"data-constant\",\n\t\t\t\"default\": .8,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"transition\": true\n\t\t}\n\t},\n\tterrain: {\n\t\t\"source\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"required\": true\n\t\t},\n\t\t\"exaggeration\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"default\": 1\n\t\t}\n\t},\n\tprojection: { \"type\": {\n\t\t\"type\": \"projectionDefinition\",\n\t\t\"default\": \"mercator\",\n\t\t\"property-type\": \"data-constant\",\n\t\t\"transition\": false,\n\t\t\"expression\": {\n\t\t\t\"interpolated\": true,\n\t\t\t\"parameters\": [\"zoom\"]\n\t\t}\n\t} },\n\tpaint: [\n\t\t\"paint_fill\",\n\t\t\"paint_line\",\n\t\t\"paint_circle\",\n\t\t\"paint_heatmap\",\n\t\t\"paint_fill-extrusion\",\n\t\t\"paint_symbol\",\n\t\t\"paint_raster\",\n\t\t\"paint_hillshade\",\n\t\t\"paint_color-relief\",\n\t\t\"paint_background\"\n\t],\n\tpaint_fill: {\n\t\t\"fill-antialias\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"fill-layer-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"global-state\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-layer-blend\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"normal\": {},\n\t\t\t\t\"multiply\": {},\n\t\t\t\t\"color\": {},\n\t\t\t\t\"luminosity\": {},\n\t\t\t\t\"plus-lighter\": {},\n\t\t\t\t\"screen\": {},\n\t\t\t\t\"overlay\": {}\n\t\t\t},\n\t\t\t\"default\": \"normal\",\n\t\t\t\"property-type\": \"constant\",\n\t\t\t\"transition\": false\n\t\t},\n\t\t\"fill-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"fill-outline-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [{ \"!\": \"fill-pattern\" }, { \"fill-antialias\": true }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"fill-translate\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-translate-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"map\",\n\t\t\t\"requires\": [\"fill-translate\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-pattern\": {\n\t\t\t\"type\": \"resolvedImage\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"cross-faded-data-driven\"\n\t\t}\n\t},\n\t\"paint_fill-extrusion\": {\n\t\t\"fill-extrusion-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-extrusion-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [{ \"!\": \"fill-extrusion-pattern\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\",\n\t\t\t\t\t\"elevation\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"fill-extrusion-translate\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-extrusion-translate-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"map\",\n\t\t\t\"requires\": [\"fill-extrusion-translate\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"fill-extrusion-pattern\": {\n\t\t\t\"type\": \"resolvedImage\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"cross-faded-data-driven\"\n\t\t},\n\t\t\"fill-extrusion-height\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"units\": \"meters\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"fill-extrusion-base\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"units\": \"meters\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [\"fill-extrusion-height\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"fill-extrusion-vertical-gradient\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"default\": true,\n\t\t\t\"transition\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tpaint_line: {\n\t\t\"line-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-layer-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\", \"global-state\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"line-layer-blend\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"normal\": {},\n\t\t\t\t\"multiply\": {},\n\t\t\t\t\"color\": {},\n\t\t\t\t\"luminosity\": {},\n\t\t\t\t\"plus-lighter\": {},\n\t\t\t\t\"screen\": {},\n\t\t\t\t\"overlay\": {}\n\t\t\t},\n\t\t\t\"default\": \"normal\",\n\t\t\t\"property-type\": \"constant\",\n\t\t\t\"transition\": false\n\t\t},\n\t\t\"line-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [{ \"!\": \"line-pattern\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-translate\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"line-translate-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"map\",\n\t\t\t\"requires\": [\"line-translate\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"line-width\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-gap-width\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-offset\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-blur\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"line-dasharray\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"line widths\",\n\t\t\t\"requires\": [{ \"!\": \"line-pattern\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"cross-faded-data-driven\"\n\t\t},\n\t\t\"line-pattern\": {\n\t\t\t\"type\": \"resolvedImage\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\", \"feature\"]\n\t\t\t},\n\t\t\t\"property-type\": \"cross-faded-data-driven\"\n\t\t},\n\t\t\"line-gradient\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"transition\": false,\n\t\t\t\"requires\": [\n\t\t\t\t{ \"!\": \"line-dasharray\" },\n\t\t\t\t{ \"!\": \"line-pattern\" },\n\t\t\t\t{\n\t\t\t\t\t\"source\": \"geojson\",\n\t\t\t\t\t\"has\": { \"lineMetrics\": true }\n\t\t\t\t}\n\t\t\t],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"line-progress\"]\n\t\t\t},\n\t\t\t\"property-type\": \"color-ramp\"\n\t\t}\n\t},\n\tpaint_circle: {\n\t\t\"circle-radius\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 5,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"circle-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"circle-blur\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"circle-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"circle-translate\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"circle-translate-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"map\",\n\t\t\t\"requires\": [\"circle-translate\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"circle-pitch-scale\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"map\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"circle-pitch-alignment\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"viewport\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"circle-stroke-width\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"circle-stroke-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"circle-stroke-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t}\n\t},\n\tpaint_heatmap: {\n\t\t\"heatmap-radius\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 30,\n\t\t\t\"minimum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"heatmap-weight\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"heatmap-intensity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"heatmap-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": [\n\t\t\t\t\"interpolate\",\n\t\t\t\t[\"linear\"],\n\t\t\t\t[\"heatmap-density\"],\n\t\t\t\t0,\n\t\t\t\t\"rgba(0, 0, 255, 0)\",\n\t\t\t\t.1,\n\t\t\t\t\"royalblue\",\n\t\t\t\t.3,\n\t\t\t\t\"cyan\",\n\t\t\t\t.5,\n\t\t\t\t\"lime\",\n\t\t\t\t.7,\n\t\t\t\t\"yellow\",\n\t\t\t\t1,\n\t\t\t\t\"red\"\n\t\t\t],\n\t\t\t\"transition\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"heatmap-density\"]\n\t\t\t},\n\t\t\t\"property-type\": \"color-ramp\"\n\t\t},\n\t\t\"heatmap-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tpaint_symbol: {\n\t\t\"icon-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-halo-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"rgba(0, 0, 0, 0)\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-halo-width\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-halo-blur\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"icon-translate\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"icon-image\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"icon-translate-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"map\",\n\t\t\t\"requires\": [\"icon-image\", \"icon-translate\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"overridable\": true,\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-halo-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"rgba(0, 0, 0, 0)\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-halo-width\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-halo-blur\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t\"zoom\",\n\t\t\t\t\t\"feature\",\n\t\t\t\t\t\"feature-state\"\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"property-type\": \"data-driven\"\n\t\t},\n\t\t\"text-translate\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"value\": \"number\",\n\t\t\t\"length\": 2,\n\t\t\t\"default\": [0, 0],\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"pixels\",\n\t\t\t\"requires\": [\"text-field\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"text-translate-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"map\",\n\t\t\t\"requires\": [\"text-field\", \"text-translate\"],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tpaint_raster: {\n\t\t\"raster-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"raster-hue-rotate\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"period\": 360,\n\t\t\t\"transition\": true,\n\t\t\t\"units\": \"degrees\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"raster-brightness-min\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"raster-brightness-max\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"raster-saturation\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": -1,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"raster-contrast\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": -1,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"resampling\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"linear\": {},\n\t\t\t\t\"nearest\": {}\n\t\t\t},\n\t\t\t\"default\": \"linear\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"raster-resampling\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"linear\": {},\n\t\t\t\t\"nearest\": {}\n\t\t\t},\n\t\t\t\"default\": \"linear\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"raster-fade-duration\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 300,\n\t\t\t\"minimum\": 0,\n\t\t\t\"transition\": false,\n\t\t\t\"units\": \"milliseconds\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tpaint_hillshade: {\n\t\t\"hillshade-illumination-direction\": {\n\t\t\t\"type\": \"numberArray\",\n\t\t\t\"default\": 335,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 359,\n\t\t\t\"transition\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"hillshade-illumination-altitude\": {\n\t\t\t\"type\": \"numberArray\",\n\t\t\t\"default\": 45,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 90,\n\t\t\t\"transition\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"hillshade-illumination-anchor\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"map\": {},\n\t\t\t\t\"viewport\": {}\n\t\t\t},\n\t\t\t\"default\": \"viewport\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"hillshade-exaggeration\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": .5,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"hillshade-shadow-color\": {\n\t\t\t\"type\": \"colorArray\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"hillshade-highlight-color\": {\n\t\t\t\"type\": \"colorArray\",\n\t\t\t\"default\": \"#FFFFFF\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"hillshade-accent-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"hillshade-method\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"standard\": {},\n\t\t\t\t\"basic\": {},\n\t\t\t\t\"combined\": {},\n\t\t\t\t\"igor\": {},\n\t\t\t\t\"multidirectional\": {}\n\t\t\t},\n\t\t\t\"default\": \"standard\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"resampling\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"linear\": {},\n\t\t\t\t\"nearest\": {}\n\t\t\t},\n\t\t\t\"default\": \"linear\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\t\"paint_color-relief\": {\n\t\t\"color-relief-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"color-relief-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"transition\": false,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"elevation\"]\n\t\t\t},\n\t\t\t\"property-type\": \"color-ramp\"\n\t\t},\n\t\t\"resampling\": {\n\t\t\t\"type\": \"enum\",\n\t\t\t\"values\": {\n\t\t\t\t\"linear\": {},\n\t\t\t\t\"nearest\": {}\n\t\t\t},\n\t\t\t\"default\": \"linear\",\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\tpaint_background: {\n\t\t\"background-color\": {\n\t\t\t\"type\": \"color\",\n\t\t\t\"default\": \"#000000\",\n\t\t\t\"transition\": true,\n\t\t\t\"requires\": [{ \"!\": \"background-pattern\" }],\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t},\n\t\t\"background-pattern\": {\n\t\t\t\"type\": \"resolvedImage\",\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": false,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"cross-faded\"\n\t\t},\n\t\t\"background-opacity\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 1,\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1,\n\t\t\t\"transition\": true,\n\t\t\t\"expression\": {\n\t\t\t\t\"interpolated\": true,\n\t\t\t\t\"parameters\": [\"zoom\"]\n\t\t\t},\n\t\t\t\"property-type\": \"data-constant\"\n\t\t}\n\t},\n\ttransition: {\n\t\t\"duration\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 300,\n\t\t\t\"minimum\": 0,\n\t\t\t\"units\": \"milliseconds\"\n\t\t},\n\t\t\"delay\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"default\": 0,\n\t\t\t\"minimum\": 0,\n\t\t\t\"units\": \"milliseconds\"\n\t\t}\n\t},\n\t\"property-type\": {\n\t\t\"data-driven\": { \"type\": \"property-type\" },\n\t\t\"cross-faded\": { \"type\": \"property-type\" },\n\t\t\"cross-faded-data-driven\": { \"type\": \"property-type\" },\n\t\t\"color-ramp\": { \"type\": \"property-type\" },\n\t\t\"data-constant\": { \"type\": \"property-type\" },\n\t\t\"constant\": { \"type\": \"property-type\" }\n\t},\n\tpromoteId: { \"*\": { \"type\": \"string\" } },\n\tinterpolation: {\n\t\t\"type\": \"array\",\n\t\t\"value\": \"interpolation_name\",\n\t\t\"minimum\": 1\n\t},\n\tinterpolation_name: {\n\t\t\"type\": \"enum\",\n\t\t\"values\": {\n\t\t\t\"linear\": { \"syntax\": {\n\t\t\t\t\"overloads\": [{\n\t\t\t\t\t\"parameters\": [],\n\t\t\t\t\t\"output-type\": \"interpolation\"\n\t\t\t\t}],\n\t\t\t\t\"parameters\": []\n\t\t\t} },\n\t\t\t\"exponential\": { \"syntax\": {\n\t\t\t\t\"overloads\": [{\n\t\t\t\t\t\"parameters\": [\"base\"],\n\t\t\t\t\t\"output-type\": \"interpolation\"\n\t\t\t\t}],\n\t\t\t\t\"parameters\": [{\n\t\t\t\t\t\"name\": \"base\",\n\t\t\t\t\t\"type\": \"number literal\"\n\t\t\t\t}]\n\t\t\t} },\n\t\t\t\"cubic-bezier\": { \"syntax\": {\n\t\t\t\t\"overloads\": [{\n\t\t\t\t\t\"parameters\": [\n\t\t\t\t\t\t\"x1\",\n\t\t\t\t\t\t\"y1\",\n\t\t\t\t\t\t\"x2\",\n\t\t\t\t\t\t\"y2\"\n\t\t\t\t\t],\n\t\t\t\t\t\"output-type\": \"interpolation\"\n\t\t\t\t}],\n\t\t\t\t\"parameters\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"name\": \"x1\",\n\t\t\t\t\t\t\"type\": \"number literal\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"name\": \"y1\",\n\t\t\t\t\t\t\"type\": \"number literal\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"name\": \"x2\",\n\t\t\t\t\t\t\"type\": \"number literal\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"name\": \"y2\",\n\t\t\t\t\t\t\"type\": \"number literal\"\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t} }\n\t\t}\n\t}\n};\nexport { v8_default as default };\n\n//# sourceMappingURL=v8.mjs.map", "import v8_default from \"./v8.mjs\";\n// src/reference/latest.ts\nconst latest = v8_default;\nexport { latest };\n\n//# sourceMappingURL=latest.mjs.map", "// src/util/ref_properties.ts\nconst refProperties = [\n\t\"type\",\n\t\"source\",\n\t\"source-layer\",\n\t\"minzoom\",\n\t\"maxzoom\",\n\t\"filter\",\n\t\"layout\"\n];\nexport { refProperties };\n\n//# sourceMappingURL=ref_properties.mjs.map", "import { refProperties } from \"./util/ref_properties.mjs\";\n// src/deref.ts\nfunction deref(layer, parent) {\n\tconst result = {};\n\tfor (const k in layer) if (k !== \"ref\") result[k] = layer[k];\n\trefProperties.forEach((k) => {\n\t\tif (k in parent) result[k] = parent[k];\n\t});\n\treturn result;\n}\n/**\n*\n* The input is not modified. The output may contain references to portions\n* of the input.\n*\n* @param layers - array of layers, some of which may contain `ref` properties\n* whose value is the `id` of another property\n* @returns a new array where such layers have been augmented with the 'type', 'source', etc. properties\n* from the parent layer, and the `ref` property has been removed.\n*/\nfunction derefLayers(layers) {\n\tlayers = layers.slice();\n\tconst map = Object.create(null);\n\tfor (let i = 0; i < layers.length; i++) map[layers[i].id] = layers[i];\n\tfor (let i = 0; i < layers.length; i++) if (\"ref\" in layers[i]) layers[i] = deref(layers[i], map[layers[i].ref]);\n\treturn layers;\n}\nexport { derefLayers };\n\n//# sourceMappingURL=deref.mjs.map", "// src/util/deep_equal.ts\n/**\n* Deeply compares two object literals.\n*\n* @private\n*/\nfunction deepEqual(a, b) {\n\tif (Array.isArray(a)) {\n\t\tif (!Array.isArray(b) || a.length !== b.length) return false;\n\t\tfor (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;\n\t\treturn true;\n\t}\n\tif (typeof a === \"object\" && a !== null && b !== null) {\n\t\tif (!(typeof b === \"object\")) return false;\n\t\tif (Object.keys(a).length !== Object.keys(b).length) return false;\n\t\tfor (const key in a) if (!deepEqual(a[key], b[key])) return false;\n\t\treturn true;\n\t}\n\treturn a === b;\n}\nexport { deepEqual };\n\n//# sourceMappingURL=deep_equal.mjs.map", "import { deepEqual } from \"./util/deep_equal.mjs\";\n// src/diff.ts\n/**\n* The main reason for this method is to allow type check when adding a command to the array.\n* @param commands - The commands array to add to\n* @param command - The command to add\n*/\nfunction addCommand(commands, command) {\n\tcommands.push(command);\n}\nfunction addSource(sourceId, after, commands) {\n\taddCommand(commands, {\n\t\tcommand: \"addSource\",\n\t\targs: [sourceId, after[sourceId]]\n\t});\n}\nfunction removeSource(sourceId, commands, sourcesRemoved) {\n\taddCommand(commands, {\n\t\tcommand: \"removeSource\",\n\t\targs: [sourceId]\n\t});\n\tsourcesRemoved[sourceId] = true;\n}\nfunction updateSource(sourceId, after, commands, sourcesRemoved) {\n\tremoveSource(sourceId, commands, sourcesRemoved);\n\taddSource(sourceId, after, commands);\n}\nfunction canUpdateGeoJSON(before, after, sourceId) {\n\tlet prop;\n\tfor (prop in before[sourceId]) {\n\t\tif (!Object.prototype.hasOwnProperty.call(before[sourceId], prop)) continue;\n\t\tif (prop !== \"data\" && !deepEqual(before[sourceId][prop], after[sourceId][prop])) return false;\n\t}\n\tfor (prop in after[sourceId]) {\n\t\tif (!Object.prototype.hasOwnProperty.call(after[sourceId], prop)) continue;\n\t\tif (prop !== \"data\" && !deepEqual(before[sourceId][prop], after[sourceId][prop])) return false;\n\t}\n\treturn true;\n}\nfunction diffSources(before, after, commands, sourcesRemoved) {\n\tbefore = before || {};\n\tafter = after || {};\n\tlet sourceId;\n\tfor (sourceId in before) {\n\t\tif (!Object.prototype.hasOwnProperty.call(before, sourceId)) continue;\n\t\tif (!Object.prototype.hasOwnProperty.call(after, sourceId)) removeSource(sourceId, commands, sourcesRemoved);\n\t}\n\tfor (sourceId in after) {\n\t\tif (!Object.prototype.hasOwnProperty.call(after, sourceId)) continue;\n\t\tif (!Object.prototype.hasOwnProperty.call(before, sourceId)) addSource(sourceId, after, commands);\n\t\telse if (!deepEqual(before[sourceId], after[sourceId])) {\n\t\t\tif (before[sourceId].type === \"geojson\" && after[sourceId].type === \"geojson\" && canUpdateGeoJSON(before, after, sourceId)) addCommand(commands, {\n\t\t\t\tcommand: \"setGeoJSONSourceData\",\n\t\t\t\targs: [sourceId, after[sourceId].data]\n\t\t\t});\n\t\t\telse updateSource(sourceId, after, commands, sourcesRemoved);\n\t\t}\n\t}\n}\n/**\n* Adds a paint or layout property command for a single property of a layer.\n* The property names are taken from a layer's paint/layout object, so they are known to be\n* valid names for the given command, which a `for ... in` loop over that object can't express.\n* @param after - The paint or layout object to take the property value from\n* @param commands - The commands array to add to\n* @param layerId - The id of the layer the property belongs to\n* @param prop - The name of the property that changed\n* @param command - The command to add\n*/\nfunction addPropertyCommand(after, commands, layerId, prop, command) {\n\tif (command === \"setPaintProperty\") addCommand(commands, {\n\t\tcommand,\n\t\targs: [\n\t\t\tlayerId,\n\t\t\tprop,\n\t\t\tafter[prop]\n\t\t]\n\t});\n\telse addCommand(commands, {\n\t\tcommand,\n\t\targs: [\n\t\t\tlayerId,\n\t\t\tprop,\n\t\t\tafter[prop]\n\t\t]\n\t});\n}\nfunction diffLayerPropertyChanges(before, after, commands, layerId, command) {\n\tbefore = before || {};\n\tafter = after || {};\n\tfor (const prop in before) {\n\t\tif (!Object.prototype.hasOwnProperty.call(before, prop)) continue;\n\t\tif (!deepEqual(before[prop], after[prop])) addPropertyCommand(after, commands, layerId, prop, command);\n\t}\n\tfor (const prop in after) {\n\t\tif (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop)) continue;\n\t\tif (!deepEqual(before[prop], after[prop])) addPropertyCommand(after, commands, layerId, prop, command);\n\t}\n}\nfunction pluckId(layer) {\n\treturn layer.id;\n}\nfunction indexById(group, layer) {\n\tgroup[layer.id] = layer;\n\treturn group;\n}\nfunction diffLayers(before, after, commands) {\n\tbefore = before || [];\n\tafter = after || [];\n\tconst beforeOrder = before.map(pluckId);\n\tconst afterOrder = after.map(pluckId);\n\tconst beforeIndex = before.reduce(indexById, {});\n\tconst afterIndex = after.reduce(indexById, {});\n\tconst tracker = beforeOrder.slice();\n\tconst clean = Object.create(null);\n\tlet layerId;\n\tlet beforeLayer;\n\tlet afterLayer;\n\tlet insertBeforeLayerId;\n\tlet prop;\n\tfor (let i = 0, d = 0; i < beforeOrder.length; i++) {\n\t\tlayerId = beforeOrder[i];\n\t\tif (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) {\n\t\t\taddCommand(commands, {\n\t\t\t\tcommand: \"removeLayer\",\n\t\t\t\targs: [layerId]\n\t\t\t});\n\t\t\ttracker.splice(tracker.indexOf(layerId, d), 1);\n\t\t} else d++;\n\t}\n\tfor (let i = 0, d = 0; i < afterOrder.length; i++) {\n\t\tlayerId = afterOrder[afterOrder.length - 1 - i];\n\t\tif (tracker[tracker.length - 1 - i] === layerId) continue;\n\t\tif (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) {\n\t\t\taddCommand(commands, {\n\t\t\t\tcommand: \"removeLayer\",\n\t\t\t\targs: [layerId]\n\t\t\t});\n\t\t\ttracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);\n\t\t} else d++;\n\t\tinsertBeforeLayerId = tracker[tracker.length - i];\n\t\taddCommand(commands, {\n\t\t\tcommand: \"addLayer\",\n\t\t\targs: [afterIndex[layerId], insertBeforeLayerId]\n\t\t});\n\t\ttracker.splice(tracker.length - i, 0, layerId);\n\t\tclean[layerId] = true;\n\t}\n\tfor (let i = 0; i < afterOrder.length; i++) {\n\t\tlayerId = afterOrder[i];\n\t\tbeforeLayer = beforeIndex[layerId];\n\t\tafterLayer = afterIndex[layerId];\n\t\tif (clean[layerId] || deepEqual(beforeLayer, afterLayer)) continue;\n\t\tif (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer[\"source-layer\"], afterLayer[\"source-layer\"]) || !deepEqual(beforeLayer.type, afterLayer.type)) {\n\t\t\taddCommand(commands, {\n\t\t\t\tcommand: \"removeLayer\",\n\t\t\t\targs: [layerId]\n\t\t\t});\n\t\t\tinsertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];\n\t\t\taddCommand(commands, {\n\t\t\t\tcommand: \"addLayer\",\n\t\t\t\targs: [afterLayer, insertBeforeLayerId]\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tdiffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, \"setLayoutProperty\");\n\t\tdiffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, \"setPaintProperty\");\n\t\tif (!deepEqual(beforeLayer.filter, afterLayer.filter)) addCommand(commands, {\n\t\t\tcommand: \"setFilter\",\n\t\t\targs: [layerId, afterLayer.filter]\n\t\t});\n\t\tif (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) addCommand(commands, {\n\t\t\tcommand: \"setLayerZoomRange\",\n\t\t\targs: [\n\t\t\t\tlayerId,\n\t\t\t\tafterLayer.minzoom,\n\t\t\t\tafterLayer.maxzoom\n\t\t\t]\n\t\t});\n\t\tfor (prop in beforeLayer) {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(beforeLayer, prop)) continue;\n\t\t\tif (prop === \"layout\" || prop === \"paint\" || prop === \"filter\" || prop === \"metadata\" || prop === \"minzoom\" || prop === \"maxzoom\") continue;\n\t\t\tif (prop.indexOf(\"paint.\") === 0) diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, \"setPaintProperty\");\n\t\t\telse if (!deepEqual(beforeLayer[prop], afterLayer[prop])) addCommand(commands, {\n\t\t\t\tcommand: \"setLayerProperty\",\n\t\t\t\targs: [\n\t\t\t\t\tlayerId,\n\t\t\t\t\tprop,\n\t\t\t\t\tafterLayer[prop]\n\t\t\t\t]\n\t\t\t});\n\t\t}\n\t\tfor (prop in afterLayer) {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop)) continue;\n\t\t\tif (prop === \"layout\" || prop === \"paint\" || prop === \"filter\" || prop === \"metadata\" || prop === \"minzoom\" || prop === \"maxzoom\") continue;\n\t\t\tif (prop.indexOf(\"paint.\") === 0) diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, \"setPaintProperty\");\n\t\t\telse if (!deepEqual(beforeLayer[prop], afterLayer[prop])) addCommand(commands, {\n\t\t\t\tcommand: \"setLayerProperty\",\n\t\t\t\targs: [\n\t\t\t\t\tlayerId,\n\t\t\t\t\tprop,\n\t\t\t\t\tafterLayer[prop]\n\t\t\t\t]\n\t\t\t});\n\t\t}\n\t}\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 maplibre-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 diff(before, after) {\n\tif (!before) return [{\n\t\tcommand: \"setStyle\",\n\t\targs: [after]\n\t}];\n\tlet commands = [];\n\ttry {\n\t\tif (!deepEqual(before.version, after.version)) return [{\n\t\t\tcommand: \"setStyle\",\n\t\t\targs: [after]\n\t\t}];\n\t\tif (!deepEqual(before.center, after.center)) commands.push({\n\t\t\tcommand: \"setCenter\",\n\t\t\targs: [after.center]\n\t\t});\n\t\tif (!deepEqual(before.state, after.state)) commands.push({\n\t\t\tcommand: \"setGlobalState\",\n\t\t\targs: [after.state]\n\t\t});\n\t\tif (!deepEqual(before.centerAltitude, after.centerAltitude)) commands.push({\n\t\t\tcommand: \"setCenterAltitude\",\n\t\t\targs: [after.centerAltitude]\n\t\t});\n\t\tif (!deepEqual(before.zoom, after.zoom)) commands.push({\n\t\t\tcommand: \"setZoom\",\n\t\t\targs: [after.zoom]\n\t\t});\n\t\tif (!deepEqual(before.bearing, after.bearing)) commands.push({\n\t\t\tcommand: \"setBearing\",\n\t\t\targs: [after.bearing]\n\t\t});\n\t\tif (!deepEqual(before.pitch, after.pitch)) commands.push({\n\t\t\tcommand: \"setPitch\",\n\t\t\targs: [after.pitch]\n\t\t});\n\t\tif (!deepEqual(before.roll, after.roll)) commands.push({\n\t\t\tcommand: \"setRoll\",\n\t\t\targs: [after.roll]\n\t\t});\n\t\tif (!deepEqual(before.sprite, after.sprite)) commands.push({\n\t\t\tcommand: \"setSprite\",\n\t\t\targs: [after.sprite]\n\t\t});\n\t\tif (!deepEqual(before.glyphs, after.glyphs)) commands.push({\n\t\t\tcommand: \"setGlyphs\",\n\t\t\targs: [after.glyphs]\n\t\t});\n\t\tif (!deepEqual(before[\"font-faces\"], after[\"font-faces\"])) commands.push({\n\t\t\tcommand: \"setFontFaces\",\n\t\t\targs: [after[\"font-faces\"]]\n\t\t});\n\t\tif (!deepEqual(before.transition, after.transition)) commands.push({\n\t\t\tcommand: \"setTransition\",\n\t\t\targs: [after.transition]\n\t\t});\n\t\tif (!deepEqual(before.light, after.light)) commands.push({\n\t\t\tcommand: \"setLight\",\n\t\t\targs: [after.light]\n\t\t});\n\t\tconst terrainChanged = !deepEqual(before.terrain, after.terrain);\n\t\tif (terrainChanged && !after.terrain) commands.push({\n\t\t\tcommand: \"setTerrain\",\n\t\t\targs: [void 0]\n\t\t});\n\t\tif (!deepEqual(before.sky, after.sky)) commands.push({\n\t\t\tcommand: \"setSky\",\n\t\t\targs: [after.sky]\n\t\t});\n\t\tif (!deepEqual(before.projection, after.projection)) commands.push({\n\t\t\tcommand: \"setProjection\",\n\t\t\targs: [after.projection]\n\t\t});\n\t\tconst sourcesRemoved = {};\n\t\tconst removeOrAddSourceCommands = [];\n\t\tdiffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);\n\t\tconst beforeLayers = [];\n\t\tif (before.layers) before.layers.forEach((layer) => {\n\t\t\tif (\"source\" in layer && sourcesRemoved[layer.source]) commands.push({\n\t\t\t\tcommand: \"removeLayer\",\n\t\t\t\targs: [layer.id]\n\t\t\t});\n\t\t\telse beforeLayers.push(layer);\n\t\t});\n\t\tcommands = commands.concat(removeOrAddSourceCommands);\n\t\tdiffLayers(beforeLayers, after.layers, commands);\n\t\tif (terrainChanged && after.terrain) commands.push({\n\t\t\tcommand: \"setTerrain\",\n\t\t\targs: [after.terrain]\n\t\t});\n\t} catch (e) {\n\t\tconsole.warn(\"Unable to compute style diff:\", e);\n\t\tcommands = [{\n\t\t\tcommand: \"setStyle\",\n\t\t\targs: [after]\n\t\t}];\n\t}\n\treturn commands;\n}\nexport { diff };\n\n//# sourceMappingURL=diff.mjs.map", "// src/error/validation_error.ts\nvar ValidationError = class {\n\tconstructor(key, value, message, identifier, severity = \"error\") {\n\t\tthis.message = (key ? `${key}: ` : \"\") + message;\n\t\tif (identifier) this.identifier = identifier;\n\t\tthis.severity = severity;\n\t\tif (value !== null && value !== void 0 && value.__line__) this.line = value.__line__;\n\t}\n};\nexport { ValidationError };\n\n//# sourceMappingURL=validation_error.mjs.map", "// src/expression/types.ts\nconst NullType = { kind: \"null\" };\nconst NumberType = { kind: \"number\" };\nconst StringType = { kind: \"string\" };\nconst BooleanType = { kind: \"boolean\" };\nconst ColorType = { kind: \"color\" };\nconst ProjectionDefinitionType = { kind: \"projectionDefinition\" };\nconst ObjectType = { kind: \"object\" };\nconst ValueType = { kind: \"value\" };\nconst ErrorType = { kind: \"error\" };\nconst CollatorType = { kind: \"collator\" };\nconst FormattedType = { kind: \"formatted\" };\nconst PaddingType = { kind: \"padding\" };\nconst ColorArrayType = { kind: \"colorArray\" };\nconst NumberArrayType = { kind: \"numberArray\" };\nconst ResolvedImageType = { kind: \"resolvedImage\" };\nconst VariableAnchorOffsetCollectionType = { kind: \"variableAnchorOffsetCollection\" };\nfunction array(itemType, N) {\n\treturn {\n\t\tkind: \"array\",\n\t\titemType,\n\t\tN\n\t};\n}\nfunction typeToString(type) {\n\tif (type.kind === \"array\") {\n\t\tconst itemType = typeToString(type.itemType);\n\t\treturn typeof type.N === \"number\" ? `array<${itemType}, ${type.N}>` : type.itemType.kind === \"value\" ? \"array\" : `array<${itemType}>`;\n\t} else return type.kind;\n}\nconst valueMemberTypes = [\n\tNullType,\n\tNumberType,\n\tStringType,\n\tBooleanType,\n\tColorType,\n\tProjectionDefinitionType,\n\tFormattedType,\n\tObjectType,\n\tarray(ValueType),\n\tPaddingType,\n\tNumberArrayType,\n\tColorArrayType,\n\tResolvedImageType,\n\tVariableAnchorOffsetCollectionType\n];\n/**\n* Returns null if `t` is a subtype of `expected`; otherwise returns an\n* error message.\n* @private\n*/\nfunction checkSubtype(expected, t) {\n\tif (t.kind === \"error\") return null;\n\telse if (expected.kind === \"array\") {\n\t\tif (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;\n\t} else if (expected.kind === t.kind) return null;\n\telse if (expected.kind === \"value\") {\n\t\tfor (const memberType of valueMemberTypes) if (!checkSubtype(memberType, t)) return null;\n\t}\n\treturn `Expected ${typeToString(expected)} but found ${typeToString(t)} instead.`;\n}\nfunction isValidType(provided, allowedTypes) {\n\treturn allowedTypes.some((t) => t.kind === provided.kind);\n}\nfunction isValidNativeType(provided, allowedTypes) {\n\treturn allowedTypes.some((t) => {\n\t\tif (t === \"null\") return provided === null;\n\t\telse if (t === \"array\") return Array.isArray(provided);\n\t\telse if (t === \"object\") return provided && !Array.isArray(provided) && typeof provided === \"object\";\n\t\telse return t === typeof provided;\n\t});\n}\n/**\n* Verify whether the specified type is of the same type as the specified sample.\n*\n* @param provided Type to verify\n* @param sample Sample type to reference\n* @returns `true` if both objects are of the same type, `false` otherwise\n* @example basic types\n* if (verifyType(outputType, ValueType)) {\n*     // type narrowed to:\n*     outputType.kind; // 'value'\n* }\n* @example array types\n* if (verifyType(outputType, array(NumberType))) {\n*     // type narrowed to:\n*     outputType.kind; // 'array'\n*     outputType.itemType; // NumberTypeT\n*     outputType.itemType.kind; // 'number'\n* }\n*/\nfunction verifyType(provided, sample) {\n\tif (provided.kind === \"array\" && sample.kind === \"array\") return provided.itemType.kind === sample.itemType.kind && typeof provided.N === \"number\";\n\treturn provided.kind === sample.kind;\n}\nexport { BooleanType, CollatorType, ColorArrayType, ColorType, ErrorType, FormattedType, NullType, NumberArrayType, NumberType, ObjectType, PaddingType, ProjectionDefinitionType, ResolvedImageType, StringType, ValueType, VariableAnchorOffsetCollectionType, array, checkSubtype, isValidNativeType, isValidType, typeToString, verifyType };\n\n//# sourceMappingURL=types.mjs.map", "// src/expression/types/color_spaces.ts\nconst Xn = .96422;\nconst Yn = 1;\nconst Zn = .82521;\nconst t0 = 4 / 29;\nconst t1 = 6 / 29;\nconst t2 = 3 * t1 * t1;\nconst t3 = t1 * t1 * t1;\nconst deg2rad = Math.PI / 180;\nconst rad2deg = 180 / Math.PI;\nfunction constrainAngle(angle) {\n\tangle = angle % 360;\n\tif (angle < 0) angle += 360;\n\treturn angle;\n}\nfunction rgbToLab([r, g, b, alpha]) {\n\tr = rgb2xyz(r);\n\tg = rgb2xyz(g);\n\tb = rgb2xyz(b);\n\tlet x, z;\n\tconst y = xyz2lab((.2225045 * r + .7168786 * g + .0606169 * b) / Yn);\n\tif (r === g && g === b) x = z = y;\n\telse {\n\t\tx = xyz2lab((.4360747 * r + .3850649 * g + .1430804 * b) / Xn);\n\t\tz = xyz2lab((.0139322 * r + .0971045 * g + .7141733 * b) / Zn);\n\t}\n\tconst l = 116 * y - 16;\n\treturn [\n\t\tl < 0 ? 0 : l,\n\t\t500 * (x - y),\n\t\t200 * (y - z),\n\t\talpha\n\t];\n}\nfunction rgb2xyz(x) {\n\treturn x <= .04045 ? x / 12.92 : Math.pow((x + .055) / 1.055, 2.4);\n}\nfunction xyz2lab(t) {\n\treturn t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\nfunction labToRgb([l, a, b, alpha]) {\n\tlet y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200;\n\ty = Yn * lab2xyz(y);\n\tx = Xn * lab2xyz(x);\n\tz = Zn * lab2xyz(z);\n\treturn [\n\t\txyz2rgb(3.1338561 * x - 1.6168667 * y - .4906146 * z),\n\t\txyz2rgb(-.9787684 * x + 1.9161415 * y + .033454 * z),\n\t\txyz2rgb(.0719453 * x - .2289914 * y + 1.4052427 * z),\n\t\talpha\n\t];\n}\nfunction xyz2rgb(x) {\n\tx = x <= .00304 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - .055;\n\treturn x < 0 ? 0 : x > 1 ? 1 : x;\n}\nfunction lab2xyz(t) {\n\treturn t > t1 ? t * t * t : t2 * (t - t0);\n}\nfunction rgbToHcl(rgbColor) {\n\tconst [l, a, b, alpha] = rgbToLab(rgbColor);\n\tconst c = Math.sqrt(a * a + b * b);\n\treturn [\n\t\tMath.round(c * 1e4) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN,\n\t\tc,\n\t\tl,\n\t\talpha\n\t];\n}\nfunction hclToRgb([h, c, l, alpha]) {\n\th = isNaN(h) ? 0 : h * deg2rad;\n\treturn labToRgb([\n\t\tl,\n\t\tMath.cos(h) * c,\n\t\tMath.sin(h) * c,\n\t\talpha\n\t]);\n}\nfunction hslToRgb([h, s, l, alpha]) {\n\th = constrainAngle(h);\n\ts /= 100;\n\tl /= 100;\n\tfunction f(n) {\n\t\tconst k = (n + h / 30) % 12;\n\t\tconst a = s * Math.min(l, 1 - l);\n\t\treturn l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));\n\t}\n\treturn [\n\t\tf(0),\n\t\tf(8),\n\t\tf(4),\n\t\talpha\n\t];\n}\nexport { hclToRgb, hslToRgb, labToRgb, rgbToHcl, rgbToLab };\n\n//# sourceMappingURL=color_spaces.mjs.map", "// src/util/get_own.ts\nconst hasOwnProperty = Object.hasOwn || function hasOwnProperty(object, key) {\n\treturn Object.prototype.hasOwnProperty.call(object, key);\n};\nfunction getOwn(object, key) {\n\treturn hasOwnProperty(object, key) ? object[key] : void 0;\n}\nexport { getOwn };\n\n//# sourceMappingURL=get_own.mjs.map", "import { hslToRgb } from \"./color_spaces.mjs\";\nimport { getOwn } from \"../../util/get_own.mjs\";\n// src/expression/types/parse_css_color.ts\n/**\n* CSS color parser compliant with CSS Color 4 Specification.\n* Supports: named colors, `transparent` keyword, all rgb hex notations,\n* rgb(), rgba(), hsl() and hsla() functions.\n* Does not round the parsed values to integers from the range 0..255.\n*\n* Syntax:\n*\n* <alpha-value> = <number> | <percentage>\n*         <hue> = <number> | <angle>\n*\n*         rgb() = rgb( <percentage>{3} [ / <alpha-value> ]? ) | rgb( <number>{3} [ / <alpha-value> ]? )\n*         rgb() = rgb( <percentage>#{3} , <alpha-value>? )    | rgb( <number>#{3} , <alpha-value>? )\n*\n*         hsl() = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? )\n*         hsl() = hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )\n*\n* Caveats:\n*   - <angle> - <number> with optional `deg` suffix; `grad`, `rad`, `turn` are not supported\n*   - `none` keyword is not supported\n*   - comments inside rgb()/hsl() are not supported\n*   - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb()\n*   - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl()\n*\n* @param input CSS color string to parse.\n* @returns Color in sRGB color space, with `red`, `green`, `blue`\n* and `alpha` channels normalized to the range 0..1,\n* or `undefined` if the input is not a valid color string.\n*/\nfunction parseCssColor(input) {\n\tinput = input.toLowerCase().trim();\n\tif (input === \"transparent\") return [\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0\n\t];\n\tconst namedColorsMatch = getOwn(namedColors, input);\n\tif (namedColorsMatch) {\n\t\tconst [r, g, b] = namedColorsMatch;\n\t\treturn [\n\t\t\tr / 255,\n\t\t\tg / 255,\n\t\t\tb / 255,\n\t\t\t1\n\t\t];\n\t}\n\tif (input.startsWith(\"#\")) {\n\t\tif (/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(input)) {\n\t\t\tconst step = input.length < 6 ? 1 : 2;\n\t\t\tlet i = 1;\n\t\t\treturn [\n\t\t\t\tparseHex(input.slice(i, i += step)),\n\t\t\t\tparseHex(input.slice(i, i += step)),\n\t\t\t\tparseHex(input.slice(i, i += step)),\n\t\t\t\tparseHex(input.slice(i, i + step) || \"ff\")\n\t\t\t];\n\t\t}\n\t}\n\tif (input.startsWith(\"rgb\")) {\n\t\tconst rgbMatch = input.match(/^rgba?\\(\\s*([\\de.+-]+)(%)?(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)(%)?(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)(%)?(?:\\s*([,\\/])\\s*([\\de.+-]+)(%)?)?\\s*\\)$/);\n\t\tif (rgbMatch) {\n\t\t\tconst [_, r, rp, f1, g, gp, f2, b, bp, f3, a, ap] = rgbMatch;\n\t\t\tconst argFormat = [\n\t\t\t\tf1 || \" \",\n\t\t\t\tf2 || \" \",\n\t\t\t\tf3\n\t\t\t].join(\"\");\n\t\t\tif (argFormat === \"  \" || argFormat === \"  /\" || argFormat === \",,\" || argFormat === \",,,\") {\n\t\t\t\tconst valFormat = [\n\t\t\t\t\trp,\n\t\t\t\t\tgp,\n\t\t\t\t\tbp\n\t\t\t\t].join(\"\");\n\t\t\t\tconst maxValue = valFormat === \"%%%\" ? 100 : valFormat === \"\" ? 255 : 0;\n\t\t\t\tif (maxValue) {\n\t\t\t\t\tconst rgba = [\n\t\t\t\t\t\tclamp(+r / maxValue, 0, 1),\n\t\t\t\t\t\tclamp(+g / maxValue, 0, 1),\n\t\t\t\t\t\tclamp(+b / maxValue, 0, 1),\n\t\t\t\t\t\ta ? parseAlpha(+a, ap) : 1\n\t\t\t\t\t];\n\t\t\t\t\tif (validateNumbers(rgba)) return rgba;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n\tconst hslMatch = input.match(/^hsla?\\(\\s*([\\de.+-]+)(?:deg)?(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)%(?:\\s+|\\s*(,)\\s*)([\\de.+-]+)%(?:\\s*([,\\/])\\s*([\\de.+-]+)(%)?)?\\s*\\)$/);\n\tif (hslMatch) {\n\t\tconst [_, h, f1, s, f2, l, f3, a, ap] = hslMatch;\n\t\tconst argFormat = [\n\t\t\tf1 || \" \",\n\t\t\tf2 || \" \",\n\t\t\tf3\n\t\t].join(\"\");\n\t\tif (argFormat === \"  \" || argFormat === \"  /\" || argFormat === \",,\" || argFormat === \",,,\") {\n\t\t\tconst hsla = [\n\t\t\t\t+h,\n\t\t\t\tclamp(+s, 0, 100),\n\t\t\t\tclamp(+l, 0, 100),\n\t\t\t\ta ? parseAlpha(+a, ap) : 1\n\t\t\t];\n\t\t\tif (validateNumbers(hsla)) return hslToRgb(hsla);\n\t\t}\n\t}\n}\nfunction parseHex(hex) {\n\treturn parseInt(hex.padEnd(2, hex), 16) / 255;\n}\nfunction parseAlpha(a, asPercentage) {\n\treturn clamp(asPercentage ? a / 100 : a, 0, 1);\n}\nfunction clamp(n, min, max) {\n\treturn Math.min(Math.max(min, n), max);\n}\n/**\n* The regular expression for numeric values is not super specific, and it may\n* happen that it will accept a value that is not a valid number. In order to\n* detect and eliminate such values this function exists.\n*\n* @param array Array of uncertain numbers.\n* @returns `true` if the specified array contains only valid numbers, `false` otherwise.\n*/\nfunction validateNumbers(array) {\n\treturn !array.some(Number.isNaN);\n}\n/**\n* To generate:\n* - visit {@link https://www.w3.org/TR/css-color-4/#named-colors}\n* - run in the console:\n* @example\n* copy(`{\\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\\s+/).join(', ')}],`).join('\\n')}\\n}`);\n*/\nconst namedColors = {\n\taliceblue: [\n\t\t240,\n\t\t248,\n\t\t255\n\t],\n\tantiquewhite: [\n\t\t250,\n\t\t235,\n\t\t215\n\t],\n\taqua: [\n\t\t0,\n\t\t255,\n\t\t255\n\t],\n\taquamarine: [\n\t\t127,\n\t\t255,\n\t\t212\n\t],\n\tazure: [\n\t\t240,\n\t\t255,\n\t\t255\n\t],\n\tbeige: [\n\t\t245,\n\t\t245,\n\t\t220\n\t],\n\tbisque: [\n\t\t255,\n\t\t228,\n\t\t196\n\t],\n\tblack: [\n\t\t0,\n\t\t0,\n\t\t0\n\t],\n\tblanchedalmond: [\n\t\t255,\n\t\t235,\n\t\t205\n\t],\n\tblue: [\n\t\t0,\n\t\t0,\n\t\t255\n\t],\n\tblueviolet: [\n\t\t138,\n\t\t43,\n\t\t226\n\t],\n\tbrown: [\n\t\t165,\n\t\t42,\n\t\t42\n\t],\n\tburlywood: [\n\t\t222,\n\t\t184,\n\t\t135\n\t],\n\tcadetblue: [\n\t\t95,\n\t\t158,\n\t\t160\n\t],\n\tchartreuse: [\n\t\t127,\n\t\t255,\n\t\t0\n\t],\n\tchocolate: [\n\t\t210,\n\t\t105,\n\t\t30\n\t],\n\tcoral: [\n\t\t255,\n\t\t127,\n\t\t80\n\t],\n\tcornflowerblue: [\n\t\t100,\n\t\t149,\n\t\t237\n\t],\n\tcornsilk: [\n\t\t255,\n\t\t248,\n\t\t220\n\t],\n\tcrimson: [\n\t\t220,\n\t\t20,\n\t\t60\n\t],\n\tcyan: [\n\t\t0,\n\t\t255,\n\t\t255\n\t],\n\tdarkblue: [\n\t\t0,\n\t\t0,\n\t\t139\n\t],\n\tdarkcyan: [\n\t\t0,\n\t\t139,\n\t\t139\n\t],\n\tdarkgoldenrod: [\n\t\t184,\n\t\t134,\n\t\t11\n\t],\n\tdarkgray: [\n\t\t169,\n\t\t169,\n\t\t169\n\t],\n\tdarkgreen: [\n\t\t0,\n\t\t100,\n\t\t0\n\t],\n\tdarkgrey: [\n\t\t169,\n\t\t169,\n\t\t169\n\t],\n\tdarkkhaki: [\n\t\t189,\n\t\t183,\n\t\t107\n\t],\n\tdarkmagenta: [\n\t\t139,\n\t\t0,\n\t\t139\n\t],\n\tdarkolivegreen: [\n\t\t85,\n\t\t107,\n\t\t47\n\t],\n\tdarkorange: [\n\t\t255,\n\t\t140,\n\t\t0\n\t],\n\tdarkorchid: [\n\t\t153,\n\t\t50,\n\t\t204\n\t],\n\tdarkred: [\n\t\t139,\n\t\t0,\n\t\t0\n\t],\n\tdarksalmon: [\n\t\t233,\n\t\t150,\n\t\t122\n\t],\n\tdarkseagreen: [\n\t\t143,\n\t\t188,\n\t\t143\n\t],\n\tdarkslateblue: [\n\t\t72,\n\t\t61,\n\t\t139\n\t],\n\tdarkslategray: [\n\t\t47,\n\t\t79,\n\t\t79\n\t],\n\tdarkslategrey: [\n\t\t47,\n\t\t79,\n\t\t79\n\t],\n\tdarkturquoise: [\n\t\t0,\n\t\t206,\n\t\t209\n\t],\n\tdarkviolet: [\n\t\t148,\n\t\t0,\n\t\t211\n\t],\n\tdeeppink: [\n\t\t255,\n\t\t20,\n\t\t147\n\t],\n\tdeepskyblue: [\n\t\t0,\n\t\t191,\n\t\t255\n\t],\n\tdimgray: [\n\t\t105,\n\t\t105,\n\t\t105\n\t],\n\tdimgrey: [\n\t\t105,\n\t\t105,\n\t\t105\n\t],\n\tdodgerblue: [\n\t\t30,\n\t\t144,\n\t\t255\n\t],\n\tfirebrick: [\n\t\t178,\n\t\t34,\n\t\t34\n\t],\n\tfloralwhite: [\n\t\t255,\n\t\t250,\n\t\t240\n\t],\n\tforestgreen: [\n\t\t34,\n\t\t139,\n\t\t34\n\t],\n\tfuchsia: [\n\t\t255,\n\t\t0,\n\t\t255\n\t],\n\tgainsboro: [\n\t\t220,\n\t\t220,\n\t\t220\n\t],\n\tghostwhite: [\n\t\t248,\n\t\t248,\n\t\t255\n\t],\n\tgold: [\n\t\t255,\n\t\t215,\n\t\t0\n\t],\n\tgoldenrod: [\n\t\t218,\n\t\t165,\n\t\t32\n\t],\n\tgray: [\n\t\t128,\n\t\t128,\n\t\t128\n\t],\n\tgreen: [\n\t\t0,\n\t\t128,\n\t\t0\n\t],\n\tgreenyellow: [\n\t\t173,\n\t\t255,\n\t\t47\n\t],\n\tgrey: [\n\t\t128,\n\t\t128,\n\t\t128\n\t],\n\thoneydew: [\n\t\t240,\n\t\t255,\n\t\t240\n\t],\n\thotpink: [\n\t\t255,\n\t\t105,\n\t\t180\n\t],\n\tindianred: [\n\t\t205,\n\t\t92,\n\t\t92\n\t],\n\tindigo: [\n\t\t75,\n\t\t0,\n\t\t130\n\t],\n\tivory: [\n\t\t255,\n\t\t255,\n\t\t240\n\t],\n\tkhaki: [\n\t\t240,\n\t\t230,\n\t\t140\n\t],\n\tlavender: [\n\t\t230,\n\t\t230,\n\t\t250\n\t],\n\tlavenderblush: [\n\t\t255,\n\t\t240,\n\t\t245\n\t],\n\tlawngreen: [\n\t\t124,\n\t\t252,\n\t\t0\n\t],\n\tlemonchiffon: [\n\t\t255,\n\t\t250,\n\t\t205\n\t],\n\tlightblue: [\n\t\t173,\n\t\t216,\n\t\t230\n\t],\n\tlightcoral: [\n\t\t240,\n\t\t128,\n\t\t128\n\t],\n\tlightcyan: [\n\t\t224,\n\t\t255,\n\t\t255\n\t],\n\tlightgoldenrodyellow: [\n\t\t250,\n\t\t250,\n\t\t210\n\t],\n\tlightgray: [\n\t\t211,\n\t\t211,\n\t\t211\n\t],\n\tlightgreen: [\n\t\t144,\n\t\t238,\n\t\t144\n\t],\n\tlightgrey: [\n\t\t211,\n\t\t211,\n\t\t211\n\t],\n\tlightpink: [\n\t\t255,\n\t\t182,\n\t\t193\n\t],\n\tlightsalmon: [\n\t\t255,\n\t\t160,\n\t\t122\n\t],\n\tlightseagreen: [\n\t\t32,\n\t\t178,\n\t\t170\n\t],\n\tlightskyblue: [\n\t\t135,\n\t\t206,\n\t\t250\n\t],\n\tlightslategray: [\n\t\t119,\n\t\t136,\n\t\t153\n\t],\n\tlightslategrey: [\n\t\t119,\n\t\t136,\n\t\t153\n\t],\n\tlightsteelblue: [\n\t\t176,\n\t\t196,\n\t\t222\n\t],\n\tlightyellow: [\n\t\t255,\n\t\t255,\n\t\t224\n\t],\n\tlime: [\n\t\t0,\n\t\t255,\n\t\t0\n\t],\n\tlimegreen: [\n\t\t50,\n\t\t205,\n\t\t50\n\t],\n\tlinen: [\n\t\t250,\n\t\t240,\n\t\t230\n\t],\n\tmagenta: [\n\t\t255,\n\t\t0,\n\t\t255\n\t],\n\tmaroon: [\n\t\t128,\n\t\t0,\n\t\t0\n\t],\n\tmediumaquamarine: [\n\t\t102,\n\t\t205,\n\t\t170\n\t],\n\tmediumblue: [\n\t\t0,\n\t\t0,\n\t\t205\n\t],\n\tmediumorchid: [\n\t\t186,\n\t\t85,\n\t\t211\n\t],\n\tmediumpurple: [\n\t\t147,\n\t\t112,\n\t\t219\n\t],\n\tmediumseagreen: [\n\t\t60,\n\t\t179,\n\t\t113\n\t],\n\tmediumslateblue: [\n\t\t123,\n\t\t104,\n\t\t238\n\t],\n\tmediumspringgreen: [\n\t\t0,\n\t\t250,\n\t\t154\n\t],\n\tmediumturquoise: [\n\t\t72,\n\t\t209,\n\t\t204\n\t],\n\tmediumvioletred: [\n\t\t199,\n\t\t21,\n\t\t133\n\t],\n\tmidnightblue: [\n\t\t25,\n\t\t25,\n\t\t112\n\t],\n\tmintcream: [\n\t\t245,\n\t\t255,\n\t\t250\n\t],\n\tmistyrose: [\n\t\t255,\n\t\t228,\n\t\t225\n\t],\n\tmoccasin: [\n\t\t255,\n\t\t228,\n\t\t181\n\t],\n\tnavajowhite: [\n\t\t255,\n\t\t222,\n\t\t173\n\t],\n\tnavy: [\n\t\t0,\n\t\t0,\n\t\t128\n\t],\n\toldlace: [\n\t\t253,\n\t\t245,\n\t\t230\n\t],\n\tolive: [\n\t\t128,\n\t\t128,\n\t\t0\n\t],\n\tolivedrab: [\n\t\t107,\n\t\t142,\n\t\t35\n\t],\n\torange: [\n\t\t255,\n\t\t165,\n\t\t0\n\t],\n\torangered: [\n\t\t255,\n\t\t69,\n\t\t0\n\t],\n\torchid: [\n\t\t218,\n\t\t112,\n\t\t214\n\t],\n\tpalegoldenrod: [\n\t\t238,\n\t\t232,\n\t\t170\n\t],\n\tpalegreen: [\n\t\t152,\n\t\t251,\n\t\t152\n\t],\n\tpaleturquoise: [\n\t\t175,\n\t\t238,\n\t\t238\n\t],\n\tpalevioletred: [\n\t\t219,\n\t\t112,\n\t\t147\n\t],\n\tpapayawhip: [\n\t\t255,\n\t\t239,\n\t\t213\n\t],\n\tpeachpuff: [\n\t\t255,\n\t\t218,\n\t\t185\n\t],\n\tperu: [\n\t\t205,\n\t\t133,\n\t\t63\n\t],\n\tpink: [\n\t\t255,\n\t\t192,\n\t\t203\n\t],\n\tplum: [\n\t\t221,\n\t\t160,\n\t\t221\n\t],\n\tpowderblue: [\n\t\t176,\n\t\t224,\n\t\t230\n\t],\n\tpurple: [\n\t\t128,\n\t\t0,\n\t\t128\n\t],\n\trebeccapurple: [\n\t\t102,\n\t\t51,\n\t\t153\n\t],\n\tred: [\n\t\t255,\n\t\t0,\n\t\t0\n\t],\n\trosybrown: [\n\t\t188,\n\t\t143,\n\t\t143\n\t],\n\troyalblue: [\n\t\t65,\n\t\t105,\n\t\t225\n\t],\n\tsaddlebrown: [\n\t\t139,\n\t\t69,\n\t\t19\n\t],\n\tsalmon: [\n\t\t250,\n\t\t128,\n\t\t114\n\t],\n\tsandybrown: [\n\t\t244,\n\t\t164,\n\t\t96\n\t],\n\tseagreen: [\n\t\t46,\n\t\t139,\n\t\t87\n\t],\n\tseashell: [\n\t\t255,\n\t\t245,\n\t\t238\n\t],\n\tsienna: [\n\t\t160,\n\t\t82,\n\t\t45\n\t],\n\tsilver: [\n\t\t192,\n\t\t192,\n\t\t192\n\t],\n\tskyblue: [\n\t\t135,\n\t\t206,\n\t\t235\n\t],\n\tslateblue: [\n\t\t106,\n\t\t90,\n\t\t205\n\t],\n\tslategray: [\n\t\t112,\n\t\t128,\n\t\t144\n\t],\n\tslategrey: [\n\t\t112,\n\t\t128,\n\t\t144\n\t],\n\tsnow: [\n\t\t255,\n\t\t250,\n\t\t250\n\t],\n\tspringgreen: [\n\t\t0,\n\t\t255,\n\t\t127\n\t],\n\tsteelblue: [\n\t\t70,\n\t\t130,\n\t\t180\n\t],\n\ttan: [\n\t\t210,\n\t\t180,\n\t\t140\n\t],\n\tteal: [\n\t\t0,\n\t\t128,\n\t\t128\n\t],\n\tthistle: [\n\t\t216,\n\t\t191,\n\t\t216\n\t],\n\ttomato: [\n\t\t255,\n\t\t99,\n\t\t71\n\t],\n\tturquoise: [\n\t\t64,\n\t\t224,\n\t\t208\n\t],\n\tviolet: [\n\t\t238,\n\t\t130,\n\t\t238\n\t],\n\twheat: [\n\t\t245,\n\t\t222,\n\t\t179\n\t],\n\twhite: [\n\t\t255,\n\t\t255,\n\t\t255\n\t],\n\twhitesmoke: [\n\t\t245,\n\t\t245,\n\t\t245\n\t],\n\tyellow: [\n\t\t255,\n\t\t255,\n\t\t0\n\t],\n\tyellowgreen: [\n\t\t154,\n\t\t205,\n\t\t50\n\t]\n};\nexport { parseCssColor };\n\n//# sourceMappingURL=parse_css_color.mjs.map", "// src/util/interpolate-primitives.ts\nfunction interpolateNumber(from, to, t) {\n\treturn from + t * (to - from);\n}\nfunction interpolateArray(from, to, t) {\n\treturn from.map((d, i) => {\n\t\treturn interpolateNumber(d, to[i], t);\n\t});\n}\nexport { interpolateArray, interpolateNumber };\n\n//# sourceMappingURL=interpolate-primitives.mjs.map", "import { hclToRgb, labToRgb, rgbToHcl, rgbToLab } from \"./color_spaces.mjs\";\nimport { parseCssColor } from \"./parse_css_color.mjs\";\nimport { interpolateArray, interpolateNumber } from \"../../util/interpolate-primitives.mjs\";\n// src/expression/types/color.ts\n/**\n* Checks whether the specified color space is one of the supported interpolation color spaces.\n*\n* @param colorSpace Color space key to verify.\n* @returns `true` if the specified color space is one of the supported\n* interpolation color spaces, `false` otherwise\n*/\nfunction isSupportedInterpolationColorSpace(colorSpace) {\n\treturn colorSpace === \"rgb\" || colorSpace === \"hcl\" || colorSpace === \"lab\";\n}\n/**\n* Color representation used by WebGL.\n* Defined in sRGB color space and pre-blended with alpha.\n* @private\n*/\nvar Color = class Color {\n\t/**\n\t* @param r Red component premultiplied by `alpha` 0..1\n\t* @param g Green component premultiplied by `alpha` 0..1\n\t* @param b Blue component premultiplied by `alpha` 0..1\n\t* @param [alpha=1] Alpha component 0..1\n\t* @param [premultiplied=true] Whether the `r`, `g` and `b` values have already\n\t* been multiplied by alpha. If `true` nothing happens if `false` then they will\n\t* be multiplied automatically.\n\t*/\n\tconstructor(r, g, b, alpha = 1, premultiplied = true) {\n\t\tthis.r = r;\n\t\tthis.g = g;\n\t\tthis.b = b;\n\t\tthis.a = alpha;\n\t\tif (!premultiplied) {\n\t\t\tthis.r *= alpha;\n\t\t\tthis.g *= alpha;\n\t\t\tthis.b *= alpha;\n\t\t\tif (!alpha) this.overwriteGetter(\"rgb\", [\n\t\t\t\tr,\n\t\t\t\tg,\n\t\t\t\tb,\n\t\t\t\talpha\n\t\t\t]);\n\t\t}\n\t}\n\tstatic {\n\t\tthis.black = new Color(0, 0, 0, 1);\n\t}\n\tstatic {\n\t\tthis.white = new Color(1, 1, 1, 1);\n\t}\n\tstatic {\n\t\tthis.transparent = new Color(0, 0, 0, 0);\n\t}\n\tstatic {\n\t\tthis.red = new Color(1, 0, 0, 1);\n\t}\n\t/**\n\t* Parses CSS color strings and converts colors to sRGB color space if needed.\n\t* Officially supported color formats:\n\t* - keyword, e.g. 'aquamarine' or 'steelblue'\n\t* - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9'\n\t* - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)'\n\t* - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)'\n\t*\n\t* @param input CSS color string to parse.\n\t* @returns A `Color` instance, or `undefined` if the input is not a valid color string.\n\t*/\n\tstatic parse(input) {\n\t\tif (input instanceof Color) return input;\n\t\tif (typeof input !== \"string\") return;\n\t\tconst rgba = parseCssColor(input);\n\t\tif (rgba) return new Color(...rgba, false);\n\t}\n\t/**\n\t* Used in color interpolation and by 'to-rgba' expression.\n\t*\n\t* @returns Gien color, with reversed alpha blending, in sRGB color space.\n\t*/\n\tget rgb() {\n\t\tconst { r, g, b, a } = this;\n\t\tconst f = a || Infinity;\n\t\treturn this.overwriteGetter(\"rgb\", [\n\t\t\tr / f,\n\t\t\tg / f,\n\t\t\tb / f,\n\t\t\ta\n\t\t]);\n\t}\n\t/**\n\t* Used in color interpolation.\n\t*\n\t* @returns Gien color, with reversed alpha blending, in HCL color space.\n\t*/\n\tget hcl() {\n\t\treturn this.overwriteGetter(\"hcl\", rgbToHcl(this.rgb));\n\t}\n\t/**\n\t* Used in color interpolation.\n\t*\n\t* @returns Gien color, with reversed alpha blending, in LAB color space.\n\t*/\n\tget lab() {\n\t\treturn this.overwriteGetter(\"lab\", rgbToLab(this.rgb));\n\t}\n\t/**\n\t* Lazy getter pattern. When getter is called for the first time lazy value\n\t* is calculated and then overwrites getter function in given object instance.\n\t*\n\t* @example:\n\t* const redColor = Color.parse('red');\n\t* let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate\n\t* // the value of red in HCL space and invoke this `overwriteGetter` function\n\t* // which in turn will set a field with a key 'hcl' in the `redColor` object.\n\t* // In other words it will override `get hcl()` from its `Color` prototype\n\t* // with its own property: hcl = [calculated red value in hcl].\n\t* let y = redColor.hcl; // next call will no longer invoke getter but simply\n\t* // return the previously calculated value\n\t* x === y; // true - `x` is exactly the same object as `y`\n\t*\n\t* @param getterKey Getter key\n\t* @param lazyValue Lazily calculated value to be memoized by current instance\n\t* @private\n\t*/\n\toverwriteGetter(getterKey, lazyValue) {\n\t\tObject.defineProperty(this, getterKey, { value: lazyValue });\n\t\treturn lazyValue;\n\t}\n\t/**\n\t* Used by 'to-string' expression.\n\t*\n\t* @returns Serialized color in format `rgba(r,g,b,a)`\n\t* where r,g,b are numbers within 0..255 and alpha is number within 1..0\n\t*\n\t* @example\n\t* var purple = new Color.parse('purple');\n\t* purple.toString; // = \"rgba(128,0,128,1)\"\n\t* var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');\n\t* translucentGreen.toString(); // = \"rgba(26,207,26,0.73)\"\n\t*/\n\ttoString() {\n\t\tconst [r, g, b, a] = this.rgb;\n\t\treturn `rgba(${[\n\t\t\tr,\n\t\t\tg,\n\t\t\tb\n\t\t].map((n) => Math.round(n * 255)).join(\",\")},${a})`;\n\t}\n\tstatic interpolate(from, to, t, spaceKey = \"rgb\") {\n\t\tswitch (spaceKey) {\n\t\t\tcase \"rgb\": {\n\t\t\t\tconst [r, g, b, alpha] = interpolateArray(from.rgb, to.rgb, t);\n\t\t\t\treturn new Color(r, g, b, alpha, false);\n\t\t\t}\n\t\t\tcase \"hcl\": {\n\t\t\t\tconst [hue0, chroma0, light0, alphaF] = from.hcl;\n\t\t\t\tconst [hue1, chroma1, light1, alphaT] = to.hcl;\n\t\t\t\tlet hue, chroma;\n\t\t\t\tif (!isNaN(hue0) && !isNaN(hue1)) {\n\t\t\t\t\tlet dh = hue1 - hue0;\n\t\t\t\t\tif (hue1 > hue0 && dh > 180) dh -= 360;\n\t\t\t\t\telse if (hue1 < hue0 && hue0 - hue1 > 180) dh += 360;\n\t\t\t\t\thue = hue0 + t * dh;\n\t\t\t\t} else if (!isNaN(hue0)) {\n\t\t\t\t\thue = hue0;\n\t\t\t\t\tif (light1 === 1 || light1 === 0) chroma = chroma0;\n\t\t\t\t} else if (!isNaN(hue1)) {\n\t\t\t\t\thue = hue1;\n\t\t\t\t\tif (light0 === 1 || light0 === 0) chroma = chroma1;\n\t\t\t\t} else hue = NaN;\n\t\t\t\tconst [r, g, b, alpha] = hclToRgb([\n\t\t\t\t\thue,\n\t\t\t\t\tchroma ?? interpolateNumber(chroma0, chroma1, t),\n\t\t\t\t\tinterpolateNumber(light0, light1, t),\n\t\t\t\t\tinterpolateNumber(alphaF, alphaT, t)\n\t\t\t\t]);\n\t\t\t\treturn new Color(r, g, b, alpha, false);\n\t\t\t}\n\t\t\tcase \"lab\": {\n\t\t\t\tconst [r, g, b, alpha] = labToRgb(interpolateArray(from.lab, to.lab, t));\n\t\t\t\treturn new Color(r, g, b, alpha, false);\n\t\t\t}\n\t\t}\n\t}\n};\nexport { Color, isSupportedInterpolationColorSpace };\n\n//# sourceMappingURL=color.mjs.map", "// src/expression/types/formatted.ts\nconst VERTICAL_ALIGN_OPTIONS = [\n\t\"bottom\",\n\t\"center\",\n\t\"top\"\n];\nvar FormattedSection = class {\n\tconstructor(text, image, scale, fontStack, textColor, verticalAlign) {\n\t\tthis.text = text;\n\t\tthis.image = image;\n\t\tthis.scale = scale;\n\t\tthis.fontStack = fontStack;\n\t\tthis.textColor = textColor;\n\t\tthis.verticalAlign = verticalAlign;\n\t}\n};\nvar Formatted = class Formatted {\n\tconstructor(sections) {\n\t\tthis.sections = sections;\n\t}\n\tstatic fromString(unformatted) {\n\t\treturn new Formatted([new FormattedSection(unformatted, null, null, null, null, null)]);\n\t}\n\tisEmpty() {\n\t\tif (this.sections.length === 0) return true;\n\t\treturn !this.sections.some((section) => section.text.length !== 0 || section.image && section.image.name.length !== 0);\n\t}\n\tstatic factory(text) {\n\t\tif (text instanceof Formatted) return text;\n\t\telse return Formatted.fromString(text);\n\t}\n\ttoString() {\n\t\tif (this.sections.length === 0) return \"\";\n\t\treturn this.sections.map((section) => section.text).join(\"\");\n\t}\n};\nexport { Formatted, FormattedSection, VERTICAL_ALIGN_OPTIONS };\n\n//# sourceMappingURL=formatted.mjs.map", "import { interpolateArray } from \"../../util/interpolate-primitives.mjs\";\n// src/expression/types/padding.ts\n/**\n* A set of four numbers representing padding around a box. Create instances from\n* bare arrays or numeric values using the static method `Padding.parse`.\n* @private\n*/\nvar Padding = class Padding {\n\tconstructor(values) {\n\t\tthis.values = values.slice();\n\t}\n\t/**\n\t* Numeric padding values\n\t* @param input A padding value\n\t* @returns A `Padding` instance, or `undefined` if the input is not a valid padding value.\n\t*/\n\tstatic parse(input) {\n\t\tif (input instanceof Padding) return input;\n\t\tif (typeof input === \"number\") return new Padding([\n\t\t\tinput,\n\t\t\tinput,\n\t\t\tinput,\n\t\t\tinput\n\t\t]);\n\t\tif (!Array.isArray(input)) return;\n\t\tif (input.length < 1 || input.length > 4) return;\n\t\tfor (const val of input) if (typeof val !== \"number\") return;\n\t\tswitch (input.length) {\n\t\t\tcase 1:\n\t\t\t\tinput = [\n\t\t\t\t\tinput[0],\n\t\t\t\t\tinput[0],\n\t\t\t\t\tinput[0],\n\t\t\t\t\tinput[0]\n\t\t\t\t];\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tinput = [\n\t\t\t\t\tinput[0],\n\t\t\t\t\tinput[1],\n\t\t\t\t\tinput[0],\n\t\t\t\t\tinput[1]\n\t\t\t\t];\n\t\t\t\tbreak;\n\t\t\tcase 3: input = [\n\t\t\t\tinput[0],\n\t\t\t\tinput[1],\n\t\t\t\tinput[2],\n\t\t\t\tinput[1]\n\t\t\t];\n\t\t}\n\t\treturn new Padding(input);\n\t}\n\ttoString() {\n\t\treturn JSON.stringify(this.values);\n\t}\n\tstatic interpolate(from, to, t) {\n\t\treturn new Padding(interpolateArray(from.values, to.values, t));\n\t}\n};\nexport { Padding };\n\n//# sourceMappingURL=padding.mjs.map", "import { interpolateArray } from \"../../util/interpolate-primitives.mjs\";\n// src/expression/types/number_array.ts\n/**\n* An array of numbers. Create instances from\n* bare arrays or numeric values using the static method `NumberArray.parse`.\n* @private\n*/\nvar NumberArray = class NumberArray {\n\tconstructor(values) {\n\t\tthis.values = values.slice();\n\t}\n\t/**\n\t* Numeric NumberArray values\n\t* @param input A NumberArray value\n\t* @returns A `NumberArray` instance, or `undefined` if the input is not a valid NumberArray value.\n\t*/\n\tstatic parse(input) {\n\t\tif (input instanceof NumberArray) return input;\n\t\tif (typeof input === \"number\") return new NumberArray([input]);\n\t\tif (!Array.isArray(input)) return;\n\t\tfor (const val of input) if (typeof val !== \"number\") return;\n\t\treturn new NumberArray(input);\n\t}\n\ttoString() {\n\t\treturn JSON.stringify(this.values);\n\t}\n\tstatic interpolate(from, to, t) {\n\t\treturn new NumberArray(interpolateArray(from.values, to.values, t));\n\t}\n};\nexport { NumberArray };\n\n//# sourceMappingURL=number_array.mjs.map", "import { Color } from \"./color.mjs\";\n// src/expression/types/color_array.ts\n/**\n* An array of colors. Create instances from\n* bare arrays or strings using the static method `ColorArray.parse`.\n* @private\n*/\nvar ColorArray = class ColorArray {\n\tconstructor(values) {\n\t\tthis.values = values.slice();\n\t}\n\t/**\n\t* ColorArray values\n\t* @param input A ColorArray value\n\t* @returns A `ColorArray` instance, or `undefined` if the input is not a valid ColorArray value.\n\t*/\n\tstatic parse(input) {\n\t\tif (input instanceof ColorArray) return input;\n\t\tif (typeof input === \"string\") {\n\t\t\tconst parsed_val = Color.parse(input);\n\t\t\tif (!parsed_val) return;\n\t\t\treturn new ColorArray([parsed_val]);\n\t\t}\n\t\tif (!Array.isArray(input)) return;\n\t\tconst colors = [];\n\t\tfor (const val of input) {\n\t\t\tif (typeof val !== \"string\") return;\n\t\t\tconst parsed_val = Color.parse(val);\n\t\t\tif (!parsed_val) return;\n\t\t\tcolors.push(parsed_val);\n\t\t}\n\t\treturn new ColorArray(colors);\n\t}\n\ttoString() {\n\t\treturn JSON.stringify(this.values);\n\t}\n\tstatic interpolate(from, to, t, spaceKey = \"rgb\") {\n\t\tconst colors = [];\n\t\tif (from.values.length != to.values.length) throw new Error(`colorArray: Arrays have mismatched length (${from.values.length} vs. ${to.values.length}), cannot interpolate.`);\n\t\tfor (let i = 0; i < from.values.length; i++) colors.push(Color.interpolate(from.values[i], to.values[i], t, spaceKey));\n\t\treturn new ColorArray(colors);\n\t}\n};\nexport { ColorArray };\n\n//# sourceMappingURL=color_array.mjs.map", "// src/expression/runtime_error.ts\nvar RuntimeError = class extends Error {\n\tconstructor(message, path) {\n\t\tsuper(message);\n\t\tthis.name = \"RuntimeError\";\n\t\tthis.path = path;\n\t}\n\ttoJSON() {\n\t\treturn this.message;\n\t}\n};\nexport { RuntimeError };\n\n//# sourceMappingURL=runtime_error.mjs.map", "import { interpolateNumber } from \"../../util/interpolate-primitives.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\n// src/expression/types/variable_anchor_offset_collection.ts\n/** Set of valid anchor positions, as a set for validation */\nconst anchors = /* @__PURE__ */ new Set([\n\t\"center\",\n\t\"left\",\n\t\"right\",\n\t\"top\",\n\t\"bottom\",\n\t\"top-left\",\n\t\"top-right\",\n\t\"bottom-left\",\n\t\"bottom-right\"\n]);\n/**\n* Utility class to assist managing values for text-variable-anchor-offset property. Create instances from\n* bare arrays using the static method `VariableAnchorOffsetCollection.parse`.\n* @private\n*/\nvar VariableAnchorOffsetCollection = class VariableAnchorOffsetCollection {\n\tconstructor(values) {\n\t\tthis.values = values.slice();\n\t}\n\tstatic parse(input) {\n\t\tif (input instanceof VariableAnchorOffsetCollection) return input;\n\t\tif (!Array.isArray(input) || input.length < 1 || input.length % 2 !== 0) return;\n\t\tfor (let i = 0; i < input.length; i += 2) {\n\t\t\tconst anchorValue = input[i];\n\t\t\tconst offsetValue = input[i + 1];\n\t\t\tif (typeof anchorValue !== \"string\" || !anchors.has(anchorValue)) return;\n\t\t\tif (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== \"number\" || typeof offsetValue[1] !== \"number\") return;\n\t\t}\n\t\treturn new VariableAnchorOffsetCollection(input);\n\t}\n\ttoString() {\n\t\treturn JSON.stringify(this.values);\n\t}\n\tstatic interpolate(from, to, t, key) {\n\t\tconst fromValues = from.values;\n\t\tconst toValues = to.values;\n\t\tif (fromValues.length !== toValues.length) throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`, key);\n\t\tconst output = [];\n\t\tfor (let i = 0; i < fromValues.length; i += 2) {\n\t\t\tif (fromValues[i] !== toValues[i]) throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`, key);\n\t\t\toutput.push(fromValues[i]);\n\t\t\tconst [fx, fy] = fromValues[i + 1];\n\t\t\tconst [tx, ty] = toValues[i + 1];\n\t\t\toutput.push([interpolateNumber(fx, tx, t), interpolateNumber(fy, ty, t)]);\n\t\t}\n\t\treturn new VariableAnchorOffsetCollection(output);\n\t}\n};\nexport { VariableAnchorOffsetCollection };\n\n//# sourceMappingURL=variable_anchor_offset_collection.mjs.map", "// src/expression/types/resolved_image.ts\nvar ResolvedImage = class ResolvedImage {\n\tconstructor(options) {\n\t\tthis.name = options.name;\n\t\tthis.available = options.available;\n\t}\n\ttoString() {\n\t\treturn this.name;\n\t}\n\tstatic fromString(name) {\n\t\tif (!name) return null;\n\t\treturn new ResolvedImage({\n\t\t\tname,\n\t\t\tavailable: false\n\t\t});\n\t}\n};\nexport { ResolvedImage };\n\n//# sourceMappingURL=resolved_image.mjs.map", "// src/expression/types/projection_definition.ts\nvar ProjectionDefinition = class ProjectionDefinition {\n\tconstructor(from, to, transition) {\n\t\tthis.from = from;\n\t\tthis.to = to;\n\t\tthis.transition = transition;\n\t}\n\ttoString() {\n\t\tif (this.from === this.to && this.transition === 1) return this.from;\n\t\treturn JSON.stringify([\n\t\t\tthis.from,\n\t\t\tthis.to,\n\t\t\tthis.transition\n\t\t]);\n\t}\n\tstatic interpolate(from, to, t) {\n\t\treturn new ProjectionDefinition(from, to, t);\n\t}\n\tstatic parse(input) {\n\t\tif (input instanceof ProjectionDefinition) return input;\n\t\tif (Array.isArray(input) && input.length === 3 && typeof input[0] === \"string\" && typeof input[1] === \"string\" && typeof input[2] === \"number\") return new ProjectionDefinition(input[0], input[1], input[2]);\n\t\tif (typeof input === \"object\" && typeof input.from === \"string\" && typeof input.to === \"string\" && typeof input.transition === \"number\") return new ProjectionDefinition(input.from, input.to, input.transition);\n\t\tif (typeof input === \"string\") return new ProjectionDefinition(input, input, 1);\n\t}\n};\nexport { ProjectionDefinition };\n\n//# sourceMappingURL=projection_definition.mjs.map", "// src/expression/types/collator.ts\nvar Collator = class {\n\tconstructor(caseSensitive, diacriticSensitive, locale) {\n\t\tif (caseSensitive) this.sensitivity = diacriticSensitive ? \"variant\" : \"case\";\n\t\telse this.sensitivity = diacriticSensitive ? \"accent\" : \"base\";\n\t\tthis.locale = locale;\n\t\tthis.collator = new Intl.Collator(this.locale ? this.locale : [], {\n\t\t\tsensitivity: this.sensitivity,\n\t\t\tusage: \"search\"\n\t\t});\n\t}\n\tcompare(lhs, rhs) {\n\t\treturn this.collator.compare(lhs, rhs);\n\t}\n\tresolvedLocale() {\n\t\treturn new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale;\n\t}\n};\nexport { Collator };\n\n//# sourceMappingURL=collator.mjs.map", "import { BooleanType, CollatorType, ColorArrayType, ColorType, FormattedType, NullType, NumberArrayType, NumberType, ObjectType, PaddingType, ProjectionDefinitionType, ResolvedImageType, StringType, ValueType, VariableAnchorOffsetCollectionType, array } from \"./types.mjs\";\nimport { Color } from \"./types/color.mjs\";\nimport { Collator } from \"./types/collator.mjs\";\nimport { Formatted } from \"./types/formatted.mjs\";\nimport { Padding } from \"./types/padding.mjs\";\nimport { NumberArray } from \"./types/number_array.mjs\";\nimport { ColorArray } from \"./types/color_array.mjs\";\nimport { VariableAnchorOffsetCollection } from \"./types/variable_anchor_offset_collection.mjs\";\nimport { ResolvedImage } from \"./types/resolved_image.mjs\";\nimport { ProjectionDefinition } from \"./types/projection_definition.mjs\";\n// src/expression/values.ts\nfunction validateRGBA(r, g, b, a) {\n\tif (!(typeof r === \"number\" && r >= 0 && r <= 255 && typeof g === \"number\" && g >= 0 && g <= 255 && typeof b === \"number\" && b >= 0 && b <= 255)) return `Invalid rgba value [${(typeof a === \"number\" ? [\n\t\tr,\n\t\tg,\n\t\tb,\n\t\ta\n\t] : [\n\t\tr,\n\t\tg,\n\t\tb\n\t]).join(\", \")}]: 'r', 'g', and 'b' must be between 0 and 255.`;\n\tif (!(typeof a === \"undefined\" || typeof a === \"number\" && a >= 0 && a <= 1)) return `Invalid rgba value [${[\n\t\tr,\n\t\tg,\n\t\tb,\n\t\ta\n\t].join(\", \")}]: 'a' must be between 0 and 1.`;\n\treturn null;\n}\nfunction isValue(mixed) {\n\tif (mixed === null || typeof mixed === \"string\" || typeof mixed === \"boolean\" || typeof mixed === \"number\" || mixed instanceof ProjectionDefinition || mixed instanceof Color || mixed instanceof Collator || mixed instanceof Formatted || mixed instanceof Padding || mixed instanceof NumberArray || mixed instanceof ColorArray || mixed instanceof VariableAnchorOffsetCollection || mixed instanceof ResolvedImage) return true;\n\telse if (Array.isArray(mixed)) {\n\t\tfor (const item of mixed) if (!isValue(item)) return false;\n\t\treturn true;\n\t} else if (typeof mixed === \"object\") {\n\t\tfor (const key in mixed) if (!isValue(mixed[key])) return false;\n\t\treturn true;\n\t} else return false;\n}\nfunction typeOf(value) {\n\tif (value === null) return NullType;\n\telse if (typeof value === \"string\") return StringType;\n\telse if (typeof value === \"boolean\") return BooleanType;\n\telse if (typeof value === \"number\") return NumberType;\n\telse if (value instanceof Color) return ColorType;\n\telse if (value instanceof ProjectionDefinition) return ProjectionDefinitionType;\n\telse if (value instanceof Collator) return CollatorType;\n\telse if (value instanceof Formatted) return FormattedType;\n\telse if (value instanceof Padding) return PaddingType;\n\telse if (value instanceof NumberArray) return NumberArrayType;\n\telse if (value instanceof ColorArray) return ColorArrayType;\n\telse if (value instanceof VariableAnchorOffsetCollection) return VariableAnchorOffsetCollectionType;\n\telse if (value instanceof ResolvedImage) return ResolvedImageType;\n\telse if (Array.isArray(value)) {\n\t\tconst length = value.length;\n\t\tlet itemType;\n\t\tfor (const item of value) {\n\t\t\tconst t = typeOf(item);\n\t\t\tif (!itemType) itemType = t;\n\t\t\telse if (itemType === t) continue;\n\t\t\telse {\n\t\t\t\titemType = ValueType;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn array(itemType || ValueType, length);\n\t} else return ObjectType;\n}\nfunction valueToString(value) {\n\tconst type = typeof value;\n\tif (value === null) return \"\";\n\telse if (type === \"string\" || type === \"number\" || type === \"boolean\") return String(value);\n\telse if (value instanceof Color || value instanceof ProjectionDefinition || value instanceof Formatted || value instanceof Padding || value instanceof NumberArray || value instanceof ColorArray || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) return value.toString();\n\telse return JSON.stringify(value);\n}\nexport { isValue, typeOf, validateRGBA, valueToString };\n\n//# sourceMappingURL=values.mjs.map", "import { isValue, typeOf } from \"../values.mjs\";\n// src/expression/definitions/literal.ts\nvar Literal = class Literal {\n\tconstructor(type, value) {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\t\tif (!isValue(args[1])) return context.error(`invalid value of type \"${typeof args[1]}\"`);\n\t\tconst value = args[1];\n\t\tlet type = typeOf(value);\n\t\tconst expected = context.expectedType;\n\t\tif (type.kind === \"array\" && type.N === 0 && expected && expected.kind === \"array\" && (typeof expected.N !== \"number\" || expected.N === 0)) type = expected;\n\t\treturn new Literal(type, value);\n\t}\n\tevaluate() {\n\t\treturn this.value;\n\t}\n\teachChild() {}\n\toutputDefined() {\n\t\treturn true;\n\t}\n};\nexport { Literal };\n\n//# sourceMappingURL=literal.mjs.map", "import { Color } from \"./types/color.mjs\";\n// src/expression/evaluation_context.ts\nconst geometryTypes = [\n\t\"Unknown\",\n\t\"Point\",\n\t\"LineString\",\n\t\"Polygon\"\n];\nvar EvaluationContext = class {\n\tconstructor() {\n\t\tthis.globals = null;\n\t\tthis.feature = null;\n\t\tthis.featureState = null;\n\t\tthis.formattedSection = null;\n\t\tthis._parseColorCache = /* @__PURE__ */ new Map();\n\t\tthis.availableImages = null;\n\t\tthis.canonical = null;\n\t}\n\tid() {\n\t\treturn this.feature && \"id\" in this.feature ? this.feature.id : null;\n\t}\n\tgeometryType() {\n\t\treturn this.feature ? typeof this.feature.type === \"number\" ? geometryTypes[this.feature.type] : this.feature.type : null;\n\t}\n\tgeometry() {\n\t\treturn this.feature && \"geometry\" in this.feature ? this.feature.geometry : null;\n\t}\n\tcanonicalID() {\n\t\treturn this.canonical;\n\t}\n\tproperties() {\n\t\treturn this.feature && this.feature.properties || {};\n\t}\n\tparseColor(input) {\n\t\tlet cached = this._parseColorCache.get(input);\n\t\tif (!cached) {\n\t\t\tcached = Color.parse(input);\n\t\t\tthis._parseColorCache.set(input, cached);\n\t\t}\n\t\treturn cached;\n\t}\n};\nexport { EvaluationContext };\n\n//# sourceMappingURL=evaluation_context.mjs.map", "import { RuntimeError } from \"./runtime_error.mjs\";\n// src/expression/stops.ts\n/**\n* Returns the index of the last stop <= input, or 0 if it doesn't exist.\n* @private\n*/\nfunction findStopLessThanOrEqualTo(stops, input, key) {\n\tconst lastIndex = stops.length - 1;\n\tlet lowerIndex = 0;\n\tlet upperIndex = lastIndex;\n\tlet currentIndex = 0;\n\tlet currentValue, nextValue;\n\twhile (lowerIndex <= upperIndex) {\n\t\tcurrentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n\t\tcurrentValue = stops[currentIndex];\n\t\tnextValue = stops[currentIndex + 1];\n\t\tif (currentValue <= input) {\n\t\t\tif (currentIndex === lastIndex || input < nextValue) return currentIndex;\n\t\t\tlowerIndex = currentIndex + 1;\n\t\t} else if (currentValue > input) upperIndex = currentIndex - 1;\n\t\telse throw new RuntimeError(\"Input is not a number.\", key);\n\t}\n\treturn 0;\n}\nexport { findStopLessThanOrEqualTo };\n\n//# sourceMappingURL=stops.mjs.map", "import { NumberType } from \"../types.mjs\";\nimport { findStopLessThanOrEqualTo } from \"../stops.mjs\";\n// src/expression/definitions/step.ts\nvar Step = class Step {\n\tconstructor(type, input, stops, key) {\n\t\tthis.type = type;\n\t\tthis.input = input;\n\t\tthis.key = key;\n\t\tthis.labels = [];\n\t\tthis.outputs = [];\n\t\tfor (const [label, expression] of stops) {\n\t\t\tthis.labels.push(label);\n\t\t\tthis.outputs.push(expression);\n\t\t}\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length - 1 < 4) return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n\t\tif ((args.length - 1) % 2 !== 0) return context.error(\"Expected an even number of arguments.\");\n\t\tconst input = context.parse(args[1], 1, NumberType);\n\t\tif (!input) return null;\n\t\tconst stops = [];\n\t\tlet outputType = null;\n\t\tif (context.expectedType && context.expectedType.kind !== \"value\") outputType = context.expectedType;\n\t\tfor (let i = 1; i < args.length; i += 2) {\n\t\t\tconst label = i === 1 ? -Infinity : args[i];\n\t\t\tconst value = args[i + 1];\n\t\t\tconst labelKey = i;\n\t\t\tconst valueKey = i + 1;\n\t\t\tif (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);\n\t\t\tif (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);\n\t\t\tconst parsed = context.parse(value, valueKey, outputType);\n\t\t\tif (!parsed) return null;\n\t\t\toutputType = outputType || parsed.type;\n\t\t\tstops.push([label, parsed]);\n\t\t}\n\t\treturn new Step(outputType, input, stops, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tconst labels = this.labels;\n\t\tconst outputs = this.outputs;\n\t\tif (labels.length === 1) return outputs[0].evaluate(ctx);\n\t\tconst value = this.input.evaluate(ctx);\n\t\tif (value <= labels[0]) return outputs[0].evaluate(ctx);\n\t\tconst stopCount = labels.length;\n\t\tif (value >= labels[stopCount - 1]) return outputs[stopCount - 1].evaluate(ctx);\n\t\treturn outputs[findStopLessThanOrEqualTo(labels, value, this.key)].evaluate(ctx);\n\t}\n\teachChild(fn) {\n\t\tfn(this.input);\n\t\tfor (const expression of this.outputs) fn(expression);\n\t}\n\toutputDefined() {\n\t\treturn this.outputs.every((out) => out.outputDefined());\n\t}\n};\nexport { Step };\n\n//# sourceMappingURL=step.mjs.map", "// node_modules/@mapbox/unitbezier/index.js\nfunction unitBezier(p1x, p1y, p2x, p2y) {\n\tconst cx = 3 * p1x;\n\tconst bx = 3 * (p2x - p1x) - cx;\n\tconst ax = 1 - cx - bx;\n\tconst cy = 3 * p1y;\n\tconst by = 3 * (p2y - p1y) - cy;\n\tconst ay = 1 - cy - by;\n\treturn function solve(x, epsilon = 1e-6) {\n\t\tif (x <= 0) return 0;\n\t\tif (x >= 1) return 1;\n\t\tlet t = x;\n\t\tfor (let i = 0; i < 8; i++) {\n\t\t\tconst x2 = ((ax * t + bx) * t + cx) * t - x;\n\t\t\tif (Math.abs(x2) < epsilon) return ((ay * t + by) * t + cy) * t;\n\t\t\tconst d2 = (3 * ax * t + 2 * bx) * t + cx;\n\t\t\tif (Math.abs(d2) < 1e-6) break;\n\t\t\tt -= x2 / d2;\n\t\t}\n\t\tlet t0 = 0;\n\t\tlet t1 = 1;\n\t\tt = x;\n\t\tfor (let i = 0; i < 20; i++) {\n\t\t\tconst x2 = ((ax * t + bx) * t + cx) * t;\n\t\t\tif (Math.abs(x2 - x) < epsilon) break;\n\t\t\tif (x > x2) t0 = t;\n\t\t\telse t1 = t;\n\t\t\tt = (t0 + t1) * .5;\n\t\t}\n\t\treturn ((ay * t + by) * t + cy) * t;\n\t};\n}\nexport { unitBezier as default };\n\n//# sourceMappingURL=index.mjs.map", "import { ColorArrayType, ColorType, NumberArrayType, NumberType, PaddingType, ProjectionDefinitionType, VariableAnchorOffsetCollectionType, array, typeToString, verifyType } from \"../types.mjs\";\nimport { interpolateArray, interpolateNumber } from \"../../util/interpolate-primitives.mjs\";\nimport { Color } from \"../types/color.mjs\";\nimport { Padding } from \"../types/padding.mjs\";\nimport { NumberArray } from \"../types/number_array.mjs\";\nimport { ColorArray } from \"../types/color_array.mjs\";\nimport { VariableAnchorOffsetCollection } from \"../types/variable_anchor_offset_collection.mjs\";\nimport { ProjectionDefinition } from \"../types/projection_definition.mjs\";\nimport { findStopLessThanOrEqualTo } from \"../stops.mjs\";\nimport unitBezier from \"../../node_modules/@mapbox/unitbezier/index.mjs\";\n// src/expression/definitions/interpolate.ts\nvar Interpolate = class Interpolate {\n\tconstructor(type, operator, interpolation, input, stops, key) {\n\t\tthis.type = type;\n\t\tthis.operator = operator;\n\t\tthis.interpolation = interpolation;\n\t\tthis.input = input;\n\t\tthis.key = key;\n\t\tthis.labels = [];\n\t\tthis.outputs = [];\n\t\tfor (const [label, expression] of stops) {\n\t\t\tthis.labels.push(label);\n\t\t\tthis.outputs.push(expression);\n\t\t}\n\t}\n\tstatic interpolationFactor(interpolation, input, lower, upper) {\n\t\tlet t = 0;\n\t\tif (interpolation.name === \"exponential\") t = exponentialInterpolation(input, interpolation.base, lower, upper);\n\t\telse if (interpolation.name === \"linear\") t = exponentialInterpolation(input, 1, lower, upper);\n\t\telse if (interpolation.name === \"cubic-bezier\") {\n\t\t\tconst c = interpolation.controlPoints;\n\t\t\tt = unitBezier(c[0], c[1], c[2], c[3])(exponentialInterpolation(input, 1, lower, upper));\n\t\t}\n\t\treturn t;\n\t}\n\tstatic parse(args, context) {\n\t\tlet [operator, interpolation, input, ...rest] = args;\n\t\tif (!Array.isArray(interpolation) || interpolation.length === 0) return context.error(\"Expected an interpolation type expression.\", 1);\n\t\tif (interpolation[0] === \"linear\") interpolation = { name: \"linear\" };\n\t\telse if (interpolation[0] === \"exponential\") {\n\t\t\tconst base = interpolation[1];\n\t\t\tif (typeof base !== \"number\") return context.error(\"Exponential interpolation requires a numeric base.\", 1, 1);\n\t\t\tinterpolation = {\n\t\t\t\tname: \"exponential\",\n\t\t\t\tbase\n\t\t\t};\n\t\t} else if (interpolation[0] === \"cubic-bezier\") {\n\t\t\tconst controlPoints = interpolation.slice(1);\n\t\t\tif (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);\n\t\t\tinterpolation = {\n\t\t\t\tname: \"cubic-bezier\",\n\t\t\t\tcontrolPoints\n\t\t\t};\n\t\t} else return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0);\n\t\tif (args.length - 1 < 4) return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n\t\tif ((args.length - 1) % 2 !== 0) return context.error(\"Expected an even number of arguments.\");\n\t\tinput = context.parse(input, 2, NumberType);\n\t\tif (!input) return null;\n\t\tconst stops = [];\n\t\tlet outputType = null;\n\t\tif ((operator === \"interpolate-hcl\" || operator === \"interpolate-lab\") && context.expectedType != ColorArrayType) outputType = ColorType;\n\t\telse if (context.expectedType && context.expectedType.kind !== \"value\") outputType = context.expectedType;\n\t\tfor (let i = 0; i < rest.length; i += 2) {\n\t\t\tconst label = rest[i];\n\t\t\tconst value = rest[i + 1];\n\t\t\tconst labelKey = i + 3;\n\t\t\tconst valueKey = i + 4;\n\t\t\tif (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);\n\t\t\tif (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);\n\t\t\tconst parsed = context.parse(value, valueKey, outputType);\n\t\t\tif (!parsed) return null;\n\t\t\toutputType = outputType || parsed.type;\n\t\t\tstops.push([label, parsed]);\n\t\t}\n\t\tif (!verifyType(outputType, NumberType) && !verifyType(outputType, ProjectionDefinitionType) && !verifyType(outputType, ColorType) && !verifyType(outputType, PaddingType) && !verifyType(outputType, NumberArrayType) && !verifyType(outputType, ColorArrayType) && !verifyType(outputType, VariableAnchorOffsetCollectionType) && !verifyType(outputType, array(NumberType))) return context.error(`Type ${typeToString(outputType)} is not interpolatable.`);\n\t\treturn new Interpolate(outputType, operator, interpolation, input, stops, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tconst labels = this.labels;\n\t\tconst outputs = this.outputs;\n\t\tif (labels.length === 1) return outputs[0].evaluate(ctx);\n\t\tconst value = this.input.evaluate(ctx);\n\t\tif (value <= labels[0]) return outputs[0].evaluate(ctx);\n\t\tconst stopCount = labels.length;\n\t\tif (value >= labels[stopCount - 1]) return outputs[stopCount - 1].evaluate(ctx);\n\t\tconst index = findStopLessThanOrEqualTo(labels, value, this.key);\n\t\tconst lower = labels[index];\n\t\tconst upper = labels[index + 1];\n\t\tconst t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);\n\t\tconst outputLower = outputs[index].evaluate(ctx);\n\t\tconst outputUpper = outputs[index + 1].evaluate(ctx);\n\t\tswitch (this.operator) {\n\t\t\tcase \"interpolate\": switch (this.type.kind) {\n\t\t\t\tcase \"number\": return interpolateNumber(outputLower, outputUpper, t);\n\t\t\t\tcase \"color\": return Color.interpolate(outputLower, outputUpper, t);\n\t\t\t\tcase \"padding\": return Padding.interpolate(outputLower, outputUpper, t);\n\t\t\t\tcase \"colorArray\": return ColorArray.interpolate(outputLower, outputUpper, t);\n\t\t\t\tcase \"numberArray\": return NumberArray.interpolate(outputLower, outputUpper, t);\n\t\t\t\tcase \"variableAnchorOffsetCollection\": return VariableAnchorOffsetCollection.interpolate(outputLower, outputUpper, t, this.key);\n\t\t\t\tcase \"array\": return interpolateArray(outputLower, outputUpper, t);\n\t\t\t\tcase \"projectionDefinition\": return ProjectionDefinition.interpolate(outputLower, outputUpper, t);\n\t\t\t}\n\t\t\tcase \"interpolate-hcl\": switch (this.type.kind) {\n\t\t\t\tcase \"color\": return Color.interpolate(outputLower, outputUpper, t, \"hcl\");\n\t\t\t\tcase \"colorArray\": return ColorArray.interpolate(outputLower, outputUpper, t, \"hcl\");\n\t\t\t}\n\t\t\tcase \"interpolate-lab\": switch (this.type.kind) {\n\t\t\t\tcase \"color\": return Color.interpolate(outputLower, outputUpper, t, \"lab\");\n\t\t\t\tcase \"colorArray\": return ColorArray.interpolate(outputLower, outputUpper, t, \"lab\");\n\t\t\t}\n\t\t}\n\t}\n\teachChild(fn) {\n\t\tfn(this.input);\n\t\tfor (const expression of this.outputs) fn(expression);\n\t}\n\toutputDefined() {\n\t\treturn this.outputs.every((out) => out.outputDefined());\n\t}\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\tconst difference = upperValue - lowerValue;\n\tconst progress = input - lowerValue;\n\tif (difference === 0) return 0;\n\telse if (base === 1) return progress / difference;\n\telse return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n}\nconst interpolateFactory = {\n\tcolor: Color.interpolate,\n\tnumber: interpolateNumber,\n\tpadding: Padding.interpolate,\n\tnumberArray: NumberArray.interpolate,\n\tcolorArray: ColorArray.interpolate,\n\tvariableAnchorOffsetCollection: VariableAnchorOffsetCollection.interpolate,\n\tarray: interpolateArray\n};\nexport { Interpolate, interpolateFactory };\n\n//# sourceMappingURL=interpolate.mjs.map", "import { ColorType, FormattedType, NumberType, ResolvedImageType, StringType, ValueType, array } from \"../types.mjs\";\nimport { Formatted, FormattedSection, VERTICAL_ALIGN_OPTIONS } from \"../types/formatted.mjs\";\nimport { typeOf, valueToString } from \"../values.mjs\";\n// src/expression/definitions/format.ts\nvar FormatExpression = class FormatExpression {\n\tconstructor(sections) {\n\t\tthis.type = FormattedType;\n\t\tthis.sections = sections;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length < 2) return context.error(\"Expected at least one argument.\");\n\t\tconst firstArg = args[1];\n\t\tif (!Array.isArray(firstArg) && typeof firstArg === \"object\") return context.error(\"First argument must be an image or text section.\");\n\t\tconst sections = [];\n\t\tlet nextTokenMayBeObject = false;\n\t\tfor (let i = 1; i <= args.length - 1; ++i) {\n\t\t\tconst arg = args[i];\n\t\t\tif (nextTokenMayBeObject && typeof arg === \"object\" && !Array.isArray(arg)) {\n\t\t\t\tnextTokenMayBeObject = false;\n\t\t\t\tlet scale = null;\n\t\t\t\tif (arg[\"font-scale\"]) {\n\t\t\t\t\tscale = context.parse(arg[\"font-scale\"], 1, NumberType);\n\t\t\t\t\tif (!scale) return null;\n\t\t\t\t}\n\t\t\t\tlet font = null;\n\t\t\t\tif (arg[\"text-font\"]) {\n\t\t\t\t\tfont = context.parse(arg[\"text-font\"], 1, array(StringType));\n\t\t\t\t\tif (!font) return null;\n\t\t\t\t}\n\t\t\t\tlet textColor = null;\n\t\t\t\tif (arg[\"text-color\"]) {\n\t\t\t\t\ttextColor = context.parse(arg[\"text-color\"], 1, ColorType);\n\t\t\t\t\tif (!textColor) return null;\n\t\t\t\t}\n\t\t\t\tlet verticalAlign = null;\n\t\t\t\tif (arg[\"vertical-align\"]) {\n\t\t\t\t\tif (typeof arg[\"vertical-align\"] === \"string\" && !VERTICAL_ALIGN_OPTIONS.includes(arg[\"vertical-align\"])) return context.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${arg[\"vertical-align\"]}' instead.`);\n\t\t\t\t\tverticalAlign = context.parse(arg[\"vertical-align\"], 1, StringType);\n\t\t\t\t\tif (!verticalAlign) return null;\n\t\t\t\t}\n\t\t\t\tconst lastExpression = sections[sections.length - 1];\n\t\t\t\tlastExpression.scale = scale;\n\t\t\t\tlastExpression.font = font;\n\t\t\t\tlastExpression.textColor = textColor;\n\t\t\t\tlastExpression.verticalAlign = verticalAlign;\n\t\t\t} else {\n\t\t\t\tconst content = context.parse(args[i], 1, ValueType);\n\t\t\t\tif (!content) return null;\n\t\t\t\tconst kind = content.type.kind;\n\t\t\t\tif (kind !== \"string\" && kind !== \"value\" && kind !== \"null\" && kind !== \"resolvedImage\") return context.error(\"Formatted text type must be 'string', 'value', 'image' or 'null'.\");\n\t\t\t\tnextTokenMayBeObject = true;\n\t\t\t\tsections.push({\n\t\t\t\t\tcontent,\n\t\t\t\t\tscale: null,\n\t\t\t\t\tfont: null,\n\t\t\t\t\ttextColor: null,\n\t\t\t\t\tverticalAlign: null\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn new FormatExpression(sections);\n\t}\n\tevaluate(ctx) {\n\t\tconst evaluateSection = (section) => {\n\t\t\tconst evaluatedContent = section.content.evaluate(ctx);\n\t\t\tif (typeOf(evaluatedContent) === ResolvedImageType) return new FormattedSection(\"\", evaluatedContent, null, null, null, section.verticalAlign ? section.verticalAlign.evaluate(ctx) : null);\n\t\t\treturn new FormattedSection(valueToString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(\",\") : null, section.textColor ? section.textColor.evaluate(ctx) : null, section.verticalAlign ? section.verticalAlign.evaluate(ctx) : null);\n\t\t};\n\t\treturn new Formatted(this.sections.map(evaluateSection));\n\t}\n\teachChild(fn) {\n\t\tfor (const section of this.sections) {\n\t\t\tfn(section.content);\n\t\t\tif (section.scale) fn(section.scale);\n\t\t\tif (section.font) fn(section.font);\n\t\t\tif (section.textColor) fn(section.textColor);\n\t\t\tif (section.verticalAlign) fn(section.verticalAlign);\n\t\t}\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { FormatExpression };\n\n//# sourceMappingURL=format.mjs.map", "// node_modules/quickselect/index.js\n/**\n* Rearranges items so that all items in the [left, k] are the smallest.\n* The k-th element will have the (k - left + 1)-th smallest value in [left, right].\n*\n* @template T\n* @param {T[]} arr the array to partially sort (in place)\n* @param {number} k middle index for partial sorting (as defined above)\n* @param {number} [left=0] left index of the range to sort\n* @param {number} [right=arr.length-1] right index\n* @param {(a: T, b: T) => number} [compare = (a, b) => a - b] compare function\n*/\nfunction quickselect(arr, k, left = 0, right = arr.length - 1, compare = defaultCompare) {\n\twhile (right > left) {\n\t\tif (right - left > 600) {\n\t\t\tconst n = right - left + 1;\n\t\t\tconst m = k - left + 1;\n\t\t\tconst z = Math.log(n);\n\t\t\tconst s = .5 * Math.exp(2 * z / 3);\n\t\t\tconst sd = .5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n\t\t\tquickselect(arr, k, Math.max(left, Math.floor(k - m * s / n + sd)), Math.min(right, Math.floor(k + (n - m) * s / n + sd)), compare);\n\t\t}\n\t\tconst t = arr[k];\n\t\tlet i = left;\n\t\t/** @type {number} */\n\t\tlet j = right;\n\t\tswap(arr, left, k);\n\t\tif (compare(arr[right], t) > 0) swap(arr, left, right);\n\t\twhile (i < j) {\n\t\t\tswap(arr, i, j);\n\t\t\ti++;\n\t\t\tj--;\n\t\t\twhile (compare(arr[i], t) < 0) i++;\n\t\t\twhile (compare(arr[j], t) > 0) j--;\n\t\t}\n\t\tif (compare(arr[left], t) === 0) swap(arr, left, j);\n\t\telse {\n\t\t\tj++;\n\t\t\tswap(arr, j, right);\n\t\t}\n\t\tif (j <= k) left = j + 1;\n\t\tif (k <= j) right = j - 1;\n\t}\n}\n/**\n* @template T\n* @param {T[]} arr\n* @param {number} i\n* @param {number} j\n*/\nfunction swap(arr, i, j) {\n\tconst tmp = arr[i];\n\tarr[i] = arr[j];\n\tarr[j] = tmp;\n}\n/**\n* @template T\n* @param {T} a\n* @param {T} b\n* @returns {number}\n*/\nfunction defaultCompare(a, b) {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\nexport { quickselect as default };\n\n//# sourceMappingURL=index.mjs.map", "import quickselect from \"../node_modules/quickselect/index.mjs\";\n// src/util/classify_rings.ts\n/**\n* Classifies an array of rings into polygons with outer rings and holes\n* @param rings - the rings to classify\n* @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings\n* @returns an array of polygons with internal rings as holes\n*/\nfunction classifyRings(rings, maxRings) {\n\tif (rings.length <= 1) return [rings];\n\tconst polygons = [];\n\tlet polygon;\n\tlet ccw;\n\tfor (const ring of rings) {\n\t\tconst area = calculateSignedArea(ring);\n\t\tif (area === 0) continue;\n\t\tring.area = Math.abs(area);\n\t\tif (ccw === void 0) ccw = area < 0;\n\t\tif (ccw === area < 0) {\n\t\t\tif (polygon) polygons.push(polygon);\n\t\t\tpolygon = [ring];\n\t\t} else polygon.push(ring);\n\t}\n\tif (polygon) polygons.push(polygon);\n\tif (maxRings > 1) for (let j = 0; j < polygons.length; j++) {\n\t\tif (polygons[j].length <= maxRings) continue;\n\t\tquickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas);\n\t\tpolygons[j] = polygons[j].slice(0, maxRings);\n\t}\n\treturn polygons;\n}\nfunction compareAreas(a, b) {\n\treturn b.area - a.area;\n}\n/**\n* Returns the signed area for the polygon ring.  Positive areas are exterior rings and\n* have a clockwise winding.  Negative areas are interior rings and have a counter clockwise\n* ordering.\n*\n* @param ring - Exterior or interior ring\n* @returns Signed area\n*/\nfunction calculateSignedArea(ring) {\n\tlet sum = 0;\n\tfor (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n\t\tp1 = ring[i];\n\t\tp2 = ring[j];\n\t\tsum += (p2.x - p1.x) * (p1.y + p2.y);\n\t}\n\treturn sum;\n}\nexport { classifyRings };\n\n//# sourceMappingURL=classify_rings.mjs.map", "import { BooleanType, NumberType, ObjectType, StringType, ValueType, array, checkSubtype, typeToString } from \"../types.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\nimport { typeOf } from \"../values.mjs\";\n// src/expression/definitions/assertion.ts\nconst types = {\n\tstring: StringType,\n\tnumber: NumberType,\n\tboolean: BooleanType,\n\tobject: ObjectType\n};\nvar Assertion = class Assertion {\n\tconstructor(type, args, key) {\n\t\tthis.type = type;\n\t\tthis.args = args;\n\t\tthis.key = key;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length < 2) return context.error(\"Expected at least one argument.\");\n\t\tlet i = 1;\n\t\tlet type;\n\t\tconst name = args[0];\n\t\tif (name === \"array\") {\n\t\t\tlet itemType;\n\t\t\tif (args.length > 2) {\n\t\t\t\tconst type = args[1];\n\t\t\t\tif (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);\n\t\t\t\titemType = types[type];\n\t\t\t\ti++;\n\t\t\t} else itemType = ValueType;\n\t\t\tlet N;\n\t\t\tif (args.length > 3) {\n\t\t\t\tif (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\t\t\t\tN = args[2];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ttype = array(itemType, N);\n\t\t} else {\n\t\t\tif (!types[name]) throw new Error(`Types doesn't contain name = ${name}`);\n\t\t\ttype = types[name];\n\t\t}\n\t\tconst parsed = [];\n\t\tfor (; i < args.length; i++) {\n\t\t\tconst input = context.parse(args[i], i, ValueType);\n\t\t\tif (!input) return null;\n\t\t\tparsed.push(input);\n\t\t}\n\t\treturn new Assertion(type, parsed, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tfor (let i = 0; i < this.args.length; i++) {\n\t\t\tconst value = this.args[i].evaluate(ctx);\n\t\t\tif (!checkSubtype(this.type, typeOf(value))) return value;\n\t\t\telse if (i === this.args.length - 1) throw new RuntimeError(`Expected value to be of type ${typeToString(this.type)}, but found ${typeToString(typeOf(value))} instead.`, this.key);\n\t\t}\n\t\tthrow new Error();\n\t}\n\teachChild(fn) {\n\t\tthis.args.forEach(fn);\n\t}\n\toutputDefined() {\n\t\treturn this.args.every((arg) => arg.outputDefined());\n\t}\n};\nexport { Assertion };\n\n//# sourceMappingURL=assertion.mjs.map", "import { BooleanType, ColorType, NumberType, StringType, ValueType } from \"../types.mjs\";\nimport { Color } from \"../types/color.mjs\";\nimport { Formatted } from \"../types/formatted.mjs\";\nimport { Padding } from \"../types/padding.mjs\";\nimport { NumberArray } from \"../types/number_array.mjs\";\nimport { ColorArray } from \"../types/color_array.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\nimport { VariableAnchorOffsetCollection } from \"../types/variable_anchor_offset_collection.mjs\";\nimport { ResolvedImage } from \"../types/resolved_image.mjs\";\nimport { ProjectionDefinition } from \"../types/projection_definition.mjs\";\nimport { validateRGBA, valueToString } from \"../values.mjs\";\n// src/expression/definitions/coercion.ts\nconst types = {\n\t\"to-boolean\": BooleanType,\n\t\"to-color\": ColorType,\n\t\"to-number\": NumberType,\n\t\"to-string\": StringType\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*/\nvar Coercion = class Coercion {\n\tconstructor(type, args, key) {\n\t\tthis.type = type;\n\t\tthis.args = args;\n\t\tthis.key = key;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length < 2) return context.error(\"Expected at least one argument.\");\n\t\tconst name = args[0];\n\t\tif (!types[name]) throw new Error(`Can't parse ${name} as it is not part of the known types`);\n\t\tif ((name === \"to-boolean\" || name === \"to-string\") && args.length !== 2) return context.error(\"Expected one argument.\");\n\t\tconst type = types[name];\n\t\tconst parsed = [];\n\t\tfor (let i = 1; i < args.length; i++) {\n\t\t\tconst input = context.parse(args[i], i, ValueType);\n\t\t\tif (!input) return null;\n\t\t\tparsed.push(input);\n\t\t}\n\t\treturn new Coercion(type, parsed, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tswitch (this.type.kind) {\n\t\t\tcase \"boolean\": return Boolean(this.args[0].evaluate(ctx));\n\t\t\tcase \"color\": {\n\t\t\t\tlet input;\n\t\t\t\tlet error;\n\t\t\t\tfor (const arg of this.args) {\n\t\t\t\t\tinput = arg.evaluate(ctx);\n\t\t\t\t\terror = null;\n\t\t\t\t\tif (input instanceof Color) return input;\n\t\t\t\t\telse if (typeof input === \"string\") {\n\t\t\t\t\t\tconst c = ctx.parseColor(input);\n\t\t\t\t\t\tif (c) return c;\n\t\t\t\t\t} else if (Array.isArray(input)) {\n\t\t\t\t\t\tif (input.length < 3 || input.length > 4) error = `Invalid rgba value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`;\n\t\t\t\t\t\telse error = validateRGBA(input[0], input[1], input[2], input[3]);\n\t\t\t\t\t\tif (!error) return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new RuntimeError(error || `Could not parse color from value '${typeof input === \"string\" ? input : JSON.stringify(input)}'`, this.key);\n\t\t\t}\n\t\t\tcase \"padding\": {\n\t\t\t\tlet input;\n\t\t\t\tfor (const arg of this.args) {\n\t\t\t\t\tinput = arg.evaluate(ctx);\n\t\t\t\t\tconst pad = Padding.parse(input);\n\t\t\t\t\tif (pad) return pad;\n\t\t\t\t}\n\t\t\t\tthrow new RuntimeError(`Could not parse padding from value '${typeof input === \"string\" ? input : JSON.stringify(input)}'`, this.key);\n\t\t\t}\n\t\t\tcase \"numberArray\": {\n\t\t\t\tlet input;\n\t\t\t\tfor (const arg of this.args) {\n\t\t\t\t\tinput = arg.evaluate(ctx);\n\t\t\t\t\tconst val = NumberArray.parse(input);\n\t\t\t\t\tif (val) return val;\n\t\t\t\t}\n\t\t\t\tthrow new RuntimeError(`Could not parse numberArray from value '${typeof input === \"string\" ? input : JSON.stringify(input)}'`, this.key);\n\t\t\t}\n\t\t\tcase \"colorArray\": {\n\t\t\t\tlet input;\n\t\t\t\tfor (const arg of this.args) {\n\t\t\t\t\tinput = arg.evaluate(ctx);\n\t\t\t\t\tconst val = ColorArray.parse(input);\n\t\t\t\t\tif (val) return val;\n\t\t\t\t}\n\t\t\t\tthrow new RuntimeError(`Could not parse colorArray from value '${typeof input === \"string\" ? input : JSON.stringify(input)}'`, this.key);\n\t\t\t}\n\t\t\tcase \"variableAnchorOffsetCollection\": {\n\t\t\t\tlet input;\n\t\t\t\tfor (const arg of this.args) {\n\t\t\t\t\tinput = arg.evaluate(ctx);\n\t\t\t\t\tconst coll = VariableAnchorOffsetCollection.parse(input);\n\t\t\t\t\tif (coll) return coll;\n\t\t\t\t}\n\t\t\t\tthrow new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === \"string\" ? input : JSON.stringify(input)}'`, this.key);\n\t\t\t}\n\t\t\tcase \"number\": {\n\t\t\t\tlet value = null;\n\t\t\t\tfor (const arg of this.args) {\n\t\t\t\t\tvalue = arg.evaluate(ctx);\n\t\t\t\t\tif (value === null) return 0;\n\t\t\t\t\tconst num = Number(value);\n\t\t\t\t\tif (isNaN(num)) continue;\n\t\t\t\t\treturn num;\n\t\t\t\t}\n\t\t\t\tthrow new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`, this.key);\n\t\t\t}\n\t\t\tcase \"formatted\": return Formatted.fromString(valueToString(this.args[0].evaluate(ctx)));\n\t\t\tcase \"resolvedImage\": return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx)));\n\t\t\tcase \"projectionDefinition\": {\n\t\t\t\tconst input = this.args[0].evaluate(ctx);\n\t\t\t\tif (ProjectionDefinition.parse(input)) return input;\n\t\t\t\tthrow new RuntimeError(`Could not parse projectionDefinition from value '${typeof input === \"string\" ? input : JSON.stringify(input)}'`, this.key);\n\t\t\t}\n\t\t\tdefault: return valueToString(this.args[0].evaluate(ctx));\n\t\t}\n\t}\n\teachChild(fn) {\n\t\tthis.args.forEach(fn);\n\t}\n\toutputDefined() {\n\t\treturn this.args.every((arg) => arg.outputDefined());\n\t}\n};\nexport { Coercion };\n\n//# sourceMappingURL=coercion.mjs.map", "// src/expression/definitions/let.ts\nvar Let = class Let {\n\tconstructor(bindings, result) {\n\t\tthis.type = result.type;\n\t\tthis.bindings = [].concat(bindings);\n\t\tthis.result = result;\n\t}\n\tevaluate(ctx) {\n\t\treturn this.result.evaluate(ctx);\n\t}\n\teachChild(fn) {\n\t\tfor (const binding of this.bindings) fn(binding[1]);\n\t\tfn(this.result);\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length < 4) return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`);\n\t\tconst bindings = [];\n\t\tfor (let i = 1; i < args.length - 1; i += 2) {\n\t\t\tconst name = args[i];\n\t\t\tif (typeof name !== \"string\") return context.error(`Expected string, but found ${typeof name} instead.`, i);\n\t\t\tif (/[^a-zA-Z0-9_]/.test(name)) return context.error(\"Variable names must contain only alphanumeric characters or '_'.\", i);\n\t\t\tconst value = context.parse(args[i + 1], i + 1);\n\t\t\tif (!value) return null;\n\t\t\tbindings.push([name, value]);\n\t\t}\n\t\tconst result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);\n\t\tif (!result) return null;\n\t\treturn new Let(bindings, result);\n\t}\n\toutputDefined() {\n\t\treturn this.result.outputDefined();\n\t}\n};\nexport { Let };\n\n//# sourceMappingURL=let.mjs.map", "// src/expression/definitions/var.ts\nvar Var = class Var {\n\tconstructor(name, boundExpression) {\n\t\tthis.type = boundExpression.type;\n\t\tthis.name = name;\n\t\tthis.boundExpression = boundExpression;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2 || typeof args[1] !== \"string\") return context.error(\"'var' expression requires exactly one string literal argument.\");\n\t\tconst name = args[1];\n\t\tif (!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);\n\t\treturn new Var(name, context.scope.get(name));\n\t}\n\tevaluate(ctx) {\n\t\treturn this.boundExpression.evaluate(ctx);\n\t}\n\teachChild() {}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { Var };\n\n//# sourceMappingURL=var.mjs.map", "import { NumberType, ValueType, array } from \"../types.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\n// src/expression/definitions/at.ts\nvar At = class At {\n\tconstructor(type, index, input, key) {\n\t\tthis.type = type;\n\t\tthis.index = index;\n\t\tthis.input = input;\n\t\tthis.key = key;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 3) return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n\t\tconst index = context.parse(args[1], 1, NumberType);\n\t\tconst input = context.parse(args[2], 2, array(context.expectedType || ValueType));\n\t\tif (!index || !input) return null;\n\t\tconst t = input.type;\n\t\treturn new At(t.itemType, index, input, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tconst index = this.index.evaluate(ctx);\n\t\tconst array = this.input.evaluate(ctx);\n\t\tif (index < 0) throw new RuntimeError(`Array index out of bounds: ${index} < 0.`, this.key);\n\t\tif (index >= array.length) throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`, this.key);\n\t\tif (index !== Math.floor(index)) throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`, this.key);\n\t\treturn array[index];\n\t}\n\teachChild(fn) {\n\t\tfn(this.index);\n\t\tfn(this.input);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { At };\n\n//# sourceMappingURL=at.mjs.map", "import { BooleanType, NullType, NumberType, StringType, ValueType, isValidNativeType, isValidType, typeToString } from \"../types.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\nimport { typeOf } from \"../values.mjs\";\n// src/expression/definitions/in.ts\nvar In = class In {\n\tconstructor(needle, haystack, key) {\n\t\tthis.needle = needle;\n\t\tthis.haystack = haystack;\n\t\tthis.key = key;\n\t\tthis.type = BooleanType;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 3) return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n\t\tconst needle = context.parse(args[1], 1, ValueType);\n\t\tconst haystack = context.parse(args[2], 2, ValueType);\n\t\tif (!needle || !haystack) return null;\n\t\tif (!isValidType(needle.type, [\n\t\t\tBooleanType,\n\t\t\tStringType,\n\t\t\tNumberType,\n\t\t\tNullType,\n\t\t\tValueType\n\t\t])) return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(needle.type)} instead`);\n\t\treturn new In(needle, haystack, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tconst needle = this.needle.evaluate(ctx);\n\t\tconst haystack = this.haystack.evaluate(ctx);\n\t\tif (!haystack) return false;\n\t\tif (!isValidNativeType(needle, [\n\t\t\t\"boolean\",\n\t\t\t\"string\",\n\t\t\t\"number\",\n\t\t\t\"null\"\n\t\t])) throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(needle))} instead.`, this.key);\n\t\tif (!isValidNativeType(haystack, [\"string\", \"array\"])) throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(haystack))} instead.`, this.key);\n\t\treturn haystack.indexOf(needle) >= 0;\n\t}\n\teachChild(fn) {\n\t\tfn(this.needle);\n\t\tfn(this.haystack);\n\t}\n\toutputDefined() {\n\t\treturn true;\n\t}\n};\nexport { In };\n\n//# sourceMappingURL=in.mjs.map", "import { BooleanType, NullType, NumberType, StringType, ValueType, isValidNativeType, isValidType, typeToString } from \"../types.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\nimport { typeOf } from \"../values.mjs\";\n// src/expression/definitions/index_of.ts\nvar IndexOf = class IndexOf {\n\tconstructor(needle, haystack, key, fromIndex) {\n\t\tthis.needle = needle;\n\t\tthis.haystack = haystack;\n\t\tthis.key = key;\n\t\tthis.fromIndex = fromIndex;\n\t\tthis.type = NumberType;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length <= 2 || args.length >= 5) return context.error(`Expected 2 or 3 arguments, but found ${args.length - 1} instead.`);\n\t\tconst needle = context.parse(args[1], 1, ValueType);\n\t\tconst haystack = context.parse(args[2], 2, ValueType);\n\t\tif (!needle || !haystack) return null;\n\t\tif (!isValidType(needle.type, [\n\t\t\tBooleanType,\n\t\t\tStringType,\n\t\t\tNumberType,\n\t\t\tNullType,\n\t\t\tValueType\n\t\t])) return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(needle.type)} instead`);\n\t\tif (args.length === 4) {\n\t\t\tconst fromIndex = context.parse(args[3], 3, NumberType);\n\t\t\tif (!fromIndex) return null;\n\t\t\treturn new IndexOf(needle, haystack, context.key, fromIndex);\n\t\t} else return new IndexOf(needle, haystack, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tconst needle = this.needle.evaluate(ctx);\n\t\tconst haystack = this.haystack.evaluate(ctx);\n\t\tif (!isValidNativeType(needle, [\n\t\t\t\"boolean\",\n\t\t\t\"string\",\n\t\t\t\"number\",\n\t\t\t\"null\"\n\t\t])) throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(needle))} instead.`, this.key);\n\t\tlet fromIndex;\n\t\tif (this.fromIndex) fromIndex = this.fromIndex.evaluate(ctx);\n\t\tif (isValidNativeType(haystack, [\"string\"])) {\n\t\t\tconst rawIndex = haystack.indexOf(needle, fromIndex);\n\t\t\tif (rawIndex === -1) return -1;\n\t\t\telse return [...haystack.slice(0, rawIndex)].length;\n\t\t} else if (isValidNativeType(haystack, [\"array\"])) return haystack.indexOf(needle, fromIndex);\n\t\telse throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(haystack))} instead.`, this.key);\n\t}\n\teachChild(fn) {\n\t\tfn(this.needle);\n\t\tfn(this.haystack);\n\t\tif (this.fromIndex) fn(this.fromIndex);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { IndexOf };\n\n//# sourceMappingURL=index_of.mjs.map", "import { ValueType } from \"../types.mjs\";\nimport { typeOf } from \"../values.mjs\";\n// src/expression/definitions/match.ts\nvar Match = class Match {\n\tconstructor(inputType, outputType, input, cases, outputs, otherwise) {\n\t\tthis.inputType = inputType;\n\t\tthis.type = outputType;\n\t\tthis.input = input;\n\t\tthis.cases = cases;\n\t\tthis.outputs = outputs;\n\t\tthis.otherwise = otherwise;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length < 5) return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n\t\tif (args.length % 2 !== 1) return context.error(\"Expected an even number of arguments.\");\n\t\tlet inputType;\n\t\tlet outputType;\n\t\tif (context.expectedType && context.expectedType.kind !== \"value\") outputType = context.expectedType;\n\t\tconst cases = {};\n\t\tconst outputs = [];\n\t\tfor (let i = 2; i < args.length - 1; i += 2) {\n\t\t\tlet labels = args[i];\n\t\t\tconst value = args[i + 1];\n\t\t\tif (!Array.isArray(labels)) labels = [labels];\n\t\t\tconst labelContext = context.concat(i);\n\t\t\tif (labels.length === 0) return labelContext.error(\"Expected at least one branch label.\");\n\t\t\tfor (const label of labels) {\n\t\t\t\tif (typeof label !== \"number\" && typeof label !== \"string\") return labelContext.error(\"Branch labels must be numbers or strings.\");\n\t\t\t\telse 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}.`);\n\t\t\t\telse if (typeof label === \"number\" && Math.floor(label) !== label) return labelContext.error(\"Numeric branch labels must be integer values.\");\n\t\t\t\telse if (!inputType) inputType = typeOf(label);\n\t\t\t\telse if (labelContext.checkSubtype(inputType, typeOf(label))) return null;\n\t\t\t\tif (typeof cases[String(label)] !== \"undefined\") return labelContext.error(\"Branch labels must be unique.\");\n\t\t\t\tcases[String(label)] = outputs.length;\n\t\t\t}\n\t\t\tconst result = context.parse(value, i, outputType);\n\t\t\tif (!result) return null;\n\t\t\toutputType = outputType || result.type;\n\t\t\toutputs.push(result);\n\t\t}\n\t\tconst input = context.parse(args[1], 1, ValueType);\n\t\tif (!input) return null;\n\t\tconst otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n\t\tif (!otherwise) return null;\n\t\tif (input.type.kind !== \"value\" && context.concat(1).checkSubtype(inputType, input.type)) return null;\n\t\treturn new Match(inputType, outputType, input, cases, outputs, otherwise);\n\t}\n\tevaluate(ctx) {\n\t\tconst input = this.input.evaluate(ctx);\n\t\treturn (typeOf(input) === this.inputType && this.outputs[this.cases[input]] || this.otherwise).evaluate(ctx);\n\t}\n\teachChild(fn) {\n\t\tfn(this.input);\n\t\tthis.outputs.forEach(fn);\n\t\tfn(this.otherwise);\n\t}\n\toutputDefined() {\n\t\treturn this.outputs.every((out) => out.outputDefined()) && this.otherwise.outputDefined();\n\t}\n};\nexport { Match };\n\n//# sourceMappingURL=match.mjs.map", "import { BooleanType } from \"../types.mjs\";\n// src/expression/definitions/case.ts\nvar Case = class Case {\n\tconstructor(type, branches, otherwise) {\n\t\tthis.type = type;\n\t\tthis.branches = branches;\n\t\tthis.otherwise = otherwise;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length < 4) return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`);\n\t\tif (args.length % 2 !== 0) return context.error(\"Expected an odd number of arguments.\");\n\t\tlet outputType;\n\t\tif (context.expectedType && context.expectedType.kind !== \"value\") outputType = context.expectedType;\n\t\tconst branches = [];\n\t\tfor (let i = 1; i < args.length - 1; i += 2) {\n\t\t\tconst test = context.parse(args[i], i, BooleanType);\n\t\t\tif (!test) return null;\n\t\t\tconst result = context.parse(args[i + 1], i + 1, outputType);\n\t\t\tif (!result) return null;\n\t\t\tbranches.push([test, result]);\n\t\t\toutputType = outputType || result.type;\n\t\t}\n\t\tconst otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n\t\tif (!otherwise) return null;\n\t\tif (!outputType) throw new Error(\"Can't infer output type\");\n\t\treturn new Case(outputType, branches, otherwise);\n\t}\n\tevaluate(ctx) {\n\t\tfor (const [test, expression] of this.branches) if (test.evaluate(ctx)) return expression.evaluate(ctx);\n\t\treturn this.otherwise.evaluate(ctx);\n\t}\n\teachChild(fn) {\n\t\tfor (const [test, expression] of this.branches) {\n\t\t\tfn(test);\n\t\t\tfn(expression);\n\t\t}\n\t\tfn(this.otherwise);\n\t}\n\toutputDefined() {\n\t\treturn this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();\n\t}\n};\nexport { Case };\n\n//# sourceMappingURL=case.mjs.map", "import { NumberType, StringType, ValueType, array, isValidNativeType, isValidType, typeToString } from \"../types.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\nimport { typeOf } from \"../values.mjs\";\n// src/expression/definitions/slice.ts\nvar Slice = class Slice {\n\tconstructor(type, input, beginIndex, key, endIndex) {\n\t\tthis.type = type;\n\t\tthis.input = input;\n\t\tthis.beginIndex = beginIndex;\n\t\tthis.key = key;\n\t\tthis.endIndex = endIndex;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length <= 2 || args.length >= 5) return context.error(`Expected 2 or 3 arguments, but found ${args.length - 1} instead.`);\n\t\tconst input = context.parse(args[1], 1, ValueType);\n\t\tconst beginIndex = context.parse(args[2], 2, NumberType);\n\t\tif (!input || !beginIndex) return null;\n\t\tif (!isValidType(input.type, [\n\t\t\tarray(ValueType),\n\t\t\tStringType,\n\t\t\tValueType\n\t\t])) return context.error(`Expected first argument to be of type array or string, but found ${typeToString(input.type)} instead`);\n\t\tif (args.length === 4) {\n\t\t\tconst endIndex = context.parse(args[3], 3, NumberType);\n\t\t\tif (!endIndex) return null;\n\t\t\treturn new Slice(input.type, input, beginIndex, context.key, endIndex);\n\t\t} else return new Slice(input.type, input, beginIndex, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tconst input = this.input.evaluate(ctx);\n\t\tconst beginIndex = this.beginIndex.evaluate(ctx);\n\t\tlet endIndex;\n\t\tif (this.endIndex) endIndex = this.endIndex.evaluate(ctx);\n\t\tif (isValidNativeType(input, [\"string\"])) return [...input].slice(beginIndex, endIndex).join(\"\");\n\t\telse if (isValidNativeType(input, [\"array\"])) return input.slice(beginIndex, endIndex);\n\t\telse throw new RuntimeError(`Expected first argument to be of type array or string, but found ${typeToString(typeOf(input))} instead.`, this.key);\n\t}\n\teachChild(fn) {\n\t\tfn(this.input);\n\t\tfn(this.beginIndex);\n\t\tif (this.endIndex) fn(this.endIndex);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { Slice };\n\n//# sourceMappingURL=slice.mjs.map", "import { ValueType, checkSubtype } from \"../types.mjs\";\nimport { ResolvedImage } from \"../types/resolved_image.mjs\";\n// src/expression/definitions/coalesce.ts\nvar Coalesce = class Coalesce {\n\tconstructor(type, args) {\n\t\tthis.type = type;\n\t\tthis.args = args;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length < 2) return context.error(\"Expected at least one argument.\");\n\t\tlet outputType = null;\n\t\tconst expectedType = context.expectedType;\n\t\tif (expectedType && expectedType.kind !== \"value\") outputType = expectedType;\n\t\tconst parsedArgs = [];\n\t\tfor (const arg of args.slice(1)) {\n\t\t\tconst parsed = context.parse(arg, 1 + parsedArgs.length, outputType, void 0, { typeAnnotation: \"omit\" });\n\t\t\tif (!parsed) return null;\n\t\t\toutputType = outputType || parsed.type;\n\t\t\tparsedArgs.push(parsed);\n\t\t}\n\t\tif (!outputType) throw new Error(\"No output type\");\n\t\treturn expectedType && parsedArgs.some((arg) => checkSubtype(expectedType, arg.type)) ? new Coalesce(ValueType, parsedArgs) : new Coalesce(outputType, parsedArgs);\n\t}\n\tevaluate(ctx) {\n\t\tlet result = null;\n\t\tlet argCount = 0;\n\t\tlet requestedImageName;\n\t\tfor (const arg of this.args) {\n\t\t\targCount++;\n\t\t\tresult = arg.evaluate(ctx);\n\t\t\tif (result && result instanceof ResolvedImage && !result.available) {\n\t\t\t\tif (!requestedImageName) requestedImageName = result.name;\n\t\t\t\tresult = null;\n\t\t\t\tif (argCount === this.args.length) result = requestedImageName;\n\t\t\t}\n\t\t\tif (result !== null) break;\n\t\t}\n\t\treturn result;\n\t}\n\teachChild(fn) {\n\t\tthis.args.forEach(fn);\n\t}\n\toutputDefined() {\n\t\treturn this.args.every((arg) => arg.outputDefined());\n\t}\n};\nexport { Coalesce };\n\n//# sourceMappingURL=coalesce.mjs.map", "import { BooleanType, CollatorType, ValueType, typeToString } from \"../types.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\nimport { typeOf } from \"../values.mjs\";\nimport { Assertion } from \"./assertion.mjs\";\n// src/expression/definitions/comparison.ts\nfunction isComparableType(op, type) {\n\tif (op === \"==\" || op === \"!=\") return type.kind === \"boolean\" || type.kind === \"string\" || type.kind === \"number\" || type.kind === \"null\" || type.kind === \"value\";\n\telse return type.kind === \"string\" || type.kind === \"number\" || type.kind === \"value\";\n}\nfunction eq(ctx, a, b) {\n\treturn a === b;\n}\nfunction neq(ctx, a, b) {\n\treturn a !== b;\n}\nfunction lt(ctx, a, b) {\n\treturn a < b;\n}\nfunction gt(ctx, a, b) {\n\treturn a > b;\n}\nfunction lteq(ctx, a, b) {\n\treturn a <= b;\n}\nfunction gteq(ctx, a, b) {\n\treturn a >= b;\n}\nfunction eqCollate(ctx, a, b, c) {\n\treturn c.compare(a, b) === 0;\n}\nfunction neqCollate(ctx, a, b, c) {\n\treturn !eqCollate(ctx, a, b, c);\n}\nfunction ltCollate(ctx, a, b, c) {\n\treturn c.compare(a, b) < 0;\n}\nfunction gtCollate(ctx, a, b, c) {\n\treturn c.compare(a, b) > 0;\n}\nfunction lteqCollate(ctx, a, b, c) {\n\treturn c.compare(a, b) <= 0;\n}\nfunction gteqCollate(ctx, a, b, c) {\n\treturn 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, compareBasic, compareWithCollator) {\n\tconst isOrderComparison = op !== \"==\" && op !== \"!=\";\n\treturn class Comparison {\n\t\tconstructor(lhs, rhs, key, collator) {\n\t\t\tthis.lhs = lhs;\n\t\t\tthis.rhs = rhs;\n\t\t\tthis.key = key;\n\t\t\tthis.collator = collator;\n\t\t\tthis.type = BooleanType;\n\t\t\tthis.hasUntypedArgument = lhs.type.kind === \"value\" || rhs.type.kind === \"value\";\n\t\t}\n\t\tstatic parse(args, context) {\n\t\t\tif (args.length !== 3 && args.length !== 4) return context.error(\"Expected two or three arguments.\");\n\t\t\tconst op = args[0];\n\t\t\tlet lhs = context.parse(args[1], 1, ValueType);\n\t\t\tif (!lhs) return null;\n\t\t\tif (!isComparableType(op, lhs.type)) return context.concat(1).error(`\"${op}\" comparisons are not supported for type '${typeToString(lhs.type)}'.`);\n\t\t\tlet rhs = context.parse(args[2], 2, ValueType);\n\t\t\tif (!rhs) return null;\n\t\t\tif (!isComparableType(op, rhs.type)) return context.concat(2).error(`\"${op}\" comparisons are not supported for type '${typeToString(rhs.type)}'.`);\n\t\t\tif (lhs.type.kind !== rhs.type.kind && lhs.type.kind !== \"value\" && rhs.type.kind !== \"value\") return context.error(`Cannot compare types '${typeToString(lhs.type)}' and '${typeToString(rhs.type)}'.`);\n\t\t\tif (isOrderComparison) {\n\t\t\t\tif (lhs.type.kind === \"value\" && rhs.type.kind !== \"value\") lhs = new Assertion(rhs.type, [lhs], context.key);\n\t\t\t\telse if (lhs.type.kind !== \"value\" && rhs.type.kind === \"value\") rhs = new Assertion(lhs.type, [rhs], context.key);\n\t\t\t}\n\t\t\tlet collator = null;\n\t\t\tif (args.length === 4) {\n\t\t\t\tif (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.\");\n\t\t\t\tcollator = context.parse(args[3], 3, CollatorType);\n\t\t\t\tif (!collator) return null;\n\t\t\t}\n\t\t\treturn new Comparison(lhs, rhs, context.key, collator);\n\t\t}\n\t\tevaluate(ctx) {\n\t\t\tconst lhs = this.lhs.evaluate(ctx);\n\t\t\tconst rhs = this.rhs.evaluate(ctx);\n\t\t\tif (isOrderComparison && this.hasUntypedArgument) {\n\t\t\t\tconst lt = typeOf(lhs);\n\t\t\t\tconst rt = typeOf(rhs);\n\t\t\t\tif (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.`, this.key);\n\t\t\t}\n\t\t\tif (this.collator && !isOrderComparison && this.hasUntypedArgument) {\n\t\t\t\tconst lt = typeOf(lhs);\n\t\t\t\tconst rt = typeOf(rhs);\n\t\t\t\tif (lt.kind !== \"string\" || rt.kind !== \"string\") return compareBasic(ctx, lhs, rhs);\n\t\t\t}\n\t\t\treturn this.collator ? compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : compareBasic(ctx, lhs, rhs);\n\t\t}\n\t\teachChild(fn) {\n\t\t\tfn(this.lhs);\n\t\t\tfn(this.rhs);\n\t\t\tif (this.collator) fn(this.collator);\n\t\t}\n\t\toutputDefined() {\n\t\t\treturn true;\n\t\t}\n\t};\n}\nconst Equals = makeComparison(\"==\", eq, eqCollate);\nconst NotEquals = makeComparison(\"!=\", neq, neqCollate);\nconst LessThan = makeComparison(\"<\", lt, ltCollate);\nconst GreaterThan = makeComparison(\">\", gt, gtCollate);\nconst LessThanOrEqual = makeComparison(\"<=\", lteq, lteqCollate);\nconst GreaterThanOrEqual = makeComparison(\">=\", gteq, gteqCollate);\nexport { Equals, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, NotEquals };\n\n//# sourceMappingURL=comparison.mjs.map", "import { BooleanType, CollatorType, StringType } from \"../types.mjs\";\nimport { Collator } from \"../types/collator.mjs\";\n// src/expression/definitions/collator.ts\nvar CollatorExpression = class CollatorExpression {\n\tconstructor(caseSensitive, diacriticSensitive, locale) {\n\t\tthis.type = CollatorType;\n\t\tthis.locale = locale;\n\t\tthis.caseSensitive = caseSensitive;\n\t\tthis.diacriticSensitive = diacriticSensitive;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(\"Expected one argument.\");\n\t\tconst options = args[1];\n\t\tif (typeof options !== \"object\" || Array.isArray(options)) return context.error(\"Collator options argument must be an object.\");\n\t\tconst caseSensitive = context.parse(options[\"case-sensitive\"] === void 0 ? false : options[\"case-sensitive\"], 1, BooleanType);\n\t\tif (!caseSensitive) return null;\n\t\tconst diacriticSensitive = context.parse(options[\"diacritic-sensitive\"] === void 0 ? false : options[\"diacritic-sensitive\"], 1, BooleanType);\n\t\tif (!diacriticSensitive) return null;\n\t\tlet locale = null;\n\t\tif (options[\"locale\"]) {\n\t\t\tlocale = context.parse(options[\"locale\"], 1, StringType);\n\t\t\tif (!locale) return null;\n\t\t}\n\t\treturn new CollatorExpression(caseSensitive, diacriticSensitive, locale);\n\t}\n\tevaluate(ctx) {\n\t\treturn new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);\n\t}\n\teachChild(fn) {\n\t\tfn(this.caseSensitive);\n\t\tfn(this.diacriticSensitive);\n\t\tif (this.locale) fn(this.locale);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { CollatorExpression };\n\n//# sourceMappingURL=collator.mjs.map", "import { NumberType, StringType } from \"../types.mjs\";\n// src/expression/definitions/number_format.ts\nvar NumberFormat = class NumberFormat {\n\tconstructor(number, locale, currency, unit, minFractionDigits, maxFractionDigits) {\n\t\tthis.type = StringType;\n\t\tthis.number = number;\n\t\tthis.locale = locale;\n\t\tthis.currency = currency;\n\t\tthis.unit = unit;\n\t\tthis.minFractionDigits = minFractionDigits;\n\t\tthis.maxFractionDigits = maxFractionDigits;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 3) return context.error(\"Expected two arguments.\");\n\t\tconst number = context.parse(args[1], 1, NumberType);\n\t\tif (!number) return null;\n\t\tconst options = args[2];\n\t\tif (typeof options !== \"object\" || Array.isArray(options)) return context.error(\"NumberFormat options argument must be an object.\");\n\t\tlet locale = null;\n\t\tif (options[\"locale\"]) {\n\t\t\tlocale = context.parse(options[\"locale\"], 1, StringType);\n\t\t\tif (!locale) return null;\n\t\t}\n\t\tlet currency = null;\n\t\tif (options[\"currency\"]) {\n\t\t\tcurrency = context.parse(options[\"currency\"], 1, StringType);\n\t\t\tif (!currency) return null;\n\t\t}\n\t\tlet unit = null;\n\t\tif (options[\"unit\"]) {\n\t\t\tunit = context.parse(options[\"unit\"], 1, StringType);\n\t\t\tif (!unit) return null;\n\t\t}\n\t\tif (currency && unit) return context.error(\"NumberFormat options `currency` and `unit` are mutually exclusive\");\n\t\tlet minFractionDigits = null;\n\t\tif (options[\"min-fraction-digits\"]) {\n\t\t\tminFractionDigits = context.parse(options[\"min-fraction-digits\"], 1, NumberType);\n\t\t\tif (!minFractionDigits) return null;\n\t\t}\n\t\tlet maxFractionDigits = null;\n\t\tif (options[\"max-fraction-digits\"]) {\n\t\t\tmaxFractionDigits = context.parse(options[\"max-fraction-digits\"], 1, NumberType);\n\t\t\tif (!maxFractionDigits) return null;\n\t\t}\n\t\treturn new NumberFormat(number, locale, currency, unit, minFractionDigits, maxFractionDigits);\n\t}\n\tevaluate(ctx) {\n\t\treturn new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], {\n\t\t\tstyle: this.currency ? \"currency\" : this.unit ? \"unit\" : \"decimal\",\n\t\t\tcurrency: this.currency ? this.currency.evaluate(ctx) : void 0,\n\t\t\tunit: this.unit ? this.unit.evaluate(ctx) : void 0,\n\t\t\tminimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : void 0,\n\t\t\tmaximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : void 0\n\t\t}).format(this.number.evaluate(ctx));\n\t}\n\teachChild(fn) {\n\t\tfn(this.number);\n\t\tif (this.locale) fn(this.locale);\n\t\tif (this.currency) fn(this.currency);\n\t\tif (this.unit) fn(this.unit);\n\t\tif (this.minFractionDigits) fn(this.minFractionDigits);\n\t\tif (this.maxFractionDigits) fn(this.maxFractionDigits);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { NumberFormat };\n\n//# sourceMappingURL=number_format.mjs.map", "import { ResolvedImageType, StringType } from \"../types.mjs\";\nimport { ResolvedImage } from \"../types/resolved_image.mjs\";\n// src/expression/definitions/image.ts\nvar ImageExpression = class ImageExpression {\n\tconstructor(input) {\n\t\tthis.type = ResolvedImageType;\n\t\tthis.input = input;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(\"Expected two arguments.\");\n\t\tconst name = context.parse(args[1], 1, StringType);\n\t\tif (!name) return context.error(\"No image name provided.\");\n\t\treturn new ImageExpression(name);\n\t}\n\tevaluate(ctx) {\n\t\tconst evaluatedImageName = this.input.evaluate(ctx);\n\t\tconst value = ResolvedImage.fromString(evaluatedImageName);\n\t\tif (value && ctx.availableImages) value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1;\n\t\treturn value;\n\t}\n\teachChild(fn) {\n\t\tfn(this.input);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { ImageExpression };\n\n//# sourceMappingURL=image.mjs.map", "import { NumberType, typeToString } from \"../types.mjs\";\nimport { RuntimeError } from \"../runtime_error.mjs\";\nimport { typeOf } from \"../values.mjs\";\n// src/expression/definitions/length.ts\nvar Length = class Length {\n\tconstructor(input, key) {\n\t\tthis.input = input;\n\t\tthis.key = key;\n\t\tthis.type = NumberType;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);\n\t\tconst input = context.parse(args[1], 1);\n\t\tif (!input) return null;\n\t\tif (input.type.kind !== \"array\" && input.type.kind !== \"string\" && input.type.kind !== \"value\") return context.error(`Expected argument of type string or array, but found ${typeToString(input.type)} instead.`);\n\t\treturn new Length(input, context.key);\n\t}\n\tevaluate(ctx) {\n\t\tconst input = this.input.evaluate(ctx);\n\t\tif (typeof input === \"string\") return [...input].length;\n\t\telse if (Array.isArray(input)) return input.length;\n\t\telse throw new RuntimeError(`Expected value to be of type string or array, but found ${typeToString(typeOf(input))} instead.`, this.key);\n\t}\n\teachChild(fn) {\n\t\tfn(this.input);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { Length };\n\n//# sourceMappingURL=length.mjs.map", "// src/util/geometry_util.ts\nconst EXTENT = 8192;\nfunction getTileCoordinates(p, canonical) {\n\tconst x = mercatorXfromLng(p[0]);\n\tconst y = mercatorYfromLat(p[1]);\n\tconst tilesAtZoom = Math.pow(2, canonical.z);\n\treturn [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)];\n}\nfunction getLngLatFromTileCoord(coord, canonical) {\n\tconst tilesAtZoom = Math.pow(2, canonical.z);\n\tconst x = (coord[0] / EXTENT + canonical.x) / tilesAtZoom;\n\tconst y = (coord[1] / EXTENT + canonical.y) / tilesAtZoom;\n\treturn [lngFromMercatorXfromLng(x), latFromMercatorY(y)];\n}\nfunction mercatorXfromLng(lng) {\n\treturn (180 + lng) / 360;\n}\nfunction lngFromMercatorXfromLng(mercatorX) {\n\treturn mercatorX * 360 - 180;\n}\nfunction mercatorYfromLat(lat) {\n\treturn (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;\n}\nfunction latFromMercatorY(mercatorY) {\n\treturn 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90;\n}\nfunction updateBBox(bbox, coord) {\n\tbbox[0] = Math.min(bbox[0], coord[0]);\n\tbbox[1] = Math.min(bbox[1], coord[1]);\n\tbbox[2] = Math.max(bbox[2], coord[0]);\n\tbbox[3] = Math.max(bbox[3], coord[1]);\n}\nfunction boxWithinBox(bbox1, bbox2) {\n\tif (bbox1[0] <= bbox2[0]) return false;\n\tif (bbox1[2] >= bbox2[2]) return false;\n\tif (bbox1[1] <= bbox2[1]) return false;\n\tif (bbox1[3] >= bbox2[3]) return false;\n\treturn true;\n}\nfunction rayIntersect(p, p1, p2) {\n\treturn 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}\nfunction pointOnBoundary(p, p1, p2) {\n\tconst x1 = p[0] - p1[0];\n\tconst y1 = p[1] - p1[1];\n\tconst x2 = p[0] - p2[0];\n\tconst y2 = p[1] - p2[1];\n\treturn x1 * y2 - x2 * y1 === 0 && x1 * x2 <= 0 && y1 * y2 <= 0;\n}\nfunction segmentIntersectSegment(a, b, c, d) {\n\tconst vectorP = [b[0] - a[0], b[1] - a[1]];\n\tif (perp([d[0] - c[0], d[1] - c[1]], vectorP) === 0) return false;\n\tif (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true;\n\treturn false;\n}\nfunction lineIntersectPolygon(p1, p2, polygon) {\n\tfor (const ring of polygon) for (let j = 0; j < ring.length - 1; ++j) if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) return true;\n\treturn false;\n}\nfunction pointWithinPolygon(point, rings, trueIfOnBoundary = false) {\n\tlet inside = false;\n\tfor (const ring of rings) for (let j = 0; j < ring.length - 1; j++) {\n\t\tif (pointOnBoundary(point, ring[j], ring[j + 1])) return trueIfOnBoundary;\n\t\tif (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside;\n\t}\n\treturn inside;\n}\nfunction pointWithinPolygons(point, polygons) {\n\tfor (const polygon of polygons) if (pointWithinPolygon(point, polygon)) return true;\n\treturn false;\n}\nfunction lineStringWithinPolygon(line, polygon) {\n\tfor (const point of line) if (!pointWithinPolygon(point, polygon)) return false;\n\tfor (let i = 0; i < line.length - 1; ++i) if (lineIntersectPolygon(line[i], line[i + 1], polygon)) return false;\n\treturn true;\n}\nfunction lineStringWithinPolygons(line, polygons) {\n\tfor (const polygon of polygons) if (lineStringWithinPolygon(line, polygon)) return true;\n\treturn false;\n}\nfunction perp(v1, v2) {\n\treturn v1[0] * v2[1] - v1[1] * v2[0];\n}\nfunction twoSided(p1, p2, q1, q2) {\n\tconst x1 = p1[0] - q1[0];\n\tconst y1 = p1[1] - q1[1];\n\tconst x2 = p2[0] - q1[0];\n\tconst y2 = p2[1] - q1[1];\n\tconst x3 = q2[0] - q1[0];\n\tconst y3 = q2[1] - q1[1];\n\tconst det1 = x1 * y3 - x3 * y1;\n\tconst det2 = x2 * y3 - x3 * y2;\n\tif (det1 > 0 && det2 < 0 || det1 < 0 && det2 > 0) return true;\n\treturn false;\n}\nexport { EXTENT, boxWithinBox, getLngLatFromTileCoord, getTileCoordinates, lineIntersectPolygon, lineStringWithinPolygon, lineStringWithinPolygons, pointWithinPolygon, pointWithinPolygons, rayIntersect, segmentIntersectSegment, updateBBox };\n\n//# sourceMappingURL=geometry_util.mjs.map", "import { BooleanType } from \"../types.mjs\";\nimport { isValue } from \"../values.mjs\";\nimport { EXTENT, boxWithinBox, getTileCoordinates, lineStringWithinPolygon, lineStringWithinPolygons, pointWithinPolygon, pointWithinPolygons, updateBBox } from \"../../util/geometry_util.mjs\";\n// src/expression/definitions/within.ts\nfunction getTilePolygon(coordinates, bbox, canonical) {\n\tconst polygon = [];\n\tfor (let i = 0; i < coordinates.length; i++) {\n\t\tconst ring = [];\n\t\tfor (let j = 0; j < coordinates[i].length; j++) {\n\t\t\tconst coord = getTileCoordinates(coordinates[i][j], canonical);\n\t\t\tupdateBBox(bbox, coord);\n\t\t\tring.push(coord);\n\t\t}\n\t\tpolygon.push(ring);\n\t}\n\treturn polygon;\n}\nfunction getTilePolygons(coordinates, bbox, canonical) {\n\tconst polygons = [];\n\tfor (let i = 0; i < coordinates.length; i++) {\n\t\tconst polygon = getTilePolygon(coordinates[i], bbox, canonical);\n\t\tpolygons.push(polygon);\n\t}\n\treturn polygons;\n}\nfunction updatePoint(p, bbox, polyBBox, worldSize) {\n\tif (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {\n\t\tconst halfWorldSize = worldSize * .5;\n\t\tlet shift = p[0] - polyBBox[0] > halfWorldSize ? -worldSize : polyBBox[0] - p[0] > halfWorldSize ? worldSize : 0;\n\t\tif (shift === 0) shift = p[0] - polyBBox[2] > halfWorldSize ? -worldSize : polyBBox[2] - p[0] > halfWorldSize ? worldSize : 0;\n\t\tp[0] += shift;\n\t}\n\tupdateBBox(bbox, p);\n}\nfunction resetBBox(bbox) {\n\tbbox[0] = bbox[1] = Infinity;\n\tbbox[2] = bbox[3] = -Infinity;\n}\nfunction getTilePoints(geometry, pointBBox, polyBBox, canonical) {\n\tconst worldSize = Math.pow(2, canonical.z) * EXTENT;\n\tconst shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n\tconst tilePoints = [];\n\tfor (const points of geometry) for (const point of points) {\n\t\tconst p = [point.x + shifts[0], point.y + shifts[1]];\n\t\tupdatePoint(p, pointBBox, polyBBox, worldSize);\n\t\ttilePoints.push(p);\n\t}\n\treturn tilePoints;\n}\nfunction getTileLines(geometry, lineBBox, polyBBox, canonical) {\n\tconst worldSize = Math.pow(2, canonical.z) * EXTENT;\n\tconst shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n\tconst tileLines = [];\n\tfor (const line of geometry) {\n\t\tconst tileLine = [];\n\t\tfor (const point of line) {\n\t\t\tconst p = [point.x + shifts[0], point.y + shifts[1]];\n\t\t\tupdateBBox(lineBBox, p);\n\t\t\ttileLine.push(p);\n\t\t}\n\t\ttileLines.push(tileLine);\n\t}\n\tif (lineBBox[2] - lineBBox[0] <= worldSize / 2) {\n\t\tresetBBox(lineBBox);\n\t\tfor (const line of tileLines) for (const p of line) updatePoint(p, lineBBox, polyBBox, worldSize);\n\t}\n\treturn tileLines;\n}\nfunction pointsWithinPolygons(ctx, polygonGeometry) {\n\tconst pointBBox = [\n\t\tInfinity,\n\t\tInfinity,\n\t\t-Infinity,\n\t\t-Infinity\n\t];\n\tconst polyBBox = [\n\t\tInfinity,\n\t\tInfinity,\n\t\t-Infinity,\n\t\t-Infinity\n\t];\n\tconst canonical = ctx.canonicalID();\n\tif (polygonGeometry.type === \"Polygon\") {\n\t\tconst tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n\t\tconst tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n\t\tif (!boxWithinBox(pointBBox, polyBBox)) return false;\n\t\tfor (const point of tilePoints) if (!pointWithinPolygon(point, tilePolygon)) return false;\n\t}\n\tif (polygonGeometry.type === \"MultiPolygon\") {\n\t\tconst tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n\t\tconst tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n\t\tif (!boxWithinBox(pointBBox, polyBBox)) return false;\n\t\tfor (const point of tilePoints) if (!pointWithinPolygons(point, tilePolygons)) return false;\n\t}\n\treturn true;\n}\nfunction linesWithinPolygons(ctx, polygonGeometry) {\n\tconst lineBBox = [\n\t\tInfinity,\n\t\tInfinity,\n\t\t-Infinity,\n\t\t-Infinity\n\t];\n\tconst polyBBox = [\n\t\tInfinity,\n\t\tInfinity,\n\t\t-Infinity,\n\t\t-Infinity\n\t];\n\tconst canonical = ctx.canonicalID();\n\tif (polygonGeometry.type === \"Polygon\") {\n\t\tconst tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n\t\tconst tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n\t\tif (!boxWithinBox(lineBBox, polyBBox)) return false;\n\t\tfor (const line of tileLines) if (!lineStringWithinPolygon(line, tilePolygon)) return false;\n\t}\n\tif (polygonGeometry.type === \"MultiPolygon\") {\n\t\tconst tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n\t\tconst tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n\t\tif (!boxWithinBox(lineBBox, polyBBox)) return false;\n\t\tfor (const line of tileLines) if (!lineStringWithinPolygons(line, tilePolygons)) return false;\n\t}\n\treturn true;\n}\nvar Within = class Within {\n\tconstructor(geojson, geometries) {\n\t\tthis.type = BooleanType;\n\t\tthis.geojson = geojson;\n\t\tthis.geometries = geometries;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\t\tif (isValue(args[1])) {\n\t\t\tconst geojson = args[1];\n\t\t\tif (geojson.type === \"FeatureCollection\") {\n\t\t\t\tconst polygonsCoords = [];\n\t\t\t\tfor (const polygon of geojson.features) {\n\t\t\t\t\tconst { type, coordinates } = polygon.geometry;\n\t\t\t\t\tif (type === \"Polygon\") polygonsCoords.push(coordinates);\n\t\t\t\t\tif (type === \"MultiPolygon\") polygonsCoords.push(...coordinates);\n\t\t\t\t}\n\t\t\t\tif (polygonsCoords.length) return new Within(geojson, {\n\t\t\t\t\ttype: \"MultiPolygon\",\n\t\t\t\t\tcoordinates: polygonsCoords\n\t\t\t\t});\n\t\t\t} else if (geojson.type === \"Feature\") {\n\t\t\t\tconst type = geojson.geometry.type;\n\t\t\t\tif (type === \"Polygon\" || type === \"MultiPolygon\") return new Within(geojson, geojson.geometry);\n\t\t\t} else if (geojson.type === \"Polygon\" || geojson.type === \"MultiPolygon\") return new Within(geojson, geojson);\n\t\t}\n\t\treturn context.error(\"'within' expression requires valid geojson object that contains polygon geometry type.\");\n\t}\n\tevaluate(ctx) {\n\t\tif (ctx.geometry() != null && ctx.canonicalID() != null) {\n\t\t\tif (ctx.geometryType() === \"Point\") return pointsWithinPolygons(ctx, this.geometries);\n\t\t\telse if (ctx.geometryType() === \"LineString\") return linesWithinPolygons(ctx, this.geometries);\n\t\t}\n\t\treturn false;\n\t}\n\teachChild() {}\n\toutputDefined() {\n\t\treturn true;\n\t}\n};\nexport { Within };\n\n//# sourceMappingURL=within.mjs.map", "// node_modules/tinyqueue/index.js\nvar TinyQueue = class {\n\tconstructor(data = [], compare = (a, b) => a < b ? -1 : a > b ? 1 : 0) {\n\t\tthis.data = data;\n\t\tthis.length = this.data.length;\n\t\tthis.compare = compare;\n\t\tif (this.length > 0) for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i);\n\t}\n\tpush(item) {\n\t\tthis.data.push(item);\n\t\tthis._up(this.length++);\n\t}\n\tpop() {\n\t\tif (this.length === 0) return void 0;\n\t\tconst top = this.data[0];\n\t\tconst bottom = this.data.pop();\n\t\tif (--this.length > 0) {\n\t\t\tthis.data[0] = bottom;\n\t\t\tthis._down(0);\n\t\t}\n\t\treturn top;\n\t}\n\tpeek() {\n\t\treturn this.data[0];\n\t}\n\t_up(pos) {\n\t\tconst { data, compare } = this;\n\t\tconst item = data[pos];\n\t\twhile (pos > 0) {\n\t\t\tconst parent = pos - 1 >> 1;\n\t\t\tconst current = data[parent];\n\t\t\tif (compare(item, current) >= 0) break;\n\t\t\tdata[pos] = current;\n\t\t\tpos = parent;\n\t\t}\n\t\tdata[pos] = item;\n\t}\n\t_down(pos) {\n\t\tconst { data, compare } = this;\n\t\tconst halfLength = this.length >> 1;\n\t\tconst item = data[pos];\n\t\twhile (pos < halfLength) {\n\t\t\tlet bestChild = (pos << 1) + 1;\n\t\t\tconst right = bestChild + 1;\n\t\t\tif (right < this.length && compare(data[right], data[bestChild]) < 0) bestChild = right;\n\t\t\tif (compare(data[bestChild], item) >= 0) break;\n\t\t\tdata[pos] = data[bestChild];\n\t\t\tpos = bestChild;\n\t\t}\n\t\tdata[pos] = item;\n\t}\n};\nexport { TinyQueue as default };\n\n//# sourceMappingURL=index.mjs.map", "// src/util/cheap_ruler.ts\nconst RE = 6378.137;\nconst E2 = .0066943799901413165;\nconst RAD = Math.PI / 180;\nvar CheapRuler = class {\n\tconstructor(lat) {\n\t\tconst m = RAD * RE * 1e3;\n\t\tconst coslat = Math.cos(lat * RAD);\n\t\tconst w2 = 1 / (1 - E2 * (1 - coslat * coslat));\n\t\tconst w = Math.sqrt(w2);\n\t\tthis.kx = m * w * coslat;\n\t\tthis.ky = m * w * w2 * .9933056200098587;\n\t}\n\t/**\n\t* Given two points of the form [longitude, latitude], returns the distance.\n\t*\n\t* @param a - point [longitude, latitude]\n\t* @param b - point [longitude, latitude]\n\t* @returns distance\n\t* @example\n\t* const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]);\n\t* //=distance\n\t*/\n\tdistance(a, b) {\n\t\tconst dx = this.wrap(a[0] - b[0]) * this.kx;\n\t\tconst dy = (a[1] - b[1]) * this.ky;\n\t\treturn Math.sqrt(dx * dx + dy * dy);\n\t}\n\t/**\n\t* Returns an object of the form {point, index, t}, where point is closest point on the line\n\t* from the given point, index is the start index of the segment with the closest point,\n\t* and t is a parameter from 0 to 1 that indicates where the closest point is on that segment.\n\t*\n\t* @param line - an array of points that form the line\n\t* @param p - point [longitude, latitude]\n\t* @returns the nearest point, its index in the array and the proportion along the line\n\t* @example\n\t* const point = ruler.pointOnLine(line, [-67.04, 50.5]).point;\n\t* //=point\n\t*/\n\tpointOnLine(line, p) {\n\t\tlet minDist = Infinity;\n\t\tlet minX, minY, minI, minT;\n\t\tfor (let i = 0; i < line.length - 1; i++) {\n\t\t\tlet x = line[i][0];\n\t\t\tlet y = line[i][1];\n\t\t\tlet dx = this.wrap(line[i + 1][0] - x) * this.kx;\n\t\t\tlet dy = (line[i + 1][1] - y) * this.ky;\n\t\t\tlet t = 0;\n\t\t\tif (dx !== 0 || dy !== 0) {\n\t\t\t\tt = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy);\n\t\t\t\tif (t > 1) {\n\t\t\t\t\tx = line[i + 1][0];\n\t\t\t\t\ty = line[i + 1][1];\n\t\t\t\t} else if (t > 0) {\n\t\t\t\t\tx += dx / this.kx * t;\n\t\t\t\t\ty += dy / this.ky * t;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdx = this.wrap(p[0] - x) * this.kx;\n\t\t\tdy = (p[1] - y) * this.ky;\n\t\t\tconst sqDist = dx * dx + dy * dy;\n\t\t\tif (sqDist < minDist) {\n\t\t\t\tminDist = sqDist;\n\t\t\t\tminX = x;\n\t\t\t\tminY = y;\n\t\t\t\tminI = i;\n\t\t\t\tminT = t;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tpoint: [minX, minY],\n\t\t\tindex: minI,\n\t\t\tt: Math.max(0, Math.min(1, minT))\n\t\t};\n\t}\n\twrap(deg) {\n\t\twhile (deg < -180) deg += 360;\n\t\twhile (deg > 180) deg -= 360;\n\t\treturn deg;\n\t}\n};\nexport { CheapRuler };\n\n//# sourceMappingURL=cheap_ruler.mjs.map", "import { NumberType } from \"../types.mjs\";\nimport { isValue } from \"../values.mjs\";\nimport { boxWithinBox, getLngLatFromTileCoord, pointWithinPolygon, segmentIntersectSegment, updateBBox } from \"../../util/geometry_util.mjs\";\nimport TinyQueue from \"../../node_modules/tinyqueue/index.mjs\";\nimport { classifyRings } from \"../../util/classify_rings.mjs\";\nimport { CheapRuler } from \"../../util/cheap_ruler.mjs\";\n// src/expression/definitions/distance.ts\nconst MinPointsSize = 100;\nconst MinLinePointsSize = 50;\nfunction compareDistPair(a, b) {\n\treturn b[0] - a[0];\n}\nfunction getRangeSize(range) {\n\treturn range[1] - range[0] + 1;\n}\nfunction isRangeSafe(range, threshold) {\n\treturn range[1] >= range[0] && range[1] < threshold;\n}\nfunction splitRange(range, isLine) {\n\tif (range[0] > range[1]) return [null, null];\n\tconst size = getRangeSize(range);\n\tif (isLine) {\n\t\tif (size === 2) return [range, null];\n\t\tconst size1 = Math.floor(size / 2);\n\t\treturn [[range[0], range[0] + size1], [range[0] + size1, range[1]]];\n\t}\n\tif (size === 1) return [range, null];\n\tconst size1 = Math.floor(size / 2) - 1;\n\treturn [[range[0], range[0] + size1], [range[0] + size1 + 1, range[1]]];\n}\nfunction getBBox(coords, range) {\n\tif (!isRangeSafe(range, coords.length)) return [\n\t\tInfinity,\n\t\tInfinity,\n\t\t-Infinity,\n\t\t-Infinity\n\t];\n\tconst bbox = [\n\t\tInfinity,\n\t\tInfinity,\n\t\t-Infinity,\n\t\t-Infinity\n\t];\n\tfor (let i = range[0]; i <= range[1]; ++i) updateBBox(bbox, coords[i]);\n\treturn bbox;\n}\nfunction getPolygonBBox(polygon) {\n\tconst bbox = [\n\t\tInfinity,\n\t\tInfinity,\n\t\t-Infinity,\n\t\t-Infinity\n\t];\n\tfor (const ring of polygon) for (const coord of ring) updateBBox(bbox, coord);\n\treturn bbox;\n}\nfunction isValidBBox(bbox) {\n\treturn bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity;\n}\nfunction bboxToBBoxDistance(bbox1, bbox2, ruler) {\n\tif (!isValidBBox(bbox1) || !isValidBBox(bbox2)) return NaN;\n\tlet dx = 0;\n\tlet dy = 0;\n\tif (bbox1[2] < bbox2[0]) dx = bbox2[0] - bbox1[2];\n\tif (bbox1[0] > bbox2[2]) dx = bbox1[0] - bbox2[2];\n\tif (bbox1[1] > bbox2[3]) dy = bbox1[1] - bbox2[3];\n\tif (bbox1[3] < bbox2[1]) dy = bbox2[1] - bbox1[3];\n\treturn ruler.distance([0, 0], [dx, dy]);\n}\nfunction pointToLineDistance(point, line, ruler) {\n\tconst nearestPoint = ruler.pointOnLine(line, point);\n\treturn ruler.distance(point, nearestPoint.point);\n}\nfunction segmentToSegmentDistance(p1, p2, q1, q2, ruler) {\n\tconst dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler));\n\tconst dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler));\n\treturn Math.min(dist1, dist2);\n}\nfunction lineToLineDistance(line1, range1, line2, range2, ruler) {\n\tif (!(isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length))) return Infinity;\n\tlet dist = Infinity;\n\tfor (let i = range1[0]; i < range1[1]; ++i) {\n\t\tconst p1 = line1[i];\n\t\tconst p2 = line1[i + 1];\n\t\tfor (let j = range2[0]; j < range2[1]; ++j) {\n\t\t\tconst q1 = line2[j];\n\t\t\tconst q2 = line2[j + 1];\n\t\t\tif (segmentIntersectSegment(p1, p2, q1, q2)) return 0;\n\t\t\tdist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));\n\t\t}\n\t}\n\treturn dist;\n}\nfunction pointsToPointsDistance(points1, range1, points2, range2, ruler) {\n\tif (!(isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length))) return NaN;\n\tlet dist = Infinity;\n\tfor (let i = range1[0]; i <= range1[1]; ++i) for (let j = range2[0]; j <= range2[1]; ++j) {\n\t\tdist = Math.min(dist, ruler.distance(points1[i], points2[j]));\n\t\tif (dist === 0) return dist;\n\t}\n\treturn dist;\n}\nfunction pointToPolygonDistance(point, polygon, ruler) {\n\tif (pointWithinPolygon(point, polygon, true)) return 0;\n\tlet dist = Infinity;\n\tfor (const ring of polygon) {\n\t\tconst front = ring[0];\n\t\tconst back = ring[ring.length - 1];\n\t\tif (front !== back) {\n\t\t\tdist = Math.min(dist, pointToLineDistance(point, [back, front], ruler));\n\t\t\tif (dist === 0) return dist;\n\t\t}\n\t\tconst nearestPoint = ruler.pointOnLine(ring, point);\n\t\tdist = Math.min(dist, ruler.distance(point, nearestPoint.point));\n\t\tif (dist === 0) return dist;\n\t}\n\treturn dist;\n}\nfunction lineToPolygonDistance(line, range, polygon, ruler) {\n\tif (!isRangeSafe(range, line.length)) return NaN;\n\tfor (let i = range[0]; i <= range[1]; ++i) if (pointWithinPolygon(line[i], polygon, true)) return 0;\n\tlet dist = Infinity;\n\tfor (let i = range[0]; i < range[1]; ++i) {\n\t\tconst p1 = line[i];\n\t\tconst p2 = line[i + 1];\n\t\tfor (const ring of polygon) for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) {\n\t\t\tconst q1 = ring[k];\n\t\t\tconst q2 = ring[j];\n\t\t\tif (segmentIntersectSegment(p1, p2, q1, q2)) return 0;\n\t\t\tdist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));\n\t\t}\n\t}\n\treturn dist;\n}\nfunction polygonIntersect(poly1, poly2) {\n\tfor (const ring of poly1) for (const point of ring) if (pointWithinPolygon(point, poly2, true)) return true;\n\treturn false;\n}\nfunction polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) {\n\tconst bbox1 = getPolygonBBox(polygon1);\n\tconst bbox2 = getPolygonBBox(polygon2);\n\tif (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) return currentMiniDist;\n\tif (boxWithinBox(bbox1, bbox2)) {\n\t\tif (polygonIntersect(polygon1, polygon2)) return 0;\n\t} else if (polygonIntersect(polygon2, polygon1)) return 0;\n\tlet dist = Infinity;\n\tfor (const ring1 of polygon1) for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) {\n\t\tconst p1 = ring1[l];\n\t\tconst p2 = ring1[i];\n\t\tfor (const ring2 of polygon2) for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\tconst q1 = ring2[k];\n\t\t\tconst q2 = ring2[j];\n\t\t\tif (segmentIntersectSegment(p1, p2, q1, q2)) return 0;\n\t\t\tdist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));\n\t\t}\n\t}\n\treturn dist;\n}\nfunction updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) {\n\tif (!rangeA) return;\n\tconst tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler);\n\tif (tempDist < miniDist) distQueue.push([\n\t\ttempDist,\n\t\trangeA,\n\t\t[0, 0]\n\t]);\n}\nfunction updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) {\n\tif (!range1 || !range2) return;\n\tconst tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler);\n\tif (tempDist < miniDist) distQueue.push([\n\t\ttempDist,\n\t\trange1,\n\t\trange2\n\t]);\n}\nfunction pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) {\n\tlet miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist);\n\tif (miniDist === 0) return miniDist;\n\tconst distQueue = new TinyQueue([[\n\t\t0,\n\t\t[0, points.length - 1],\n\t\t[0, 0]\n\t]], compareDistPair);\n\tconst polyBBox = getPolygonBBox(polygon);\n\twhile (distQueue.length > 0) {\n\t\tconst distPair = distQueue.pop();\n\t\tif (distPair[0] >= miniDist) continue;\n\t\tconst range = distPair[1];\n\t\tconst threshold = isLine ? MinLinePointsSize : MinPointsSize;\n\t\tif (getRangeSize(range) <= threshold) {\n\t\t\tif (!isRangeSafe(range, points.length)) return NaN;\n\t\t\tif (isLine) {\n\t\t\t\tconst tempDist = lineToPolygonDistance(points, range, polygon, ruler);\n\t\t\t\tif (isNaN(tempDist) || tempDist === 0) return tempDist;\n\t\t\t\tminiDist = Math.min(miniDist, tempDist);\n\t\t\t} else for (let i = range[0]; i <= range[1]; ++i) {\n\t\t\t\tconst tempDist = pointToPolygonDistance(points[i], polygon, ruler);\n\t\t\t\tminiDist = Math.min(miniDist, tempDist);\n\t\t\t\tif (miniDist === 0) return 0;\n\t\t\t}\n\t\t} else {\n\t\t\tconst newRangesA = splitRange(range, isLine);\n\t\t\tupdateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]);\n\t\t\tupdateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]);\n\t\t}\n\t}\n\treturn miniDist;\n}\nfunction pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) {\n\tlet miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0]));\n\tif (miniDist === 0) return miniDist;\n\tconst distQueue = new TinyQueue([[\n\t\t0,\n\t\t[0, pointSet1.length - 1],\n\t\t[0, pointSet2.length - 1]\n\t]], compareDistPair);\n\twhile (distQueue.length > 0) {\n\t\tconst distPair = distQueue.pop();\n\t\tif (distPair[0] >= miniDist) continue;\n\t\tconst rangeA = distPair[1];\n\t\tconst rangeB = distPair[2];\n\t\tconst threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize;\n\t\tconst threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize;\n\t\tif (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) {\n\t\t\tif (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) return NaN;\n\t\t\tlet tempDist;\n\t\t\tif (isLine1 && isLine2) {\n\t\t\t\ttempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler);\n\t\t\t\tminiDist = Math.min(miniDist, tempDist);\n\t\t\t} else if (isLine1 && !isLine2) {\n\t\t\t\tconst sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1);\n\t\t\t\tfor (let i = rangeB[0]; i <= rangeB[1]; ++i) {\n\t\t\t\t\ttempDist = pointToLineDistance(pointSet2[i], sublibe, ruler);\n\t\t\t\t\tminiDist = Math.min(miniDist, tempDist);\n\t\t\t\t\tif (miniDist === 0) return miniDist;\n\t\t\t\t}\n\t\t\t} else if (!isLine1 && isLine2) {\n\t\t\t\tconst sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1);\n\t\t\t\tfor (let i = rangeA[0]; i <= rangeA[1]; ++i) {\n\t\t\t\t\ttempDist = pointToLineDistance(pointSet1[i], sublibe, ruler);\n\t\t\t\t\tminiDist = Math.min(miniDist, tempDist);\n\t\t\t\t\tif (miniDist === 0) return miniDist;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler);\n\t\t\t\tminiDist = Math.min(miniDist, tempDist);\n\t\t\t}\n\t\t} else {\n\t\t\tconst newRangesA = splitRange(rangeA, isLine1);\n\t\t\tconst newRangesB = splitRange(rangeB, isLine2);\n\t\t\tupdateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]);\n\t\t\tupdateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]);\n\t\t\tupdateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]);\n\t\t\tupdateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]);\n\t\t}\n\t}\n\treturn miniDist;\n}\nfunction pointToGeometryDistance(ctx, geometries) {\n\tconst tilePoints = ctx.geometry();\n\tconst pointPosition = tilePoints.flat().map((p) => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));\n\tif (tilePoints.length === 0) return NaN;\n\tconst ruler = new CheapRuler(pointPosition[0][1]);\n\tlet dist = Infinity;\n\tfor (const geometry of geometries) {\n\t\tswitch (geometry.type) {\n\t\t\tcase \"Point\":\n\t\t\t\tdist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist));\n\t\t\t\tbreak;\n\t\t\tcase \"LineString\":\n\t\t\t\tdist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist));\n\t\t\t\tbreak;\n\t\t\tcase \"Polygon\": dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist));\n\t\t}\n\t\tif (dist === 0) return dist;\n\t}\n\treturn dist;\n}\nfunction lineStringToGeometryDistance(ctx, geometries) {\n\tconst tileLine = ctx.geometry();\n\tconst linePositions = tileLine.flat().map((p) => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));\n\tif (tileLine.length === 0) return NaN;\n\tconst ruler = new CheapRuler(linePositions[0][1]);\n\tlet dist = Infinity;\n\tfor (const geometry of geometries) {\n\t\tswitch (geometry.type) {\n\t\t\tcase \"Point\":\n\t\t\t\tdist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist));\n\t\t\t\tbreak;\n\t\t\tcase \"LineString\":\n\t\t\t\tdist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist));\n\t\t\t\tbreak;\n\t\t\tcase \"Polygon\": dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist));\n\t\t}\n\t\tif (dist === 0) return dist;\n\t}\n\treturn dist;\n}\nfunction polygonToGeometryDistance(ctx, geometries) {\n\tconst tilePolygon = ctx.geometry();\n\tif (tilePolygon.length === 0 || tilePolygon[0].length === 0) return NaN;\n\tconst polygons = classifyRings(tilePolygon, 0).map((polygon) => {\n\t\treturn polygon.map((ring) => {\n\t\t\treturn ring.map((p) => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));\n\t\t});\n\t});\n\tconst ruler = new CheapRuler(polygons[0][0][0][1]);\n\tlet dist = Infinity;\n\tfor (const geometry of geometries) for (const polygon of polygons) {\n\t\tswitch (geometry.type) {\n\t\t\tcase \"Point\":\n\t\t\t\tdist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist));\n\t\t\t\tbreak;\n\t\t\tcase \"LineString\":\n\t\t\t\tdist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist));\n\t\t\t\tbreak;\n\t\t\tcase \"Polygon\": dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist));\n\t\t}\n\t\tif (dist === 0) return dist;\n\t}\n\treturn dist;\n}\nfunction toSimpleGeometry(geometry) {\n\tif (geometry.type === \"MultiPolygon\") return geometry.coordinates.map((polygon) => {\n\t\treturn {\n\t\t\ttype: \"Polygon\",\n\t\t\tcoordinates: polygon\n\t\t};\n\t});\n\tif (geometry.type === \"MultiLineString\") return geometry.coordinates.map((lineString) => {\n\t\treturn {\n\t\t\ttype: \"LineString\",\n\t\t\tcoordinates: lineString\n\t\t};\n\t});\n\tif (geometry.type === \"MultiPoint\") return geometry.coordinates.map((point) => {\n\t\treturn {\n\t\t\ttype: \"Point\",\n\t\t\tcoordinates: point\n\t\t};\n\t});\n\treturn [geometry];\n}\nvar Distance = class Distance {\n\tconstructor(geojson, geometries) {\n\t\tthis.type = NumberType;\n\t\tthis.geojson = geojson;\n\t\tthis.geometries = geometries;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\t\tif (isValue(args[1])) {\n\t\t\tconst geojson = args[1];\n\t\t\tif (geojson.type === \"FeatureCollection\") return new Distance(geojson, geojson.features.map((feature) => toSimpleGeometry(feature.geometry)).flat());\n\t\t\telse if (geojson.type === \"Feature\") return new Distance(geojson, toSimpleGeometry(geojson.geometry));\n\t\t\telse if (\"type\" in geojson && \"coordinates\" in geojson) return new Distance(geojson, toSimpleGeometry(geojson));\n\t\t}\n\t\treturn context.error(\"'distance' expression requires valid geojson object that contains polygon geometry type.\");\n\t}\n\tevaluate(ctx) {\n\t\tif (ctx.geometry() != null && ctx.canonicalID() != null) {\n\t\t\tif (ctx.geometryType() === \"Point\") return pointToGeometryDistance(ctx, this.geometries);\n\t\t\telse if (ctx.geometryType() === \"LineString\") return lineStringToGeometryDistance(ctx, this.geometries);\n\t\t\telse if (ctx.geometryType() === \"Polygon\") return polygonToGeometryDistance(ctx, this.geometries);\n\t\t}\n\t\treturn NaN;\n\t}\n\teachChild() {}\n\toutputDefined() {\n\t\treturn true;\n\t}\n};\nexport { Distance };\n\n//# sourceMappingURL=distance.mjs.map", "import { ValueType, array } from \"../types.mjs\";\nimport { isValue, typeOf } from \"../values.mjs\";\nimport { Literal } from \"./literal.mjs\";\n// src/expression/definitions/semiliteral.ts\nvar Semiliteral = class Semiliteral {\n\tconstructor(arr) {\n\t\tlet elementType = null;\n\t\tfor (const expr of arr) if (!elementType) elementType = expr.type;\n\t\telse if (elementType === expr.type) continue;\n\t\telse {\n\t\t\telementType = ValueType;\n\t\t\tbreak;\n\t\t}\n\t\tthis.type = array(elementType ?? ValueType, arr.length);\n\t\tthis.arr = arr;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(`'semiliteral' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\t\tif (!isValue(args[1])) return context.error(`invalid value of type \"${typeof args[1]}\"`);\n\t\tconst value = args[1];\n\t\tconst type = typeOf(value);\n\t\tif (type.kind === \"array\") {\n\t\t\tconst arr = value;\n\t\t\tconst arrayContext = context.concat(1);\n\t\t\tconst parsed = [];\n\t\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\t\tconst item = arrayContext.parse(arr[i], i, ValueType);\n\t\t\t\tif (!item) return null;\n\t\t\t\tparsed.push(item);\n\t\t\t}\n\t\t\treturn new Semiliteral(parsed);\n\t\t} else return new Literal(type, value);\n\t}\n\tevaluate(ctx) {\n\t\treturn this.arr.map((arg) => arg.evaluate(ctx));\n\t}\n\teachChild(fn) {\n\t\tthis.arr.forEach(fn);\n\t}\n\toutputDefined() {\n\t\treturn this.arr.every((arg) => arg.outputDefined());\n\t}\n};\nexport { Semiliteral };\n\n//# sourceMappingURL=semiliteral.mjs.map", "import { ValueType } from \"../types.mjs\";\nimport { getOwn } from \"../../util/get_own.mjs\";\n// src/expression/definitions/global_state.ts\nvar GlobalState = class GlobalState {\n\tconstructor(key) {\n\t\tthis.key = key;\n\t\tthis.type = ValueType;\n\t}\n\tstatic parse(args, context) {\n\t\tif (args.length !== 2) return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);\n\t\tconst key = args[1];\n\t\tif (key === void 0 || key === null) return context.error(\"Global state property must be defined.\");\n\t\tif (typeof key !== \"string\") return context.error(`Global state property must be string, but found ${typeof args[1]} instead.`);\n\t\treturn new GlobalState(key);\n\t}\n\tevaluate(ctx) {\n\t\tconst globalState = ctx.globals?.globalState;\n\t\tif (!globalState || Object.keys(globalState).length === 0) return null;\n\t\treturn getOwn(globalState, this.key) ?? null;\n\t}\n\teachChild() {}\n\toutputDefined() {\n\t\treturn false;\n\t}\n};\nexport { GlobalState };\n\n//# sourceMappingURL=global_state.mjs.map", "import { Literal } from \"./literal.mjs\";\nimport { Assertion } from \"./assertion.mjs\";\nimport { Coercion } from \"./coercion.mjs\";\nimport { Let } from \"./let.mjs\";\nimport { Var } from \"./var.mjs\";\nimport { At } from \"./at.mjs\";\nimport { In } from \"./in.mjs\";\nimport { IndexOf } from \"./index_of.mjs\";\nimport { Match } from \"./match.mjs\";\nimport { Case } from \"./case.mjs\";\nimport { Slice } from \"./slice.mjs\";\nimport { Step } from \"./step.mjs\";\nimport { Interpolate } from \"./interpolate.mjs\";\nimport { Coalesce } from \"./coalesce.mjs\";\nimport { Equals, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, NotEquals } from \"./comparison.mjs\";\nimport { CollatorExpression } from \"./collator.mjs\";\nimport { NumberFormat } from \"./number_format.mjs\";\nimport { FormatExpression } from \"./format.mjs\";\nimport { ImageExpression } from \"./image.mjs\";\nimport { Length } from \"./length.mjs\";\nimport { Within } from \"./within.mjs\";\nimport { Distance } from \"./distance.mjs\";\nimport { Semiliteral } from \"./semiliteral.mjs\";\nimport { GlobalState } from \"./global_state.mjs\";\n// src/expression/definitions/index.ts\nconst expressions = {\n\t\"==\": Equals,\n\t\"!=\": NotEquals,\n\t\">\": GreaterThan,\n\t\"<\": LessThan,\n\t\">=\": GreaterThanOrEqual,\n\t\"<=\": LessThanOrEqual,\n\tarray: Assertion,\n\tat: At,\n\tboolean: Assertion,\n\tcase: Case,\n\tcoalesce: Coalesce,\n\tcollator: CollatorExpression,\n\tformat: FormatExpression,\n\timage: ImageExpression,\n\tin: In,\n\t\"index-of\": IndexOf,\n\tinterpolate: Interpolate,\n\t\"interpolate-hcl\": Interpolate,\n\t\"interpolate-lab\": Interpolate,\n\tlength: Length,\n\tlet: Let,\n\tliteral: Literal,\n\tmatch: Match,\n\tnumber: Assertion,\n\t\"number-format\": NumberFormat,\n\tobject: Assertion,\n\tsemiliteral: Semiliteral,\n\tslice: Slice,\n\tstep: Step,\n\tstring: Assertion,\n\t\"to-boolean\": Coercion,\n\t\"to-color\": Coercion,\n\t\"to-number\": Coercion,\n\t\"to-string\": Coercion,\n\tvar: Var,\n\twithin: Within,\n\tdistance: Distance,\n\t\"global-state\": GlobalState\n};\nexport { expressions };\n\n//# sourceMappingURL=index.mjs.map", "// src/expression/parsing_error.ts\nvar ExpressionParsingError = class extends Error {\n\tconstructor(key, message) {\n\t\tsuper(message);\n\t\tthis.message = message;\n\t\tthis.key = key;\n\t}\n};\nexport { ExpressionParsingError };\n\n//# sourceMappingURL=parsing_error.mjs.map", "// src/expression/scope.ts\n/**\n* Tracks `let` bindings during expression parsing.\n* @private\n*/\nvar Scope = class Scope {\n\tconstructor(parent, bindings = []) {\n\t\tthis.parent = parent;\n\t\tthis.bindings = {};\n\t\tfor (const [name, expression] of bindings) this.bindings[name] = expression;\n\t}\n\tconcat(bindings) {\n\t\treturn new Scope(this, bindings);\n\t}\n\tget(name) {\n\t\tif (this.bindings[name]) return this.bindings[name];\n\t\tif (this.parent) return this.parent.get(name);\n\t\tthrow new Error(`${name} not found in scope.`);\n\t}\n\thas(name) {\n\t\tif (this.bindings[name]) return true;\n\t\treturn this.parent ? this.parent.has(name) : false;\n\t}\n};\nexport { Scope };\n\n//# sourceMappingURL=scope.mjs.map", "import { ExpressionParsingError } from \"./parsing_error.mjs\";\nimport { Scope } from \"./scope.mjs\";\nimport { checkSubtype } from \"./types.mjs\";\nimport { Literal } from \"./definitions/literal.mjs\";\nimport { Assertion } from \"./definitions/assertion.mjs\";\nimport { Coercion } from \"./definitions/coercion.mjs\";\nimport { EvaluationContext } from \"./evaluation_context.mjs\";\n// src/expression/parsing_context.ts\n/**\n* State associated parsing at a given point in an expression tree.\n* @private\n*/\nvar ParsingContext = class ParsingContext {\n\tconstructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) {\n\t\tthis.registry = registry;\n\t\tthis.path = path;\n\t\tthis.key = path.map((part) => `[${part}]`).join(\"\");\n\t\tthis.scope = scope;\n\t\tthis.errors = errors;\n\t\tthis.expectedType = expectedType;\n\t\tthis._isConstant = isConstantFunc;\n\t}\n\t/**\n\t* @param expr the JSON expression to parse\n\t* @param index the optional argument index if this expression is an argument of a parent expression that's being parsed\n\t* @param options\n\t* @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\t* @private\n\t*/\n\tparse(expr, index, expectedType, bindings, options = {}) {\n\t\tif (index != null) return this.concat(index, expectedType, bindings)._parse(expr, options);\n\t\treturn this._parse(expr, options);\n\t}\n\t_parse(expr, options) {\n\t\tif (expr === null || typeof expr === \"string\" || typeof expr === \"boolean\" || typeof expr === \"number\") expr = [\"literal\", expr];\n\t\tconst key = this.key;\n\t\tfunction annotate(parsed, type, typeAnnotation) {\n\t\t\tif (typeAnnotation === \"assert\") return new Assertion(type, [parsed], key);\n\t\t\telse if (typeAnnotation === \"coerce\") return new Coercion(type, [parsed], key);\n\t\t\telse return parsed;\n\t\t}\n\t\tif (Array.isArray(expr)) {\n\t\t\tif (expr.length === 0) return this.error(\"Expected an array with at least one element. If you wanted a literal array, use [\\\"literal\\\", []].\");\n\t\t\tconst op = expr[0];\n\t\t\tif (typeof op !== \"string\") {\n\t\t\t\tthis.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use [\"literal\", [...]].`, 0);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst Expr = this.registry[op];\n\t\t\tif (Expr) {\n\t\t\t\tlet parsed = Expr.parse(expr, this);\n\t\t\t\tif (!parsed) return null;\n\t\t\t\tif (this.expectedType) {\n\t\t\t\t\tconst expected = this.expectedType;\n\t\t\t\t\tconst actual = parsed.type;\n\t\t\t\t\tif ((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\");\n\t\t\t\t\telse if (\"projectionDefinition\" === expected.kind && [\n\t\t\t\t\t\t\"string\",\n\t\t\t\t\t\t\"array\",\n\t\t\t\t\t\t\"value\"\n\t\t\t\t\t].includes(actual.kind) || [\n\t\t\t\t\t\t\"color\",\n\t\t\t\t\t\t\"formatted\",\n\t\t\t\t\t\t\"resolvedImage\"\n\t\t\t\t\t].includes(expected.kind) && [\"value\", \"string\"].includes(actual.kind) || [\"padding\", \"numberArray\"].includes(expected.kind) && [\n\t\t\t\t\t\t\"value\",\n\t\t\t\t\t\t\"number\",\n\t\t\t\t\t\t\"array\"\n\t\t\t\t\t].includes(actual.kind) || \"colorArray\" === expected.kind && [\n\t\t\t\t\t\t\"value\",\n\t\t\t\t\t\t\"string\",\n\t\t\t\t\t\t\"array\"\n\t\t\t\t\t].includes(actual.kind) || \"variableAnchorOffsetCollection\" === expected.kind && [\"value\", \"array\"].includes(actual.kind)) parsed = annotate(parsed, expected, options.typeAnnotation || \"coerce\");\n\t\t\t\t\telse if (this.checkSubtype(expected, actual)) return null;\n\t\t\t\t}\n\t\t\t\tif (!(parsed instanceof Literal) && parsed.type.kind !== \"resolvedImage\" && this._isConstant(parsed)) {\n\t\t\t\t\tconst ec = new EvaluationContext();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparsed = new Literal(parsed.type, parsed.evaluate(ec));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tthis.error(e.message);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t\treturn this.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n\t\t} else if (typeof expr === \"undefined\") return this.error(\"'undefined' value invalid. Use null instead.\");\n\t\telse if (typeof expr === \"object\") return this.error(\"Bare objects invalid. Use [\\\"literal\\\", {...}] instead.\");\n\t\telse return this.error(`Expected an array, but found ${typeof expr} instead.`);\n\t}\n\t/**\n\t* Returns a copy of this context suitable for parsing the subexpression at\n\t* index `index`, optionally appending to 'let' binding map.\n\t*\n\t* Note that `errors` property, intended for collecting errors while\n\t* parsing, is copied by reference rather than cloned.\n\t* @private\n\t*/\n\tconcat(index, expectedType, bindings) {\n\t\tconst path = typeof index === \"number\" ? this.path.concat(index) : this.path;\n\t\tconst scope = bindings ? this.scope.concat(bindings) : this.scope;\n\t\treturn new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors);\n\t}\n\t/**\n\t* Push a parsing (or type checking) error into the `this.errors`\n\t* @param error The message\n\t* @param keys Optionally specify the source of the error at a child\n\t* of the current expression at `this.key`.\n\t* @private\n\t*/\n\terror(error, ...keys) {\n\t\tconst key = `${this.key}${keys.map((k) => `[${k}]`).join(\"\")}`;\n\t\tthis.errors.push(new ExpressionParsingError(key, error));\n\t}\n\t/**\n\t* Returns null if `t` is a subtype of `expected`; otherwise returns an\n\t* error message and also pushes it to `this.errors`.\n\t* @param expected The expected type\n\t* @param t The actual type\n\t* @returns null if `t` is a subtype of `expected`; otherwise returns an error message\n\t*/\n\tcheckSubtype(expected, t) {\n\t\tconst error = checkSubtype(expected, t);\n\t\tif (error) this.error(error);\n\t\treturn error;\n\t}\n};\nexport { ParsingContext };\n\n//# sourceMappingURL=parsing_context.mjs.map", "import { BooleanType, CollatorType, ColorType, ErrorType, NumberType, ObjectType, StringType, ValueType, array, typeToString } from \"./types.mjs\";\nimport { Color } from \"./types/color.mjs\";\nimport { RuntimeError } from \"./runtime_error.mjs\";\nimport { typeOf, validateRGBA, valueToString } from \"./values.mjs\";\nimport { Literal } from \"./definitions/literal.mjs\";\nimport { Assertion } from \"./definitions/assertion.mjs\";\nimport { Coercion } from \"./definitions/coercion.mjs\";\nimport { ParsingContext } from \"./parsing_context.mjs\";\nimport { Var } from \"./definitions/var.mjs\";\nimport { CollatorExpression } from \"./definitions/collator.mjs\";\nimport { Within } from \"./definitions/within.mjs\";\nimport { Distance } from \"./definitions/distance.mjs\";\nimport { GlobalState } from \"./definitions/global_state.mjs\";\nimport { expressions } from \"./definitions/index.mjs\";\n// src/expression/compound_expression.ts\nvar CompoundExpression = class CompoundExpression {\n\tconstructor(name, type, evaluate, args, key) {\n\t\tthis.name = name;\n\t\tthis.type = type;\n\t\tthis._evaluate = evaluate;\n\t\tthis.args = args;\n\t\tthis.key = key;\n\t}\n\tevaluate(ctx) {\n\t\treturn this._evaluate(ctx, this.args, this.key);\n\t}\n\teachChild(fn) {\n\t\tthis.args.forEach(fn);\n\t}\n\toutputDefined() {\n\t\treturn false;\n\t}\n\tstatic parse(args, context) {\n\t\tconst op = args[0];\n\t\tconst definition = CompoundExpression.definitions[op];\n\t\tif (!definition) return context.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n\t\tconst type = Array.isArray(definition) ? definition[0] : definition.type;\n\t\tconst availableOverloads = Array.isArray(definition) ? [[definition[1], definition[2]]] : definition.overloads;\n\t\tconst overloads = availableOverloads.filter(([signature]) => !Array.isArray(signature) || signature.length === args.length - 1);\n\t\tlet signatureContext = null;\n\t\tfor (const [params, evaluate] of overloads) {\n\t\t\tsignatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope);\n\t\t\tconst parsedArgs = [];\n\t\t\tlet argParseFailed = false;\n\t\t\tfor (let i = 1; i < args.length; i++) {\n\t\t\t\tconst arg = args[i];\n\t\t\t\tconst expectedType = Array.isArray(params) ? params[i - 1] : params.type;\n\t\t\t\tconst parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);\n\t\t\t\tif (!parsed) {\n\t\t\t\t\targParseFailed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tparsedArgs.push(parsed);\n\t\t\t}\n\t\t\tif (argParseFailed) continue;\n\t\t\tif (Array.isArray(params)) {\n\t\t\t\tif (params.length !== parsedArgs.length) {\n\t\t\t\t\tsignatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (let i = 0; i < parsedArgs.length; i++) {\n\t\t\t\tconst expected = Array.isArray(params) ? params[i] : params.type;\n\t\t\t\tconst arg = parsedArgs[i];\n\t\t\t\tsignatureContext.concat(i + 1).checkSubtype(expected, arg.type);\n\t\t\t}\n\t\t\tif (signatureContext.errors.length === 0) return new CompoundExpression(op, type, evaluate, parsedArgs, context.key);\n\t\t}\n\t\tif (overloads.length === 1) context.errors.push(...signatureContext.errors);\n\t\telse {\n\t\t\tconst signatures = (overloads.length ? overloads : availableOverloads).map(([params]) => stringifySignature(params)).join(\" | \");\n\t\t\tconst actualTypes = [];\n\t\t\tfor (let i = 1; i < args.length; i++) {\n\t\t\t\tconst parsed = context.parse(args[i], 1 + actualTypes.length);\n\t\t\t\tif (!parsed) return null;\n\t\t\t\tactualTypes.push(typeToString(parsed.type));\n\t\t\t}\n\t\t\tcontext.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(\", \")}) instead.`);\n\t\t}\n\t\treturn null;\n\t}\n\tstatic register(registry, definitions) {\n\t\tCompoundExpression.definitions = definitions;\n\t\tfor (const name in definitions) registry[name] = CompoundExpression;\n\t}\n};\nfunction rgba(ctx, [r, g, b, a], key) {\n\tr = r.evaluate(ctx);\n\tg = g.evaluate(ctx);\n\tb = b.evaluate(ctx);\n\tconst alpha = a ? a.evaluate(ctx) : 1;\n\tconst error = validateRGBA(r, g, b, alpha);\n\tif (error) throw new RuntimeError(error, key);\n\treturn new Color(r / 255, g / 255, b / 255, alpha, false);\n}\nfunction has(key, obj) {\n\treturn key in obj && obj[key] !== void 0;\n}\nfunction get(key, obj) {\n\tconst v = obj[key];\n\treturn typeof v === \"undefined\" ? null : v;\n}\nfunction binarySearch(v, a, i, j) {\n\twhile (i <= j) {\n\t\tconst m = i + j >> 1;\n\t\tif (a[m] === v) return true;\n\t\tif (a[m] > v) j = m - 1;\n\t\telse i = m + 1;\n\t}\n\treturn false;\n}\nfunction varargs(type) {\n\treturn { type };\n}\nCompoundExpression.register(expressions, {\n\terror: [\n\t\tErrorType,\n\t\t[StringType],\n\t\t(ctx, [v], key) => {\n\t\t\tthrow new RuntimeError(v.evaluate(ctx), key);\n\t\t}\n\t],\n\ttypeof: [\n\t\tStringType,\n\t\t[ValueType],\n\t\t(ctx, [v]) => typeToString(typeOf(v.evaluate(ctx)))\n\t],\n\t\"to-rgba\": [\n\t\tarray(NumberType, 4),\n\t\t[ColorType],\n\t\t(ctx, [v]) => {\n\t\t\tconst [r, g, b, a] = v.evaluate(ctx).rgb;\n\t\t\treturn [\n\t\t\t\tr * 255,\n\t\t\t\tg * 255,\n\t\t\t\tb * 255,\n\t\t\t\ta\n\t\t\t];\n\t\t}\n\t],\n\trgb: [\n\t\tColorType,\n\t\t[\n\t\t\tNumberType,\n\t\t\tNumberType,\n\t\t\tNumberType\n\t\t],\n\t\trgba\n\t],\n\trgba: [\n\t\tColorType,\n\t\t[\n\t\t\tNumberType,\n\t\t\tNumberType,\n\t\t\tNumberType,\n\t\t\tNumberType\n\t\t],\n\t\trgba\n\t],\n\thas: {\n\t\ttype: BooleanType,\n\t\toverloads: [[[StringType], (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())], [[StringType, ObjectType], (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))]]\n\t},\n\tget: {\n\t\ttype: ValueType,\n\t\toverloads: [[[StringType], (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())], [[StringType, ObjectType], (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))]]\n\t},\n\t\"feature-state\": [\n\t\tValueType,\n\t\t[StringType],\n\t\t(ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})\n\t],\n\tproperties: [\n\t\tObjectType,\n\t\t[],\n\t\t(ctx) => ctx.properties()\n\t],\n\t\"geometry-type\": [\n\t\tStringType,\n\t\t[],\n\t\t(ctx) => ctx.geometryType()\n\t],\n\tid: [\n\t\tValueType,\n\t\t[],\n\t\t(ctx) => ctx.id()\n\t],\n\tzoom: [\n\t\tNumberType,\n\t\t[],\n\t\t(ctx) => ctx.globals.zoom\n\t],\n\t\"heatmap-density\": [\n\t\tNumberType,\n\t\t[],\n\t\t(ctx) => ctx.globals.heatmapDensity || 0\n\t],\n\televation: [\n\t\tNumberType,\n\t\t[],\n\t\t(ctx) => ctx.globals.elevation || 0\n\t],\n\t\"line-progress\": [\n\t\tNumberType,\n\t\t[],\n\t\t(ctx) => ctx.globals.lineProgress || 0\n\t],\n\taccumulated: [\n\t\tValueType,\n\t\t[],\n\t\t(ctx) => ctx.globals.accumulated === void 0 ? null : ctx.globals.accumulated\n\t],\n\t\"+\": [\n\t\tNumberType,\n\t\tvarargs(NumberType),\n\t\t(ctx, args) => {\n\t\t\tlet result = 0;\n\t\t\tfor (const arg of args) result += arg.evaluate(ctx);\n\t\t\treturn result;\n\t\t}\n\t],\n\t\"*\": [\n\t\tNumberType,\n\t\tvarargs(NumberType),\n\t\t(ctx, args) => {\n\t\t\tlet result = 1;\n\t\t\tfor (const arg of args) result *= arg.evaluate(ctx);\n\t\t\treturn result;\n\t\t}\n\t],\n\t\"-\": {\n\t\ttype: NumberType,\n\t\toverloads: [[[NumberType, NumberType], (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)], [[NumberType], (ctx, [a]) => -a.evaluate(ctx)]]\n\t},\n\t\"/\": [\n\t\tNumberType,\n\t\t[NumberType, NumberType],\n\t\t(ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)\n\t],\n\t\"%\": [\n\t\tNumberType,\n\t\t[NumberType, NumberType],\n\t\t(ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)\n\t],\n\tln2: [\n\t\tNumberType,\n\t\t[],\n\t\t() => Math.LN2\n\t],\n\tpi: [\n\t\tNumberType,\n\t\t[],\n\t\t() => Math.PI\n\t],\n\te: [\n\t\tNumberType,\n\t\t[],\n\t\t() => Math.E\n\t],\n\t\"^\": [\n\t\tNumberType,\n\t\t[NumberType, NumberType],\n\t\t(ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))\n\t],\n\tsqrt: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [x]) => Math.sqrt(x.evaluate(ctx))\n\t],\n\tlog10: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10\n\t],\n\tln: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.log(n.evaluate(ctx))\n\t],\n\tlog2: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2\n\t],\n\tsin: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.sin(n.evaluate(ctx))\n\t],\n\tcos: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.cos(n.evaluate(ctx))\n\t],\n\ttan: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.tan(n.evaluate(ctx))\n\t],\n\tasin: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.asin(n.evaluate(ctx))\n\t],\n\tacos: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.acos(n.evaluate(ctx))\n\t],\n\tatan: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.atan(n.evaluate(ctx))\n\t],\n\tmin: [\n\t\tNumberType,\n\t\tvarargs(NumberType),\n\t\t(ctx, args) => Math.min(...args.map((arg) => arg.evaluate(ctx)))\n\t],\n\tmax: [\n\t\tNumberType,\n\t\tvarargs(NumberType),\n\t\t(ctx, args) => Math.max(...args.map((arg) => arg.evaluate(ctx)))\n\t],\n\tabs: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.abs(n.evaluate(ctx))\n\t],\n\tround: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => {\n\t\t\tconst v = n.evaluate(ctx);\n\t\t\treturn v < 0 ? -Math.round(-v) : Math.round(v);\n\t\t}\n\t],\n\tfloor: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.floor(n.evaluate(ctx))\n\t],\n\tceil: [\n\t\tNumberType,\n\t\t[NumberType],\n\t\t(ctx, [n]) => Math.ceil(n.evaluate(ctx))\n\t],\n\t\"filter-==\": [\n\t\tBooleanType,\n\t\t[StringType, ValueType],\n\t\t(ctx, [k, v]) => ctx.properties()[k.value] === v.value\n\t],\n\t\"filter-id-==\": [\n\t\tBooleanType,\n\t\t[ValueType],\n\t\t(ctx, [v]) => ctx.id() === v.value\n\t],\n\t\"filter-type-==\": [\n\t\tBooleanType,\n\t\t[StringType],\n\t\t(ctx, [v]) => ctx.geometryType() === v.value\n\t],\n\t\"filter-<\": [\n\t\tBooleanType,\n\t\t[StringType, ValueType],\n\t\t(ctx, [k, v]) => {\n\t\t\tconst a = ctx.properties()[k.value];\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a < b;\n\t\t}\n\t],\n\t\"filter-id-<\": [\n\t\tBooleanType,\n\t\t[ValueType],\n\t\t(ctx, [v]) => {\n\t\t\tconst a = ctx.id();\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a < b;\n\t\t}\n\t],\n\t\"filter->\": [\n\t\tBooleanType,\n\t\t[StringType, ValueType],\n\t\t(ctx, [k, v]) => {\n\t\t\tconst a = ctx.properties()[k.value];\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a > b;\n\t\t}\n\t],\n\t\"filter-id->\": [\n\t\tBooleanType,\n\t\t[ValueType],\n\t\t(ctx, [v]) => {\n\t\t\tconst a = ctx.id();\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a > b;\n\t\t}\n\t],\n\t\"filter-<=\": [\n\t\tBooleanType,\n\t\t[StringType, ValueType],\n\t\t(ctx, [k, v]) => {\n\t\t\tconst a = ctx.properties()[k.value];\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a <= b;\n\t\t}\n\t],\n\t\"filter-id-<=\": [\n\t\tBooleanType,\n\t\t[ValueType],\n\t\t(ctx, [v]) => {\n\t\t\tconst a = ctx.id();\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a <= b;\n\t\t}\n\t],\n\t\"filter->=\": [\n\t\tBooleanType,\n\t\t[StringType, ValueType],\n\t\t(ctx, [k, v]) => {\n\t\t\tconst a = ctx.properties()[k.value];\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a >= b;\n\t\t}\n\t],\n\t\"filter-id->=\": [\n\t\tBooleanType,\n\t\t[ValueType],\n\t\t(ctx, [v]) => {\n\t\t\tconst a = ctx.id();\n\t\t\tconst b = v.value;\n\t\t\treturn typeof a === typeof b && a >= b;\n\t\t}\n\t],\n\t\"filter-has\": [\n\t\tBooleanType,\n\t\t[ValueType],\n\t\t(ctx, [k]) => {\n\t\t\tconst key = k.value;\n\t\t\tconst props = ctx.properties();\n\t\t\treturn key in props && props[key] !== void 0;\n\t\t}\n\t],\n\t\"filter-has-id\": [\n\t\tBooleanType,\n\t\t[],\n\t\t(ctx) => ctx.id() !== null && ctx.id() !== void 0\n\t],\n\t\"filter-type-in\": [\n\t\tBooleanType,\n\t\t[array(StringType)],\n\t\t(ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0\n\t],\n\t\"filter-id-in\": [\n\t\tBooleanType,\n\t\t[array(ValueType)],\n\t\t(ctx, [v]) => v.value.indexOf(ctx.id()) >= 0\n\t],\n\t\"filter-in-small\": [\n\t\tBooleanType,\n\t\t[StringType, array(ValueType)],\n\t\t(ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0\n\t],\n\t\"filter-in-large\": [\n\t\tBooleanType,\n\t\t[StringType, array(ValueType)],\n\t\t(ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1)\n\t],\n\tall: {\n\t\ttype: BooleanType,\n\t\toverloads: [[[BooleanType, BooleanType], (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)], [varargs(BooleanType), (ctx, args) => {\n\t\t\tfor (const arg of args) if (!arg.evaluate(ctx)) return false;\n\t\t\treturn true;\n\t\t}]]\n\t},\n\tany: {\n\t\ttype: BooleanType,\n\t\toverloads: [[[BooleanType, BooleanType], (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)], [varargs(BooleanType), (ctx, args) => {\n\t\t\tfor (const arg of args) if (arg.evaluate(ctx)) return true;\n\t\t\treturn false;\n\t\t}]]\n\t},\n\t\"!\": [\n\t\tBooleanType,\n\t\t[BooleanType],\n\t\t(ctx, [b]) => !b.evaluate(ctx)\n\t],\n\t\"is-supported-script\": [\n\t\tBooleanType,\n\t\t[StringType],\n\t\t(ctx, [s]) => {\n\t\t\tconst isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;\n\t\t\tif (isSupportedScript) return isSupportedScript(s.evaluate(ctx));\n\t\t\treturn true;\n\t\t}\n\t],\n\tupcase: [\n\t\tStringType,\n\t\t[StringType],\n\t\t(ctx, [s]) => s.evaluate(ctx).toUpperCase()\n\t],\n\tdowncase: [\n\t\tStringType,\n\t\t[StringType],\n\t\t(ctx, [s]) => s.evaluate(ctx).toLowerCase()\n\t],\n\tconcat: [\n\t\tStringType,\n\t\tvarargs(ValueType),\n\t\t(ctx, args) => args.map((arg) => valueToString(arg.evaluate(ctx))).join(\"\")\n\t],\n\tsplit: [\n\t\tarray(StringType),\n\t\t[StringType, StringType],\n\t\t(ctx, [s, delim]) => s.evaluate(ctx).split(delim.evaluate(ctx))\n\t],\n\tjoin: [\n\t\tStringType,\n\t\t[array(StringType), StringType],\n\t\t(ctx, [arr, delim]) => arr.evaluate(ctx).join(delim.evaluate(ctx))\n\t],\n\t\"resolved-locale\": [\n\t\tStringType,\n\t\t[CollatorType],\n\t\t(ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()\n\t]\n});\nfunction stringifySignature(signature) {\n\tif (Array.isArray(signature)) return `(${signature.map(typeToString).join(\", \")})`;\n\telse return `(${typeToString(signature.type)}...)`;\n}\nfunction isExpressionConstant(expression) {\n\tif (expression instanceof Var) return isExpressionConstant(expression.boundExpression);\n\telse if (expression instanceof CompoundExpression && expression.name === \"error\") return false;\n\telse if (expression instanceof CollatorExpression) return false;\n\telse if (expression instanceof Within) return false;\n\telse if (expression instanceof Distance) return false;\n\telse if (expression instanceof GlobalState) return false;\n\tconst isTypeAnnotation = expression instanceof Coercion || expression instanceof Assertion;\n\tlet childrenConstant = true;\n\texpression.eachChild((child) => {\n\t\tif (isTypeAnnotation) childrenConstant = childrenConstant && isExpressionConstant(child);\n\t\telse childrenConstant = childrenConstant && child instanceof Literal;\n\t});\n\tif (!childrenConstant) return false;\n\treturn isFeatureConstant(expression) && isGlobalPropertyConstant(expression, [\n\t\t\"zoom\",\n\t\t\"heatmap-density\",\n\t\t\"elevation\",\n\t\t\"line-progress\",\n\t\t\"accumulated\",\n\t\t\"is-supported-script\"\n\t]);\n}\nfunction isFeatureConstant(e) {\n\tif (e instanceof CompoundExpression) {\n\t\tif (e.name === \"get\" && e.args.length === 1) return false;\n\t\telse if (e.name === \"feature-state\") return false;\n\t\telse if (e.name === \"has\" && e.args.length === 1) return false;\n\t\telse if (e.name === \"properties\" || e.name === \"geometry-type\" || e.name === \"id\") return false;\n\t\telse if (/^filter-/.test(e.name)) return false;\n\t}\n\tif (e instanceof Within) return false;\n\tif (e instanceof Distance) return false;\n\tlet result = true;\n\te.eachChild((arg) => {\n\t\tif (result && !isFeatureConstant(arg)) result = false;\n\t});\n\treturn result;\n}\nfunction isStateConstant(e) {\n\tif (e instanceof CompoundExpression) {\n\t\tif (e.name === \"feature-state\") return false;\n\t}\n\tlet result = true;\n\te.eachChild((arg) => {\n\t\tif (result && !isStateConstant(arg)) result = false;\n\t});\n\treturn result;\n}\nfunction isGlobalPropertyConstant(e, properties) {\n\tif (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) return false;\n\tlet result = true;\n\te.eachChild((arg) => {\n\t\tif (result && !isGlobalPropertyConstant(arg, properties)) result = false;\n\t});\n\treturn result;\n}\nexport { CompoundExpression, isExpressionConstant, isFeatureConstant, isGlobalPropertyConstant, isStateConstant };\n\n//# sourceMappingURL=compound_expression.mjs.map", "// src/util/properties.ts\nfunction supportsPropertyExpression(spec) {\n\treturn spec[\"property-type\"] === \"data-driven\" || spec[\"property-type\"] === \"cross-faded-data-driven\";\n}\nfunction supportsZoomExpression(spec) {\n\treturn !!spec.expression && spec.expression.parameters.indexOf(\"zoom\") > -1;\n}\nfunction supportsInterpolation(spec) {\n\treturn !!spec.expression && spec.expression.interpolated;\n}\n/**\n* Matches a `<property>-transition` key and captures the property it belongs to.\n*/\nconst transitionPropertyRegExp = /^(.*)-transition$/;\nexport { supportsInterpolation, supportsPropertyExpression, supportsZoomExpression, transitionPropertyRegExp };\n\n//# sourceMappingURL=properties.mjs.map", "// src/util/extend.ts\nfunction extendBy(output, ...inputs) {\n\tfor (const input of inputs) for (const k in input) output[k] = input[k];\n\treturn output;\n}\nexport { extendBy };\n\n//# sourceMappingURL=extend.mjs.map", "// src/util/get_type.ts\nfunction getType(val) {\n\tif (val instanceof Number) return \"number\";\n\telse if (val instanceof String) return \"string\";\n\telse if (val instanceof Boolean) return \"boolean\";\n\telse if (Array.isArray(val)) return \"array\";\n\telse if (val === null) return \"null\";\n\telse return typeof val;\n}\nexport { getType };\n\n//# sourceMappingURL=get_type.mjs.map", "import { ObjectType } from \"../expression/types.mjs\";\nimport { Color, isSupportedInterpolationColorSpace } from \"../expression/types/color.mjs\";\nimport { Formatted } from \"../expression/types/formatted.mjs\";\nimport { Padding } from \"../expression/types/padding.mjs\";\nimport { NumberArray } from \"../expression/types/number_array.mjs\";\nimport { ColorArray } from \"../expression/types/color_array.mjs\";\nimport { ResolvedImage } from \"../expression/types/resolved_image.mjs\";\nimport { typeOf } from \"../expression/values.mjs\";\nimport { findStopLessThanOrEqualTo } from \"../expression/stops.mjs\";\nimport { Interpolate, interpolateFactory } from \"../expression/definitions/interpolate.mjs\";\nimport { supportsInterpolation } from \"../util/properties.mjs\";\nimport { extendBy } from \"../util/extend.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/function/index.ts\nfunction isFunction(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) && typeOf(value) === ObjectType;\n}\nfunction identityFunction(x) {\n\treturn x;\n}\nfunction getParseFunction(propertySpec) {\n\tswitch (propertySpec.type) {\n\t\tcase \"color\": return Color.parse;\n\t\tcase \"padding\": return Padding.parse;\n\t\tcase \"numberArray\": return NumberArray.parse;\n\t\tcase \"colorArray\": return ColorArray.parse;\n\t\tdefault: return null;\n\t}\n}\nfunction getInnerFunction(type) {\n\tswitch (type) {\n\t\tcase \"exponential\": return evaluateExponentialFunction;\n\t\tcase \"interval\": return evaluateIntervalFunction;\n\t\tcase \"categorical\": return evaluateCategoricalFunction;\n\t\tcase \"identity\": return evaluateIdentityFunction;\n\t\tdefault: throw new Error(`Unknown function type \"${type}\"`);\n\t}\n}\nfunction createFunction(parameters, propertySpec) {\n\tconst zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === \"object\";\n\tconst featureDependent = zoomAndFeatureDependent || parameters.property !== void 0;\n\tconst zoomDependent = zoomAndFeatureDependent || !featureDependent;\n\tconst type = parameters.type || (supportsInterpolation(propertySpec) ? \"exponential\" : \"interval\");\n\tconst parseFn = getParseFunction(propertySpec);\n\tif (parseFn) {\n\t\tparameters = extendBy({}, parameters);\n\t\tif (parameters.stops) parameters.stops = parameters.stops.map((stop) => {\n\t\t\treturn [stop[0], parseFn(stop[1])];\n\t\t});\n\t\tif (parameters.default) parameters.default = parseFn(parameters.default);\n\t\telse parameters.default = parseFn(propertySpec.default);\n\t}\n\tif (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) throw new Error(`Unknown color space: \"${parameters.colorSpace}\"`);\n\tconst innerFun = getInnerFunction(type);\n\tlet hashedStops;\n\tlet categoricalKeyType;\n\tif (type === \"categorical\") {\n\t\thashedStops = Object.create(null);\n\t\tfor (const stop of parameters.stops) hashedStops[stop[0]] = stop[1];\n\t\tcategoricalKeyType = typeof parameters.stops[0][0];\n\t}\n\tif (zoomAndFeatureDependent) {\n\t\tconst featureFunctions = {};\n\t\tconst zoomStops = [];\n\t\tfor (let s = 0; s < parameters.stops.length; s++) {\n\t\t\tconst stop = parameters.stops[s];\n\t\t\tconst zoom = stop[0].zoom;\n\t\t\tif (featureFunctions[zoom] === void 0) {\n\t\t\t\tfeatureFunctions[zoom] = {\n\t\t\t\t\tzoom,\n\t\t\t\t\ttype: parameters.type,\n\t\t\t\t\tproperty: parameters.property,\n\t\t\t\t\tdefault: parameters.default,\n\t\t\t\t\tstops: []\n\t\t\t\t};\n\t\t\t\tzoomStops.push(zoom);\n\t\t\t}\n\t\t\tfeatureFunctions[zoom].stops.push([stop[0].value, stop[1]]);\n\t\t}\n\t\tconst featureFunctionStops = [];\n\t\tfor (const z of zoomStops) featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]);\n\t\tconst interpolationType = { name: \"linear\" };\n\t\treturn {\n\t\t\tkind: \"composite\",\n\t\t\tinterpolationType,\n\t\t\tinterpolationFactor: Interpolate.interpolationFactor.bind(void 0, interpolationType),\n\t\t\tzoomStops: featureFunctionStops.map((s) => s[0]),\n\t\t\tevaluate({ zoom }, properties) {\n\t\t\t\treturn evaluateExponentialFunction({\n\t\t\t\t\tstops: featureFunctionStops,\n\t\t\t\t\tbase: parameters.base\n\t\t\t\t}, propertySpec, zoom).evaluate(zoom, properties);\n\t\t\t}\n\t\t};\n\t} else if (zoomDependent) {\n\t\tconst interpolationType = type === \"exponential\" ? {\n\t\t\tname: \"exponential\",\n\t\t\tbase: parameters.base !== void 0 ? parameters.base : 1\n\t\t} : null;\n\t\treturn {\n\t\t\tkind: \"camera\",\n\t\t\tinterpolationType,\n\t\t\tinterpolationFactor: Interpolate.interpolationFactor.bind(void 0, interpolationType),\n\t\t\tzoomStops: parameters.stops.map((s) => s[0]),\n\t\t\tevaluate: ({ zoom }) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType)\n\t\t};\n\t} else return {\n\t\tkind: \"source\",\n\t\tevaluate(_, feature) {\n\t\t\tconst value = feature && feature.properties ? feature.properties[parameters.property] : void 0;\n\t\t\tif (value === void 0) return coalesce(parameters.default, propertySpec.default);\n\t\t\treturn innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);\n\t\t}\n\t};\n}\nfunction coalesce(a, b, c) {\n\tif (a !== void 0) return a;\n\tif (b !== void 0) return b;\n\tif (c !== void 0) return c;\n}\nfunction evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {\n\treturn coalesce(typeof input === keyType ? hashedStops[input] : void 0, parameters.default, propertySpec.default);\n}\nfunction evaluateIntervalFunction(parameters, propertySpec, input) {\n\tif (getType(input) !== \"number\") return coalesce(parameters.default, propertySpec.default);\n\tconst n = parameters.stops.length;\n\tif (n === 1) return parameters.stops[0][1];\n\tif (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n\tif (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\tconst index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input, \"\");\n\treturn parameters.stops[index][1];\n}\nfunction evaluateExponentialFunction(parameters, propertySpec, input) {\n\tconst base = parameters.base !== void 0 ? parameters.base : 1;\n\tif (getType(input) !== \"number\") return coalesce(parameters.default, propertySpec.default);\n\tconst n = parameters.stops.length;\n\tif (n === 1) return parameters.stops[0][1];\n\tif (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n\tif (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\tconst index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input, \"\");\n\tconst t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]);\n\tconst outputLower = parameters.stops[index][1];\n\tconst outputUpper = parameters.stops[index + 1][1];\n\tconst interp = interpolateFactory[propertySpec.type] || identityFunction;\n\tif (typeof outputLower.evaluate === \"function\") return { evaluate(...args) {\n\t\tconst evaluatedLower = outputLower.evaluate.apply(void 0, args);\n\t\tconst evaluatedUpper = outputUpper.evaluate.apply(void 0, args);\n\t\tif (evaluatedLower === void 0 || evaluatedUpper === void 0) return;\n\t\treturn interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace);\n\t} };\n\treturn interp(outputLower, outputUpper, t, parameters.colorSpace);\n}\nfunction evaluateIdentityFunction(parameters, propertySpec, input) {\n\tswitch (propertySpec.type) {\n\t\tcase \"color\":\n\t\t\tinput = Color.parse(input);\n\t\t\tbreak;\n\t\tcase \"formatted\":\n\t\t\tinput = Formatted.fromString(input.toString());\n\t\t\tbreak;\n\t\tcase \"resolvedImage\":\n\t\t\tinput = ResolvedImage.fromString(input.toString());\n\t\t\tbreak;\n\t\tcase \"padding\":\n\t\t\tinput = Padding.parse(input);\n\t\t\tbreak;\n\t\tcase \"colorArray\":\n\t\t\tinput = ColorArray.parse(input);\n\t\t\tbreak;\n\t\tcase \"numberArray\":\n\t\t\tinput = NumberArray.parse(input);\n\t\t\tbreak;\n\t\tdefault: if (getType(input) !== propertySpec.type && (propertySpec.type !== \"enum\" || !propertySpec.values[input])) input = void 0;\n\t}\n\treturn coalesce(input, parameters.default, propertySpec.default);\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\tconst difference = upperValue - lowerValue;\n\tconst progress = input - lowerValue;\n\tif (difference === 0) return 0;\n\telse if (base === 1) return progress / difference;\n\telse return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n}\nexport { createFunction, isFunction };\n\n//# sourceMappingURL=index.mjs.map", "// src/util/result.ts\nfunction success(value) {\n\treturn {\n\t\tresult: \"success\",\n\t\tvalue\n\t};\n}\nfunction error(value) {\n\treturn {\n\t\tresult: \"error\",\n\t\tvalue\n\t};\n}\nexport { error, success };\n\n//# sourceMappingURL=result.mjs.map", "import { ExpressionParsingError } from \"./parsing_error.mjs\";\nimport { BooleanType, ColorArrayType, ColorType, FormattedType, NumberArrayType, NumberType, PaddingType, ProjectionDefinitionType, ResolvedImageType, StringType, ValueType, VariableAnchorOffsetCollectionType, array } from \"./types.mjs\";\nimport { Color } from \"./types/color.mjs\";\nimport { Padding } from \"./types/padding.mjs\";\nimport { NumberArray } from \"./types/number_array.mjs\";\nimport { ColorArray } from \"./types/color_array.mjs\";\nimport { RuntimeError } from \"./runtime_error.mjs\";\nimport { VariableAnchorOffsetCollection } from \"./types/variable_anchor_offset_collection.mjs\";\nimport { ProjectionDefinition } from \"./types/projection_definition.mjs\";\nimport { EvaluationContext } from \"./evaluation_context.mjs\";\nimport { ParsingContext } from \"./parsing_context.mjs\";\nimport { Let } from \"./definitions/let.mjs\";\nimport { Step } from \"./definitions/step.mjs\";\nimport { Interpolate } from \"./definitions/interpolate.mjs\";\nimport { Coalesce } from \"./definitions/coalesce.mjs\";\nimport { GlobalState } from \"./definitions/global_state.mjs\";\nimport { expressions } from \"./definitions/index.mjs\";\nimport { CompoundExpression, isExpressionConstant, isFeatureConstant, isGlobalPropertyConstant, isStateConstant } from \"./compound_expression.mjs\";\nimport { error, success } from \"../util/result.mjs\";\nimport { supportsInterpolation, supportsPropertyExpression, supportsZoomExpression } from \"../util/properties.mjs\";\nimport { createFunction, isFunction } from \"../function/index.mjs\";\n// src/expression/index.ts\nvar StyleExpression = class {\n\tconstructor(expression, rootKey, propertySpec, globalState) {\n\t\tthis.expression = expression;\n\t\tthis._warningHistory = {};\n\t\tthis._evaluator = new EvaluationContext();\n\t\tthis._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;\n\t\tthis._enumValues = propertySpec && propertySpec.type === \"enum\" ? propertySpec.values : null;\n\t\tthis._globalState = globalState;\n\t\tthis._rootKey = rootKey;\n\t}\n\tevaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {\n\t\tif (this._globalState) globals = addGlobalState(globals, this._globalState);\n\t\tthis._evaluator.globals = globals;\n\t\tthis._evaluator.feature = feature;\n\t\tthis._evaluator.featureState = featureState;\n\t\tthis._evaluator.canonical = canonical;\n\t\tthis._evaluator.availableImages = availableImages || null;\n\t\tthis._evaluator.formattedSection = formattedSection;\n\t\treturn this.expression.evaluate(this._evaluator);\n\t}\n\tevaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {\n\t\tif (this._globalState) globals = addGlobalState(globals, this._globalState);\n\t\tthis._evaluator.globals = globals;\n\t\tthis._evaluator.feature = feature || null;\n\t\tthis._evaluator.featureState = featureState || null;\n\t\tthis._evaluator.canonical = canonical;\n\t\tthis._evaluator.availableImages = availableImages || null;\n\t\tthis._evaluator.formattedSection = formattedSection || null;\n\t\ttry {\n\t\t\tconst val = this.expression.evaluate(this._evaluator);\n\t\t\tif (val === null || val === void 0 || typeof val === \"number\" && val !== val) return this._defaultValue;\n\t\t\tif (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.`, \"\");\n\t\t\treturn val;\n\t\t} catch (e) {\n\t\t\tconst path = e instanceof RuntimeError ? e.path : \"\";\n\t\t\tconst dedupKey = `${path}|${e.message}`;\n\t\t\tif (!this._warningHistory[dedupKey]) {\n\t\t\t\tthis._warningHistory[dedupKey] = true;\n\t\t\t\tif (typeof console !== \"undefined\") console.warn(formatRuntimeWarning(this._rootKey, path, e.message, this._defaultValue));\n\t\t\t}\n\t\t\treturn this._defaultValue;\n\t\t}\n\t}\n};\n/**\n* Builds the warning logged when an expression or legacy function fails at\n* evaluation: a `rootKey + index path` location prefix, plus the fallback\n* value being used.\n* @param rootKey Caller-supplied location of the expression in the style JSON\n* @param path Index path of the throwing sub-expression ('' for the root)\n* @param message The error message from the failed evaluation\n* @param defaultValue The value being fallen back to\n* @returns The formatted warning string\n*/\nfunction formatRuntimeWarning(rootKey, path, message, defaultValue) {\n\treturn `${rootKey}${path}: ${message}${defaultValue == null ? \"\" : ` Falling back to ${String(defaultValue)}.`}`;\n}\n/**\n* Rejects a missing or empty root key. The location prefix is what makes\n* runtime warnings actionable, so callers must always supply one; failing\n* here surfaces the programmer error at style load instead of producing\n* unattributable warnings at render time.\n* @param rootKey The root key to check\n*/\nfunction assertRootKey(rootKey) {\n\tif (!rootKey) throw new Error(\"rootKey must identify the location of the expression in the style JSON, e.g. \\\"layers[3].paint.line-width\\\".\");\n}\nfunction isExpression(expression) {\n\treturn Array.isArray(expression) && expression.length > 0 && typeof expression[0] === \"string\" && expression[0] in expressions;\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*/\nfunction createExpression(expression, rootKey, propertySpec, globalState) {\n\tassertRootKey(rootKey);\n\tconst parser = new ParsingContext(expressions, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : void 0);\n\tconst parsed = parser.parse(expression, void 0, void 0, void 0, propertySpec && propertySpec.type === \"string\" ? { typeAnnotation: \"coerce\" } : void 0);\n\tif (!parsed) return error(parser.errors);\n\treturn success(new StyleExpression(parsed, rootKey, propertySpec, globalState));\n}\nvar ZoomConstantExpression = class {\n\tconstructor(kind, expression, globalState) {\n\t\tthis.kind = kind;\n\t\tthis._styleExpression = expression;\n\t\tthis.isStateDependent = kind !== \"constant\" && !isStateConstant(expression.expression);\n\t\tthis.globalStateRefs = findGlobalStateRefs(expression.expression);\n\t\tthis._globalState = globalState;\n\t}\n\tevaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {\n\t\tif (this._globalState) globals = addGlobalState(globals, this._globalState);\n\t\treturn this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n\t}\n\tevaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {\n\t\tif (this._globalState) globals = addGlobalState(globals, this._globalState);\n\t\treturn this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n\t}\n};\nvar ZoomDependentExpression = class {\n\tconstructor(kind, expression, zoomStops, interpolationType, globalState) {\n\t\tthis.kind = kind;\n\t\tthis.zoomStops = zoomStops;\n\t\tthis._styleExpression = expression;\n\t\tthis.isStateDependent = kind !== \"camera\" && !isStateConstant(expression.expression);\n\t\tthis.globalStateRefs = findGlobalStateRefs(expression.expression);\n\t\tthis.interpolationType = interpolationType;\n\t\tthis._globalState = globalState;\n\t}\n\tevaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {\n\t\tif (this._globalState) globals = addGlobalState(globals, this._globalState);\n\t\treturn this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n\t}\n\tevaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {\n\t\tif (this._globalState) globals = addGlobalState(globals, this._globalState);\n\t\treturn this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n\t}\n\tinterpolationFactor(input, lower, upper) {\n\t\tif (this.interpolationType) return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);\n\t\telse return 0;\n\t}\n};\nfunction isZoomExpression(expression) {\n\treturn expression._styleExpression !== void 0;\n}\nfunction createPropertyExpression(expressionInput, rootKey, propertySpec, globalState) {\n\tconst expression = createExpression(expressionInput, rootKey, propertySpec, globalState);\n\tif (expression.result === \"error\") return expression;\n\tconst parsed = expression.value.expression;\n\tconst isFeatureConstantResult = isFeatureConstant(parsed);\n\tif (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) return error([new ExpressionParsingError(\"\", \"data expressions not supported\")]);\n\tconst isZoomConstant = isGlobalPropertyConstant(parsed, [\"zoom\"]);\n\tif (!isZoomConstant && !supportsZoomExpression(propertySpec)) return error([new ExpressionParsingError(\"\", \"zoom expressions not supported\")]);\n\tconst zoomCurve = findZoomCurve(parsed);\n\tif (!zoomCurve && !isZoomConstant) return error([new ExpressionParsingError(\"\", \"\\\"zoom\\\" expression may only be used as input to a top-level \\\"step\\\" or \\\"interpolate\\\" expression.\")]);\n\telse if (zoomCurve instanceof ExpressionParsingError) return error([zoomCurve]);\n\telse if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) return error([new ExpressionParsingError(\"\", \"\\\"interpolate\\\" expressions cannot be used with this property\")]);\n\tif (!zoomCurve) return success(isFeatureConstantResult ? new ZoomConstantExpression(\"constant\", expression.value, globalState) : new ZoomConstantExpression(\"source\", expression.value, globalState));\n\tconst interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : void 0;\n\treturn success(isFeatureConstantResult ? new ZoomDependentExpression(\"camera\", expression.value, zoomCurve.labels, interpolationType, globalState) : new ZoomDependentExpression(\"composite\", expression.value, zoomCurve.labels, interpolationType, globalState));\n}\nvar StylePropertyFunction = class StylePropertyFunction {\n\tconstructor(parameters, rootKey, specification) {\n\t\tthis.isStateDependent = false;\n\t\tthis.globalStateRefs = /* @__PURE__ */ new Set();\n\t\tthis._globalState = null;\n\t\tassertRootKey(rootKey);\n\t\tthis._parameters = parameters;\n\t\tthis._specification = specification;\n\t\tthis._rootKey = rootKey;\n\t\tthis._defaultValue = getDefaultValue(specification);\n\t\tthis._warningHistory = {};\n\t\tconst fn = createFunction(this._parameters, this._specification);\n\t\tthis.kind = fn.kind;\n\t\tthis.interpolationFactor = fn.interpolationFactor;\n\t\tthis.zoomStops = fn.zoomStops;\n\t\tthis.interpolationType = fn.interpolationType;\n\t\tthis._innerEvaluate = fn.evaluate;\n\t}\n\t/**\n\t* Evaluates the legacy function, handling a runtime throw (e.g. interpolating\n\t* mismatched value types) by warning with the property location and falling\n\t* back to the spec default, mirroring {@link StyleExpression.evaluate}.\n\t* @param globals Global evaluation properties (e.g. zoom)\n\t* @param feature The feature being evaluated, if any\n\t* @returns The function result, or the spec default if evaluation throws\n\t*/\n\tevaluate(globals, feature) {\n\t\ttry {\n\t\t\treturn this._innerEvaluate(globals, feature);\n\t\t} catch (e) {\n\t\t\tconst message = e instanceof Error ? e.message : String(e);\n\t\t\tconst dedupKey = `|${message}`;\n\t\t\tif (!this._warningHistory[dedupKey]) {\n\t\t\t\tthis._warningHistory[dedupKey] = true;\n\t\t\t\tif (typeof console !== \"undefined\") console.warn(formatRuntimeWarning(this._rootKey, \"\", message, this._defaultValue));\n\t\t\t}\n\t\t\treturn this._defaultValue;\n\t\t}\n\t}\n\tstatic deserialize(serialized) {\n\t\treturn new StylePropertyFunction(serialized._parameters, serialized._rootKey, serialized._specification);\n\t}\n\tstatic serialize(input) {\n\t\treturn {\n\t\t\t_parameters: input._parameters,\n\t\t\t_specification: input._specification,\n\t\t\t_rootKey: input._rootKey\n\t\t};\n\t}\n};\nfunction normalizePropertyExpression(value, rootKey, specification, globalState) {\n\tif (isFunction(value)) return new StylePropertyFunction(value, rootKey, specification);\n\telse if (isExpression(value)) {\n\t\tconst expression = createPropertyExpression(value, rootKey, specification, globalState);\n\t\tif (expression.result === \"error\") throw new Error(expression.value.map((err) => `${err.key}: ${err.message}`).join(\", \"));\n\t\treturn expression.value;\n\t} else {\n\t\tlet constant = value;\n\t\tif (specification.type === \"color\" && typeof value === \"string\") constant = Color.parse(value);\n\t\telse if (specification.type === \"padding\" && (typeof value === \"number\" || Array.isArray(value))) constant = Padding.parse(value);\n\t\telse if (specification.type === \"numberArray\" && (typeof value === \"number\" || Array.isArray(value))) constant = NumberArray.parse(value);\n\t\telse if (specification.type === \"colorArray\" && (typeof value === \"string\" || Array.isArray(value))) constant = ColorArray.parse(value);\n\t\telse if (specification.type === \"variableAnchorOffsetCollection\" && Array.isArray(value)) constant = VariableAnchorOffsetCollection.parse(value);\n\t\telse if (specification.type === \"projectionDefinition\" && typeof value === \"string\") constant = ProjectionDefinition.parse(value);\n\t\treturn {\n\t\t\tglobalStateRefs: /* @__PURE__ */ new Set(),\n\t\t\t_globalState: null,\n\t\t\tkind: \"constant\",\n\t\t\tevaluate: () => constant\n\t\t};\n\t}\n}\nfunction findZoomCurve(expression, seen = /* @__PURE__ */ new Map()) {\n\tif (seen.has(expression)) return seen.get(expression);\n\tlet result = null;\n\tif (expression instanceof Let) result = findZoomCurve(expression.result, seen);\n\telse if (expression instanceof Coalesce) for (const arg of expression.args) {\n\t\tresult = findZoomCurve(arg, seen);\n\t\tif (result) break;\n\t}\n\telse if ((expression instanceof Step || expression instanceof Interpolate) && expression.input instanceof CompoundExpression && expression.input.name === \"zoom\") result = expression;\n\tif (result instanceof ExpressionParsingError) {\n\t\tseen.set(expression, result);\n\t\treturn result;\n\t}\n\texpression.eachChild((child) => {\n\t\tconst childResult = findZoomCurve(child, seen);\n\t\tif (childResult instanceof ExpressionParsingError) result = childResult;\n\t\telse if (!result && childResult) result = new ExpressionParsingError(\"\", \"\\\"zoom\\\" expression may only be used as input to a top-level \\\"step\\\" or \\\"interpolate\\\" expression.\");\n\t\telse if (result && childResult && result !== childResult) result = new ExpressionParsingError(\"\", \"Only one zoom-based \\\"step\\\" or \\\"interpolate\\\" subexpression may be used in an expression.\");\n\t});\n\tseen.set(expression, result);\n\treturn result;\n}\nfunction findGlobalStateRefs(expression, results = /* @__PURE__ */ new Set()) {\n\tif (expression instanceof GlobalState) results.add(expression.key);\n\texpression.eachChild((childExpression) => {\n\t\tfindGlobalStateRefs(childExpression, results);\n\t});\n\treturn results;\n}\nfunction getExpectedType(spec) {\n\tconst types = {\n\t\tcolor: ColorType,\n\t\tstring: StringType,\n\t\tnumber: NumberType,\n\t\tenum: StringType,\n\t\tboolean: BooleanType,\n\t\tformatted: FormattedType,\n\t\tpadding: PaddingType,\n\t\tnumberArray: NumberArrayType,\n\t\tcolorArray: ColorArrayType,\n\t\tprojectionDefinition: ProjectionDefinitionType,\n\t\tresolvedImage: ResolvedImageType,\n\t\tvariableAnchorOffsetCollection: VariableAnchorOffsetCollectionType\n\t};\n\tif (spec.type === \"array\") return array(types[spec.value] || ValueType, spec.length);\n\treturn types[spec.type];\n}\nfunction getDefaultValue(spec) {\n\tif (spec.type === \"color\" && isFunction(spec.default)) return new Color(0, 0, 0, 0);\n\tswitch (spec.type) {\n\t\tcase \"color\": return Color.parse(spec.default) || null;\n\t\tcase \"padding\": return Padding.parse(spec.default) || null;\n\t\tcase \"numberArray\": return NumberArray.parse(spec.default) || null;\n\t\tcase \"colorArray\": return ColorArray.parse(spec.default) || null;\n\t\tcase \"variableAnchorOffsetCollection\": return VariableAnchorOffsetCollection.parse(spec.default) || null;\n\t\tcase \"projectionDefinition\": return ProjectionDefinition.parse(spec.default) || null;\n\t\tdefault: return spec.default === void 0 ? null : spec.default;\n\t}\n}\nfunction addGlobalState(globals, globalState) {\n\tconst { zoom, heatmapDensity, elevation, lineProgress, isSupportedScript, accumulated } = globals ?? {};\n\treturn {\n\t\tzoom,\n\t\theatmapDensity,\n\t\televation,\n\t\tlineProgress,\n\t\tisSupportedScript,\n\t\taccumulated,\n\t\tglobalState\n\t};\n}\nexport { StyleExpression, StylePropertyFunction, ZoomConstantExpression, ZoomDependentExpression, createExpression, createPropertyExpression, findGlobalStateRefs, isExpression, isZoomExpression, normalizePropertyExpression };\n\n//# sourceMappingURL=index.mjs.map", "import { createExpression, findGlobalStateRefs } from \"../expression/index.mjs\";\n// src/feature_filter/index.ts\nfunction classifyChildren(children) {\n\tlet sawLegacy = false;\n\tfor (const child of children) {\n\t\tconst classification = classifyFilter(child);\n\t\tif (classification === \"expression\") return \"expression\";\n\t\tif (classification === \"legacy\") sawLegacy = true;\n\t}\n\treturn sawLegacy ? \"legacy\" : \"neutral\";\n}\nfunction classifyFilter(filter) {\n\tif (typeof filter === \"boolean\") return \"neutral\";\n\tif (!Array.isArray(filter) || filter.length === 0) return \"legacy\";\n\tswitch (filter[0]) {\n\t\tcase \"has\":\n\t\t\tif (filter.length < 2 || filter[1] === \"$id\" || filter[1] === \"$type\") return \"legacy\";\n\t\t\treturn filter.length === 2 ? \"neutral\" : \"expression\";\n\t\tcase \"in\": return filter.length >= 3 && (typeof filter[1] !== \"string\" || Array.isArray(filter[2])) ? \"expression\" : \"legacy\";\n\t\tcase \"!in\":\n\t\tcase \"!has\": return \"legacy\";\n\t\tcase \"==\":\n\t\tcase \"!=\":\n\t\tcase \">\":\n\t\tcase \">=\":\n\t\tcase \"<\":\n\t\tcase \"<=\": return filter.length !== 3 || Array.isArray(filter[1]) || Array.isArray(filter[2]) ? \"expression\" : \"legacy\";\n\t\tcase \"none\": return \"legacy\";\n\t\tcase \"any\":\n\t\tcase \"all\": return classifyChildren(filter.slice(1));\n\t\tdefault: return \"expression\";\n\t}\n}\nfunction isExpressionFilter(filter) {\n\treturn classifyFilter(filter) !== \"legacy\";\n}\nfunction getFilterPropertyExpression(property) {\n\tif (property === \"$type\") return [\"geometry-type\"];\n\tif (property === \"$id\") return [\"id\"];\n\treturn [\"get\", property];\n}\nfunction getLegacyFilterExpressionSuggestion(filter) {\n\tswitch (filter[0]) {\n\t\tcase \"==\":\n\t\tcase \"!=\":\n\t\tcase \"<\":\n\t\tcase \"<=\":\n\t\tcase \">\":\n\t\tcase \">=\":\n\t\t\tif (filter.length !== 3 || typeof filter[1] !== \"string\") return null;\n\t\t\treturn [\n\t\t\t\tfilter[0],\n\t\t\t\tgetFilterPropertyExpression(filter[1]),\n\t\t\t\tfilter[2]\n\t\t\t];\n\t\tcase \"in\":\n\t\tcase \"!in\": {\n\t\t\tif (filter.length < 2 || typeof filter[1] !== \"string\") return null;\n\t\t\tconst expression = [\n\t\t\t\t\"in\",\n\t\t\t\tgetFilterPropertyExpression(filter[1]),\n\t\t\t\t[\"literal\", filter.slice(2)]\n\t\t\t];\n\t\t\treturn filter[0] === \"!in\" ? [\"!\", expression] : expression;\n\t\t}\n\t\tcase \"has\":\n\t\tcase \"!has\": {\n\t\t\tif (filter.length !== 2 || typeof filter[1] !== \"string\") return null;\n\t\t\tif (filter[1] === \"$type\" || filter[1] === \"$id\") return null;\n\t\t\tconst expression = [\"has\", filter[1]];\n\t\t\treturn filter[0] === \"!has\" ? [\"!\", expression] : expression;\n\t\t}\n\t\tdefault: return null;\n\t}\n}\nfunction getMixedFilterMessage(filter) {\n\tif ((filter[0] === \"<\" || filter[0] === \"<=\" || filter[0] === \">\" || filter[0] === \">=\") && filter[1] === \"$type\") return `\"$type\" cannot be use with operator \"${filter[0]}\"`;\n\tconst suggestion = getLegacyFilterExpressionSuggestion(filter);\n\tif (suggestion) return `Mixing deprecated filter syntax with expression syntax is not supported. Replace ${JSON.stringify(filter)} with ${JSON.stringify(suggestion)}.`;\n\treturn `Mixing deprecated filter syntax with expression syntax is not supported. Convert ${JSON.stringify(filter)} to expression syntax.`;\n}\nfunction checkChild(index, path, filter) {\n\tconst child = filter[index];\n\tif (!Array.isArray(child)) return null;\n\tif (!isExpressionFilter(child)) return {\n\t\tpath: path.concat(index),\n\t\tlegacyFilter: child\n\t};\n\treturn findMixedLegacyFilter(child, path.concat(index));\n}\nfunction findMixedLegacyFilter(filter, path = []) {\n\tif (!Array.isArray(filter) || filter.length < 1) return null;\n\tswitch (filter[0]) {\n\t\tcase \"all\":\n\t\tcase \"any\":\n\t\tcase \"none\":\n\t\t\tfor (let i = 1; i < filter.length; i++) {\n\t\t\t\tconst diagnostic = checkChild(i, path, filter);\n\t\t\t\tif (diagnostic) return diagnostic;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"!\": {\n\t\t\tconst diagnostic = checkChild(1, path, filter);\n\t\t\tif (diagnostic) return diagnostic;\n\t\t\tbreak;\n\t\t}\n\t\tcase \"case\": for (let i = 1; i < filter.length - 1; i += 2) {\n\t\t\tconst diagnostic = checkChild(i, path, filter);\n\t\t\tif (diagnostic) return diagnostic;\n\t\t}\n\t}\n\treturn null;\n}\nfunction warnAboutMixedLegacyFilter(filter, rootKey) {\n\tconst diagnostic = findMixedLegacyFilter(filter);\n\tif (!diagnostic || typeof console === \"undefined\") return;\n\tconst path = diagnostic.path.map((index) => `[${index}]`).join(\"\");\n\tconsole.warn(`${rootKey}${path}: ${getMixedFilterMessage(diagnostic.legacyFilter)}`);\n}\nconst filterSpec = {\n\ttype: \"boolean\",\n\tdefault: false,\n\ttransition: false,\n\t\"property-type\": \"data-driven\",\n\texpression: {\n\t\tinterpolated: false,\n\t\tparameters: [\"zoom\", \"feature\"]\n\t}\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 filter MapLibre filter\n* @param rootKey Location of the filter in the style JSON (e.g. `layers[3].filter`),\n* used to prefix runtime warnings\n* @param [globalState] Global state object to be used for evaluating 'global-state' expressions\n* @returns filter-evaluating function\n*/\nfunction featureFilter(filter, rootKey, globalState) {\n\tif (filter === null || filter === void 0) return {\n\t\tfilter: () => true,\n\t\tneedGeometry: false,\n\t\tgetGlobalStateRefs: () => /* @__PURE__ */ new Set()\n\t};\n\tif (!isExpressionFilter(filter)) filter = convertFilter(filter);\n\telse warnAboutMixedLegacyFilter(filter, rootKey);\n\tconst compiled = createExpression(filter, rootKey, filterSpec, globalState);\n\tif (compiled.result === \"error\") throw new Error(compiled.value.map((err) => `${err.key}: ${err.message}`).join(\", \"));\n\telse return {\n\t\tfilter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical),\n\t\tneedGeometry: geometryNeeded(filter),\n\t\tgetGlobalStateRefs: () => findGlobalStateRefs(compiled.value.expression)\n\t};\n}\nfunction compare(a, b) {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\nfunction geometryNeeded(filter) {\n\tif (!Array.isArray(filter)) return false;\n\tif (filter[0] === \"within\" || filter[0] === \"distance\") return true;\n\tfor (let index = 1; index < filter.length; index++) if (geometryNeeded(filter[index])) return true;\n\treturn false;\n}\nfunction convertFilter(filter) {\n\tif (!filter) return true;\n\tconst op = filter[0];\n\tif (filter.length <= 1) return op !== \"any\";\n\treturn 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])) : true;\n}\nfunction convertComparisonOp(property, value, op) {\n\tswitch (property) {\n\t\tcase \"$type\": return [`filter-type-${op}`, value];\n\t\tcase \"$id\": return [`filter-id-${op}`, value];\n\t\tdefault: return [\n\t\t\t`filter-${op}`,\n\t\t\tproperty,\n\t\t\tvalue\n\t\t];\n\t}\n}\nfunction convertDisjunctionOp(filters) {\n\treturn [\"any\"].concat(filters.map(convertFilter));\n}\nfunction convertInOp(property, values) {\n\tif (values.length === 0) return false;\n\tswitch (property) {\n\t\tcase \"$type\": return [\"filter-type-in\", [\"literal\", values]];\n\t\tcase \"$id\": return [\"filter-id-in\", [\"literal\", values]];\n\t\tdefault: if (values.length > 200 && !values.some((v) => typeof v !== typeof values[0])) return [\n\t\t\t\"filter-in-large\",\n\t\t\tproperty,\n\t\t\t[\"literal\", values.sort(compare)]\n\t\t];\n\t\telse return [\n\t\t\t\"filter-in-small\",\n\t\t\tproperty,\n\t\t\t[\"literal\", values]\n\t\t];\n\t}\n}\nfunction convertHasOp(property) {\n\tswitch (property) {\n\t\tcase \"$type\": return true;\n\t\tcase \"$id\": return [\"filter-has-id\"];\n\t\tdefault: return [\"filter-has\", property];\n\t}\n}\nfunction convertNegation(filter) {\n\treturn [\"!\", filter];\n}\nexport { featureFilter, findMixedLegacyFilter, getMixedFilterMessage, isExpressionFilter, warnAboutMixedLegacyFilter };\n\n//# sourceMappingURL=index.mjs.map", "import { latest } from \"./reference/latest.mjs\";\n// src/empty.ts\nfunction emptyStyle() {\n\tconst style = {};\n\tconst version = latest[\"$version\"];\n\tfor (const styleKey in latest[\"$root\"]) {\n\t\tconst specification = latest[\"$root\"][styleKey];\n\t\tif (specification.required) {\n\t\t\tlet value = null;\n\t\t\tif (styleKey === \"version\") value = version;\n\t\t\telse if (specification.type === \"array\") value = [];\n\t\t\telse value = {};\n\t\t\tif (value != null) style[styleKey] = value;\n\t\t}\n\t}\n\treturn style;\n}\nexport { emptyStyle };\n\n//# sourceMappingURL=empty.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\n// src/validate/validate_constants.ts\nfunction validateConstants(options) {\n\tconst key = options.key;\n\tconst constants = options.value;\n\tif (constants) return [new ValidationError(key, constants, \"constants have been deprecated as of v8\")];\n\telse return [];\n}\nexport { validateConstants };\n\n//# sourceMappingURL=validate_constants.mjs.map", "// src/util/unbundle_jsonlint.ts\nfunction unbundle(value) {\n\tif (value instanceof Number || value instanceof String || value instanceof Boolean) return value.valueOf();\n\telse return value;\n}\nfunction deepUnbundle(value) {\n\tif (Array.isArray(value)) return value.map(deepUnbundle);\n\telse if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) {\n\t\tconst unbundledValue = {};\n\t\tfor (const key in value) unbundledValue[key] = deepUnbundle(value[key]);\n\t\treturn unbundledValue;\n\t}\n\treturn unbundle(value);\n}\nexport { deepUnbundle, unbundle };\n\n//# sourceMappingURL=unbundle_jsonlint.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getOwn } from \"../util/get_own.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_object.ts\nfunction validateObject(options) {\n\tconst key = options.key;\n\tconst object = options.value;\n\tconst elementSpecs = options.valueSpec || {};\n\tconst elementValidators = options.objectElementValidators || {};\n\tconst style = options.style;\n\tconst styleSpec = options.styleSpec;\n\tconst validateSpec = options.validateSpec;\n\tlet errors = [];\n\tconst type = getType(object);\n\tif (type !== \"object\") return [new ValidationError(key, object, `object expected, ${type} found`)];\n\tfor (const objectKey in object) {\n\t\tconst elementSpecKey = objectKey.split(\".\")[0];\n\t\tconst elementSpec = getOwn(elementSpecs, elementSpecKey) || elementSpecs[\"*\"];\n\t\tlet validateElement;\n\t\tif (getOwn(elementValidators, elementSpecKey)) validateElement = elementValidators[elementSpecKey];\n\t\telse if (getOwn(elementSpecs, elementSpecKey)) {\n\t\t\tif (object[objectKey] === void 0) continue;\n\t\t\tvalidateElement = validateSpec;\n\t\t} else if (elementValidators[\"*\"]) validateElement = elementValidators[\"*\"];\n\t\telse if (elementSpecs[\"*\"]) validateElement = validateSpec;\n\t\telse {\n\t\t\terrors.push(new ValidationError(key, object[objectKey], `unknown property \"${objectKey}\"`));\n\t\t\tcontinue;\n\t\t}\n\t\terrors = errors.concat(validateElement({\n\t\t\tkey: (key ? `${key}.` : key) + objectKey,\n\t\t\tvalue: object[objectKey],\n\t\t\tvalueSpec: elementSpec,\n\t\t\tstyle,\n\t\t\tstyleSpec,\n\t\t\tobject,\n\t\t\tobjectKey,\n\t\t\tvalidateSpec\n\t\t}, object));\n\t}\n\tfor (const elementSpecKey in elementSpecs) {\n\t\tif (elementValidators[elementSpecKey]) continue;\n\t\tif (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey][\"default\"] === void 0 && object[elementSpecKey] === void 0) errors.push(new ValidationError(key, object, `missing required property \"${elementSpecKey}\"`));\n\t}\n\treturn errors;\n}\nexport { validateObject };\n\n//# sourceMappingURL=validate_object.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_array.ts\nfunction validateArray(options) {\n\tconst array = options.value;\n\tconst arraySpec = options.valueSpec;\n\tconst validateSpec = options.validateSpec;\n\tconst style = options.style;\n\tconst styleSpec = options.styleSpec;\n\tconst key = options.key;\n\tconst validateArrayElement = options.arrayElementValidator || validateSpec;\n\tif (getType(array) !== \"array\") return [new ValidationError(key, array, `array expected, ${getType(array)} found`)];\n\tif (arraySpec.length && array.length !== arraySpec.length) return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)];\n\tlet arrayElementSpec = {\n\t\ttype: arraySpec.value,\n\t\tvalues: arraySpec.values\n\t};\n\tif (styleSpec.$version < 7) arrayElementSpec[\"function\"] = arraySpec.function;\n\tif (getType(arraySpec.value) === \"object\") arrayElementSpec = arraySpec.value;\n\tlet errors = [];\n\tfor (let i = 0; i < array.length; i++) errors = errors.concat(validateArrayElement({\n\t\tarray,\n\t\tarrayIndex: i,\n\t\tvalue: array[i],\n\t\tvalueSpec: arrayElementSpec,\n\t\tvalidateSpec: options.validateSpec,\n\t\tstyle,\n\t\tstyleSpec,\n\t\tkey: `${key}[${i}]`\n\t}));\n\treturn errors;\n}\nexport { validateArray };\n\n//# sourceMappingURL=validate_array.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_number.ts\nfunction validateNumber(options) {\n\tconst key = options.key;\n\tconst value = options.value;\n\tconst valueSpec = options.valueSpec;\n\tlet type = getType(value);\n\tif (type === \"number\" && value !== value) type = \"NaN\";\n\tif (type !== \"number\") return [new ValidationError(key, value, `number expected, ${type} found`)];\n\tif (\"minimum\" in valueSpec && value < valueSpec.minimum) return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)];\n\tif (\"maximum\" in valueSpec && value > valueSpec.maximum) return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)];\n\treturn [];\n}\nexport { validateNumber };\n\n//# sourceMappingURL=validate_number.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { supportsInterpolation, supportsPropertyExpression, supportsZoomExpression } from \"../util/properties.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { isExpression } from \"../expression/index.mjs\";\nimport { deepUnbundle, unbundle } from \"../util/unbundle_jsonlint.mjs\";\nimport { validateObject } from \"./validate_object.mjs\";\nimport { validateArray } from \"./validate_array.mjs\";\nimport { validateNumber } from \"./validate_number.mjs\";\n// src/validate/validate_function.ts\nfunction validateFunction(options) {\n\tconst functionValueSpec = options.valueSpec;\n\tconst functionType = unbundle(options.value.type);\n\tlet stopKeyType;\n\tlet stopDomainValues = {};\n\tlet previousStopDomainValue;\n\tlet previousStopDomainZoom;\n\tconst isZoomFunction = functionType !== \"categorical\" && options.value.property === void 0;\n\tconst isPropertyFunction = !isZoomFunction;\n\tconst isZoomAndPropertyFunction = getType(options.value.stops) === \"array\" && getType(options.value.stops[0]) === \"array\" && getType(options.value.stops[0][0]) === \"object\";\n\tconst errors = validateObject({\n\t\tkey: options.key,\n\t\tvalue: options.value,\n\t\tvalueSpec: options.styleSpec.function,\n\t\tvalidateSpec: options.validateSpec,\n\t\tstyle: options.style,\n\t\tstyleSpec: options.styleSpec,\n\t\tobjectElementValidators: {\n\t\t\tstops: validateFunctionStops,\n\t\t\tdefault: validateFunctionDefault\n\t\t}\n\t});\n\tif (functionType === \"identity\" && isZoomFunction) errors.push(new ValidationError(options.key, options.value, \"missing required property \\\"property\\\"\"));\n\tif (functionType !== \"identity\" && !options.value.stops) errors.push(new ValidationError(options.key, options.value, \"missing required property \\\"stops\\\"\"));\n\tif (functionType === \"exponential\" && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) errors.push(new ValidationError(options.key, options.value, \"exponential functions not supported\"));\n\tif (options.styleSpec.$version >= 8) {\n\t\tif (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) errors.push(new ValidationError(options.key, options.value, \"property functions not supported\"));\n\t\telse if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) errors.push(new ValidationError(options.key, options.value, \"zoom functions not supported\"));\n\t}\n\tif ((functionType === \"categorical\" || isZoomAndPropertyFunction) && options.value.property === void 0) errors.push(new ValidationError(options.key, options.value, \"\\\"property\\\" property is required\"));\n\treturn errors;\n\tfunction validateFunctionStops(options) {\n\t\tif (functionType === \"identity\") return [new ValidationError(options.key, options.value, \"identity function may not have a \\\"stops\\\" property\")];\n\t\tlet errors = [];\n\t\tconst value = options.value;\n\t\terrors = errors.concat(validateArray({\n\t\t\tkey: options.key,\n\t\t\tvalue,\n\t\t\tvalueSpec: options.valueSpec,\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tstyle: options.style,\n\t\t\tstyleSpec: options.styleSpec,\n\t\t\tarrayElementValidator: validateFunctionStop\n\t\t}));\n\t\tif (getType(value) === \"array\" && value.length === 0) errors.push(new ValidationError(options.key, value, \"array must have at least one stop\"));\n\t\treturn errors;\n\t}\n\tfunction validateFunctionStop(options) {\n\t\tlet errors = [];\n\t\tconst value = options.value;\n\t\tconst key = options.key;\n\t\tif (getType(value) !== \"array\") return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n\t\tif (value.length !== 2) return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)];\n\t\tif (isZoomAndPropertyFunction) {\n\t\t\tif (getType(value[0]) !== \"object\") return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)];\n\t\t\tif (value[0].zoom === void 0) return [new ValidationError(key, value, \"object stop key must have zoom\")];\n\t\t\tif (value[0].value === void 0) return [new ValidationError(key, value, \"object stop key must have value\")];\n\t\t\tif (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) return [new ValidationError(key, value[0].zoom, \"stop zoom values must appear in ascending order\")];\n\t\t\tif (unbundle(value[0].zoom) !== previousStopDomainZoom) {\n\t\t\t\tpreviousStopDomainZoom = unbundle(value[0].zoom);\n\t\t\t\tpreviousStopDomainValue = void 0;\n\t\t\t\tstopDomainValues = {};\n\t\t\t}\n\t\t\terrors = errors.concat(validateObject({\n\t\t\t\tkey: `${key}[0]`,\n\t\t\t\tvalue: value[0],\n\t\t\t\tvalueSpec: { zoom: {} },\n\t\t\t\tvalidateSpec: options.validateSpec,\n\t\t\t\tstyle: options.style,\n\t\t\t\tstyleSpec: options.styleSpec,\n\t\t\t\tobjectElementValidators: {\n\t\t\t\t\tzoom: validateNumber,\n\t\t\t\t\tvalue: validateStopDomainValue\n\t\t\t\t}\n\t\t\t}));\n\t\t} else errors = errors.concat(validateStopDomainValue({\n\t\t\tkey: `${key}[0]`,\n\t\t\tvalue: value[0],\n\t\t\tvalueSpec: {},\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tstyle: options.style,\n\t\t\tstyleSpec: options.styleSpec\n\t\t}, value));\n\t\tif (isExpression(deepUnbundle(value[1]))) return errors.concat([new ValidationError(`${key}[1]`, value[1], \"expressions are not allowed in function stops.\")]);\n\t\treturn errors.concat(options.validateSpec({\n\t\t\tkey: `${key}[1]`,\n\t\t\tvalue: value[1],\n\t\t\tvalueSpec: functionValueSpec,\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tstyle: options.style,\n\t\t\tstyleSpec: options.styleSpec\n\t\t}));\n\t}\n\tfunction validateStopDomainValue(options, stop) {\n\t\tconst type = getType(options.value);\n\t\tconst value = unbundle(options.value);\n\t\tconst reportValue = options.value !== null ? options.value : stop;\n\t\tif (!stopKeyType) stopKeyType = type;\n\t\telse if (type !== stopKeyType) return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)];\n\t\tif (type !== \"number\" && type !== \"string\" && type !== \"boolean\") return [new ValidationError(options.key, reportValue, \"stop domain value must be a number, string, or boolean\")];\n\t\tif (type !== \"number\" && functionType !== \"categorical\") {\n\t\t\tlet message = `number expected, ${type} found`;\n\t\t\tif (supportsPropertyExpression(functionValueSpec) && functionType === void 0) message += \"\\nIf you intended to use a categorical function, specify `\\\"type\\\": \\\"categorical\\\"`.\";\n\t\t\treturn [new ValidationError(options.key, reportValue, message)];\n\t\t}\n\t\tif (functionType === \"categorical\" && type === \"number\" && (!isFinite(value) || Math.floor(value) !== value)) return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)];\n\t\tif (functionType !== \"categorical\" && type === \"number\" && previousStopDomainValue !== void 0 && value < previousStopDomainValue) return [new ValidationError(options.key, reportValue, \"stop domain values must appear in ascending order\")];\n\t\telse previousStopDomainValue = value;\n\t\tif (functionType === \"categorical\" && value in stopDomainValues) return [new ValidationError(options.key, reportValue, \"stop domain values must be unique\")];\n\t\telse stopDomainValues[value] = true;\n\t\treturn [];\n\t}\n\tfunction validateFunctionDefault(options) {\n\t\treturn options.validateSpec({\n\t\t\tkey: options.key,\n\t\t\tvalue: options.value,\n\t\t\tvalueSpec: functionValueSpec,\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tstyle: options.style,\n\t\t\tstyleSpec: options.styleSpec\n\t\t});\n\t}\n}\nexport { validateFunction };\n\n//# sourceMappingURL=validate_function.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { isFeatureConstant, isGlobalPropertyConstant, isStateConstant } from \"../expression/compound_expression.mjs\";\nimport { createExpression, createPropertyExpression } from \"../expression/index.mjs\";\nimport { deepUnbundle } from \"../util/unbundle_jsonlint.mjs\";\n// src/validate/validate_expression.ts\nfunction validateExpression(options) {\n\tconst expression = (options.expressionContext === \"property\" ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.key, options.valueSpec);\n\tif (expression.result === \"error\") return expression.value.map((error) => {\n\t\treturn new ValidationError(`${options.key}${error.key}`, options.value, error.message);\n\t});\n\tconst expressionObj = expression.value.expression || expression.value._styleExpression.expression;\n\tif (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.`)];\n\tif (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.\")];\n\tif (options.expressionContext === \"filter\" && !isStateConstant(expressionObj)) return [new ValidationError(options.key, options.value, \"\\\"feature-state\\\" data expressions are not supported with filters.\")];\n\tif (options.expressionContext && options.expressionContext.indexOf(\"cluster\") === 0) {\n\t\tif (!isGlobalPropertyConstant(expressionObj, [\"zoom\", \"feature-state\"])) return [new ValidationError(options.key, options.value, \"\\\"zoom\\\" and \\\"feature-state\\\" expressions are not supported with cluster properties.\")];\n\t\tif (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.\")];\n\t}\n\treturn [];\n}\nexport { validateExpression };\n\n//# sourceMappingURL=validate_expression.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_boolean.ts\nfunction validateBoolean(options) {\n\tconst value = options.value;\n\tconst key = options.key;\n\tconst type = getType(value);\n\tif (type !== \"boolean\") return [new ValidationError(key, value, `boolean expected, ${type} found`)];\n\treturn [];\n}\nexport { validateBoolean };\n\n//# sourceMappingURL=validate_boolean.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { Color } from \"../expression/types/color.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_color.ts\nfunction validateColor(options) {\n\tconst key = options.key;\n\tconst value = options.value;\n\tconst type = getType(value);\n\tif (type !== \"string\") return [new ValidationError(key, value, `color expected, ${type} found`)];\n\tif (!Color.parse(String(value))) return [new ValidationError(key, value, `color expected, \"${value}\" found`)];\n\treturn [];\n}\nexport { validateColor };\n\n//# sourceMappingURL=validate_color.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { unbundle } from \"../util/unbundle_jsonlint.mjs\";\n// src/validate/validate_enum.ts\nfunction validateEnum(options) {\n\tconst key = options.key;\n\tconst value = options.value;\n\tconst valueSpec = options.valueSpec;\n\tconst errors = [];\n\tif (Array.isArray(valueSpec.values)) {\n\t\tif (valueSpec.values.indexOf(unbundle(value)) === -1) errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(\", \")}], ${JSON.stringify(value)} found`));\n\t} 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`));\n\treturn errors;\n}\nexport { validateEnum };\n\n//# sourceMappingURL=validate_enum.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { extendBy } from \"../util/extend.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { findMixedLegacyFilter, getMixedFilterMessage, isExpressionFilter } from \"../feature_filter/index.mjs\";\nimport { deepUnbundle, unbundle } from \"../util/unbundle_jsonlint.mjs\";\nimport { validateExpression } from \"./validate_expression.mjs\";\nimport { validateEnum } from \"./validate_enum.mjs\";\n// src/validate/validate_filter.ts\nfunction getValueAtPath(value, path) {\n\tlet current = value;\n\tfor (const index of path) current = current[index];\n\treturn current;\n}\n/**\n* Reports a filter that mixes deprecated syntax into an expression tree as a *warning*.\n* @param options The validation options, used for the key and the un-unbundled value\n* @param value The unbundled filter to inspect\n* @returns A single warning, or an empty array when nothing is mixed\n*/\nfunction validateNoMixedLegacyFilter(options, value) {\n\tconst diagnostic = findMixedLegacyFilter(value);\n\tif (!diagnostic) return [];\n\tconst key = `${options.key}${diagnostic.path.map((index) => `[${index}]`).join(\"\")}`;\n\treturn [new ValidationError(key, getValueAtPath(options.value, diagnostic.path), getMixedFilterMessage(diagnostic.legacyFilter), null, \"warning\")];\n}\nfunction validateFilter(options) {\n\tconst value = deepUnbundle(options.value);\n\tif (!isExpressionFilter(value)) return validateNonExpressionFilter(options);\n\treturn [...validateNoMixedLegacyFilter(options, value), ...validateExpression(extendBy({}, options, {\n\t\texpressionContext: \"filter\",\n\t\tvalueSpec: { value: \"boolean\" }\n\t}))];\n}\nfunction validateNonExpressionFilter(options) {\n\tconst value = options.value;\n\tconst key = options.key;\n\tif (getType(value) !== \"array\") return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n\tconst styleSpec = options.styleSpec;\n\tlet type;\n\tlet errors = [];\n\tif (value.length < 1) return [new ValidationError(key, value, \"filter array must have at least 1 element\")];\n\terrors = errors.concat(validateEnum({\n\t\tkey: `${key}[0]`,\n\t\tvalue: value[0],\n\t\tvalueSpec: styleSpec.filter_operator,\n\t\tstyle: options.style,\n\t\tstyleSpec: options.styleSpec\n\t}));\n\tswitch (unbundle(value[0])) {\n\t\tcase \"<\":\n\t\tcase \"<=\":\n\t\tcase \">\":\n\t\tcase \">=\": if (value.length >= 2 && unbundle(value[1]) === \"$type\") errors.push(new ValidationError(key, value, `\"$type\" cannot be use with operator \"${value[0]}\"`));\n\t\tcase \"==\":\n\t\tcase \"!=\": if (value.length !== 3) errors.push(new ValidationError(key, value, `filter array for operator \"${value[0]}\" must have 3 elements`));\n\t\tcase \"in\":\n\t\tcase \"!in\":\n\t\t\tif (value.length >= 2) {\n\t\t\t\ttype = getType(value[1]);\n\t\t\t\tif (type !== \"string\") errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n\t\t\t}\n\t\t\tfor (let i = 2; i < value.length; i++) {\n\t\t\t\ttype = getType(value[i]);\n\t\t\t\tif (unbundle(value[1]) === \"$type\") errors = errors.concat(validateEnum({\n\t\t\t\t\tkey: `${key}[${i}]`,\n\t\t\t\t\tvalue: value[i],\n\t\t\t\t\tvalueSpec: styleSpec.geometry_type,\n\t\t\t\t\tstyle: options.style,\n\t\t\t\t\tstyleSpec: options.styleSpec\n\t\t\t\t}));\n\t\t\t\telse if (type !== \"string\" && type !== \"number\" && type !== \"boolean\") errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"any\":\n\t\tcase \"all\":\n\t\tcase \"none\":\n\t\t\tfor (let i = 1; i < value.length; i++) errors = errors.concat(validateNonExpressionFilter({\n\t\t\t\tkey: `${key}[${i}]`,\n\t\t\t\tvalue: value[i],\n\t\t\t\tstyle: options.style,\n\t\t\t\tstyleSpec: options.styleSpec\n\t\t\t}));\n\t\t\tbreak;\n\t\tcase \"has\":\n\t\tcase \"!has\":\n\t\t\ttype = getType(value[1]);\n\t\t\tif (value.length !== 2) errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n\t\t\telse if (type !== \"string\") errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n\t}\n\treturn errors;\n}\nexport { validateFilter };\n\n//# sourceMappingURL=validate_filter.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { supportsPropertyExpression, transitionPropertyRegExp } from \"../util/properties.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { isFunction } from \"../function/index.mjs\";\nimport { deepUnbundle, unbundle } from \"../util/unbundle_jsonlint.mjs\";\n// src/validate/validate_property.ts\nfunction validateProperty(options, propertyType) {\n\tconst key = options.key;\n\tconst validateSpec = options.validateSpec;\n\tconst style = options.style;\n\tconst styleSpec = options.styleSpec;\n\tconst value = options.value;\n\tconst propertyKey = options.objectKey;\n\tconst layerSpec = styleSpec[`${propertyType}_${options.layerType}`];\n\tif (!layerSpec) return [];\n\tconst transitionMatch = propertyKey.match(transitionPropertyRegExp);\n\tif (propertyType === \"paint\" && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) return validateSpec({\n\t\tkey,\n\t\tvalue,\n\t\tvalueSpec: styleSpec.transition,\n\t\tstyle,\n\t\tstyleSpec\n\t});\n\tconst valueSpec = options.valueSpec || layerSpec[propertyKey];\n\tif (!valueSpec) return [new ValidationError(key, value, `unknown property \"${propertyKey}\"`)];\n\tlet tokenMatch;\n\tif (getType(value) === \"string\" && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) return [new ValidationError(key, value, `\"${propertyKey}\" does not support interpolation syntax\\nUse an identity property function instead: \\`{ \"type\": \"identity\", \"property\": ${JSON.stringify(tokenMatch[1])} }\\`.`)];\n\tconst errors = [];\n\tif (options.layerType === \"symbol\") {\n\t\tif (propertyKey === \"text-font\" && isFunction(deepUnbundle(value)) && unbundle(value.type) === \"identity\") errors.push(new ValidationError(key, value, \"\\\"text-font\\\" does not support identity functions\"));\n\t}\n\treturn errors.concat(validateSpec({\n\t\tkey: options.key,\n\t\tvalue,\n\t\tvalueSpec,\n\t\tstyle,\n\t\tstyleSpec,\n\t\texpressionContext: \"property\",\n\t\tpropertyType,\n\t\tpropertyKey\n\t}));\n}\nexport { validateProperty };\n\n//# sourceMappingURL=validate_property.mjs.map", "import { validateProperty } from \"./validate_property.mjs\";\n// src/validate/validate_paint_property.ts\nfunction validatePaintProperty(options) {\n\treturn validateProperty(options, \"paint\");\n}\nexport { validatePaintProperty };\n\n//# sourceMappingURL=validate_paint_property.mjs.map", "import { validateProperty } from \"./validate_property.mjs\";\n// src/validate/validate_layout_property.ts\nfunction validateLayoutProperty(options) {\n\treturn validateProperty(options, \"layout\");\n}\nexport { validateLayoutProperty };\n\n//# sourceMappingURL=validate_layout_property.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { extendBy } from \"../util/extend.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { unbundle } from \"../util/unbundle_jsonlint.mjs\";\nimport { validateObject } from \"./validate_object.mjs\";\nimport { validateFilter } from \"./validate_filter.mjs\";\nimport { validatePaintProperty } from \"./validate_paint_property.mjs\";\nimport { validateLayoutProperty } from \"./validate_layout_property.mjs\";\n// src/validate/validate_layer.ts\nfunction validateLayer(options) {\n\tlet errors = [];\n\tconst layer = options.value;\n\tconst key = options.key;\n\tconst style = options.style;\n\tconst styleSpec = options.styleSpec;\n\tif (getType(layer) !== \"object\") return [new ValidationError(key, layer, `object expected, ${getType(layer)} found`)];\n\tif (!layer.type && !layer.ref) errors.push(new ValidationError(key, layer, \"either \\\"type\\\" or \\\"ref\\\" is required\"));\n\tlet type = unbundle(layer.type);\n\tconst ref = unbundle(layer.ref);\n\tif (layer.id) {\n\t\tconst layerId = unbundle(layer.id);\n\t\tfor (let i = 0; i < options.arrayIndex; i++) {\n\t\t\tconst otherLayer = style.layers[i];\n\t\t\tif (unbundle(otherLayer.id) === layerId) errors.push(new ValidationError(key, layer.id, `duplicate layer id \"${layer.id}\", previously used at line ${otherLayer.id.__line__}`));\n\t\t}\n\t}\n\tif (\"ref\" in layer) {\n\t\t[\n\t\t\t\"type\",\n\t\t\t\"source\",\n\t\t\t\"source-layer\",\n\t\t\t\"filter\",\n\t\t\t\"layout\"\n\t\t].forEach((p) => {\n\t\t\tif (p in layer) errors.push(new ValidationError(key, layer[p], `\"${p}\" is prohibited for ref layers`));\n\t\t});\n\t\tlet parent;\n\t\tstyle.layers.forEach((layer) => {\n\t\t\tif (unbundle(layer.id) === ref) parent = layer;\n\t\t});\n\t\tif (!parent) errors.push(new ValidationError(key, layer.ref, `ref layer \"${ref}\" not found`));\n\t\telse if (parent.ref) errors.push(new ValidationError(key, layer.ref, \"ref cannot reference another ref layer\"));\n\t\telse type = unbundle(parent.type);\n\t} else if (type !== \"background\") {\n\t\tif (!layer.source) errors.push(new ValidationError(key, layer, \"missing required property \\\"source\\\"\"));\n\t\telse {\n\t\t\tconst source = style.sources && style.sources[layer.source];\n\t\t\tconst sourceType = source && unbundle(source.type);\n\t\t\tif (!source) errors.push(new ValidationError(key, layer.source, `source \"${layer.source}\" not found`));\n\t\t\telse if (sourceType === \"vector\" && type === \"raster\") errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster source`));\n\t\t\telse if (sourceType !== \"raster-dem\" && type === \"hillshade\") errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster-dem source`));\n\t\t\telse if (sourceType !== \"raster-dem\" && type === \"color-relief\") errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster-dem source`));\n\t\t\telse if (sourceType === \"raster\" && type !== \"raster\") errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a vector source`));\n\t\t\telse if (sourceType === \"vector\" && !layer[\"source-layer\"]) errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" must specify a \"source-layer\"`));\n\t\t\telse if (sourceType === \"raster-dem\" && type !== \"hillshade\" && type !== \"color-relief\") errors.push(new ValidationError(key, layer.source, \"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.\"));\n\t\t\telse 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.`));\n\t\t}\n\t}\n\tif (type === \"raster\" && layer.paint?.resampling && layer.paint?.[\"raster-resampling\"]) errors.push(new ValidationError(key, layer.paint, `layer \"${layer.id}\" redundantly specifies \"resampling\" and \"raster-resampling\" paint properties, but only one is allowed. It is advised to use \"resampling\".`));\n\terrors = errors.concat(validateObject({\n\t\tkey,\n\t\tvalue: layer,\n\t\tvalueSpec: styleSpec.layer,\n\t\tstyle: options.style,\n\t\tstyleSpec: options.styleSpec,\n\t\tvalidateSpec: options.validateSpec,\n\t\tobjectElementValidators: {\n\t\t\t\"*\"() {\n\t\t\t\treturn [];\n\t\t\t},\n\t\t\ttype() {\n\t\t\t\treturn options.validateSpec({\n\t\t\t\t\tkey: `${key}.type`,\n\t\t\t\t\tvalue: layer.type,\n\t\t\t\t\tvalueSpec: styleSpec.layer.type,\n\t\t\t\t\tstyle: options.style,\n\t\t\t\t\tstyleSpec: options.styleSpec,\n\t\t\t\t\tvalidateSpec: options.validateSpec,\n\t\t\t\t\tobject: layer,\n\t\t\t\t\tobjectKey: \"type\"\n\t\t\t\t});\n\t\t\t},\n\t\t\tfilter: validateFilter,\n\t\t\tlayout(options) {\n\t\t\t\treturn validateObject({\n\t\t\t\t\tlayer,\n\t\t\t\t\tkey: options.key,\n\t\t\t\t\tvalue: options.value,\n\t\t\t\t\tstyle: options.style,\n\t\t\t\t\tstyleSpec: options.styleSpec,\n\t\t\t\t\tvalidateSpec: options.validateSpec,\n\t\t\t\t\tobjectElementValidators: { \"*\"(options) {\n\t\t\t\t\t\treturn validateLayoutProperty(extendBy({ layerType: type }, options));\n\t\t\t\t\t} }\n\t\t\t\t});\n\t\t\t},\n\t\t\tpaint(options) {\n\t\t\t\treturn validateObject({\n\t\t\t\t\tlayer,\n\t\t\t\t\tkey: options.key,\n\t\t\t\t\tvalue: options.value,\n\t\t\t\t\tstyle: options.style,\n\t\t\t\t\tstyleSpec: options.styleSpec,\n\t\t\t\t\tvalidateSpec: options.validateSpec,\n\t\t\t\t\tobjectElementValidators: { \"*\"(options) {\n\t\t\t\t\t\treturn validatePaintProperty(extendBy({ layerType: type }, options));\n\t\t\t\t\t} }\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}));\n\treturn errors;\n}\nexport { validateLayer };\n\n//# sourceMappingURL=validate_layer.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_string.ts\nfunction validateString(options) {\n\tconst value = options.value;\n\tconst key = options.key;\n\tconst type = getType(value);\n\tif (type !== \"string\") return [new ValidationError(key, value, `string expected, ${type} found`)];\n\treturn [];\n}\nexport { validateString };\n\n//# sourceMappingURL=validate_string.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { unbundle } from \"../util/unbundle_jsonlint.mjs\";\n// src/validate/validate_raster_dem_source.ts\nfunction validateRasterDEMSource(options) {\n\tconst sourceName = options.sourceName ?? \"\";\n\tconst rasterDEM = options.value;\n\tconst styleSpec = options.styleSpec;\n\tconst rasterDEMSpec = styleSpec.source_raster_dem;\n\tconst style = options.style;\n\tlet errors = [];\n\tconst rootType = getType(rasterDEM);\n\tif (rasterDEM === void 0) return errors;\n\telse if (rootType !== \"object\") {\n\t\terrors.push(new ValidationError(\"source_raster_dem\", rasterDEM, `object expected, ${rootType} found`));\n\t\treturn errors;\n\t}\n\tconst isCustomEncoding = unbundle(rasterDEM.encoding) === \"custom\";\n\tconst customEncodingKeys = [\n\t\t\"redFactor\",\n\t\t\"greenFactor\",\n\t\t\"blueFactor\",\n\t\t\"baseShift\"\n\t];\n\tconst encodingName = options.value.encoding ? `\"${options.value.encoding}\"` : \"Default\";\n\tfor (const key in rasterDEM) if (!isCustomEncoding && customEncodingKeys.includes(key)) errors.push(new ValidationError(key, rasterDEM[key], `In \"${sourceName}\": \"${key}\" is only valid when \"encoding\" is set to \"custom\". ${encodingName} encoding found`));\n\telse if (rasterDEMSpec[key]) errors = errors.concat(options.validateSpec({\n\t\tkey,\n\t\tvalue: rasterDEM[key],\n\t\tvalueSpec: rasterDEMSpec[key],\n\t\tvalidateSpec: options.validateSpec,\n\t\tstyle,\n\t\tstyleSpec\n\t}));\n\telse errors.push(new ValidationError(key, rasterDEM[key], `unknown property \"${key}\"`));\n\treturn errors;\n}\nexport { validateRasterDEMSource };\n\n//# sourceMappingURL=validate_raster_dem_source.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { unbundle } from \"../util/unbundle_jsonlint.mjs\";\nimport { validateObject } from \"./validate_object.mjs\";\nimport { validateExpression } from \"./validate_expression.mjs\";\nimport { validateEnum } from \"./validate_enum.mjs\";\nimport { validateString } from \"./validate_string.mjs\";\nimport { validateRasterDEMSource } from \"./validate_raster_dem_source.mjs\";\n// src/validate/validate_source.ts\nconst objectElementValidators = { promoteId: validatePromoteId };\nfunction validateSource(options) {\n\tconst value = options.value;\n\tconst key = options.key;\n\tconst styleSpec = options.styleSpec;\n\tconst style = options.style;\n\tconst validateSpec = options.validateSpec;\n\tif (!value.type) return [new ValidationError(key, value, \"\\\"type\\\" is required\")];\n\tconst type = unbundle(value.type);\n\tlet errors;\n\tswitch (type) {\n\t\tcase \"vector\":\n\t\tcase \"raster\":\n\t\t\terrors = validateObject({\n\t\t\t\tkey,\n\t\t\t\tvalue,\n\t\t\t\tvalueSpec: styleSpec[`source_${type.replace(\"-\", \"_\")}`],\n\t\t\t\tstyle: options.style,\n\t\t\t\tstyleSpec,\n\t\t\t\tobjectElementValidators,\n\t\t\t\tvalidateSpec\n\t\t\t});\n\t\t\treturn errors;\n\t\tcase \"raster-dem\":\n\t\t\terrors = validateRasterDEMSource({\n\t\t\t\tsourceName: key,\n\t\t\t\tvalue,\n\t\t\t\tstyle: options.style,\n\t\t\t\tstyleSpec,\n\t\t\t\tvalidateSpec\n\t\t\t});\n\t\t\treturn errors;\n\t\tcase \"geojson\":\n\t\t\terrors = validateObject({\n\t\t\t\tkey,\n\t\t\t\tvalue,\n\t\t\t\tvalueSpec: styleSpec.source_geojson,\n\t\t\t\tstyle,\n\t\t\t\tstyleSpec,\n\t\t\t\tvalidateSpec,\n\t\t\t\tobjectElementValidators\n\t\t\t});\n\t\t\tif (value.cluster) for (const prop in value.clusterProperties) {\n\t\t\t\tconst [operator, mapExpr] = value.clusterProperties[prop];\n\t\t\t\tconst reduceExpr = typeof operator === \"string\" ? [\n\t\t\t\t\toperator,\n\t\t\t\t\t[\"accumulated\"],\n\t\t\t\t\t[\"get\", prop]\n\t\t\t\t] : operator;\n\t\t\t\terrors.push(...validateExpression({\n\t\t\t\t\tkey: `${key}.${prop}.map`,\n\t\t\t\t\tvalue: mapExpr,\n\t\t\t\t\tvalidateSpec,\n\t\t\t\t\texpressionContext: \"cluster-map\"\n\t\t\t\t}));\n\t\t\t\terrors.push(...validateExpression({\n\t\t\t\t\tkey: `${key}.${prop}.reduce`,\n\t\t\t\t\tvalue: reduceExpr,\n\t\t\t\t\tvalidateSpec,\n\t\t\t\t\texpressionContext: \"cluster-reduce\"\n\t\t\t\t}));\n\t\t\t}\n\t\t\treturn errors;\n\t\tcase \"video\": return validateObject({\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\tvalueSpec: styleSpec.source_video,\n\t\t\tstyle,\n\t\t\tvalidateSpec,\n\t\t\tstyleSpec\n\t\t});\n\t\tcase \"image\": return validateObject({\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\tvalueSpec: styleSpec.source_image,\n\t\t\tstyle,\n\t\t\tvalidateSpec,\n\t\t\tstyleSpec\n\t\t});\n\t\tcase \"canvas\": return [new ValidationError(key, null, \"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.\", \"source.canvas\")];\n\t\tdefault: return validateEnum({\n\t\t\tkey: `${key}.type`,\n\t\t\tvalue: value.type,\n\t\t\tvalueSpec: { values: [\n\t\t\t\t\"vector\",\n\t\t\t\t\"raster\",\n\t\t\t\t\"raster-dem\",\n\t\t\t\t\"geojson\",\n\t\t\t\t\"video\",\n\t\t\t\t\"image\"\n\t\t\t] },\n\t\t\tstyle,\n\t\t\tvalidateSpec,\n\t\t\tstyleSpec\n\t\t});\n\t}\n}\nfunction validatePromoteId({ key, value }) {\n\tif (getType(value) === \"string\") return validateString({\n\t\tkey,\n\t\tvalue\n\t});\n\telse {\n\t\tconst errors = [];\n\t\tfor (const prop in value) errors.push(...validateString({\n\t\t\tkey: `${key}.${prop}`,\n\t\t\tvalue: value[prop]\n\t\t}));\n\t\treturn errors;\n\t}\n}\nexport { validateSource };\n\n//# sourceMappingURL=validate_source.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { transitionPropertyRegExp } from \"../util/properties.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_light.ts\nfunction validateLight(options) {\n\tconst light = options.value;\n\tconst styleSpec = options.styleSpec;\n\tconst lightSpec = styleSpec.light;\n\tconst style = options.style;\n\tlet errors = [];\n\tconst rootType = getType(light);\n\tif (light === void 0) return errors;\n\telse if (rootType !== \"object\") {\n\t\terrors = errors.concat([new ValidationError(\"light\", light, `object expected, ${rootType} found`)]);\n\t\treturn errors;\n\t}\n\tfor (const key in light) {\n\t\tconst transitionMatch = key.match(transitionPropertyRegExp);\n\t\tif (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) errors = errors.concat(options.validateSpec({\n\t\t\tkey,\n\t\t\tvalue: light[key],\n\t\t\tvalueSpec: styleSpec.transition,\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tstyle,\n\t\t\tstyleSpec\n\t\t}));\n\t\telse if (lightSpec[key]) errors = errors.concat(options.validateSpec({\n\t\t\tkey,\n\t\t\tvalue: light[key],\n\t\t\tvalueSpec: lightSpec[key],\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tstyle,\n\t\t\tstyleSpec\n\t\t}));\n\t\telse errors = errors.concat([new ValidationError(key, light[key], `unknown property \"${key}\"`)]);\n\t}\n\treturn errors;\n}\nexport { validateLight };\n\n//# sourceMappingURL=validate_light.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { transitionPropertyRegExp } from \"../util/properties.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_sky.ts\nfunction validateSky(options) {\n\tconst sky = options.value;\n\tconst styleSpec = options.styleSpec;\n\tconst skySpec = styleSpec.sky;\n\tconst style = options.style;\n\tconst rootType = getType(sky);\n\tif (sky === void 0) return [];\n\telse if (rootType !== \"object\") return [new ValidationError(\"sky\", sky, `object expected, ${rootType} found`)];\n\tlet errors = [];\n\tfor (const key in sky) {\n\t\tconst transitionMatch = key.match(transitionPropertyRegExp);\n\t\tif (transitionMatch && skySpec[transitionMatch[1]] && skySpec[transitionMatch[1]].transition) errors = errors.concat(options.validateSpec({\n\t\t\tkey,\n\t\t\tvalue: sky[key],\n\t\t\tvalueSpec: styleSpec.transition,\n\t\t\tstyle,\n\t\t\tstyleSpec\n\t\t}));\n\t\telse if (skySpec[key]) errors = errors.concat(options.validateSpec({\n\t\t\tkey,\n\t\t\tvalue: sky[key],\n\t\t\tvalueSpec: skySpec[key],\n\t\t\tstyle,\n\t\t\tstyleSpec\n\t\t}));\n\t\telse errors = errors.concat([new ValidationError(key, sky[key], `unknown property \"${key}\"`)]);\n\t}\n\treturn errors;\n}\nexport { validateSky };\n\n//# sourceMappingURL=validate_sky.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_terrain.ts\nfunction validateTerrain(options) {\n\tconst terrain = options.value;\n\tconst styleSpec = options.styleSpec;\n\tconst terrainSpec = styleSpec.terrain;\n\tconst style = options.style;\n\tlet errors = [];\n\tconst rootType = getType(terrain);\n\tif (terrain === void 0) return errors;\n\telse if (rootType !== \"object\") {\n\t\terrors = errors.concat([new ValidationError(\"terrain\", terrain, `object expected, ${rootType} found`)]);\n\t\treturn errors;\n\t}\n\tfor (const key in terrain) if (terrainSpec[key]) errors = errors.concat(options.validateSpec({\n\t\tkey,\n\t\tvalue: terrain[key],\n\t\tvalueSpec: terrainSpec[key],\n\t\tvalidateSpec: options.validateSpec,\n\t\tstyle,\n\t\tstyleSpec\n\t}));\n\telse errors = errors.concat([new ValidationError(key, terrain[key], `unknown property \"${key}\"`)]);\n\treturn errors;\n}\nexport { validateTerrain };\n\n//# sourceMappingURL=validate_terrain.mjs.map", "import { validateExpression } from \"./validate_expression.mjs\";\nimport { validateString } from \"./validate_string.mjs\";\n// src/validate/validate_formatted.ts\nfunction validateFormatted(options) {\n\tif (validateString(options).length === 0) return [];\n\treturn validateExpression(options);\n}\nexport { validateFormatted };\n\n//# sourceMappingURL=validate_formatted.mjs.map", "import { validateExpression } from \"./validate_expression.mjs\";\nimport { validateString } from \"./validate_string.mjs\";\n// src/validate/validate_image.ts\nfunction validateImage(options) {\n\tif (validateString(options).length === 0) return [];\n\treturn validateExpression(options);\n}\nexport { validateImage };\n\n//# sourceMappingURL=validate_image.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { validateNumber } from \"./validate_number.mjs\";\n// src/validate/validate_padding.ts\nfunction validatePadding(options) {\n\tconst key = options.key;\n\tconst value = options.value;\n\tif (getType(value) === \"array\") {\n\t\tif (value.length < 1 || value.length > 4) return [new ValidationError(key, value, `padding requires 1 to 4 values; ${value.length} values found`)];\n\t\tconst arrayElementSpec = { type: \"number\" };\n\t\tlet errors = [];\n\t\tfor (let i = 0; i < value.length; i++) errors = errors.concat(options.validateSpec({\n\t\t\tkey: `${key}[${i}]`,\n\t\t\tvalue: value[i],\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tvalueSpec: arrayElementSpec\n\t\t}));\n\t\treturn errors;\n\t} else return validateNumber({\n\t\tkey,\n\t\tvalue,\n\t\tvalueSpec: {}\n\t});\n}\nexport { validatePadding };\n\n//# sourceMappingURL=validate_padding.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { validateNumber } from \"./validate_number.mjs\";\n// src/validate/validate_number_array.ts\nfunction validateNumberArray(options) {\n\tconst key = options.key;\n\tconst value = options.value;\n\tif (getType(value) === \"array\") {\n\t\tconst arrayElementSpec = { type: \"number\" };\n\t\tif (value.length < 1) return [new ValidationError(key, value, \"array length at least 1 expected, length 0 found\")];\n\t\tlet errors = [];\n\t\tfor (let i = 0; i < value.length; i++) errors = errors.concat(options.validateSpec({\n\t\t\tkey: `${key}[${i}]`,\n\t\t\tvalue: value[i],\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tvalueSpec: arrayElementSpec\n\t\t}));\n\t\treturn errors;\n\t} else return validateNumber({\n\t\tkey,\n\t\tvalue,\n\t\tvalueSpec: {}\n\t});\n}\nexport { validateNumberArray };\n\n//# sourceMappingURL=validate_number_array.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { validateColor } from \"./validate_color.mjs\";\n// src/validate/validate_color_array.ts\nfunction validateColorArray(options) {\n\tconst key = options.key;\n\tconst value = options.value;\n\tif (getType(value) === \"array\") {\n\t\tif (value.length < 1) return [new ValidationError(key, value, \"array length at least 1 expected, length 0 found\")];\n\t\tlet errors = [];\n\t\tfor (let i = 0; i < value.length; i++) errors = errors.concat(validateColor({\n\t\t\tkey: `${key}[${i}]`,\n\t\t\tvalue: value[i],\n\t\t\tvalueSpec: {}\n\t\t}));\n\t\treturn errors;\n\t} else return validateColor({\n\t\tkey,\n\t\tvalue,\n\t\tvalueSpec: {}\n\t});\n}\nexport { validateColorArray };\n\n//# sourceMappingURL=validate_color_array.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { validateArray } from \"./validate_array.mjs\";\nimport { validateEnum } from \"./validate_enum.mjs\";\n// src/validate/validate_variable_anchor_offset_collection.ts\nfunction validateVariableAnchorOffsetCollection(options) {\n\tconst key = options.key;\n\tconst value = options.value;\n\tconst type = getType(value);\n\tconst styleSpec = options.styleSpec;\n\tif (type !== \"array\" || value.length < 1 || value.length % 2 !== 0) return [new ValidationError(key, value, \"variableAnchorOffsetCollection requires a non-empty array of even length\")];\n\tlet errors = [];\n\tfor (let i = 0; i < value.length; i += 2) {\n\t\terrors = errors.concat(validateEnum({\n\t\t\tkey: `${key}[${i}]`,\n\t\t\tvalue: value[i],\n\t\t\tvalueSpec: styleSpec[\"layout_symbol\"][\"text-anchor\"]\n\t\t}));\n\t\terrors = errors.concat(validateArray({\n\t\t\tkey: `${key}[${i + 1}]`,\n\t\t\tvalue: value[i + 1],\n\t\t\tvalueSpec: {\n\t\t\t\tlength: 2,\n\t\t\t\tvalue: \"number\"\n\t\t\t},\n\t\t\tvalidateSpec: options.validateSpec,\n\t\t\tstyle: options.style,\n\t\t\tstyleSpec\n\t\t}));\n\t}\n\treturn errors;\n}\nexport { validateVariableAnchorOffsetCollection };\n\n//# sourceMappingURL=validate_variable_anchor_offset_collection.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { validateObject } from \"./validate_object.mjs\";\nimport { validateString } from \"./validate_string.mjs\";\n// src/validate/validate_sprite.ts\nfunction validateSprite(options) {\n\tlet errors = [];\n\tconst sprite = options.value;\n\tconst key = options.key;\n\tif (!Array.isArray(sprite)) return validateString({\n\t\tkey,\n\t\tvalue: sprite\n\t});\n\telse {\n\t\tconst allSpriteIds = [];\n\t\tconst allSpriteURLs = [];\n\t\tfor (const i in sprite) {\n\t\t\tif (sprite[i].id && allSpriteIds.includes(sprite[i].id)) errors.push(new ValidationError(key, sprite, `all the sprites' ids must be unique, but ${sprite[i].id} is duplicated`));\n\t\t\tallSpriteIds.push(sprite[i].id);\n\t\t\tif (sprite[i].url && allSpriteURLs.includes(sprite[i].url)) errors.push(new ValidationError(key, sprite, `all the sprites' URLs must be unique, but ${sprite[i].url} is duplicated`));\n\t\t\tallSpriteURLs.push(sprite[i].url);\n\t\t\terrors = errors.concat(validateObject({\n\t\t\t\tkey: `${key}[${i}]`,\n\t\t\t\tvalue: sprite[i],\n\t\t\t\tvalueSpec: {\n\t\t\t\t\tid: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\trequired: true\n\t\t\t\t\t},\n\t\t\t\t\turl: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\trequired: true\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tvalidateSpec: options.validateSpec\n\t\t\t}));\n\t\t}\n\t\treturn errors;\n\t}\n}\nexport { validateSprite };\n\n//# sourceMappingURL=validate_sprite.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_projection.ts\nfunction validateProjection(options) {\n\tconst projection = options.value;\n\tconst styleSpec = options.styleSpec;\n\tconst projectionSpec = styleSpec.projection;\n\tconst style = options.style;\n\tconst rootType = getType(projection);\n\tif (projection === void 0) return [];\n\telse if (rootType !== \"object\") return [new ValidationError(\"projection\", projection, `object expected, ${rootType} found`)];\n\tlet errors = [];\n\tfor (const key in projection) if (projectionSpec[key]) errors = errors.concat(options.validateSpec({\n\t\tkey,\n\t\tvalue: projection[key],\n\t\tvalueSpec: projectionSpec[key],\n\t\tstyle,\n\t\tstyleSpec\n\t}));\n\telse errors = errors.concat([new ValidationError(key, projection[key], `unknown property \"${key}\"`)]);\n\treturn errors;\n}\nexport { validateProjection };\n\n//# sourceMappingURL=validate_projection.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\n// src/validate/validate_projectiondefinition.ts\nfunction validateProjectionDefinition(options) {\n\tconst key = options.key;\n\tlet value = options.value;\n\tvalue = value instanceof String ? value.valueOf() : value;\n\tconst type = getType(value);\n\tif (type === \"array\" && !isProjectionDefinitionValue(value) && !isPropertyValueSpecification(value)) return [new ValidationError(key, value, `projection expected, invalid array ${JSON.stringify(value)} found`)];\n\telse if (![\"array\", \"string\"].includes(type)) return [new ValidationError(key, value, `projection expected, invalid type \"${type}\" found`)];\n\treturn [];\n}\nfunction isPropertyValueSpecification(value) {\n\tif ([\n\t\t\"interpolate\",\n\t\t\"step\",\n\t\t\"literal\"\n\t].includes(value[0])) return true;\n\treturn false;\n}\nfunction isProjectionDefinitionValue(value) {\n\treturn Array.isArray(value) && value.length === 3 && typeof value[0] === \"string\" && typeof value[1] === \"string\" && typeof value[2] === \"number\";\n}\nexport { validateProjectionDefinition };\n\n//# sourceMappingURL=validate_projectiondefinition.mjs.map", "// src/util/is_object_literal.ts\nfunction isObjectLiteral(anything) {\n\treturn Boolean(anything) && anything.constructor === Object;\n}\nexport { isObjectLiteral };\n\n//# sourceMappingURL=is_object_literal.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { isObjectLiteral } from \"../util/is_object_literal.mjs\";\n// src/validate/validate_state.ts\nfunction validateState(options) {\n\tif (!isObjectLiteral(options.value)) return [new ValidationError(options.key, options.value, `object expected, ${getType(options.value)} found`)];\n\treturn [];\n}\nexport { validateState };\n\n//# sourceMappingURL=validate_state.mjs.map", "import v8_default from \"../reference/v8.mjs\";\nimport { ValidationError } from \"../error/validation_error.mjs\";\nimport { getType } from \"../util/get_type.mjs\";\nimport { validateObject } from \"./validate_object.mjs\";\nimport { validateString } from \"./validate_string.mjs\";\nimport { isObjectLiteral } from \"../util/is_object_literal.mjs\";\n// src/validate/validate_font_faces.ts\nconst MAX_CODE_POINT = 1114111;\n/**\n* A single unicode range, as described by the [CSS descriptor with the same name](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range):\n* a single code point (`U+26`), a range of code points (`U+0-7F`) or a wildcard range (`U+4??`).\n* At most six hexadecimal digits are allowed on either side.\n*/\nconst UNICODE_RANGE_REGEX = /^u\\+(?:([0-9a-f]{1,6})(?:-([0-9a-f]{1,6}))?|([0-9a-f]{0,5}\\?{1,6}))$/i;\nfunction validateUnicodeRange(key, value) {\n\tif (getType(value) !== \"string\") return [];\n\tconst range = `${value}`;\n\tconst invalid = () => [new ValidationError(key, value, `invalid unicode range, expected a value such as \"U+26\", \"U+0-10FFFF\" or \"U+4??\"`)];\n\tconst match = range.match(UNICODE_RANGE_REGEX);\n\tif (!match) return invalid();\n\tconst [, start, end, wildcard] = match;\n\tif (wildcard !== void 0) return wildcard.length > 6 ? invalid() : [];\n\tconst startCodePoint = parseInt(start, 16);\n\tconst endCodePoint = end === void 0 ? startCodePoint : parseInt(end, 16);\n\tif (startCodePoint > MAX_CODE_POINT || endCodePoint > MAX_CODE_POINT) return [new ValidationError(key, value, `unicode range is out of bounds, the maximum code point is U+10FFFF`)];\n\tif (startCodePoint > endCodePoint) return [new ValidationError(key, value, `unicode range start must not be greater than its end, but ${range} is`)];\n\treturn [];\n}\nfunction validateFontFaces(options) {\n\tconst key = options.key ?? \"font-faces\";\n\tconst value = options.value;\n\tconst validateSpec = options.validateSpec;\n\tconst styleSpec = options.styleSpec ?? v8_default;\n\tconst style = options.style;\n\tif (!isObjectLiteral(value)) return [new ValidationError(key, value, `object expected, ${getType(value)} found`)];\n\tconst errors = [];\n\tfor (const fontName in value) {\n\t\tconst fontValue = value[fontName];\n\t\tconst fontValueType = getType(fontValue);\n\t\tif (fontValueType === \"string\") errors.push(...validateString({\n\t\t\tkey: `${key}.${fontName}`,\n\t\t\tvalue: fontValue\n\t\t}));\n\t\telse if (fontValueType === \"array\") {\n\t\t\tconst fontFaceSpec = {\n\t\t\t\turl: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true\n\t\t\t\t},\n\t\t\t\t\"unicode-range\": {\n\t\t\t\t\ttype: \"array\",\n\t\t\t\t\tvalue: \"string\"\n\t\t\t\t}\n\t\t\t};\n\t\t\tfor (const [i, fontFace] of fontValue.entries()) {\n\t\t\t\tconst fontFaceKey = `${key}.${fontName}[${i}]`;\n\t\t\t\terrors.push(...validateObject({\n\t\t\t\t\tkey: fontFaceKey,\n\t\t\t\t\tvalue: fontFace,\n\t\t\t\t\tvalueSpec: fontFaceSpec,\n\t\t\t\t\tstyleSpec,\n\t\t\t\t\tstyle,\n\t\t\t\t\tvalidateSpec\n\t\t\t\t}));\n\t\t\t\tconst unicodeRanges = isObjectLiteral(fontFace) ? fontFace[\"unicode-range\"] : void 0;\n\t\t\t\tif (getType(unicodeRanges) !== \"array\") continue;\n\t\t\t\tfor (const [j, unicodeRange] of unicodeRanges.entries()) errors.push(...validateUnicodeRange(`${fontFaceKey}.unicode-range[${j}]`, unicodeRange));\n\t\t\t}\n\t\t} else errors.push(new ValidationError(`${key}.${fontName}`, fontValue, `string or array expected, ${fontValueType} found`));\n\t}\n\treturn errors;\n}\nexport { validateFontFaces };\n\n//# sourceMappingURL=validate_font_faces.mjs.map", "import { extendBy } from \"../util/extend.mjs\";\nimport { isFunction } from \"../function/index.mjs\";\nimport { isExpression } from \"../expression/index.mjs\";\nimport { validateConstants } from \"./validate_constants.mjs\";\nimport { deepUnbundle, unbundle } from \"../util/unbundle_jsonlint.mjs\";\nimport { validateObject } from \"./validate_object.mjs\";\nimport { validateArray } from \"./validate_array.mjs\";\nimport { validateNumber } from \"./validate_number.mjs\";\nimport { validateFunction } from \"./validate_function.mjs\";\nimport { validateExpression } from \"./validate_expression.mjs\";\nimport { validateBoolean } from \"./validate_boolean.mjs\";\nimport { validateColor } from \"./validate_color.mjs\";\nimport { validateEnum } from \"./validate_enum.mjs\";\nimport { validateFilter } from \"./validate_filter.mjs\";\nimport { validateLayer } from \"./validate_layer.mjs\";\nimport { validateString } from \"./validate_string.mjs\";\nimport { validateSource } from \"./validate_source.mjs\";\nimport { validateLight } from \"./validate_light.mjs\";\nimport { validateSky } from \"./validate_sky.mjs\";\nimport { validateTerrain } from \"./validate_terrain.mjs\";\nimport { validateFormatted } from \"./validate_formatted.mjs\";\nimport { validateImage } from \"./validate_image.mjs\";\nimport { validatePadding } from \"./validate_padding.mjs\";\nimport { validateNumberArray } from \"./validate_number_array.mjs\";\nimport { validateColorArray } from \"./validate_color_array.mjs\";\nimport { validateVariableAnchorOffsetCollection } from \"./validate_variable_anchor_offset_collection.mjs\";\nimport { validateSprite } from \"./validate_sprite.mjs\";\nimport { validateProjection } from \"./validate_projection.mjs\";\nimport { validateProjectionDefinition } from \"./validate_projectiondefinition.mjs\";\nimport { validateState } from \"./validate_state.mjs\";\nimport { validateFontFaces } from \"./validate_font_faces.mjs\";\n// src/validate/validate.ts\nconst VALIDATORS = {\n\t\"*\"() {\n\t\treturn [];\n\t},\n\tarray: validateArray,\n\tboolean: validateBoolean,\n\tnumber: validateNumber,\n\tcolor: validateColor,\n\tconstants: validateConstants,\n\tenum: validateEnum,\n\tfilter: validateFilter,\n\tfunction: validateFunction,\n\tlayer: validateLayer,\n\tobject: validateObject,\n\tsource: validateSource,\n\tlight: validateLight,\n\tsky: validateSky,\n\tterrain: validateTerrain,\n\tprojection: validateProjection,\n\tprojectionDefinition: validateProjectionDefinition,\n\tstring: validateString,\n\tformatted: validateFormatted,\n\tresolvedImage: validateImage,\n\tpadding: validatePadding,\n\tnumberArray: validateNumberArray,\n\tcolorArray: validateColorArray,\n\tvariableAnchorOffsetCollection: validateVariableAnchorOffsetCollection,\n\tsprite: validateSprite,\n\tstate: validateState,\n\tfontFaces: validateFontFaces\n};\n/**\n* Main recursive validation function used internally.\n* You should use `validateStyleMin` in the browser or `validateStyle` in node env.\n* @param options - the options object\n* @param options.key - string representing location of validation in style tree. Used only\n* for more informative error reporting.\n* @param options.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* @param options.valueSpec - current spec being evaluated. Tracks value.\n* @param options.styleSpec - current full spec being evaluated.\n* @param options.validateSpec - the validate function itself\n* @param options.style - the style object\n* @param options.objectElementValidators - optional object of functions that will be called\n* @returns an array of errors, or an empty array if no errors are found.\n*/\nfunction validate(options) {\n\tconst value = options.value;\n\tconst valueSpec = options.valueSpec;\n\tconst styleSpec = options.styleSpec;\n\toptions.validateSpec = validate;\n\tif (valueSpec.expression && isFunction(unbundle(value))) return validateFunction(options);\n\telse if (valueSpec.expression && isExpression(deepUnbundle(value))) return validateExpression(options);\n\telse if (valueSpec.type && VALIDATORS[valueSpec.type]) return VALIDATORS[valueSpec.type](options);\n\telse return validateObject(extendBy({}, options, { valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec }));\n}\nexport { validate };\n\n//# sourceMappingURL=validate.mjs.map", "import { ValidationError } from \"../error/validation_error.mjs\";\nimport { validateString } from \"./validate_string.mjs\";\n// src/validate/validate_glyphs_url.ts\nfunction validateGlyphsUrl(options) {\n\tconst value = options.value;\n\tconst key = options.key;\n\tconst errors = validateString(options);\n\tif (errors.length) return errors;\n\tif (value.indexOf(\"{fontstack}\") === -1) errors.push(new ValidationError(key, value, \"\\\"glyphs\\\" url must include a \\\"{fontstack}\\\" token\"));\n\tif (value.indexOf(\"{range}\") === -1) errors.push(new ValidationError(key, value, \"\\\"glyphs\\\" url must include a \\\"{range}\\\" token\"));\n\treturn errors;\n}\nexport { validateGlyphsUrl };\n\n//# sourceMappingURL=validate_glyphs_url.mjs.map", "import { latest } from \"./reference/latest.mjs\";\nimport { validateConstants } from \"./validate/validate_constants.mjs\";\nimport { validateFilter } from \"./validate/validate_filter.mjs\";\nimport { validatePaintProperty } from \"./validate/validate_paint_property.mjs\";\nimport { validateLayoutProperty } from \"./validate/validate_layout_property.mjs\";\nimport { validateLayer } from \"./validate/validate_layer.mjs\";\nimport { validateSource } from \"./validate/validate_source.mjs\";\nimport { validateLight } from \"./validate/validate_light.mjs\";\nimport { validateSky } from \"./validate/validate_sky.mjs\";\nimport { validateTerrain } from \"./validate/validate_terrain.mjs\";\nimport { validateSprite } from \"./validate/validate_sprite.mjs\";\nimport { validateState } from \"./validate/validate_state.mjs\";\nimport { validateFontFaces } from \"./validate/validate_font_faces.mjs\";\nimport { validate } from \"./validate/validate.mjs\";\nimport { validateGlyphsUrl } from \"./validate/validate_glyphs_url.mjs\";\n// src/validate_style.min.ts\n/**\n* Validate a MapLibre style against the style specification.\n* Use this when running in the browser.\n*\n* @param style - The style to be validated.\n* @param styleSpec - The style specification to validate against.\n* If omitted, the latest style spec is used.\n* @returns an array of errors, or an empty array if no errors are found.\n* @example\n*   const validate = require('@maplibre/maplibre-gl-style-spec/').validateStyleMin;\n*   const errors = validate(style);\n*/\nfunction validateStyleMin(style, styleSpec = latest) {\n\tlet errors = [];\n\terrors = errors.concat(validate({\n\t\tkey: \"\",\n\t\tvalue: style,\n\t\tvalueSpec: styleSpec.$root,\n\t\tstyleSpec,\n\t\tstyle,\n\t\tvalidateSpec: validate,\n\t\tobjectElementValidators: {\n\t\t\tglyphs: validateGlyphsUrl,\n\t\t\t\"*\"() {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\t}));\n\tif (style[\"constants\"]) errors = errors.concat(validateConstants({\n\t\tkey: \"constants\",\n\t\tvalue: style[\"constants\"],\n\t\tstyle,\n\t\tstyleSpec,\n\t\tvalidateSpec: validate\n\t}));\n\treturn sortErrors(errors);\n}\nvalidateStyleMin.source = wrapCleanErrors(injectValidateSpec(validateSource));\nvalidateStyleMin.sprite = wrapCleanErrors(injectValidateSpec(validateSprite));\nvalidateStyleMin.glyphs = wrapCleanErrors(injectValidateSpec(validateGlyphsUrl));\nvalidateStyleMin.fontFaces = wrapCleanErrors(injectValidateSpec(validateFontFaces));\nvalidateStyleMin.light = wrapCleanErrors(injectValidateSpec(validateLight));\nvalidateStyleMin.sky = wrapCleanErrors(injectValidateSpec(validateSky));\nvalidateStyleMin.terrain = wrapCleanErrors(injectValidateSpec(validateTerrain));\nvalidateStyleMin.state = wrapCleanErrors(injectValidateSpec(validateState));\nvalidateStyleMin.layer = wrapCleanErrors(injectValidateSpec(validateLayer));\nvalidateStyleMin.filter = wrapCleanErrors(injectValidateSpec(validateFilter));\nvalidateStyleMin.paintProperty = wrapCleanErrors(injectValidateSpec(validatePaintProperty));\nvalidateStyleMin.layoutProperty = wrapCleanErrors(injectValidateSpec(validateLayoutProperty));\nfunction injectValidateSpec(validator) {\n\treturn function(options) {\n\t\treturn validator(Object.assign({}, options, { validateSpec: validate }));\n\t};\n}\nfunction sortErrors(errors) {\n\treturn [].concat(errors).sort((a, b) => {\n\t\treturn a.line - b.line;\n\t});\n}\nfunction wrapCleanErrors(inner) {\n\treturn function(...args) {\n\t\treturn sortErrors(inner.apply(this, args));\n\t};\n}\nexport { validateStyleMin };\n\n//# sourceMappingURL=validate_style.min.mjs.map", "import { createExpression, findGlobalStateRefs } from \"./index.mjs\";\n// src/expression/visibility.ts\nconst visibilitySpec = {\n\ttype: \"enum\",\n\t\"property-type\": \"data-constant\",\n\texpression: {\n\t\tinterpolated: false,\n\t\tparameters: [\"global-state\"]\n\t},\n\tvalues: {\n\t\tvisible: {},\n\t\tnone: {}\n\t},\n\ttransition: false,\n\tdefault: \"visible\"\n};\nvar VisibilityExpressionClass = class {\n\tconstructor(visibility, rootKey, globalState) {\n\t\tthis._rootKey = rootKey;\n\t\tthis._globalState = globalState;\n\t\tthis.setValue(visibility);\n\t}\n\tevaluate() {\n\t\treturn this._literalValue ?? this._compiledValue.evaluate({});\n\t}\n\tsetValue(visibility) {\n\t\tif (visibility === null || visibility === void 0 || visibility === \"visible\" || visibility === \"none\") {\n\t\t\tthis._literalValue = visibility === \"none\" ? \"none\" : \"visible\";\n\t\t\tthis._compiledValue = void 0;\n\t\t\tthis._globalStateRefs = /* @__PURE__ */ new Set();\n\t\t\treturn;\n\t\t}\n\t\tconst compiled = createExpression(visibility, this._rootKey, visibilitySpec, this._globalState);\n\t\tif (compiled.result === \"error\") {\n\t\t\tthis._literalValue = \"visible\";\n\t\t\tthis._compiledValue = void 0;\n\t\t\tthrow new Error(compiled.value.map((err) => `${err.key}: ${err.message}`).join(\", \"));\n\t\t}\n\t\tthis._literalValue = void 0;\n\t\tthis._compiledValue = compiled.value;\n\t\tthis._globalStateRefs = findGlobalStateRefs(compiled.value.expression);\n\t}\n\tgetGlobalStateRefs() {\n\t\treturn this._globalStateRefs;\n\t}\n};\n/**\n* Creates a visibility expression from a visibility specification.\n* @param visibility - the visibility specification, literal or expression\n* @param rootKey - location of the visibility value in the style JSON\n* (e.g. `layers[3].layout.visibility`), used to prefix runtime warnings\n* @param globalState - the global state object\n* @returns visibility expression object\n*/\nfunction createVisibility(visibility, rootKey, globalState) {\n\treturn new VisibilityExpressionClass(visibility, rootKey, globalState);\n}\nexport { createVisibility as default };\n\n//# sourceMappingURL=visibility.mjs.map", "import {TransferableGridIndex} from './transferable_grid_index.ts';\nimport {Color, CompoundExpression, expressions, ResolvedImage, StylePropertyFunction,\n    StyleExpression, ZoomDependentExpression, ZoomConstantExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {AJAXError} from './ajax.ts';\nimport {isImageBitmap} from './util.ts';\n\n/**\n * A class that is serialized to and json, that can be constructed back to the original class in the worker or in the main thread\n */\ntype SerializedObject<S extends Serialized = any> = {\n    [_: string]: S;\n};\n\n/**\n * All the possible values that can be serialized and sent to and from the worker\n */\nexport type Serialized = null | void | boolean | number | string | Boolean | Number | String | Date | RegExp | ArrayBuffer | ArrayBufferView | ImageData | ImageBitmap | Blob | Serialized[] | SerializedObject;\n\ntype Registry = {\n    [_: string]: {\n        klass: {\n            new (...args: any): any;\n            deserialize?: (input: Serialized) => unknown;\n            serialize?: (input: any, transferables: Transferable[]) => SerializedObject;\n        };\n        omit: readonly string[];\n        shallow: readonly string[];\n    };\n};\n\n/**\n * Register options\n */\ntype RegisterOptions<T> = {\n    /**\n     * List of properties to omit from serialization (e.g., cached/computed properties)\n     */\n    omit?: ReadonlyArray<keyof T>;\n    /**\n     * List of properties that should be serialized by a simple shallow copy, rather than by a recursive call to serialize().\n     */\n    shallow?: ReadonlyArray<keyof T>;\n};\n\nconst registry: Registry = {};\n\n/**\n * Register the given class as serializable.\n *\n * @param options - the registration options\n */\nexport function register<T extends any>(\n    name: string,\n    klass: {\n        new (...args: any): T;\n    },\n    options: RegisterOptions<T> = {}\n): void {\n    if (registry[name]) throw new Error(`${name} is already registered.`);\n    ((Object.defineProperty as any))(klass, '_classRegistryKey', {\n        value: name,\n        writeable: false\n    });\n    registry[name] = {\n        klass,\n        omit: options.omit as readonly string[] || [],\n        shallow: options.shallow as readonly string[] || []\n    };\n}\n\nregister('Object', Object);\nregister('Set', Set);\nregister('TransferableGridIndex', TransferableGridIndex);\n\nregister('Color', Color);\nregister('Error', Error);\nregister('AJAXError', AJAXError);\nregister('ResolvedImage', ResolvedImage);\n\nregister('StylePropertyFunction', StylePropertyFunction);\nregister('StyleExpression', StyleExpression, {omit: ['_evaluator']});\n\nregister('ZoomDependentExpression', ZoomDependentExpression);\nregister('ZoomConstantExpression', ZoomConstantExpression);\nregister('CompoundExpression', CompoundExpression, {omit: ['_evaluate']});\nfor (const name in expressions) {\n    if ((expressions[name] as any)._classRegistryKey) continue;\n    register(`Expression_${name}`, expressions[name]);\n}\n\nfunction isArrayBuffer(value: any): value is ArrayBuffer {\n    return value && typeof ArrayBuffer !== 'undefined' &&\n           (value instanceof ArrayBuffer || (value.constructor?.name === 'ArrayBuffer'));\n}\n\nfunction getClassRegistryKey(input: Object|SerializedObject): string {\n    const klass = (input.constructor as any);\n    return (input as SerializedObject).$name || klass._classRegistryKey;\n}\n\nfunction isRegistered(input: unknown): boolean {\n    if (input === null || typeof input !== 'object') {\n        return false;\n    }\n    const classRegistryKey = getClassRegistryKey(input);\n    return classRegistryKey && classRegistryKey !== 'Object';\n}\n\nfunction isSerializeHandledByBuiltin(input: unknown) {\n    return (!isRegistered(input) && (\n        input === null ||\n        input === undefined ||\n        typeof input === 'boolean' ||\n        typeof input === 'number' ||\n        typeof input === 'string' ||\n        input instanceof Boolean ||\n        input instanceof Number ||\n        input instanceof String ||\n        input instanceof Date ||\n        input instanceof RegExp ||\n        input instanceof Blob ||\n        input instanceof Error ||\n        isArrayBuffer(input) ||\n        isImageBitmap(input) ||\n        ArrayBuffer.isView(input) ||\n        input instanceof ImageData)\n    );\n}\n\n/**\n * Serialize the given object for transfer to or from a web worker.\n *\n * For non-builtin types, recursively serialize each property (possibly\n * omitting certain properties - see register()), and package the result along\n * with the constructor's `name` so that the appropriate constructor can be\n * looked up in `deserialize()`.\n *\n * If a `transferables` array is provided, add any transferable objects (i.e.,\n * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed,\n * this should happen in the client code, before using serialize().)\n */\nexport function serialize(input: unknown, transferables?: Transferable[] | null): Serialized {\n    if (isSerializeHandledByBuiltin(input)) {\n        if (isArrayBuffer(input) || isImageBitmap(input)) {\n            if (transferables) {\n                transferables.push(input);\n            }\n        }\n        if (ArrayBuffer.isView(input)) {\n            if (transferables) {\n                transferables.push(input.buffer);\n            }\n        }\n        if (input instanceof ImageData) {\n            if (transferables) {\n                transferables.push(input.data.buffer);\n            }\n        }\n        return input;\n    }\n\n    if (Array.isArray(input)) {\n        const serialized: Serialized[] = [];\n        for (const item of input) {\n            serialized.push(serialize(item, transferables));\n        }\n        return serialized;\n    }\n\n    if (typeof input !== 'object') {\n        throw new Error(`can't serialize object of type ${typeof input}`);\n    }\n    const classRegistryKey = getClassRegistryKey(input);\n    if (!classRegistryKey) {\n        throw new Error(`can't serialize object of unregistered class ${input.constructor.name}`);\n    }\n    if (!registry[classRegistryKey]) throw new Error(`${classRegistryKey} is not registered.`);\n    const {klass} = registry[classRegistryKey];\n    const properties: SerializedObject = klass.serialize ?\n        // (Temporary workaround) allow a class to provide static\n        // `serialize()` and `deserialize()` methods to bypass the generic\n        // approach.\n        // This temporary workaround lets us use the generic serialization\n        // approach for objects whose members include instances of dynamic\n        // StructArray types. Once we refactor StructArray to be static,\n        // we can remove this complexity.\n        klass.serialize(input, transferables) : {};\n\n    if (!klass.serialize) {\n        for (const key in input) {\n            if (!input.hasOwnProperty(key)) continue;\n            if (registry[classRegistryKey].omit.includes(key)) continue;\n            const property = input[key];\n            if (property === undefined) continue;\n            properties[key] = registry[classRegistryKey].shallow.includes(key) ?\n                property :\n                serialize(property, transferables);\n        }\n        if (input instanceof Error) {\n            properties.message = input.message;\n        }\n    } else {\n        if (properties === transferables?.[transferables.length - 1]) {\n            throw new Error('statically serialized object won\\'t survive transfer of $name property');\n        }\n    }\n\n    if (properties.$name) {\n        throw new Error('$name property is reserved for worker serialization logic.');\n    }\n    if (classRegistryKey !== 'Object') {\n        properties.$name = classRegistryKey;\n    }\n\n    return properties;\n}\n\nexport function deserialize(input: Serialized): unknown {\n    if (isSerializeHandledByBuiltin(input)) {\n        return input;\n    }\n\n    if (Array.isArray(input)) {\n        return input.map(deserialize);\n    }\n\n    if (typeof input !== 'object') {\n        throw new Error(`can't deserialize object of type ${typeof input}`);\n    }\n    const classRegistryKey = getClassRegistryKey(input) || 'Object';\n    if (!registry[classRegistryKey]) {\n        throw new Error(`can't deserialize unregistered class ${classRegistryKey}`);\n    }\n    const {klass} = registry[classRegistryKey];\n    if (!klass) {\n        throw new Error(`can't deserialize unregistered class ${classRegistryKey}`);\n    }\n\n    if (klass.deserialize) {\n        return klass.deserialize(input);\n    }\n\n    const result = Object.create(klass.prototype);\n\n    for (const key of Object.keys(input)) {\n        if (key === '$name') continue;\n        const value = (input as SerializedObject)[key];\n        result[key] = registry[classRegistryKey].shallow.includes(key) ? value : deserialize(value);\n    }\n\n    return result;\n}\n", "/**\n * Invokes the wrapped function in a non-blocking way when trigger() is called.\n * Invocation requests are ignored until the function was actually invoked.\n * A timer backs up the message, since WebKit can close the message ports (#8780).\n */\nexport class ThrottledInvoker {\n    _channel: MessageChannel | undefined;\n    _triggered: boolean;\n    _methodToThrottle: Function;\n\n    constructor(methodToThrottle: Function) {\n        this._methodToThrottle = methodToThrottle;\n        this._triggered = false;\n        this._channel = new MessageChannel();\n        this._channel.port2.onmessage = () => this._invoke();\n    }\n\n    trigger(): void {\n        if (this._triggered) {\n            return;\n        }\n        this._triggered = true;\n        this._channel?.port1.postMessage(true);\n        setTimeout(() => this._invoke(), 0);\n    }\n\n    _invoke(): void {\n        if (!this._triggered) {\n            return;\n        }\n        this._triggered = false;\n        this._methodToThrottle();\n    }\n\n    remove(): void {\n        delete this._channel;\n        this._methodToThrottle = () => {};\n    }\n}\n", "import {type Subscription, ensureError, isWorker, subscribe} from './util.ts';\nimport {ErrorEvent, type Evented, type ErrorEventType} from './evented.ts';\nimport {AbortError} from './abort_error.ts';\nimport {serialize, deserialize, type Serialized} from './web_worker_transfer.ts';\nimport {ThrottledInvoker} from './throttled_invoker.ts';\n\nimport type {\n    MessageType,\n    ActorMessage,\n    RequestResponseMessageMap,\n} from './actor_messages.ts';\n\n/**\n * An interface to be sent to the actor in order for it to allow communication between the worker and the main thread\n */\nexport interface ActorTarget {\n    addEventListener: typeof window.addEventListener;\n    removeEventListener: typeof window.removeEventListener;\n    postMessage: typeof window.postMessage;\n    terminate?: () => void;\n}\n\n/**\n * This is used to define the parameters of the message that is sent to the worker and back\n */\ntype MessageData = {\n    id: string;\n    type: MessageType | '<cancel>' | '<response>';\n    origin: string;\n    data?: Serialized;\n    targetMapId?: string | number | null;\n    mustQueue?: boolean;\n    error?: Serialized | null;\n    sourceMapId: string | number | null;\n};\n\ntype ResolveReject = {\n    resolve: (value?: RequestResponseMessageMap[MessageType][1]) => void;\n    reject: (reason?: Error) => void;\n};\n\n/**\n * This interface allowing to substitute only the sendAsync method of the Actor class.\n */\nexport interface IActor {\n    sendAsync<T extends MessageType>(message: ActorMessage<T>, abortController?: AbortController): Promise<RequestResponseMessageMap[T][1]>;\n}\n\nexport type MessageHandler<T extends MessageType> = (mapId: string | number, params: RequestResponseMessageMap[T][0], abortController?: AbortController) => Promise<RequestResponseMessageMap[T][1]>;\n\nconst addEventDefaultOptions: AddEventListenerOptions = {once: true};\n\n/**\n * An implementation of the [Actor design pattern](https://en.wikipedia.org/wiki/Actor_model)\n * that maintains the relationship between asynchronous tasks and the objects\n * that spin them off - in this case, tasks like parsing parts of styles,\n * owned by the styles\n */\nexport class Actor implements IActor {\n    target: ActorTarget;\n    mapId: string | number | null;\n    resolveRejects: { [x: string]: ResolveReject};\n    name: string;\n    tasks: { [x: string]: MessageData };\n    taskQueue: string[];\n    abortControllers: { [x: number | string]: AbortController };\n    invoker: ThrottledInvoker;\n    globalScope: ActorTarget;\n    messageHandlers: { [K in MessageType]?: MessageHandler<K>};\n    subscription: Subscription;\n\n    /**\n     * @param target - The target\n     * @param mapId - A unique identifier for the Map instance using this Actor.\n     */\n    constructor(target: ActorTarget, mapId?: string | number) {\n        this.target = target;\n        this.mapId = mapId;\n        this.resolveRejects = {};\n        this.tasks = {};\n        this.taskQueue = [];\n        this.abortControllers = {};\n        this.messageHandlers = {};\n        this.invoker = new ThrottledInvoker(() => this.process());\n        this.subscription = subscribe(this.target, 'message', (message) => this.receive(message), false);\n        this.globalScope = isWorker(self) ? target : window;\n    }\n\n    registerMessageHandler<T extends MessageType>(type: T, handler: MessageHandler<T>): void {\n        (this.messageHandlers as Record<T, MessageHandler<T>>)[type] = handler;\n    }\n\n    unregisterMessageHandler<T extends MessageType>(type: T): void {\n        delete this.messageHandlers[type];\n    }\n\n    /**\n     * Sends a message from a main-thread map to a Worker or from a Worker back to\n     * a main-thread map instance.\n     * @param message - the message to send\n     * @param abortController - an optional AbortController to abort the request\n     * @returns a promise that will be resolved with the response data\n     */\n    sendAsync<T extends MessageType>(message: ActorMessage<T>, abortController?: AbortController): Promise<RequestResponseMessageMap[T][1]> {\n        return new Promise((resolve, reject) => {\n            // We're using a string ID instead of numbers because they are being used as object keys\n            // anyway, and thus stringified implicitly. We use random IDs because an actor may receive\n            // message from multiple other actors which could run in different execution context. A\n            // linearly increasing ID could produce collisions.\n            const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10);\n\n            const subscription =  abortController ? subscribe(abortController.signal, 'abort', () => {\n                subscription?.unsubscribe();\n                delete this.resolveRejects[id];\n                const cancelMessage: MessageData = {\n                    id,\n                    type: '<cancel>',\n                    origin: location.origin,\n                    targetMapId: message.targetMapId,\n                    sourceMapId: this.mapId\n                };\n                this.target.postMessage(cancelMessage);\n                // Reject the promise so the awaiting caller unwinds; leaving it pending kept the\n                // suspended async frame (and everything it captured) alive forever.\n                reject(new AbortError(abortController.signal.reason));\n            }, addEventDefaultOptions) : null;\n\n            this.resolveRejects[id] = {\n                resolve: (value) => {\n                    subscription?.unsubscribe();\n                    resolve(value);\n                },\n                reject: (reason) => {\n                    subscription?.unsubscribe();\n                    reject(reason);\n                }\n            };\n\n            const buffers: Transferable[] = [];\n            const messageToPost: MessageData = {\n                ...message,\n                id,\n                sourceMapId: this.mapId,\n                origin: location.origin,\n                data: serialize(message.data, buffers)\n            };\n            this.target.postMessage(messageToPost, {transfer: buffers});\n        });\n    }\n\n    receive(message: {data: MessageData}): void {\n        const data = message.data;\n        const id = data.id;\n\n        const SPECIAL_ORIGINS = ['file://', 'resource://android', 'null'];\n        const origins = [data.origin, location.origin];\n\n        const isSameOrigin = data.origin === location.origin;\n        const hasSpecialOrigin = origins.some((origin) => SPECIAL_ORIGINS.includes(origin));\n\n        // Ignore cross-origin messages except for special origins.\n        if (!isSameOrigin && !hasSpecialOrigin) {\n            return;\n        }\n        if (data.targetMapId && this.mapId !== data.targetMapId) {\n            return;\n        }\n        if (data.type === '<cancel>') {\n            // Remove the original request from the queue. This is only possible if it\n            // hasn't been kicked off yet. The id will remain in the queue, but because\n            // there is no associated task, it will be dropped once it's time to execute it.\n            delete this.tasks[id];\n            const abortController = this.abortControllers[id];\n            delete this.abortControllers[id];\n            if (abortController) {\n                abortController.abort();\n            }\n            return;\n        }\n        if (isWorker(self) || data.mustQueue) {\n            // In workers, store the tasks that we need to process before actually processing them. This\n            // is necessary because we want to keep receiving messages, and in particular,\n            // <cancel> messages. Some tasks may take a while in the worker thread, so before\n            // executing the next task in our queue, postMessage preempts this and <cancel>\n            // messages can be processed. We're using a MessageChannel object to get throttle the\n            // process() flow to one at a time.\n            this.tasks[id] = data;\n            this.taskQueue.push(id);\n            this.invoker.trigger();\n            return;\n        }\n        // In the main thread, process messages immediately so that other work does not slip in\n        // between getting partial data back from workers.\n        this.processTask(id, data);\n    }\n\n    process(): void {\n        if (this.taskQueue.length === 0) {\n            return;\n        }\n        const id = this.taskQueue.shift();\n        const task = this.tasks[id];\n        delete this.tasks[id];\n        // Schedule another process call if we know there's more to process _before_ invoking the\n        // current task. This is necessary so that processing continues even if the current task\n        // doesn't execute successfully.\n        if (this.taskQueue.length > 0) {\n            this.invoker.trigger();\n        }\n        if (!task) {\n            // If the task ID doesn't have associated task data anymore, it was canceled.\n            return;\n        }\n\n        this.processTask(id, task);\n    }\n\n    async processTask(id: string, task: MessageData): Promise<void> {\n        if (task.type === '<response>') {\n            // The `completeTask` function in the counterpart actor has been called, and we are now\n            // resolving or rejecting the promise in the originating actor, if there is one.\n            const resolveReject = this.resolveRejects[id];\n            delete this.resolveRejects[id];\n            if (!resolveReject) {\n                // If we get a response, but don't have a resolve or reject, the request was canceled.\n                return;\n            }\n            if (task.error) {\n                resolveReject.reject(ensureError(deserialize(task.error)));\n            } else {\n                resolveReject.resolve(deserialize(task.data));\n            }\n            return;\n        }\n        if (!this.messageHandlers[task.type]) {\n            // This might be the case of a custom worker code sending messages to the main thread. \n            // No need to do anything.\n            // This can be changed for debug in case there's a need to make sure all messages are being handled.\n            this.completeTask(id, null, null);\n            return;\n        }\n        const params = deserialize(task.data) as RequestResponseMessageMap[MessageType][0];\n        const abortController = new AbortController();\n        this.abortControllers[id] = abortController;\n        try {\n            const data = await this.messageHandlers[task.type](task.sourceMapId, params, abortController);\n            this.completeTask(id, null, data);\n        } catch (err) {\n            this.completeTask(id, ensureError(err));\n        }\n    }\n\n    completeTask(id: string, err: Error, data?: RequestResponseMessageMap[MessageType][1]): void {\n        const buffers: Transferable[] = [];\n        delete this.abortControllers[id];\n        const responseMessage: MessageData = {\n            id,\n            type: '<response>',\n            sourceMapId: this.mapId,\n            origin: location.origin,\n            error: err ? serialize(err) : null,\n            data: serialize(data, buffers)\n        };\n        this.target.postMessage(responseMessage, {transfer: buffers});\n    }\n\n    remove(): void {\n        this.invoker.remove();\n        this.subscription.unsubscribe();\n    }\n}\n\n/** Builds a named actor per worker and reports worker errors to `errorTarget`. */\nexport function createActors(workers: ActorTarget[], mapId: string | number, errorTarget: Evented<ErrorEventType>): {actors: Actor[]; workerErrorSubscriptions: Subscription[]} {\n    const workerErrorSubscriptions = workers.map(worker => subscribe(worker, 'error', () => {\n        errorTarget.fire(new ErrorEvent(new Error('Worker failed to load. Check that the worker URL is correct.')));\n    }, false));\n    const actors = workers.map((worker, i) => {\n        const actor = new Actor(worker, mapId);\n        actor.name = `Worker ${i}`;\n        return actor;\n    });\n    return {actors, workerErrorSubscriptions};\n}\n", "import packageJSON from '../../package.json' with {type: 'json'};\nimport {type AddProtocolAction, config} from './config.ts';\n\nimport type {default as MaplibreWorker} from '../source/worker.ts';\nimport type {WorkerSourceConstructor} from '../source/worker_source.ts';\nimport type {GetResourceResponse, RequestParameters} from './ajax.ts';\nimport type {ProjectionHandler} from '../source/projection_handler_worker.ts';\n\nexport interface WorkerGlobalScopeInterface {\n    registerWorkerSource: (sourceName: string, sourceConstructor: WorkerSourceConstructor) => void;\n    registerRTLTextPlugin: (_: any) => void;\n    addProtocol: (customProtocol: string, loadFn: AddProtocolAction) => void;\n    removeProtocol: (customProtocol: string) => void;\n    makeRequest: (request: RequestParameters, abortController: AbortController) => Promise<GetResourceResponse<any>>;\n    /**\n     * @experimental\n     * Sets the workers' `ProjectionHandler`, for GeoJSON sources on a map in a registered projection; `null` removes it.\n     */\n    setProjectionHandler: (handler: ProjectionHandler | null) => void;\n    worker: MaplibreWorker;\n}\n\nfunction isCrossOrigin(url: string): boolean {\n    if (!url) return false;\n    const loc = (globalThis as any).location;\n    if (!loc) return false;\n    try {\n        return new URL(url, loc.href).origin !== loc.origin;\n    } catch {\n        return false;\n    }\n}\n\n/**\n * The URL of the worker bundle next to this module, carrying the package version as a `v` query\n * parameter so that a browser does not serve a worker cached from an older release.\n */\nfunction defaultWorkerUrl(): string {\n    const moduleUrl = import.meta.url;\n    if (!/^https?:/.test(moduleUrl)) return '';\n    const workerName = moduleUrl.endsWith('-dev.mjs')\n        ? 'maplibre-gl-worker-dev.mjs'\n        : 'maplibre-gl-worker.mjs';\n    const url = new URL(`./${workerName}`, moduleUrl);\n    url.searchParams.set('v', packageJSON.version);\n    return url.href;\n}\n\nfunction isClassicWorkerUrl(url: string): boolean {\n    return url.endsWith('.cjs') || url.split(/[?#]/)[0].endsWith('.cjs');\n}\n\nfunction createWorker(url: string, asModule: boolean): Worker {\n    if (asModule) {\n        try {\n            return new Worker(url, {type: 'module'});\n        } catch (e) {\n            console.warn('Module worker not supported, falling back to classic worker', e);\n        }\n    }\n    return new Worker(url);\n}\n\nasync function fetchWorkerCode(url: string): Promise<string> {\n    const response = await fetch(url);\n    if (!response.ok) {\n        throw new Error(`Failed to fetch worker script (${response.status}): ${url}`);\n    }\n    return response.text();\n}\n\nasync function fetchAsBlobUrl(url: string): Promise<string> {\n    const blob = new Blob([await fetchWorkerCode(url)], {type: 'text/javascript'});\n    return URL.createObjectURL(blob);\n}\n\nfunction hasOpaqueOrigin(): boolean {\n    return globalThis.origin === 'null';\n}\n\n/**\n * On a page with an opaque origin, Chrome doesn't start a module worker from a `blob:` URL, https://issues.chromium.org/issues/40067939\n */\nasync function fetchAsDataUrl(url: string): Promise<string> {\n    return `data:text/javascript;charset=utf-8,${encodeURIComponent(await fetchWorkerCode(url))}`;\n}\n\nfunction importAsBlobUrl(url: string): string {\n    const blob = new Blob([`import ${JSON.stringify(new URL(url, import.meta.url).href)}`], {type: 'text/javascript'});\n    return URL.createObjectURL(blob);\n}\n\nexport async function workerFactory(): Promise<Worker> {\n    const url = config.WORKER_URL || defaultWorkerUrl();\n    const asModule = !isClassicWorkerUrl(url);\n\n    if (asModule && hasOpaqueOrigin()) {\n        return createWorker(await fetchAsDataUrl(url), asModule);\n    }\n\n    if (!isCrossOrigin(url)) {\n        return createWorker(url, asModule);\n    }\n\n    if (asModule) {\n        const blobUrl = importAsBlobUrl(url);\n        try {\n            return createWorker(blobUrl, asModule);\n        } finally {\n            URL.revokeObjectURL(blobUrl);\n        }\n    }\n\n    const blobUrl = await fetchAsBlobUrl(url);\n    try {\n        return createWorker(blobUrl, asModule);\n    } finally {\n        URL.revokeObjectURL(blobUrl);\n    }\n}\n", "import {workerFactory} from './web_worker.ts';\nimport {browser} from './browser.ts';\nimport {isSafari, warnOnce} from './util.ts';\nimport {Evented, type Event} from './evented.ts';\n\nimport type {ActorTarget} from './actor.ts';\n\nexport const PRELOAD_POOL_ID = 'maplibre_preloaded_worker_pool';\n\nexport type WorkerPoolEventType = {\n    /** Fires once a new set of workers exists, unless they were terminated while being created. */\n    create: Event;\n    /** Fires when the workers are dropped, before they are terminated. */\n    terminate: Event;\n    /** Fires after {@link WorkerPool.restart} replaces the workers, whose state the old ones took with them. */\n    restart: Event;\n};\n\n/**\n * Constructs a worker pool.\n */\nexport class WorkerPool extends Evented<WorkerPoolEventType> {\n    static workerCount: number;\n\n    active: {\n        [_ in number | string]: boolean;\n    };\n    private workersPromise: Promise<ActorTarget[]> | null;\n\n    constructor() {\n        super();\n        this.active = {};\n        this.workersPromise = null;\n    }\n\n    /** Claims the shared workers, creating them on the first claim. */\n    acquire(mapId: number | string): Promise<ActorTarget[]> {\n        this.active[mapId] = true;\n        return this.start();\n    }\n\n    /**\n     * Starts the shared workers if they are not running and returns them, without claiming them.\n     * The `terminate` event still fires once the last claim is released.\n     */\n    async start(): Promise<ActorTarget[]> {\n        if (this.workersPromise) return (await this.workersPromise).slice();\n\n        const promises: Array<Promise<Worker>> = [];\n        while (promises.length < WorkerPool.workerCount) {\n            promises.push(workerFactory());\n        }\n        const workersPromise = this.workersPromise = Promise.all(promises);\n        const workers = await workersPromise;\n        if (this.workersPromise === workersPromise) this.fire('create');\n        return workers.slice();\n    }\n\n    /**\n     * Terminates the shared workers and creates replacements, keeping every claim. For workers\n     * the browser killed behind the library's back. Fires `restart` once the replacements exist,\n     * so whatever held state in the old workers can send it again.\n     */\n    async restart(): Promise<void> {\n        if (!this.workersPromise) return;\n        this.terminate();\n        try {\n            await this.start();\n        } catch (error) {\n            warnOnce(`Failed to create replacement workers: ${error}`);\n            return;\n        }\n        this.fire('restart');\n    }\n\n    /** Releases a claim, terminating the workers once no claim is left. Resolves once they are terminated. */\n    async release(mapId: number | string): Promise<void> {\n        delete this.active[mapId];\n        if (this.numActive() === 0) {\n            await this.terminate();\n        }\n    }\n\n    /**\n     * Drops the current workers and fires `terminate` before returning to the caller, so nothing\n     * can reach them afterwards. Resolves once each one, still being created or not, is terminated.\n     */\n    private async terminate(): Promise<void> {\n        const promise = this.workersPromise;\n        if (!promise) return;\n        this.workersPromise = null;\n        this.fire('terminate');\n        try {\n            for (const w of await promise) {\n                w.terminate();\n            }\n        } catch (error) {\n            warnOnce(`The terminated workers were never created: ${error}`);\n        }\n    }\n\n    isStarted(): boolean {\n        return !!this.workersPromise;\n    }\n\n    isPreloaded(): boolean {\n        return !!this.active[PRELOAD_POOL_ID];\n    }\n\n    numActive(): number {\n        return Object.keys(this.active).length;\n    }\n}\n\n// Based on results from A/B testing: https://github.com/maplibre/maplibre-gl-js/pull/2354\nconst availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2);\nWorkerPool.workerCount = isSafari(globalThis) ? Math.max(Math.min(availableLogicalProcessors, 3), 1) : 1;\n", "import {WorkerPool, PRELOAD_POOL_ID} from './worker_pool.ts';\n\nlet globalWorkerPool: WorkerPool;\n\n/**\n * Creates (if necessary) and returns the single, global WorkerPool instance\n * to be shared across each Map\n */\nexport function getGlobalWorkerPool(): WorkerPool {\n    globalWorkerPool ||= new WorkerPool();\n    return globalWorkerPool;\n}\n\n/**\n * Initializes resources like WebWorkers that can be shared across maps to lower load\n * times in some situations. `setWorkerUrl()` and `setWorkerCount()`, if being\n * used, must be set before `prewarm()` is called to have an effect.\n *\n * By default, the lifecycle of these resources is managed automatically, and they are\n * lazily initialized when a Map is first created. By invoking `prewarm()`, these\n * resources will be created ahead of time, and will not be cleared when the last Map\n * is removed from the page. This allows them to be re-used by new Map instances that\n * are created later. They can be manually cleared by calling\n * `clearPrewarmedResources()`. This is only necessary if your web page remains\n * active but stops using maps altogether.\n *\n * This is primarily useful when using GL-JS maps in a single page app, wherein a user\n * would navigate between various views that can cause Map instances to constantly be\n * created and destroyed.\n *\n * @example\n * ```ts\n * prewarm()\n * ```\n */\nexport function prewarm(): void {\n    const workerPool = getGlobalWorkerPool();\n    workerPool.acquire(PRELOAD_POOL_ID);\n}\n\n/**\n * Clears up resources that have previously been created by `prewarm()`.\n * Note that this is typically not necessary. You should only call this function\n * if you expect the user of your app to not return to a Map view at any point\n * in your application.\n *\n * @example\n * ```ts\n * clearPrewarmedResources()\n * ```\n */\nexport function clearPrewarmedResources(): void {\n    const pool = globalWorkerPool;\n    if (pool) {\n        // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed.\n        if (pool.isPreloaded() && pool.numActive() === 1) {\n            pool.release(PRELOAD_POOL_ID);\n        } else {\n            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()');\n        }\n    }\n}\n", "import {createActors} from './actor.ts';\nimport {getGlobalWorkerPool} from './global_worker_pool.ts';\nimport {GLOBAL_DISPATCHER_ID, makeRequest} from './ajax.ts';\nimport {MessageType} from './actor_messages.ts';\nimport {type ErrorEvent, Evented, type Event} from './evented.ts';\nimport {warnOnce} from './util.ts';\nimport {isAbortError, throwIfAborted} from './abort_error.ts';\n\nimport type {Actor, MessageHandler} from './actor.ts';\nimport type {WorkerPool} from './worker_pool.ts';\nimport type {RequestResponseMessageMap} from './actor_messages.ts';\n\nexport type GlobalDispatcherEventType = {\n    /**\n     * Fires each time the global workers are created, including the first. Removing the last map\n     * terminates them unless `prewarm()` holds them, so a listener here is the place to restore\n     * state that lives in the workers rather than in any one map.\n     *\n     * Message handlers registered through {@link getGlobalDispatcher} and scripts loaded through\n     * {@link importScriptInWorkers} come back on their own and do not need this.\n     *\n     * @example\n     * ```ts\n     * getGlobalDispatcher().on('workerscreate', () => {\n     *     getGlobalDispatcher().broadcast('my-plugin-config', {tiles: 'https://example.com/{z}/{x}/{y}.png'});\n     * });\n     * ```\n     */\n    workerscreate: Event;\n    error: ErrorEvent;\n};\n\n/**\n * A handler for a message that is not one of the built-in {@link MessageType}s, e.g. a message that is sent by a plugin.\n */\nexport type CustomMessageHandler<TData, TResult> = (mapId: string | number, params: TData, abortController?: AbortController) => Promise<TResult>;\n\n/**\n * How long the workers get to answer a ping before they are considered terminated. The ping\n * queues ahead of tile work on return to the foreground, so the budget only needs to cover one\n * in-flight tile parse on slow hardware. A false timeout restarts healthy workers and drops map\n * state, so err on the large side.\n */\nconst PING_TIMEOUT_MS = 500;\n\n/**\n * The dispatcher shared across all map instances, see {@link getGlobalDispatcher}. Unlike a map's\n * dispatcher it never claims the workers: it builds actors for whichever workers the pool is\n * running, and discards them when the pool terminates those workers.\n */\nexport class GlobalDispatcher extends Evented<GlobalDispatcherEventType> {\n    /** Every script url {@link importScriptInWorkers} has sent, so they can be sent again to new workers. */\n    private importedScriptUrls = new Set<string>();\n    private messageHandlers: Record<string, MessageHandler<MessageType>> = {};\n    /** The actors on the pool's current workers, built on first use and cleared when those workers terminate. */\n    private actorsPromise: Promise<Actor[]> | undefined;\n    private workersAbortController: AbortController | undefined;\n    private workerPool: WorkerPool;\n    private watchingWorkers = false;\n    private ensureWorkersPromise: Promise<void> | undefined;\n\n    /**\n     * Builds actors on the pool's workers as soon as they exist, including workers started before\n     * construction, e.g. by prewarm(), so that messages the workers send find their handlers.\n     */\n    constructor(workerPool: WorkerPool) {\n        super();\n        this.workerPool = workerPool;\n        workerPool.on('create', () => this.buildActorsInBackground());\n        workerPool.on('terminate', () => this.handleWorkersTerminated());\n        if (workerPool.isStarted()) this.buildActorsInBackground();\n    }\n\n    private async buildActorsInBackground(): Promise<void> {\n        try {\n            await this.getActors();\n        } catch (error) {\n            if (!isAbortError(error)) warnOnce(`Failed to connect to the workers: ${error}`);\n        }\n    }\n\n    private handleWorkersTerminated(): void {\n        this.workersAbortController?.abort(new Error('The workers were terminated while a message was in flight.'));\n        this.actorsPromise = undefined;\n    }\n\n    /** Returns the actors on the pool's current workers, starting the workers if none are running. */\n    private getActors(): Promise<Actor[]> {\n        this.actorsPromise ??= this.buildActors();\n        return this.actorsPromise;\n    }\n\n    /**\n     * Builds an actor per worker with the registered message handlers, and sends the imported\n     * scripts ahead of anything else, so a message for a script never reaches a worker before it.\n     * Rejects with an `AbortError` if the workers terminate before they are created.\n     */\n    private async buildActors(): Promise<Actor[]> {\n        const abortController = new AbortController();\n        this.workersAbortController = abortController;\n        const workers = await this.workerPool.start();\n        throwIfAborted(abortController.signal);\n\n        const {actors, workerErrorSubscriptions} = createActors(workers, GLOBAL_DISPATCHER_ID, this);\n        abortController.signal.addEventListener('abort', () => {\n            for (const actor of actors) actor.remove();\n            for (const subscription of workerErrorSubscriptions) subscription.unsubscribe();\n        }, {once: true});\n        for (const actor of actors) {\n            for (const [type, handler] of Object.entries(this.messageHandlers)) {\n                actor.registerMessageHandler(type as MessageType, handler);\n            }\n        }\n        for (const url of this.importedScriptUrls) {\n            this.importScriptInto(actors, abortController, url);\n        }\n        this.fire('workerscreate');\n        return actors;\n    }\n\n    /** Returns the actors already built or being built, without starting any workers. */\n    private async getBuiltActors(): Promise<Actor[]> {\n        try {\n            return (await this.actorsPromise) ?? [];\n        } catch {\n            // The workers terminated first, and the next actors pick up messageHandlers.\n            return [];\n        }\n    }\n\n    private async importScriptInto(actors: Actor[], abortController: AbortController, url: string): Promise<void> {\n        try {\n            await Promise.all(actors.map(actor => actor.sendAsync({type: MessageType.importScript, data: url}, abortController)));\n        } catch (error) {\n            warnOnce(`Failed to import script ${url} into the workers: ${error}`);\n        }\n    }\n\n    /**\n     * Broadcast a message to all Workers.\n     * The type can be any string, to allow sending messages that are handled by a script that was imported using {@link importScriptInWorkers}.\n     */\n    broadcast<T extends MessageType>(type: T, data: RequestResponseMessageMap[T][0]): Promise<Array<RequestResponseMessageMap[T][1]>>;\n    broadcast<TData = any, TResult = any>(type: string, data: TData): Promise<TResult[]>;\n    async broadcast(type: string, data: any): Promise<unknown[]> {\n        const actorsPromise = this.getActors();\n        // Read before awaiting: once these workers terminate, the field holds the next workers' controller.\n        const abortController = this.workersAbortController;\n        const actors = await actorsPromise;\n        throwIfAborted(abortController.signal);\n        return Promise.all(actors.map(actor => actor.sendAsync({type: type as MessageType, data}, abortController)));\n    }\n\n    /**\n     * Registers a handler for messages that the workers send to this dispatcher.\n     * The type can be any string, to allow handling messages that are sent by a script that was imported using {@link importScriptInWorkers}.\n     */\n    registerMessageHandler<T extends MessageType>(type: T, handler: MessageHandler<T>): Promise<void>;\n    registerMessageHandler<TData = any, TResult = any>(type: string, handler: CustomMessageHandler<TData, TResult>): Promise<void>;\n    async registerMessageHandler(type: string, handler: CustomMessageHandler<any, any>): Promise<void> {\n        this.messageHandlers[type] = handler;\n        for (const actor of await this.getBuiltActors()) {\n            actor.registerMessageHandler(type as MessageType, handler);\n        }\n    }\n\n    async unregisterMessageHandler(type: MessageType | string): Promise<void> {\n        delete this.messageHandlers[type];\n        for (const actor of await this.getBuiltActors()) {\n            actor.unregisterMessageHandler(type as MessageType);\n        }\n    }\n\n    /**\n     * See {@link importScriptInWorkers}. A url may be broadcast more than once, e.g. when this\n     * call is what creates the workers; the worker runs each url only once.\n     */\n    async importScript(workerUrl: string): Promise<void> {\n        this.importedScriptUrls.add(workerUrl);\n        await this.broadcast(MessageType.importScript, workerUrl);\n    }\n\n    /**\n     * Pings the workers on every return to the foreground, restarting them if the browser\n     * terminated them while the page was hidden, as iOS does under memory pressure. Browsers fire no\n     * event for the termination, so the ping is the only way to notice it. Each map then\n     * recovers through the same contract as a lost WebGL context, see `Map._handleWorkersRestarted`.\n     */\n    watchWorkers(): void {\n        if (this.watchingWorkers || typeof document === 'undefined') return;\n        this.watchingWorkers = true;\n        document.addEventListener('visibilitychange', () => {\n            if (document.visibilityState === 'visible') this.ensureWorkers();\n        }, false);\n    }\n\n    /**\n     * Restarts the workers if they don't answer a ping, for apps that learn of a return to the\n     * foreground some other way. Calls made while a check is running share that check.\n     */\n    ensureWorkers(): Promise<void> {\n        this.ensureWorkersPromise ??= this.ensureWorkersInternal();\n        return this.ensureWorkersPromise;\n    }\n\n    private async ensureWorkersInternal(): Promise<void> {\n        try {\n            if (!await this.ping()) await this.workerPool.restart();\n        } finally {\n            this.ensureWorkersPromise = undefined;\n        }\n    }\n\n    /**\n     * Pings the workers, resolving false only on silence: any answer, even an error, proves they\n     * are alive. Resolves true when no workers exist, since there is nothing to restart.\n     */\n    async ping(timeoutMs: number = PING_TIMEOUT_MS): Promise<boolean> {\n        if (!this.workerPool.isStarted()) return true;\n        let timer: ReturnType<typeof setTimeout>;\n        try {\n            return await Promise.race([\n                this.answersPing(),\n                new Promise<boolean>((resolve) => { timer = setTimeout(() => resolve(false), timeoutMs); })\n            ]);\n        } finally {\n            clearTimeout(timer);\n        }\n    }\n\n    /** Resolves true once the workers answer a ping, whether with a result or an error. */\n    private async answersPing(): Promise<boolean> {\n        try {\n            await this.broadcast(MessageType.ping, undefined);\n        } catch {\n            // An error is still an answer.\n        }\n        return true;\n    }\n}\n\nlet globalDispatcher: GlobalDispatcher;\n\n/**\n * This function is used to get the global dispatcher that is shared across all maps instances.\n * It is used by the main thread to send messages to the workers, and by the workers to send messages back to the main thread.\n * If you import a script into the worker and need to send a message to the workers to pass some parameters for example,\n * you can use this function to get the global dispatcher and send a message to the workers.\n *\n * The same dispatcher is returned for the life of the page, so it is safe to keep, and the message\n * handlers registered on it come back on the workers that replace terminated ones. Configuration\n * you broadcast into the workers does not, so send that from a `workerscreate` listener.\n * @returns The global dispatcher instance.\n */\nexport function getGlobalDispatcher(): GlobalDispatcher {\n    if (!globalDispatcher) {\n        globalDispatcher = new GlobalDispatcher(getGlobalWorkerPool());\n        globalDispatcher.registerMessageHandler(MessageType.getResource, (_mapId, params, abortController) => {\n            return makeRequest(params, abortController);\n        });\n    }\n    return globalDispatcher;\n}\n", "import {type RequestParameters, makeRequest, sameOrigin, type GetResourceResponse} from './ajax.ts';\nimport {arrayBufferToImageBitmap, arrayBufferToImage, ensureError, extend, isWorker, isImageBitmap} from './util.ts';\nimport {config} from './config.ts';\nimport {AbortError, throwIfAborted} from './abort_error.ts';\nimport {getProtocol} from '../source/protocol_crud.ts';\n\nimport type {RequestManager, ResourceType} from './request_manager.ts';\n\ntype ImageQueueThrottleControlCallback = () => boolean;\n\nexport type ImageRequestQueueItem  = {\n    requestParameters: RequestParameters;\n    supportImageRefresh: boolean;\n    imageBitmapOptions?: ImageBitmapOptions;\n    state: 'queued' | 'running' | 'completed';\n    abortController: AbortController;\n    onError: (error: Error) => void;\n    onSuccess: (response: GetResourceResponse<HTMLImageElement | ImageBitmap | null>) => void;\n};\n\ntype ImageQueueThrottleCallbackDictionary = {\n    [Key: number]: ImageQueueThrottleControlCallback;\n};\n\ntype HTMLImageElementWithPriority = HTMLImageElement &\n{\n    // fetchPriority is experimental property supported on Chromium browsers from Version 102\n    // By default images are downloaded with priority low, whereas fetch request downloads with priority high\n    // https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority\n    fetchPriority?: 'auto' | 'high' | 'low';\n};\n\n/**\n * By default, the image queue is self driven, meaning as soon as one requested item is processed,\n * it will move on to next one as quickly as it can while limiting\n * the number of concurrent requests to MAX_PARALLEL_IMAGE_REQUESTS. The default behavior\n * ensures that static views of the map can be rendered with minimal delay.\n *\n * However, the default behavior can prevent dynamic views of the map from rendering\n * smoothly in that many requests can finish in one render frame, putting too much pressure on GPU.\n *\n * When the view of the map is moving dynamically, smoother frame rates can be achieved\n * by throttling the number of items processed by the queue per frame. This can be\n * accomplished by using {@link addThrottleControl} to allow the caller to\n * use a lambda function to determine when the queue should be throttled (e.g. when isMoving())\n * and manually calling {@link processQueue} in the render loop.\n */\nexport namespace ImageRequest {\n    let imageRequestQueue : ImageRequestQueueItem[];\n    let currentParallelImageRequests:number;\n\n    let throttleControlCallbackHandleCounter: number;\n    let throttleControlCallbacks: ImageQueueThrottleCallbackDictionary;\n\n    /**\n     * Reset the image request queue, removing all pending requests.\n     */\n    export const resetRequestQueue = (): void => {\n        imageRequestQueue = [];\n        currentParallelImageRequests = 0;\n        throttleControlCallbackHandleCounter = 0;\n        throttleControlCallbacks = {};\n    };\n\n    /**\n     * Install a callback to control when image queue throttling is desired.\n     * (e.g. when the map view is moving)\n     * @param callback - The callback function to install\n     * @returns handle that identifies the installed callback.\n     */\n    export const addThrottleControl = (callback: ImageQueueThrottleControlCallback): number => {\n        const handle = throttleControlCallbackHandleCounter++;\n        throttleControlCallbacks[handle] = callback;\n        return handle;\n    };\n\n    /**\n     * Remove a previously installed callback by passing in the handle returned\n     * by {@link addThrottleControl}.\n     * @param callbackHandle - The handle for the callback to remove.\n     */\n    export const removeThrottleControl = (callbackHandle: number): void => {\n        delete throttleControlCallbacks[callbackHandle];\n        // Try updating the queue\n        processQueue();\n    };\n\n    /**\n     * Check to see if any of the installed callbacks are requesting the queue\n     * to be throttled.\n     * @returns `true` if any callback is causing the queue to be throttled.\n     */\n    const isThrottled = (): boolean => {\n        for (const key of Object.keys(throttleControlCallbacks)) {\n            if (throttleControlCallbacks[key]()) {\n                return true;\n            }\n        }\n        return false;\n    };\n\n    /**\n     * Transform `url` through {@link RequestManager.transformRequest} and load the image.\n     * The transform may be async; if `abortController` aborts while it is pending, the\n     * request is never issued and the returned promise rejects with an `AbortError`.\n     * @param requestManager - The request manager whose transform to apply.\n     * @param url - The image URL, before transformation.\n     * @param resourceType - The resource type to pass to the transform.\n     * @param abortController - allows to abort the request.\n     * @param supportImageRefresh - `true`, if the image request need to support refresh based on cache headers.\n     * @param imageBitmapOptions - Options for `createImageBitmap`. Pass `{colorSpaceConversion: 'none'}` for images\n     * whose pixels hold data rather than color, such as raster-DEM tiles, so the browser does not color manage them.\n     * @returns - A promise resolved when the image is loaded.\n     */\n    export async function transformAndGetImage(\n        requestManager: RequestManager,\n        url: string,\n        resourceType: ResourceType,\n        abortController: AbortController,\n        supportImageRefresh: boolean = true,\n        imageBitmapOptions?: ImageBitmapOptions\n    ): Promise<GetResourceResponse<HTMLImageElement | ImageBitmap | null>> {\n        const requestParameters = await requestManager.transformRequest(url, resourceType);\n        throwIfAborted(abortController.signal);\n        return ImageRequest.getImage(requestParameters, abortController, supportImageRefresh, imageBitmapOptions);\n    }\n\n    /**\n     * Request to load an image.\n     * @param requestParameters - Request parameters.\n     * @param abortController - allows to abort the request.\n     * @param supportImageRefresh - `true`, if the image request need to support refresh based on cache headers.\n     * @param imageBitmapOptions - Options for `createImageBitmap`. Pass `{colorSpaceConversion: 'none'}` for images\n     * whose pixels hold data rather than color, such as raster-DEM tiles, so the browser does not color manage them.\n     * @returns - A promise resolved when the image is loaded.\n     */\n    export const getImage = (\n        requestParameters: RequestParameters,\n        abortController: AbortController,\n        supportImageRefresh: boolean = true,\n        imageBitmapOptions?: ImageBitmapOptions\n    ): Promise<GetResourceResponse<HTMLImageElement | ImageBitmap | null>> => {\n        return new Promise<GetResourceResponse<HTMLImageElement | ImageBitmap | null>>((resolve, reject) => {\n            requestParameters.headers ||= {};\n            requestParameters.headers.accept = 'image/webp,*/*';\n            extend(requestParameters, {type: 'image'});\n            const request: ImageRequestQueueItem = {\n                abortController,\n                requestParameters,\n                supportImageRefresh,\n                imageBitmapOptions,\n                state: 'queued',\n                onError: (error: Error) => {\n                    reject(error);\n                },\n                onSuccess: (response) => {\n                    resolve(response);\n                }\n            };\n\n            imageRequestQueue.push(request);\n            processQueue();\n        });\n    };\n\n    const arrayBufferToCanvasImageSource = (data: ArrayBuffer, imageBitmapOptions?: ImageBitmapOptions): Promise<HTMLImageElement | ImageBitmap | null> => {\n        const imageBitmapSupported = typeof createImageBitmap === 'function';\n        if (imageBitmapSupported) {\n            return arrayBufferToImageBitmap(data, imageBitmapOptions);\n        } else {\n            return arrayBufferToImage(data);\n        }\n    };\n\n    /**\n     * Runs one queued image request.\n     *\n     * An empty response body (e.g. HTTP 204 for a tile without content) resolves with\n     * `data: null`, keeping the expiry headers, so callers can handle the absence\n     * explicitly and re-request when the headers say so.\n     */\n    const doImageRequest = async (itemInQueue: ImageRequestQueueItem) => {\n        itemInQueue.state = 'running';\n        const {requestParameters, supportImageRefresh, imageBitmapOptions, onError, onSuccess, abortController} = itemInQueue;\n        // - If refreshExpiredTiles is false, then we can use HTMLImageElement to download raster images.\n        // - Fetch/XHR (via MakeRequest API) will be used to download images for following scenarios:\n        //      1. Style image sprite will had a issue with HTMLImageElement as described\n        //          here: https://github.com/mapbox/mapbox-gl-js/issues/1470\n        //      2. If refreshExpiredTiles is true (default), then in order to read the image cache header,\n        //          fetch/XHR request will be required\n        // - For any special case handling like use of AddProtocol, worker initiated request or additional headers\n        //      let makeRequest handle it.\n        // - HtmlImageElement request automatically adds accept header for all the browser supported images\n        const canUseHTMLImageElement = supportImageRefresh === false &&\n            !imageBitmapOptions &&\n            !isWorker(self) &&\n            !getProtocol(requestParameters.url) &&\n            (!requestParameters.headers ||\n                Object.keys(requestParameters.headers).reduce((acc, item) => acc && item === 'accept', true));\n\n        currentParallelImageRequests++;\n\n        const getImagePromise = canUseHTMLImageElement ?\n            getImageUsingHtmlImage(requestParameters, abortController) :\n            makeRequest(requestParameters, abortController);\n\n        try {\n            const response = await getImagePromise;\n            delete itemInQueue.abortController;\n            itemInQueue.state = 'completed';\n            if (response.data instanceof HTMLImageElement || isImageBitmap(response.data)) {\n                // User using addProtocol can directly return HTMLImageElement/ImageBitmap type\n                // If HtmlImageElement is used to get image then response type will be HTMLImageElement\n                onSuccess(response);\n            } else if (!response.data || response.data.byteLength === 0) {\n                onSuccess({data: null, cacheControl: response.cacheControl, expires: response.expires});\n            } else {\n                const img = await arrayBufferToCanvasImageSource(response.data, imageBitmapOptions);\n                onSuccess({data: img, cacheControl: response.cacheControl, expires: response.expires});\n            }\n        } catch (err) {\n            delete itemInQueue.abortController;\n            onError(ensureError(err));\n        } finally {\n            currentParallelImageRequests--;\n            processQueue();\n        }\n    };\n\n    /**\n     * Process some number of items in the image request queue.\n     */\n    const processQueue = (): void => {\n\n        const maxImageRequests = isThrottled() ?\n            config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME :\n            config.MAX_PARALLEL_IMAGE_REQUESTS;\n\n        // limit concurrent image loads to help with raster sources performance on big screens\n        for (let numImageRequests = currentParallelImageRequests;\n            numImageRequests < maxImageRequests && imageRequestQueue.length > 0;\n            numImageRequests++) {\n\n            const topItemInQueue: ImageRequestQueueItem = imageRequestQueue.shift();\n            if (topItemInQueue.abortController.signal.aborted) {\n                numImageRequests--;\n                continue;\n            }\n            doImageRequest(topItemInQueue);\n        }\n    };\n\n    const getImageUsingHtmlImage = (requestParameters: RequestParameters, abortController: AbortController): Promise<GetResourceResponse<HTMLImageElement | ImageBitmap | null>>  => {\n        return new Promise<GetResourceResponse<HTMLImageElement | ImageBitmap | null>>((resolve, reject) => {\n\n            const image = new Image() as HTMLImageElementWithPriority;\n            const url = requestParameters.url;\n            const credentials = requestParameters.credentials;\n            if (credentials && credentials === 'include') {\n                image.crossOrigin = 'use-credentials';\n            } else if ((credentials && credentials === 'same-origin') || !sameOrigin(url)) {\n                image.crossOrigin = 'anonymous';\n            }\n\n            abortController.signal.addEventListener('abort', () => {\n                // Set src to '' to actually cancel the request\n                image.src = '';\n                reject(new AbortError(abortController.signal.reason));\n            });\n\n            image.fetchPriority = 'high';\n            image.onload = () => {\n                image.onerror = image.onload = null;\n                resolve({data: image});\n            };\n            image.onerror = () => {\n                image.onerror = image.onload = null;\n                if (abortController.signal.aborted) {\n                    return;\n                }\n                reject(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.'));\n            };\n            image.src = url;\n        });\n    };\n}\n\nImageRequest.resetRequestQueue();\n", "import type {RequestParameters} from './ajax.ts';\n\n/**\n * A type of MapLibre resource.\n */\nexport const enum ResourceType {\n    Glyphs = 'Glyphs',\n    Image = 'Image',\n    Source = 'Source',\n    SpriteImage = 'SpriteImage',\n    SpriteJSON = 'SpriteJSON',\n    Style = 'Style',\n    Tile = 'Tile',\n    Unknown = 'Unknown',\n}\n\n/**\n * This function is used to transform a request.\n * It is used just before executing the relevant request.\n */\nexport type RequestTransformFunction = (url: string, resourceType?: ResourceType) => RequestParameters | Promise<RequestParameters> | undefined;\n\nexport class RequestManager {\n    _transformRequestFn: RequestTransformFunction | null;\n\n    constructor(transformRequestFn?: RequestTransformFunction | null) {\n        this._transformRequestFn = transformRequestFn ?? null;\n    }\n\n    transformRequest(url: string, type: ResourceType): RequestParameters | Promise<RequestParameters> {\n        if (this._transformRequestFn) {\n            return this._transformRequestFn(url, type) || {url};\n        }\n\n        return {url};\n    }\n\n    setTransformRequest(transformRequest: RequestTransformFunction | null): void {\n        this._transformRequestFn = transformRequest;\n    }\n}\n\n", "import {Event, type ErrorEvent} from '../util/evented.ts';\nimport {DOM} from '../util/dom.ts';\nimport Point from '@mapbox/point-geometry';\nimport {extend} from '../util/util.ts';\n\nimport type {MapGeoJSONFeature} from '../util/vectortile_to_geojson.ts';\nimport type {Map} from './map.ts';\nimport type {LngLat} from '../geo/lng_lat.ts';\nimport type {ProjectionSpecification, SourceSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {GeoJSONSourceShouldReloadTileOptions} from '../source/geojson_source.ts';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\n\n/**\n * An event from the mouse relevant to a specific layer.\n *\n * @group Event Related\n */\nexport type MapLayerMouseEvent = MapMouseEvent & { features?: MapGeoJSONFeature[] };\n\n/**\n * An event from a touch device relevant to a specific layer.\n *\n * @group Event Related\n */\nexport type MapLayerTouchEvent = MapTouchEvent & { features?: MapGeoJSONFeature[] };\n\n/**\n * The source event data type\n */\nexport type MapSourceDataType = 'content' | 'metadata' | 'visibility' | 'idle';\n\n/**\n * `MapLayerEventType` - a mapping between the event name and the event.\n * !!! note\n *     These events are compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map.on}, the event listener will fire only when the\n * event action contains a visible portion of the specified layer.\n * The following example can be used for all the events.\n *\n * @group Event Related\n * @example\n * ```ts\n * // Initialize the map\n * let map = new Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('the-event-name', 'poi-label', (e) => {\n *   console.log('An event has occurred on a visible portion of the poi-label layer');\n * });\n * ```\n */\nexport type MapLayerEventType = {\n    /**\n     * Fired when a pointing device (usually a mouse) is pressed and released contains a visible portion of the specified layer.\n     *\n     * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure-distances/)\n     * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-the-map-on-a-clicked-symbol/)\n     */\n    click: MapLayerMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is pressed and released twice contains a visible portion of the specified layer.\n     *\n     * !!! note\n     *     Under normal conditions, this event will be preceded by two `click` events.\n     */\n    dblclick: MapLayerMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is pressed while inside a visible portion of the specified layer.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    mousedown: MapLayerMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is released while inside a visible portion of the specified layer.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    mouseup: MapLayerMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is moved while the cursor is inside a visible portion of the specified layer.\n     * As you move the cursor across the layer, the event will fire every time the cursor changes position within that layer.\n     *\n     * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-coordinates-of-the-mouse-pointer/)\n     * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)\n     * @see [Display a popup on over](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n     * @see [Animate symbol to follow the mouse](https://maplibre.org/maplibre-gl-js/docs/examples/animate-symbol-to-follow-the-mouse/)\n     */\n    mousemove: MapLayerMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from\n     * outside that layer or outside the map canvas.\n     *\n     * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-the-map-on-a-clicked-symbol/)\n     * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)\n     */\n    mouseenter: MapLayerMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves\n     * the map canvas.\n     *\n     * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)\n     * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)\n     */\n    mouseleave: MapLayerMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is moved inside a visible portion of the specified layer.\n     *\n     * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-coordinates-of-the-mouse-pointer/)\n     * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)\n     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n     */\n    mouseover: MapLayerMouseEvent;\n    /**\n     * Fired when a point device (usually a mouse) leaves the visible portion of the specified layer.\n     */\n    mouseout: MapLayerMouseEvent;\n    /**\n     * Fired when the right button of the mouse is clicked or the context menu key is pressed within visible portion of the specified layer.\n     */\n    contextmenu: MapLayerMouseEvent;\n    /**\n     * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the visible portion of the specified layer.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    touchstart: MapLayerTouchEvent;\n    /**\n     * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the visible portion of the specified layer.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    touchend: MapLayerTouchEvent;\n    /**\n     * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the visible portion of the specified layer.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    touchcancel: MapLayerTouchEvent;\n};\n\n/**\n * `MapEventType` - a mapping between the event name and the event value.\n * These events are used with the {@link Map.on} method.\n * When using a `layerId` with {@link Map.on} method, please refer to {@link MapLayerEventType}.\n * The following example can be used for all the events.\n *\n * @group Event Related\n * @example\n * ```ts\n * // Initialize the map\n * let map = new Map({ // map options });\n * // Set an event listener\n * map.on('the-event-name', () => {\n *   console.log('An event has occurred!');\n * });\n * ```\n */\nexport type MapEventType = {\n    /**\n     * Fired when an error occurs. This is GL JS's primary error reporting\n     * mechanism. We use an event instead of `throw` to better accommodate\n     * asynchronous operations. If no listeners are bound to the `error` event, the\n     * error will be printed to the console.\n     */\n    error: ErrorEvent;\n    /**\n     * Fired immediately after all necessary resources have been downloaded\n     * and the first visually complete rendering of the map has occurred.\n     *\n     * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/draw-geojson-points/)\n     * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/add-live-realtime-data/)\n     * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-a-point/)\n     */\n    load: MapLibreEvent;\n    /**\n     * Fired after the last frame rendered before the map enters an\n     * \"idle\" state:\n     *\n     * - No camera transitions are in progress\n     * - All currently requested tiles have loaded\n     * - All fade/transition animations have completed\n     */\n    idle: MapLibreEvent;\n    /**\n     * Fired immediately after the map has been removed with {@link Map.remove}.\n     */\n    remove: MapLibreEvent;\n    /**\n     * Fired whenever the map is drawn to the screen, as the result of\n     *\n     * - a change to the map's position, zoom, pitch, or bearing\n     * - a change to the map's style\n     * - a change to a GeoJSON source\n     * - the loading of a vector tile, GeoJSON file, glyph, or sprite\n     */\n    render: MapLibreEvent;\n    /**\n     * Fired immediately after the map has been resized.\n     */\n    resize: MapLibreEvent;\n    /**\n     * Fired when the WebGL context is lost.\n     *\n     * The map rebuilds its style once the context is restored. Until the rebuilt style fires `style.load`,\n     * {@link Map.getSource} may return `undefined` and changes to sources or layers are not kept, so apply them\n     * again on that `style.load` event.\n     */\n    webglcontextlost: MapContextEvent;\n    /**\n     * Fired when the WebGL context is restored.\n     *\n     * The style is rebuilt asynchronously, so its sources and layers are not available yet when this fires.\n     * Wait for the next `style.load` event before using them.\n     */\n    webglcontextrestored: MapContextEvent;\n    /**\n     * Fired when any map data (style, source, tile, etc) begins loading or\n     * changing asynchronously. All `dataloading` events are followed by a `data`,\n     * `dataabort` or `error` event.\n     */\n    dataloading: MapSourceDataEvent | MapStyleDataEvent;\n    /**\n     * Fired when any map data loads or changes. See {@link MapSourceDataEvent} and {@link MapStyleDataEvent} for more information.\n     * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/display-html-clusters-with-custom-properties/)\n     */\n    data: MapSourceDataEvent | MapStyleDataEvent;\n    /**\n     * Fired when one of the map's sources begins loading or changing asynchronously.\n     * All `sourcedataloading` events are followed by a `sourcedata`, `sourcedataabort` or `error` event.\n     */\n    sourcedataloading: MapSourceDataEvent;\n    /**\n     * Fired when the map's style begins loading or changing asynchronously.\n     * All `styledataloading` events are followed by a `styledata`\n     * or `error` event.\n     */\n    styledataloading: MapStyleDataEvent;\n    /**\n     * Fired when one of the map's sources loads or changes, including if a tile belonging\n     * to a source loads or changes.\n     */\n    sourcedata: MapSourceDataEvent;\n    /**\n     * Fired when the map's style loads or changes.\n     */\n    styledata: MapStyleDataEvent;\n    /**\n     * Fired once the map's style has fully loaded or changed, after all\n     * necessary resources referenced by the style have been requested.\n     */\n    'style.load': MapStyleLoadEvent;\n    /**\n     * Fired when an icon or pattern needed by the style is missing and no missing style image resolver\n     * supplies it. To load or generate images on demand, use {@link Map.setMissingStyleImageResolver}.\n     * Event listeners cannot resolve the missing image for the current request.\n     * @see [Generate and add a missing icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/generate-and-add-a-missing-icon-to-the-map/)\n     */\n    styleimagemissing: MapStyleImageMissingEvent;\n    /**\n     * Fired when a request for one of the map's sources' tiles or data is aborted.\n     */\n    dataabort: MapSourceDataEvent;\n    /**\n     * Fired when a request for one of the map's sources' data is aborted.\n     */\n    sourcedataabort: MapSourceDataEvent;\n    /**\n     * Fired when the user cancels a \"box zoom\" interaction, or when the bounding box does not meet the minimum size threshold.\n     * See {@link BoxZoomHandler}.\n     */\n    boxzoomcancel: MapBoxZoomEvent;\n    /**\n     * Fired when a \"box zoom\" interaction starts. See {@link BoxZoomHandler}.\n     */\n    boxzoomstart: MapBoxZoomEvent;\n    /**\n     * Fired when a \"box zoom\" interaction ends.  See {@link BoxZoomHandler}.\n     */\n    boxzoomend: MapBoxZoomEvent;\n    /**\n     * Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map.\n     */\n    touchcancel: MapTouchEvent;\n    /**\n     * Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    touchmove: MapTouchEvent;\n    /**\n     * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    touchend: MapTouchEvent;\n    /**\n     * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    touchstart: MapTouchEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.\n     *\n     * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure-distances/)\n     * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-the-map-on-a-clicked-symbol/)\n     */\n    click: MapMouseEvent;\n    /**\n     * Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.\n     */\n    contextmenu: MapMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on the map in rapid succession.\n     *\n     * !!! note\n     *     Under normal conditions, this event will be preceded by two `click` events.\n     */\n    dblclick: MapMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map.\n     * As you move the cursor across the map, the event will fire every time the cursor changes position within the map.\n     *\n     * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-coordinates-of-the-mouse-pointer/)\n     * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)\n     * @see [Display a popup on over](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n     */\n    mousemove: MapMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is released within the map.\n     *\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    mouseup: MapMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is pressed within the map.\n     *\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    mousedown: MapMouseEvent;\n    /**\n     * Fired when a point device (usually a mouse) leaves the map's canvas.\n     */\n    mouseout: MapMouseEvent;\n    /**\n     * Fired when a pointing device (usually a mouse) is moved within the map.\n     * As you move the cursor across a web page containing a map,\n     * the event will fire each time it enters the map or any child elements.\n     *\n     * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-coordinates-of-the-mouse-pointer/)\n     * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)\n     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n     */\n    mouseover: MapMouseEvent;\n    /**\n     * Fired just before the map begins a transition from one\n     * view to another, as the result of either user interaction or methods such as {@link Map.jumpTo}.\n     *\n     */\n    movestart: MapMovementEvent;\n    /**\n     * Fired repeatedly during an animated transition from one view to\n     * another, as the result of either user interaction or methods such as {@link Map.flyTo}.\n     *\n     * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/display-html-clusters-with-custom-properties/)\n     */\n    move: MapMovementEvent;\n    /**\n     * Fired just after the map completes a transition from one\n     * view to another, as the result of either user interaction or methods such as {@link Map.jumpTo}.\n     *\n     * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/display-html-clusters-with-custom-properties/)\n     */\n    moveend: MapMovementEvent;\n    /**\n     * Fired just before the map begins a transition from one zoom level to another,\n     * as the result of either user interaction or methods such as {@link Map.flyTo}.\n     */\n    zoomstart: MapMovementEvent;\n    /**\n     * Fired repeatedly during an animated transition from one zoom level to another,\n     * as the result of either user interaction or methods such as {@link Map.flyTo}.\n     */\n    zoom: MapMovementEvent;\n    /**\n     * Fired just after the map completes a transition from one zoom level to another,\n     * as the result of either user interaction or methods such as {@link Map.flyTo}.\n     */\n    zoomend: MapMovementEvent;\n    /**\n     * Fired when a \"drag to rotate\" interaction starts. See {@link DragRotateHandler}.\n     */\n    rotatestart: MapMovementEvent;\n    /**\n     * Fired repeatedly during a \"drag to rotate\" interaction. See {@link DragRotateHandler}.\n     */\n    rotate: MapMovementEvent;\n    /**\n     * Fired when a \"drag to rotate\" interaction ends. See {@link DragRotateHandler}.\n     */\n    rotateend: MapMovementEvent;\n    /**\n     * Fired when a \"drag to pan\" interaction starts. See {@link DragPanHandler}.\n     */\n    dragstart: MapMovementEvent;\n    /**\n     * Fired repeatedly during a \"drag to pan\" interaction. See {@link DragPanHandler}.\n     */\n    drag: MapMovementEvent;\n    /**\n     * Fired when a \"drag to pan\" interaction ends. See {@link DragPanHandler}.\n     * @see [Create a draggable marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)\n     */\n    dragend: MapMovementEvent;\n    /**\n     * Fired whenever the map's pitch (tilt) begins a change as\n     * the result of either user interaction or methods such as {@link Map.flyTo} .\n     */\n    pitchstart: MapMovementEvent;\n    /**\n     * Fired repeatedly during the map's pitch (tilt) animation between\n     * one state and another as the result of either user interaction\n     * or methods such as {@link Map.flyTo}.\n     */\n    pitch: MapMovementEvent;\n    /**\n     * Fired immediately after the map's pitch (tilt) finishes changing as\n     * the result of either user interaction or methods such as {@link Map.flyTo}.\n     */\n    pitchend: MapMovementEvent;\n    /**\n     * Fired whenever the map's roll begins a change as\n     * the result of either user interaction or methods such as {@link Map.flyTo}.\n     */\n    rollstart: MapMovementEvent;\n    /**\n     * Fired repeatedly during the map's roll animation between\n     * one state and another as the result of either user interaction\n     * or methods such as {@link Map.flyTo}.\n     */\n    roll: MapMovementEvent;\n    /**\n     * Fired immediately after the map's roll finishes changing as\n     * the result of either user interaction or methods such as {@link Map.flyTo}.\n     */\n    rollend: MapMovementEvent;\n    /**\n     * Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map.\n     */\n    wheel: MapWheelEvent;\n    /**\n     * Fired when terrain is changed\n     */\n    terrain: MapTerrainEvent;\n    /**\n     * Fired whenever the cooperativeGestures option prevents a gesture from being handled by the map.\n     * This is useful for showing your own UI when this happens.\n     */\n    cooperativegestureprevented: MapLibreEvent<WheelEvent | TouchEvent> & {\n        gestureType: 'wheel_zoom' | 'touch_pan';\n    };\n    /**\n     * Fired when map's projection is modified in other ways than by map being moved.\n     */\n    projectiontransition: MapProjectionEvent;\n};\n\n/**\n * `SourceEventType` - a mapping between the source data event names and their event value.\n * These are the events fired by a {@link Source} as its data loads or changes; they also bubble\n * up to the {@link Map}. See {@link MapSourceDataEvent} for the event shape.\n *\n * @group Event Related\n */\nexport type SourceEventType = {\n    /**\n     * Fired when the source's data loads or changes.\n     */\n    data: MapSourceDataEvent;\n    /**\n     * Fired when the source begins loading or changing data.\n     */\n    dataloading: MapSourceDataEvent;\n    /**\n     * Fired when a request for the source's data is aborted.\n     */\n    dataabort: MapSourceDataEvent;\n    /**\n     * Fired when there's an error\n     */ \n    error: ErrorEvent;\n};\n\n/**\n * The base event for MapLibre\n *\n * @group Event Related\n */\nexport class MapLibreEvent<TOrig = unknown> extends Event {\n    type: keyof MapEventType | keyof MapLayerEventType;\n    target: Map;\n    originalEvent: TOrig;\n}\n\n/**\n * `MapMovementEvent` is the event type for the camera-transition map events:\n * `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `rotatestart`, `rotate`, `rotateend`,\n * `dragstart`, `drag`, `dragend`, `pitchstart`, `pitch`, `pitchend`, `rollstart`, `roll` and `rollend`.\n * These are fired as the map's view changes, as a result of either user interaction or methods such\n * as {@link Map.jumpTo} / {@link Map.flyTo}.\n *\n * @group Event Related\n */\nexport class MapMovementEvent extends MapLibreEvent<MouseEvent | TouchEvent | WheelEvent | undefined> {\n    type: 'movestart' | 'move' | 'moveend' | 'zoomstart' | 'zoom' | 'zoomend' |\n    'rotatestart' | 'rotate' | 'rotateend' | 'dragstart' | 'drag' | 'dragend' |\n    'pitchstart' | 'pitch' | 'pitchend' | 'rollstart' | 'roll' | 'rollend';\n}\n\n/**\n * The `style.load` event, fired once the map's style has fully loaded or changed.\n *\n * @group Event Related\n */\nexport class MapStyleLoadEvent extends MapLibreEvent {\n    type: 'style.load';\n\n    constructor(data: any = {}) {\n        super('style.load', data);\n    }\n}\n\n/**\n * The style data event\n *\n * @group Event Related\n */\nexport class MapStyleDataEvent extends MapLibreEvent {\n    type: 'data' | 'dataloading' | 'styledata' | 'styledataloading';\n    dataType: 'style';\n\n    constructor(type: MapStyleDataEvent['type'], data: Omit<Partial<MapStyleDataEvent>, 'type' | 'dataType' | 'target'> = {}) {\n        super(type, data);\n        this.dataType = 'style';\n    }\n}\n\n/**\n * A `MapSourceDataEvent` is emitted with the source-related `data`, `dataloading`, `dataabort`,\n * `sourcedata`, `sourcedataloading` and `sourcedataabort` events. Its `dataType` is always `'source'`.\n *\n * Possible values for `sourceDataType`s are:\n *\n * - `'metadata'`: indicates that any necessary source metadata has been loaded (such as TileJSON) and it is ok to start loading tiles\n * - `'content'`: indicates the source data has changed (such as when source.setData() has been called on GeoJSONSource)\n * - `'visibility'`: send when the source becomes used when at least one of its layers becomes visible in style sense (inside the layer's zoom range and with layout.visibility set to 'visible')\n * - `'idle'`: indicates that no new source data has been fetched (but the source has done loading)\n *\n * @group Event Related\n *\n * @example\n * ```ts\n * // The sourcedata event is an example of a MapSourceDataEvent.\n * // Set up an event listener on the map.\n * map.on('sourcedata', (e) => {\n *    if (e.isSourceLoaded) {\n *        // Do something when the source has finished loading\n *    }\n * });\n * ```\n */\nexport class MapSourceDataEvent extends MapLibreEvent {\n    type: 'data' | 'dataloading' | 'dataabort' | 'sourcedata' | 'sourcedataloading' | 'sourcedataabort';\n    dataType: 'source';\n    /**\n     * True if the event has a `dataType` of `source` and the source has no outstanding network requests.\n     */\n    isSourceLoaded: boolean;\n    /**\n     * The [style spec representation of the source](https://maplibre.org/maplibre-style-spec/#sources) if the event has a `dataType` of `source`.\n     */\n    source: SourceSpecification;\n    sourceId: string;\n    sourceDataType: MapSourceDataType;\n    sourceDataChanged?: boolean;\n    /**\n     * The tile being loaded or changed, if the event has a `dataType` of `source` and\n     * the event is related to loading of a tile.\n     */\n    tile: any;\n    /**\n     * The tile ID of the tile being loaded or changed, if the event is related to loading of a tile.\n     */\n    coord: OverscaledTileID;\n    /**\n     * Resource timing data, if `collectResourceTiming` is enabled for the source.\n     */\n    resourceTiming?: PerformanceResourceTiming[];\n\n    /**\n     * Options to determine whether a tile should be reloaded.\n     * @internal\n     */\n    shouldReloadTileOptions: GeoJSONSourceShouldReloadTileOptions;\n\n    constructor(type: MapSourceDataEvent['type'], data: Omit<Partial<MapSourceDataEvent>, 'type' | 'dataType' | 'target'> = {}) {\n        super(type, data);\n        this.dataType = 'source';\n    }\n};\n/**\n * `MapMouseEvent` is the event type for mouse-related map events.\n *\n * @group Event Related\n *\n * @example\n * ```ts\n * // The `click` event is an example of a `MapMouseEvent`.\n * // Set up an event listener on the map.\n * map.on('click', (e) => {\n *   // The event object (e) contains information like the\n *   // coordinates of the point on the map that was clicked.\n *   console.log('A click event has occurred at ' + e.lngLat);\n * });\n * ```\n */\nexport class MapMouseEvent extends MapLibreEvent<MouseEvent> {\n    /**\n     * The event type\n     */\n    type: 'mousedown' | 'mouseup' | 'click' | 'dblclick' | 'mousemove' | 'mouseover' | 'mouseenter' | 'mouseleave' | 'mouseout' | 'contextmenu';\n\n    /**\n     * The `Map` object that fired the event.\n     */\n    target: Map;\n\n    /**\n     * The DOM event which caused the map event.\n     */\n    originalEvent: MouseEvent;\n\n    /**\n     * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner.\n     */\n    point: Point;\n\n    /**\n     * The geographic location on the map of the mouse cursor.\n     */\n    lngLat: LngLat;\n\n    /**\n     * Prevents subsequent default processing of the event by the map.\n     *\n     * Calling this method will prevent the following default map behaviors:\n     *\n     *   * On `mousedown` events, the behavior of {@link DragPanHandler}\n     *   * On `mousedown` events, the behavior of {@link DragRotateHandler}\n     *   * On `mousedown` events, the behavior of {@link BoxZoomHandler}\n     *   * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler}\n     *\n     */\n    preventDefault(): void {\n        this._defaultPrevented = true;\n    }\n\n    /**\n     * `true` if `preventDefault` has been called.\n     */\n    get defaultPrevented(): boolean {\n        return this._defaultPrevented;\n    }\n\n    _defaultPrevented: boolean;\n\n    constructor(type: string, map: Map, originalEvent: MouseEvent, data: any = {}) {\n        originalEvent = originalEvent instanceof MouseEvent ? originalEvent : new MouseEvent(type, originalEvent);\n        const point = DOM.mousePos(map.getCanvas(), originalEvent);\n        const lngLat = map.unproject(point);\n        super(type, extend({point, lngLat, originalEvent}, data));\n        this._defaultPrevented = false;\n        this.target = map;\n    }\n}\n\n/**\n * `MapTouchEvent` is the event type for touch-related map events.\n *\n * @group Event Related\n */\nexport class MapTouchEvent extends MapLibreEvent<TouchEvent> {\n    /**\n     * The event type.\n     */\n    type: 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel';\n\n    /**\n     * The `Map` object that fired the event.\n     */\n    target: Map;\n\n    /**\n     * The DOM event which caused the map event.\n     */\n    originalEvent: TouchEvent;\n\n    /**\n     * The geographic location on the map of the center of the touch event points.\n     */\n    lngLat: LngLat;\n\n    /**\n     * The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left\n     * corner.\n     */\n    point: Point;\n\n    /**\n     * The array of pixel coordinates corresponding to a\n     * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.\n     */\n    points: Point[];\n\n    /**\n     * The geographical locations on the map corresponding to a\n     * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.\n     */\n    lngLats: LngLat[];\n\n    /**\n     * Prevents subsequent default processing of the event by the map.\n     *\n     * Calling this method will prevent the following default map behaviors:\n     *\n     *   * On `touchstart` events, the behavior of {@link DragPanHandler}\n     *   * On `touchstart` events, the behavior of {@link TwoFingersTouchZoomRotateHandler}\n     *\n     */\n    preventDefault(): void {\n        this._defaultPrevented = true;\n    }\n\n    /**\n     * `true` if `preventDefault` has been called.\n     */\n    get defaultPrevented(): boolean {\n        return this._defaultPrevented;\n    }\n\n    _defaultPrevented: boolean;\n\n    constructor(type: string, map: Map, originalEvent: TouchEvent) {\n        const touches = type === 'touchend' ? originalEvent.changedTouches : originalEvent.touches;\n        const points = DOM.touchPos(map.getCanvasContainer(), touches);\n        const lngLats = points.map((t) => map.unproject(t));\n        const point = points.reduce((prev, curr, i, arr) => {\n            return prev.add(curr.div(arr.length));\n        }, new Point(0, 0));\n        const lngLat = map.unproject(point);\n        super(type, {points, point, lngLats, lngLat, originalEvent});\n        this._defaultPrevented = false;\n    }\n}\n\n/**\n * `MapWheelEvent` is the event type for the `wheel` map event.\n *\n * @group Event Related\n */\nexport class MapWheelEvent extends MapLibreEvent<WheelEvent> {\n    /**\n     * The event type.\n     */\n    type: 'wheel';\n\n    /**\n     * The `Map` object that fired the event.\n     */\n    target: Map;\n\n    /**\n     * The DOM event which caused the map event.\n     */\n    originalEvent: WheelEvent;\n\n    /**\n     * Prevents subsequent default processing of the event by the map.\n     *\n     * Calling this method will prevent the behavior of {@link ScrollZoomHandler}.\n     */\n    preventDefault(): void {\n        this._defaultPrevented = true;\n    }\n\n    /**\n     * `true` if `preventDefault` has been called.\n     */\n    get defaultPrevented(): boolean {\n        return this._defaultPrevented;\n    }\n\n    _defaultPrevented: boolean;\n\n    /** */\n    constructor(map: Map, originalEvent: WheelEvent) {\n        super('wheel', {originalEvent});\n        this._defaultPrevented = false;\n    }\n}\n\n/**\n * A `MapBoxZoomEvent` is the event type for the boxzoom-related map events emitted by the {@link BoxZoomHandler}.\n *\n * @group Event Related\n */\nexport class MapBoxZoomEvent extends MapLibreEvent<MouseEvent> {\n    /**\n     * The type of boxzoom event. One of `boxzoomstart`, `boxzoomend` or `boxzoomcancel`\n     */\n    type: 'boxzoomstart' | 'boxzoomend' | 'boxzoomcancel';\n    /**\n     * The `Map` instance that triggered the event\n     */\n    target: Map;\n    /**\n     * The DOM event that triggered the boxzoom event. Can be a `MouseEvent` or `KeyboardEvent`\n     */\n    originalEvent: MouseEvent;\n};\n\n/**\n * The terrain event\n *\n * @group Event Related\n */\nexport class MapTerrainEvent extends MapLibreEvent {\n    type: 'terrain';\n\n    constructor(data: any = {}) {\n        super('terrain', data);\n    }\n};\n\n/**\n * The map projection event\n *\n * @group Event Related\n */\nexport class MapProjectionEvent extends MapLibreEvent {\n    type: 'projectiontransition';\n    /**\n     * Specifies the name of the new projection.\n     * For example:\n     *\n     *  - `globe` to describe globe that has internally switched to mercator\n     *  - `vertical-perspective` to describe a globe that doesn't change to mercator\n     *  - `mercator` to describe mercator projection\n     */\n    newProjection: ProjectionSpecification['type'];\n\n    constructor(data: any = {}) {\n        super('projectiontransition', data);\n    }\n}\n\n/**\n * An event related to the web gl context\n *\n * @group Event Related\n */\nexport class MapContextEvent extends MapLibreEvent<WebGLContextEvent> {\n    type: 'webglcontextlost' | 'webglcontextrestored';\n    originalEvent: WebGLContextEvent;\n};\n\n/**\n * The style image missing event, fired when an image is still missing after the missing style image\n * resolver has been given a chance to supply it. To load or generate images on demand,\n * use {@link Map.setMissingStyleImageResolver}.\n * Event listeners cannot resolve the missing image for the current request.\n *\n * @group Event Related\n *\n * @see [Generate and add a missing icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/generate-and-add-a-missing-icon-to-the-map/)\n */\nexport class MapStyleImageMissingEvent extends MapLibreEvent {\n    type: 'styleimagemissing';\n    id: string;\n\n    constructor(data: any = {}) {\n        super('styleimagemissing', data);\n    }\n};\n", "import {latest as styleSpec, validateStyleMin} from '@maplibre/maplibre-gl-style-spec';\nimport {ErrorEvent} from '../util/evented.ts';\nimport {warnOnce} from '../util/util.ts';\n\nimport type {StyleSpecification, ValidationError} from '@maplibre/maplibre-gl-style-spec';\nimport type {Evented} from '../util/evented.ts';\nimport type {StyleSetterOptions} from './style.ts';\n\n/**\n * Validates a single part of a style, e.g. a source, a filter or a paint property.\n * The options it takes are the ones assembled by {@link validateAndEmit}.\n */\nexport type Validator = (options: any) => readonly ValidationError[];\n\ntype ValidateStyle = {\n    source: Validator;\n    sprite: Validator;\n    glyphs: Validator;\n    layer: Validator;\n    light: Validator;\n    sky: Validator;\n    terrain: Validator;\n    filter: Validator;\n    paintProperty: Validator;\n    layoutProperty: Validator;\n    (b: any, a?: any | null): readonly ValidationError[];\n};\n\nexport const validateStyle = (validateStyleMin as unknown as ValidateStyle);\n\n/**\n * The source types the spec has a schema for, and therefore the only ones it can judge. Taken from\n * the spec itself so the two cannot drift apart.\n */\nexport const SPEC_SOURCE_TYPES: ReadonlySet<string> = new Set(\n    Object.keys(styleSpec)\n        .filter(key => key.startsWith('source_'))\n        .map(key => key.slice('source_'.length).replaceAll('_', '-'))\n);\n\n/**\n * The sources whose type the spec has no schema for, so it rejects them outright even though we\n * render them: `canvas`, and anything registered with {@link addSourceType}. They are the renderer's\n * business rather than the spec's, so the spec's complaints about them are dropped -- otherwise\n * `map.setStyle(map.getStyle())` would fail on a source the user added correctly.\n *\n * Each such source produces a single error keyed by `sources.<id>`, which is what is matched here.\n * @param style - the style about to be validated\n * @returns the `sources.<id>` key prefixes whose errors should be ignored\n */\nfunction unjudgeableSourceKeys(style: StyleSpecification): string[] {\n    return Object.entries(style.sources ?? {})\n        .filter(([, source]) => !SPEC_SOURCE_TYPES.has(source.type))\n        .map(([id]) => `sources.${id}`);\n}\n\n/**\n * Validates a whole style and emits what it finds, ignoring the sources the spec cannot judge.\n *\n * @param emitter - the object to fire {@link ErrorEvent}s on\n * @param style - the style to validate\n * @returns whether validation failed, i.e. whether the caller should give up on the style\n */\nexport function validateStyleAndEmit(emitter: Evented, style: StyleSpecification): boolean {\n    const ignored = unjudgeableSourceKeys(style);\n    const errors = validateStyle(style).filter(({message}) =>\n        !ignored.some(key => message.startsWith(`${key}:`) || message.startsWith(`${key}.`))\n    );\n    return emitValidationErrors(emitter, errors);\n}\n\n/**\n * Emits everything a validator found, and reports whether any of it was severe enough to abort.\n *\n * Warnings are logged rather than emitted as errors: the style still renders, just not necessarily\n * as its author intended (e.g. a filter mixing deprecated syntax into an expression tree). Treating\n * them as errors would abort the whole style load and leave a blank map.\n * See https://github.com/maplibre/maplibre-style-spec/issues/1751\n *\n * @param emitter - the object to fire {@link ErrorEvent}s on\n * @param errors - what validation turned up, if anything\n * @returns whether validation failed, i.e. whether the caller should give up on the value\n */\nexport function emitValidationErrors(emitter: Evented, errors: readonly ValidationError[]): boolean {\n    let hasErrors = false;\n    for (const error of errors) {\n        if (error.severity === 'warning') {\n            warnOnce(error.message);\n            continue;\n        }\n        emitter.fire(new ErrorEvent(new Error(error.message)));\n        hasErrors = true;\n    }\n    return hasErrors;\n}\n\n/**\n * Runs a validator over a value and emits whatever it finds.\n *\n * @param emitter - the object to fire {@link ErrorEvent}s on\n * @param validator - the validator to run, e.g. {@link validateFilter}\n * @param params - what to validate: the `value`, plus whatever context the validator needs, such as\n * the `key` locating it in the style, or the surrounding `style` that {@link validateStyle.layer} looks at\n * @param options - setter options; validation is skipped entirely when `validate` is `false`\n * @returns whether validation failed, i.e. whether the caller should give up on the value\n */\nexport function validateAndEmit(\n    emitter: Evented,\n    validator: Validator,\n    params: {value: unknown} & Record<string, unknown>,\n    options?: StyleSetterOptions\n): boolean {\n    if (options?.validate === false) {\n        return false;\n    }\n    return emitValidationErrors(emitter, validator({\n        styleSpec,\n        ...params\n    }));\n}\n", "export class ZoomHistory {\n    lastZoom: number;\n    lastFloorZoom: number;\n    lastIntegerZoom: number;\n    lastIntegerZoomTime: number;\n    first: boolean;\n\n    constructor() {\n        this.first = true;\n    }\n\n    update(z: number, now: number): boolean {\n        const floorZ = Math.floor(z);\n\n        if (this.first) {\n            this.first = false;\n            this.lastIntegerZoom = floorZ;\n            this.lastIntegerZoomTime = 0;\n            this.lastZoom = z;\n            this.lastFloorZoom = floorZ;\n            return true;\n        }\n\n        if (this.lastFloorZoom > floorZ) {\n            this.lastIntegerZoom = floorZ + 1;\n            this.lastIntegerZoomTime = now;\n        } else if (this.lastFloorZoom < floorZ) {\n            this.lastIntegerZoom = floorZ;\n            this.lastIntegerZoomTime = now;\n        }\n\n        if (z !== this.lastZoom) {\n            this.lastZoom = z;\n            this.lastFloorZoom = floorZ;\n            return true;\n        }\n\n        return false;\n    }\n}\n", "import {ZoomHistory} from './zoom_history.ts';\n\nimport type {GlobalProperties, TransitionSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type CrossfadeParameters = {\n    fromScale: number;\n    toScale: number;\n    t: number;\n};\n\n/**\n * @internal\n * A parameter that can be evaluated to a value.\n * It's main purpose is a parameter to expression `evaluate` methods.\n */\nexport class EvaluationParameters implements GlobalProperties {\n    zoom: number;\n    now: number;\n    fadeDuration: number;\n    zoomHistory: ZoomHistory;\n    transition: TransitionSpecification;\n    // \"options\" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate\n    constructor(zoom: number, options?: any) {\n        this.zoom = zoom;\n\n        if (options) {\n            this.now = options.now || 0;\n            this.fadeDuration = options.fadeDuration || 0;\n            this.zoomHistory = options.zoomHistory || new ZoomHistory();\n            this.transition = options.transition || {};\n        } else {\n            this.now = 0;\n            this.fadeDuration = 0;\n            this.zoomHistory = new ZoomHistory();\n            this.transition = {};\n        }\n    }\n\n    crossFadingFactor(): number {\n        if (this.fadeDuration === 0) {\n            return 1;\n        } else {\n            return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1);\n        }\n    }\n\n    getCrossfadeParameters(): CrossfadeParameters {\n        const z = this.zoom;\n        const fraction = z - Math.floor(z);\n        const t = this.crossFadingFactor();\n\n        return z > this.zoomHistory.lastIntegerZoom ?\n            {fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t} :\n            {fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction};\n    }\n}\n", "import {clone, deepEqual, extend, easeCubicInOut, warnOnce} from '../util/util.ts';\nimport {interpolates, type Color, type StylePropertySpecification, normalizePropertyExpression,\n    type Feature,\n    type FeatureState,\n    type StylePropertyExpression,\n    type SourceExpression,\n    type CompositeExpression, type TransitionSpecification,\n    type PropertyValueSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {register} from '../util/web_worker_transfer.ts';\nimport {EvaluationParameters} from './evaluation_parameters.ts';\n\nimport type {CanonicalTileID} from '../tile/tile_id.ts';\n\ntype TimePoint = number;\n\nexport const TRANSITION_SUFFIX = '-transition';\n\n/**\n * A from-to type\n */\nexport type CrossFaded<T> = {\n    to: T;\n    from: T;\n};\n\n/**\n * @internal\n *  Implementations of the `Property` interface:\n *\n *  * Hold metadata about a property that's independent of any specific value: stuff like the type of the value,\n *    the default value, etc. This comes from the style specification JSON.\n *  * Define behavior that needs to be polymorphic across different properties: \"possibly evaluating\"\n *    an input value (see below), and interpolating between two possibly-evaluted values.\n *\n *  The type `T` is the fully-evaluated value type (e.g. `number`, `string`, `Color`).\n *  The type `R` is the intermediate \"possibly evaluated\" value type. See below.\n *\n *  There are two main implementations of the interface -- one for properties that allow data-driven values,\n *  and one for properties that don't. There are a few \"special case\" implementations as well: one for properties\n *  which cross-fade between two values rather than interpolating, one for `heatmap-color` and `line-gradient`,\n *  and one for `light-position`.\n */\nexport interface Property<T, R> {\n    specification: StylePropertySpecification;\n    name: string;\n    possiblyEvaluate(\n        value: PropertyValue<T, R>,\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): R;\n    interpolate(a: R, b: R, t: number): R;\n}\n\n/**\n * @internal\n *  `PropertyValue` represents the value part of a property key-value unit. It's used to represent both\n *  paint and layout property values, and regardless of whether or not their property supports data-driven\n *  expressions.\n *\n *  `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the\n *  following:\n *\n *    * A constant value of the type appropriate for the property\n *    * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions)\n *    * An expression which produces a value of that type\n *    * \"undefined\"/\"not present\", in which case the property is assumed to take on its default value.\n *\n *  In addition to storing the original input value, `PropertyValue` also stores a normalized representation,\n *  effectively treating functions as if they are expressions, and constant or default values as if they are\n *  (constant) expressions.\n */\nexport class PropertyValue<T, R> {\n    property: Property<T, R>;\n    value: PropertyValueSpecification<T> | void;\n    expression: StylePropertyExpression;\n\n    constructor(property: Property<T, R>, value: PropertyValueSpecification<T> | void, rootKey: string, globalState: Record<string, any>) {\n        this.property = property;\n        this.value = value;\n        this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, rootKey, property.specification, globalState);\n    }\n\n    isDataDriven(): boolean {\n        return this.expression.kind === 'source' || this.expression.kind === 'composite';\n    }\n\n    getGlobalStateRefs(): Set<string> {\n        return this.expression.globalStateRefs || new Set<string>();\n    }\n\n    /** Whether the expression reads one of the global state keys in `refs`. */\n    readsGlobalState(refs: string[]): boolean {\n        const globalStateRefs = this.getGlobalStateRefs();\n        return refs.some(ref => globalStateRefs.has(ref));\n    }\n\n    possiblyEvaluate(\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): R {\n        return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);\n    }\n}\n\nexport type TransitionParameters = {\n    now: TimePoint;\n    transition: TransitionSpecification;\n};\n\n/**\n * @internal\n * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between\n * old and new value. The duration of the transition, and the delay before it begins, is configurable.\n *\n * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition\n * configuration.\n *\n * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values:\n * `TransitioningPropertyValue`.\n */\nclass TransitionablePropertyValue<T, R> {\n    property: Property<T, R>;\n    value: PropertyValue<T, R>;\n    transition: TransitionSpecification | void;\n\n    constructor(property: Property<T, R>, rootKey: string, globalState: Record<string, any>) {\n        this.property = property;\n        this.value = new PropertyValue(property, undefined, rootKey, globalState);\n    }\n\n    /** The same `PropertyValue` means `setValue` was never called, so there is nothing to transition to. */\n    transitioned(parameters: TransitionParameters, prior: TransitioningPropertyValue<T, R>): TransitioningPropertyValue<T, R> {\n        if (prior.value === this.value) return prior;\n        return new TransitioningPropertyValue(this.property, this.value, prior,\n            extend({}, parameters.transition, this.transition), parameters.now);\n    }\n\n    untransitioned(): TransitioningPropertyValue<T, R> {\n        return new TransitioningPropertyValue(this.property, this.value, null, {}, 0);\n    }\n}\n\n/**\n * @internal\n * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a\n * `Transitioning` instance for the same set of properties.\n */\nexport class Transitionable<Props> {\n    _properties: Properties<Props>;\n    _values: {[K in keyof Props]: TransitionablePropertyValue<any, unknown>};\n    private _globalState: Record<string, any>;\n    private _rootKey: string;\n\n    constructor(properties: Properties<Props>, rootKey: string, globalState: Record<string, any>) {\n        this._properties = properties;\n        this._values = (Object.create(properties.defaultTransitionablePropertyValues));\n        this._globalState = globalState;\n        this._rootKey = rootKey;\n    }\n\n    /** rootKey of a property, e.g. `layers[3].paint.line-color`. */\n    private _propertyRootKey(name: keyof Props): string {\n        return `${this._rootKey}.${String(name)}`;\n    }\n\n    hasProperty(name: string): boolean {\n        return name in this._properties.defaultTransitionablePropertyValues;\n    }\n\n    getValue<S extends keyof Props, T>(name: S): PropertyValueSpecification<T> | void {\n        return clone(this._values[name].value.value);\n    }\n\n    setValue<S extends keyof Props, T>(name: S, value: PropertyValueSpecification<T> | void): void {\n        if (!Object.hasOwn(this._values, name)) {\n            this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._propertyRootKey(name), this._globalState);\n        }\n        // Note that we do not _remove_ an own property in the case where a value is being reset\n        // to the default: the transition might still be non-default.\n        this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value), this._propertyRootKey(name), this._globalState);\n    }\n\n    /** Applies a whole spec, skipping the values we already hold so they do not transition. */\n    setValues(values: {[name: string]: unknown}): void {\n        for (const name in values) {\n            const value = values[name];\n            if (name.endsWith(TRANSITION_SUFFIX)) {\n                this.setTransition(name.slice(0, -TRANSITION_SUFFIX.length) as keyof Props, value);\n            } else if (!deepEqual(this._values[name].value.value, value)) {\n                this.setValue(name as keyof Props, value);\n            }\n        }\n    }\n\n    getTransition<S extends keyof Props>(name: S): TransitionSpecification | void {\n        return clone(this._values[name].transition);\n    }\n\n    setTransition<S extends keyof Props>(name: S, value: TransitionSpecification | void): void {\n        if (!Object.hasOwn(this._values, name)) {\n            this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._propertyRootKey(name), this._globalState);\n        }\n        this._values[name].transition = clone(value) || undefined;\n    }\n\n    /** Keeps the transitions running in `transitioning` on `priorGlobalState` where they read one of `refs` live. */\n    retainPriorGlobalState(refs: string[], priorGlobalState: Record<string, any>, transitioning: Transitioning<Props>): void {\n        for (const name of Object.keys(transitioning._values)) {\n            for (let step: TransitioningPropertyValue<any, unknown> = transitioning._values[name]; step; step = step.prior) {\n                const {value} = step;\n                if (!value.property.specification.transition || value.isDataDriven() ||\n                    value.expression._globalState !== this._globalState || !value.readsGlobalState(refs)) continue;\n\n                step.value = new PropertyValue(value.property, value.value, this._propertyRootKey(name as keyof Props), priorGlobalState);\n            }\n        }\n    }\n\n    /** Reads every value that reads one of `refs` again and transitions it from what `transitioning` shows. */\n    applyGlobalStateChange(refs: string[], priorGlobalState: Record<string, any>, transitioning: Transitioning<Props>, parameters: TransitionParameters): Transitioning<Props> {\n        this.retainPriorGlobalState(refs, priorGlobalState, transitioning);\n        let changed = false;\n        for (const name of Object.keys(this._values)) {\n            const {value} = this._values[name];\n            if (!value.readsGlobalState(refs)) continue;\n\n            this.setValue(name as keyof Props, value.value);\n            changed = true;\n        }\n        return changed ? this.transitioned(parameters, transitioning) : transitioning;\n    }\n\n    serialize(): any {\n        const result: any = {};\n        for (const property of Object.keys(this._values)) {\n            const value = this.getValue(property as keyof Props);\n            if (value !== undefined) {\n                result[property] = value;\n            }\n\n            const transition = this.getTransition(property as keyof Props);\n            if (transition !== undefined) {\n                result[`${property}${TRANSITION_SUFFIX}`] = transition;\n            }\n        }\n        return result;\n    }\n\n    transitioned(parameters: TransitionParameters, prior: Transitioning<Props>): Transitioning<Props> {\n        const result = new Transitioning(this._properties);\n        for (const property of Object.keys(this._values)) {\n            result._values[property] = this._values[property].transitioned(parameters, prior._values[property]);\n        }\n        return result;\n    }\n\n    untransitioned(): Transitioning<Props> {\n        const result = new Transitioning(this._properties);\n        for (const property of Object.keys(this._values)) {\n            result._values[property] = this._values[property].untransitioned();\n        }\n        return result;\n    }\n}\n\n/**\n * @internal\n * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint\n * property value. In this step, transitions between old and new values are handled: as long as the transition is in\n * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and\n * the new value based on the current time and the configured transition duration and delay. The product is the next\n * step in the evaluation chain: the \"possibly evaluated\" result type `R`. See below for more on this concept.\n */\nclass TransitioningPropertyValue<T, R> {\n    property: Property<T, R>;\n    value: PropertyValue<T, R>;\n    prior: TransitioningPropertyValue<T, R>;\n    begin: TimePoint;\n    end: TimePoint;\n\n    constructor(property: Property<T, R>,\n        value: PropertyValue<T, R>,\n        prior: TransitioningPropertyValue<T, R>,\n        transition: TransitionSpecification,\n        now: TimePoint) {\n        this.property = property;\n        this.value = value;\n        this.begin = now + transition.delay || 0;\n        this.end = this.begin + transition.duration || 0;\n        if (property.specification.transition && (transition.delay || transition.duration)) {\n            this.prior = prior;\n        }\n    }\n\n    possiblyEvaluate(\n        parameters: EvaluationParameters,\n        canonical: CanonicalTileID,\n        availableImages: string[]\n    ): R {\n        const now = parameters.now || 0;\n        const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages);\n        const prior = this.prior;\n        if (!prior) {\n            // No prior value.\n            return finalValue;\n        } else if (now > this.end) {\n            // Transition from prior value is now complete.\n            this.prior = null;\n            return finalValue;\n        } else if (this.value.isDataDriven()) {\n            // Transitions to data-driven properties are not supported.\n            // We snap immediately to the data-driven value so that, when we perform layout,\n            // we see the data-driven function and can use it to populate vertex buffers.\n            this.prior = null;\n            return finalValue;\n        } else if (now < this.begin) {\n            // Transition hasn't started yet.\n            return prior.possiblyEvaluate(parameters, canonical, availableImages);\n        } else {\n            // Interpolate between recursively-calculated prior value and final.\n            const t = (now - this.begin) / (this.end - this.begin);\n            return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t));\n        }\n    }\n}\n\n/**\n * @internal\n * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n */\nexport class Transitioning<Props> {\n    _properties: Properties<Props>;\n    _values: {[K in keyof Props]: PossiblyEvaluatedPropertyValue<unknown>};\n\n    constructor(properties: Properties<Props>) {\n        this._properties = properties;\n        this._values = (Object.create(properties.defaultTransitioningPropertyValues));\n    }\n\n    possiblyEvaluate(\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): PossiblyEvaluated<Props, any> {\n        const result = new PossiblyEvaluated(this._properties);\n        for (const property of Object.keys(this._values)) {\n            result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n        }\n        return result;\n    }\n\n    hasTransition(): boolean {\n        for (const property of Object.keys(this._values)) {\n            if (this._values[property].prior) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n\n// ------- Layout -------\n\n/**\n * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than\n * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then\n * fully evaluated.\n *\n * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n */\nexport class Layout<Props> {\n    _properties: Properties<Props>;\n    _values: {[K in keyof Props]: PropertyValue<any, PossiblyEvaluatedPropertyValue<any>>};\n    private _globalState: Record<string, any>; // reference to global state\n    private _rootKey: string;\n\n    constructor(properties: Properties<Props>, rootKey: string, globalState: Record<string, any>) {\n        this._properties = properties;\n        this._values = (Object.create(properties.defaultPropertyValues));\n        this._globalState = globalState;\n        this._rootKey = rootKey;\n    }\n\n    /** rootKey of a property, e.g. `layers[3].layout.line-cap`. */\n    private _propertyRootKey(name: keyof Props): string {\n        return `${this._rootKey}.${String(name)}`;\n    }\n\n    hasValue<S extends keyof Props>(name: S): boolean {\n        return this._values[name].value !== undefined;\n    }\n\n    hasProperty(name: string): boolean {\n        return name in this._properties.defaultPropertyValues;\n    }\n\n    getValue<S extends keyof Props>(name: S): any {\n        return clone(this._values[name].value);\n    }\n\n    setValue<S extends keyof Props>(name: S, value: any): void {\n        this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value), this._propertyRootKey(name), this._globalState) as any;\n    }\n\n    serialize(): any {\n        const result: any = {};\n        for (const property of Object.keys(this._values)) {\n            const value = this.getValue(property as keyof Props);\n            if (value !== undefined) {\n                result[property] = value;\n            }\n        }\n        return result;\n    }\n\n    possiblyEvaluate(\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): PossiblyEvaluated<Props, any> {\n        const result = new PossiblyEvaluated(this._properties);\n        for (const property of Object.keys(this._values)) {\n            result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n        }\n        return result;\n    }\n}\n\n// ------- PossiblyEvaluated -------\n\n/**\n * \"Possibly evaluated value\" is an intermediate stage in the evaluation chain for both paint and layout property\n * values. The purpose of this stage is to optimize away unnecessary recalculations for data-driven properties. Code\n * which uses data-driven property values must assume that the value is dependent on feature data, and request that it\n * be evaluated for each feature. But when that property value is in fact a constant or camera function, the calculation\n * will not actually depend on the feature, and we can benefit from returning the prior result of having done the\n * evaluation once, ahead of time, in an intermediate step whose inputs are just the value and \"global\" parameters\n * such as current zoom level.\n *\n * `PossiblyEvaluatedValue` represents the three possible outcomes of this step: if the input value was a constant or\n * camera expression, then the \"possibly evaluated\" result is a constant value. Otherwise, the input value was either\n * a source or composite expression, and we must defer final evaluation until supplied a feature. We separate\n * the source and composite cases because they are handled differently when generating GL attributes, buffers, and\n * uniforms.\n *\n * Note that `PossiblyEvaluatedValue` (and `PossiblyEvaluatedPropertyValue`, below) are _not_ used for properties that\n * do not allow data-driven values. For such properties, we know that the \"possibly evaluated\" result is always a constant\n * scalar value. See below.\n */\ntype PossiblyEvaluatedValue<T> = {\n    kind: 'constant';\n    value: T;\n} | SourceExpression | CompositeExpression;\n\n/**\n * @internal\n * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a\n * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply\n * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the\n * case where the input value was a constant or camera function.\n */\nexport class PossiblyEvaluatedPropertyValue<T> {\n    property: DataDrivenProperty<T>;\n    value: PossiblyEvaluatedValue<T>;\n    parameters: EvaluationParameters;\n\n    constructor(property: DataDrivenProperty<T>, value: PossiblyEvaluatedValue<T>, parameters: EvaluationParameters) {\n        this.property = property;\n        this.value = value;\n        this.parameters = parameters;\n    }\n\n    isConstant(): boolean {\n        return this.value.kind === 'constant';\n    }\n\n    constantOr(value: T): T {\n        if (this.value.kind === 'constant') {\n            return this.value.value;\n        } else {\n            return value;\n        }\n    }\n\n    evaluate(\n        feature: Feature,\n        featureState: FeatureState,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): T {\n        return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages);\n    }\n}\n\n/**\n * @internal\n * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a\n * given layer type.\n */\nexport class PossiblyEvaluated<Props, PossibleEvaluatedProps> {\n    _properties: Properties<Props>;\n    _values: PossibleEvaluatedProps;\n\n    constructor(properties: Properties<Props>) {\n        this._properties = properties;\n        this._values = Object.create(properties.defaultPossiblyEvaluatedValues);\n    }\n\n    get<S extends keyof PossibleEvaluatedProps>(name: S): PossibleEvaluatedProps[S] {\n        return this._values[name];\n    }\n}\n\n/**\n * Returns the length of the array value, or undefined if the value is not an array or a style spec array wrapper.\n */\nfunction getArrayValueLength(value: unknown): number | undefined {\n    if (Array.isArray(value)) {\n        return value.length;\n    }\n    const values = (value as {values?: unknown})?.values;\n    return Array.isArray(values) ? values.length : undefined;\n}\n\n/**\n * Returns true if the two values are arrays of different length, either bare arrays or style spec array wrappers.\n */\nfunction isNonInterpolableArrayChange(a: unknown, b: unknown): boolean {\n    const lengthA = getArrayValueLength(a);\n    const lengthB = getArrayValueLength(b);\n    return lengthA !== undefined && lengthB !== undefined && lengthA !== lengthB;\n}\n\n/**\n * @internal\n * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions.\n * This restriction allows us to declare statically that the result of possibly evaluating this kind of property\n * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis.\n */\nexport class DataConstantProperty<T> implements Property<T, T> {\n    specification: StylePropertySpecification;\n    name: string;\n\n    constructor(specification: StylePropertySpecification, name: string) {\n        this.specification = specification;\n        this.name = name;\n    }\n\n    possiblyEvaluate(value: PropertyValue<T, T>, parameters: EvaluationParameters): T {\n        if (value.isDataDriven()) throw new Error('Value should not be data driven');\n        return value.expression.evaluate(parameters);\n    }\n\n    interpolate(a: T, b: T, t: number): T {\n        if (isNonInterpolableArrayChange(a, b)) {\n            warnOnce(`Property \"${this.name}\" is trying to interpolate arrays of different lengths. Rendering may 'jump'.`);\n            return b;\n        }\n        const interpolationType = this.specification.type as keyof typeof interpolates;\n        const interpolationFn = interpolates[interpolationType] as ((from: T, to: T, t: number) => T) | undefined;\n        if (interpolationFn) {\n            return interpolationFn(a, b, t);\n        } else {\n            return a;\n        }\n    }\n}\n\n/**\n * @internal\n * An implementation of `Property` for properties that permit data-driven (source or composite) expressions.\n * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue<T>`; obtaining\n * a scalar value `T` requires further evaluation on a per-feature basis.\n */\nexport class DataDrivenProperty<T> implements Property<T, PossiblyEvaluatedPropertyValue<T>> {\n    specification: StylePropertySpecification;\n    name: string;\n    overrides: any;\n\n    constructor(specification: StylePropertySpecification, name: string, overrides?: any) {\n        this.specification = specification;\n        this.name = name;\n        this.overrides = overrides;\n    }\n\n    possiblyEvaluate(\n        value: PropertyValue<T, PossiblyEvaluatedPropertyValue<T>>,\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): PossiblyEvaluatedPropertyValue<T> {\n        if (value.expression.kind === 'constant' || value.expression.kind === 'camera') {\n            return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: value.expression.evaluate(parameters, null, {}, canonical, availableImages)}, parameters);\n        } else {\n            return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n        }\n    }\n\n    interpolate(\n        a: PossiblyEvaluatedPropertyValue<T>,\n        b: PossiblyEvaluatedPropertyValue<T>,\n        t: number\n    ): PossiblyEvaluatedPropertyValue<T> {\n        // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values.\n        if (a.value.kind !== 'constant' || b.value.kind !== 'constant') {\n            return a;\n        }\n\n        // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in\n        // FillStyleLayer.recalculate, which sets fill-outline-color to the fill-color value if the former\n        // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the\n        // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant\n        // undefined value is the \"default value\" for fill-outline-color held in\n        // `Properties.defaultPossiblyEvaluatedValues`, which serves as the prototype of\n        // `PossiblyEvaluated._values`.\n        if (a.value.value === undefined || b.value.value === undefined) {\n            return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: undefined}, a.parameters);\n        }\n\n        if (isNonInterpolableArrayChange(a.value.value, b.value.value)) {\n            warnOnce(`Property \"${this.name}\" is trying to interpolate arrays of different lengths. Rendering may 'jump'.`);\n            return b;\n        }\n\n        const interpolationType = this.specification.type as keyof typeof interpolates;\n        const interpolationFn = interpolates[interpolationType] as ((from: T, to: T, t: number) => T) | undefined;\n        if (interpolationFn) {\n            const interpolatedValue = interpolationFn(a.value.value, b.value.value, t);\n            return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: interpolatedValue}, a.parameters);\n        } else {\n            return a;\n        }\n    }\n\n    evaluate(\n        value: PossiblyEvaluatedValue<T>,\n        parameters: EvaluationParameters,\n        feature: Feature,\n        featureState: FeatureState,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): T {\n        if (value.kind === 'constant') {\n            return value.value;\n        } else {\n            return value.evaluate(parameters, feature, featureState, canonical, availableImages);\n        }\n    }\n}\n\n/**\n * @internal\n * An implementation of `Property` for  data driven `line-pattern` which are transitioned by cross-fading\n * rather than interpolation.\n */\n\nexport class CrossFadedDataDrivenProperty<T> extends DataDrivenProperty<CrossFaded<T>> {\n\n    possiblyEvaluate(\n        value: PropertyValue<CrossFaded<T>, PossiblyEvaluatedPropertyValue<CrossFaded<T>>>,\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): PossiblyEvaluatedPropertyValue<CrossFaded<T>> {\n        if (value.value === undefined) {\n            return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: undefined}, parameters);\n        } else if (value.expression.kind === 'constant') {\n            const evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages);\n            const isImageExpression = value.property.specification.type as any === 'resolvedImage';\n            const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue;\n            const constant = this._calculate(constantValue, constantValue, constantValue, parameters);\n            return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: constant}, parameters);\n        } else if (value.expression.kind === 'camera') {\n            const cameraVal = this._calculate(\n                value.expression.evaluate({zoom: parameters.zoom - 1.0}),\n                value.expression.evaluate({zoom: parameters.zoom}),\n                value.expression.evaluate({zoom: parameters.zoom + 1.0}),\n                parameters);\n            return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: cameraVal}, parameters);\n        } else {\n            // source or composite expression\n            return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n        }\n    }\n\n    evaluate(\n        value: PossiblyEvaluatedValue<CrossFaded<T>>,\n        globals: EvaluationParameters,\n        feature: Feature,\n        featureState: FeatureState,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): CrossFaded<T> {\n        if (value.kind === 'source') {\n            const constant = value.evaluate(globals, feature, featureState, canonical, availableImages);\n            return this._calculate(constant, constant, constant, globals);\n        } else if (value.kind === 'composite') {\n            return this._calculate(\n                value.evaluate({zoom: Math.floor(globals.zoom) - 1.0}, feature, featureState),\n                value.evaluate({zoom: Math.floor(globals.zoom)}, feature, featureState),\n                value.evaluate({zoom: Math.floor(globals.zoom) + 1.0}, feature, featureState),\n                globals);\n        } else {\n            return value.value;\n        }\n    }\n\n    _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded<T> {\n        const z = parameters.zoom;\n        return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid};\n    }\n\n    interpolate(a: PossiblyEvaluatedPropertyValue<CrossFaded<T>>): PossiblyEvaluatedPropertyValue<CrossFaded<T>> {\n        return a;\n    }\n}\n/**\n * @internal\n * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading\n * rather than interpolation.\n */\nexport class CrossFadedProperty<T> implements Property<T, CrossFaded<T>> {\n    specification: StylePropertySpecification;\n    name: string;\n\n    constructor(specification: StylePropertySpecification, name: string) {\n        this.specification = specification;\n        this.name = name;\n    }\n\n    possiblyEvaluate(\n        value: PropertyValue<T, CrossFaded<T>>,\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): CrossFaded<T> {\n        if (value.value === undefined) {\n            return undefined;\n        } else if (value.expression.kind === 'constant') {\n            const constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages);\n            return this._calculate(constant, constant, constant, parameters);\n        } else {\n            return this._calculate(\n                value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)),\n                value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)),\n                value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)),\n                parameters);\n        }\n    }\n\n    _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded<T> {\n        const z = parameters.zoom;\n        return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid};\n    }\n\n    interpolate(a?: CrossFaded<T> | null): CrossFaded<T> {\n        return a;\n    }\n}\n\n/**\n * @internal\n * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and\n * evaluation returns a boolean value in order to indicate its presence, but the real\n * evaluation happens in StyleLayer classes.\n */\n\nexport class ColorRampProperty implements Property<Color, boolean> {\n    specification: StylePropertySpecification;\n    name: string;\n\n    constructor(specification: StylePropertySpecification, name: string) {\n        this.specification = specification;\n        this.name = name;\n    }\n\n    possiblyEvaluate(\n        value: PropertyValue<Color, boolean>,\n        parameters: EvaluationParameters,\n        canonical?: CanonicalTileID,\n        availableImages?: string[]\n    ): boolean {\n        return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages);\n    }\n\n    interpolate(): boolean { return false; }\n}\n\n/**\n * @internal\n * `Properties` holds objects containing default values for the layout or paint property set of a given\n * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of\n * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid\n * doing work in the common case where a property has no explicit value set and should be considered to take\n * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over\n * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final\n * evaluations for defaults, the result of which will always be the same.\n */\nexport class Properties<Props> {\n    properties: Props;\n    defaultPropertyValues: {[K in keyof Props]: PropertyValue<unknown, any>};\n    defaultTransitionablePropertyValues: {[K in keyof Props]: TransitionablePropertyValue<unknown, unknown>};\n    defaultTransitioningPropertyValues: {[K in keyof Props]: TransitioningPropertyValue<unknown, unknown>};\n    defaultPossiblyEvaluatedValues: {[K in keyof Props]: PossiblyEvaluatedPropertyValue<unknown>};\n    overridableProperties: string[];\n\n    constructor(properties: Props) {\n        this.properties = properties;\n        this.defaultPropertyValues = ({} as any);\n        this.defaultTransitionablePropertyValues = ({} as any);\n        this.defaultTransitioningPropertyValues = ({} as any);\n        this.defaultPossiblyEvaluatedValues = ({} as any);\n        this.overridableProperties = ([]);\n\n        for (const property in properties) {\n            const prop = properties[property] as any;\n            if (prop.specification.overridable) {\n                this.overridableProperties.push(property);\n            }\n            // These defaults are shared across all layers, so we only have the property name as a location\n            // here. The full location (e.g. `layers[3].paint.line-color`) is filled in later when an actual\n            // value is set through Transitionable/Layout.\n            const defaultPropertyValue = this.defaultPropertyValues[property] =\n                new PropertyValue(prop, undefined, prop.name, undefined);\n            const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] =\n                new TransitionablePropertyValue(prop, prop.name, undefined);\n            this.defaultTransitioningPropertyValues[property] =\n                defaultTransitionablePropertyValue.untransitioned();\n            this.defaultPossiblyEvaluatedValues[property] =\n                defaultPropertyValue.possiblyEvaluate({} as any);\n        }\n    }\n}\n\nregister('DataDrivenProperty', DataDrivenProperty);\nregister('DataConstantProperty', DataConstantProperty);\nregister('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty);\nregister('CrossFadedProperty', CrossFadedProperty);\nregister('ColorRampProperty', ColorRampProperty);\n", "import {filterObject} from '../util/util.ts';\nimport {createVisibilityExpression, featureFilter, supportsPropertyExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {validateStyle, validateAndEmit, type Validator} from './validate_style.ts';\nimport {Evented, ErrorEvent, type ErrorEventType} from '../util/evented.ts';\nimport {Layout, Transitionable, type Transitioning, type Properties, PossiblyEvaluated, PossiblyEvaluatedPropertyValue, TRANSITION_SUFFIX} from './properties.ts';\n\nimport type {mat4} from 'gl-matrix';\nimport type {Bucket, BucketParameters} from '../data/bucket.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {\n    FeatureFilter,\n    FeatureState,\n    LayerSpecification,\n    FilterSpecification,\n    VisibilitySpecification,\n    VisibilityExpression,\n    AllPaintProperties,\n    AllLayoutProperties,\n} from '@maplibre/maplibre-gl-style-spec';\nimport type {TransitionParameters, PropertyValue} from './properties.ts';\nimport type {EvaluationParameters} from './evaluation_parameters.ts';\nimport type {CrossfadeParameters} from './evaluation_parameters.ts';\nimport type {IReadonlyTransform, GetElevation} from '../geo/transform_interface.ts';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer.ts';\nimport type {Map} from '../ui/map.ts';\nimport type {StyleSetterOptions} from './style.ts';\nimport type {UnwrappedTileID} from '../tile/tile_id.ts';\nimport type {VectorTileFeatureLike} from '@maplibre/vt-pbf';\n\nexport type PaintPropertyEntry = { [K in keyof AllPaintProperties]: {name: K; value: AllPaintProperties[K]} }[keyof AllPaintProperties];\n\nexport type QueryIntersectsFeatureParams = {\n    /**\n     * The geometry to check intersection with.\n     * This geometry is in tile coordinates.\n     */\n    queryGeometry: Point[];\n    /**\n     * The feature to allow expression evaluation.\n     */\n    feature: VectorTileFeatureLike;\n    /**\n     * The feature state to allow expression evaluation.\n     */\n    featureState: FeatureState;\n    /**\n     * The geometry of the feature.\n     * This geometry is in tile coordinates.\n     */\n    geometry: Point[][];\n    /**\n     * The current zoom level.\n     */\n    zoom: number;\n    /**\n     * The transform to convert from tile coordinates to pixels.\n     */\n    transform: IReadonlyTransform;\n    /**\n     * The number of pixels per tile unit.\n     */\n    pixelsToTileUnits: number;\n    /**\n     * The matrix to convert from tile coordinates to pixel coordinates.\n     * The pixel coordinates are relative to the center of the screen.\n     */\n    pixelPosMatrix: mat4;\n    /**\n     * The unwrapped tile ID for the tile being queried.\n     */\n    unwrappedTileID: UnwrappedTileID;\n    /**\n     * A function to get the elevation of a point in tile coordinates.\n     */\n    getElevation: GetElevation | undefined;\n};\n\nconst ERROR_PAINT_NOT_LAYOUT = ' is a PAINT property not a LAYOUT property. Use get/setPaintProperty instead?';\nconst ERROR_LAYOUT_NOT_PAINT = ' is a LAYOUT property not a PAINT property. Use get/setLayoutProperty instead?';\n\n/**\n * A base class for style layers\n */\nexport abstract class StyleLayer extends Evented<ErrorEventType> {\n    id: string;\n    metadata: unknown;\n    type: LayerSpecification['type'] | CustomLayerInterface['type'];\n    source: string;\n    sourceLayer: string;\n    minzoom: number;\n    maxzoom: number;\n    filter: FilterSpecification | void;\n    visibility: VisibilitySpecification;\n    private _evaluatedVisibility: 'visible' | 'none' | void;\n\n    _crossfadeParameters: CrossfadeParameters;\n\n    _unevaluatedLayout: Layout<any>;\n    readonly layout: unknown;\n\n    _transitionablePaint: Transitionable<any>;\n    _transitioningPaint: Transitioning<any>;\n    readonly paint: unknown;\n\n    _featureFilter: FeatureFilter;\n\n    _visibilityExpression: VisibilityExpression;\n\n    readonly onAdd: ((map: Map) => void);\n    readonly onRemove: ((map: Map) => void);\n\n    queryRadius?(bucket: Bucket): number;\n    queryIntersectsFeature?(params: QueryIntersectsFeatureParams): boolean | number;\n    createBucket?(parameters: BucketParameters<any>): Bucket;\n\n    private _globalState: Record<string, any>; // reference to global state\n\n    constructor(layer: LayerSpecification | CustomLayerInterface, properties: Readonly<{\n        layout?: Properties<any>;\n        paint?: Properties<any>;\n    }>, globalState: Record<string, any>) {\n        super();\n\n        this.id = layer.id;\n        this.type = layer.type;\n        this._globalState = globalState;\n        this._featureFilter = {filter: () => true, needGeometry: false, getGlobalStateRefs: () => new Set<string>()};\n        this._visibilityExpression = createVisibilityExpression(this.visibility, `layers[${this.id}].layout.visibility`, globalState);\n\n        if (layer.type === 'custom') return;\n\n        this.metadata = layer.metadata;\n        this.minzoom = layer.minzoom;\n        this.maxzoom = layer.maxzoom;\n\n        if (layer.type !== 'background') {\n            this.source = layer.source;\n            this.sourceLayer = layer['source-layer'];\n            this.filter = layer.filter;\n            this._featureFilter = featureFilter(layer.filter, `layers[${this.id}].filter`, globalState);\n        }\n\n        if (properties.layout) {\n            this._unevaluatedLayout = new Layout(properties.layout, `layers[${this.id}].layout`, globalState);\n        }\n\n        if (properties.paint) {\n            this._transitionablePaint = new Transitionable(properties.paint, `layers[${this.id}].paint`, globalState);\n\n            for (const property in layer.paint) {\n                this.setPaintProperty(property as keyof AllPaintProperties, layer.paint[property as keyof typeof layer.paint], {validate: false});\n            }\n            for (const property in layer.layout) {\n                this.setLayoutProperty(property as keyof AllLayoutProperties, layer.layout[property as keyof typeof layer.layout], {validate: false});\n            }\n\n            this._transitioningPaint = this._transitionablePaint.untransitioned();\n            this.paint = new PossiblyEvaluated(properties.paint);\n        }\n    }\n\n    setFilter(filter: FilterSpecification | void): void {\n        this.filter = filter;\n        this._featureFilter = featureFilter(filter, `layers[${this.id}].filter`, this._globalState);\n    }\n\n    getCrossfadeParameters(): CrossfadeParameters {\n        return this._crossfadeParameters;\n    }\n\n    getLayoutProperty<K extends keyof AllLayoutProperties>(name: K): AllLayoutProperties[K] {\n        if (name === 'visibility') {\n            // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- otherwise typescript fails with error TS2590: Expression produces a union type that is too complex to represent\n            return this.visibility as AllLayoutProperties[K];\n        }\n        if (this._transitionablePaint?.hasProperty(name)) {\n            throw new Error(name + ERROR_PAINT_NOT_LAYOUT);\n        }\n        if (!this._unevaluatedLayout) {\n            throw new Error(`Cannot get layout property \"${name}\" on layer type \"${this.type}\" which has no layout properties.`);\n        }\n        return this._unevaluatedLayout.getValue(name);\n    }\n\n    /**\n     * Get list of global state references that are used within layout or filter properties.\n     * This is used to determine if layer source need to be reloaded when global state property changes.\n     *\n     */\n    getLayoutAffectingGlobalStateRefs(): Set<string> {\n        const globalStateRefs = new Set<string>();\n\n        for (const globalStateRef of this._visibilityExpression.getGlobalStateRefs()) {\n            globalStateRefs.add(globalStateRef);\n        }\n\n        if (this._unevaluatedLayout) {\n            for (const propertyName in this._unevaluatedLayout._values) {\n                const value = this._unevaluatedLayout._values[propertyName];\n\n                for (const globalStateRef of value.getGlobalStateRefs()) {\n                    globalStateRefs.add(globalStateRef);\n                }\n            }\n        }\n\n        for (const globalStateRef of this._featureFilter.getGlobalStateRefs()) {\n            globalStateRefs.add(globalStateRef);\n        }\n\n        return globalStateRefs;\n    }\n\n    /**\n     * Get list of global state references that are used within paint properties.\n     * This is used to determine if layer needs to be repainted when global state property changes.\n     *\n     */\n    getPaintAffectingGlobalStateRefs(): globalThis.Map<string, PaintPropertyEntry[]> {\n        const globalStateRefs = new globalThis.Map<string, PaintPropertyEntry[]>();\n\n        if (this._transitionablePaint) {\n            for (const propertyName in this._transitionablePaint._values) {\n                const value = this._transitionablePaint._values[propertyName].value;\n\n                for (const globalStateRef of value.getGlobalStateRefs()) {\n                    const properties = globalStateRefs.get(globalStateRef) ?? [];\n                    properties.push({name: propertyName as keyof AllPaintProperties, value: value.value} as PaintPropertyEntry);\n                    globalStateRefs.set(globalStateRef, properties);\n                }\n            }\n        }\n\n        return globalStateRefs;\n    }\n\n    /**\n     * Get list of global state references that are used within visibility expression.\n     * This is used to determine if layer visibility needs to be updated when global state property changes.\n     */\n    getVisibilityAffectingGlobalStateRefs(): Set<string> {\n        return this._visibilityExpression.getGlobalStateRefs();\n    }\n\n    setLayoutProperty<K extends keyof AllLayoutProperties>(name: K, value: AllLayoutProperties[K], options: StyleSetterOptions = {}): void {\n        if (name === 'visibility') {\n            this.visibility = value as VisibilitySpecification;\n            this._visibilityExpression.setValue(value as VisibilitySpecification);\n            this.recalculateVisibility();\n            return;\n        }\n\n        if (this._transitionablePaint?.hasProperty(name)) {\n            this.fire(new ErrorEvent(new Error(name + ERROR_PAINT_NOT_LAYOUT)));\n            return;\n        }\n\n        if (value !== null && value !== undefined && this._validate(validateStyle.layoutProperty, `layers.${this.id}.layout.${name}`, name, value, options))  return;\n\n        this._unevaluatedLayout.setValue(name, value);\n    }\n\n    getPaintProperty<K extends keyof AllPaintProperties>(name: K): AllPaintProperties[K] {\n        if (name.endsWith(TRANSITION_SUFFIX)) {\n            const baseName = name.slice(0, -TRANSITION_SUFFIX.length);\n            if (baseName === 'visibility' || this._unevaluatedLayout?.hasProperty(baseName)) {\n                throw new Error(name + ERROR_LAYOUT_NOT_PAINT);\n            }\n            // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- otherwise typescript fails with error TS2590: Expression produces a union type that is too complex to represent\n            return this._transitionablePaint.getTransition(baseName) as AllPaintProperties[K];\n        } else {\n            if (name as any === 'visibility' || this._unevaluatedLayout?.hasProperty(name)) {\n                throw new Error(name + ERROR_LAYOUT_NOT_PAINT);\n            }\n            // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- otherwise typescript fails with error TS2590: Expression produces a union type that is too complex to represent\n            return this._transitionablePaint.getValue(name) as AllPaintProperties[K];\n        }\n    }\n\n    setPaintProperty<K extends keyof AllPaintProperties>(name: K, value: AllPaintProperties[K], options: StyleSetterOptions = {}): boolean {\n        if (name as any === 'visibility' || this._unevaluatedLayout?.hasProperty(name)) {\n            this.fire(new ErrorEvent(new Error(name + ERROR_LAYOUT_NOT_PAINT)));\n            return false;\n        }\n\n        if (value !== null && value !== undefined && this._validate(validateStyle.paintProperty, `layers.${this.id}.paint.${name}`, name, value, options)) return false;\n\n        if (name.endsWith(TRANSITION_SUFFIX)) {\n            this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), (value as any) || undefined);\n            return false;\n        } else {\n            const transitionable = this._transitionablePaint._values[name];\n            const isCrossFadedProperty = transitionable.property.specification['property-type'] === 'cross-faded-data-driven';\n            const wasDataDriven = transitionable.value.isDataDriven();\n            const oldValue = transitionable.value;\n\n            // Transitionable.setValue uses a free-floating T that can't unify with the AllPaintProperties union -> better types downstream of this code needed\n            this._transitionablePaint.setValue(name, value as any);\n            this._handleSpecialPaintPropertyUpdate(name);\n\n            const newValue = this._transitionablePaint._values[name].value;\n            const isDataDriven = newValue.isDataDriven();\n\n            // if a cross-faded value is changed, we need to make sure the new icons get added to each tile's iconAtlas\n            // so a call to _updateLayer is necessary, and we return true from this function so it gets called in\n            // Style.setPaintProperty\n            return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue);\n        }\n    }\n\n    _handleSpecialPaintPropertyUpdate(_: string): void {\n        // No-op; can be overridden by derived classes.\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _handleOverridablePaintPropertyUpdate<T, R>(name: string, oldValue: PropertyValue<T, R>, newValue: PropertyValue<T, R>): boolean {\n        // No-op; can be overridden by derived classes.\n        return false;\n    }\n\n    isHidden(zoom: number = this.minzoom, roundMinZoom: boolean = false): boolean {\n        if (this.minzoom && zoom < (roundMinZoom ? Math.floor(this.minzoom) : this.minzoom)) return true;\n        if (this.maxzoom && zoom >= this.maxzoom) return true;\n        return this._evaluatedVisibility === 'none';\n    }\n\n    updateTransitions(parameters: TransitionParameters): void {\n        this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint);\n    }\n\n    /** The re-read itself goes through `setPaintProperty`, which also rebuilds colour ramps and relayouts. */\n    retainPriorGlobalState(refs: string[], priorGlobalState: Record<string, any>): void {\n        this._transitionablePaint?.retainPriorGlobalState(refs, priorGlobalState, this._transitioningPaint);\n    }\n\n    hasTransition(): boolean {\n        return this._transitioningPaint.hasTransition();\n    }\n\n    recalculateVisibility(): void {\n        this._evaluatedVisibility = this._visibilityExpression.evaluate();\n    }\n\n    recalculate(parameters: EvaluationParameters, availableImages: string[]): void {\n        if (parameters.getCrossfadeParameters) {\n            this._crossfadeParameters = parameters.getCrossfadeParameters();\n        }\n\n        if (this._unevaluatedLayout) {\n            (this as any).layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages);\n        }\n\n        (this as any).paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages);\n    }\n\n    serialize(): LayerSpecification {\n        const output: LayerSpecification = {\n            'id': this.id,\n            'type': this.type as LayerSpecification['type'],\n            'source': this.source,\n            'source-layer': this.sourceLayer,\n            'metadata': this.metadata,\n            'minzoom': this.minzoom,\n            'maxzoom': this.maxzoom,\n            'filter': this.filter as FilterSpecification,\n            'layout': this._unevaluatedLayout?.serialize(),\n            'paint': this._transitionablePaint?.serialize()\n        };\n\n        if (this.visibility) {\n            output.layout ||= {};\n            output.layout.visibility = this.visibility;\n        }\n\n        return filterObject(output, (value, key) => {\n            return value !== undefined &&\n                !(key === 'layout' && !Object.keys(value).length) &&\n                !(key === 'paint' && !Object.keys(value).length);\n        });\n    }\n\n    _validate(validate: Validator, key: string, name: string, value: unknown, options: StyleSetterOptions = {}): boolean {\n        return validateAndEmit(this, validate, {\n            key,\n            layerType: this.type,\n            objectKey: name,\n            value\n        }, options);\n    }\n\n    is3D(): boolean {\n        return false;\n    }\n\n    isTileClipped(): boolean {\n        return false;\n    }\n\n    hasOffscreenPass(): boolean {\n        return false;\n    }\n\n    resize(): void {\n        // noop\n    }\n\n    isStateDependent(): boolean {\n        for (const property in (this as any).paint._values) {\n            const value = (this as any).paint.get(property);\n            if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n                continue;\n            }\n\n            if ((value.value.kind === 'source' || value.value.kind === 'composite') &&\n                value.value.isStateDependent) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type RasterPaintProps = {\n    \"raster-opacity\": DataConstantProperty<number>,\n    \"raster-hue-rotate\": DataConstantProperty<number>,\n    \"raster-brightness-min\": DataConstantProperty<number>,\n    \"raster-brightness-max\": DataConstantProperty<number>,\n    \"raster-saturation\": DataConstantProperty<number>,\n    \"raster-contrast\": DataConstantProperty<number>,\n    \"resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n    \"raster-resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n    \"raster-fade-duration\": DataConstantProperty<number>,\n};\n\nexport type RasterPaintPropsPossiblyEvaluated = {\n    \"raster-opacity\": number,\n    \"raster-hue-rotate\": number,\n    \"raster-brightness-min\": number,\n    \"raster-brightness-max\": number,\n    \"raster-saturation\": number,\n    \"raster-contrast\": number,\n    \"resampling\": \"linear\" | \"nearest\",\n    \"raster-resampling\": \"linear\" | \"nearest\",\n    \"raster-fade-duration\": number,\n};\n\nlet paint: Properties<RasterPaintProps>;\nconst getPaint = (): Properties<RasterPaintProps> => paint = paint || new Properties({\n    \"raster-opacity\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-opacity\"] as any as StylePropertySpecification, \"raster-opacity\"),\n    \"raster-hue-rotate\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-hue-rotate\"] as any as StylePropertySpecification, \"raster-hue-rotate\"),\n    \"raster-brightness-min\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-min\"] as any as StylePropertySpecification, \"raster-brightness-min\"),\n    \"raster-brightness-max\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-max\"] as any as StylePropertySpecification, \"raster-brightness-max\"),\n    \"raster-saturation\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-saturation\"] as any as StylePropertySpecification, \"raster-saturation\"),\n    \"raster-contrast\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-contrast\"] as any as StylePropertySpecification, \"raster-contrast\"),\n    \"resampling\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"resampling\"] as any as StylePropertySpecification, \"resampling\"),\n    \"raster-resampling\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-resampling\"] as any as StylePropertySpecification, \"raster-resampling\"),\n    \"raster-fade-duration\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-fade-duration\"] as any as StylePropertySpecification, \"raster-fade-duration\"),\n});\n\nexport default ({ get paint(): Properties<RasterPaintProps> { return getPaint() } });", "import {StyleLayer} from '../style_layer.ts';\nimport properties, {type RasterPaintPropsPossiblyEvaluated} from './raster_style_layer_properties.g.ts';\n\nimport type {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.ts';\nimport type {RasterPaintProps} from './raster_style_layer_properties.g.ts';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport const isRasterStyleLayer = (layer: StyleLayer): layer is RasterStyleLayer => layer.type === 'raster';\n\nexport class RasterStyleLayer extends StyleLayer {\n    _transitionablePaint: Transitionable<RasterPaintProps>;\n    _transitioningPaint: Transitioning<RasterPaintProps>;\n    paint: PossiblyEvaluated<RasterPaintProps, RasterPaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n    }\n}\n", "// Note: all \"sizes\" are measured in bytes\n\n/**\n * @internal\n * A view type size\n */\nconst viewTypes: {\n    Int8: Int8ArrayConstructor;\n    Uint8: Uint8ArrayConstructor;\n    Int16: Int16ArrayConstructor;\n    Uint16: Uint16ArrayConstructor;\n    Int32: Int32ArrayConstructor;\n    Uint32: Uint32ArrayConstructor;\n    Float32: Float32ArrayConstructor;\n} = {\n    'Int8': Int8Array,\n    'Uint8': Uint8Array,\n    'Int16': Int16Array,\n    'Uint16': Uint16Array,\n    'Int32': Int32Array,\n    'Uint32': Uint32Array,\n    'Float32': Float32Array\n};\n\n/**\n * @internal\n * A view type size\n */\nexport type ViewType = keyof typeof viewTypes;\n\n/** @internal */\nclass Struct {\n    _pos1: number;\n    _pos2: number;\n    _pos4: number;\n    _pos8: number;\n    readonly _structArray: StructArray;\n\n    // The following properties are defined on the prototype of sub classes.\n    size: number;\n\n    /**\n     * @param structArray - The StructArray the struct is stored in\n     * @param index - The index of the struct in the StructArray.\n     */\n    constructor(structArray: StructArray, index: number) {\n        (this as any)._structArray = structArray;\n        this._pos1 = index * this.size;\n        this._pos2 = this._pos1 / 2;\n        this._pos4 = this._pos1 / 4;\n        this._pos8 = this._pos1 / 8;\n    }\n}\n\nconst DEFAULT_CAPACITY = 128;\nconst RESIZE_MULTIPLIER = 5;\n\n/**\n * @internal\n * A struct array member\n */\nexport type StructArrayMember = {\n    name: string;\n    type: ViewType;\n    components: number;\n    offset: number;\n};\n\nexport type StructArrayLayout = {\n    members: StructArrayMember[];\n    size: number;\n    alignment: number;\n};\n\n/**\n * An array that can be deserialized\n */\nexport type SerializedStructArray = {\n    length: number;\n    arrayBuffer: ArrayBuffer;\n};\n\n/**\n * @internal\n * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray`\n * making it behave like an array of typed structs.\n *\n * Conceptually, a StructArray is comprised of elements, i.e., instances of its\n * associated struct type. Each particular struct type, together with an\n * alignment size, determines the memory layout of a StructArray whose elements\n * are of that type.  Thus, for each such layout that we need, we have\n * a corresponding StructArrayLayout class, inheriting from StructArray and\n * implementing `emplaceBack()` and `_refreshViews()`.\n *\n * In some cases, where we need to access particular elements of a StructArray,\n * we implement a more specific subclass that inherits from one of the\n * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured\n * object whose properties are proxies into the underlying memory space for the\n * i-th element.  This affords the convenience of working with (seemingly) plain\n * Javascript objects without the overhead of serializing/deserializing them\n * into ArrayBuffers for efficient web worker transfer.\n */\nabstract class StructArray {\n    capacity: number;\n    length: number;\n    isTransferred: boolean;\n    arrayBuffer: ArrayBuffer;\n    uint8: Uint8Array;\n\n    // The following properties are defined on the prototype.\n    members: StructArrayMember[];\n    bytesPerElement: number;\n    abstract emplaceBack(...v: number[]): number;\n    abstract emplace(i: number, ...v: number[]): number;\n\n    constructor() {\n        this.isTransferred = false;\n        this.capacity = -1;\n        this.resize(0);\n    }\n\n    /**\n     * Serialize a StructArray instance.  Serializes both the raw data and the\n     * metadata needed to reconstruct the StructArray base class during\n     * deserialization.\n     */\n    static serialize(array: StructArray, transferables?: Transferable[]): SerializedStructArray {\n\n        array._trim();\n\n        if (transferables) {\n            array.isTransferred = true;\n            transferables.push(array.arrayBuffer);\n        }\n\n        return {\n            length: array.length,\n            arrayBuffer: array.arrayBuffer,\n        };\n    }\n\n    static deserialize<T extends StructArray>(this: {prototype: T} & (new () => T), input: SerializedStructArray): T {\n        const structArray: T = Object.create(this.prototype);\n        structArray.arrayBuffer = input.arrayBuffer;\n        structArray.length = input.length;\n        structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement;\n        structArray._refreshViews();\n        return structArray;\n    }\n\n    /**\n     * Resize the array to discard unused capacity.\n     */\n    _trim(): void {\n        if (this.length !== this.capacity) {\n            this.capacity = this.length;\n            this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement);\n            this._refreshViews();\n        }\n    }\n\n    /**\n     * Resets the length of the array to 0 without de-allocating capacity.\n     */\n    clear(): void {\n        this.length = 0;\n    }\n\n    /**\n     * Resize the array.\n     * If `n` is greater than the current length then additional elements with undefined values are added.\n     * If `n` is less than the current length then the array will be reduced to the first `n` elements.\n     * @param n - The new size of the array.\n     */\n    resize(n: number): void {\n        this.reserve(n);\n        this.length = n;\n    }\n\n    /**\n     * Indicate a planned increase in size, so that any necessary allocation may\n     * be done once, ahead of time.\n     * @param n - The expected size of the array.\n     */\n    reserve(n: number): void {\n        if (n > this.capacity) {\n            this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY);\n            this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);\n\n            const oldUint8Array = this.uint8;\n            this._refreshViews();\n            if (oldUint8Array) this.uint8.set(oldUint8Array);\n        }\n    }\n\n    /**\n     * Create TypedArray views for the current ArrayBuffer.\n     */\n    _refreshViews(): void {\n        throw new Error('_refreshViews() must be implemented by each concrete StructArray layout');\n    }\n\n    /**\n     * Replace the buffer with an empty one so typed views release the original ArrayBuffer for GC.\n     */\n    freeBufferAfterUpload(): void {\n        this.arrayBuffer = new ArrayBuffer(0);\n        this._refreshViews();\n    }\n}\n\n/**\n * Given a list of member fields, create a full StructArrayLayout, in\n * particular calculating the correct byte offset for each field.  This data\n * is used at build time to generate StructArrayLayout_*.emplaceBack() and\n * other accessors, and at runtime for binding vertex buffer attributes.\n */\nfunction createLayout(\n    members: Array<{\n        name: string;\n        type: ViewType;\n        readonly components?: number;\n    }>,\n    alignment: number = 1\n): StructArrayLayout {\n\n    let offset = 0;\n    let maxSize = 0;\n    const layoutMembers = members.map((member) => {\n        const typeSize = sizeOf(member.type);\n        const memberOffset = offset = align(offset, Math.max(alignment, typeSize));\n        const components = member.components || 1;\n\n        maxSize = Math.max(maxSize, typeSize);\n        offset += typeSize * components;\n\n        return {\n            name: member.name,\n            type: member.type,\n            components,\n            offset: memberOffset,\n        };\n    });\n\n    const size = align(offset, Math.max(maxSize, alignment));\n\n    return {\n        members: layoutMembers,\n        size,\n        alignment\n    };\n}\n\nfunction sizeOf(type: ViewType): number {\n    return viewTypes[type].BYTES_PER_ELEMENT;\n}\n\nfunction align(offset: number, size: number): number {\n    return Math.ceil(offset / size) * size;\n}\n\nexport {StructArray, Struct, viewTypes, createLayout};\n", "// This file is generated. Edit build/generate-struct-arrays.ts, then run `npm run codegen`.\n\nimport {Struct, StructArray} from '../util/struct_array.ts';\nimport {register} from '../util/web_worker_transfer.ts';\nimport Point from '@mapbox/point-geometry';\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n *\n */\nclass StructArrayLayout2i4 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1);\n    }\n\n    public emplace(i: number, v0: number, v1: number): number {\n        const o2 = i * 2;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        return i;\n    }\n}\n\nStructArrayLayout2i4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout2i4', StructArrayLayout2i4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[3]\n *\n */\nclass StructArrayLayout3i6 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number): number {\n        const o2 = i * 3;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.int16[o2 + 2] = v2;\n        return i;\n    }\n}\n\nStructArrayLayout3i6.prototype.bytesPerElement = 6;\nregister('StructArrayLayout3i6', StructArrayLayout3i6);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[4]\n *\n */\nclass StructArrayLayout4i8 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number): number {\n        const o2 = i * 4;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.int16[o2 + 2] = v2;\n        this.int16[o2 + 3] = v3;\n        return i;\n    }\n}\n\nStructArrayLayout4i8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout4i8', StructArrayLayout4i8);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Int16[4]\n *\n */\nclass StructArrayLayout2i4i12 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n        const o2 = i * 6;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.int16[o2 + 2] = v2;\n        this.int16[o2 + 3] = v3;\n        this.int16[o2 + 4] = v4;\n        this.int16[o2 + 5] = v5;\n        return i;\n    }\n}\n\nStructArrayLayout2i4i12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2i4i12', StructArrayLayout2i4i12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Uint8[4]\n * [8] - Int8[2]\n *\n */\nclass StructArrayLayout2i4ub2b10 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n    int8: Int8Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n        this.int8 = new Int8Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): number {\n        const o2 = i * 5;\n        const o1 = i * 10;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.uint8[o1 + 4] = v2;\n        this.uint8[o1 + 5] = v3;\n        this.uint8[o1 + 6] = v4;\n        this.uint8[o1 + 7] = v5;\n        this.int8[o1 + 8] = v6;\n        this.int8[o1 + 9] = v7;\n        return i;\n    }\n}\n\nStructArrayLayout2i4ub2b10.prototype.bytesPerElement = 10;\nregister('StructArrayLayout2i4ub2b10', StructArrayLayout2i4ub2b10);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[2]\n *\n */\nclass StructArrayLayout2f8 extends StructArray {\n    uint8: Uint8Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1);\n    }\n\n    public emplace(i: number, v0: number, v1: number): number {\n        const o4 = i * 2;\n        this.float32[o4 + 0] = v0;\n        this.float32[o4 + 1] = v1;\n        return i;\n    }\n}\n\nStructArrayLayout2f8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout2f8', StructArrayLayout2f8);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[10]\n *\n */\nclass StructArrayLayout10ui20 extends StructArray {\n    uint8: Uint8Array;\n    uint16: Uint16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number): number {\n        const o2 = i * 10;\n        this.uint16[o2 + 0] = v0;\n        this.uint16[o2 + 1] = v1;\n        this.uint16[o2 + 2] = v2;\n        this.uint16[o2 + 3] = v3;\n        this.uint16[o2 + 4] = v4;\n        this.uint16[o2 + 5] = v5;\n        this.uint16[o2 + 6] = v6;\n        this.uint16[o2 + 7] = v7;\n        this.uint16[o2 + 8] = v8;\n        this.uint16[o2 + 9] = v9;\n        return i;\n    }\n}\n\nStructArrayLayout10ui20.prototype.bytesPerElement = 20;\nregister('StructArrayLayout10ui20', StructArrayLayout10ui20);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[8]\n *\n */\nclass StructArrayLayout8ui16 extends StructArray {\n    uint8: Uint8Array;\n    uint16: Uint16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): number {\n        const o2 = i * 8;\n        this.uint16[o2 + 0] = v0;\n        this.uint16[o2 + 1] = v1;\n        this.uint16[o2 + 2] = v2;\n        this.uint16[o2 + 3] = v3;\n        this.uint16[o2 + 4] = v4;\n        this.uint16[o2 + 5] = v5;\n        this.uint16[o2 + 6] = v6;\n        this.uint16[o2 + 7] = v7;\n        return i;\n    }\n}\n\nStructArrayLayout8ui16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout8ui16', StructArrayLayout8ui16);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[4]\n * [8] - Uint16[4]\n * [16] - Int16[4]\n * [24] - Float32[1]\n *\n */\nclass StructArrayLayout4i4ui4i1f28 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n    uint16: Uint16Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number): number {\n        const o2 = i * 14;\n        const o4 = i * 7;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.int16[o2 + 2] = v2;\n        this.int16[o2 + 3] = v3;\n        this.uint16[o2 + 4] = v4;\n        this.uint16[o2 + 5] = v5;\n        this.uint16[o2 + 6] = v6;\n        this.uint16[o2 + 7] = v7;\n        this.int16[o2 + 8] = v8;\n        this.int16[o2 + 9] = v9;\n        this.int16[o2 + 10] = v10;\n        this.int16[o2 + 11] = v11;\n        this.float32[o4 + 6] = v12;\n        return i;\n    }\n}\n\nStructArrayLayout4i4ui4i1f28.prototype.bytesPerElement = 28;\nregister('StructArrayLayout4i4ui4i1f28', StructArrayLayout4i4ui4i1f28);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[3]\n *\n */\nclass StructArrayLayout3f12 extends StructArray {\n    uint8: Uint8Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number): number {\n        const o4 = i * 3;\n        this.float32[o4 + 0] = v0;\n        this.float32[o4 + 1] = v1;\n        this.float32[o4 + 2] = v2;\n        return i;\n    }\n}\n\nStructArrayLayout3f12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout3f12', StructArrayLayout3f12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint32[1]\n *\n */\nclass StructArrayLayout1ul4 extends StructArray {\n    uint8: Uint8Array;\n    uint32: Uint32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint32 = new Uint32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0);\n    }\n\n    public emplace(i: number, v0: number): number {\n        const o4 = i * 1;\n        this.uint32[o4 + 0] = v0;\n        return i;\n    }\n}\n\nStructArrayLayout1ul4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout1ul4', StructArrayLayout1ul4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[6]\n * [12] - Uint32[1]\n * [16] - Uint16[2]\n *\n */\nclass StructArrayLayout6i1ul2ui20 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n    uint32: Uint32Array;\n    uint16: Uint16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n        this.uint32 = new Uint32Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number): number {\n        const o2 = i * 10;\n        const o4 = i * 5;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.int16[o2 + 2] = v2;\n        this.int16[o2 + 3] = v3;\n        this.int16[o2 + 4] = v4;\n        this.int16[o2 + 5] = v5;\n        this.uint32[o4 + 3] = v6;\n        this.uint16[o2 + 8] = v7;\n        this.uint16[o2 + 9] = v8;\n        return i;\n    }\n}\n\nStructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20;\nregister('StructArrayLayout6i1ul2ui20', StructArrayLayout6i1ul2ui20);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Int16[2]\n * [8] - Int16[2]\n *\n */\nclass StructArrayLayout2i2i2i12 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n        const o2 = i * 6;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.int16[o2 + 2] = v2;\n        this.int16[o2 + 3] = v3;\n        this.int16[o2 + 4] = v4;\n        this.int16[o2 + 5] = v5;\n        return i;\n    }\n}\n\nStructArrayLayout2i2i2i12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[2]\n * [8] - Float32[1]\n * [12] - Int16[2]\n *\n */\nclass StructArrayLayout2f1f2i16 extends StructArray {\n    uint8: Uint8Array;\n    float32: Float32Array;\n    int16: Int16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number): number {\n        const o4 = i * 4;\n        const o2 = i * 8;\n        this.float32[o4 + 0] = v0;\n        this.float32[o4 + 1] = v1;\n        this.float32[o4 + 2] = v2;\n        this.int16[o2 + 6] = v3;\n        this.int16[o2 + 7] = v4;\n        return i;\n    }\n}\n\nStructArrayLayout2f1f2i16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout2f1f2i16', StructArrayLayout2f1f2i16);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint8[2]\n * [4] - Float32[2]\n * [12] - Int16[2]\n *\n */\nclass StructArrayLayout2ub2f2i16 extends StructArray {\n    uint8: Uint8Array;\n    float32: Float32Array;\n    int16: Int16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n        const o1 = i * 16;\n        const o4 = i * 4;\n        const o2 = i * 8;\n        this.uint8[o1 + 0] = v0;\n        this.uint8[o1 + 1] = v1;\n        this.float32[o4 + 1] = v2;\n        this.float32[o4 + 2] = v3;\n        this.int16[o2 + 6] = v4;\n        this.int16[o2 + 7] = v5;\n        return i;\n    }\n}\n\nStructArrayLayout2ub2f2i16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout2ub2f2i16', StructArrayLayout2ub2f2i16);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[3]\n *\n */\nclass StructArrayLayout3ui6 extends StructArray {\n    uint8: Uint8Array;\n    uint16: Uint16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number): number {\n        const o2 = i * 3;\n        this.uint16[o2 + 0] = v0;\n        this.uint16[o2 + 1] = v1;\n        this.uint16[o2 + 2] = v2;\n        return i;\n    }\n}\n\nStructArrayLayout3ui6.prototype.bytesPerElement = 6;\nregister('StructArrayLayout3ui6', StructArrayLayout3ui6);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[2]\n * [4] - Uint16[2]\n * [8] - Uint32[3]\n * [20] - Uint16[3]\n * [28] - Float32[2]\n * [36] - Uint8[3]\n * [40] - Uint32[1]\n * [44] - Int16[1]\n * [48] - Float32[1]\n *\n */\nclass StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n    uint16: Uint16Array;\n    uint32: Uint32Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n        this.uint32 = new Uint32Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number): number {\n        const o2 = i * 26;\n        const o4 = i * 13;\n        const o1 = i * 52;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.uint16[o2 + 2] = v2;\n        this.uint16[o2 + 3] = v3;\n        this.uint32[o4 + 2] = v4;\n        this.uint32[o4 + 3] = v5;\n        this.uint32[o4 + 4] = v6;\n        this.uint16[o2 + 10] = v7;\n        this.uint16[o2 + 11] = v8;\n        this.uint16[o2 + 12] = v9;\n        this.float32[o4 + 7] = v10;\n        this.float32[o4 + 8] = v11;\n        this.uint8[o1 + 36] = v12;\n        this.uint8[o1 + 37] = v13;\n        this.uint8[o1 + 38] = v14;\n        this.uint32[o4 + 10] = v15;\n        this.int16[o2 + 22] = v16;\n        this.float32[o4 + 12] = v17;\n        return i;\n    }\n}\n\nStructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52.prototype.bytesPerElement = 52;\nregister('StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52', StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Int16[8]\n * [16] - Uint16[15]\n * [48] - Uint32[1]\n * [52] - Float32[2]\n * [60] - Uint16[2]\n * [64] - Float32[1]\n *\n */\nclass StructArrayLayout8i15ui1ul2f2ui1f68 extends StructArray {\n    uint8: Uint8Array;\n    int16: Int16Array;\n    uint16: Uint16Array;\n    uint32: Uint32Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.int16 = new Int16Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n        this.uint32 = new Uint32Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number, v21: number, v22: number, v23: number, v24: number, v25: number, v26: number, v27: number, v28: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number, v21: number, v22: number, v23: number, v24: number, v25: number, v26: number, v27: number, v28: number): number {\n        const o2 = i * 34;\n        const o4 = i * 17;\n        this.int16[o2 + 0] = v0;\n        this.int16[o2 + 1] = v1;\n        this.int16[o2 + 2] = v2;\n        this.int16[o2 + 3] = v3;\n        this.int16[o2 + 4] = v4;\n        this.int16[o2 + 5] = v5;\n        this.int16[o2 + 6] = v6;\n        this.int16[o2 + 7] = v7;\n        this.uint16[o2 + 8] = v8;\n        this.uint16[o2 + 9] = v9;\n        this.uint16[o2 + 10] = v10;\n        this.uint16[o2 + 11] = v11;\n        this.uint16[o2 + 12] = v12;\n        this.uint16[o2 + 13] = v13;\n        this.uint16[o2 + 14] = v14;\n        this.uint16[o2 + 15] = v15;\n        this.uint16[o2 + 16] = v16;\n        this.uint16[o2 + 17] = v17;\n        this.uint16[o2 + 18] = v18;\n        this.uint16[o2 + 19] = v19;\n        this.uint16[o2 + 20] = v20;\n        this.uint16[o2 + 21] = v21;\n        this.uint16[o2 + 22] = v22;\n        this.uint32[o4 + 12] = v23;\n        this.float32[o4 + 13] = v24;\n        this.float32[o4 + 14] = v25;\n        this.uint16[o2 + 30] = v26;\n        this.uint16[o2 + 31] = v27;\n        this.float32[o4 + 16] = v28;\n        return i;\n    }\n}\n\nStructArrayLayout8i15ui1ul2f2ui1f68.prototype.bytesPerElement = 68;\nregister('StructArrayLayout8i15ui1ul2f2ui1f68', StructArrayLayout8i15ui1ul2f2ui1f68);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[1]\n *\n */\nclass StructArrayLayout1f4 extends StructArray {\n    uint8: Uint8Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0);\n    }\n\n    public emplace(i: number, v0: number): number {\n        const o4 = i * 1;\n        this.float32[o4 + 0] = v0;\n        return i;\n    }\n}\n\nStructArrayLayout1f4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout1f4', StructArrayLayout1f4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[1]\n * [4] - Float32[2]\n *\n */\nclass StructArrayLayout1ui2f12 extends StructArray {\n    uint8: Uint8Array;\n    uint16: Uint16Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number): number {\n        const o2 = i * 6;\n        const o4 = i * 3;\n        this.uint16[o2 + 0] = v0;\n        this.float32[o4 + 1] = v1;\n        this.float32[o4 + 2] = v2;\n        return i;\n    }\n}\n\nStructArrayLayout1ui2f12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout1ui2f12', StructArrayLayout1ui2f12);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint32[1]\n * [4] - Uint16[2]\n *\n */\nclass StructArrayLayout1ul2ui8 extends StructArray {\n    uint8: Uint8Array;\n    uint32: Uint32Array;\n    uint16: Uint16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint32 = new Uint32Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number): number {\n        const o4 = i * 2;\n        const o2 = i * 4;\n        this.uint32[o4 + 0] = v0;\n        this.uint16[o2 + 2] = v1;\n        this.uint16[o2 + 3] = v2;\n        return i;\n    }\n}\n\nStructArrayLayout1ul2ui8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[2]\n *\n */\nclass StructArrayLayout2ui4 extends StructArray {\n    uint8: Uint8Array;\n    uint16: Uint16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1);\n    }\n\n    public emplace(i: number, v0: number, v1: number): number {\n        const o2 = i * 2;\n        this.uint16[o2 + 0] = v0;\n        this.uint16[o2 + 1] = v1;\n        return i;\n    }\n}\n\nStructArrayLayout2ui4.prototype.bytesPerElement = 4;\nregister('StructArrayLayout2ui4', StructArrayLayout2ui4);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Uint16[1]\n *\n */\nclass StructArrayLayout1ui2 extends StructArray {\n    uint8: Uint8Array;\n    uint16: Uint16Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.uint16 = new Uint16Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0);\n    }\n\n    public emplace(i: number, v0: number): number {\n        const o2 = i * 1;\n        this.uint16[o2 + 0] = v0;\n        return i;\n    }\n}\n\nStructArrayLayout1ui2.prototype.bytesPerElement = 2;\nregister('StructArrayLayout1ui2', StructArrayLayout1ui2);\n\n/**\n * @internal\n * Implementation of the StructArray layout:\n * [0] - Float32[4]\n *\n */\nclass StructArrayLayout4f16 extends StructArray {\n    uint8: Uint8Array;\n    float32: Float32Array;\n\n    _refreshViews(): void {\n        this.uint8 = new Uint8Array(this.arrayBuffer);\n        this.float32 = new Float32Array(this.arrayBuffer);\n    }\n\n    public emplaceBack(v0: number, v1: number, v2: number, v3: number): number {\n        const i = this.length;\n        this.resize(i + 1);\n        return this.emplace(i, v0, v1, v2, v3);\n    }\n\n    public emplace(i: number, v0: number, v1: number, v2: number, v3: number): number {\n        const o4 = i * 4;\n        this.float32[o4 + 0] = v0;\n        this.float32[o4 + 1] = v1;\n        this.float32[o4 + 2] = v2;\n        this.float32[o4 + 3] = v3;\n        return i;\n    }\n}\n\nStructArrayLayout4f16.prototype.bytesPerElement = 16;\nregister('StructArrayLayout4f16', StructArrayLayout4f16);\n\n/** @internal */\nclass CollisionBoxStruct extends Struct {\n    _structArray: CollisionBoxArray;\n    get anchorPointX(): number { return this._structArray.int16[this._pos2 + 0]; }\n    get anchorPointY(): number { return this._structArray.int16[this._pos2 + 1]; }\n    get x1(): number { return this._structArray.int16[this._pos2 + 2]; }\n    get y1(): number { return this._structArray.int16[this._pos2 + 3]; }\n    get x2(): number { return this._structArray.int16[this._pos2 + 4]; }\n    get y2(): number { return this._structArray.int16[this._pos2 + 5]; }\n    get featureIndex(): number { return this._structArray.uint32[this._pos4 + 3]; }\n    get sourceLayerIndex(): number { return this._structArray.uint16[this._pos2 + 8]; }\n    get bucketIndex(): number { return this._structArray.uint16[this._pos2 + 9]; }\n    get anchorPoint(): Point { return new Point(this.anchorPointX, this.anchorPointY); }\n}\n\nCollisionBoxStruct.prototype.size = 20;\n\nexport type CollisionBox = CollisionBoxStruct;\n\n/** @internal */\nexport class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 {\n    /**\n     * Return the CollisionBoxStruct at the given location in the array.\n     * @param index - The index of the element.\n     */\n    get(index: number): CollisionBoxStruct {\n        return new CollisionBoxStruct(this, index);\n    }\n}\n\nregister('CollisionBoxArray', CollisionBoxArray);\n\n/** @internal */\nclass PlacedSymbolStruct extends Struct {\n    _structArray: PlacedSymbolArray;\n    get anchorX(): number { return this._structArray.int16[this._pos2 + 0]; }\n    get anchorY(): number { return this._structArray.int16[this._pos2 + 1]; }\n    get glyphStartIndex(): number { return this._structArray.uint16[this._pos2 + 2]; }\n    get numGlyphs(): number { return this._structArray.uint16[this._pos2 + 3]; }\n    get vertexStartIndex(): number { return this._structArray.uint32[this._pos4 + 2]; }\n    get lineStartIndex(): number { return this._structArray.uint32[this._pos4 + 3]; }\n    get lineLength(): number { return this._structArray.uint32[this._pos4 + 4]; }\n    get segment(): number { return this._structArray.uint16[this._pos2 + 10]; }\n    get lowerSize(): number { return this._structArray.uint16[this._pos2 + 11]; }\n    get upperSize(): number { return this._structArray.uint16[this._pos2 + 12]; }\n    get lineOffsetX(): number { return this._structArray.float32[this._pos4 + 7]; }\n    get lineOffsetY(): number { return this._structArray.float32[this._pos4 + 8]; }\n    get writingMode(): number { return this._structArray.uint8[this._pos1 + 36]; }\n    get placedOrientation(): number { return this._structArray.uint8[this._pos1 + 37]; }\n    set placedOrientation(x: number) { this._structArray.uint8[this._pos1 + 37] = x; }\n    get hidden(): number { return this._structArray.uint8[this._pos1 + 38]; }\n    set hidden(x: number) { this._structArray.uint8[this._pos1 + 38] = x; }\n    get crossTileID(): number { return this._structArray.uint32[this._pos4 + 10]; }\n    set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 10] = x; }\n    get associatedIconIndex(): number { return this._structArray.int16[this._pos2 + 22]; }\n    get heightOffset(): number { return this._structArray.float32[this._pos4 + 12]; }\n}\n\nPlacedSymbolStruct.prototype.size = 52;\n\nexport type PlacedSymbol = PlacedSymbolStruct;\n\n/** @internal */\nexport class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52 {\n    /**\n     * Return the PlacedSymbolStruct at the given location in the array.\n     * @param index - The index of the element.\n     */\n    get(index: number): PlacedSymbolStruct {\n        return new PlacedSymbolStruct(this, index);\n    }\n}\n\nregister('PlacedSymbolArray', PlacedSymbolArray);\n\n/** @internal */\nclass SymbolInstanceStruct extends Struct {\n    _structArray: SymbolInstanceArray;\n    get anchorX(): number { return this._structArray.int16[this._pos2 + 0]; }\n    get anchorY(): number { return this._structArray.int16[this._pos2 + 1]; }\n    get rightJustifiedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 2]; }\n    get centerJustifiedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 3]; }\n    get leftJustifiedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 4]; }\n    get verticalPlacedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 5]; }\n    get placedIconSymbolIndex(): number { return this._structArray.int16[this._pos2 + 6]; }\n    get verticalPlacedIconSymbolIndex(): number { return this._structArray.int16[this._pos2 + 7]; }\n    get key(): number { return this._structArray.uint16[this._pos2 + 8]; }\n    get textBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 9]; }\n    get textBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 10]; }\n    get verticalTextBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 11]; }\n    get verticalTextBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 12]; }\n    get iconBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 13]; }\n    get iconBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 14]; }\n    get verticalIconBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 15]; }\n    get verticalIconBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 16]; }\n    get featureIndex(): number { return this._structArray.uint16[this._pos2 + 17]; }\n    get numHorizontalGlyphVertices(): number { return this._structArray.uint16[this._pos2 + 18]; }\n    get numVerticalGlyphVertices(): number { return this._structArray.uint16[this._pos2 + 19]; }\n    get numIconVertices(): number { return this._structArray.uint16[this._pos2 + 20]; }\n    get numVerticalIconVertices(): number { return this._structArray.uint16[this._pos2 + 21]; }\n    get useRuntimeCollisionCircles(): number { return this._structArray.uint16[this._pos2 + 22]; }\n    get crossTileID(): number { return this._structArray.uint32[this._pos4 + 12]; }\n    set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 12] = x; }\n    get textBoxScale(): number { return this._structArray.float32[this._pos4 + 13]; }\n    get collisionCircleDiameter(): number { return this._structArray.float32[this._pos4 + 14]; }\n    get textAnchorOffsetStartIndex(): number { return this._structArray.uint16[this._pos2 + 30]; }\n    get textAnchorOffsetEndIndex(): number { return this._structArray.uint16[this._pos2 + 31]; }\n    get heightOffset(): number { return this._structArray.float32[this._pos4 + 16]; }\n}\n\nSymbolInstanceStruct.prototype.size = 68;\n\nexport type SymbolInstance = SymbolInstanceStruct;\n\n/** @internal */\nexport class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui1f68 {\n    /**\n     * Return the SymbolInstanceStruct at the given location in the array.\n     * @param index - The index of the element.\n     */\n    get(index: number): SymbolInstanceStruct {\n        return new SymbolInstanceStruct(this, index);\n    }\n}\n\nregister('SymbolInstanceArray', SymbolInstanceArray);\n\n/** @internal */\nexport class GlyphOffsetArray extends StructArrayLayout1f4 {\n    getoffsetX(index: number): number { return this.float32[index * 1 + 0]; }\n}\n\nregister('GlyphOffsetArray', GlyphOffsetArray);\n\n/** @internal */\nexport class SymbolLineVertexArray extends StructArrayLayout3i6 {\n    getx(index: number): number { return this.int16[index * 3 + 0]; }\n    gety(index: number): number { return this.int16[index * 3 + 1]; }\n    gettileUnitDistanceFromAnchor(index: number): number { return this.int16[index * 3 + 2]; }\n}\n\nregister('SymbolLineVertexArray', SymbolLineVertexArray);\n\n/** @internal */\nclass TextAnchorOffsetStruct extends Struct {\n    _structArray: TextAnchorOffsetArray;\n    get textAnchor(): number { return this._structArray.uint16[this._pos2 + 0]; }\n    get textOffset0(): number { return this._structArray.float32[this._pos4 + 1]; }\n    get textOffset1(): number { return this._structArray.float32[this._pos4 + 2]; }\n}\n\nTextAnchorOffsetStruct.prototype.size = 12;\n\nexport type TextAnchorOffset = TextAnchorOffsetStruct;\n\n/** @internal */\nexport class TextAnchorOffsetArray extends StructArrayLayout1ui2f12 {\n    /**\n     * Return the TextAnchorOffsetStruct at the given location in the array.\n     * @param index - The index of the element.\n     */\n    get(index: number): TextAnchorOffsetStruct {\n        return new TextAnchorOffsetStruct(this, index);\n    }\n}\n\nregister('TextAnchorOffsetArray', TextAnchorOffsetArray);\n\n/** @internal */\nclass FeatureIndexStruct extends Struct {\n    _structArray: FeatureIndexArray;\n    get featureIndex(): number { return this._structArray.uint32[this._pos4 + 0]; }\n    get sourceLayerIndex(): number { return this._structArray.uint16[this._pos2 + 2]; }\n    get bucketIndex(): number { return this._structArray.uint16[this._pos2 + 3]; }\n}\n\nFeatureIndexStruct.prototype.size = 8;\n\nexport type FeatureIndex = FeatureIndexStruct;\n\n/** @internal */\nexport class FeatureIndexArray extends StructArrayLayout1ul2ui8 {\n    /**\n     * Return the FeatureIndexStruct at the given location in the array.\n     * @param index - The index of the element.\n     */\n    get(index: number): FeatureIndexStruct {\n        return new FeatureIndexStruct(this, index);\n    }\n}\n\nregister('FeatureIndexArray', FeatureIndexArray);\n\nexport class PosArray extends StructArrayLayout2i4 {}\nexport class Pos3dArray extends StructArrayLayout3i6 {}\nexport class RasterBoundsArray extends StructArrayLayout4i8 {}\nexport class CircleLayoutArray extends StructArrayLayout2i4 {}\nexport class FillLayoutArray extends StructArrayLayout2i4 {}\nexport class FillExtrusionLayoutArray extends StructArrayLayout2i4i12 {}\nexport class HeatmapLayoutArray extends StructArrayLayout2i4 {}\nexport class LineLayoutArray extends StructArrayLayout2i4ub2b10 {}\nexport class LineExtLayoutArray extends StructArrayLayout2f8 {}\nexport class PatternLayoutArray extends StructArrayLayout10ui20 {}\nexport class DashLayoutArray extends StructArrayLayout8ui16 {}\nexport class SymbolLayoutArray extends StructArrayLayout4i4ui4i1f28 {}\nexport class SymbolDynamicLayoutArray extends StructArrayLayout3f12 {}\nexport class SymbolOpacityArray extends StructArrayLayout1ul4 {}\nexport class CollisionBoxLayoutArray extends StructArrayLayout2i2i2i12 {}\nexport class CollisionCircleLayoutArray extends StructArrayLayout2f1f2i16 {}\nexport class CollisionVertexArray extends StructArrayLayout2ub2f2i16 {}\nexport class QuadTriangleArray extends StructArrayLayout3ui6 {}\nexport class TriangleIndexArray extends StructArrayLayout3ui6 {}\nexport class LineIndexArray extends StructArrayLayout2ui4 {}\nexport class LineStripIndexArray extends StructArrayLayout1ui2 {}\nexport {\n    StructArrayLayout2i4,\n    StructArrayLayout3i6,\n    StructArrayLayout4i8,\n    StructArrayLayout2i4i12,\n    StructArrayLayout2i4ub2b10,\n    StructArrayLayout2f8,\n    StructArrayLayout10ui20,\n    StructArrayLayout8ui16,\n    StructArrayLayout4i4ui4i1f28,\n    StructArrayLayout3f12,\n    StructArrayLayout1ul4,\n    StructArrayLayout6i1ul2ui20,\n    StructArrayLayout2i2i2i12,\n    StructArrayLayout2f1f2i16,\n    StructArrayLayout2ub2f2i16,\n    StructArrayLayout3ui6,\n    StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52,\n    StructArrayLayout8i15ui1ul2f2ui1f68,\n    StructArrayLayout1f4,\n    StructArrayLayout1ui2f12,\n    StructArrayLayout1ul2ui8,\n    StructArrayLayout2ui4,\n    StructArrayLayout1ui2,\n    StructArrayLayout4f16\n};\n", "import {createLayout, type StructArrayLayout, type StructArrayMember} from '../../util/struct_array.ts';\n\nconst layout: StructArrayLayout = createLayout([\n    {name: 'a_pos', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const members: StructArrayMember[] = layout.members;\nexport const size: number = layout.size;\nexport const alignment: number = layout.alignment;\n", "import {warnOnce} from '../util/util.ts';\nimport {register} from '../util/web_worker_transfer.ts';\n\nimport type {VertexArrayObject} from '../webgl/vertex_array_object.ts';\nimport type {StructArray} from '../util/struct_array.ts';\n\n/**\n * @internal\n * A single segment of a vector\n */\nexport type Segment = {\n    sortKey?: number;\n    vertexOffset: number;\n    primitiveOffset: number;\n    vertexLength: number;\n    primitiveLength: number;\n    vaos: {[_: string]: VertexArrayObject};\n};\n\n/**\n * @internal\n * Used for calculations on vector segments\n */\nexport class SegmentVector {\n    static MAX_VERTEX_ARRAY_LENGTH: number;\n    segments: Segment[];\n    private _forceNewSegmentOnNextPrepare: boolean = false;\n\n    constructor(segments: Segment[] = []) {\n        this.segments = segments;\n    }\n\n    /**\n     * Returns the last segment if `numVertices` fits into it.\n     * If there are no segments yet or `numVertices` doesn't fit into the last one, creates a new empty segment and returns it.\n     */\n    prepareSegment(\n        numVertices: number,\n        layoutVertexArray: StructArray,\n        indexArray: StructArray,\n        sortKey?: number\n    ): Segment {\n        const lastSegment: Segment = this.segments[this.segments.length - 1];\n\n        if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n            warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}. Consider using the \\`fillLargeMeshArrays\\` function if you require meshes with more than ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH} vertices.`);\n        }\n\n        if (this._forceNewSegmentOnNextPrepare || !lastSegment || lastSegment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || lastSegment.sortKey !== sortKey) {\n            return this.createNewSegment(layoutVertexArray, indexArray, sortKey);\n        } else {\n            return lastSegment;\n        }\n    }\n\n    /**\n     * Creates a new empty segment and returns it.\n     */\n    createNewSegment(\n        layoutVertexArray: StructArray,\n        indexArray: StructArray,\n        sortKey?: number\n    ): Segment {\n        const segment: Segment = {\n            vertexOffset: layoutVertexArray.length,\n            primitiveOffset: indexArray.length,\n            vertexLength: 0,\n            primitiveLength: 0,\n            vaos: {}\n        };\n\n        if (sortKey !== undefined) {\n            segment.sortKey = sortKey;\n        }\n\n        // If this was set, we have no need to create a new segment on next prepareSegment call,\n        // since this function already created a new, empty segment.\n        this._forceNewSegmentOnNextPrepare = false;\n        this.segments.push(segment);\n        return segment;\n    }\n\n    /**\n     * Returns the last segment, or creates a new segments if there are no segments yet.\n     */\n    getOrCreateLatestSegment(\n        layoutVertexArray: StructArray,\n        indexArray: StructArray,\n        sortKey?: number\n    ): Segment {\n        return this.prepareSegment(0, layoutVertexArray, indexArray, sortKey);\n    }\n\n    /**\n     * Causes the next call to {@link prepareSegment} to always return a new segment,\n     * not reusing the current segment even if the new geometry would fit it.\n     */\n    forceNewSegmentOnNextPrepare(): void {\n        this._forceNewSegmentOnNextPrepare = true;\n    }\n\n    get(): Segment[] {\n        return this.segments;\n    }\n\n    destroy(): void {\n        for (const segment of this.segments) {\n            for (const k in segment.vaos) {\n                segment.vaos[k].destroy();\n            }\n        }\n    }\n\n    static simpleSegment(\n        vertexOffset: number,\n        primitiveOffset: number,\n        vertexLength: number,\n        primitiveLength: number\n    ): SegmentVector {\n        return new SegmentVector([{\n            vertexOffset,\n            primitiveOffset,\n            vertexLength,\n            primitiveLength,\n            vaos: {},\n            sortKey: 0\n        }]);\n    }\n}\n\n/**\n * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit\n * addressing of vertex buffers.\n */\nSegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;\n\nregister('SegmentVector', SegmentVector);\n", "import {clamp} from '../util/util.ts';\n\n/**\n * Packs two numbers, interpreted as 8-bit unsigned integers, into a single\n * float.  Unpack them in the shader using the `unpack_float()` function,\n * defined in _prelude.vertex.glsl\n */\nexport function packUint8ToFloat(a: number, b: number): number {\n    // coerce a and b to 8-bit ints\n    a = clamp(Math.floor(a), 0, 255);\n    b = clamp(Math.floor(b), 0, 255);\n    return 256 * a + b;\n}\n", "import {createLayout, type StructArrayLayout} from '../../util/struct_array.ts';\n\nexport const patternAttributes: StructArrayLayout = createLayout([\n    // [tl.x, tl.y, br.x, br.y]\n    {name: 'a_pattern_from', components: 4, type: 'Uint16'},\n    {name: 'a_pattern_to', components: 4, type: 'Uint16'},\n    {name: 'a_pixel_ratio_from', components: 1, type: 'Uint16'},\n    {name: 'a_pixel_ratio_to', components: 1, type: 'Uint16'},\n]);\n", "import {createLayout, type StructArrayLayout} from '../../util/struct_array.ts';\n\nexport const dashAttributes: StructArrayLayout = createLayout([\n    // [0, y, height, width]\n    {name: 'a_dasharray_from', components: 4, type: 'Uint16'},\n    {name: 'a_dasharray_to', components: 4, type: 'Uint16'},\n]);\n", "/**\n * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)\n * \n * @author <a href=\"mailto:gary.court@gmail.com\">Gary Court</a>\n * @see http://github.com/garycourt/murmurhash-js\n * @author <a href=\"mailto:aappleby@gmail.com\">Austin Appleby</a>\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} key ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash \n */\n\nfunction murmurhash3_32_gc(key, seed) {\n\tvar remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;\n\t\n\tremainder = key.length & 3; // key.length % 4\n\tbytes = key.length - remainder;\n\th1 = seed;\n\tc1 = 0xcc9e2d51;\n\tc2 = 0x1b873593;\n\ti = 0;\n\t\n\twhile (i < bytes) {\n\t  \tk1 = \n\t  \t  ((key.charCodeAt(i) & 0xff)) |\n\t  \t  ((key.charCodeAt(++i) & 0xff) << 8) |\n\t  \t  ((key.charCodeAt(++i) & 0xff) << 16) |\n\t  \t  ((key.charCodeAt(++i) & 0xff) << 24);\n\t\t++i;\n\t\t\n\t\tk1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;\n\n\t\th1 ^= k1;\n        h1 = (h1 << 13) | (h1 >>> 19);\n\t\th1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;\n\t\th1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));\n\t}\n\t\n\tk1 = 0;\n\t\n\tswitch (remainder) {\n\t\tcase 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n\t\tcase 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n\t\tcase 1: k1 ^= (key.charCodeAt(i) & 0xff);\n\t\t\n\t\tk1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;\n\t\th1 ^= k1;\n\t}\n\t\n\th1 ^= key.length;\n\n\th1 ^= h1 >>> 16;\n\th1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;\n\th1 ^= h1 >>> 13;\n\th1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;\n\th1 ^= h1 >>> 16;\n\n\treturn h1 >>> 0;\n}\n\nif(typeof module !== \"undefined\") {\n  module.exports = murmurhash3_32_gc\n}", "/**\n * JS Implementation of MurmurHash2\n * \n * @author <a href=\"mailto:gary.court@gmail.com\">Gary Court</a>\n * @see http://github.com/garycourt/murmurhash-js\n * @author <a href=\"mailto:aappleby@gmail.com\">Austin Appleby</a>\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} str ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash\n */\n\nfunction murmurhash2_32_gc(str, seed) {\n  var\n    l = str.length,\n    h = seed ^ l,\n    i = 0,\n    k;\n  \n  while (l >= 4) {\n  \tk = \n  \t  ((str.charCodeAt(i) & 0xff)) |\n  \t  ((str.charCodeAt(++i) & 0xff) << 8) |\n  \t  ((str.charCodeAt(++i) & 0xff) << 16) |\n  \t  ((str.charCodeAt(++i) & 0xff) << 24);\n    \n    k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n    k ^= k >>> 24;\n    k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n\n\th = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k;\n\n    l -= 4;\n    ++i;\n  }\n  \n  switch (l) {\n  case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16;\n  case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8;\n  case 1: h ^= (str.charCodeAt(i) & 0xff);\n          h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n  }\n\n  h ^= h >>> 13;\n  h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n  h ^= h >>> 15;\n\n  return h >>> 0;\n}\n\nif(typeof module !== undefined) {\n  module.exports = murmurhash2_32_gc\n}\n", "var murmur3 = require(\"./murmurhash3_gc.js\")\nvar murmur2 = require(\"./murmurhash2_gc.js\")\n\nmodule.exports = murmur3\nmodule.exports.murmur3 = murmur3\nmodule.exports.murmur2 = murmur2\n", "import murmur3 from 'murmurhash-js';\nimport {register} from '../util/web_worker_transfer.ts';\n\ntype SerializedFeaturePositionMap = {\n    ids: Float64Array;\n    positions: Uint32Array;\n};\n\ntype FeaturePosition = {\n    index: number;\n    start: number;\n    end: number;\n};\n\n// A transferable data structure that maps feature ids to their indices and buffer offsets\nexport class FeaturePositionMap {\n    ids: number[];\n    positions: number[];\n    indexed: boolean;\n\n    constructor() {\n        this.ids = [];\n        this.positions = [];\n        this.indexed = false;\n    }\n\n    add(id: unknown, index: number, start: number, end: number): void {\n        this.ids.push(getNumericId(id));\n        this.positions.push(index, start, end);\n    }\n\n    getPositions(id: unknown): FeaturePosition[] {\n        if (!this.indexed) throw new Error('Trying to get index, but feature positions are not indexed');\n\n        const intId = getNumericId(id);\n\n        // binary search for the first occurrence of id in this.ids;\n        // relies on ids/positions being sorted by id, which happens in serialization\n        let i = 0;\n        let j = this.ids.length - 1;\n        while (i < j) {\n            const m = (i + j) >> 1;\n            if (this.ids[m] >= intId) {\n                j = m;\n            } else {\n                i = m + 1;\n            }\n        }\n        const positions = [];\n        while (this.ids[i] === intId) {\n            const index = this.positions[3 * i];\n            const start = this.positions[3 * i + 1];\n            const end = this.positions[3 * i + 2];\n            positions.push({index, start, end});\n            i++;\n        }\n        return positions;\n    }\n\n    static serialize(map: FeaturePositionMap, transferables: ArrayBuffer[]): SerializedFeaturePositionMap {\n        const ids = new Float64Array(map.ids);\n        const positions = new Uint32Array(map.positions);\n\n        sort(ids, positions, 0, ids.length - 1);\n\n        if (transferables) {\n            transferables.push(ids.buffer, positions.buffer);\n        }\n\n        return {ids, positions};\n    }\n\n    static deserialize(obj: SerializedFeaturePositionMap): FeaturePositionMap {\n        const map = new FeaturePositionMap();\n        // after transferring, we only use these arrays statically (no pushes),\n        // so TypedArray vs Array distinction that flow points out doesn't matter\n        map.ids = (obj.ids as any);\n        map.positions = (obj.positions as any);\n        map.indexed = true;\n        return map;\n    }\n}\n\nfunction getNumericId(value: unknown) {\n    const numValue = +value;\n    if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) {\n        return numValue;\n    }\n    return murmur3(String(value));\n}\n\n// custom quicksort that sorts ids, indices and offsets together (by ids)\n// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios\nfunction sort(ids, positions, left, right) {\n    while (left < right) {\n        const pivot = ids[(left + right) >> 1];\n        let i = left - 1;\n        let j = right + 1;\n\n        while (true) {\n            do i++; while (ids[i] < pivot);\n            do j--; while (ids[j] > pivot);\n            if (i >= j) break;\n            swap(ids, i, j);\n            swap(positions, 3 * i, 3 * j);\n            swap(positions, 3 * i + 1, 3 * j + 1);\n            swap(positions, 3 * i + 2, 3 * j + 2);\n        }\n\n        if (j - left < right - j) {\n            sort(ids, positions, left, j);\n            left = j + 1;\n        } else {\n            sort(ids, positions, j + 1, right);\n            right = j;\n        }\n    }\n}\n\nfunction swap(arr, i, j) {\n    const tmp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = tmp;\n}\n\nregister('FeaturePositionMap', FeaturePositionMap);\n", "import {Color} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {mat4, vec2, vec3, vec4} from 'gl-matrix';\nimport type {Context} from './context.ts';\n\ntype $ObjMap<T extends {}, F extends (v: any) => any> = {\n    [K in keyof T]: F extends (v: T[K]) => infer R ? R : never;\n};\n\nexport type UniformValues<Us extends {}> = $ObjMap<Us, <V>(u: Uniform<V>) => V>;\nexport type UniformLocations = {[_: string]: WebGLUniformLocation};\n\n/**\n * @internal\n * A base uniform abstract class\n */\nabstract class Uniform<T> {\n    gl: WebGL2RenderingContext;\n    location: WebGLUniformLocation;\n    current: T;\n\n    constructor(context: Context, location: WebGLUniformLocation) {\n        this.gl = context.gl;\n        this.location = location;\n    }\n\n    abstract set(v: T): void;\n}\n\nclass Uniform1i extends Uniform<number> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = 0;\n    }\n\n    set(v: number): void {\n        if (this.current !== v) {\n            this.current = v;\n            this.gl.uniform1i(this.location, v);\n        }\n    }\n}\n\nclass Uniform1f extends Uniform<number> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = 0;\n    }\n\n    set(v: number): void {\n        if (this.current !== v) {\n            this.current = v;\n            this.gl.uniform1f(this.location, v);\n        }\n    }\n}\n\nclass Uniform2f extends Uniform<vec2> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = [0, 0];\n    }\n\n    set(v: vec2): void {\n        if (v[0] !== this.current[0] || v[1] !== this.current[1]) {\n            this.current = v;\n            this.gl.uniform2f(this.location, v[0], v[1]);\n        }\n    }\n}\n\nclass Uniform3f extends Uniform<vec3> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = [0, 0, 0];\n    }\n\n    set(v: vec3): void {\n        if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) {\n            this.current = v;\n            this.gl.uniform3f(this.location, v[0], v[1], v[2]);\n        }\n    }\n}\n\nclass Uniform4f extends Uniform<vec4> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = [0, 0, 0, 0];\n    }\n\n    set(v: vec4): void {\n        if (v[0] !== this.current[0] || v[1] !== this.current[1] ||\n            v[2] !== this.current[2] || v[3] !== this.current[3]) {\n            this.current = v;\n            this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]);\n        }\n    }\n}\n\nclass UniformColor extends Uniform<Color> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = Color.transparent;\n    }\n\n    set(v: Color): void {\n        if (v.r !== this.current.r || v.g !== this.current.g ||\n            v.b !== this.current.b || v.a !== this.current.a) {\n            this.current = v;\n            this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a);\n        }\n    }\n}\n\nclass UniformColorArray extends Uniform<Color[]> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = new Array<Color>();\n    }\n\n    set(v: Color[]): void {\n        if (v != this.current) {\n            this.current = v;\n            const values = new Float32Array(v.length*4);\n            for( let i = 0; i < v.length; i++) {\n                values[4*i] = v[i].r;\n                values[4*i+1] = v[i].g;\n                values[4*i+2] = v[i].b;\n                values[4*i+3] = v[i].a;\n            }\n            this.gl.uniform4fv(this.location, values);\n        }\n    }\n}\n\nclass UniformFloatArray extends Uniform<number[]> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = new Array<number>();\n    }\n\n    set(v: number[]): void {\n        if (v != this.current) {\n            this.current = v;\n            const values = new Float32Array(v);\n            this.gl.uniform1fv(this.location, values);\n        }\n    }\n}\n\nconst emptyMat4 = new Float32Array(16) as mat4;\nclass UniformMatrix4f extends Uniform<mat4> {\n    constructor(context: Context, location: WebGLUniformLocation) {\n        super(context, location);\n        this.current = emptyMat4;\n    }\n\n    set(v: mat4): void {\n        // The vast majority of matrix comparisons that will trip this set\n        // happen at i=12 or i=0, so we check those first to avoid lots of\n        // unnecessary iteration:\n        if (v[12] !== this.current[12] || v[0] !== this.current[0]) {\n            this.current = v;\n            this.gl.uniformMatrix4fv(this.location, false, v);\n            return;\n        }\n        for (let i = 1; i < 16; i++) {\n            if (v[i] !== this.current[i]) {\n                this.current = v;\n                this.gl.uniformMatrix4fv(this.location, false, v);\n                break;\n            }\n        }\n    }\n}\n\nexport {\n    Uniform,\n    Uniform1i,\n    Uniform1f,\n    Uniform2f,\n    Uniform3f,\n    Uniform4f,\n    UniformColor,\n    UniformColorArray,\n    UniformFloatArray,\n    UniformMatrix4f\n};\n\n/**\n * @internal\n * A uniform bindings\n */\nexport type UniformBindings = {[_: string]: Uniform<any>};\n", "import {packUint8ToFloat} from '../shaders/encode_attribute.ts';\nimport {type Color, supportsPropertyExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {register} from '../util/web_worker_transfer.ts';\nimport {PossiblyEvaluatedPropertyValue} from '../style/properties.ts';\nimport {StructArrayLayout1f4, StructArrayLayout2f8, StructArrayLayout4f16, PatternLayoutArray, DashLayoutArray} from './array_types.g.ts';\nimport {clamp} from '../util/util.ts';\nimport {patternAttributes} from './bucket/pattern_attributes.ts';\nimport {dashAttributes} from './bucket/dash_attributes.ts';\nimport {EvaluationParameters} from '../style/evaluation_parameters.ts';\nimport {FeaturePositionMap} from './feature_position_map.ts';\nimport {type Uniform, Uniform1f, UniformColor, Uniform4f} from '../webgl/uniform_binding.ts';\n\nimport type {UniformLocations} from '../webgl/uniform_binding.ts';\nimport type {CanonicalTileID} from '../tile/tile_id.ts';\nimport type {Context} from '../webgl/context.ts';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer.ts';\nimport type {CrossfadeParameters} from '../style/evaluation_parameters.ts';\nimport type {StructArray, StructArrayMember} from '../util/struct_array.ts';\nimport type {VertexBuffer} from '../webgl/vertex_buffer.ts';\nimport type {ImagePosition} from '../render/image_atlas.ts';\nimport type {\n    Feature,\n    FeatureState,\n    GlobalProperties,\n    SourceExpression,\n    CompositeExpression,\n    FormattedSection\n} from '@maplibre/maplibre-gl-style-spec';\nimport type {FeatureStates} from '../source/source_state.ts';\nimport type {DashEntry} from '../render/line_atlas.ts';\nimport type {VectorTileLayerLike} from '@maplibre/vt-pbf';\n\nexport type BinderUniform = {\n    name: string;\n    property: string;\n    binding: Uniform<any>;\n};\n\nfunction packColor(color: Color): [number, number] {\n    return [\n        packUint8ToFloat(255 * color.r, 255 * color.g),\n        packUint8ToFloat(255 * color.b, 255 * color.a)\n    ];\n}\n\ntype PaintOptions = {\n    imagePositions: {\n        [_: string]: ImagePosition;\n    };\n    dashPositions?: {\n        [_: string]: DashEntry;\n    };\n    canonical?: CanonicalTileID;\n    formattedSection?: FormattedSection;\n    globalState?: Record<string, any>;\n};\n\n/**\n *  `Binder` is the interface definition for the strategies for constructing,\n *  uploading, and binding paint property data as GLSL attributes. Most style-\n *  spec properties have a 1:1 relationship to shader attribute/uniforms, but\n *  some require multiple values per feature to be passed to the GPU, and in\n *  those cases we bind multiple attributes/uniforms.\n *\n *  It has three implementations, one for each of the three strategies we use:\n *\n *  * For _constant_ properties -- those whose value is a constant, or the constant\n *    result of evaluating a camera expression at a particular camera position -- we\n *    don't need a vertex attribute buffer, and instead use a uniform.\n *  * For data expressions, we use a vertex buffer with a single attribute value,\n *    the evaluated result of the source function for the given feature.\n *  * For composite expressions, we use a vertex buffer with two attributes: min and\n *    max values covering the range of zooms at which we expect the tile to be\n *    displayed. These values are calculated by evaluating the composite expression for\n *    the given feature at strategically chosen zoom levels. In addition to this\n *    attribute data, we also use a uniform value which the shader uses to interpolate\n *    between the min and max value at the final displayed zoom level. The use of a\n *    uniform allows us to cheaply update the value on every frame.\n *\n *  Note that the shader source varies depending on whether we're using a uniform or\n *  attribute. We dynamically compile shaders at runtime to accommodate this.\n */\ninterface AttributeBinder {\n    populatePaintArray(\n        length: number,\n        feature: Feature,\n        options: PaintOptions\n    ): void;\n    updatePaintArray(\n        start: number,\n        length: number,\n        feature: Feature,\n        featureState: FeatureState,\n        options: PaintOptions\n    ): void;\n    upload(a: Context): void;\n    destroy(): void;\n}\n\ninterface UniformBinder {\n    uniformNames: string[];\n    setUniform(\n        uniform: Uniform<any>,\n        globals: GlobalProperties,\n        currentValue: PossiblyEvaluatedPropertyValue<any>,\n        uniformName: string\n    ): void;\n    getBinding(context: Context, location: WebGLUniformLocation, name: string): Partial<Uniform<any>>;\n}\n\nclass ConstantBinder implements UniformBinder {\n    value: unknown;\n    type: string;\n    uniformNames: string[];\n\n    constructor(value: unknown, names: string[], type: string) {\n        this.value = value;\n        this.uniformNames = names.map(name => `u_${name}`);\n        this.type = type;\n    }\n\n    setUniform(\n        uniform: Uniform<any>,\n        globals: GlobalProperties,\n        currentValue: PossiblyEvaluatedPropertyValue<unknown>\n    ): void {\n        uniform.set(currentValue.constantOr(this.value));\n    }\n\n    getBinding(context: Context, location: WebGLUniformLocation, _: string): Partial<Uniform<any>> {\n        return (this.type === 'color') ?\n            new UniformColor(context, location) :\n            new Uniform1f(context, location);\n    }\n}\n\nclass CrossFadedConstantBinder implements UniformBinder {\n    uniformNames: string[];\n    patternFrom: number[];\n    patternTo: number[];\n    dashFrom: number[];\n    dashTo: number[];\n    pixelRatioFrom: number;\n    pixelRatioTo: number;\n\n    constructor(value: unknown, names: string[]) {\n        this.uniformNames = names.map(name => `u_${name}`);\n        this.patternFrom = null;\n        this.patternTo = null;\n        this.dashFrom = null;\n        this.dashTo = null;\n        this.pixelRatioFrom = 1.0;\n        this.pixelRatioTo = 1.0;\n    }\n\n    setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition) {\n        this.pixelRatioFrom = posFrom.pixelRatio;\n        this.pixelRatioTo = posTo.pixelRatio;\n        this.patternFrom = posFrom.tlbr;\n        this.patternTo = posTo.tlbr;\n    }\n\n    setConstantDashPositions(dashTo: DashEntry, dashFrom: DashEntry) {\n        this.dashTo = [0, dashTo.y, dashTo.height, dashTo.width];\n        this.dashFrom = [0, dashFrom.y, dashFrom.height, dashFrom.width];\n    }\n\n    setUniform(uniform: Uniform<any>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue<unknown>, uniformName: string) {\n        let value = null;\n\n        if (uniformName === 'u_pattern_to') {\n            value = this.patternTo;\n        } else if (uniformName === 'u_pattern_from') {\n            value = this.patternFrom;\n        } else if (uniformName === 'u_dasharray_to') {\n            value = this.dashTo;\n        } else if (uniformName === 'u_dasharray_from') {\n            value = this.dashFrom;\n        } else if (uniformName === 'u_pixel_ratio_to') {\n            value = this.pixelRatioTo;\n        } else if (uniformName === 'u_pixel_ratio_from') {\n            value = this.pixelRatioFrom;\n        }\n\n        if (value !== null) {\n            uniform.set(value);\n        }\n    }\n\n    getBinding(context: Context, location: WebGLUniformLocation, name: string): Partial<Uniform<any>> {\n        return (name.startsWith('u_pattern') || name.startsWith('u_dasharray_')) ?\n            new Uniform4f(context, location) :\n            new Uniform1f(context, location);\n    }\n}\n\nclass SourceExpressionBinder implements AttributeBinder {\n    expression: SourceExpression;\n    type: string;\n    maxValue: number;\n\n    paintVertexArray: StructArray;\n    paintVertexAttributes: StructArrayMember[];\n    paintVertexBuffer: VertexBuffer;\n\n    constructor(expression: SourceExpression, names: string[], type: string, PaintVertexArray: {\n        new (...args: any): StructArray;\n    }) {\n        this.expression = expression;\n        this.type = type;\n        this.maxValue = 0;\n        this.paintVertexAttributes = names.map((name) => ({\n            name: `a_${name}`,\n            type: 'Float32',\n            components: type === 'color' ? 2 : 1,\n            offset: 0\n        }));\n        this.paintVertexArray = new PaintVertexArray();\n    }\n\n    populatePaintArray(newLength: number, feature: Feature, options: PaintOptions) {\n        const start = this.paintVertexArray.length;\n        const value = this.expression.evaluate(new EvaluationParameters(0, options), feature, {}, options.canonical, [], options.formattedSection);\n        this.paintVertexArray.resize(newLength);\n        this._setPaintValue(start, newLength, value);\n    }\n\n    updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, options: PaintOptions) {\n        const value = this.expression.evaluate(new EvaluationParameters(0, options), feature, featureState);\n        this._setPaintValue(start, end, value);\n    }\n\n    _setPaintValue(start, end, value) {\n        if (this.type === 'color') {\n            const color = packColor(value);\n            for (let i = start; i < end; i++) {\n                this.paintVertexArray.emplace(i, color[0], color[1]);\n            }\n        } else {\n            for (let i = start; i < end; i++) {\n                this.paintVertexArray.emplace(i, value);\n            }\n            this.maxValue = Math.max(this.maxValue, Math.abs(value));\n        }\n    }\n\n    upload(context: Context) {\n        if (this.paintVertexArray?.arrayBuffer.byteLength) {\n            if (this.paintVertexBuffer?.buffer) {\n                this.paintVertexBuffer.updateData(this.paintVertexArray);\n            } else {\n                this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);\n            }\n        }\n    }\n\n    destroy() {\n        if (this.paintVertexBuffer) {\n            this.paintVertexBuffer.destroy();\n        }\n    }\n}\n\nclass CompositeExpressionBinder implements AttributeBinder, UniformBinder {\n    expression: CompositeExpression;\n    uniformNames: string[];\n    type: string;\n    useIntegerZoom: boolean;\n    zoom: number;\n    maxValue: number;\n\n    paintVertexArray: StructArray;\n    paintVertexAttributes: StructArrayMember[];\n    paintVertexBuffer: VertexBuffer;\n\n    constructor(expression: CompositeExpression, names: string[], type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: {\n        new (...args: any): StructArray;\n    }) {\n        this.expression = expression;\n        this.uniformNames = names.map(name => `u_${name}_t`);\n        this.type = type;\n        this.useIntegerZoom = useIntegerZoom;\n        this.zoom = zoom;\n        this.maxValue = 0;\n        this.paintVertexAttributes = names.map((name) => ({\n            name: `a_${name}`,\n            type: 'Float32',\n            components: type === 'color' ? 4 : 2,\n            offset: 0\n        }));\n        this.paintVertexArray = new PaintVertexArray();\n    }\n\n    populatePaintArray(newLength: number, feature: Feature, options: PaintOptions) {\n        const min = this.expression.evaluate(new EvaluationParameters(this.zoom, options), feature, {}, options.canonical, [], options.formattedSection);\n        const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1, options), feature, {}, options.canonical, [], options.formattedSection);\n        const start = this.paintVertexArray.length;\n        this.paintVertexArray.resize(newLength);\n        this._setPaintValue(start, newLength, min, max);\n    }\n\n    updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, options: PaintOptions) {\n        const min = this.expression.evaluate(new EvaluationParameters(this.zoom, options), feature, featureState);\n        const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1, options), feature, featureState);\n        this._setPaintValue(start, end, min, max);\n    }\n\n    _setPaintValue(start, end, min, max) {\n        if (this.type === 'color') {\n            const minColor = packColor(min);\n            const maxColor = packColor(max);\n            for (let i = start; i < end; i++) {\n                this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]);\n            }\n        } else {\n            for (let i = start; i < end; i++) {\n                this.paintVertexArray.emplace(i, min, max);\n            }\n            this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max));\n        }\n    }\n\n    upload(context: Context) {\n        if (this.paintVertexArray?.arrayBuffer.byteLength) {\n            if (this.paintVertexBuffer?.buffer) {\n                this.paintVertexBuffer.updateData(this.paintVertexArray);\n            } else {\n                this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);\n            }\n        }\n    }\n\n    destroy() {\n        if (this.paintVertexBuffer) {\n            this.paintVertexBuffer.destroy();\n        }\n    }\n\n    setUniform(uniform: Uniform<any>, globals: GlobalProperties): void {\n        const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom;\n        const factor = clamp(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1);\n        uniform.set(factor);\n    }\n\n    getBinding(context: Context, location: WebGLUniformLocation, _: string): Uniform1f {\n        return new Uniform1f(context, location);\n    }\n}\n\nabstract class CrossFadedBinder<T> implements AttributeBinder {\n    expression: CompositeExpression;\n    type: string;\n    useIntegerZoom: boolean;\n    zoom: number;\n    layerId: string;\n\n    zoomInPaintVertexArray: StructArray;\n    zoomOutPaintVertexArray: StructArray;\n    zoomInPaintVertexBuffer: VertexBuffer;\n    zoomOutPaintVertexBuffer: VertexBuffer;\n    paintVertexAttributes: StructArrayMember[];\n\n    constructor(expression: CompositeExpression, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: {\n        new (...args: any): StructArray;\n    }, layerId: string) {\n        this.expression = expression;\n        this.type = type;\n        this.useIntegerZoom = useIntegerZoom;\n        this.zoom = zoom;\n        this.layerId = layerId;\n\n        this.zoomInPaintVertexArray = new PaintVertexArray();\n        this.zoomOutPaintVertexArray = new PaintVertexArray();\n    }\n\n    populatePaintArray(length: number, feature: Feature, options: PaintOptions) {\n        const start = this.zoomInPaintVertexArray.length;\n        this.zoomInPaintVertexArray.resize(length);\n        this.zoomOutPaintVertexArray.resize(length);\n        this._setPaintValues(start, length, this.getPositionIds(feature), options);\n    }\n\n    updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, options: PaintOptions) {\n        this._setPaintValues(start, end, this.getPositionIds(feature), options);\n    }\n\n    abstract getVertexAttributes(): StructArrayMember[];\n\n    protected abstract getPositionIds(feature: Feature): {min: string; mid: string; max: string};\n    protected abstract getPositions(options: PaintOptions): {[_: string]: T};\n    protected abstract emplace(array: StructArray, index: number, fromPos: T, toPos: T): void;\n\n    protected _setPaintValues(start: number, end: number, positionIds: {min: string; mid: string; max: string}, options: PaintOptions) {\n        const positions = this.getPositions(options);\n        if (!positions || !positionIds) return;\n        const min = positions[positionIds.min];\n        const mid = positions[positionIds.mid];\n        const max = positions[positionIds.max];\n        if (!min || !mid || !max) return;\n\n        // We populate two paint arrays because, for cross-faded properties, we don't know which direction\n        // we're cross-fading to at layout time. In order to keep vertex attributes to a minimum and not pass\n        // unnecessary vertex data to the shaders, we determine which to upload at draw time.\n        //\n        // The crossfade `from` vertex is the value at the previous integer zoom (min when zooming in,\n        // max when zooming out) and `to` is the value at the current integer zoom (mid). This matches the\n        // convention used by CrossFadedConstantBinder, where `u_dasharray_to` / `u_pattern_to` carry the\n        // current zoom's value and the crossfade `t` blends from the previous value to it.\n        for (let i = start; i < end; i++) {\n            this.emplace(this.zoomInPaintVertexArray, i, min, mid);\n            this.emplace(this.zoomOutPaintVertexArray, i, max, mid);\n        }\n    }\n\n    upload(context: Context) {\n        if (this.zoomInPaintVertexArray?.arrayBuffer.byteLength && this.zoomOutPaintVertexArray?.arrayBuffer.byteLength) {\n            const attributes = this.getVertexAttributes();\n            this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, attributes, this.expression.isStateDependent);\n            this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, attributes, this.expression.isStateDependent);\n        }\n    }\n\n    destroy() {\n        if (this.zoomOutPaintVertexBuffer) this.zoomOutPaintVertexBuffer.destroy();\n        if (this.zoomInPaintVertexBuffer) this.zoomInPaintVertexBuffer.destroy();\n    }\n}\n\nclass CrossFadedPatternBinder extends CrossFadedBinder<ImagePosition> {\n    protected getPositions(options: PaintOptions): {[_: string]: ImagePosition} {\n        return options.imagePositions;\n    }\n\n    protected getPositionIds(feature: Feature) {\n        return feature.patterns?.[this.layerId];\n    }\n\n    getVertexAttributes(): StructArrayMember[] {\n        return patternAttributes.members;\n    }\n\n    protected emplace(array: StructArray, index: number, fromPos: ImagePosition, toPos: ImagePosition): void {\n        array.emplace(index,\n            fromPos.tlbr[0], fromPos.tlbr[1], fromPos.tlbr[2], fromPos.tlbr[3],\n            toPos.tlbr[0], toPos.tlbr[1], toPos.tlbr[2], toPos.tlbr[3],\n            fromPos.pixelRatio,\n            toPos.pixelRatio,\n        );\n    }\n}\n\nclass CrossFadedDasharrayBinder extends CrossFadedBinder<DashEntry> {\n    protected getPositions(options: PaintOptions): {[_: string]: DashEntry} {\n        return options.dashPositions;\n    }\n\n    protected getPositionIds(feature: Feature) {\n        return feature.dashes?.[this.layerId];\n    }\n\n    getVertexAttributes(): StructArrayMember[] {\n        return dashAttributes.members;\n    }\n\n    protected emplace(array: StructArray, index: number, fromPos: DashEntry, toPos: DashEntry): void {\n        array.emplace(index,\n            0, fromPos.y, fromPos.height, fromPos.width,\n            0, toPos.y, toPos.height, toPos.width,\n        );\n    }\n}\n\n/**\n * @internal\n * ProgramConfiguration contains the logic for binding style layer properties and tile\n * layer feature data into GL program uniforms and vertex attributes.\n *\n * Non-data-driven property values are bound to shader uniforms. Data-driven property\n * values are bound to vertex attributes. In order to support a uniform GLSL syntax over\n * both, the [shaders](../shaders/README.md) define a `#pragma` abstraction, which\n * ProgramConfiguration is responsible for implementing. At runtime,\n * it examines the attributes of a particular layer, combines this with fixed knowledge\n * about how layers of the particular type are implemented, and determines which uniforms\n * and vertex attributes will be required. It can then substitute the appropriate text\n * into the shader source code, create and link a program, and bind the uniforms and\n * vertex attributes in preparation for drawing.\n *\n * When a vector tile is parsed, this same configuration information is used to\n * populate the attribute buffers needed for data-driven styling using the zoom\n * level and feature property data.\n */\nexport class ProgramConfiguration {\n    binders: {[_: string]: AttributeBinder | UniformBinder};\n    cacheKey: string;\n\n    _buffers: VertexBuffer[];\n\n    constructor(layer: TypedStyleLayer, zoom: number, filterProperties: (_: string) => boolean) {\n        this.binders = {};\n        this._buffers = [];\n\n        const keys = [];\n\n        for (const property in layer.paint._values) {\n            if (!filterProperties(property)) continue;\n            const value = (layer.paint as any).get(property);\n            if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n                continue;\n            }\n            const names = paintAttributeNames(property, layer.type);\n            const expression = value.value;\n            const type = value.property.specification.type;\n            const useIntegerZoom = (value.property as any).useIntegerZoom;\n            const propType = value.property.specification['property-type'];\n            const isCrossFaded = propType === 'cross-faded' || propType === 'cross-faded-data-driven';\n\n            if (expression.kind === 'constant') {\n                this.binders[property] = isCrossFaded ?\n                    new CrossFadedConstantBinder(expression.value, names) :\n                    new ConstantBinder(expression.value, names, type);\n                keys.push(`/u_${property}`);\n\n            } else if (expression.kind === 'source' || isCrossFaded) {\n                const StructArrayLayout = layoutType(property, type, 'source');\n                this.binders[property] = isCrossFaded ?\n                    property === 'line-dasharray' ?\n                        new CrossFadedDasharrayBinder(expression as CompositeExpression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) :\n                        new CrossFadedPatternBinder(expression as CompositeExpression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) :\n                    new SourceExpressionBinder(expression as SourceExpression, names, type, StructArrayLayout);\n                keys.push(`/a_${property}`);\n\n            } else {\n                const StructArrayLayout = layoutType(property, type, 'composite');\n                this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout);\n                keys.push(`/z_${property}`);\n            }\n        }\n\n        this.cacheKey = keys.sort().join('');\n    }\n\n    getMaxValue(property: string): number {\n        const binder = this.binders[property];\n        return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0;\n    }\n\n    populatePaintArrays(newLength: number, feature: Feature, options: PaintOptions): void {\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder)\n                binder.populatePaintArray(newLength, feature, options);\n        }\n    }\n    setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition): void {\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof CrossFadedConstantBinder)\n                binder.setConstantPatternPositions(posTo, posFrom);\n        }\n    }\n\n    setConstantDashPositions(dashTo: DashEntry, dashFrom: DashEntry): void {\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof CrossFadedConstantBinder)\n                binder.setConstantDashPositions(dashTo, dashFrom);\n        }\n    }\n\n    updatePaintArrays(\n        featureStates: FeatureStates,\n        featureMap: FeaturePositionMap,\n        vtLayer: VectorTileLayerLike,\n        layer: TypedStyleLayer,\n        options: PaintOptions\n    ): boolean {\n        let dirty: boolean = false;\n        for (const fs of featureStates) {\n            const positions = featureMap.getPositions(fs.id);\n\n            for (const pos of positions) {\n                const feature = vtLayer.feature(pos.index);\n\n                for (const property in this.binders) {\n                    const binder = this.binders[property];\n                    if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ||\n                         binder instanceof CrossFadedBinder) && binder.expression.isStateDependent === true) {\n                        //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255\n                        const value = (layer.paint as any).get(property);\n                        binder.expression = value.value;\n                        binder.updatePaintArray(pos.start, pos.end, feature, fs.state, options);\n                        dirty = true;\n                    }\n                }\n            }\n        }\n        return dirty;\n    }\n\n    defines(): string[] {\n        const result = [];\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) {\n                result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`));\n            }\n        }\n        return result;\n    }\n\n    getBinderAttributes(): string[] {\n        const result = [];\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) {\n                for (const attribute of binder.paintVertexAttributes) {\n                    result.push(attribute.name);\n                }\n            } else if (binder instanceof CrossFadedBinder) {\n                const attributes = binder.getVertexAttributes();\n                for (const attribute of attributes) {\n                    result.push(attribute.name);\n                }\n            }\n        }\n        return result;\n    }\n\n    getBinderUniforms(): string[] {\n        const uniforms = [];\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) {\n                for (const uniformName of binder.uniformNames) {\n                    uniforms.push(uniformName);\n                }\n            }\n        }\n        return uniforms;\n    }\n\n    getPaintVertexBuffers(): VertexBuffer[] {\n        return this._buffers;\n    }\n\n    getUniforms(context: Context, locations: UniformLocations): BinderUniform[] {\n        const uniforms = [];\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) {\n                for (const name of binder.uniformNames) {\n                    if (locations[name]) {\n                        const binding = binder.getBinding(context, locations[name], name);\n                        uniforms.push({name, property, binding});\n                    }\n                }\n            }\n        }\n        return uniforms;\n    }\n\n    setUniforms(\n        context: Context,\n        binderUniforms: BinderUniform[],\n        properties: any,\n        globals: GlobalProperties\n    ): void {\n        // Uniform state bindings are owned by the Program, but we set them\n        // from within the ProgramConfiguration's binder members.\n        for (const {name, property, binding} of binderUniforms) {\n            (this.binders[property] as any).setUniform(binding, globals, properties.get(property), name);\n        }\n    }\n\n    updatePaintBuffers(crossfade?: CrossfadeParameters): void {\n        this._buffers = [];\n\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (crossfade && binder instanceof CrossFadedBinder) {\n                const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer;\n                if (patternVertexBuffer) this._buffers.push(patternVertexBuffer);\n\n            } else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) {\n                this._buffers.push(binder.paintVertexBuffer);\n            }\n        }\n    }\n\n    upload(context: Context): void {\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder)\n                binder.upload(context);\n        }\n        this.updatePaintBuffers();\n    }\n\n    destroy(): void {\n        for (const property in this.binders) {\n            const binder = this.binders[property];\n            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder)\n                binder.destroy();\n        }\n    }\n}\n\nexport class ProgramConfigurationSet<Layer extends TypedStyleLayer> {\n    programConfigurations: {[_: string]: ProgramConfiguration};\n    needsUpload: boolean;\n    _featureMap: FeaturePositionMap;\n    _bufferOffset: number;\n\n    constructor(layers: readonly Layer[], zoom: number, filterProperties: (_: string) => boolean = () => true) {\n        this.programConfigurations = {};\n        for (const layer of layers) {\n            this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties);\n        }\n        this.needsUpload = false;\n        this._featureMap = new FeaturePositionMap();\n        this._bufferOffset = 0;\n    }\n\n    populatePaintArrays(length: number, feature: Feature, index: number, options: PaintOptions): void {\n        for (const key in this.programConfigurations) {\n            this.programConfigurations[key].populatePaintArrays(length, feature, options);\n        }\n\n        if (feature.id !== undefined) {\n            this._featureMap.add(feature.id, index, this._bufferOffset, length);\n        }\n        this._bufferOffset = length;\n\n        this.needsUpload = true;\n    }\n\n    updatePaintArrays(featureStates: FeatureStates, vtLayer: VectorTileLayerLike, layers: readonly TypedStyleLayer[], options: PaintOptions): void {\n        for (const layer of layers) {\n            this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, options) || this.needsUpload;\n        }\n    }\n\n    get(layerId: string): ProgramConfiguration {\n        return this.programConfigurations[layerId];\n    }\n\n    upload(context: Context): void {\n        if (!this.needsUpload) return;\n        for (const layerId in this.programConfigurations) {\n            this.programConfigurations[layerId].upload(context);\n        }\n        this.needsUpload = false;\n    }\n\n    destroy(): void {\n        for (const layerId in this.programConfigurations) {\n            this.programConfigurations[layerId].destroy();\n        }\n    }\n}\n\nfunction paintAttributeNames(property: string, type: string) {\n    const attributeNameExceptions = {\n        'text-opacity': ['opacity'],\n        'icon-opacity': ['opacity'],\n        'text-color': ['fill_color'],\n        'icon-color': ['fill_color'],\n        'text-halo-color': ['halo_color'],\n        'icon-halo-color': ['halo_color'],\n        'text-halo-blur': ['halo_blur'],\n        'icon-halo-blur': ['halo_blur'],\n        'text-halo-width': ['halo_width'],\n        'icon-halo-width': ['halo_width'],\n        'line-gap-width': ['gapwidth'],\n        'line-dasharray': ['dasharray_to', 'dasharray_from'],\n        'line-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n        'fill-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n        'fill-extrusion-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n    };\n\n    return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')];\n}\n\nfunction getLayoutException(property: string) {\n    const propertyExceptions = {\n        'line-pattern': {\n            'source': PatternLayoutArray,\n            'composite': PatternLayoutArray\n        },\n        'fill-pattern': {\n            'source': PatternLayoutArray,\n            'composite': PatternLayoutArray\n        },\n        'fill-extrusion-pattern': {\n            'source': PatternLayoutArray,\n            'composite': PatternLayoutArray\n        },\n        'line-dasharray': {\n            'source': DashLayoutArray,\n            'composite': DashLayoutArray\n        },\n    };\n\n    return propertyExceptions[property];\n}\n\nfunction layoutType(property: string, type: string, binderType: string) {\n    const defaultLayouts = {\n        'color': {\n            'source': StructArrayLayout2f8,\n            'composite': StructArrayLayout4f16\n        },\n        'number': {\n            'source': StructArrayLayout1f4,\n            'composite': StructArrayLayout2f8\n        }\n    };\n\n    const layoutException = getLayoutException(property);\n    return  layoutException?.[binderType] || defaultLayouts[type][binderType];\n}\n\nregister('ConstantBinder', ConstantBinder);\nregister('CrossFadedConstantBinder', CrossFadedConstantBinder);\nregister('SourceExpressionBinder', SourceExpressionBinder);\nregister('CrossFadedPatternBinder', CrossFadedPatternBinder);\nregister('CrossFadedDasharrayBinder', CrossFadedDasharrayBinder);\nregister('CompositeExpressionBinder', CompositeExpressionBinder);\nregister('ProgramConfiguration', ProgramConfiguration, {omit: ['_buffers']});\nregister('ProgramConfigurationSet', ProgramConfigurationSet);\n", "import {warnOnce, clamp} from '../util/util.ts';\nimport {EXTENT} from './extent.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {VectorTileFeatureLike} from '@maplibre/vt-pbf';\n\n// These bounds define the minimum and maximum supported coordinate values.\n// While visible coordinates are within [0, EXTENT], tiles may theoretically\n// contain coordinates within [-Infinity, Infinity]. Our range is limited by the\n// number of bits used to represent the coordinate.\nconst BITS = 15;\nconst MAX = Math.pow(2, BITS - 1) - 1;\nconst MIN = -MAX - 1;\n\n/**\n * Loads a geometry from a VectorTileFeatureLike and scales it to the common extent\n * used internally.\n * @param feature - the vector tile feature to load\n */\nexport function loadGeometry(feature: VectorTileFeatureLike): Point[][] {\n    const scale = EXTENT / feature.extent;\n    const geometry = feature.loadGeometry();\n    for (const ring of geometry) {\n        for (const point of ring) {\n            // round here because mapbox-gl-native uses integers to represent\n            // points and we need to do the same to avoid rendering differences.\n            const x = Math.round(point.x * scale);\n            const y = Math.round(point.y * scale);\n\n            point.x = clamp(x, MIN, MAX);\n            point.y = clamp(y, MIN, MAX);\n\n            if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) {\n                // warn when exceeding allowed extent except for the 1-px-off case\n                // https://github.com/mapbox/mapbox-gl-js/issues/8992\n                warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');\n            }\n        }\n    }\n    return geometry;\n}\n", "import {loadGeometry} from './load_geometry.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Feature} from '@maplibre/maplibre-gl-style-spec';\nimport type {VectorTileFeatureLike} from '@maplibre/vt-pbf';\n\ntype EvaluationFeature = Feature & { geometry: Point[][] };\n/**\n * Construct a new feature based on a VectorTileFeatureLike for expression evaluation, the geometry of which\n * will be loaded based on necessity.\n * @param feature - the feature to evaluate\n * @param needGeometry - if set to true this will load the geometry\n */\nexport function toEvaluationFeature(feature: VectorTileFeatureLike, needGeometry: boolean): EvaluationFeature {\n    return {type: feature.type,\n        id: feature.id,\n        properties: feature.properties,\n        geometry: needGeometry ? loadGeometry(feature) : []};\n}\n", "import Point from '@mapbox/point-geometry';\n\nimport type {Point2D} from '@maplibre/maplibre-gl-style-spec';\n\nexport interface ReadOnlyBounds {\n    readonly minX: number;\n    readonly maxX: number;\n    readonly minY: number;\n    readonly maxY: number;\n\n    /**\n     * Returns whether this bounding box contains a point\n     *\n     * @param point - The point to check\n     * @returns True if this bounding box contains point, false otherwise.\n     */\n    contains(point: Point2D): boolean;\n\n    /**\n     * Returns true if this bounding box contains no points\n     *\n     * @returns True if this bounding box contains no points.\n     */\n    empty(): boolean;\n\n    /**\n     * Returns the width of this bounding box.\n     *\n     * @returns `maxX - minX`.\n     */\n    width(): number;\n\n    /**\n     * Returns the height of this bounding box.\n     *\n     * @returns `maxY - minY`.\n     */\n    height(): number;\n\n    /**\n     * Returns true if this bounding box completely covers `other`.\n     *\n     * @param other - The other bounding box\n     * @returns True if this bounding box completely encloses `other`\n     */\n    covers(other: ReadOnlyBounds): boolean;\n\n    /**\n     * Returns true if this bounding box touches any part of `other`.\n     *\n     * @param other - The other bounding box\n     * @returns True if this bounding box touches any part of `other`.\n     */\n    intersects(other: ReadOnlyBounds): boolean;\n}\n\n/** A 2-d bounding box covering an X and Y range. */\nexport class Bounds implements ReadOnlyBounds {\n    minX: number = Infinity;\n    maxX: number = -Infinity;\n    minY: number = Infinity;\n    maxY: number = -Infinity;\n\n    /**\n     * Expands this bounding box to include point.\n     *\n     * @param point - The point to include in this bounding box\n     * @returns This mutated bounding box\n     */\n    extend(point: Point2D): this {\n        this.minX = Math.min(this.minX, point.x);\n        this.minY = Math.min(this.minY, point.y);\n        this.maxX = Math.max(this.maxX, point.x);\n        this.maxY = Math.max(this.maxY, point.y);\n        return this;\n    }\n\n    /**\n     * Expands this bounding box by a fixed amount in each direction.\n     *\n     * @param amount - The amount to expand the box by, or contract if negative\n     * @returns This mutated bounding box\n     */\n    expandBy(amount: number): this {\n        this.minX -= amount;\n        this.minY -= amount;\n        this.maxX += amount;\n        this.maxY += amount;\n        // check if bounds collapsed in either dimension\n        if (this.minX > this.maxX || this.minY > this.maxY) {\n            this.minX = Infinity;\n            this.maxX = -Infinity;\n            this.minY = Infinity;\n            this.maxY = -Infinity;\n        }\n        return this;\n    }\n\n    /**\n     * Shrinks this bounding box by a fixed amount in each direction.\n     *\n     * @param amount - The amount to shrink the box by\n     * @returns This mutated bounding box\n     */\n    shrinkBy(amount: number): this {\n        return this.expandBy(-amount);\n    }\n\n    /**\n     * Returns a new bounding box that contains all of the corners of this bounding\n     * box with a transform applied. Does not modify this bounding box.\n     *\n     * @param fn - The function to apply to each corner\n     * @returns A new bounding box containing all of the mapped points.\n     */\n    map(fn: (point: Point) => Point2D): Bounds {\n        const result = new Bounds();\n        result.extend(fn(new Point(this.minX, this.minY)));\n        result.extend(fn(new Point(this.maxX, this.minY)));\n        result.extend(fn(new Point(this.minX, this.maxY)));\n        result.extend(fn(new Point(this.maxX, this.maxY)));\n        return result;\n    }\n\n    /**\n     * Creates a new bounding box that includes all points provided.\n     *\n     * @param points - The points to include inside the bounding box\n     * @returns The new bounding box\n     */\n    static fromPoints(points: Point2D[]): Bounds {\n        const result = new Bounds();\n        for (const p of points) {\n            result.extend(p);\n        }\n        return result;\n    }\n\n    contains(point: Point2D): boolean {\n        return point.x >= this.minX && point.x <= this.maxX && point.y >= this.minY && point.y <= this.maxY;\n    }\n\n    empty(): boolean {\n        return this.minX > this.maxX;\n    }\n\n    width(): number {\n        return this.maxX - this.minX;\n    }\n\n    height(): number {\n        return this.maxY - this.minY;\n    }\n\n    covers(other: ReadOnlyBounds): boolean {\n        return !this.empty() && !other.empty() &&\n            other.minX >= this.minX &&\n            other.maxX <= this.maxX &&\n            other.minY >= this.minY &&\n            other.maxY <= this.maxY;\n    }\n\n    intersects(other: ReadOnlyBounds): boolean {\n        return !this.empty() && !other.empty() &&\n            other.minX <= this.maxX &&\n            other.maxX >= this.minX &&\n            other.minY <= this.maxY &&\n            other.maxY >= this.minY;\n    }\n}\n", "import Point from '@mapbox/point-geometry';\nimport {Bounds, type ReadOnlyBounds} from '../geo/bounds.ts';\nimport {EXTENT} from './extent.ts';\n\nimport type {Point2D} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * The bounding box covering the entire extent of a tile.\n */\nexport const EXTENT_BOUNDS = Bounds.fromPoints([new Point(0, 0), new Point(EXTENT, EXTENT)]) as ReadOnlyBounds;\n\n/**\n * Whether an edge runs along one of the lines the tile was cut out of the world at. Clipping happens\n * on the buffer rectangle, outside the tile, so an axis parallel edge out there belongs to the cut\n * rather than to the feature. Such an edge is shared with the neighbouring tile, which cuts the same\n * feature somewhere else, so geometry derived from it has to stay identical in both tiles.\n * @param p1 - First vertex of the edge\n * @param p2 - Second vertex of the edge\n * @returns True when the edge lies on a clip line.\n */\nexport function isBoundaryEdge(p1: Point2D, p2: Point2D): boolean {\n    return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) ||\n        (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT));\n}\n\n/**\n * Whether a ring lies completely off one side of the tile, and so cannot contribute a visible pixel.\n * @param ring - Ring to test\n * @returns True when every vertex is beyond the same edge of the tile.\n */\nexport function isEntirelyOutside(ring: Point2D[]): boolean {\n    return ring.every(p => p.x < 0) ||\n        ring.every(p => p.x > EXTENT) ||\n        ring.every(p => p.y < 0) ||\n        ring.every(p => p.y > EXTENT);\n}\n\n/**\n * Whether a point lies outside the tile, in the buffer the neighbouring tile draws.\n * @param p - Point to test\n * @returns True when the point is beyond the left or top edge, or on or beyond the right or bottom edge.\n */\nexport function isOutsideTile(p: Point2D): boolean {\n    return p.x < 0 || p.x >= EXTENT || p.y < 0 || p.y >= EXTENT;\n}\n", "import {CircleLayoutArray} from '../array_types.g.ts';\nimport {members as layoutAttributes} from './circle_attributes.ts';\nimport {SegmentVector} from '../segment.ts';\nimport {ProgramConfigurationSet} from '../program_configuration.ts';\nimport {TriangleIndexArray} from '../index_array_type.ts';\nimport {loadGeometry} from '../load_geometry.ts';\nimport {toEvaluationFeature} from '../evaluation_feature.ts';\nimport {isOutsideTile} from '../extent_bounds.ts';\nimport {register} from '../../util/web_worker_transfer.ts';\nimport {EvaluationParameters} from '../../style/evaluation_parameters.ts';\n\nimport type {CircleGranularity} from '../../render/subdivision_granularity_settings.ts';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {\n    Bucket,\n    BucketParameters,\n    BucketFeature,\n    BucketDependencyParameters,\n    IndexedFeature,\n    PopulateParameters\n} from '../bucket.ts';\nimport type {CircleStyleLayer} from '../../style/style_layer/circle_style_layer.ts';\nimport type {HeatmapStyleLayer} from '../../style/style_layer/heatmap_style_layer.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {IndexBuffer} from '../../webgl/index_buffer.ts';\nimport type {VertexBuffer} from '../../webgl/vertex_buffer.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state.ts';\nimport type {ImagePosition} from '../../render/image_atlas.ts';\nimport type {VectorTileLayerLike} from '@maplibre/vt-pbf';\n\nconst VERTEX_MIN_VALUE = -32768; // -(2^15)\n\n// Extrude is in range 0..7, which will be mapped to -1..1 in the shader.\nfunction addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {\n    // We pack circle position and extrude into range 0..65535, but vertices are stored as *signed* 16-bit integers, so we need to offset the number by 2^15.\n    layoutVertexArray.emplaceBack(\n        VERTEX_MIN_VALUE + (x * 8) + extrudeX,\n        VERTEX_MIN_VALUE + (y * 8) + extrudeY);\n}\n\n/**\n * @internal\n * Circles are represented by two triangles.\n *\n * Each corner has a pos that is the center of the circle and an extrusion\n * vector that is where it points.\n */\nexport class CircleBucket<Layer extends CircleStyleLayer | HeatmapStyleLayer> implements Bucket {\n    index: number;\n    zoom: number;\n    overscaling: number;\n    layerIds: string[];\n    layers: Layer[];\n    stateDependentLayers: Layer[];\n    stateDependentLayerIds: string[];\n\n    layoutVertexArray: CircleLayoutArray;\n    layoutVertexBuffer: VertexBuffer;\n\n    indexArray: TriangleIndexArray;\n    indexBuffer: IndexBuffer;\n\n    hasDependencies: boolean;\n    programConfigurations: ProgramConfigurationSet<Layer>;\n    segments: SegmentVector;\n    uploaded: boolean;\n\n    constructor(options: BucketParameters<Layer>) {\n        this.zoom = options.zoom;\n        this.overscaling = options.overscaling;\n        this.layers = options.layers;\n        this.layerIds = this.layers.map(layer => layer.id);\n        this.index = options.index;\n        this.hasDependencies = false;\n\n        this.layoutVertexArray = new CircleLayoutArray();\n        this.indexArray = new TriangleIndexArray();\n        this.segments = new SegmentVector();\n        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n        this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n    }\n\n    populate(features: IndexedFeature[], options: PopulateParameters, canonical: CanonicalTileID): void {\n        const styleLayer = this.layers[0];\n        const bucketFeatures: BucketFeature[] = [];\n        let circleSortKey = null;\n        let sortFeaturesByKey = false;\n\n        // Heatmap circles are usually large (and map-pitch-aligned), tessellate them to allow curvature along the globe.\n        let subdivide = styleLayer.type === 'heatmap';\n\n        // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access\n        if (styleLayer.type === 'circle') {\n            const circleStyle = (styleLayer as CircleStyleLayer);\n            circleSortKey = circleStyle.layout.get('circle-sort-key');\n            sortFeaturesByKey = !circleSortKey.isConstant();\n\n            // Circles that are \"printed\" onto the map surface should be tessellated to follow the globe's curvature.\n            subdivide ||= circleStyle.paint.get('circle-pitch-alignment') === 'map';\n        }\n\n        const granularity = subdivide ? options.subdivisionGranularity.circle : 1;\n\n        const globalProperties = new EvaluationParameters(this.zoom);\n        const needGeometry = this.layers[0]._featureFilter.needGeometry;\n        for (const {feature, id, index, sourceLayerIndex} of features) {\n            const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n            if (!this.layers[0]._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue;\n\n            const sortKey = sortFeaturesByKey ?\n                circleSortKey.evaluate(evaluationFeature, {}, canonical) :\n                undefined;\n\n            const bucketFeature: BucketFeature = {\n                id,\n                properties: feature.properties,\n                type: feature.type,\n                sourceLayerIndex,\n                index,\n                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),\n                patterns: {},\n                sortKey\n            };\n\n            bucketFeatures.push(bucketFeature);\n\n        }\n\n        if (sortFeaturesByKey) {\n            bucketFeatures.sort((a, b) => a.sortKey - b.sortKey);\n        }\n\n        for (const bucketFeature of bucketFeatures) {\n            const {geometry, index, sourceLayerIndex} = bucketFeature;\n            const feature = features[index].feature;\n\n            this.addFeature(bucketFeature, geometry, index, canonical, granularity);\n            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n        }\n    }\n\n    update(states: FeatureStates, vtLayer: VectorTileLayerLike, imagePositions: {[_: string]: ImagePosition}): void {\n        if (!this.stateDependentLayers.length) return;\n        this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, {\n            imagePositions\n        });\n    }\n\n    addFeatures(_parameters: BucketDependencyParameters): void {}\n\n    isEmpty(): boolean {\n        return this.layoutVertexArray.length === 0;\n    }\n\n    uploadPending(): boolean {\n        return !this.uploaded || this.programConfigurations.needsUpload;\n    }\n\n    upload(context: Context): void {\n        if (!this.uploaded) {\n            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n            this.indexBuffer = context.createIndexBuffer(this.indexArray);\n        }\n        this.programConfigurations.upload(context);\n        this.uploaded = true;\n    }\n\n    destroy(): void {\n        if (!this.layoutVertexBuffer) return;\n        this.layoutVertexBuffer.destroy();\n        this.indexBuffer.destroy();\n        this.programConfigurations.destroy();\n        this.segments.destroy();\n    }\n\n    addFeature(feature: BucketFeature, geometry: Point[][], index: number, canonical: CanonicalTileID, granularity: CircleGranularity = 1): void {\n        // Since we store the circle's center in each vertex, we only have 3 bits for actual vertex position in each axis.\n        // Thus the valid range of positions is 0..7.\n        // This gives us 4 possible granularity settings that are symmetrical.\n\n        // This array stores vertex positions that should by used by the tessellated quad.\n        let extrudes: number[];\n\n        switch (granularity) {\n            case 1:\n                extrudes = [0, 7];\n                break;\n            case 3:\n                extrudes = [0, 2, 5, 7];\n                break;\n            case 5:\n                extrudes = [0, 1, 3, 4, 6, 7];\n                break;\n            case 7:\n                extrudes = [0, 1, 2, 3, 4, 5, 6, 7];\n                break;\n            default:\n                throw new Error(`Invalid circle bucket granularity: ${granularity}; valid values are 1, 3, 5, 7.`);\n        }\n\n        const verticesPerAxis = extrudes.length;\n\n        for (const ring of geometry) {\n            for (const point of ring) {\n                const vx = point.x;\n                const vy = point.y;\n\n                if (isOutsideTile(point)) {\n                    continue;\n                }\n\n                const segment = this.segments.prepareSegment(verticesPerAxis * verticesPerAxis, this.layoutVertexArray, this.indexArray, feature.sortKey);\n                const index = segment.vertexLength;\n\n                for (let y = 0; y < verticesPerAxis; y++) {\n                    for (let x = 0; x < verticesPerAxis; x++) {\n                        addCircleVertex(this.layoutVertexArray, vx, vy, extrudes[x], extrudes[y]);\n                    }\n                }\n\n                for (let y = 0; y < verticesPerAxis - 1; y++) {\n                    for (let x = 0; x < verticesPerAxis - 1; x++) {\n                        const lowerIndex = index + y * verticesPerAxis + x;\n                        const upperIndex = index + (y + 1) * verticesPerAxis + x;\n                        this.indexArray.emplaceBack(lowerIndex, upperIndex + 1, lowerIndex + 1);\n                        this.indexArray.emplaceBack(lowerIndex, upperIndex, upperIndex + 1);\n                    }\n                }\n\n                segment.vertexLength += verticesPerAxis * verticesPerAxis;\n                segment.primitiveLength += (verticesPerAxis - 1) * (verticesPerAxis - 1) * 2;\n            }\n        }\n\n        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {imagePositions: {}, canonical});\n    }\n}\n\nregister('CircleBucket', CircleBucket, {omit: ['layers']});\n", "import {isCounterClockwise} from './util.ts';\nimport Point from '@mapbox/point-geometry';\n\nexport {polygonIntersectsBufferedPoint, polygonIntersectsMultiPolygon, polygonIntersectsBufferedMultiLine, polygonIntersectsPolygon, distToSegmentSquared, polygonIntersectsBox};\n\ntype Line = Point[];\ntype MultiLine = Line[];\ntype Ring = Point[];\ntype Polygon = Point[];\ntype MultiPolygon = Polygon[];\n\nfunction polygonIntersectsPolygon(polygonA: Polygon, polygonB: Polygon): boolean {\n    for (const point of polygonA) {\n        if (polygonContainsPoint(polygonB, point)) return true;\n    }\n\n    for (const point of polygonB) {\n        if (polygonContainsPoint(polygonA, point)) return true;\n    }\n\n    return lineIntersectsLine(polygonA, polygonB);\n}\n\nfunction polygonIntersectsBufferedPoint(polygon: Polygon, point: Point, radius: number): boolean {\n    if (polygonContainsPoint(polygon, point)) return true;\n    return pointIntersectsBufferedLine(point, polygon, radius);\n}\n\nfunction polygonIntersectsMultiPolygon(polygon: Polygon, multiPolygon: MultiPolygon): boolean {\n\n    if (polygon.length === 1) {\n        return multiPolygonContainsPoint(multiPolygon, polygon[0]);\n    }\n\n    for (const ring of multiPolygon) {\n        for (const point of ring) {\n            if (polygonContainsPoint(polygon, point)) return true;\n        }\n    }\n\n    for (const point of polygon) {\n        if (multiPolygonContainsPoint(multiPolygon, point)) return true;\n    }\n\n    for (const ring of multiPolygon) {\n        if (lineIntersectsLine(polygon, ring)) return true;\n    }\n\n    return false;\n}\n\nfunction polygonIntersectsBufferedMultiLine(polygon: Polygon, multiLine: MultiLine, radius: number): boolean {\n    for (const line of multiLine) {\n\n        if (polygon.length >= 3) {\n            for (const point of line) {\n                if (polygonContainsPoint(polygon, point)) return true;\n            }\n        }\n\n        if (lineIntersectsBufferedLine(polygon, line, radius)) return true;\n    }\n    return false;\n}\n\nfunction lineIntersectsBufferedLine(lineA: Line, lineB: Line, radius: number) {\n\n    if (lineA.length > 1) {\n        if (lineIntersectsLine(lineA, lineB)) return true;\n\n        // Check whether any point in either line is within radius of the other line\n        for (const point of lineB) {\n            if (pointIntersectsBufferedLine(point, lineA, radius)) return true;\n        }\n    }\n\n    for (const point of lineA) {\n        if (pointIntersectsBufferedLine(point, lineB, radius)) return true;\n    }\n\n    return false;\n}\n\nfunction lineIntersectsLine(lineA: Line, lineB: Line) {\n    if (lineA.length === 0 || lineB.length === 0) return false;\n    for (let i = 0; i < lineA.length - 1; i++) {\n        const a0 = lineA[i];\n        const a1 = lineA[i + 1];\n        for (let j = 0; j < lineB.length - 1; j++) {\n            const b0 = lineB[j];\n            const b1 = lineB[j + 1];\n            if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) return true;\n        }\n    }\n    return false;\n}\n\nfunction lineSegmentIntersectsLineSegment(a0: Point, a1: Point, b0: Point, b1: Point) {\n    return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) &&\n        isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1);\n}\n\nfunction pointIntersectsBufferedLine(p: Point, line: Line, radius: number) {\n    const radiusSquared = radius * radius;\n\n    if (line.length === 1) return p.distSqr(line[0]) < radiusSquared;\n\n    for (let i = 1; i < line.length; i++) {\n        // Find line segments that have a distance <= radius^2 to p\n        // In that case, we treat the line as \"containing point p\".\n        const v = line[i - 1], w = line[i];\n        if (distToSegmentSquared(p, v, w) < radiusSquared) return true;\n    }\n    return false;\n}\n\n// Code from https://stackoverflow.com/a/1501725/331379.\nfunction distToSegmentSquared(p: Point, v: Point, w: Point): number {\n    const l2 = v.distSqr(w);\n    if (l2 === 0) return p.distSqr(v);\n    const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;\n    if (t < 0) return p.distSqr(v);\n    if (t > 1) return p.distSqr(w);\n    return p.distSqr(w.sub(v)._mult(t)._add(v));\n}\n\n// point in polygon ray casting algorithm\nfunction multiPolygonContainsPoint(rings: Ring[], p: Point) {\n    let c = false,\n        ring, p1, p2;\n\n    for (const currentRing of rings) {\n        ring = currentRing;\n        for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n            p1 = ring[i];\n            p2 = ring[j];\n            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)) {\n                c = !c;\n            }\n        }\n    }\n    return c;\n}\n\nfunction polygonContainsPoint(ring: Ring, p: Point) {\n    let c = false;\n    for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n        const p1 = ring[i];\n        const p2 = ring[j];\n        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)) {\n            c = !c;\n        }\n    }\n    return c;\n}\n\nfunction polygonIntersectsBox(ring: Ring, boxX1: number, boxY1: number, boxX2: number, boxY2: number): boolean {\n    for (const p of ring) {\n        if (boxX1 <= p.x &&\n            boxY1 <= p.y &&\n            boxX2 >= p.x &&\n            boxY2 >= p.y) return true;\n    }\n\n    const corners = [\n        new Point(boxX1, boxY1),\n        new Point(boxX1, boxY2),\n        new Point(boxX2, boxY2),\n        new Point(boxX2, boxY1)];\n\n    if (ring.length > 2) {\n        for (const corner of corners) {\n            if (polygonContainsPoint(ring, corner)) return true;\n        }\n    }\n\n    for (let i = 0; i < ring.length - 1; i++) {\n        const p1 = ring[i];\n        const p2 = ring[i + 1];\n        if (edgeIntersectsBox(p1, p2, corners)) return true;\n    }\n\n    return false;\n}\n\nfunction edgeIntersectsBox(e1: Point, e2: Point, corners: Point[]) {\n    const tl = corners[0];\n    const br = corners[2];\n    // the edge and box do not intersect in either the x or y dimensions\n    if (((e1.x < tl.x) && (e2.x < tl.x)) ||\n        ((e1.x > br.x) && (e2.x > br.x)) ||\n        ((e1.y < tl.y) && (e2.y < tl.y)) ||\n        ((e1.y > br.y) && (e2.y > br.y))) return false;\n\n    // check if all corners of the box are on the same side of the edge\n    const dir = isCounterClockwise(e1, e2, corners[0]);\n    return dir !== isCounterClockwise(e1, e2, corners[1]) ||\n        dir !== isCounterClockwise(e1, e2, corners[2]) ||\n        dir !== isCounterClockwise(e1, e2, corners[3]);\n}\n", "import Point from '@mapbox/point-geometry';\nimport {polygonIntersectsBufferedPoint} from '../util/intersection_tests.ts';\n\nimport type {PossiblyEvaluatedPropertyValue} from './properties.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {CircleBucket} from '../data/bucket/circle_bucket.ts';\nimport type {LineBucket} from '../data/bucket/line_bucket.ts';\nimport type {IReadonlyTransform, GetElevation} from '../geo/transform_interface.ts';\nimport type {UnwrappedTileID} from '../tile/tile_id.ts';\n\nexport function getMaximumPaintValue(\n    property: string,\n    layer: StyleLayer,\n    bucket: CircleBucket<any> | LineBucket\n): number {\n    const value = ((layer.paint as any).get(property) as PossiblyEvaluatedPropertyValue<any>).value;\n    if (value.kind === 'constant') {\n        return value.value;\n    } else {\n        return bucket.programConfigurations.get(layer.id).getMaxValue(property);\n    }\n}\n\nexport function translateDistance(translate: [number, number]): number {\n    return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]);\n}\n\n/**\n * @internal\n * Translates a geometry by a certain pixels in tile coordinates\n * @param queryGeometry - The geometry to translate in tile coordinates\n * @param translate - The translation in pixels\n * @param translateAnchor - The anchor of the translation\n * @param bearing - The bearing of the map\n * @param pixelsToTileUnits - The scale factor from pixels to tile units\n * @returns the translated geometry in tile coordinates\n */\nexport function translate(queryGeometry: Point[],\n    translate: [number, number],\n    translateAnchor: 'viewport' | 'map',\n    bearing: number,\n    pixelsToTileUnits: number): Point[] {\n    if (!translate[0] && !translate[1]) {\n        return queryGeometry;\n    }\n    const pt = Point.convert(translate)._mult(pixelsToTileUnits);\n\n    if (translateAnchor === 'viewport') {\n        pt._rotate(-bearing);\n    }\n\n    const translated: Point[] = [];\n    for (const point of queryGeometry) {\n        translated.push(point.sub(pt));\n    }\n    return translated;\n}\n\n/**\n * Filter out consecutive duplicate points from a line\n */\nfunction _stripDuplicates(ring: Point[]): Point[] {\n    const filteredRing: Point[] = [];\n    for (let index = 0; index < ring.length; index++) {\n        const point = ring[index];\n        const prevPoint = filteredRing.at(-1);\n        if (index === 0 || (prevPoint && !(point.equals(prevPoint)))) {\n            filteredRing.push(point);\n        }\n    }\n    return filteredRing;\n}\n\nexport function offsetLine(rings: Point[][], offset: number): Point[][] {\n    const newRings: Point[][] = [];\n    for (const rawRing of rings) {\n        const ring = _stripDuplicates(rawRing);\n        const newRing: Point[] = [];\n        for (let index = 0; index < ring.length; index++) {\n            const point = ring[index];\n            const prevPoint = ring[index - 1];\n            const nextPoint = ring[index + 1];\n            // perpendicular unit vectors (outward unit normal vector):\n            // these indicate which direction the segments should be offset in\n            const unitNormalAB: Point = index === 0 ? new Point(0, 0) : point.sub(prevPoint)._unit()._perp();\n            const unitNormalBC: Point = index === ring.length - 1 ? new Point(0, 0) : nextPoint.sub(point)._unit()._perp();\n            // unit bisector direction\n            const bisectorDir = unitNormalAB._add(unitNormalBC)._unit();\n            const cosHalfAngle = bisectorDir.x * unitNormalBC.x + bisectorDir.y * unitNormalBC.y;\n            if (cosHalfAngle !== 0) {\n                bisectorDir._mult(1 / cosHalfAngle);\n            }\n            newRing.push(bisectorDir._mult(offset)._add(point));\n        }\n        newRings.push(newRing);\n    }\n    return newRings;\n}\n\ntype CircleIntersectionTestParams = {\n    queryGeometry: Point[];\n    size: number;\n    transform: IReadonlyTransform;\n    unwrappedTileID: UnwrappedTileID;\n    getElevation: GetElevation | undefined;\n    pitchAlignment?: 'map' | 'viewport';\n    pitchScale?: 'map' | 'viewport';\n};\n\nfunction intersectionTestMapMap({queryGeometry, size}: CircleIntersectionTestParams, point: Point): boolean {\n    return polygonIntersectsBufferedPoint(queryGeometry, point, size);\n}\n\nfunction intersectionTestMapViewport({queryGeometry, size, transform, unwrappedTileID, getElevation}: CircleIntersectionTestParams, point: Point): boolean {\n    const w = transform.projectTileCoordinates(point.x, point.y, unwrappedTileID, getElevation?.(point.x, point.y)).signedDistanceFromCamera;\n    const adjustedSize = size * (w / transform.cameraToCenterDistance);\n    return polygonIntersectsBufferedPoint(queryGeometry, point, adjustedSize);\n}\n\nfunction intersectionTestViewportMap({queryGeometry, size, transform, unwrappedTileID, getElevation}: CircleIntersectionTestParams, point: Point): boolean {\n    const w = transform.projectTileCoordinates(point.x, point.y, unwrappedTileID, getElevation?.(point.x, point.y)).signedDistanceFromCamera;\n    const adjustedSize = size * (transform.cameraToCenterDistance / w);\n    return polygonIntersectsBufferedPoint(queryGeometry, projectPoint(point, transform, unwrappedTileID, getElevation), adjustedSize);\n}\n\nfunction intersectionTestViewportViewport({queryGeometry, size, transform, unwrappedTileID, getElevation}: CircleIntersectionTestParams, point: Point): boolean {\n    return polygonIntersectsBufferedPoint(queryGeometry, projectPoint(point, transform, unwrappedTileID, getElevation), size);\n}\n\nexport function circleIntersection({\n    queryGeometry,\n    size,\n    transform,\n    unwrappedTileID,\n    getElevation,\n    pitchAlignment = 'map',\n    pitchScale = 'map'\n}: CircleIntersectionTestParams, geometry: Point[][]): boolean {\n    const intersectionTest = pitchAlignment === 'map'\n        ? (pitchScale === 'map' ? intersectionTestMapMap : intersectionTestMapViewport)\n        : (pitchScale === 'map' ? intersectionTestViewportMap : intersectionTestViewportViewport);\n\n    const param = {queryGeometry, size, transform, unwrappedTileID, getElevation} as CircleIntersectionTestParams;\n    for (const ring of geometry) {\n        for (const point of ring) {\n            if (intersectionTest(param, point)) {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nfunction projectPoint(tilePoint: Point, transform: IReadonlyTransform, unwrappedTileID: UnwrappedTileID, getElevation: GetElevation | undefined): Point {\n    // Convert `tilePoint` from tile coordinates to clip coordinates.\n    const clipPoint = transform.projectTileCoordinates(tilePoint.x, tilePoint.y, unwrappedTileID, getElevation?.(tilePoint.x, tilePoint.y)).point;\n    // Convert `clipPoint` from clip coordinates into pixel/screen coordinates.\n    return new Point(\n        (clipPoint.x * 0.5 + 0.5) * transform.width,\n        (-clipPoint.y * 0.5 + 0.5) * transform.height\n    );\n}\n\nexport function projectQueryGeometry(queryGeometry: Point[], transform: IReadonlyTransform, unwrappedTileID: UnwrappedTileID, getElevation: GetElevation | undefined): Point[] {\n    return queryGeometry.map((p) => {\n        return projectPoint(p, transform, unwrappedTileID, getElevation);\n    });\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type CircleLayoutProps = {\n    \"circle-sort-key\": DataDrivenProperty<number>,\n};\n\nexport type CircleLayoutPropsPossiblyEvaluated = {\n    \"circle-sort-key\": PossiblyEvaluatedPropertyValue<number>,\n};\n\nlet layout: Properties<CircleLayoutProps>;\nconst getLayout = (): Properties<CircleLayoutProps> => layout = layout || new Properties({\n    \"circle-sort-key\": new DataDrivenProperty(styleSpec[\"layout_circle\"][\"circle-sort-key\"] as any as StylePropertySpecification, \"circle-sort-key\"),\n});\n\nexport type CirclePaintProps = {\n    \"circle-radius\": DataDrivenProperty<number>,\n    \"circle-color\": DataDrivenProperty<Color>,\n    \"circle-blur\": DataDrivenProperty<number>,\n    \"circle-opacity\": DataDrivenProperty<number>,\n    \"circle-translate\": DataConstantProperty<[number, number]>,\n    \"circle-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"circle-pitch-scale\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"circle-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"circle-stroke-width\": DataDrivenProperty<number>,\n    \"circle-stroke-color\": DataDrivenProperty<Color>,\n    \"circle-stroke-opacity\": DataDrivenProperty<number>,\n};\n\nexport type CirclePaintPropsPossiblyEvaluated = {\n    \"circle-radius\": PossiblyEvaluatedPropertyValue<number>,\n    \"circle-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"circle-blur\": PossiblyEvaluatedPropertyValue<number>,\n    \"circle-opacity\": PossiblyEvaluatedPropertyValue<number>,\n    \"circle-translate\": [number, number],\n    \"circle-translate-anchor\": \"map\" | \"viewport\",\n    \"circle-pitch-scale\": \"map\" | \"viewport\",\n    \"circle-pitch-alignment\": \"map\" | \"viewport\",\n    \"circle-stroke-width\": PossiblyEvaluatedPropertyValue<number>,\n    \"circle-stroke-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"circle-stroke-opacity\": PossiblyEvaluatedPropertyValue<number>,\n};\n\nlet paint: Properties<CirclePaintProps>;\nconst getPaint = (): Properties<CirclePaintProps> => paint = paint || new Properties({\n    \"circle-radius\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-radius\"] as any as StylePropertySpecification, \"circle-radius\"),\n    \"circle-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-color\"] as any as StylePropertySpecification, \"circle-color\"),\n    \"circle-blur\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-blur\"] as any as StylePropertySpecification, \"circle-blur\"),\n    \"circle-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-opacity\"] as any as StylePropertySpecification, \"circle-opacity\"),\n    \"circle-translate\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate\"] as any as StylePropertySpecification, \"circle-translate\"),\n    \"circle-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate-anchor\"] as any as StylePropertySpecification, \"circle-translate-anchor\"),\n    \"circle-pitch-scale\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-scale\"] as any as StylePropertySpecification, \"circle-pitch-scale\"),\n    \"circle-pitch-alignment\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-alignment\"] as any as StylePropertySpecification, \"circle-pitch-alignment\"),\n    \"circle-stroke-width\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-width\"] as any as StylePropertySpecification, \"circle-stroke-width\"),\n    \"circle-stroke-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-color\"] as any as StylePropertySpecification, \"circle-stroke-color\"),\n    \"circle-stroke-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-opacity\"] as any as StylePropertySpecification, \"circle-stroke-opacity\"),\n});\n\nexport default ({ get paint(): Properties<CirclePaintProps> { return getPaint() }, get layout(): Properties<CircleLayoutProps> { return getLayout() } });", "import {StyleLayer, type QueryIntersectsFeatureParams} from '../style_layer.ts';\nimport {CircleBucket} from '../../data/bucket/circle_bucket.ts';\nimport {circleIntersection, getMaximumPaintValue, projectQueryGeometry, translateDistance, translate} from '../query_utils.ts';\nimport properties, {type CircleLayoutPropsPossiblyEvaluated, type CirclePaintPropsPossiblyEvaluated} from './circle_style_layer_properties.g.ts';\n\nimport type {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Bucket, BucketParameters} from '../../data/bucket.ts';\nimport type {CircleLayoutProps, CirclePaintProps} from './circle_style_layer_properties.g.ts';\n\nexport const isCircleStyleLayer = (layer: StyleLayer): layer is CircleStyleLayer => layer.type === 'circle';\n\n/**\n * A style layer that defines a circle\n */\nexport class CircleStyleLayer extends StyleLayer {\n    _unevaluatedLayout: Layout<CircleLayoutProps>;\n    layout: PossiblyEvaluated<CircleLayoutProps, CircleLayoutPropsPossiblyEvaluated>;\n\n    _transitionablePaint: Transitionable<CirclePaintProps>;\n    _transitioningPaint: Transitioning<CirclePaintProps>;\n    paint: PossiblyEvaluated<CirclePaintProps, CirclePaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n    }\n\n    createBucket(parameters: BucketParameters<any>): CircleBucket<any> {\n        return new CircleBucket(parameters);\n    }\n\n    queryRadius(bucket: Bucket): number {\n        const circleBucket: CircleBucket<CircleStyleLayer> = (bucket as any);\n        return getMaximumPaintValue('circle-radius', this, circleBucket) +\n            getMaximumPaintValue('circle-stroke-width', this, circleBucket) +\n            translateDistance(this.paint.get('circle-translate'));\n    }\n\n    queryIntersectsFeature({\n        queryGeometry,\n        feature,\n        featureState,\n        geometry,\n        transform,\n        pixelsToTileUnits,\n        unwrappedTileID,\n        getElevation}: QueryIntersectsFeatureParams\n    ): boolean {\n        const translatedPolygon = translate(queryGeometry,\n            this.paint.get('circle-translate'),\n            this.paint.get('circle-translate-anchor'),\n            -transform.bearingInRadians, pixelsToTileUnits);\n        const radius = this.paint.get('circle-radius').evaluate(feature, featureState);\n        const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState);\n        const size  = radius + stroke;\n\n        // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile\n        // Otherwise, compare geometry in the plane of the viewport\n        // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance\n        // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance\n\n        const pitchScale = this.paint.get('circle-pitch-scale');\n        const pitchAlignment = this.paint.get('circle-pitch-alignment');\n\n        let transformedPolygon: Point[];\n        let transformedSize: number;\n        if (pitchAlignment === 'map') {\n            transformedPolygon = translatedPolygon;\n            transformedSize = size * pixelsToTileUnits;\n        } else {\n            transformedPolygon = projectQueryGeometry(translatedPolygon, transform, unwrappedTileID, getElevation);\n            transformedSize = size;\n        }\n\n        return circleIntersection({\n            queryGeometry: transformedPolygon,\n            size: transformedSize,\n            transform,\n            unwrappedTileID,\n            getElevation,\n            pitchAlignment,\n            pitchScale\n        }, geometry);\n    }\n}\n\n", "import {CircleBucket} from './circle_bucket.ts';\nimport {register} from '../../util/web_worker_transfer.ts';\n\nimport type {HeatmapStyleLayer} from '../../style/style_layer/heatmap_style_layer.ts';\n\nexport class HeatmapBucket extends CircleBucket<HeatmapStyleLayer> {\n    // Needed for flow to accept omit: ['layers'] below, due to\n    // https://github.com/facebook/flow/issues/4262\n    layers: HeatmapStyleLayer[];\n}\n\nregister('HeatmapBucket', HeatmapBucket, {omit: ['layers']});\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type HeatmapPaintProps = {\n    \"heatmap-radius\": DataDrivenProperty<number>,\n    \"heatmap-weight\": DataDrivenProperty<number>,\n    \"heatmap-intensity\": DataConstantProperty<number>,\n    \"heatmap-color\": ColorRampProperty,\n    \"heatmap-opacity\": DataConstantProperty<number>,\n};\n\nexport type HeatmapPaintPropsPossiblyEvaluated = {\n    \"heatmap-radius\": PossiblyEvaluatedPropertyValue<number>,\n    \"heatmap-weight\": PossiblyEvaluatedPropertyValue<number>,\n    \"heatmap-intensity\": number,\n    \"heatmap-color\": ColorRampProperty,\n    \"heatmap-opacity\": number,\n};\n\nlet paint: Properties<HeatmapPaintProps>;\nconst getPaint = (): Properties<HeatmapPaintProps> => paint = paint || new Properties({\n    \"heatmap-radius\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-radius\"] as any as StylePropertySpecification, \"heatmap-radius\"),\n    \"heatmap-weight\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-weight\"] as any as StylePropertySpecification, \"heatmap-weight\"),\n    \"heatmap-intensity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-intensity\"] as any as StylePropertySpecification, \"heatmap-intensity\"),\n    \"heatmap-color\": new ColorRampProperty(styleSpec[\"paint_heatmap\"][\"heatmap-color\"] as any as StylePropertySpecification, \"heatmap-color\"),\n    \"heatmap-opacity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-opacity\"] as any as StylePropertySpecification, \"heatmap-opacity\"),\n});\n\nexport default ({ get paint(): Properties<HeatmapPaintProps> { return getPaint() } });", "import {register} from './web_worker_transfer.ts';\n\nimport type {Color} from '@maplibre/maplibre-gl-style-spec';\n\nexport type Size = {\n    width: number;\n    height: number;\n};\n\ntype Point2D = {\n    x: number;\n    y: number;\n};\n\nfunction createImage(image: any, {\n    width,\n    height\n}: Size, channels: number, data?: Uint8Array | Uint8ClampedArray) {\n    if (!data) {\n        data = new Uint8Array(width * height * channels);\n    } else if (data instanceof Uint8ClampedArray) {\n        data = new Uint8Array(data.buffer);\n    } else if (data.length !== width * height * channels) {\n        throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width * height * channels}`);\n    }\n    image.width = width;\n    image.height = height;\n    image.data = data;\n    return image;\n}\n\nfunction resizeImage(image: any, {\n    width,\n    height\n}: Size, channels: number) {\n    if (width === image.width && height === image.height) {\n        return;\n    }\n\n    const newImage = createImage({}, {width, height}, channels);\n\n    copyImage(image, newImage, {x: 0, y: 0}, {x: 0, y: 0}, {\n        width: Math.min(image.width, width),\n        height: Math.min(image.height, height)\n    }, channels);\n\n    image.width = width;\n    image.height = height;\n    image.data = newImage.data;\n}\n\nfunction copyImage(srcImg: any, dstImg: any, srcPt: Point2D, dstPt: Point2D, size: Size, channels: number) {\n    if (size.width === 0 || size.height === 0) {\n        return dstImg;\n    }\n\n    if (size.width > srcImg.width ||\n        size.height > srcImg.height ||\n        srcPt.x > srcImg.width - size.width ||\n        srcPt.y > srcImg.height - size.height) {\n        throw new RangeError('out of range source coordinates for image copy');\n    }\n\n    if (size.width > dstImg.width ||\n        size.height > dstImg.height ||\n        dstPt.x > dstImg.width - size.width ||\n        dstPt.y > dstImg.height - size.height) {\n        throw new RangeError('out of range destination coordinates for image copy');\n    }\n\n    const srcData = srcImg.data;\n    const dstData = dstImg.data;\n\n    if (srcData === dstData) throw new Error('srcData equals dstData, so image is already copied');\n\n    for (let y = 0; y < size.height; y++) {\n        const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels;\n        const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels;\n        for (let i = 0; i < size.width * channels; i++) {\n            dstData[dstOffset + i] = srcData[srcOffset + i];\n        }\n    }\n    return dstImg;\n}\n\n/**\n * An image with alpha color value\n */\nexport class AlphaImage {\n    width: number;\n    height: number;\n    data: Uint8Array;\n\n    constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) {\n        createImage(this, size, 1, data);\n    }\n\n    resize(size: Size): void {\n        resizeImage(this, size, 1);\n    }\n\n    clone(): AlphaImage {\n        return new AlphaImage({width: this.width, height: this.height}, new Uint8Array(this.data));\n    }\n\n    static copy(srcImg: AlphaImage, dstImg: AlphaImage, srcPt: Point2D, dstPt: Point2D, size: Size): void {\n        copyImage(srcImg, dstImg, srcPt, dstPt, size, 1);\n    }\n}\n\n/**\n * An object to store image data not premultiplied, because ImageData is not premultiplied.\n * Premultiplication is applied in JS before uploading to a texture.\n */\nexport class RGBAImage {\n    width: number;\n    height: number;\n\n    /**\n     * data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not support Uint8ClampedArray in all browsers.\n     */\n    data: Uint8Array;\n\n    constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) {\n        createImage(this, size, 4, data);\n    }\n\n    resize(size: Size): void {\n        resizeImage(this, size, 4);\n    }\n\n    replace(data: Uint8Array | Uint8ClampedArray, copy?: boolean): void {\n        if (copy) {\n            this.data.set(data);\n        } else if (data instanceof Uint8ClampedArray) {\n            this.data = new Uint8Array(data.buffer);\n        } else {\n            this.data = data;\n        }\n    }\n\n    clone(): RGBAImage {\n        return new RGBAImage({width: this.width, height: this.height}, new Uint8Array(this.data));\n    }\n\n    static copy(srcImg: RGBAImage | ImageData, dstImg: RGBAImage, srcPt: Point2D, dstPt: Point2D, size: Size): void {\n        copyImage(srcImg, dstImg, srcPt, dstPt, size, 4);\n    }\n\n    setPixel(row: number, col: number, value: Color): void {\n        const rLocation = (row * this.width + col) * 4;\n        this.data[rLocation + 0] = Math.round(value.r * 255 / value.a);\n        this.data[rLocation + 1] = Math.round(value.g * 255 / value.a);\n        this.data[rLocation + 2] = Math.round(value.b * 255 / value.a);\n        this.data[rLocation + 3] = Math.round(value.a * 255);\n    }\n}\n\n/** Returns a copy of RGBA data with premultiplied alpha. */\nexport function premultiplyAlpha(data: Uint8Array): Uint8Array {\n    const out = new Uint8Array(data.length);\n    for (let i = 0; i < data.length; i += 4) {\n        const a = data[i + 3];\n        out[i + 0] = Math.round(data[i + 0] * a / 255);\n        out[i + 1] = Math.round(data[i + 1] * a / 255);\n        out[i + 2] = Math.round(data[i + 2] * a / 255);\n        out[i + 3] = a;\n    }\n    return out;\n}\n\nregister('AlphaImage', AlphaImage);\nregister('RGBAImage', RGBAImage);\n", "import {RGBAImage} from './image.ts';\nimport {isPowerOfTwo} from './util.ts';\n\nimport type {StylePropertyExpression} from '@maplibre/maplibre-gl-style-spec';\n\nexport type ColorRampParams = {\n    expression: StylePropertyExpression;\n    evaluationKey: string;\n    resolution?: number;\n    image?: RGBAImage;\n    clips?: any[];\n};\n\n/**\n * Given an expression that should evaluate to a color ramp,\n * return a RGBA image representing that ramp expression.\n */\nexport function renderColorRamp(params: ColorRampParams): RGBAImage {\n    const evaluationGlobals = {};\n    const width = params.resolution || 256;\n    const height = params.clips ? params.clips.length : 1;\n    const image = params.image || new RGBAImage({width, height});\n\n    if (!isPowerOfTwo(width)) throw new Error(`width is not a power of 2 - ${width}`);\n\n    const renderPixel = (stride, index, progress) => {\n        evaluationGlobals[params.evaluationKey] = progress;\n        const pxColor = params.expression.evaluate(evaluationGlobals as any);\n        image.setPixel(stride / 4 / width, index / 4, pxColor);\n    };\n\n    if (!params.clips) {\n        for (let i = 0, j = 0; i < width; i++, j += 4) {\n            const progress = i / (width - 1);\n\n            renderPixel(0, j, progress);\n        }\n    } else {\n        for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) {\n            for (let i = 0, j = 0; i < width; i++, j += 4) {\n                // Remap progress between clips\n                const progress = i / (width - 1);\n                const {start, end} = params.clips[clip];\n                const evaluationProgress = start * (1 - progress) + end * progress;\n                renderPixel(stride, j, evaluationProgress);\n            }\n        }\n    }\n\n    return image;\n}\n", "import {type QueryIntersectsFeatureParams, StyleLayer} from '../style_layer.ts';\nimport {HeatmapBucket} from '../../data/bucket/heatmap_bucket.ts';\nimport properties, {type HeatmapPaintPropsPossiblyEvaluated} from './heatmap_style_layer_properties.g.ts';\nimport {renderColorRamp} from '../../util/color_ramp.ts';\nimport {circleIntersection, getMaximumPaintValue} from '../query_utils.ts';\n\nimport type {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.ts';\nimport type {RGBAImage} from '../../util/image.ts';\nimport type {Texture} from '../../webgl/texture.ts';\nimport type {Framebuffer} from '../../webgl/framebuffer.ts';\nimport type {HeatmapPaintProps} from './heatmap_style_layer_properties.g.ts';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Bucket} from '../../data/bucket.ts';\n\nexport const HEATMAP_FULL_RENDER_FBO_KEY = 'big-fb';\n\nexport const isHeatmapStyleLayer = (layer: StyleLayer): layer is HeatmapStyleLayer => layer.type === 'heatmap';\n\n/**\n * A style layer that defines a heatmap\n */\nexport class HeatmapStyleLayer extends StyleLayer {\n\n    heatmapFbos: Map<string, Framebuffer>;\n    colorRamp: RGBAImage;\n    colorRampTexture: Texture;\n\n    _transitionablePaint: Transitionable<HeatmapPaintProps>;\n    _transitioningPaint: Transitioning<HeatmapPaintProps>;\n    paint: PossiblyEvaluated<HeatmapPaintProps, HeatmapPaintPropsPossiblyEvaluated>;\n\n    createBucket(options: any): HeatmapBucket {\n        return new HeatmapBucket(options);\n    }\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n\n        this.heatmapFbos = new Map();\n        // make sure color ramp texture is generated for default heatmap color too\n        this._updateColorRamp();\n    }\n\n    _handleSpecialPaintPropertyUpdate(name: string): void {\n        if (name === 'heatmap-color') {\n            this._updateColorRamp();\n        }\n    }\n\n    _updateColorRamp(): void {\n        const expression = this._transitionablePaint._values['heatmap-color'].value.expression;\n        this.colorRamp = renderColorRamp({\n            expression,\n            evaluationKey: 'heatmapDensity',\n            image: this.colorRamp\n        });\n        this.colorRampTexture = null;\n    }\n\n    resize(): void {\n        if (this.heatmapFbos.has(HEATMAP_FULL_RENDER_FBO_KEY)) {\n            this.heatmapFbos.delete(HEATMAP_FULL_RENDER_FBO_KEY);\n        }\n    }\n\n    queryRadius(bucket: Bucket): number {\n        return getMaximumPaintValue('heatmap-radius', this, bucket as HeatmapBucket);\n    }\n\n    queryIntersectsFeature({\n        queryGeometry,\n        feature,\n        featureState,\n        geometry,\n        transform,\n        pixelsToTileUnits,\n        unwrappedTileID,\n        getElevation}: QueryIntersectsFeatureParams\n    ): boolean {\n        return circleIntersection({\n            queryGeometry,\n            size: this.paint.get('heatmap-radius').evaluate(feature, featureState) * pixelsToTileUnits,\n            transform,\n            unwrappedTileID,\n            getElevation\n        }, geometry);\n    }\n\n    hasOffscreenPass(): boolean {\n        return this.paint.get('heatmap-opacity') !== 0 && !this.isHidden();\n    }\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type HillshadePaintProps = {\n    \"hillshade-illumination-direction\": DataConstantProperty<NumberArray>,\n    \"hillshade-illumination-altitude\": DataConstantProperty<NumberArray>,\n    \"hillshade-illumination-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"hillshade-exaggeration\": DataConstantProperty<number>,\n    \"hillshade-shadow-color\": DataConstantProperty<ColorArray>,\n    \"hillshade-highlight-color\": DataConstantProperty<ColorArray>,\n    \"hillshade-accent-color\": DataConstantProperty<Color>,\n    \"hillshade-method\": DataConstantProperty<\"standard\" | \"basic\" | \"combined\" | \"igor\" | \"multidirectional\">,\n    \"resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n};\n\nexport type HillshadePaintPropsPossiblyEvaluated = {\n    \"hillshade-illumination-direction\": NumberArray,\n    \"hillshade-illumination-altitude\": NumberArray,\n    \"hillshade-illumination-anchor\": \"map\" | \"viewport\",\n    \"hillshade-exaggeration\": number,\n    \"hillshade-shadow-color\": ColorArray,\n    \"hillshade-highlight-color\": ColorArray,\n    \"hillshade-accent-color\": Color,\n    \"hillshade-method\": \"standard\" | \"basic\" | \"combined\" | \"igor\" | \"multidirectional\",\n    \"resampling\": \"linear\" | \"nearest\",\n};\n\nlet paint: Properties<HillshadePaintProps>;\nconst getPaint = (): Properties<HillshadePaintProps> => paint = paint || new Properties({\n    \"hillshade-illumination-direction\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-direction\"] as any as StylePropertySpecification, \"hillshade-illumination-direction\"),\n    \"hillshade-illumination-altitude\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-altitude\"] as any as StylePropertySpecification, \"hillshade-illumination-altitude\"),\n    \"hillshade-illumination-anchor\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-anchor\"] as any as StylePropertySpecification, \"hillshade-illumination-anchor\"),\n    \"hillshade-exaggeration\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-exaggeration\"] as any as StylePropertySpecification, \"hillshade-exaggeration\"),\n    \"hillshade-shadow-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-shadow-color\"] as any as StylePropertySpecification, \"hillshade-shadow-color\"),\n    \"hillshade-highlight-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-highlight-color\"] as any as StylePropertySpecification, \"hillshade-highlight-color\"),\n    \"hillshade-accent-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-accent-color\"] as any as StylePropertySpecification, \"hillshade-accent-color\"),\n    \"hillshade-method\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-method\"] as any as StylePropertySpecification, \"hillshade-method\"),\n    \"resampling\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"resampling\"] as any as StylePropertySpecification, \"resampling\"),\n});\n\nexport default ({ get paint(): Properties<HillshadePaintProps> { return getPaint() } });", "import {StyleLayer} from '../style_layer.ts';\nimport properties, {type HillshadePaintPropsPossiblyEvaluated} from './hillshade_style_layer_properties.g.ts';\nimport {degreesToRadians} from '../../util/util.ts';\n\nimport type {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.ts';\nimport type {HillshadePaintProps} from './hillshade_style_layer_properties.g.ts';\nimport type {Color, LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {EvaluationParameters} from '../evaluation_parameters.ts';\n\nexport const isHillshadeStyleLayer = (layer: StyleLayer): layer is HillshadeStyleLayer => layer.type === 'hillshade';\n\nexport class HillshadeStyleLayer extends StyleLayer {\n    _transitionablePaint: Transitionable<HillshadePaintProps>;\n    _transitioningPaint: Transitioning<HillshadePaintProps>;\n    paint: PossiblyEvaluated<HillshadePaintProps, HillshadePaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n        this.recalculate({zoom: 0, zoomHistory: {}} as EvaluationParameters, undefined);\n    }\n\n    getIlluminationProperties(): {directionRadians: number[]; altitudeRadians: number[]; shadowColor: Color[]; highlightColor: Color[]} {\n        let direction = this.paint.get('hillshade-illumination-direction').values;\n        let altitude = this.paint.get('hillshade-illumination-altitude').values;\n        let highlightColor = this.paint.get('hillshade-highlight-color').values;\n        let shadowColor = this.paint.get('hillshade-shadow-color').values;\n\n        // ensure all illumination properties have the same length\n        const numIlluminationSources = Math.max(direction.length, altitude.length, highlightColor.length, shadowColor.length);\n        direction = direction.concat(Array(numIlluminationSources - direction.length).fill(direction.at(-1)));\n        altitude = altitude.concat(Array(numIlluminationSources - altitude.length).fill(altitude.at(-1)));\n        highlightColor = highlightColor.concat(Array(numIlluminationSources - highlightColor.length).fill(highlightColor.at(-1)));\n        shadowColor = shadowColor.concat(Array(numIlluminationSources - shadowColor.length).fill(shadowColor.at(-1)));\n\n        const altitudeRadians = altitude.map(degreesToRadians);\n        const directionRadians = direction.map(degreesToRadians);\n\n        return {directionRadians, altitudeRadians, shadowColor, highlightColor};\n    }\n\n    hasOffscreenPass(): boolean {\n        return this.paint.get('hillshade-exaggeration') !== 0 && !this.isHidden();\n    }\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type ColorReliefPaintProps = {\n    \"color-relief-opacity\": DataConstantProperty<number>,\n    \"color-relief-color\": ColorRampProperty,\n    \"resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n};\n\nexport type ColorReliefPaintPropsPossiblyEvaluated = {\n    \"color-relief-opacity\": number,\n    \"color-relief-color\": ColorRampProperty,\n    \"resampling\": \"linear\" | \"nearest\",\n};\n\nlet paint: Properties<ColorReliefPaintProps>;\nconst getPaint = (): Properties<ColorReliefPaintProps> => paint = paint || new Properties({\n    \"color-relief-opacity\": new DataConstantProperty(styleSpec[\"paint_color-relief\"][\"color-relief-opacity\"] as any as StylePropertySpecification, \"color-relief-opacity\"),\n    \"color-relief-color\": new ColorRampProperty(styleSpec[\"paint_color-relief\"][\"color-relief-color\"] as any as StylePropertySpecification, \"color-relief-color\"),\n    \"resampling\": new DataConstantProperty(styleSpec[\"paint_color-relief\"][\"resampling\"] as any as StylePropertySpecification, \"resampling\"),\n});\n\nexport default ({ get paint(): Properties<ColorReliefPaintProps> { return getPaint() } });", "import {premultiplyAlpha} from '../util/image.ts';\n\nimport type {Context} from './context.ts';\nimport type {RGBAImage, AlphaImage} from '../util/image.ts';\n\nexport type TextureFormat = WebGLRenderingContextBase['RGBA'] | WebGLRenderingContextBase['ALPHA'];\nexport type TextureFilter = WebGLRenderingContextBase['LINEAR'] | WebGLRenderingContextBase['LINEAR_MIPMAP_NEAREST'] | WebGLRenderingContextBase['LINEAR_MIPMAP_LINEAR'] | WebGLRenderingContextBase['NEAREST'];\nexport type TextureWrap = WebGLRenderingContextBase['REPEAT'] | WebGLRenderingContextBase['CLAMP_TO_EDGE'] | WebGLRenderingContextBase['MIRRORED_REPEAT'];\n\ntype EmptyImage = {\n    width: number;\n    height: number;\n    data: null;\n};\n\ntype DataTextureImage = RGBAImage | AlphaImage | EmptyImage;\nexport type TextureImage = TexImageSource | DataTextureImage;\n\nfunction hasDataProperty(image: TextureImage): image is DataTextureImage {\n    return 'data' in image;\n}\n\n/**\n * @internal\n * A `Texture` GL related object\n */\nexport class Texture {\n    context: Context;\n    size: [number, number];\n    texture: WebGLTexture;\n    format: TextureFormat;\n    magFilter: TextureFilter;\n    minFilter: TextureFilter;\n    wrap: TextureWrap;\n    useMipmap: boolean;\n\n    /** Tracks the original handle to detect corruption after context loss (#2811) */\n    private _ownedHandle: WebGLTexture;\n\n    constructor(context: Context, image: TextureImage, format: TextureFormat, options?: {\n        premultiply?: boolean;\n        useMipmap?: boolean;\n    } | null) {\n        this.context = context;\n        this.format = format;\n        this.texture = context.gl.createTexture();\n        this._ownedHandle = this.texture;\n        this.update(image, options);\n    }\n\n    update(image: TextureImage, options?: {\n        premultiply?: boolean;\n        useMipmap?: boolean;\n    } | null, position?: {\n        x: number;\n        y: number;\n    }): void {\n        const {width, height} = image as {width: number; height: number};\n        const resize = (this.size?.[0] !== width || this.size[1] !== height) && !position;\n        const {context} = this;\n        const {gl} = context;\n\n        this.useMipmap = Boolean(options?.useMipmap);\n\n        if (resize && this.size && this.format === gl.RGBA) {\n            gl.deleteTexture(this.texture);\n            this.texture = gl.createTexture();\n            this._ownedHandle = this.texture;\n            // A fresh handle is back on GL's defaults, so bind() has to re-apply these.\n            this.magFilter = undefined;\n            this.minFilter = undefined;\n            this.wrap = undefined;\n        }\n\n        gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n        context.pixelStoreUnpackFlipY.set(false);\n        context.pixelStoreUnpack.set(1);\n\n        const wantPremultiply = this.format === gl.RGBA && (options?.premultiply !== false);\n\n        if (resize) {\n            this.size = [width, height];\n\n            if (this.format === gl.RGBA && width > 0 && height > 0) {\n                const mipLevels = this.useMipmap ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1;\n                gl.texStorage2D(gl.TEXTURE_2D, mipLevels, gl.RGBA8, width, height);\n\n                if (hasDataProperty(image)) {\n                    // #2030: raw data is premultiplied in JS\n                    context.pixelStoreUnpackPremultiplyAlpha.set(false);\n                    let {data} = image;\n                    if (wantPremultiply && data) data = premultiplyAlpha(data);\n                    if (data) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);\n                } else {\n                    context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply);\n                    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, image);\n                }\n            } else {\n                if (hasDataProperty(image)) {\n                    // #2030: raw data is premultiplied in JS\n                    context.pixelStoreUnpackPremultiplyAlpha.set(false);\n                    this._uploadRawData(image, wantPremultiply, width, height, gl);\n                } else {\n                    context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply);\n                    this._uploadDomImage(image, gl);\n                }\n            }\n        } else {\n            const {x, y} = position || {x: 0, y: 0};\n            if (hasDataProperty(image)) {\n                context.pixelStoreUnpackPremultiplyAlpha.set(false);\n                this._updateRawData(image, wantPremultiply, x, y, width, height, gl);\n            } else {\n                context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply);\n                this._updateDomImage(image, x, y, gl);\n            }\n        }\n\n        if (this.useMipmap && !(hasDataProperty(image) && image.data === null)) {\n            gl.generateMipmap(gl.TEXTURE_2D);\n        }\n\n        context.pixelStoreUnpackFlipY.setDefault();\n        context.pixelStoreUnpack.setDefault();\n        context.pixelStoreUnpackPremultiplyAlpha.setDefault();\n    }\n\n    private _uploadDomImage(image: TexImageSource, gl: WebGL2RenderingContext) {\n        gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image);\n    }\n\n    private _uploadRawData(image: DataTextureImage, wantPremultiply: boolean, width: number, height: number, gl: WebGL2RenderingContext) {\n        let {data} = image;\n        if (wantPremultiply && data) data = premultiplyAlpha(data);\n        gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, data);\n    }\n\n    private _updateDomImage(image: TexImageSource, x: number, y: number, gl: WebGL2RenderingContext) {\n        gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image);\n    }\n\n    private _updateRawData(image: DataTextureImage, wantPremultiply: boolean, x: number, y: number, width: number, height: number, gl: WebGL2RenderingContext) {\n        let {data} = image;\n        if (wantPremultiply && data) data = premultiplyAlpha(data);\n        gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);\n    }\n\n    bind(magFilter: TextureFilter, wrap: TextureWrap, minFilter?: TextureFilter | null): void {\n        const {context} = this;\n        const {gl} = context;\n\n        if (this.texture !== this._ownedHandle) {\n            this.texture = this._ownedHandle;\n        }\n\n        gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n        if ((minFilter === gl.LINEAR_MIPMAP_NEAREST || minFilter === gl.LINEAR_MIPMAP_LINEAR) && !this.useMipmap) {\n            minFilter = gl.LINEAR;\n        }\n        const effectiveMinFilter = minFilter || magFilter;\n\n        if (magFilter !== this.magFilter) {\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);\n            this.magFilter = magFilter;\n        }\n\n        if (effectiveMinFilter !== this.minFilter) {\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, effectiveMinFilter);\n            this.minFilter = effectiveMinFilter;\n        }\n\n        if (wrap !== this.wrap) {\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);\n            this.wrap = wrap;\n        }\n    }\n\n    /**\n     * Builds the mip chain after the texture was drawn into as a framebuffer attachment.\n     * An allocation without pixels (`data: null`) gets no chain from `update`, so a render target is built once, here, after the draw.\n     */\n    generateMipmap(): void {\n        if (!this.useMipmap) return;\n        const {gl} = this.context;\n        gl.bindTexture(gl.TEXTURE_2D, this.texture);\n        gl.generateMipmap(gl.TEXTURE_2D);\n    }\n\n    destroy(): void {\n        const {gl} = this.context;\n        gl.deleteTexture(this.texture);\n        this.texture = null;\n        this._ownedHandle = null;\n    }\n}\n", "import {RGBAImage} from '../util/image.ts';\nimport {warnOnce} from '../util/util.ts';\nimport {register} from '../util/web_worker_transfer.ts';\n\n/**\n * The possible DEM encoding types\n */\nexport type DEMEncoding = 'mapbox' | 'terrarium' | 'custom';\n\n/**\n * DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders\n * data can be populated either from a png raw image tile or from serialized data sent back from a worker. When data is initially\n * loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the\n * elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of\n * integer overflow when creating the texture used in the hillshadePrepare step.\n *\n * DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8\n * surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a\n * tile's edge without backfilling from neighboring tiles.\n */\nexport class DEMData {\n    private static readonly byteViewCache = new WeakMap<DEMData, Uint8Array>();\n\n    uid: string | number;\n    data: Uint32Array;\n    stride: number;\n    dim: number;\n    min: number;\n    max: number;\n    redFactor: number;\n    greenFactor: number;\n    blueFactor: number;\n    baseShift: number;\n\n    /**\n     * Constructs a `DEMData` object\n     * @param uid - the tile's unique id\n     * @param data - RGBAImage data has uniform 2px padding on all sides: square tile edge size defines stride\n    // and dim is calculated as stride - 4.\n     * @param encoding - the encoding type of the data\n     * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only\n     * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only\n     * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only\n     * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only\n     */\n    constructor(uid: string | number, data: RGBAImage | ImageData, encoding: DEMEncoding, redFactor = 1.0, greenFactor = 1.0, blueFactor = 1.0, baseShift = 0.0) {\n        this.uid = uid;\n        if (data.height !== data.width) throw new RangeError('DEM tiles must be square');\n        if (encoding && !['mapbox', 'terrarium', 'custom'].includes(encoding)) {\n            warnOnce(`\"${encoding}\" is not a valid encoding type. Valid types include \"mapbox\", \"terrarium\" and \"custom\".`);\n            return;\n        }\n        this.stride = data.height;\n        const dim = this.dim = data.height - 4;\n        this.data = new Uint32Array(data.data.buffer);\n        DEMData.byteViewCache.set(this, new Uint8Array(this.data.buffer));\n        switch (encoding) {\n            case 'terrarium':\n                // unpacking formula for mapzen terrarium:\n                // https://aws.amazon.com/public-datasets/terrain/\n                this.redFactor = 256.0;\n                this.greenFactor = 1.0;\n                this.blueFactor = 1.0 / 256.0;\n                this.baseShift = 32768.0;\n                break;\n            case 'custom':\n                this.redFactor = redFactor;\n                this.greenFactor = greenFactor;\n                this.blueFactor = blueFactor;\n                this.baseShift = baseShift;\n                break;\n            case 'mapbox':\n            default:\n                // unpacking formula for mapbox.terrain-rgb:\n                // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb\n                this.redFactor = 6553.6;\n                this.greenFactor = 25.6;\n                this.blueFactor = 0.1;\n                this.baseShift = 10000.0;\n                break;\n        }\n\n        // in order to avoid flashing seams between tiles, here we are initially populating a 2px border of pixels around the image\n        // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring\n        // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder\n        for (let y = -2; y < dim + 2; y++) {\n            const offset = this._idx(0, Math.max(0, Math.min(dim - 1, y)));\n            if (y < 0 || y >= dim) this.data.copyWithin(this._idx(0, y), offset, offset + dim);\n            this.data.fill(this.data[offset], this._idx(-2, y), this._idx(0, y));\n            this.data.fill(this.data[offset + dim - 1], this._idx(dim, y), this._idx(dim + 1, y) + 1);\n        }\n\n        // calculate min/max values\n        const pixels = this._getByteView();\n        this.min = Number.MAX_SAFE_INTEGER;\n        this.max = Number.MIN_SAFE_INTEGER;\n        for (let x = 0; x < dim; x++) {\n            for (let y = 0; y < dim; y++) {\n                const index = this._idx(x, y) * 4;\n                const ele = this._unpackAtIndex(pixels, index);\n                if (ele > this.max) this.max = ele;\n                if (ele < this.min) this.min = ele;\n            }\n        }\n    }\n\n    get(x: number, y: number): number {\n        const pixels = this._getByteView();\n        const index = this._idx(x, y) * 4;\n        return this._unpackAtIndex(pixels, index);\n    }\n\n    sampleBilinear(x: number, y: number): number {\n        const cx = Math.floor(x);\n        const cy = Math.floor(y);\n        if (cx < -1 || cx >= this.dim || cy < -1 || cy >= this.dim) throw new RangeError(`Out of range source coordinates for DEM data. x: ${x}, y: ${y}, dim: ${this.dim}`);\n\n        const pixels = this._getByteView();\n        const index = ((cy + 2) * this.stride + cx + 2) * 4;\n        const strideByteWidth = this.stride * 4;\n        const tx = x - cx;\n        const ty = y - cy;\n        const z00 = this._unpackAtIndex(pixels, index);\n        const z10 = this._unpackAtIndex(pixels, index + 4);\n        const z01 = this._unpackAtIndex(pixels, index + strideByteWidth);\n        const z11 = this._unpackAtIndex(pixels, index + strideByteWidth + 4);\n\n        return (\n            z00 * (1 - tx) * (1 - ty) +\n            z10 * tx * (1 - ty) +\n            z01 * (1 - tx) * ty +\n            z11 * tx * ty\n        );\n    }\n\n    getUnpackVector(): number[] {\n        return [this.redFactor, this.greenFactor, this.blueFactor, this.baseShift];\n    }\n\n    _idx(x: number, y: number): number {\n        if (x < -2 || x >= this.dim + 2 ||  y < -2 || y >= this.dim + 2) throw new RangeError(`Out of range source coordinates for DEM data. x: ${x}, y: ${y}, dim: ${this.dim}`);\n        return (y + 2) * this.stride + (x + 2);\n    }\n\n    unpack(r: number, g: number, b: number): number {\n        return (r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift);\n    }\n\n    pack(v: number): {r: number; g: number; b: number} {\n        return packDEMData(v, this.getUnpackVector());\n    }\n\n    getPixels(): RGBAImage {\n        return new RGBAImage({width: this.stride, height: this.stride}, this._getByteView());\n    }\n\n    backfillBorder(borderTile: DEMData, dx: number, dy: number): void {\n        if (this.dim !== borderTile.dim) throw new Error('dem dimension mismatch');\n\n        let xMin = dx * this.dim,\n            xMax = dx * this.dim + this.dim,\n            yMin = dy * this.dim,\n            yMax = dy * this.dim + this.dim;\n\n        switch (dx) {\n            case -1:\n                xMin = xMax - 2;\n                break;\n            case 1:\n                xMax = xMin + 2;\n                break;\n        }\n\n        switch (dy) {\n            case -1:\n                yMin = yMax - 2;\n                break;\n            case 1:\n                yMax = yMin + 2;\n                break;\n        }\n\n        const ox = -dx * this.dim;\n        const oy = -dy * this.dim;\n        for (let y = yMin; y < yMax; y++) {\n            for (let x = xMin; x < xMax; x++) {\n                this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)];\n            }\n        }\n    }\n\n    private _getByteView(): Uint8Array {\n        let byteView = DEMData.byteViewCache.get(this);\n        if (byteView?.buffer !== this.data.buffer) {\n            byteView = new Uint8Array(this.data.buffer);\n            DEMData.byteViewCache.set(this, byteView);\n        }\n        return byteView;\n    }\n\n    private _unpackAtIndex(pixels: Uint8Array, index: number): number {\n        return this.unpack(pixels[index], pixels[index + 1], pixels[index + 2]);\n    }\n}\n\n/**\n * Packs an elevation into the RGB channels that {@link DEMData.unpack} decodes with the given\n * unpack vector `[redFactor, greenFactor, blueFactor, baseShift]`.\n *\n * A channel whose factor is 0 contributes nothing to the decoded elevation, so it packs to 0 and\n * takes no part in the scale the other channels are quantized by. When all three factors are 0\n * every color decodes to `-baseShift`, and the packed color is black.\n */\nexport function packDEMData(v: number, unpackVector: number[]): {r: number; g: number; b: number} {\n    const redFactor = unpackVector[0];\n    const greenFactor = unpackVector[1];\n    const blueFactor = unpackVector[2];\n    const baseShift = unpackVector[3];\n    const factors = [redFactor, greenFactor, blueFactor].filter(factor => factor !== 0);\n    if (factors.length === 0) {\n        return {r: 0, g: 0, b: 0};\n    }\n    const minScale = Math.min(...factors);\n    const vScaled = Math.round((v + baseShift)/minScale);\n    const packChannel = (factor: number) => factor === 0 ? 0 : Math.floor(vScaled*minScale/factor) % 256;\n    return {\n        r: packChannel(redFactor),\n        g: packChannel(greenFactor),\n        b: packChannel(blueFactor)\n    };\n}\n\nregister('DEMData', DEMData);\n", "import {StyleLayer} from '../style_layer.ts';\nimport properties, {type ColorReliefPaintPropsPossiblyEvaluated} from './color_relief_style_layer_properties.g.ts';\nimport {Color, Interpolate, ZoomConstantExpression, type LayerSpecification, type EvaluationContext, type StylePropertyExpression} from '@maplibre/maplibre-gl-style-spec';\nimport {warnOnce} from '../../util/util.ts';\nimport {Texture} from '../../webgl/texture.ts';\nimport {RGBAImage} from '../../util/image.ts';\nimport {packDEMData} from '../../data/dem_data.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.ts';\nimport type {ColorReliefPaintProps} from './color_relief_style_layer_properties.g.ts';\n\nexport const isColorReliefStyleLayer = (layer: StyleLayer): layer is ColorReliefStyleLayer => layer.type === 'color-relief';\n\nexport type ColorRamp = {elevationStops: number[]; colorStops: Color[]};\nexport type ColorRampTextures = {elevationTexture: Texture; colorTexture: Texture};\n\nexport class ColorReliefStyleLayer extends StyleLayer {\n    colorRampExpression: StylePropertyExpression;\n    colorRampTextures: ColorRampTextures;\n    _transitionablePaint: Transitionable<ColorReliefPaintProps>;\n    _transitioningPaint: Transitioning<ColorReliefPaintProps>;\n    paint: PossiblyEvaluated<ColorReliefPaintProps, ColorReliefPaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n    }\n\n    /**\n     * Create the color ramp, enforcing a maximum length for the vectors. This modifies the internal color ramp,\n     * so that the remapping is only performed once.\n     *\n     * @param maxLength - the maximum number of stops in the color ramp\n     *\n     * @return a `ColorRamp` object with no more than `maxLength` stops.\n     *\n     */\n\n    _createColorRamp(maxLength: number) : ColorRamp {\n        const colorRamp: ColorRamp = {elevationStops: [], colorStops: []};\n        const expression = this._transitionablePaint._values['color-relief-color'].value.expression;\n        if (expression instanceof ZoomConstantExpression && expression._styleExpression.expression instanceof Interpolate) {\n            this.colorRampExpression = expression;\n            const interpolater = expression._styleExpression.expression;\n            colorRamp.elevationStops = interpolater.labels;\n            colorRamp.colorStops = [];\n            for (const label of colorRamp.elevationStops) {\n                colorRamp.colorStops.push(interpolater.evaluate({globals: {elevation: label}} as EvaluationContext));\n            }\n        }\n        if (colorRamp.elevationStops.length < 1)\n        {\n            colorRamp.elevationStops = [0];\n            colorRamp.colorStops = [Color.transparent];\n        }\n        if (colorRamp.elevationStops.length < 2)\n        {\n            colorRamp.elevationStops.push(colorRamp.elevationStops[0] + 1);\n            colorRamp.colorStops.push(colorRamp.colorStops[0]);\n        }\n        if (colorRamp.elevationStops.length <= maxLength) {\n            return colorRamp;\n        }\n\n        const remappedColorRamp: ColorRamp = {elevationStops: [], colorStops: []};\n        const remapStepSize = (colorRamp.elevationStops.length - 1)/(maxLength - 1);\n\n        for (let i = 0; i < colorRamp.elevationStops.length - 0.5; i += remapStepSize) {\n            remappedColorRamp.elevationStops.push(colorRamp.elevationStops[Math.round(i)]);\n            remappedColorRamp.colorStops.push(colorRamp.colorStops[Math.round(i)]);\n        }\n        warnOnce(`Too many colors in specification of ${this.id} color-relief layer, may not render properly. Max possible colors: ${maxLength}, provided: ${colorRamp.elevationStops.length}`);\n        return remappedColorRamp;\n    }\n\n    _colorRampChanged() : boolean {\n        return this.colorRampExpression != this._transitionablePaint._values['color-relief-color'].value.expression;\n    }\n\n    getColorRampTextures(context: Context, maxLength: number, unpackVector: number[]): ColorRampTextures {\n        if (this.colorRampTextures && !this._colorRampChanged()) {\n            return this.colorRampTextures;\n        }\n        const colorRamp = this._createColorRamp(maxLength);\n        const colorImage = new RGBAImage({width: colorRamp.colorStops.length, height: 1});\n        const elevationImage = new RGBAImage({width: colorRamp.colorStops.length, height: 1});\n        for (let i = 0; i < colorRamp.elevationStops.length; i++) {\n            const elevationPacked = packDEMData(colorRamp.elevationStops[i], unpackVector);\n            elevationImage.setPixel(0, i, new Color(elevationPacked.r/255, elevationPacked.g/255, elevationPacked.b/255, 1));\n            colorImage.setPixel(0, i, colorRamp.colorStops[i]);\n        }\n        this.colorRampTextures = {\n            elevationTexture: new Texture(context, elevationImage, context.gl.RGBA),\n            colorTexture: new Texture(context, colorImage, context.gl.RGBA)\n        };\n        return this.colorRampTextures;\n    }\n\n    hasOffscreenPass(): boolean {\n        return !this.isHidden() && !!this.colorRampTextures;\n    }\n}\n", "import {createLayout, type StructArrayLayout, type StructArrayMember} from '../../util/struct_array.ts';\n\nconst layout: StructArrayLayout = createLayout([\n    {name: 'a_pos', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const members: StructArrayMember[] = layout.members;\nexport const size: number = layout.size;\nexport const alignment: number = layout.alignment;\n", "import type {PossiblyEvaluated} from '../../style/properties.ts';\nimport type {FillStyleLayer} from '../../style/style_layer/fill_style_layer.ts';\nimport type {FillExtrusionStyleLayer} from '../../style/style_layer/fill_extrusion_style_layer.ts';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer.ts';\nimport type {\n    BucketFeature,\n    PopulateParameters\n} from '../bucket.ts';\n\ntype PatternStyleLayers = LineStyleLayer[] | FillStyleLayer[] | FillExtrusionStyleLayer[];\n\nexport function hasPattern(type: string, layers: PatternStyleLayers, options: PopulateParameters): boolean {\n    const patterns = options.patternDependencies;\n    let hasPattern = false;\n\n    for (const layer of layers) {\n        const patternProperty = (layer.paint as PossiblyEvaluated<any, any>).get(`${type}-pattern`);\n        if (!patternProperty.isConstant()) {\n            hasPattern = true;\n        }\n\n        const constantPattern = patternProperty.constantOr(null);\n        if (constantPattern) {\n            hasPattern = true;\n            patterns[constantPattern.to] =  true;\n            patterns[constantPattern.from] =  true;\n        }\n    }\n\n    return hasPattern;\n}\n\nexport function addPatternDependencies(type: string, layers: PatternStyleLayers, patternFeature: BucketFeature, parameters: { zoom: number }, options: PopulateParameters): BucketFeature {\n    const {zoom} = parameters;\n    const patterns = options.patternDependencies;\n    for (const layer of layers) {\n        const patternProperty = (layer.paint  as PossiblyEvaluated<any, any>).get(`${type}-pattern`);\n\n        const patternPropertyValue = patternProperty.value;\n        if (patternPropertyValue.kind !== 'constant') {\n            let min = patternPropertyValue.evaluate({zoom: zoom - 1}, patternFeature, {}, options.availableImages);\n            let mid = patternPropertyValue.evaluate({zoom}, patternFeature, {}, options.availableImages);\n            let max = patternPropertyValue.evaluate({zoom: zoom + 1}, patternFeature, {}, options.availableImages);\n            min = min?.name ? min.name : min;\n            mid = mid?.name ? mid.name : mid;\n            max = max?.name ? max.name : max;\n            // add to patternDependencies\n            patterns[min] = true;\n            patterns[mid] = true;\n            patterns[max] = true;\n\n            // save for layout\n            patternFeature.patterns[layer.id] = {min, mid, max};\n        }\n    }\n    return patternFeature;\n}\n", "/**\n * A vertex in a circular doubly linked list representing a polygon ring.\n * `prev`/`next` are always linked (set immediately after {@link createNode}), so they're typed\n * non-null; `prevZ`/`nextZ` are the z-order list links and are null at the ends.\n *\n * @typedef {object} Node\n * @property {number} i vertex index in the coordinates array\n * @property {number} x vertex x coordinate\n * @property {number} y vertex y coordinate\n * @property {Node} prev previous vertex node in the polygon ring\n * @property {Node} next next vertex node in the polygon ring\n * @property {number} z z-order curve value; doubles as the owning block index during eliminateHoles\n * @property {Node | null} prevZ previous node in z-order\n * @property {Node | null} nextZ next node in z-order\n */\n\n// single-vertex holes to preserve through filterPoints (steiner points); kept off the Node\n// shape since they're rare — the empty-set fast path means non-steiner inputs pay nothing\n/** @type {Set<Node>} */\nconst steiners = new Set();\n\n// set by filterPoints whenever it removes at least one node; read by earcutLinked's stall\n// handler to decide whether another clip pass is worth attempting before the costlier stages\nlet filteredOut = false;\n\n/**\n * Triangulate a polygon given as a flat array of vertex coordinates.\n *\n * @param {ArrayLike<number>} data flat array of vertex coordinates\n * @param {ArrayLike<number> | null} [holeIndices] indices (in vertices, not coordinates) where each hole ring starts\n * @param {number} [dim=2] number of coordinates per vertex in `data`\n * @returns {number[]} triangles as triplets of vertex indices into `data`\n * @example earcut([10,0, 0,50, 60,60, 70,10]); // [1,0,3, 3,2,1]\n */\nexport default function earcut(data, holeIndices, dim = 2) {\n\n    const hasHoles = holeIndices && holeIndices.length;\n    const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n    if (steiners.size) steiners.clear();\n\n    let outerNode = linkedList(data, 0, outerLen, dim, true);\n    /** @type {number[]} */\n    const triangles = [];\n\n    if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n    let minX = 0, minY = 0, invSize = 0;\n\n    if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n    // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n    if (data.length > 80 * dim) {\n        minX = data[0];\n        minY = data[1];\n        let maxX = minX;\n        let maxY = minY;\n\n        for (let i = dim; i < outerLen; i += dim) {\n            const x = data[i];\n            const y = data[i + 1];\n            if (x < minX) minX = x;\n            if (y < minY) minY = y;\n            if (x > maxX) maxX = x;\n            if (y > maxY) maxY = y;\n        }\n\n        // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n        invSize = Math.max(maxX - minX, maxY - minY);\n        invSize = invSize !== 0 ? 32767 / invSize : 0;\n    }\n\n    earcutLinked(outerNode, triangles, minX, minY, invSize);\n\n    return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\n/** @param {ArrayLike<number>} data @param {number} start @param {number} end @param {number} dim @param {boolean} clockwise @returns {Node | null} */\nfunction linkedList(data, start, end, dim, clockwise) {\n    /** @type {Node | null} */\n    let last = null;\n\n    if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n        for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n    } else {\n        for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n    }\n\n    if (last && equals(last, last.next)) {\n        removeNode(last);\n        last = last.next;\n    }\n\n    return last;\n}\n\n// Remove collinear or coincident points; removability depends only on a node's immediate\n// neighbors, so we sweep forward and re-check the predecessor after each removal. With no `end`\n// we sweep the whole ring, lapping until nothing is removable (the fixpoint the clipper needs).\n// With an explicit `end` we heal only the dirty window around a bridge/diagonal cut, stopping at\n// `end` rather than lapping — O(window) instead of O(ring).\n/** @param {Node} start @param {Node} [end] @returns {Node} */\nfunction filterPoints(start, end = start) {\n    const full = end === start;\n\n    let p = start, again;\n    do {\n        again = false;\n        if (p !== p.next && (steiners.size === 0 || !steiners.has(p)) &&\n            (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n            if (full || p === end) end = p.prev; // pull the stop bound back past the removal\n            filteredOut = true;\n            removeNode(p);\n            p = p.prev;         // re-check the predecessor\n            again = true;\n        } else if (full || p !== end) {\n            p = p.next;\n            again = !full;      // local heal: keep looping until the sweep reaches end\n        }\n    } while (again || p !== end);\n\n    return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\n/** @param {Node} ear @param {number[]} triangles @param {number} minX @param {number} minY @param {number} invSize */\nfunction earcutLinked(ear, triangles, minX, minY, invSize) {\n    // interlink polygon nodes in z-order\n    if (invSize) indexCurve(ear, minX, minY, invSize);\n\n    let stop = ear, cured = false;\n\n    // iterate through ears, slicing them one by one\n    while (ear.prev !== ear.next) {\n        const prev = ear.prev;\n        /** @type {Node} */\n        const next = ear.next;\n\n        if (area(prev, ear, next) < 0 && (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear))) {\n            triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n            removeNode(ear);\n            ear = next;\n            stop = next;\n            continue;\n        }\n\n        ear = next;\n\n        // if we looped through the whole remaining polygon and can't find any more ears\n        if (ear === stop) {\n            // try filtering collinear/coincident points and slicing again — repeat as long as\n            // filtering actually removes nodes, since each removal can expose new ears\n            filteredOut = false;\n            ear = filterPoints(ear);\n            if (filteredOut) { stop = ear; continue; }\n\n            // filtering is exhausted: cure small local self-intersections once, then retry\n            if (!cured) {\n                ear = cureLocalIntersections(ear, triangles);\n                stop = ear;\n                cured = true;\n                continue;\n            }\n\n            // as a last resort, try splitting the remaining polygon into two\n            splitEarcut(ear, triangles, minX, minY, invSize);\n            break;\n        }\n    }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\n/** @param {Node} ear @returns {boolean} */\nfunction isEar(ear) {\n    // reflex check (area(a, b, c) >= 0) is hoisted into the earcutLinked caller to avoid non-inlined call here\n    const a = ear.prev, b = ear, c = ear.next,\n        ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y,\n        x0 = Math.min(ax, bx, cx), // triangle bbox\n        y0 = Math.min(ay, by, cy),\n        x1 = Math.max(ax, bx, cx),\n        y1 = Math.max(ay, by, cy);\n\n    // make sure we don't have other points inside the potential ear\n    let p = c.next;\n    while (p !== a) {\n        if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && !(ax === p.x && ay === p.y) &&\n            pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n        p = p.next;\n    }\n    return true;\n}\n\n/** @param {Node} ear @param {number} minX @param {number} minY @param {number} invSize @returns {boolean} */\nfunction isEarHashed(ear, minX, minY, invSize) {\n    // reflex check is hoisted into the earcutLinked caller (see isEar)\n    const a = ear.prev, b = ear, c = ear.next,\n        ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y,\n        x0 = Math.min(ax, bx, cx), // triangle bbox\n        y0 = Math.min(ay, by, cy),\n        x1 = Math.max(ax, bx, cx),\n        y1 = Math.max(ay, by, cy),\n        minZ = zOrder(x0, y0, minX, minY, invSize), // z-order range for the current triangle bbox;\n        maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n    let p = ear.prevZ;\n    while (p && p.z >= minZ) { // look for points inside the triangle in decreasing z-order\n        if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== c && !(ax === p.x && ay === p.y) &&\n            pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n        p = p.prevZ;\n    }\n    let n = ear.nextZ;\n    while (n && n.z <= maxZ) { // look for points in increasing z-order\n        if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== c && !(ax === n.x && ay === n.y) &&\n            pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n        n = n.nextZ;\n    }\n    return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\n/** @param {Node} start @param {number[]} triangles @returns {Node} */\nfunction cureLocalIntersections(start, triangles) {\n    let p = start;\n    let cured = false;\n    do {\n        const a = p.prev,\n            b = p.next.next;\n\n        if (intersects(a, p, p.next, b, false) && locallyInside(a, b) && locallyInside(b, a)) {\n\n            triangles.push(a.i, p.i, b.i);\n\n            // remove two nodes involved\n            removeNode(p);\n            removeNode(p.next);\n\n            p = start = b;\n            cured = true;\n        }\n        p = p.next;\n    } while (p !== start);\n\n    return cured ? filterPoints(p) : p;\n}\n\n// try splitting polygon into two and triangulate them independently\n/** @param {Node} start @param {number[]} triangles @param {number} minX @param {number} minY @param {number} invSize */\nfunction splitEarcut(start, triangles, minX, minY, invSize) {\n    // look for a valid diagonal that divides the polygon into two\n    let a = start;\n    do {\n        let b = a.next.next;\n        while (b !== a.prev) {\n            if (a.i !== b.i && isValidDiagonal(a, b)) {\n                // split the polygon in two by the diagonal\n                let c = splitPolygon(a, b);\n\n                // filter colinear points around the cuts\n                a = filterPoints(a, a.next);\n                c = filterPoints(c, c.next);\n\n                // run earcut on each half\n                earcutLinked(a, triangles, minX, minY, invSize);\n                earcutLinked(c, triangles, minX, minY, invSize);\n                return;\n            }\n            b = b.next;\n        }\n        a = a.next;\n    } while (a !== start);\n}\n\n// true only while eliminateHoles merges holes, so removeNode keeps the block index live (growBlock)\nlet indexActive = false;\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\n/** @param {ArrayLike<number>} data @param {ArrayLike<number>} holeIndices @param {Node} outerNode @param {number} dim @returns {Node} */\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n    const queue = [];\n\n    for (let i = 0, len = holeIndices.length; i < len; i++) {\n        const start = holeIndices[i] * dim;\n        const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n        const list = /** @type {Node} */ (linkedList(data, start, end, dim, false));\n        if (list === list.next) steiners.add(list);\n        queue.push(getLeftmost(list));\n    }\n\n    queue.sort(compareXYSlope);\n\n    // block-bbox index for findHoleBridge, grown append-only as holes merge (see notes\n    // above buildBlockIndex). Seed it with the outer ring, then append each merged hole.\n    buildBlockIndex(data.length / dim, holeIndices.length);\n    indexSegment(outerNode, outerNode);\n\n    // process holes from left to right; indexActive lets removeNode keep block bboxes live as\n    // filterPoints heals edges during merges (see growBlock)\n    indexActive = true;\n    for (let i = 0; i < queue.length; i++) {\n        outerNode = eliminateHole(queue[i], outerNode);\n    }\n    indexActive = false;\n\n    // collapse collinear/coincident points across the whole merged ring once before clipping\n    return filterPoints(outerNode);\n}\n\n/** @param {Node} a @param {Node} b @returns {number} */\nfunction compareXYSlope(a, b) {\n    // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n    // the bridge to the outer shell is always the point that they meet at.\n    return a.x - b.x || a.y - b.y ||\n        (a.next.y - a.y) / (a.next.x - a.x) -\n        (b.next.y - b.y) / (b.next.x - b.x);\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\n/** @param {Node} hole @param {Node} outerNode @returns {Node} */\nfunction eliminateHole(hole, outerNode) {\n    const bridge = findHoleBridge(hole, outerNode);\n    if (!bridge) {\n        return outerNode;\n    }\n\n    const bridgeReverse = splitPolygon(bridge, hole);\n\n    // index the merged-in segment before filtering: in ring order the splice runs\n    // bridge -> hole -> bridgeReverse -> bridge2 -> (bridge's old next), covering the\n    // hole's edges and both new slit edges. filterPoints below only drops collinear /\n    // coincident points, so these bboxes stay valid (conservative) supersets.\n    const bridge2 = bridgeReverse.next;\n    indexSegment(bridge, bridge2.next);\n\n    // heal collinear/coincident points around the two new slit edges\n    filterPoints(bridgeReverse, bridgeReverse.next);\n    return filterPoints(bridge, bridge.next);\n}\n\n// Block-bbox index for findHoleBridge (issue #183): one [minX,minY,maxX,maxY] bbox per K\n// consecutive ring edges, in a flat Float64Array, so the leftward-ray scan can skip whole\n// blocks in O(1) instead of walking the entire merged ring. Grown append-only — the outer\n// ring seeds it, then each merged hole appends a segment (head node, stop node, K-blocks\n// over head..stop); independent segments, not a ring tiling, since splices land mid-ring.\n// Buffers are sized once from the input upper bound and reused across calls.\n//\n// filterPoints only drops collinear/coincident points, so a stale bbox stays a conservative\n// superset of its live edges (never a false skip); the scan skips dead nodes (p.prev.next !==\n// p) and lazily advances a dead stop. Blocks are scanned in append (not ring) order, so the\n// chosen bridge can differ from the un-indexed code — a different but equally valid result.\nconst K = 16; // edges per block\n\nlet blockBBox = new Float64Array(0); // [minX,minY,maxX,maxY] per block\nlet numBlocks = 0;\n/** @type {Node[]} */\nconst blockHead = []; // first node of each block's segment\n/** @type {Node[]} */\nconst blockStop = []; // node just past each block's segment (exclusive walk bound)\n\n/** @param {number} maxNodes @param {number} numHoles */\nfunction buildBlockIndex(maxNodes, numHoles) {\n    // upper bound: every input node indexed once, +2 bridge nodes per hole, plus a partial\n    // trailing block per appended segment (outer ring + one per hole)\n    const maxBlocks = Math.ceil((maxNodes + 2 * numHoles) / K) + numHoles + 2;\n    if (blockBBox.length < maxBlocks * 4) blockBBox = new Float64Array(maxBlocks * 4);\n    numBlocks = 0;\n}\n\n// index the ring run head..stop (exclusive) as ceil(len / K) blocks; head === stop means\n// the whole ring. each block's bbox covers both endpoints of every edge it owns.\n/** @param {Node} head @param {Node} stop */\nfunction indexSegment(head, stop) {\n    let p = head;\n    do {\n        const b = numBlocks++;\n        blockHead[b] = p;\n        let minX = p.x, minY = p.y, maxX = p.x, maxY = p.y;\n        let k = 0;\n        do {\n            const c = p.next; // edge p->c; bbox must bound both endpoints\n            p.z = b; // reuse z as the owning block during eliminateHoles (see growBlock)\n            if (c.x < minX) minX = c.x; if (c.x > maxX) maxX = c.x;\n            if (c.y < minY) minY = c.y; if (c.y > maxY) maxY = c.y;\n            p = c;\n        } while (++k < K && p !== stop);\n        blockStop[b] = p;\n        const g = b * 4;\n        blockBBox[g] = minX; blockBBox[g + 1] = minY; blockBBox[g + 2] = maxX; blockBBox[g + 3] = maxY;\n    } while (p !== stop);\n}\n\n// when filterPoints heals an edge head->tail (removing the collinear node between them), the\n// healed edge can extend past head's frozen block bbox if its old far endpoint lived in another\n// block; grow head's block bbox to cover tail so the leftward-ray prune can't false-skip it.\n/** @param {Node} head @param {Node} tail */\nfunction growBlock(head, tail) {\n    const g = head.z * 4;\n    if (tail.x < blockBBox[g]) blockBBox[g] = tail.x;\n    if (tail.y < blockBBox[g + 1]) blockBBox[g + 1] = tail.y;\n    if (tail.x > blockBBox[g + 2]) blockBBox[g + 2] = tail.x;\n    if (tail.y > blockBBox[g + 3]) blockBBox[g + 3] = tail.y;\n}\n\n/** @param {number} b @returns {Node} */\nfunction liveBlockStop(b) {\n    let stop = blockStop[b];\n    while (stop.prev.next !== stop) stop = stop.next;\n    blockStop[b] = stop;\n    return stop;\n}\n\n// the block's head node can be removed by filterPoints during merges; advance it to the next\n// live node so the walk doesn't start on (and immediately terminate at) a dead node. For the\n// single full-ring seed block (head === stop) the same forward advance keeps them equal, so the\n// do-while still laps the whole ring instead of collapsing to an empty walk.\n/** @param {number} b @returns {Node} */\nfunction liveBlockHead(b) {\n    let head = blockHead[b];\n    while (head.prev.next !== head) head = head.next;\n    blockHead[b] = head;\n    return head;\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\n/** @param {Node} hole @param {Node} outerNode @returns {Node | null} */\nfunction findHoleBridge(hole, outerNode) {\n    let p = outerNode;\n    const hx = hole.x;\n    const hy = hole.y;\n    let qx = -Infinity;\n    /** @type {Node | undefined} */\n    let m;\n\n    // find a segment intersected by a ray from the hole's leftmost point to the left;\n    // segment's endpoint with lesser x will be potential connection point\n    // unless they intersect at a vertex, then choose the vertex\n    if (equals(hole, p)) return p;\n\n    // scan blocks; skip any whose bbox can't hold a crossing that beats qx and lies left\n    // of hx (the prune Morton order can't express — explicit per-axis [minY,maxY]/[minX,maxX])\n    for (let b = 0, g = 0; b < numBlocks; b++, g += 4) {\n        if (hy < blockBBox[g + 1] || hy > blockBBox[g + 3] || blockBBox[g] > hx || blockBBox[g + 2] <= qx) continue;\n\n        // ensure the walk's exclusive bound is live so we don't overrun into other blocks\n        const stop = liveBlockStop(b);\n\n        p = liveBlockHead(b);\n        do {\n            if (p.prev.next === p) { // skip nodes removed by filterPoints (stale in the index)\n                if (equals(hole, p.next)) return p.next;\n                else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n                    const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n                    if (x <= hx && x > qx) {\n                        qx = x;\n                        m = p.x < p.next.x ? p : p.next;\n                        if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n                    }\n                }\n            }\n            p = p.next;\n        } while (p !== stop);\n    }\n\n    if (!m) return null;\n\n    // look for points inside the triangle of hole point, segment intersection and endpoint;\n    // if there are no points found, we have a valid connection;\n    // otherwise choose the point of the minimum angle with the ray as connection point\n\n    const mx = m.x;\n    const my = m.y;\n    const tminY = Math.min(hy, my); // the triangle's y span; x span is [mx, hx]\n    const tmaxY = Math.max(hy, my);\n    let tanMin = Infinity;\n\n    // scan the same blocks; skip any whose bbox can't overlap the triangle's [mx,hx]×[tminY,tmaxY] box\n    for (let b = 0, g = 0; b < numBlocks; b++, g += 4) {\n        if (blockBBox[g + 2] < mx || blockBBox[g] > hx || blockBBox[g + 3] < tminY || blockBBox[g + 1] > tmaxY) continue;\n\n        const stop = liveBlockStop(b);\n\n        p = liveBlockHead(b);\n        do {\n            if (p.prev.next === p && hx >= p.x && p.x >= mx && hx !== p.x && // skip dead nodes\n                    pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n                const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n                // if hole point sits on p's horizontal edge (T-junction touch): the bridge runs\n                // along that edge — locallyInside rejects it as collinear, but it's valid\n                if ((locallyInside(p, hole) || (p.y === hy && p.next.y === hy && p.next.x > hx)) &&\n                    (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n                    m = p;\n                    tanMin = tan;\n                }\n            }\n\n            p = p.next;\n        } while (p !== stop);\n    }\n\n    return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\n/** @param {Node} m @param {Node} p @returns {boolean} */\nfunction sectorContainsSector(m, p) {\n    return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// scratch buffers reused across calls and grown on demand: two node-ref arrays that\n// ping-pong during the radix passes, plus parallel z-value arrays so the passes read\n// z from contiguous memory instead of dereferencing each node. 256-entry histogram for\n// 8-bit digits; the small histogram keeps per-call setup cheap (most rings are short)\n/** @type {Node[]} */\nconst sortArr = [];\n/** @type {Node[]} */\nlet sortBuf = [];\nlet zArr = new Uint32Array(0);\nlet zBuf = new Uint32Array(0);\nconst counts = new Uint32Array(256);\n\n// interlink polygon nodes in z-order: collect into an array, sort by z, relink\n/** @param {Node} start @param {number} minX @param {number} minY @param {number} invSize */\nfunction indexCurve(start, minX, minY, invSize) {\n    let p = start;\n    let n = 0;\n    do {\n        // always (re)compute: z may still hold a block index left over from eliminateHoles\n        p.z = zOrder(p.x, p.y, minX, minY, invSize);\n        sortArr[n++] = p;\n        p = p.next;\n    } while (p !== start);\n\n    sortNodes(n);\n\n    /** @type {Node | null} */\n    let prev = null;\n    for (let i = 0; i < n; i++) {\n        const node = sortArr[i];\n        node.prevZ = prev;\n        if (prev) prev.nextZ = node;\n        prev = node;\n    }\n    /** @type {Node} */ (prev).nextZ = null;\n\n    // drop the node refs but keep the capacity: setting length to 0 leaves sortBuf unresized\n    // (its growth is gated on zArr), so the radix scatter regrows it out of order every call\n    sortArr.fill(/** @type {Node} */ (/** @type {unknown} */ (null)), 0, n);\n    sortBuf.fill(/** @type {Node} */ (/** @type {unknown} */ (null)), 0, n);\n}\n\n// sort the first n nodes of sortArr by z, in place: insertion sort for small n (cheaper\n// than histogram setup), else LSD radix in four 8-bit passes (covering z's 30 bits)\n/** @param {number} n */\nfunction sortNodes(n) {\n    if (n <= 32) {\n        for (let i = 1; i < n; i++) {\n            const node = sortArr[i], z = node.z;\n            let j = i - 1;\n            while (j >= 0 && sortArr[j].z > z) { sortArr[j + 1] = sortArr[j]; j--; }\n            sortArr[j + 1] = node;\n        }\n        return;\n    }\n\n    if (zArr.length < n) {\n        zArr = new Uint32Array(n);\n        zBuf = new Uint32Array(n);\n        sortBuf = new Array(n);\n    }\n    for (let i = 0; i < n; i++) zArr[i] = sortArr[i].z;\n\n    // even pass count lands the sorted result back in sortArr\n    radixPass(n, sortArr, zArr, sortBuf, zBuf, 0);\n    radixPass(n, sortBuf, zBuf, sortArr, zArr, 8);\n    radixPass(n, sortArr, zArr, sortBuf, zBuf, 16);\n    radixPass(n, sortBuf, zBuf, sortArr, zArr, 24);\n}\n\n// one LSD radix pass: stably scatter the first n nodes (and their z) from src to dst,\n// bucketed by the 8-bit digit of z at the given bit shift\n/** @param {number} n @param {Node[]} src @param {Uint32Array} srcZ @param {Node[]} dst @param {Uint32Array} dstZ @param {number} shift */\nfunction radixPass(n, src, srcZ, dst, dstZ, shift) {\n    counts.fill(0);\n    for (let i = 0; i < n; i++) counts[(srcZ[i] >>> shift) & 0xff]++;\n    // turn per-bucket counts into start offsets (prefix sum)\n    let sum = 0;\n    for (let b = 0; b < 256; b++) { const c = counts[b]; counts[b] = sum; sum += c; }\n    for (let i = 0; i < n; i++) {\n        const z = srcZ[i];\n        const pos = counts[(z >>> shift) & 0xff]++;\n        dst[pos] = src[i];\n        dstZ[pos] = z;\n    }\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\n/** @param {number} x @param {number} y @param {number} minX @param {number} minY @param {number} invSize @returns {number} */\nfunction zOrder(x, y, minX, minY, invSize) {\n    // coords are transformed into non-negative 15-bit integer range\n    x = (x - minX) * invSize | 0;\n    y = (y - minY) * invSize | 0;\n\n    x = (x | (x << 8)) & 0x00FF00FF;\n    x = (x | (x << 4)) & 0x0F0F0F0F;\n    x = (x | (x << 2)) & 0x33333333;\n    x = (x | (x << 1)) & 0x55555555;\n\n    y = (y | (y << 8)) & 0x00FF00FF;\n    y = (y | (y << 4)) & 0x0F0F0F0F;\n    y = (y | (y << 2)) & 0x33333333;\n    y = (y | (y << 1)) & 0x55555555;\n\n    return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\n/** @param {Node} start @returns {Node} */\nfunction getLeftmost(start) {\n    let p = start,\n        leftmost = start;\n    do {\n        if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n        p = p.next;\n    } while (p !== start);\n\n    return leftmost;\n}\n\n// check if a point lies within a convex triangle\n/** @param {number} ax @param {number} ay @param {number} bx @param {number} by @param {number} cx @param {number} cy @param {number} px @param {number} py @returns {boolean} */\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n    return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n           (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n           (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\n/** @param {Node} a @param {Node} b @returns {boolean} true when the diagonal is valid */\nfunction isValidDiagonal(a, b) {\n    const zeroLength = equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0; // degenerate case\n    return a.next.i !== b.i && (zeroLength || locallyInside(a, b) && locallyInside(b, a) && // // locally visible\n        (area(a.prev, a, b.prev) !== 0 || area(a, b.prev, b) !== 0)) && // no opposite-facing sectors\n        !intersectsPolygon(a, b) && (zeroLength || middleInside(a, b)); // doesn't intersect other edges, diagonal inside polygon\n}\n\n// signed area of a triangle\n/** @param {Node} p @param {Node} q @param {Node} r @returns {number} */\nfunction area(p, q, r) {\n    return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\n/** @param {Node} p1 @param {Node} p2 @returns {boolean} */\nfunction equals(p1, p2) {\n    return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect; by default includes collinear boundary touches\n/** @param {Node} p1 @param {Node} q1 @param {Node} p2 @param {Node} q2 @param {boolean} [includeBoundary] @returns {boolean} */\nfunction intersects(p1, q1, p2, q2, includeBoundary = true) {\n    const o1 = area(p1, q1, p2);\n    const o2 = area(p1, q1, q2);\n    const o3 = area(p2, q2, p1);\n    const o4 = area(p2, q2, q1);\n\n    if (((o1 > 0 && o2 < 0) || (o1 < 0 && o2 > 0)) && ((o3 > 0 && o4 < 0) || (o3 < 0 && o4 > 0))) return true;\n\n    if (!includeBoundary) return false;\n\n    if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n    if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n    if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n    if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n    return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\n/** @param {Node} p @param {Node} q @param {Node} r @returns {boolean} */\nfunction onSegment(p, q, r) {\n    return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\n// check if a polygon diagonal intersects any polygon segments\n/** @param {Node} a @param {Node} b @returns {boolean} */\nfunction intersectsPolygon(a, b) {\n    // diagonal bbox; an edge whose bbox can't overlap it can't intersect it, so\n    // skip the orientation test for those (the common case — the diagonal is short)\n    const minX = Math.min(a.x, b.x);\n    const maxX = Math.max(a.x, b.x);\n    const minY = Math.min(a.y, b.y);\n    const maxY = Math.max(a.y, b.y);\n\n    let p = a;\n    do {\n        const n = p.next;\n        if ((p.x > maxX && n.x > maxX) || (p.x < minX && n.x < minX) ||\n            (p.y > maxY && n.y > maxY) || (p.y < minY && n.y < minY)) {\n            p = n;\n            continue;\n        }\n        if (p.i !== a.i && n.i !== a.i && p.i !== b.i && n.i !== b.i &&\n                intersects(p, n, a, b)) return true;\n        p = n;\n    } while (p !== a);\n\n    return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\n/** @param {Node} a @param {Node} b @returns {boolean} */\nfunction locallyInside(a, b) {\n    return area(a.prev, a, a.next) < 0 ?\n        area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n        area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\n/** @param {Node} a @param {Node} b @returns {boolean} */\nfunction middleInside(a, b) {\n    let p = a;\n    let inside = false;\n    const px = (a.x + b.x) / 2;\n    const py = (a.y + b.y) / 2;\n    do {\n        const n = p.next;\n        if (((p.y > py) !== (n.y > py)) && (px < (n.x - p.x) * (py - p.y) / (n.y - p.y) + p.x))\n            inside = !inside;\n        p = n;\n    } while (p !== a);\n\n    return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\n/** @param {Node} a @param {Node} b @returns {Node} */\nfunction splitPolygon(a, b) {\n    const a2 = createNode(a.i, a.x, a.y),\n        b2 = createNode(b.i, b.x, b.y),\n        an = a.next,\n        bp = b.prev;\n\n    a.next = b;\n    b.prev = a;\n\n    a2.next = an;\n    an.prev = a2;\n\n    b2.next = a2;\n    a2.prev = b2;\n\n    bp.next = b2;\n    b2.prev = bp;\n\n    return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\n/** @param {number} i @param {number} x @param {number} y @param {Node | null} last @returns {Node} */\nfunction insertNode(i, x, y, last) {\n    const p = createNode(i, x, y);\n\n    if (!last) {\n        p.prev = p;\n        p.next = p;\n\n    } else {\n        p.next = last.next;\n        p.prev = last;\n        last.next.prev = p;\n        last.next = p;\n    }\n    return p;\n}\n\n/** @param {Node} p */\nfunction removeNode(p) {\n    p.next.prev = p.prev;\n    p.prev.next = p.next;\n\n    if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n    if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n\n    // keep the hole-bridge index's block bboxes covering the healed prev->next edge\n    if (indexActive) growBlock(p.prev, p.next);\n}\n\n/** @param {number} i @param {number} x @param {number} y @returns {Node} */\nfunction createNode(i, x, y) {\n    // prev/next are assigned by the caller before any read, so the null init is cast away here\n    return /** @type {Node} */ (/** @type {unknown} */ ({\n        i, // vertex index in coordinates array\n        x, y, // vertex coordinates\n        prev: null, // previous and next vertex nodes in a polygon ring\n        next: null,\n        z: 0, // z-order curve value; doubles as owning block in the hole-bridge index during eliminateHoles\n        prevZ: null, // previous and next nodes in z-order\n        nextZ: null\n    }));\n}\n\n/**\n * Return the relative difference between the polygon area and the area of its triangulation —\n * a value near 0 means a correct triangulation. Useful for verifying output in tests.\n *\n * @param {ArrayLike<number>} data\n * @param {ArrayLike<number> | null} holeIndices\n * @param {number} dim number of coordinates per vertex in `data`\n * @param {ArrayLike<number>} triangles output of {@link earcut}\n * @returns {number}\n * @example deviation(data, holes, dim, earcut(data, holes, dim)); // ~0 if correct\n */\nexport function deviation(data, holeIndices, dim, triangles) {\n    const hasHoles = holeIndices && holeIndices.length;\n    const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n    let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n    if (hasHoles) {\n        for (let i = 0, len = holeIndices.length; i < len; i++) {\n            const start = holeIndices[i] * dim;\n            const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n            polygonArea -= Math.abs(signedArea(data, start, end, dim));\n        }\n    }\n\n    let trianglesArea = 0;\n    for (let i = 0; i < triangles.length; i += 3) {\n        const a = triangles[i] * dim;\n        const b = triangles[i + 1] * dim;\n        const c = triangles[i + 2] * dim;\n        trianglesArea += Math.abs(\n            (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n            (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n    }\n\n    // with no triangles, a polygon area within shoelace roundoff of zero (which scales with the\n    // squared coordinate magnitude) means the input was degenerate rather than mistriangulated\n    if (trianglesArea === 0) {\n        let max = 0;\n        for (let i = 0; i < data.length; i += dim) max = Math.max(max, Math.abs(data[i]), Math.abs(data[i + 1]));\n        return Math.abs(polygonArea) <= data.length * max * max * Number.EPSILON ? 0 : 1;\n    }\n    return Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\n/** @param {ArrayLike<number>} data @param {number} start @param {number} end @param {number} dim @returns {number} */\nfunction signedArea(data, start, end, dim) {\n    let sum = 0;\n    for (let i = start, j = end - dim; i < end; i += dim) {\n        sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n        j = i;\n    }\n    return sum;\n}\n\n/**\n * Turn a polygon in multi-dimensional array form (e.g. as in GeoJSON) into the flat form Earcut accepts.\n *\n * @param {ReadonlyArray<ReadonlyArray<ArrayLike<number>>>} data array of rings; the first ring is the outer contour, the rest are holes\n * @returns {{vertices: number[], holes: number[], dimensions: number}}\n * @example const {vertices, holes, dimensions} = flatten(geojson.coordinates);\n */\nexport function flatten(data) {\n    const vertices = [];\n    const holes = [];\n    const dimensions = data[0][0].length;\n    let holeIndex = 0;\n    let prevLen = 0;\n\n    for (const ring of data) {\n        for (const p of ring) {\n            for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n        }\n        if (prevLen) {\n            holeIndex += prevLen;\n            holes.push(holeIndex);\n        }\n        prevLen = ring.length;\n    }\n    return {vertices, holes, dimensions};\n}\n\n// Reusable module-level scratch for refine():\n//   he      = twin half-edge of each edge, or -1 on the polygon boundary\n//   hTable  = open-addressing hash, slot -> half-edge index, valid iff hStamp[slot] === gen\n//   edgeStamp = pending-in-stack flag, cleared when the edge is popped\n/** @type {Int32Array} */ let edgeStack;\n/** @type {Int32Array} */ let he;\n/** @type {Int32Array} */ let hTable;\n/** @type {Uint32Array} */ let hStamp;\n/** @type {Uint8Array} */ let edgeStamp;\nlet hMask = 0, gen = 0;\n\n/**\n * Refine a triangulation toward the constrained Delaunay triangulation by legalizing every\n * interior edge in place with Lawson flips — maximizing the minimum angle and removing most\n * slivers. An optional post-pass for {@link earcut} output, or any manifold triangle-index array\n * indexing into `coords`. Adapted from delaunator's edge legalization.\n *\n * Uses non-robust predicates: float input is fine, and the worst case is a not-quite-Delaunay\n * edge, never an invalid mesh.\n *\n * @param {number[]} triangles triangle indices, as returned by {@link earcut}; mutated in place\n * @param {ArrayLike<number>} coords the flat vertex coordinates passed to {@link earcut}\n * @param {number} [dim=2] number of coordinates per vertex in `coords`\n * @example refine(earcut(data), data);\n */\nexport function refine(triangles, coords, dim = 2) {\n    const t = triangles;\n    const n = t.length;\n    if (n < 6) return;\n    ensureScratch(n);\n    gen++;              // bumping the generation logically empties the hash (no clearing)\n    he.fill(-1, 0, n);\n\n    // Build half-edge twins with an undirected-edge hash; consumed slots mark linked pairs. As each\n    // pair is linked we seed the stack with one representative (s, the earlier-inserted edge) — this\n    // fuses the initial \"push every interior edge\" pass into the build, saving a full O(n) scan.\n    // edgeStamp is all-zero here (balanced push/pop leaves it clean) and each pair links once, so\n    // the seed write needs no dedup guard.\n    let i = 0;\n    for (let e = 0; e < n; e++) {\n        const a = t[e], b = t[nextHE(e)];\n        const lo = a < b ? a : b, hi = a < b ? b : a;\n        let h = (Math.imul(lo, 0x9e3779b1) ^ Math.imul(hi, 0x85ebca6b)) & hMask;\n        while (hStamp[h] === gen) {\n            const s = hTable[h];\n            // s === -1 marks a consumed slot (a pair already linked) — skip past it\n            if (s !== -1) {\n                const sa = t[s], sb = t[nextHE(s)];\n                if ((sa === lo && sb === hi) || (sa === hi && sb === lo)) {\n                    he[e] = s; he[s] = e; hTable[h] = -1; // link, then consume the slot\n                    edgeStamp[s] = 1; edgeStack[i++] = s; // seed the interior edge for the cascade\n                    break;\n                }\n            }\n            h = (h + 1) & hMask;\n        }\n        if (hStamp[h] !== gen) { hTable[h] = e; hStamp[h] = gen; } // first occurrence: insert\n    }\n\n    while (i > 0) {\n        const a = edgeStack[--i];\n        edgeStamp[a] = 0;\n        const b = he[a];\n        if (b === -1) continue;\n\n        const a0 = a - a % 3;\n        const b0 = b - b % 3;\n        const ar = a0 + (a + 2) % 3;\n        const al = a0 + (a + 1) % 3;\n        const bl = b0 + (b + 2) % 3;\n        const br = b0 + (b + 1) % 3;\n        const p0 = t[ar], pr = t[a], pl = t[al], p1 = t[bl];\n\n        const x0 = coords[p0 * dim], y0 = coords[p0 * dim + 1];\n        const xr = coords[pr * dim], yr = coords[pr * dim + 1];\n        const xl = coords[pl * dim], yl = coords[pl * dim + 1];\n        const x1 = coords[p1 * dim], y1 = coords[p1 * dim + 1];\n\n        // Test inCircle first: most interior edges are already Delaunay (inCircle true → no flip),\n        // so this short-circuits before the two convexity orients on the common path. The quad must\n        // also be convex (both new triangles CCW) — flipping a reflex quad would push a triangle\n        // outside the polygon. Boundary/hole edges need no guard — they self-protect via he === -1.\n        if (!inCircle(x0, y0, xr, yr, xl, yl, x1, y1) &&\n            orient(x0, y0, xr, yr, x1, y1) > 0 && orient(x0, y0, x1, y1, xl, yl) > 0) {\n            t[a] = p1; t[b] = p0;\n            const hbl = he[bl], har = he[ar];\n            he[a] = hbl; if (hbl !== -1) he[hbl] = a;\n            he[b] = har; if (har !== -1) he[har] = b;\n            he[ar] = bl; he[bl] = ar;\n\n            // re-check the quad's four outer edges; skip boundary edges (he === -1) and any\n            // already queued (edgeStamp), which also keeps the stack bounded by n.\n            if (hbl    !== -1 && edgeStamp[a]  === 0) { edgeStamp[a]  = 1; edgeStack[i++] = a; }\n            if (har    !== -1 && edgeStamp[b]  === 0) { edgeStamp[b]  = 1; edgeStack[i++] = b; }\n            if (he[al] !== -1 && edgeStamp[al] === 0) { edgeStamp[al] = 1; edgeStack[i++] = al; }\n            if (he[br] !== -1 && edgeStamp[br] === 0) { edgeStamp[br] = 1; edgeStack[i++] = br; }\n        }\n    }\n}\n\n/** @param {number} ax @param {number} ay @param {number} bx @param {number} by @param {number} cx @param {number} cy */\nfunction orient(ax, ay, bx, by, cx, cy) {\n    return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);\n}\n\n// Whether p is inside or exactly on the circumcircle of triangle (a, b, c). Sign is negated vs the\n// usual predicate to match earcut's CCW winding — the standard sign would build the anti-Delaunay\n// mesh. Cocircular quads are legal ties, so refine only flips when this returns false.\n/** @param {number} ax @param {number} ay @param {number} bx @param {number} by @param {number} cx @param {number} cy @param {number} px @param {number} py */\nfunction inCircle(ax, ay, bx, by, cx, cy, px, py) {\n    const dx = ax - px, dy = ay - py, ex = bx - px, ey = by - py, fx = cx - px, fy = cy - py;\n    const ap = dx * dx + dy * dy, bp = ex * ex + ey * ey, cp = fx * fx + fy * fy;\n    // A near-cocircular quad is a legal Delaunay tie, but roundoff can flag both an edge and its\n    // flip as illegal, cascading into an endless flip loop (#205) — so treat a determinant within\n    // a small margin of zero as a tie. The determinant's worst-case roundoff error is provably\n    // below 9e-16·(ap + bp + cp)² (Shewchuk-style bound), so the margin guarantees every executed\n    // flip is illegal in exact arithmetic, and Lawson flipping always terminates.\n    const s = ap + bp + cp;\n    return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) <= 1e-13 * s * s;\n}\n\n/** @param {number} e */\nfunction nextHE(e) { // next half-edge within the same triangle\n    return e - e % 3 + (e + 1) % 3;\n}\n\n// Grow the scratch arrays on demand (like earcut's z-order arrays). Allocating lazily here rather\n// than at module load lets the whole refine() block tree-shake away for callers who don't use it.\n/** @param {number} n */\nfunction ensureScratch(n) {\n    // edgeStack holds at most one entry per half-edge (edgeStamp dedups), so n is a safe cap —\n    // sizing it up front lets the cascade push without a bounds/grow check.\n    if (!edgeStack || edgeStack.length < n) edgeStack = new Int32Array(n);\n    if (!he || he.length < n) he = new Int32Array(n);\n    if (!edgeStamp || edgeStamp.length < n) edgeStamp = new Uint8Array(n);\n    let size = 1;\n    while (size < n * 4) size <<= 1; // power-of-two table, load factor <= 0.25\n    if (!hTable || hTable.length < size) { hTable = new Int32Array(size); hStamp = new Uint32Array(size); }\n    hMask = size - 1;\n}\n", "// Should match actual possible granularity settings from circle_bucket.ts\n\n/**\n * Defines the granularity of subdivision for circles with `circle-pitch-alignment: 'map'` and for heatmap kernels.\n * More subdivision will cause circles to more closely follow the planet's surface.\n *\n * Possible values: 1, 3, 5, 7.\n * Subdivision of 1 results in a simple quad.\n */\nexport type CircleGranularity = 1 | 3 | 5 | 7;\n\n/**\n * Controls how much subdivision happens for a given type of geometry at different zoom levels.\n */\nexport class SubdivisionGranularityExpression {\n    /**\n     * A tile of zoom level 0 will be subdivided to this granularity level.\n     * Each subsequent zoom level will have its granularity halved.\n     */\n    private readonly _baseZoomGranularity: number;\n\n    /**\n     * No tile will have granularity level smaller than this.\n     */\n    private readonly _minGranularity: number;\n\n    constructor(baseZoomGranularity: number, minGranularity: number) {\n        if (minGranularity > baseZoomGranularity) {\n            throw new Error('Min granularity must not be greater than base granularity.');\n        }\n\n        this._baseZoomGranularity = baseZoomGranularity;\n        this._minGranularity = minGranularity;\n    }\n\n    public getGranularityForZoomLevel(zoomLevel: number): number {\n        const divisor = 1 << zoomLevel;\n        return Math.max(Math.floor(this._baseZoomGranularity / divisor), this._minGranularity, 1);\n    }\n}\n\n/**\n * An object describing how much subdivision should be applied to different types of geometry at different zoom levels.\n */\nexport class SubdivisionGranularitySetting {\n    /**\n     * Granularity settings used for fill and fill-extrusion layers (for fill, both polygons and their anti-aliasing outlines).\n     */\n    public readonly fill: SubdivisionGranularityExpression;\n\n    /**\n     * Granularity used for the line layer.\n     */\n    public readonly line: SubdivisionGranularityExpression;\n\n    /**\n     * Granularity used for geometry covering the entire tile: raster tiles, etc.\n     */\n    public readonly tile: SubdivisionGranularityExpression;\n\n    /**\n     * Granularity used for stencil masks for tiles.\n     */\n    public readonly stencil: SubdivisionGranularityExpression;\n\n    /**\n     * Controls the granularity of `pitch-alignment: map` circles and heatmap kernels.\n     * More granular circles will more closely follow the map's surface.\n     */\n    public readonly circle: CircleGranularity;\n\n    constructor(options: {\n        /**\n         * Granularity settings used for fill and fill-extrusion layers (for fill, both polygons and their anti-aliasing outlines).\n         */\n        fill: SubdivisionGranularityExpression;\n        /**\n         * Granularity used for the line layer.\n         */\n        line: SubdivisionGranularityExpression;\n        /**\n         * Granularity used for geometry covering the entire tile: stencil masks, raster tiles, etc.\n         */\n        tile: SubdivisionGranularityExpression;\n        /**\n         * Granularity used for stencil masks for tiles.\n         */\n        stencil: SubdivisionGranularityExpression;\n        /**\n         * Controls the granularity of `pitch-alignment: map` circles and heatmap kernels.\n         * More granular circles will more closely follow the map's surface.\n         */\n        circle: CircleGranularity;\n    }) {\n        this.fill = options.fill;\n        this.line = options.line;\n        this.tile = options.tile;\n        this.stencil = options.stencil;\n        this.circle = options.circle;\n    }\n\n    /**\n     * Granularity settings that disable subdivision altogether.\n     */\n    public static readonly noSubdivision: SubdivisionGranularitySetting = new SubdivisionGranularitySetting({\n        fill: new SubdivisionGranularityExpression(0, 0),\n        line: new SubdivisionGranularityExpression(0, 0),\n        tile: new SubdivisionGranularityExpression(0, 0),\n        stencil: new SubdivisionGranularityExpression(0, 0),\n        circle: 1\n    });\n}\n", "import Point from '@mapbox/point-geometry';\nimport {EXTENT} from '../data/extent.ts';\nimport earcut from 'earcut';\nimport {SubdivisionGranularityExpression, SubdivisionGranularitySetting} from './subdivision_granularity_settings.ts';\nimport {register} from '../util/web_worker_transfer.ts';\n\nimport type {CanonicalTileID} from '../tile/tile_id.ts';\n\nregister('SubdivisionGranularityExpression', SubdivisionGranularityExpression);\nregister('SubdivisionGranularitySetting', SubdivisionGranularitySetting);\n\ntype SubdivisionResult = {\n    verticesFlattened: number[];\n    indicesTriangles: number[];\n\n    /**\n     * An array of arrays of indices of subdivided lines for polygon outlines.\n     * Each array of lines corresponds to one ring of the original polygon.\n     */\n    indicesLineList: number[][];\n};\n\n// Special pole vertices have coordinates -32768,-32768 for the north pole and 32767,32767 for the south pole.\n// First, find any *non-pole* vertices at those coordinates and move them slightly elsewhere.\nexport const NORTH_POLE_Y = -32768;\nexport const SOUTH_POLE_Y = 32767;\n\nclass Subdivider {\n    /**\n     * Flattened vertex positions (xyxyxy).\n     */\n    private _vertexBuffer: number[] = [];\n\n    /**\n     * Map of \"vertex x and y coordinate\" to \"index of such vertex\".\n     */\n    private _vertexDictionary: Map<number, number> = new Map<number, number>();\n    private _used: boolean = false;\n\n    private readonly _canonical: CanonicalTileID;\n\n    private readonly _granularity;\n    private readonly _granularityCellSize;\n\n    constructor(granularity: number, canonical: CanonicalTileID) {\n        this._granularity = granularity;\n        this._granularityCellSize = EXTENT / granularity;\n        this._canonical = canonical;\n    }\n\n    private _getKey(x: number, y: number) {\n        // Assumes signed 16 bit positions.\n        x = x + 32768;\n        y = y + 32768;\n        return (x << 16) | (y << 0);\n    }\n\n    /**\n     * Returns an index into the internal vertex buffer for a vertex at the given coordinates.\n     * If the internal vertex buffer contains no such vertex, then it is added.\n     */\n    private _vertexToIndex(x: number, y: number): number {\n        if (x < -32768 || y < -32768 || x > 32767 || y > 32767) {\n            throw new Error('Vertex coordinates are out of signed 16 bit integer range.');\n        }\n        const xInt = Math.round(x) | 0;\n        const yInt = Math.round(y) | 0;\n        const key = this._getKey(xInt, yInt);\n        const existing = this._vertexDictionary.get(key);\n        if (existing !== undefined) {\n            return existing;\n        }\n        const index = this._vertexBuffer.length / 2;\n        this._vertexDictionary.set(key, index);\n        this._vertexBuffer.push(xInt, yInt);\n        return index;\n    }\n\n    /**\n     * Subdivides a polygon by iterating over rows of granularity subdivision cells and splitting each row along vertical subdivision axes.\n     * @param inputIndices - Indices into the flattened input vertices of the triangulated polygon (the output of `earcut`).\n     * @param inputRemap - Index into the internal vertex buffer for each flattened input vertex.\n     * @returns Indices into the internal vertex buffer for triangles that are a subdivision of the input geometry.\n     */\n    private _subdivideTrianglesScanline(inputIndices: number[], inputRemap: number[]): number[] {\n        // A granularity cell is the square space between axes that subdivide geometry.\n        // For granularity 8, cells would be 1024 by 1024 units.\n        // For each triangle, we iterate over all cell rows it intersects, and generate subdivided geometry\n        // only within one cell row at a time. This way, we implicitly subdivide along the X-parallel axes (cell row boundaries).\n        // For each cell row, we generate an ordered point ring that describes the subdivided geometry inside this row (an intersection of the triangle and a given cell row).\n        // Such ordered ring can be trivially triangulated.\n        // Each ring may consist of sections of triangle edges that lie inside the cell row, and cell boundaries that lie inside the triangle. Both must be further subdivided along Y-parallel axes.\n        // Most complexity of this function comes from generating correct vertex rings, and from placing the vertices into the ring in the correct order.\n\n        if (this._granularity < 2) {\n            // The actual subdivision code always produces triangles with the correct winding order.\n            // Also apply winding order correction when skipping subdivision altogether to maintain consistency.\n            return fixWindingOrder(this._vertexBuffer, remapIndices(inputIndices, inputRemap));\n        }\n\n        const finalIndices = [];\n\n        // Iterate over all input triangles\n        const numIndices = inputIndices.length;\n        for (let primitiveIndex = 0; primitiveIndex < numIndices; primitiveIndex += 3) {\n            const triangleIndices: [number, number, number] = [\n                inputRemap[inputIndices[primitiveIndex + 0]], // v0\n                inputRemap[inputIndices[primitiveIndex + 1]], // v1\n                inputRemap[inputIndices[primitiveIndex + 2]], // v2\n            ];\n\n            const triangleVertices: [number, number, number, number, number, number] = [\n                this._vertexBuffer[triangleIndices[0] * 2 + 0], // v0.x\n                this._vertexBuffer[triangleIndices[0] * 2 + 1], // v0.y\n                this._vertexBuffer[triangleIndices[1] * 2 + 0], // v1.x\n                this._vertexBuffer[triangleIndices[1] * 2 + 1], // v1.y\n                this._vertexBuffer[triangleIndices[2] * 2 + 0], // v2.x\n                this._vertexBuffer[triangleIndices[2] * 2 + 1], // v2.y\n            ];\n\n            let minX = Infinity;\n            let minY = Infinity;\n            let maxX = -Infinity;\n            let maxY = -Infinity;\n\n            // Compute AABB\n            for (let i = 0; i < 3; i++) {\n                const vx = triangleVertices[i * 2];\n                const vy = triangleVertices[i * 2 + 1];\n                minX = Math.min(minX, vx);\n                maxX = Math.max(maxX, vx);\n                minY = Math.min(minY, vy);\n                maxY = Math.max(maxY, vy);\n            }\n\n            if (minX === maxX || minY === maxY) {\n                continue; // Skip degenerate linear axis-aligned triangles\n            }\n\n            const cellXmin = Math.floor(minX / this._granularityCellSize);\n            const cellXmax = Math.ceil(maxX / this._granularityCellSize);\n            const cellYmin = Math.floor(minY / this._granularityCellSize);\n            const cellYmax = Math.ceil(maxY / this._granularityCellSize);\n\n            // Skip subdividing triangles that do not span multiple cells - just add them \"as is\".\n            if (cellXmin === cellXmax && cellYmin === cellYmax) {\n                finalIndices.push(...triangleIndices);\n                continue;\n            }\n\n            // Iterate over cell rows that intersect this triangle\n            for (let cellRow = cellYmin; cellRow < cellYmax; cellRow++) {\n                const ring = this._scanlineGenerateVertexRingForCellRow(cellRow, triangleVertices, triangleIndices);\n                scanlineTriangulateVertexRing(this._vertexBuffer, ring, finalIndices);\n            }\n        }\n\n        return finalIndices;\n    }\n\n    /**\n     * Takes a triangle and a cell row index, returns a subdivided vertex ring of the intersection of the triangle and the cell row.\n     * @param cellRow - Index of the cell row. A cell row of index `i` convert range from `i * granularityCellSize` to `(i + 1) * granularityCellSize`.\n     * @param triangleVertices - An array of 6 elements, contains flattened positions of the triangle's vertices: `[v0x, v0y, v1x, v1y, v2x, v2y]`.\n     * @param triangleIndices - An array of 3 elements, contains the original indices of the triangle's vertices: `[index0, index1, index2]`.\n     * @returns The resulting ring of vertex indices and the index (to the returned ring array) of the leftmost vertex in the ring.\n     */\n    private _scanlineGenerateVertexRingForCellRow(\n        cellRow: number,\n        triangleVertices: [number, number, number, number, number, number],\n        triangleIndices: [number, number, number]\n    ) {\n        const cellRowYTop = cellRow * this._granularityCellSize;\n        const cellRowYBottom = cellRowYTop + this._granularityCellSize;\n        const ring = [];\n\n        // Generate the vertex ring\n        for (let edgeIndex = 0; edgeIndex < 3; edgeIndex++) {\n            // Current edge that will be subdivided: a --> b\n            // The remaining vertex of the triangle: c\n            const aX = triangleVertices[edgeIndex * 2];\n            const aY = triangleVertices[edgeIndex * 2 + 1];\n            const bX = triangleVertices[((edgeIndex + 1) * 2) % 6];\n            const bY = triangleVertices[((edgeIndex + 1) * 2 + 1) % 6];\n            const cX = triangleVertices[((edgeIndex + 2) * 2) % 6];\n            const cY = triangleVertices[((edgeIndex + 2) * 2 + 1) % 6];\n            // Edge direction\n            const dirX = bX - aX;\n            const dirY = bY - aY;\n\n            // Edges parallel with either axis will need special handling later.\n            const isParallelY = dirX === 0;\n            const isParallelX = dirY === 0;\n\n            // Distance along edge where it enters/exits current cell row,\n            // where distance 0 is the edge start point, 1 the endpoint, 0.5 the mid point, etc.\n            const tTop = (cellRowYTop - aY) / dirY;\n            const tBottom = (cellRowYBottom - aY) / dirY;\n            const tEnter = Math.min(tTop, tBottom);\n            const tExit = Math.max(tTop, tBottom);\n\n            // Determine if edge lies entirely outside this cell row.\n            // Check entry and exit points, or if edge is parallel with X, check its Y coordinate.\n            if ((!isParallelX && (tEnter >= 1 || tExit <= 0)) ||\n                (isParallelX && (aY < cellRowYTop || aY > cellRowYBottom))) {\n                // Skip this edge\n                // But make sure to add its endpoint vertex if needed.\n                if (bY >= cellRowYTop && bY <= cellRowYBottom) {\n                    // The edge endpoint is within this row, add it to the ring\n                    ring.push(triangleIndices[(edgeIndex + 1) % 3]);\n                }\n                continue;\n            }\n\n            // Do not add original triangle vertices now, those are handled separately later\n\n            // Special case: edge vertex for entry into cell row\n            // If edge is parallel with X axis, there is no entry vertex\n            if (!isParallelX && tEnter > 0) {\n                const x = aX + dirX * tEnter;\n                const y = aY + dirY * tEnter;\n                ring.push(this._vertexToIndex(x, y));\n            }\n\n            // The X coordinates of the points where the edge enters/exits the current cell row,\n            // or the edge start/endpoint, if the entry/exit happens beyond the edge bounds.\n            const enterX = aX + dirX * Math.max(tEnter, 0);\n            const exitX = aX + dirX * Math.min(tExit, 1);\n\n            // Generate edge interior vertices\n            // No need to subdivide (along X) edges that are parallel with Y\n            if (!isParallelY) {\n                this._generateIntraEdgeVertices(ring, aX, aY, bX, bY, enterX, exitX);\n            }\n\n            // Special case: edge vertex for exit from cell row\n            if (!isParallelX && tExit < 1) {\n                const x = aX + dirX * tExit;\n                const y = aY + dirY * tExit;\n                ring.push(this._vertexToIndex(x, y));\n            }\n\n            // When to split inter-edge boundary segments?\n            // When the boundary doesn't intersect a vertex, its easy. But what if it does?\n\n            //      a\n            //     /|\n            //    / |\n            // --c--|--boundary\n            //    \\ |\n            //     \\|\n            //      b\n            //\n            // Inter-edge region should be generated when processing the a-b edge.\n            // This happens fine for the top row, for the bottom row,\n            //\n\n            //      x\n            //     /|\n            //    / |\n            // --x--x--boundary\n            //\n            // Edge that lies on boundary should be subdivided in its edge phase.\n            // The inter-edge phase will correctly skip it.\n\n            // Add endpoint vertex\n            if (isParallelX || (bY >= cellRowYTop && bY <= cellRowYBottom)) {\n                ring.push(triangleIndices[(edgeIndex + 1) % 3]);\n            }\n            // Any edge that has endpoint outside this row or on its boundary gets\n            // inter-edge vertices.\n            // No row boundary to split for edges parallel with X\n            if (!isParallelX && (bY <= cellRowYTop || bY >= cellRowYBottom)) {\n                this._generateInterEdgeVertices(ring, aX, aY, bX, bY, cX, cY,\n                    exitX, cellRowYTop, cellRowYBottom);\n            }\n        }\n\n        return ring;\n    }\n\n    /**\n     * Generates ring vertices along an edge A-\\>B, but only in the part that intersects a given cell row.\n     * Does not handle adding edge endpoint vertices or edge cell row enter/exit vertices.\n     * @param ring - Ordered array of vertex indices for the constructed ring. New indices are placed here.\n     * @param enterX - The X coordinate of the point where edge A-\\>B enters the current cell row.\n     * @param exitX - The X coordinate of the point where edge A-\\>B exits the current cell row.\n     */\n    private _generateIntraEdgeVertices(\n        ring: number[],\n        aX: number,\n        aY: number,\n        bX: number,\n        bY: number,\n        enterX: number,\n        exitX: number\n    ): void {\n        const dirX = bX - aX;\n        const dirY = bY - aY;\n        const isParallelX = dirY === 0;\n\n        const leftX = isParallelX ? Math.min(aX, bX) : Math.min(enterX, exitX);\n        const rightX = isParallelX ? Math.max(aX, bX) : Math.max(enterX, exitX);\n\n        const edgeSubdivisionLeftCellX = Math.floor(leftX / this._granularityCellSize) + 1;\n        const edgeSubdivisionRightCellX = Math.ceil(rightX / this._granularityCellSize) - 1;\n\n        const isEdgeLeftToRight = isParallelX ? (aX < bX) : (enterX < exitX);\n        if (isEdgeLeftToRight) {\n            // Left to right\n            for (let cellX = edgeSubdivisionLeftCellX; cellX <= edgeSubdivisionRightCellX; cellX++) {\n                const x = cellX * this._granularityCellSize;\n                const y = aY + dirY * (x - aX) / dirX;\n                ring.push(this._vertexToIndex(x, y));\n            }\n        } else {\n            // Right to left\n            for (let cellX = edgeSubdivisionRightCellX; cellX >= edgeSubdivisionLeftCellX; cellX--) {\n                const x = cellX * this._granularityCellSize;\n                const y = aY + dirY * (x - aX) / dirX;\n                ring.push(this._vertexToIndex(x, y));\n            }\n        }\n    }\n\n    /**\n     * Generates ring vertices along cell border.\n     * Call when processing an edge A-\\>B that exits the current row (B lies outside the current row).\n     * Generates vertices along the cell edge between the exit point from cell row\n     * of edge A-\\>B and entry of edge B-\\>C, or entry of C-\\>A if both A and C lie outside the cell row.\n     * Does not handle adding edge endpoint vertices or edge cell row enter/exit vertices.\n     * @param ring - Ordered array of vertex indices for the constructed ring. New indices are placed here.\n     * @param exitX - The X coordinate of the point where edge A-\\>B exits the current cell row.\n     * @param cellRowYTop - The current cell row top Y coordinate.\n     * @param cellRowYBottom - The current cell row bottom Y coordinate.\n     */\n    private _generateInterEdgeVertices(\n        ring: number[],\n        aX: number,\n        aY: number,\n        bX: number,\n        bY: number,\n        cX: number,\n        cY: number,\n        exitX: number,\n        cellRowYTop: number,\n        cellRowYBottom: number\n    ): void {\n        const dirY = bY - aY;\n\n        const dir2X = cX - bX;\n        const dir2Y = cY - bY;\n        const t2Top = (cellRowYTop - bY) / dir2Y;\n        const t2Bottom = (cellRowYBottom - bY) / dir2Y;\n        // The distance along edge B->C where it enters/exits the current cell row,\n        // where distance 0 is B, 1 is C, 0.5 is the edge midpoint, etc.\n        const t2Enter = Math.min(t2Top, t2Bottom);\n        const t2Exit = Math.max(t2Top, t2Bottom);\n        const enter2X = bX + dir2X * t2Enter;\n        let boundarySubdivisionLeftCellX = Math.floor(Math.min(enter2X, exitX) / this._granularityCellSize) + 1;\n        let boundarySubdivisionRightCellX = Math.ceil(Math.max(enter2X, exitX) / this._granularityCellSize) - 1;\n        let isBoundaryLeftToRight = exitX < enter2X;\n\n        const isParallelX2 = dir2Y === 0;\n\n        if (isParallelX2 && (cY === cellRowYTop || cY === cellRowYBottom)) {\n            // Special case when edge b->c that lies on the cell boundary.\n            // Do not generate any inter-edge vertices in this case,\n            // this b->c edge gets subdivided when it is itself processed.\n            return;\n        }\n\n        if (isParallelX2 || t2Enter >= 1 || t2Exit <= 0) {\n            // The next edge (b->c) lies entirely outside this cell row\n            // Find entry point for the edge after that instead (c->a)\n\n            // There may be at most 1 edge that is parallel to X in a triangle.\n            // The main \"a->b\" edge must not be parallel at this point in the code.\n            // We know that \"a->b\" crosses the current cell row boundary, such that point \"b\" is beyond the boundary.\n            // If \"b->c\" is parallel to X, then \"c->a\" must not be parallel and must cross the cell row boundary back:\n            //      a\n            //      |\\\n            // -----|-\\--cell row boundary----\n            //      |  \\\n            //      c---b\n            // If \"b->c\" is not parallel to X and doesn't cross the cell row boundary,\n            // then c->a must also not be parallel to X and must cross the cell boundary back,\n            // since points \"a\" and \"c\" lie on different sides of the boundary and on different Y coordinates.\n            //\n            // Thus there is no need for \"parallel with X\" checks inside this condition branch.\n\n            // Compute the X coordinate where edge C->A enters the current cell row\n            const dir3X = aX - cX;\n            const dir3Y = aY - cY;\n            const t3Top = (cellRowYTop - cY) / dir3Y;\n            const t3Bottom = (cellRowYBottom - cY) / dir3Y;\n            const t3Enter = Math.min(t3Top, t3Bottom);\n            const enter3X = cX + dir3X * t3Enter;\n\n            boundarySubdivisionLeftCellX = Math.floor(Math.min(enter3X, exitX) / this._granularityCellSize) + 1;\n            boundarySubdivisionRightCellX = Math.ceil(Math.max(enter3X, exitX) / this._granularityCellSize) - 1;\n            isBoundaryLeftToRight = exitX < enter3X;\n        }\n\n        const boundaryY = dirY > 0 ? cellRowYBottom : cellRowYTop;\n        if (isBoundaryLeftToRight) {\n            // Left to right\n            for (let cellX = boundarySubdivisionLeftCellX; cellX <= boundarySubdivisionRightCellX; cellX++) {\n                const x = cellX * this._granularityCellSize;\n                ring.push(this._vertexToIndex(x, boundaryY));\n            }\n        } else {\n            // Right to left\n            for (let cellX = boundarySubdivisionRightCellX; cellX >= boundarySubdivisionLeftCellX; cellX--) {\n                const x = cellX * this._granularityCellSize;\n                ring.push(this._vertexToIndex(x, boundaryY));\n            }\n        }\n    }\n\n    /**\n     * Generates an outline for a given polygon, returns a list of arrays of line indices.\n     */\n    private _generateOutline(polygon: Point[][], inputRemap: number[]): number[][] {\n        const subdividedLines: number[][] = [];\n        let ringStart = 0;\n        for (const ring of polygon) {\n            const pathIndices = this._granularity < 2 ?\n                this._ringPathIndices(ring, ringStart, inputRemap) :\n                this._pointArrayToIndices(subdivideVertexLine(ring, this._granularity, true));\n            ringStart += ring.length;\n            // Points returned by subdivideVertexLine are \"path\" waypoints,\n            // for example with indices 0 1 2 3 0.\n            // We need list of individual line segments for rendering,\n            // for example 0, 1, 1, 2, 2, 3, 3, 0.\n            const lineIndices: number[] = [];\n            for (let i = 1; i < pathIndices.length; i++) {\n                lineIndices.push(pathIndices[i - 1]);\n                lineIndices.push(pathIndices[i]);\n            }\n            subdividedLines.push(lineIndices);\n        }\n        return subdividedLines;\n    }\n\n    /**\n     * The outline path `subdivideVertexLine(ring, granularity, true)` returns when the granularity is too low to\n     * subdivide, as vertex buffer indices rather than points, read from `inputRemap` instead of looked up per point.\n     */\n    private _ringPathIndices(ring: Point[], start: number, inputRemap: number[]): number[] {\n        const indices = inputRemap.slice(start, start + ring.length);\n        if (indices.length >= 2 && ringIsOpen(ring)) {\n            indices.push(indices[0]);\n        }\n        return indices;\n    }\n\n    /**\n     * Adds pole geometry if needed.\n     * @param subdividedTriangles - Array of generated triangle indices, new pole geometry is appended here.\n     */\n    private _handlePoles(subdividedTriangles: number[]) {\n        // Add pole vertices if the tile is at north/south mercator edge\n        let north = false;\n        let south = false;\n        if (this._canonical) {\n            if (this._canonical.y === 0) {\n                north = true;\n            }\n            if (this._canonical.y === (1 << this._canonical.z) - 1) {\n                south = true;\n            }\n        }\n        if (north || south) {\n            this._fillPoles(subdividedTriangles, north, south);\n        }\n    }\n\n    /**\n     * Checks the internal vertex buffer for all vertices that might lie on the special pole coordinates and shifts them by one unit.\n     * Use for removing unintended pole vertices that might have been created during subdivision. After calling this function, actual pole vertices can be safely generated.\n     */\n    private _ensureNoPoleVertices() {\n        const flattened = this._vertexBuffer;\n\n        for (let i = 0; i < flattened.length; i += 2) {\n            const vy = flattened[i + 1];\n            if (vy === NORTH_POLE_Y) {\n                // Move slightly down\n                flattened[i + 1] = NORTH_POLE_Y + 1;\n            }\n            if (vy === SOUTH_POLE_Y) {\n                // Move slightly down\n                flattened[i + 1] = SOUTH_POLE_Y - 1;\n            }\n        }\n    }\n\n    /**\n     * Generates a quad from an edge to a pole with the correct winding order.\n     * Helper function used inside {@link _fillPoles}.\n     * @param indices - Index array into which the geometry is generated.\n     * @param i0 - Index of the first edge vertex.\n     * @param i1 - Index of the second edge vertex.\n     * @param v0x - X coordinate of the first edge vertex.\n     * @param v1x - X coordinate of the second edge vertex.\n     * @param poleY - The Y coordinate of the desired pole (NORTH_POLE_Y or SOUTH_POLE_Y).\n     */\n    private _generatePoleQuad(indices, i0, i1, v0x, v1x, poleY): void {\n        const flip = (v0x > v1x) !== (poleY === NORTH_POLE_Y);\n\n        if (flip) {\n            indices.push(i0);\n            indices.push(i1);\n            indices.push(this._vertexToIndex(v0x, poleY));\n\n            indices.push(i1);\n            indices.push(this._vertexToIndex(v1x, poleY));\n            indices.push(this._vertexToIndex(v0x, poleY));\n        } else {\n            indices.push(i1);\n            indices.push(i0);\n            indices.push(this._vertexToIndex(v0x, poleY));\n\n            indices.push(this._vertexToIndex(v1x, poleY));\n            indices.push(i1);\n            indices.push(this._vertexToIndex(v0x, poleY));\n        }\n    }\n\n    /**\n     * Detects edges that border the north or south tile edge\n     * and adds triangles that extend those edges to the poles.\n     * Only run this function on tiles that border the poles.\n     * Assumes that supplied geometry is clipped to the inclusive range of 0..EXTENT.\n     * Mutates the supplies vertex and index arrays.\n     * @param indices - Triangle indices. This array is appended with new primitives.\n     * @param north - Whether to generate geometry for the north pole.\n     * @param south - Whether to generate geometry for the south pole.\n     */\n    private _fillPoles(indices: number[], north: boolean, south: boolean): void {\n        const flattened = this._vertexBuffer;\n\n        const northEdge = 0;\n        const southEdge = EXTENT;\n\n        const numIndices = indices.length;\n        for (let primitiveIndex = 2; primitiveIndex < numIndices; primitiveIndex += 3) {\n            const i0 = indices[primitiveIndex - 2];\n            const i1 = indices[primitiveIndex - 1];\n            const i2 = indices[primitiveIndex];\n            const v0x = flattened[i0 * 2];\n            const v0y = flattened[i0 * 2 + 1];\n            const v1x = flattened[i1 * 2];\n            const v1y = flattened[i1 * 2 + 1];\n            const v2x = flattened[i2 * 2];\n            const v2y = flattened[i2 * 2 + 1];\n\n            if (north) {\n                if (v0y === northEdge && v1y === northEdge) {\n                    this._generatePoleQuad(indices, i0, i1, v0x, v1x, NORTH_POLE_Y);\n                }\n                if (v1y === northEdge && v2y === northEdge) {\n                    this._generatePoleQuad(indices, i1, i2, v1x, v2x, NORTH_POLE_Y);\n                }\n                if (v2y === northEdge && v0y === northEdge) {\n                    this._generatePoleQuad(indices, i2, i0, v2x, v0x, NORTH_POLE_Y);\n                }\n            }\n            if (south) {\n                if (v0y === southEdge && v1y === southEdge) {\n                    this._generatePoleQuad(indices, i0, i1, v0x, v1x, SOUTH_POLE_Y);\n                }\n                if (v1y === southEdge && v2y === southEdge) {\n                    this._generatePoleQuad(indices, i1, i2, v1x, v2x, SOUTH_POLE_Y);\n                }\n                if (v2y === southEdge && v0y === southEdge) {\n                    this._generatePoleQuad(indices, i2, i0, v2x, v0x, SOUTH_POLE_Y);\n                }\n            }\n        }\n    }\n\n    /**\n     * Adds all vertices in the supplied flattened vertex buffer into the internal vertex buffer.\n     * @returns The index into the internal vertex buffer for each input vertex, in the order `flatten` produced them.\n     */\n    private _initializeVertices(flattened: number[]): number[] {\n        const inputRemap: number[] = [];\n        for (let i = 0; i < flattened.length; i += 2) {\n            inputRemap.push(this._vertexToIndex(flattened[i], flattened[i + 1]));\n        }\n        return inputRemap;\n    }\n\n    /**\n     * Subdivides an input mesh. Imagine a regular square grid with the target granularity overlaid over the mesh - this is the subdivision's result.\n     * Assumes a mesh of tile features - vertex coordinates are integers, visible range where subdivision happens is 0..8192.\n     * @param polygon - The input polygon, specified as a list of vertex rings.\n     * @param generateOutlineLines - When true, also generates line indices for outline of the supplied polygon.\n     * @returns Vertex and index buffers with subdivision applied.\n     */\n    public subdividePolygonInternal(polygon: Point[][], generateOutlineLines: boolean): SubdivisionResult {\n        if (this._used) {\n            throw new Error('Subdivision: multiple use not allowed.');\n        }\n        this._used = true;\n\n        // Initialize the vertex dictionary with input vertices since we will use all of them anyway\n        const {flattened, holeIndices} = flatten(polygon);\n        const inputRemap = this._initializeVertices(flattened);\n\n        // Subdivide triangles\n        let subdividedTriangles: number[];\n        try {\n            const earcutResult = earcut(flattened, holeIndices);\n            subdividedTriangles = this._subdivideTrianglesScanline(earcutResult, inputRemap);\n        } catch (e) {\n            console.error(e);\n        }\n\n        // Subdivide lines\n        let subdividedLines: number[][] = [];\n        if (generateOutlineLines) {\n            subdividedLines = this._generateOutline(polygon, inputRemap);\n        }\n\n        // Ensure no vertex has the special value used for pole vertices\n        this._ensureNoPoleVertices();\n\n        // Add pole geometry if needed\n        this._handlePoles(subdividedTriangles);\n\n        if (this._granularity >= 2 && this._canonical?.z === 0) {\n            subdividedTriangles = this._removeTrianglesOutsideTileX(subdividedTriangles);\n            subdividedLines = subdividedLines.map(lines => this._removeLinesOutsideTileX(lines));\n        }\n\n        return {\n            verticesFlattened: this._vertexBuffer,\n            indicesTriangles: subdividedTriangles,\n            indicesLineList: subdividedLines,\n        };\n    }\n\n    private _vertexOutsideTileX(index: number): boolean {\n        const x = this._vertexBuffer[index * 2];\n        return x < 0 || x > EXTENT;\n    }\n\n    /**\n     * Drops all triangles that reach beyond the tile's X extent.\n     *\n     * On globe the z0 tile's buffer wraps around the planet onto the tile itself, drawing buffered geometry twice.\n     * Only globe uses subdivision (`granularity >= 2`), so mercator is never affected.\n     * @param indices - Triangle indices into `this._vertexBuffer`.\n     * @returns The indices with every triangle that has a vertex outside the tile's X extent removed.\n     */\n    private _removeTrianglesOutsideTileX(indices: number[]): number[] {\n        const filtered: number[] = [];\n        for (let i = 0; i < indices.length; i += 3) {\n            if (this._vertexOutsideTileX(indices[i]) || this._vertexOutsideTileX(indices[i + 1]) || this._vertexOutsideTileX(indices[i + 2])) {\n                continue;\n            }\n            filtered.push(indices[i], indices[i + 1], indices[i + 2]);\n        }\n        return filtered;\n    }\n\n    /**\n     * Drops all outline line segments that reach beyond the tile's X extent,\n     * for the same reason as {@link Subdivider._removeTrianglesOutsideTileX}.\n     * @param indices - Line segment indices into `this._vertexBuffer`.\n     * @returns The indices with every segment that has a vertex outside the tile's X extent removed.\n     */\n    private _removeLinesOutsideTileX(indices: number[]): number[] {\n        const filtered: number[] = [];\n        for (let i = 0; i < indices.length; i += 2) {\n            if (this._vertexOutsideTileX(indices[i]) || this._vertexOutsideTileX(indices[i + 1])) {\n                continue;\n            }\n            filtered.push(indices[i], indices[i + 1]);\n        }\n        return filtered;\n    }\n\n    /**\n     * Converts an array of points into an array of indices into the internal vertex buffer (`_finalVertices`).\n     */\n    private _pointArrayToIndices(array: Point[]): number[] {\n        const indices = [];\n        for (const p of array) {\n            indices.push(this._vertexToIndex(p.x, p.y));\n        }\n        return indices;\n    }\n}\n\n/**\n * Subdivides a polygon to a given granularity. Intended for preprocessing geometry for the 'fill' and 'fill-extrusion' layer types.\n * All returned triangles have the counter-clockwise winding order.\n * @param polygon - An array of point rings that specify the polygon. The first ring is the polygon exterior, all subsequent rings form holes inside the first ring.\n * @param canonical - The canonical tile ID of the tile this polygon belongs to. Needed for generating special geometry for tiles that border the poles.\n * @param granularity - The subdivision granularity. If we assume tile EXTENT=8192, then a granularity of 2 will result in geometry being \"cut\" on each axis\n * divisible by 4096 (including outside the tile range, so -8192, -4096, or 12288...), granularity of 8 on axes divisible by 1024 and so on.\n * Granularity of 1 or lower results in *no* subdivision.\n * @param generateOutlineLines - When true, also generates index arrays for subdivided lines that form the outline of the supplied polygon. True by default.\n * @returns An object that contains the generated vertex array, triangle index array and, if specified, line index arrays.\n */\nexport function subdividePolygon(polygon: Point[][], canonical: CanonicalTileID, granularity: number, generateOutlineLines: boolean = true): SubdivisionResult {\n    const subdivider = new Subdivider(granularity, canonical);\n    return subdivider.subdividePolygonInternal(polygon, generateOutlineLines);\n}\n\n/**\n * Subdivides a line represented by an array of points. Mainly intended for preprocessing geometry for the 'line' layer type.\n * Assumes a line segment between each two consecutive points in the array.\n * Does not assume a line segment from last point to first point, unless `isRing` is set to `true`.\n * For example, an array of 4 points describes exactly 3 line segments.\n * @param linePoints - An array of points describing the line segments.\n * @param granularity - Subdivision granularity.\n * @param isRing - When true, an additional line segment is assumed to exist between the input array's last and first point.\n * @returns A new array of points of the subdivided line segments. The array may contain some of the original Point objects. If `isRing` is set to `true`, then this also includes the (subdivided) segment from the last point of the input array to the first point.\n *\n * @example\n * ```ts\n * const result = subdivideVertexLine([\n *   new Point(0, 0),\n *   new Point(8, 0),\n *   new Point(0, 8),\n * ], EXTENT / 4, false);\n * // Results in an array of points with these (x, y) coordinates:\n * //   0, 0\n * //   4, 0\n * //   8, 0\n * //   4, 4\n * //   0, 8\n * ```\n *\n * @example\n * ```ts\n * const result = subdivideVertexLine([\n *   new Point(0, 0),\n *   new Point(8, 0),\n *   new Point(0, 8),\n * ], EXTENT / 4, true);\n * // Results in an array of points with these (x, y) coordinates:\n * //   0, 0\n * //   4, 0\n * //   8, 0\n * //   4, 4\n * //   0, 8\n * //   0, 4\n * //   0, 0\n * ```\n */\nexport function subdivideVertexLine(linePoints: Point[], granularity: number, isRing: boolean = false): Point[] {\n    if (!linePoints || linePoints.length < 1) {\n        return [];\n    }\n\n    if (linePoints.length < 2) {\n        return [];\n    }\n\n    // Generate an extra line segment between the input array's first and last points,\n    // but only if isRing=true AND the first and last points actually differ.\n    const addLastToFirstSegment = isRing && ringIsOpen(linePoints);\n\n    if (granularity < 2) {\n        if (addLastToFirstSegment) {\n            return [...linePoints, linePoints[0]];\n        } else {\n            return [...linePoints];\n        }\n    }\n\n    const cellSize = Math.floor(EXTENT / granularity);\n    const finalLineVertices: Point[] = [];\n\n    finalLineVertices.push(new Point(linePoints[0].x, linePoints[0].y));\n\n    // Iterate over all input lines\n    const totalPoints = linePoints.length;\n    const lastIndex = addLastToFirstSegment ? totalPoints : (totalPoints - 1);\n    for (let pointIndex = 0; pointIndex < lastIndex; pointIndex++) {\n        const linePoint0 = linePoints[pointIndex];\n        const linePoint1 = pointIndex < (totalPoints - 1) ? linePoints[pointIndex + 1] : linePoints[0];\n        const lineVertex0x = linePoint0.x;\n        const lineVertex0y = linePoint0.y;\n        const lineVertex1x = linePoint1.x;\n        const lineVertex1y = linePoint1.y;\n\n        const dirXnonZero = lineVertex0x !== lineVertex1x;\n        const dirYnonZero = lineVertex0y !== lineVertex1y;\n\n        if (!dirXnonZero && !dirYnonZero) {\n            continue;\n        }\n\n        const dirX = lineVertex1x - lineVertex0x;\n        const dirY = lineVertex1y - lineVertex0y;\n        const absDirX = Math.abs(dirX);\n        const absDirY = Math.abs(dirY);\n\n        let lastPointX = lineVertex0x;\n        let lastPointY = lineVertex0y;\n\n        // Walk along the line segment from start to end. In every step,\n        // find out the distance from start until the line intersects either the X-parallel or Y-parallel subdivision axis.\n        // Pick the closer intersection, add it to the final line points and consider that point the new start of the line.\n        // But also make sure the intersection point does not lie beyond the end of the line.\n        // If none of the intersection points is closer than line end, add the endpoint to the final line and break the loop.\n\n        while (true) {\n            const nextBoundaryX = dirX > 0 ?\n                ((Math.floor(lastPointX / cellSize) + 1) * cellSize) :\n                ((Math.ceil(lastPointX / cellSize) - 1) * cellSize);\n            const nextBoundaryY = dirY > 0 ?\n                ((Math.floor(lastPointY / cellSize) + 1) * cellSize) :\n                ((Math.ceil(lastPointY / cellSize) - 1) * cellSize);\n            const axisDistanceToBoundaryX = Math.abs(lastPointX - nextBoundaryX);\n            const axisDistanceToBoundaryY = Math.abs(lastPointY - nextBoundaryY);\n\n            const axisDistanceToEndX = Math.abs(lastPointX - lineVertex1x);\n            const axisDistanceToEndY = Math.abs(lastPointY - lineVertex1y);\n\n            const realDistanceToBoundaryX = dirXnonZero ? axisDistanceToBoundaryX / absDirX : Number.POSITIVE_INFINITY;\n            const realDistanceToBoundaryY = dirYnonZero ? axisDistanceToBoundaryY / absDirY : Number.POSITIVE_INFINITY;\n\n            if ((axisDistanceToEndX <= axisDistanceToBoundaryX || !dirXnonZero) &&\n            (axisDistanceToEndY <= axisDistanceToBoundaryY || !dirYnonZero)) {\n                break;\n            }\n\n            if ((realDistanceToBoundaryX < realDistanceToBoundaryY && dirXnonZero) || !dirYnonZero) {\n                // We hit the X cell boundary first\n                // Always consider the X cell hit if Y dir is zero\n                lastPointX = nextBoundaryX;\n                lastPointY = lastPointY + dirY * realDistanceToBoundaryX;\n                const next = new Point(lastPointX, Math.round(lastPointY));\n\n                // Do not add the next vertex if it is equal to the last added vertex\n                if (finalLineVertices[finalLineVertices.length - 1].x !== next.x ||\n                    finalLineVertices[finalLineVertices.length - 1].y !== next.y) {\n                    finalLineVertices.push(next);\n                }\n            } else {\n                lastPointX = lastPointX + dirX * realDistanceToBoundaryY;\n                lastPointY = nextBoundaryY;\n                const next = new Point(Math.round(lastPointX), lastPointY);\n\n                if (finalLineVertices[finalLineVertices.length - 1].x !== next.x ||\n                    finalLineVertices[finalLineVertices.length - 1].y !== next.y) {\n                    finalLineVertices.push(next);\n                }\n            }\n        }\n\n        const last = new Point(lineVertex1x, lineVertex1y);\n        if (finalLineVertices[finalLineVertices.length - 1].x !== last.x ||\n            finalLineVertices[finalLineVertices.length - 1].y !== last.y) {\n            finalLineVertices.push(last);\n        }\n    }\n\n    return finalLineVertices;\n}\n\n/**\n * Whether a ring's last vertex differs from its first, so that drawing it needs a closing segment.\n */\nfunction ringIsOpen(ring: Point[]): boolean {\n    return !ring[0].equals(ring[ring.length - 1]);\n}\n\n/**\n * Takes a polygon as an array of point rings, returns a flattened array of the X,Y coordinates of these points.\n * Also creates an array of hole indices. Both returned arrays are required for `earcut`.\n */\nfunction flatten(polygon: Point[][]): {\n    flattened: number[];\n    holeIndices: number[];\n} {\n    const holeIndices = [];\n    const flattened = [];\n\n    for (const ring of polygon) {\n        if (ring.length === 0) {\n            continue;\n        }\n\n        if (ring !== polygon[0]) {\n            holeIndices.push(flattened.length / 2);\n        }\n\n        for (const vertex of ring) {\n            flattened.push(vertex.x);\n            flattened.push(vertex.y);\n        }\n    }\n\n    return {\n        flattened,\n        holeIndices\n    };\n}\n\n/**\n * Returns a copy of `indices` where every index is replaced by `remap[index]`.\n * @param indices - Indices into the array `remap` was built for.\n * @param remap - The replacement for each index.\n */\nfunction remapIndices(indices: number[], remap: number[]): number[] {\n    const remapped = new Array(indices.length);\n    for (let i = 0; i < indices.length; i++) {\n        remapped[i] = remap[indices[i]];\n    }\n    return remapped;\n}\n\n/**\n * Returns a new array of indices where all triangles have the counter-clockwise winding order.\n * @param flattened - Flattened vertex buffer.\n * @param indices - Triangle indices.\n */\nexport function fixWindingOrder(flattened: number[], indices: number[]): number[] {\n    const corrected = [];\n\n    for (let i = 0; i < indices.length; i += 3) {\n        const i0 = indices[i];\n        const i1 = indices[i + 1];\n        const i2 = indices[i + 2];\n\n        const v0x = flattened[i0 * 2];\n        const v0y = flattened[i0 * 2 + 1];\n        const v1x = flattened[i1 * 2];\n        const v1y = flattened[i1 * 2 + 1];\n        const v2x = flattened[i2 * 2];\n        const v2y = flattened[i2 * 2 + 1];\n\n        const e0x = v1x - v0x;\n        const e0y = v1y - v0y;\n        const e1x = v2x - v0x;\n        const e1y = v2y - v0y;\n\n        const crossProduct = e0x * e1y - e0y * e1x;\n\n        if (crossProduct > 0) {\n            // Flip\n            corrected.push(i0);\n            corrected.push(i2);\n            corrected.push(i1);\n        } else {\n            // Don't flip\n            corrected.push(i0);\n            corrected.push(i1);\n            corrected.push(i2);\n        }\n    }\n\n    return corrected;\n}\n\n/**\n * Triangulates a ring of vertex indices. Appends to the supplied array of final triangle indices.\n * @param vertexBuffer - Flattened vertex coordinate array.\n * @param ring - Ordered ring of vertex indices to triangulate.\n * @param leftmostIndex - The index of the leftmost vertex in the supplied ring.\n * @param finalIndices - Array of final triangle indices, into where the resulting triangles are appended.\n */\nexport function scanlineTriangulateVertexRing(vertexBuffer: number[], ring: number[], finalIndices: number[]): void {\n    // Triangulate the ring\n    // It is guaranteed to be convex and ordered\n    if (ring.length === 0) {\n        throw new Error('Subdivision vertex ring is empty.');\n    }\n\n    // Find the leftmost vertex in the ring\n    let leftmostIndex = 0;\n    let leftmostX = vertexBuffer[ring[0] * 2];\n    for (let i = 1; i < ring.length; i++) {\n        const x = vertexBuffer[ring[i] * 2];\n        if (x < leftmostX) {\n            leftmostX = x;\n            leftmostIndex = i;\n        }\n    }\n\n    // Traverse the ring in both directions from the leftmost vertex\n    // Assume ring is in CCW order (to produce CCW triangles)\n    const ringVertexLength = ring.length;\n    let lastEdgeA = leftmostIndex;\n    let lastEdgeB = (lastEdgeA + 1) % ringVertexLength;\n\n    while (true) {\n        const candidateIndexA = (lastEdgeA - 1) >= 0 ? (lastEdgeA - 1) : (ringVertexLength - 1);\n        const candidateIndexB = (lastEdgeB + 1) % ringVertexLength;\n\n        // Pick candidate, move edge\n        const candidateAx = vertexBuffer[ring[candidateIndexA] * 2];\n        const candidateAy = vertexBuffer[ring[candidateIndexA] * 2 + 1];\n        const candidateBx = vertexBuffer[ring[candidateIndexB] * 2];\n        const candidateBy = vertexBuffer[ring[candidateIndexB] * 2 + 1];\n        const lastEdgeAx = vertexBuffer[ring[lastEdgeA] * 2];\n        const lastEdgeAy = vertexBuffer[ring[lastEdgeA] * 2 + 1];\n        const lastEdgeBx = vertexBuffer[ring[lastEdgeB] * 2];\n        const lastEdgeBy = vertexBuffer[ring[lastEdgeB] * 2 + 1];\n\n        let pickA = false;\n\n        if (candidateAx < candidateBx) {\n            pickA = true;\n        } else if (candidateAx > candidateBx) {\n            pickA = false;\n        } else {\n            // Pick the candidate that is more \"right\" of the last edge's line\n            const nx = lastEdgeBy - lastEdgeAy;\n            const ny = -(lastEdgeBx - lastEdgeAx);\n            const sign = (lastEdgeAy < lastEdgeBy) ? 1 : -1;\n            // dot( (candidateA <-- lastEdgeA), normal )\n            const aRight = ((candidateAx - lastEdgeAx) * nx + (candidateAy - lastEdgeAy) * ny) * sign;\n            // dot( (candidateB <-- lastEdgeA), normal )\n            const bRight = ((candidateBx - lastEdgeAx) * nx + (candidateBy - lastEdgeAy) * ny) * sign;\n            if (aRight > bRight) {\n                pickA = true;\n            }\n        }\n\n        if (pickA) {\n            // Pick candidate A\n            const c = ring[candidateIndexA];\n            const a = ring[lastEdgeA];\n            const b = ring[lastEdgeB];\n            if (c !== a && c !== b && a !== b) {\n                finalIndices.push(b, a, c);\n            }\n            lastEdgeA--;\n            if (lastEdgeA < 0) {\n                lastEdgeA = ringVertexLength - 1;\n            }\n        } else {\n            // Pick candidate B\n            const c = ring[candidateIndexB];\n            const a = ring[lastEdgeA];\n            const b = ring[lastEdgeB];\n            if (c !== a && c !== b && a !== b) {\n                finalIndices.push(b, a, c);\n            }\n            lastEdgeB++;\n            if (lastEdgeB >= ringVertexLength) {\n                lastEdgeB = 0;\n            }\n        }\n\n        if (candidateIndexA === candidateIndexB) {\n            break; // We ran out of ring vertices\n        }\n    }\n}\n", "import {type Segment, SegmentVector} from '../data/segment.ts';\n\nimport type {LineIndexArray, TriangleIndexArray} from '../data/array_types.g.ts';\nimport type {StructArray} from '../util/struct_array.ts';\n\n/**\n * This function will take any \"mesh\" and fill in into vertex buffers, breaking it up into multiple drawcalls as needed\n * if too many (\\>65535) vertices are used.\n * This function is mainly intended for use with subdivided geometry, since sometimes subdivision might generate\n * more vertices than what fits into 16 bit indices.\n *\n * Accepts a triangle mesh, optionally with a line list (for fill outlines) as well. The triangle and line segments are expected to share a single vertex buffer.\n *\n * Mutates the provided `segmentsTriangles` and `segmentsLines` SegmentVectors,\n * `vertexArray`, `triangleIndexArray` and optionally `lineIndexArray`.\n * Does not mutate the input `flattened` vertices, `triangleIndices` and `lineList`.\n * @param addVertex - A function for adding a new vertex into `vertexArray`. We might sometimes want to add more values per vertex than just X and Y coordinates, which can be handled in this function.\n * @param segmentsTriangles - The segment array for triangle draw calls. New segments will be placed here.\n * @param vertexArray - The vertex array into which new vertices are placed by the provided `addVertex` function.\n * @param triangleIndexArray - Index array for drawing triangles. New triangle indices are placed here.\n * @param flattened - The input flattened array or vertex coordinates.\n * @param triangleIndices - Triangle indices into `flattened`.\n * @param segmentsLines - Segment array for line draw calls. New segments will be placed here. Only needed if the mesh also contains lines.\n * @param lineIndexArray - Index array for drawing lines. New triangle indices are placed here. Only needed if the mesh also contains lines.\n * @param lineList - Line indices into `flattened`. Only needed if the mesh also contains lines.\n */\nexport function fillLargeMeshArrays(\n    addVertex: (x: number, y: number) => void,\n    segmentsTriangles: SegmentVector,\n    vertexArray: StructArray,\n    triangleIndexArray: TriangleIndexArray,\n    flattened: number[],\n    triangleIndices: number[],\n    segmentsLines?: SegmentVector,\n    lineIndexArray?: LineIndexArray,\n    lineList?: number[][]): void {\n\n    const numVertices = flattened.length / 2;\n    const hasLines = segmentsLines && lineIndexArray && lineList;\n\n    if (numVertices < SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n        // The fast path - no segmentation needed\n        const triangleSegment = segmentsTriangles.prepareSegment(numVertices, vertexArray, triangleIndexArray);\n        const triangleIndex = triangleSegment.vertexLength;\n\n        for (let i = 0; i < triangleIndices.length; i += 3) {\n            triangleIndexArray.emplaceBack(\n                triangleIndex + triangleIndices[i],\n                triangleIndex + triangleIndices[i + 1],\n                triangleIndex + triangleIndices[i + 2]);\n        }\n\n        triangleSegment.vertexLength += numVertices;\n        triangleSegment.primitiveLength += triangleIndices.length / 3;\n\n        let lineIndicesStart: number;\n        let lineSegment: Segment;\n\n        if (hasLines) {\n            // Note that segment creation must happen *before* we add vertices into the vertex buffer\n            lineSegment = segmentsLines.prepareSegment(numVertices, vertexArray, lineIndexArray);\n            lineIndicesStart = lineSegment.vertexLength;\n            lineSegment.vertexLength += numVertices;\n        }\n\n        // Add vertices into vertex buffer\n        for (let i = 0; i < flattened.length; i += 2) {\n            addVertex(flattened[i], flattened[i + 1]);\n        }\n\n        if (hasLines) {\n            for (const lineIndices of lineList) {\n\n                for (let i = 1; i < lineIndices.length; i += 2) {\n                    lineIndexArray.emplaceBack(\n                        lineIndicesStart + lineIndices[i - 1],\n                        lineIndicesStart + lineIndices[i]);\n                }\n\n                lineSegment.primitiveLength += lineIndices.length / 2;\n            }\n        }\n    } else {\n        // Assumption: the incoming triangle indices use vertices in roughly linear order,\n        // for example a grid of quads where both vertices and quads are created row by row would satisfy this.\n        // Some completely random arbitrary vertex/triangle order would not.\n        // Thus, if we encounter a vertex that doesn't fit into MAX_VERTEX_ARRAY_LENGTH,\n        // we can just stop appending into the old segment and start a new segment and only append to the new segment,\n        // copying vertices that are already present in the old segment into the new segment if needed,\n        // because there will not be too many of such vertices.\n\n        // Normally, (out)lines share the same vertex buffer as triangles, but since we need to somehow split it into several drawcalls,\n        // it is easier to just consider (out)lines separately and duplicate their vertices.\n\n        fillSegmentsTriangles(segmentsTriangles, vertexArray, triangleIndexArray, flattened, triangleIndices, addVertex);\n        if (hasLines) {\n            fillSegmentsLines(segmentsLines, vertexArray, lineIndexArray, flattened, lineList, addVertex);\n        }\n\n        // Triangles and lines share the same vertex buffer, and they usually also share the same vertices.\n        // But this method might create the vertices for triangles and for lines separately, and thus increasing the vertex count\n        // of the triangle and line segments by different amounts.\n\n        // The non-splitting fillLargeMeshArrays logic (and old fill-bucket logic) assumes the vertex counts to be the same,\n        // and forcing both SegmentVectors to return a new segment upon next prepare call satisfies this.\n        segmentsTriangles.forceNewSegmentOnNextPrepare();\n        segmentsLines?.forceNewSegmentOnNextPrepare();\n    }\n}\n\n/**\n * Determines the new index of a vertex given by its old index.\n * @param actualVertexIndices - Array that maps the old index of a given vertex to a new index in the final vertex buffer.\n * @param flattened - Old vertex buffer.\n * @param addVertex - Function for creating a new vertex in the final vertex buffer.\n * @param totalVerticesCreated - Reference to an int holding how many vertices were added to the final vertex buffer.\n * @param oldIndex - The old index of the desired vertex.\n * @param needsCopy - Whether to duplicate the desired vertex in the final vertex buffer.\n * @param segment - The current segment.\n * @returns Index of the vertex in the final vertex array.\n */\nfunction copyOrReuseVertex(\n    actualVertexIndices: number[],\n    flattened: number[],\n    addVertex: (x: number, y: number) => void,\n    totalVerticesCreated: {count: number},\n    oldIndex: number,\n    needsCopy: boolean,\n    segment: Segment\n): number {\n    if (needsCopy) {\n        const newIndex = totalVerticesCreated.count;\n        addVertex(flattened[oldIndex * 2], flattened[oldIndex * 2 + 1]);\n        actualVertexIndices[oldIndex] = totalVerticesCreated.count;\n        totalVerticesCreated.count++;\n        segment.vertexLength++;\n        return newIndex;\n    } else {\n        return actualVertexIndices[oldIndex];\n    }\n}\n\nfunction fillSegmentsTriangles(\n    segmentsTriangles: SegmentVector,\n    vertexArray: StructArray,\n    triangleIndexArray: TriangleIndexArray,\n    flattened: number[],\n    triangleIndices: number[],\n    addVertex: (x: number, y: number) => void\n) {\n    // Array, or rather a map of [vertex index in the original data] -> index of the latest copy of this vertex in the final vertex buffer.\n    const actualVertexIndices: number[] = [];\n    for (let i = 0; i < flattened.length / 2; i++) {\n        actualVertexIndices.push(-1);\n    }\n\n    const totalVerticesCreated = {count: 0};\n\n    let currentSegmentCutoff = 0;\n    let segment = segmentsTriangles.getOrCreateLatestSegment(vertexArray, triangleIndexArray);\n    let baseVertex = segment.vertexLength;\n\n    for (let primitiveEndIndex = 2; primitiveEndIndex < triangleIndices.length; primitiveEndIndex += 3) {\n        const i0 = triangleIndices[primitiveEndIndex - 2];\n        const i1 = triangleIndices[primitiveEndIndex - 1];\n        const i2 = triangleIndices[primitiveEndIndex];\n\n        let i0needsVertexCopy = actualVertexIndices[i0] < currentSegmentCutoff;\n        let i1needsVertexCopy = actualVertexIndices[i1] < currentSegmentCutoff;\n        let i2needsVertexCopy = actualVertexIndices[i2] < currentSegmentCutoff;\n\n        const vertexCopyCount = (i0needsVertexCopy ? 1 : 0) + (i1needsVertexCopy ? 1 : 0) + (i2needsVertexCopy ? 1 : 0);\n\n        // Will needed vertex copies fit into this segment?\n        if (segment.vertexLength + vertexCopyCount > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n            // Break up into a new segment if not.\n            segment = segmentsTriangles.createNewSegment(vertexArray, triangleIndexArray);\n            currentSegmentCutoff = totalVerticesCreated.count;\n            i0needsVertexCopy = true;\n            i1needsVertexCopy = true;\n            i2needsVertexCopy = true;\n            baseVertex = 0;\n        }\n\n        const actualIndex0 = copyOrReuseVertex(\n            actualVertexIndices, flattened, addVertex, totalVerticesCreated,\n            i0, i0needsVertexCopy, segment);\n        const actualIndex1 = copyOrReuseVertex(\n            actualVertexIndices, flattened, addVertex, totalVerticesCreated,\n            i1, i1needsVertexCopy, segment);\n        const actualIndex2 = copyOrReuseVertex(\n            actualVertexIndices, flattened, addVertex, totalVerticesCreated,\n            i2, i2needsVertexCopy, segment);\n\n        triangleIndexArray.emplaceBack(\n            baseVertex + actualIndex0 - currentSegmentCutoff,\n            baseVertex + actualIndex1 - currentSegmentCutoff,\n            baseVertex + actualIndex2 - currentSegmentCutoff\n        );\n\n        segment.primitiveLength++;\n    }\n}\n\nfunction fillSegmentsLines(\n    segmentsLines: SegmentVector,\n    vertexArray: StructArray,\n    lineIndexArray: LineIndexArray,\n    flattened: number[],\n    lineList: number[][],\n    addVertex: (x: number, y: number) => void\n) {\n    // Array, or rather a map of [vertex index in the original data] -> index of the latest copy of this vertex in the final vertex buffer.\n    const actualVertexIndices: number[] = [];\n    for (let i = 0; i < flattened.length / 2; i++) {\n        actualVertexIndices.push(-1);\n    }\n\n    const totalVerticesCreated = {count: 0};\n\n    let currentSegmentCutoff = 0;\n    let segment = segmentsLines.getOrCreateLatestSegment(vertexArray, lineIndexArray);\n    let baseVertex = segment.vertexLength;\n\n    for (const currentLine of lineList) {\n        for (let lineVertex = 1; lineVertex < currentLine.length; lineVertex += 2) {\n            const i0 = currentLine[lineVertex - 1];\n            const i1 = currentLine[lineVertex];\n\n            let i0needsVertexCopy = actualVertexIndices[i0] < currentSegmentCutoff;\n            let i1needsVertexCopy = actualVertexIndices[i1] < currentSegmentCutoff;\n\n            const vertexCopyCount = (i0needsVertexCopy ? 1 : 0) + (i1needsVertexCopy ? 1 : 0);\n\n            // Will needed vertex copies fit into this segment?\n            if (segment.vertexLength + vertexCopyCount > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n                // Break up into a new segment if not.\n                segment = segmentsLines.createNewSegment(vertexArray, lineIndexArray);\n                currentSegmentCutoff = totalVerticesCreated.count;\n                i0needsVertexCopy = true;\n                i1needsVertexCopy = true;\n                baseVertex = 0;\n            }\n\n            const actualIndex0 = copyOrReuseVertex(\n                actualVertexIndices, flattened, addVertex, totalVerticesCreated,\n                i0, i0needsVertexCopy, segment);\n            const actualIndex1 = copyOrReuseVertex(\n                actualVertexIndices, flattened, addVertex, totalVerticesCreated,\n                i1, i1needsVertexCopy, segment);\n\n            lineIndexArray.emplaceBack(\n                baseVertex + actualIndex0 - currentSegmentCutoff,\n                baseVertex + actualIndex1 - currentSegmentCutoff\n            );\n\n            segment.primitiveLength++;\n        }\n    }\n}\n", "import {FillLayoutArray} from '../array_types.g.ts';\nimport {members as layoutAttributes} from './fill_attributes.ts';\nimport {SegmentVector} from '../segment.ts';\nimport {ProgramConfigurationSet} from '../program_configuration.ts';\nimport {LineIndexArray, TriangleIndexArray} from '../index_array_type.ts';\nimport {classifyRings} from '@maplibre/maplibre-gl-style-spec';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer.ts';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features.ts';\nimport {loadGeometry} from '../load_geometry.ts';\nimport {toEvaluationFeature} from '../evaluation_feature.ts';\nimport {EvaluationParameters} from '../../style/evaluation_parameters.ts';\nimport {subdividePolygon} from '../../render/subdivision.ts';\nimport {fillLargeMeshArrays} from '../../render/fill_large_mesh_arrays.ts';\nimport {warnOnce} from '../../util/util.ts';\n\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {\n    Bucket,\n    BucketParameters,\n    BucketFeature,\n    BucketDependencyParameters,\n    IndexedFeature,\n    PopulateParameters\n} from '../bucket.ts';\nimport type {FillStyleLayer} from '../../style/style_layer/fill_style_layer.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {IndexBuffer} from '../../webgl/index_buffer.ts';\nimport type {VertexBuffer} from '../../webgl/vertex_buffer.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state.ts';\nimport type {ImagePosition} from '../../render/image_atlas.ts';\nimport type {SubdivisionGranularitySetting} from '../../render/subdivision_granularity_settings.ts';\nimport type {VectorTileLayerLike} from '@maplibre/vt-pbf';\nimport type {GetImagesResponse} from '../../util/actor_messages.ts';\nimport type {StyleImage} from '../../style/style_image.ts';\n\nexport class FillBucket implements Bucket {\n    index: number;\n    zoom: number;\n    overscaling: number;\n    layers: FillStyleLayer[];\n    layerIds: string[];\n    stateDependentLayers: FillStyleLayer[];\n    stateDependentLayerIds: string[];\n    patternFeatures: BucketFeature[];\n\n    layoutVertexArray: FillLayoutArray;\n    layoutVertexBuffer: VertexBuffer;\n\n    indexArray: TriangleIndexArray;\n    indexBuffer: IndexBuffer;\n\n    indexArray2: LineIndexArray;\n    indexBuffer2: IndexBuffer;\n\n    hasDependencies: boolean;\n    sdfPatterns: Record<string, boolean>;\n    programConfigurations: ProgramConfigurationSet<FillStyleLayer>;\n    segments: SegmentVector;\n    segments2: SegmentVector;\n    uploaded: boolean;\n\n    constructor(options: BucketParameters<FillStyleLayer>) {\n        this.zoom = options.zoom;\n        this.overscaling = options.overscaling;\n        this.layers = options.layers;\n        this.layerIds = this.layers.map(layer => layer.id);\n        this.index = options.index;\n        this.hasDependencies = false;\n        this.sdfPatterns = {};\n        this.patternFeatures = [];\n\n        this.layoutVertexArray = new FillLayoutArray();\n        this.indexArray = new TriangleIndexArray();\n        this.indexArray2 = new LineIndexArray();\n        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n        this.segments = new SegmentVector();\n        this.segments2 = new SegmentVector();\n        this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n    }\n\n    populate(features: IndexedFeature[], options: PopulateParameters, canonical: CanonicalTileID): void {\n        this.hasDependencies = hasPattern('fill', this.layers, options);\n        const fillSortKey = this.layers[0].layout.get('fill-sort-key');\n        const sortFeaturesByKey = !fillSortKey.isConstant();\n        const bucketFeatures: BucketFeature[] = [];\n\n        const globalProperties = new EvaluationParameters(this.zoom);\n        const needGeometry = this.layers[0]._featureFilter.needGeometry;\n        for (const {feature, id, index, sourceLayerIndex} of features) {\n            const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n            if (!this.layers[0]._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue;\n\n            const sortKey = sortFeaturesByKey ?\n                fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) :\n                undefined;\n\n            const bucketFeature: BucketFeature = {\n                id,\n                properties: feature.properties,\n                type: feature.type,\n                sourceLayerIndex,\n                index,\n                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),\n                patterns: {},\n                sortKey\n            };\n\n            bucketFeatures.push(bucketFeature);\n        }\n\n        if (sortFeaturesByKey) {\n            bucketFeatures.sort((a, b) => a.sortKey - b.sortKey);\n        }\n\n        for (const bucketFeature of bucketFeatures) {\n            const {geometry, index, sourceLayerIndex} = bucketFeature;\n\n            if (this.hasDependencies) {\n                const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, {zoom: this.zoom}, options);\n                // pattern features are added only once the pattern is loaded into the image atlas\n                // so are stored during populate until later updated with positions by tile worker in addFeatures\n                this.patternFeatures.push(patternFeature);\n            } else {\n                this.addFeature(bucketFeature, geometry, index, canonical, {}, options.subdivisionGranularity);\n            }\n\n            const feature = features[index].feature;\n            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n        }\n    }\n\n    update(states: FeatureStates, vtLayer: VectorTileLayerLike, imagePositions: {\n        [_: string]: ImagePosition;\n    }): void {\n        if (!this.stateDependentLayers.length) return;\n        this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, {\n            imagePositions\n        });\n    }\n\n    addFeatures({options, canonical, patternPositions, patternMap}: BucketDependencyParameters): void {\n        this.detectSdfPatterns(patternMap);\n        for (const feature of this.patternFeatures) {\n            this.addFeature(feature, feature.geometry, feature.index, canonical, patternPositions, options.subdivisionGranularity);\n        }\n    }\n\n    private detectSdfPatterns(imageMap: GetImagesResponse): void {\n        for (const feature of this.patternFeatures) {\n            for (const layerId in feature.patterns) {\n                const pattern = feature.patterns[layerId];\n                this.recordSdfPattern(layerId, imageMap[pattern.min]);\n                this.recordSdfPattern(layerId, imageMap[pattern.mid]);\n                this.recordSdfPattern(layerId, imageMap[pattern.max]);\n            }\n        }\n\n        for (const layer of this.layers) {\n            const pattern = layer.paint.get('fill-pattern').constantOr(null);\n            if (pattern) {\n                this.recordSdfPattern(layer.id, imageMap[pattern.from.toString()]);\n                this.recordSdfPattern(layer.id, imageMap[pattern.to.toString()]);\n            }\n        }\n    }\n\n    private recordSdfPattern(layerId: string, image: StyleImage | undefined): void {\n        if (!image) return;\n\n        const isSdf = image.sdf === true;\n        const existing = this.sdfPatterns[layerId];\n        if (existing === undefined) {\n            this.sdfPatterns[layerId] = isSdf;\n        } else if (existing !== isSdf) {\n            warnOnce(`Style sheet warning: Cannot mix SDF and non-SDF fill patterns in layer \"${layerId}\"`);\n        }\n    }\n\n    isEmpty(): boolean {\n        return this.layoutVertexArray.length === 0;\n    }\n\n    uploadPending(): boolean {\n        return !this.uploaded || this.programConfigurations.needsUpload;\n    }\n    upload(context: Context): void {\n        if (!this.uploaded) {\n            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n            this.indexBuffer = context.createIndexBuffer(this.indexArray);\n            this.indexBuffer2 = context.createIndexBuffer(this.indexArray2);\n        }\n        this.programConfigurations.upload(context);\n        this.uploaded = true;\n    }\n\n    destroy(): void {\n        if (!this.layoutVertexBuffer) return;\n        this.layoutVertexBuffer.destroy();\n        this.indexBuffer.destroy();\n        this.indexBuffer2.destroy();\n        this.programConfigurations.destroy();\n        this.segments.destroy();\n        this.segments2.destroy();\n    }\n\n    addFeature(feature: BucketFeature, geometry: Point[][], index: number, canonical: CanonicalTileID, imagePositions: {\n        [_: string]: ImagePosition;\n    }, subdivisionGranularity: SubdivisionGranularitySetting): void {\n        for (const polygon of classifyRings(geometry, EARCUT_MAX_RINGS)) {\n            const subdivided = subdividePolygon(polygon, canonical, subdivisionGranularity.fill.getGranularityForZoomLevel(canonical.z));\n\n            const vertexArray = this.layoutVertexArray;\n\n            fillLargeMeshArrays(\n                (x, y) => {\n                    vertexArray.emplaceBack(x, y);\n                },\n                this.segments,\n                this.layoutVertexArray,\n                this.indexArray,\n                subdivided.verticesFlattened,\n                subdivided.indicesTriangles,\n                this.segments2,\n                this.indexArray2,\n                subdivided.indicesLineList,\n            );\n        }\n        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {imagePositions, canonical});\n    }\n}\n\nregister('FillBucket', FillBucket, {omit: ['layers', 'patternFeatures']});\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type FillLayoutProps = {\n    \"fill-sort-key\": DataDrivenProperty<number>,\n};\n\nexport type FillLayoutPropsPossiblyEvaluated = {\n    \"fill-sort-key\": PossiblyEvaluatedPropertyValue<number>,\n};\n\nlet layout: Properties<FillLayoutProps>;\nconst getLayout = (): Properties<FillLayoutProps> => layout = layout || new Properties({\n    \"fill-sort-key\": new DataDrivenProperty(styleSpec[\"layout_fill\"][\"fill-sort-key\"] as any as StylePropertySpecification, \"fill-sort-key\"),\n});\n\nexport type FillPaintProps = {\n    \"fill-antialias\": DataConstantProperty<boolean>,\n    \"fill-opacity\": DataDrivenProperty<number>,\n    \"fill-layer-opacity\": DataConstantProperty<number>,\n    \"fill-layer-blend\": DataConstantProperty<\"normal\" | \"multiply\" | \"color\" | \"luminosity\" | \"plus-lighter\" | \"screen\" | \"overlay\">,\n    \"fill-color\": DataDrivenProperty<Color>,\n    \"fill-outline-color\": DataDrivenProperty<Color>,\n    \"fill-translate\": DataConstantProperty<[number, number]>,\n    \"fill-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"fill-pattern\": CrossFadedDataDrivenProperty<ResolvedImage>,\n};\n\nexport type FillPaintPropsPossiblyEvaluated = {\n    \"fill-antialias\": boolean,\n    \"fill-opacity\": PossiblyEvaluatedPropertyValue<number>,\n    \"fill-layer-opacity\": number,\n    \"fill-layer-blend\": \"normal\" | \"multiply\" | \"color\" | \"luminosity\" | \"plus-lighter\" | \"screen\" | \"overlay\",\n    \"fill-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"fill-outline-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"fill-translate\": [number, number],\n    \"fill-translate-anchor\": \"map\" | \"viewport\",\n    \"fill-pattern\": PossiblyEvaluatedPropertyValue<CrossFaded<ResolvedImage>>,\n};\n\nlet paint: Properties<FillPaintProps>;\nconst getPaint = (): Properties<FillPaintProps> => paint = paint || new Properties({\n    \"fill-antialias\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-antialias\"] as any as StylePropertySpecification, \"fill-antialias\"),\n    \"fill-opacity\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-opacity\"] as any as StylePropertySpecification, \"fill-opacity\"),\n    \"fill-layer-opacity\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-layer-opacity\"] as any as StylePropertySpecification, \"fill-layer-opacity\"),\n    \"fill-layer-blend\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-layer-blend\"] as any as StylePropertySpecification, \"fill-layer-blend\"),\n    \"fill-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-color\"] as any as StylePropertySpecification, \"fill-color\"),\n    \"fill-outline-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-outline-color\"] as any as StylePropertySpecification, \"fill-outline-color\"),\n    \"fill-translate\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate\"] as any as StylePropertySpecification, \"fill-translate\"),\n    \"fill-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate-anchor\"] as any as StylePropertySpecification, \"fill-translate-anchor\"),\n    \"fill-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-pattern\"] as any as StylePropertySpecification, \"fill-pattern\"),\n});\n\nexport default ({ get paint(): Properties<FillPaintProps> { return getPaint() }, get layout(): Properties<FillLayoutProps> { return getLayout() } });", "import {type QueryIntersectsFeatureParams, StyleLayer} from '../style_layer.ts';\nimport {FillBucket} from '../../data/bucket/fill_bucket.ts';\nimport {polygonIntersectsMultiPolygon} from '../../util/intersection_tests.ts';\nimport {translateDistance, translate} from '../query_utils.ts';\nimport properties, {type FillLayoutPropsPossiblyEvaluated, type FillPaintPropsPossiblyEvaluated} from './fill_style_layer_properties.g.ts';\n\nimport type {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties.ts';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {BucketParameters} from '../../data/bucket.ts';\nimport type {FillLayoutProps, FillPaintProps} from './fill_style_layer_properties.g.ts';\nimport type {EvaluationParameters} from '../evaluation_parameters.ts';\n\nexport const isFillStyleLayer = (layer: StyleLayer): layer is FillStyleLayer => layer.type === 'fill';\n\nexport class FillStyleLayer extends StyleLayer {\n    _unevaluatedLayout: Layout<FillLayoutProps>;\n    layout: PossiblyEvaluated<FillLayoutProps, FillLayoutPropsPossiblyEvaluated>;\n\n    _transitionablePaint: Transitionable<FillPaintProps>;\n    _transitioningPaint: Transitioning<FillPaintProps>;\n    paint: PossiblyEvaluated<FillPaintProps, FillPaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n    }\n\n    recalculate(parameters: EvaluationParameters, availableImages: string[]): void {\n        super.recalculate(parameters, availableImages);\n\n        const outlineColor = this.paint._values['fill-outline-color'];\n        if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) {\n            this.paint._values['fill-outline-color'] = this.paint._values['fill-color'];\n        }\n    }\n\n    createBucket(parameters: BucketParameters<any>): FillBucket {\n        return new FillBucket(parameters);\n    }\n\n    queryRadius(): number {\n        return translateDistance(this.paint.get('fill-translate'));\n    }\n\n    queryIntersectsFeature({\n        queryGeometry,\n        geometry,\n        transform,\n        pixelsToTileUnits}: QueryIntersectsFeatureParams\n    ): boolean {\n        const translatedPolygon = translate(queryGeometry,\n            this.paint.get('fill-translate'),\n            this.paint.get('fill-translate-anchor'),\n            -transform.bearingInRadians, pixelsToTileUnits);\n        return polygonIntersectsMultiPolygon(translatedPolygon, geometry);\n    }\n\n    isTileClipped(): boolean {\n        return true;\n    }\n}\n", "import {createLayout, type StructArrayLayout, type StructArrayMember} from '../../util/struct_array.ts';\n\nconst layout: StructArrayLayout = createLayout([\n    {name: 'a_pos',          components: 2, type: 'Int16'},\n    {name: 'a_normal_ed',    components: 4, type: 'Int16'},\n], 4);\n\nexport const centroidAttributes: StructArrayLayout = createLayout([\n    {name: 'a_centroid', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const members: StructArrayMember[] = layout.members;\nexport const size: number = layout.size;\nexport const alignment: number = layout.alignment;\n", "\nimport Point from '@mapbox/point-geometry';\n\n/** @import {PbfReader} from 'pbf' */\n/** @import {Feature} from 'geojson' */\n\nexport class VectorTileFeature {\n    /**\n     * @param {PbfReader} pbf\n     * @param {number} end\n     * @param {number} extent\n     * @param {string[]} keys\n     * @param {(number | string | boolean)[]} values\n     */\n    constructor(pbf, end, extent, keys, values) {\n        // Public\n\n        /** @type {Record<string, number | string | boolean>} */\n        this.properties = Object.create(null);\n\n        this.extent = extent;\n        /** @type {0 | 1 | 2 | 3} */\n        this.type = 0;\n\n        /** @type {number | undefined} */\n        this.id = undefined;\n\n        /** @private */\n        this._pbf = pbf;\n        /** @private */\n        this._geometry = -1;\n        /** @private */\n        this._keys = keys;\n        /** @private */\n        this._values = values;\n\n        while (pbf.pos < end) {\n            const tag = pbf.readVarint();\n            if (tag === 8) this.id = pbf.readVarint();\n            else if (tag === 18) {\n                const tagsEnd = pbf.readVarint() + pbf.pos;\n                while (pbf.pos < tagsEnd) {\n                    const key = keys[pbf.readVarint()];\n                    const value = values[pbf.readVarint()];\n                    this.properties[key] = value;\n                }\n            } else if (tag === 24) this.type = /** @type {0 | 1 | 2 | 3} */ (pbf.readVarint());\n            else if (tag === 34) {\n                this._geometry = pbf.pos;\n                pbf.skip(tag);\n            } else pbf.skip(tag);\n        }\n    }\n\n    loadGeometry() {\n        if (this._geometry < 0) throw new Error('feature has no geometry');\n        const pbf = this._pbf;\n        pbf.pos = this._geometry;\n\n        const end = pbf.readVarint() + pbf.pos;\n\n        /** @type Point[][] */\n        const lines = [];\n\n        /** @type Point[] | undefined */\n        let line;\n\n        let cmd = 1;\n        let length = 0;\n        let x = 0;\n        let y = 0;\n\n        while (pbf.pos < end) {\n            if (length <= 0) {\n                const cmdLen = pbf.readVarint();\n                cmd = cmdLen & 0x7;\n                length = cmdLen >> 3;\n                if (length === 0) continue;\n            }\n\n            length--;\n\n            if (cmd === 1) { // moveTo\n                x += pbf.readSVarint();\n                y += pbf.readSVarint();\n                if (line) lines.push(line);\n                line = [new Point(x, y)];\n\n            } else if (cmd === 2) { // lineTo\n                x += pbf.readSVarint();\n                y += pbf.readSVarint();\n                if (line) line.push(new Point(x, y));\n\n            } else if (cmd === 7) {\n\n                // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90\n                if (line) {\n                    line.push(line[0].clone()); // closePolygon\n                }\n\n            } else {\n                throw new Error(`unknown command ${cmd}`);\n            }\n        }\n\n        if (line) lines.push(line);\n\n        return lines;\n    }\n\n    bbox() {\n        if (this._geometry < 0) throw new Error('feature has no geometry');\n        const pbf = this._pbf;\n        pbf.pos = this._geometry;\n\n        const end = pbf.readVarint() + pbf.pos;\n        let cmd = 1,\n            length = 0,\n            x = 0,\n            y = 0,\n            x1 = Infinity,\n            x2 = -Infinity,\n            y1 = Infinity,\n            y2 = -Infinity;\n\n        while (pbf.pos < end) {\n            if (length <= 0) {\n                const cmdLen = pbf.readVarint();\n                cmd = cmdLen & 0x7;\n                length = cmdLen >> 3;\n                if (length === 0) continue;\n            }\n\n            length--;\n\n            if (cmd === 1 || cmd === 2) {\n                x += pbf.readSVarint();\n                y += pbf.readSVarint();\n                if (x < x1) x1 = x;\n                if (x > x2) x2 = x;\n                if (y < y1) y1 = y;\n                if (y > y2) y2 = y;\n\n            } else if (cmd !== 7) {\n                throw new Error(`unknown command ${cmd}`);\n            }\n        }\n\n        return [x1, y1, x2, y2];\n    }\n\n    /**\n     * @param {number} x\n     * @param {number} y\n     * @param {number} z\n     * @return {Feature}\n     */\n    toGeoJSON(x, y, z) {\n        const size = this.extent * Math.pow(2, z),\n            x0 = this.extent * x,\n            y0 = this.extent * y,\n            vtCoords = this.loadGeometry();\n\n        /** @param {Point} p */\n        function projectPoint(p) {\n            return [\n                (p.x + x0) * 360 / size - 180,\n                360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90\n            ];\n        }\n\n        /** @param {Point[]} line */\n        function projectLine(line) {\n            return line.map(projectPoint);\n        }\n\n        /** @type {Feature[\"geometry\"]} */\n        let geometry;\n\n        if (this.type === 1) {\n            const points = [];\n            for (const line of vtCoords) {\n                points.push(line[0]);\n            }\n            const coordinates = projectLine(points);\n            geometry = points.length === 1 ?\n                {type: 'Point', coordinates: coordinates[0]} :\n                {type: 'MultiPoint', coordinates};\n\n        } else if (this.type === 2) {\n\n            const coordinates = vtCoords.map(projectLine);\n            geometry = coordinates.length === 1 ?\n                {type: 'LineString', coordinates: coordinates[0]} :\n                {type: 'MultiLineString', coordinates};\n\n        } else if (this.type === 3) {\n            const polygons = classifyRings(vtCoords);\n            const coordinates = [];\n            for (const polygon of polygons) {\n                coordinates.push(polygon.map(projectLine));\n            }\n            geometry = coordinates.length === 1 ?\n                {type: 'Polygon', coordinates: coordinates[0]} :\n                {type: 'MultiPolygon', coordinates};\n        } else {\n\n            throw new Error('unknown feature type');\n        }\n\n        /** @type {Feature} */\n        const result = {\n            type: 'Feature',\n            geometry,\n            properties: this.properties\n        };\n\n        if (this.id != null) {\n            result.id = this.id;\n        }\n\n        return result;\n    }\n}\n\n/** @type {['Unknown', 'Point', 'LineString', 'Polygon']} */\nVectorTileFeature.types = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\n/** classifies an array of rings into polygons with outer rings and holes\n * @param {Point[][]} rings\n */\nexport function classifyRings(rings) {\n    const len = rings.length;\n\n    if (len <= 1) return [rings];\n\n    const polygons = [];\n    let polygon, ccw;\n\n    for (let i = 0; i < len; i++) {\n        const area = signedArea(rings[i]);\n        if (area === 0) continue;\n\n        if (ccw === undefined) ccw = area < 0;\n\n        if (ccw === area < 0) {\n            if (polygon) polygons.push(polygon);\n            polygon = [rings[i]];\n\n        } else if (polygon) {\n            polygon.push(rings[i]);\n        }\n    }\n    if (polygon) polygons.push(polygon);\n\n    return polygons;\n}\n\n/** @param {Point[]} ring */\nfunction signedArea(ring) {\n    let sum = 0;\n    for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n        p1 = ring[i];\n        p2 = ring[j];\n        sum += (p2.x - p1.x) * (p1.y + p2.y);\n    }\n    return sum;\n}\n\nexport class VectorTileLayer {\n    /**\n     * @param {PbfReader} pbf\n     * @param {number} [end]\n     */\n    constructor(pbf, end) {\n        // Public\n        this.version = 1;\n        this.name = '';\n        this.extent = 4096;\n        this.length = 0;\n\n        /** @private */\n        this._pbf = pbf;\n\n        /** @private\n         * @type {string[]} */\n        this._keys = [];\n\n        /** @private\n         * @type {(number | string | boolean)[]} */\n        this._values = [];\n\n        /** @private\n         * @type {number[]} */\n        this._features = [];\n\n        if (end === undefined) end = pbf.length;\n        while (pbf.pos < end) {\n            const tag = pbf.readVarint();\n            if (tag === 10) this.name = pbf.readString();\n            else if (tag === 18) {\n                this._features.push(pbf.pos);\n                pbf.skip(tag);\n            } else if (tag === 26) this._keys.push(pbf.readString());\n            else if (tag === 34) this._values.push(readValueMessage(pbf));\n            else if (tag === 40) this.extent = pbf.readVarint();\n            else if (tag === 120) this.version = pbf.readVarint();\n            else pbf.skip(tag);\n        }\n\n        this.length = this._features.length;\n    }\n\n    /** return feature `i` from this layer as a `VectorTileFeature`\n     * @param {number} i\n     */\n    feature(i) {\n        if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds');\n\n        this._pbf.pos = this._features[i];\n\n        const end = this._pbf.readVarint() + this._pbf.pos;\n        return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values);\n    }\n}\n\n/**\n * @param {PbfReader} pbf\n */\nfunction readValueMessage(pbf) {\n    let value = null;\n    const end = pbf.readVarint() + pbf.pos;\n\n    while (pbf.pos < end) {\n        const tag = pbf.readVarint();\n        value =\n            tag === 10 ? pbf.readString() :\n            tag === 21 ? pbf.readFloat() :\n            tag === 25 ? pbf.readDouble() :\n            tag === 32 ? pbf.readVarint(true) :\n            tag === 40 ? pbf.readVarint() :\n            tag === 48 ? pbf.readSVarint() :\n            tag === 56 ? pbf.readBoolean() :\n            (pbf.skip(tag), null);\n    }\n    if (value == null) {\n        throw new Error('unknown feature value');\n    }\n\n    return value;\n}\n\nexport class VectorTile {\n    /**\n     * @param {PbfReader} pbf\n     * @param {number} [end]\n     */\n    constructor(pbf, end = pbf.length) {\n        /** @type {Record<string, VectorTileLayer>} */\n        const layers = Object.create(null);\n        while (pbf.pos < end) {\n            const tag = pbf.readVarint();\n            if (tag === 26) {\n                const layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);\n                if (layer.length) layers[layer.name] = layer;\n            } else pbf.skip(tag);\n        }\n        this.layers = layers;\n    }\n}\n", "import {wrap} from '../util/util.ts';\n\n/*\n* Approximate radius of the earth in meters.\n* Uses the WGS-84 approximation. The radius at the equator is ~6378137 and at the poles is ~6356752. https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84\n* 6371008.8 is one published \"average radius\" see https://en.wikipedia.org/wiki/Earth_radius#Mean_radius, or ftp://athena.fsv.cvut.cz/ZFG/grs80-Moritz.pdf p.4\n*/\nexport const earthRadius = 6371008.8;\n\n/**\n * A {@link LngLat} object, an array of two numbers representing longitude and latitude,\n * or an object with `lng` and `lat` or `lon` and `lat` properties.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let v1 = new LngLat(-122.420679, 37.772537);\n * let v2 = [-122.420679, 37.772537];\n * let v3 = {lon: -122.420679, lat: 37.772537};\n * ```\n */\nexport type LngLatLike = LngLat | {\n    lng: number;\n    lat: number;\n} | {\n    lon: number;\n    lat: number;\n} | [number, number];\n\n/**\n * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees.\n * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84).\n *\n * MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the\n * [GeoJSON specification](https://tools.ietf.org/html/rfc7946).\n *\n * Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option\n * can also accept an `Array` of two numbers and will perform an implicit conversion.\n * This flexible type is documented as {@link LngLatLike}.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let ll = new LngLat(-123.9749, 40.7736);\n * ll.lng; // = -123.9749\n * ```\n * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-coordinates-of-the-mouse-pointer/)\n */\nexport class LngLat {\n    /**\n     * Longitude, measured in degrees.\n     */\n    lng: number;\n\n    /**\n     * Latitude, measured in degrees.\n     */\n    lat: number;\n\n    /**\n     * @param lng - Longitude, measured in degrees.\n     * @param lat - Latitude, measured in degrees.\n     */\n    constructor(lng: number, lat: number) {\n        if (isNaN(lng) || isNaN(lat)) {\n            throw new Error(`Invalid LngLat object: (${lng}, ${lat})`);\n        }\n        this.lng = +lng;\n        this.lat = +lat;\n        if (this.lat > 90 || this.lat < -90) {\n            throw new Error('Invalid LngLat latitude value: must be between -90 and 90');\n        }\n    }\n\n    /**\n     * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180).\n     *\n     * @returns The wrapped `LngLat` object.\n     * @example\n     * ```ts\n     * let ll = new LngLat(286.0251, 40.7736);\n     * let wrapped = ll.wrap();\n     * wrapped.lng; // = -73.9749\n     * ```\n     */\n    wrap(): LngLat {\n        return new LngLat(wrap(this.lng, -180, 180), this.lat);\n    }\n\n    /**\n     * Returns the coordinates represented as an array of two numbers.\n     *\n     * @returns The coordinates represented as an array of longitude and latitude.\n     * @example\n     * ```ts\n     * let ll = new LngLat(-73.9749, 40.7736);\n     * ll.toArray(); // = [-73.9749, 40.7736]\n     * ```\n     */\n    toArray(): [number, number] {\n        return [this.lng, this.lat];\n    }\n\n    /**\n     * Returns the coordinates represent as a string.\n     *\n     * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`.\n     * @example\n     * ```ts\n     * let ll = new LngLat(-73.9749, 40.7736);\n     * ll.toString(); // = \"LngLat(-73.9749, 40.7736)\"\n     * ```\n     */\n    toString(): string {\n        return `LngLat(${this.lng}, ${this.lat})`;\n    }\n\n    /**\n     * Returns the approximate distance between a pair of coordinates in meters\n     * Uses the Haversine Formula (from R.W. Sinnott, \"Virtues of the Haversine\", Sky and Telescope, vol. 68, no. 2, 1984, p. 159)\n     *\n     * @param lngLat - coordinates to compute the distance to\n     * @returns Distance in meters between the two coordinates.\n     * @example\n     * ```ts\n     * let new_york = new LngLat(-74.0060, 40.7128);\n     * let los_angeles = new LngLat(-118.2437, 34.0522);\n     * new_york.distanceTo(los_angeles); // = 3935751.690893987, \"true distance\" using a non-spherical approximation is ~3966km\n     * ```\n     */\n    distanceTo(lngLat: LngLat): number {\n        const rad = Math.PI / 180;\n        const lat1 = this.lat * rad;\n        const lat2 = lngLat.lat * rad;\n        const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad);\n\n        return earthRadius * Math.acos(Math.min(a, 1));\n    }\n\n    /**\n     * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties\n     * to a `LngLat` object.\n     *\n     * If a `LngLat` object is passed in, the function returns it unchanged.\n     *\n     * @param input - An array of two numbers or object to convert, or a `LngLat` object to return.\n     * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object.\n     * @example\n     * ```ts\n     * let arr = [-73.9749, 40.7736];\n     * let ll = LngLat.convert(arr);\n     * ll;   // = LngLat {lng: -73.9749, lat: 40.7736}\n     * ```\n     */\n    static convert(input: LngLatLike): LngLat {\n        if (input instanceof LngLat) {\n            return input;\n        }\n        if (Array.isArray(input) && (input.length === 2 || input.length === 3)) {\n            return new LngLat(Number(input[0]), Number(input[1]));\n        }\n        if (!Array.isArray(input) && typeof input === 'object' && input !== null) {\n            return new LngLat(\n                // flow can't refine this to have one of lng or lat, so we have to cast to any\n                Number('lng' in input ? (input as any).lng : (input as any).lon),\n                Number(input.lat)\n            );\n        }\n        throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]');\n    }\n}\n", "/**\n * @experimental\n * A square, power-of-two quad tile matrix set laid over a planar CRS: tile 0/0/0 is the square of side\n * `extentAtZoom0` whose top-left corner is `origin`, and every zoom level splits each tile in four.\n */\nexport type TileMatrixSet = {\n    /**\n     * CRS coordinates of the top-left corner of tile 0/0/0 (min x, max y); x and y are in the order\n     * the definition's `projection.forward` returns (easting, northing for a projected CRS).\n     */\n    origin: [number, number];\n    /**\n     * Width (= height) of tile 0/0/0 in CRS units.\n     */\n    extentAtZoom0: number;\n};\n\n/** WGS84 spherical radius used by EPSG:3857, distinct from the mean earth radius MercatorCoordinate is built on. */\nconst EPSG3857_RADIUS = 6378137;\n\n/**\n * @internal\n * The EPSG:3857 tile matrix set in meters, the grid of the mercator, globe and vertical-perspective projections:\n * tile 0/0/0 spans half the circumference in every direction from the origin.\n */\nexport const mercatorTileMatrixSet: TileMatrixSet = {\n    origin: [-Math.PI * EPSG3857_RADIUS, Math.PI * EPSG3857_RADIUS],\n    extentAtZoom0: 2 * Math.PI * EPSG3857_RADIUS,\n};\n", "import {LngLat, earthRadius} from '../geo/lng_lat.ts';\nimport {mercatorTileMatrixSet} from './projection/tile_matrix_set.ts';\n\nimport type {IMercatorCoordinate} from '@maplibre/maplibre-gl-style-spec';\nimport type {LngLatLike} from '../geo/lng_lat.ts';\nimport type {WorldCoordinateHelper} from './transform_interface.ts';\n\n/*\n * The average circumference of the world in meters.\n */\nconst earthCircumference = 2 * Math.PI * earthRadius; // meters\n\n/*\n * The circumference at a line of latitude in meters.\n */\nfunction circumferenceAtLatitude(latitude: number) {\n    return earthCircumference * Math.cos(latitude * Math.PI / 180);\n}\n\nexport function mercatorXfromLng(lng: number): number {\n    return (180 + lng) / 360;\n}\n\nexport function mercatorYfromLat(lat: number): number {\n    return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;\n}\n\nexport function mercatorZfromAltitude(altitude: number, lat: number): number {\n    return altitude / circumferenceAtLatitude(lat);\n}\n\nexport function lngFromMercatorX(x: number): number {\n    return x * 360 - 180;\n}\n\nexport function latFromMercatorY(y: number): number {\n    const y2 = 180 - y * 360;\n    return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;\n}\n\nexport function altitudeFromMercatorZ(z: number, y: number): number {\n    return z * circumferenceAtLatitude(latFromMercatorY(y));\n}\n\n/**\n * Determine the Mercator scale factor for a given latitude, see\n * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor\n *\n * At the equator the scale factor will be 1, which increases at higher latitudes.\n *\n * @param lat - Latitude\n * @returns scale factor\n */\nexport function mercatorScale(lat: number): number {\n    return 1 / Math.cos(lat * Math.PI / 180);\n}\n\n/**\n * A `MercatorCoordinate` object represents a projected three dimensional position.\n *\n * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units:\n *\n * - the size of 1 unit is the width of the projected world instead of the \"mercator meter\"\n * - the origin of the coordinate space is at the north-west corner instead of the middle\n *\n * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and\n * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with\n * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think\n * of the coordinate space as the `0/0/0` tile with an extent of `1`.\n *\n * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let nullIsland = new MercatorCoordinate(0.5, 0.5, 0);\n * ```\n * @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-custom-style-layer/)\n * @see [Add 3D Tiles, 3D objects and models using Three.js](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-tiles-3d-objects-and-models-using-threejs/)\n * @see [Add a simple custom layer on a globe](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-simple-custom-layer-on-a-globe/)\n */\nexport class MercatorCoordinate implements IMercatorCoordinate {\n    x: number;\n    y: number;\n    z: number;\n\n    /**\n     * @param x - The x component of the position.\n     * @param y - The y component of the position.\n     * @param z - The z component of the position.\n     */\n    constructor(x: number, y: number, z: number = 0) {\n        this.x = +x;\n        this.y = +y;\n        this.z = +z;\n    }\n\n    /**\n     * Project a `LngLat` to a `MercatorCoordinate`.\n     *\n     * @param lngLatLike - The location to project.\n     * @param altitude - The altitude in meters of the position.\n     * @returns The projected mercator coordinate.\n     * @example\n     * ```ts\n     * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0);\n     * coord; // MercatorCoordinate(0.5, 0.5, 0)\n     * ```\n     */\n    static fromLngLat(lngLatLike: LngLatLike, altitude: number = 0): MercatorCoordinate {\n        const lngLat = LngLat.convert(lngLatLike);\n\n        return new MercatorCoordinate(\n            mercatorXfromLng(lngLat.lng),\n            mercatorYfromLat(lngLat.lat),\n            mercatorZfromAltitude(altitude, lngLat.lat));\n    }\n\n    /**\n     * Returns the `LngLat` for the coordinate.\n     *\n     * @returns The `LngLat` object.\n     * @example\n     * ```ts\n     * let coord = new MercatorCoordinate(0.5, 0.5, 0);\n     * let lngLat = coord.toLngLat(); // LngLat(0, 0)\n     * ```\n     */\n    toLngLat(): LngLat {\n        return new LngLat(\n            lngFromMercatorX(this.x),\n            latFromMercatorY(this.y));\n    }\n\n    /**\n     * Returns the altitude in meters of the coordinate.\n     *\n     * @returns The altitude in meters.\n     * @example\n     * ```ts\n     * let coord = new MercatorCoordinate(0, 0, 0.02);\n     * coord.toAltitude(); // 6914.281956295339\n     * ```\n     */\n    toAltitude(): number {\n        return altitudeFromMercatorZ(this.z, this.y);\n    }\n\n    /**\n     * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude.\n     *\n     * For coordinates in real world units using meters, this naturally provides the scale\n     * to transform into `MercatorCoordinate`s.\n     *\n     * @returns Distance of 1 meter in `MercatorCoordinate` units.\n     */\n    meterInMercatorCoordinateUnits(): number {\n        // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude\n        return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y));\n    }\n}\n\n/**\n * @internal\n * The Web Mercator world mapping used by the mercator, globe, and vertical-perspective projections.\n * `metersPerWorldUnit` is the inverse of `MercatorCoordinate.meterInMercatorCoordinateUnits`.\n * Lives next to the mercator functions it calls so they stay module-local on the camera paths.\n */\nclass MercatorWorldCoordinateHelper implements WorldCoordinateHelper {\n    readonly name = 'mercator';\n    worldFromLngLat(lng: number, lat: number, altitude?: number): MercatorCoordinate {\n        return new MercatorCoordinate(mercatorXfromLng(lng), mercatorYfromLat(lat), altitude === undefined ? 0 : mercatorZfromAltitude(altitude, lat));\n    }\n    lngLatFromWorld(x: number, y: number): LngLat {\n        return new LngLat(lngFromMercatorX(x), latFromMercatorY(y));\n    }\n    hasLngLat(_x: number, _y: number): boolean {\n        return true;\n    }\n    metersPerWorldUnit(_x: number, y: number): number {\n        return 1 / (1 / earthCircumference * mercatorScale(latFromMercatorY(y)));\n    }\n    worldZFromAltitude(altitude: number, lngLat: LngLat): number {\n        return mercatorZfromAltitude(altitude, lngLat.lat);\n    }\n    /** The world wraps in longitude: copies, wrapping, and the mercator latitude clamp all apply. */\n    readonly wraps = true;\n    readonly tileMatrixSet = mercatorTileMatrixSet;\n}\n\n/**\n * @internal\n * The one mercator world mapping: it holds no state, so every mercator-based transform shares this instance.\n */\nexport const mercatorWorldCoordinateHelper: WorldCoordinateHelper = new MercatorWorldCoordinateHelper();\n", "import {mat4} from 'gl-matrix';\nimport {EXTENT} from '../../data/extent.ts';\nimport {clamp, degreesToRadians, MAX_VALID_LATITUDE, zoomScale, type Mat4f64} from '../../util/util.ts';\nimport {MercatorCoordinate} from '../mercator_coordinate.ts';\nimport Point from '@mapbox/point-geometry';\n\nimport type {WorldCoordinateHelper} from '../transform_interface.ts';\nimport type {UnwrappedTileIDType} from '../transform_helper.ts';\nimport type {LngLat} from '../lng_lat.ts';\n\n/*\n* The maximum angle to use for the Mercator horizon. This must be less than 90\n* to prevent errors in `MercatorTransform::_calcMatrices()`. It shouldn't be too close\n* to 90, or the distance to the horizon will become very large, unnecessarily increasing\n* the number of tiles needed to render the map.\n*/\nexport const maxMercatorHorizonAngle = 89.25;\n\n/**\n * Returns mercator coordinates in range 0..1 for given coordinates inside a specified tile.\n * @param inTileX - X coordinate in tile units - range [0..EXTENT].\n * @param inTileY - Y coordinate in tile units - range [0..EXTENT].\n * @param canonicalTileID - Tile canonical ID - mercator X, Y and zoom.\n * @returns Mercator coordinates of the specified point in range [0..1].\n */\nexport function tileCoordinatesToMercatorCoordinates(inTileX: number, inTileY: number, canonicalTileID: {x: number; y: number; z: number}): MercatorCoordinate {\n    const scale = 1.0 / (1 << canonicalTileID.z);\n    return new MercatorCoordinate(\n        inTileX / EXTENT * scale + canonicalTileID.x * scale,\n        inTileY / EXTENT * scale + canonicalTileID.y * scale\n    );\n}\n\n/**\n * A tile's `[x, y, scaleX, scaleY]` in the world's 0..1 coordinates, where `x` and `y` are its top-left corner and\n * both scales are the size of one tile unit, `1 / EXTENT` of the tile. Without a tile it is `[0, 0, 1, 1]`.\n */\nexport function getMercatorTileCoordinates(overscaledTileID?: {canonical: {x: number; y: number; z: number}} | null): [number, number, number, number] {\n    if (!overscaledTileID) {\n        return [0, 0, 1, 1];\n    }\n    const scale = (overscaledTileID.canonical.z >= 0) ? (1 << overscaledTileID.canonical.z) : Math.pow(2.0, overscaledTileID.canonical.z);\n    return [\n        overscaledTileID.canonical.x / scale,\n        overscaledTileID.canonical.y / scale,\n        1.0 / scale / EXTENT,\n        1.0 / scale / EXTENT\n    ];\n}\n\n/**\n * Returns LngLat for given in-tile coordinates and tile ID.\n * @param inTileX - X coordinate in tile units - range [0..EXTENT].\n * @param inTileY - Y coordinate in tile units - range [0..EXTENT].\n * @param canonicalTileID - Tile canonical ID - mercator X, Y and zoom.\n */\nexport function tileCoordinatesToLocation(inTileX: number, inTileY: number, canonicalTileID: {x: number; y: number; z: number}): LngLat {\n    return tileCoordinatesToMercatorCoordinates(inTileX, inTileY, canonicalTileID).toLngLat();\n}\n\n/**\n * Convert from LngLat to world coordinates (the projection's 0..1 world square scaled by world size).\n * @param worldSize - World size computed from zoom level and tile size.\n * @param lnglat - The location to convert.\n * @param helper - The lng/lat to world mapping; latitude is clamped to the valid mercator range only for a wrapping (mercator) helper.\n * @returns Point\n */\nexport function projectToWorldCoordinates(worldSize: number, lnglat: LngLat, helper: WorldCoordinateHelper): Point {\n    const lat = helper.wraps ? clamp(lnglat.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE) : lnglat.lat;\n    const {x, y} = helper.worldFromLngLat(lnglat.lng, lat);\n    return new Point(x * worldSize, y * worldSize);\n}\n\n/**\n * Convert from world coordinates (the projection's 0..1 world square scaled by world size) to LngLat.\n * @param worldSize - World size computed from zoom level and tile size.\n * @param point - World coordinate.\n * @param helper - The lng/lat to world mapping.\n * @returns LngLat\n */\nexport function unprojectFromWorldCoordinates(worldSize: number, point: Point, helper: WorldCoordinateHelper): LngLat {\n    return helper.lngLatFromWorld(point.x / worldSize, point.y / worldSize);\n}\n\n/**\n * Calculate pixel height of the visible horizon in relation to map-center (e.g. height/2),\n * multiplied by a static factor to simulate the earth-radius.\n * The calculated value is the horizontal line from the camera-height to sea-level.\n * @returns Horizon above center in pixels.\n */\nexport function getMercatorHorizon(transform: {pitch: number; cameraToCenterDistance: number}): number {\n    return transform.cameraToCenterDistance * Math.min(Math.tan(degreesToRadians(90 - transform.pitch)) * 0.85,\n        Math.tan(degreesToRadians(maxMercatorHorizonAngle - transform.pitch)));\n}\n\nexport function calculateTileMatrix(unwrappedTileID: UnwrappedTileIDType, worldSize: number): Mat4f64 {\n    const canonical = unwrappedTileID.canonical;\n    const scale = worldSize / zoomScale(canonical.z);\n    const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;\n\n    const worldMatrix: Mat4f64 = new Float64Array(16);\n    mat4.identity(worldMatrix);\n    mat4.translate(worldMatrix, worldMatrix, [unwrappedX * scale, canonical.y * scale, 0]);\n    mat4.scale(worldMatrix, worldMatrix, [scale / EXTENT, scale / EXTENT, 1]);\n    return worldMatrix;\n}\n\n/**\n * Returns the camera position for a center already mapped to world coordinates.\n * Callers resolve the center through the transform's `WorldCoordinateHelper`; keeping the helper\n * out of this function lets the engine inline it on the per-frame camera path.\n * @param centerMercator - the center in world coordinates, with its elevation in `z`\n * @param dMercator - camera to center distance in world units\n */\nexport function cameraMercatorCoordinateFromCenterAndRotation(centerMercator: MercatorCoordinate, pitch: number, bearing: number, dMercator: number): MercatorCoordinate {\n    const {x, y, z} = cameraDirectionFromPitchBearing(pitch, bearing);\n    const dxMercator = dMercator * -x;\n    const dyMercator = dMercator * -y;\n    // Unlike x and y, z already points from the center up towards the camera.\n    const dzMercator = dMercator * z;\n    return new MercatorCoordinate(centerMercator.x + dxMercator, centerMercator.y + dyMercator, centerMercator.z + dzMercator);\n}\n\n/**\n * Returns the position of the camera in mercator coordinates, with its altitude in `z`.\n * Computed from the center, pitch, bearing and camera distance, so it holds for any projection.\n * @param center - The center to compute from, the transform's own by default.\n */\nexport function cameraMercatorCoordinate(transform: {\n    center: LngLat;\n    elevation: number;\n    pitch: number;\n    bearing: number;\n    cameraToCenterDistance: number;\n    worldSize: number;\n    worldCoordinateHelper: WorldCoordinateHelper;\n}, center: LngLat = transform.center): MercatorCoordinate {\n    const worldCoordinateHelper = transform.worldCoordinateHelper;\n    const mercUnitsPerMeter = worldCoordinateHelper.worldZFromAltitude(1, center);\n    const pixelPerMeter = mercUnitsPerMeter * transform.worldSize;\n    const distance = transform.cameraToCenterDistance / pixelPerMeter;\n    const centerMercator = worldCoordinateHelper.worldFromLngLat(center.lng, center.lat, transform.elevation);\n    return cameraMercatorCoordinateFromCenterAndRotation(centerMercator, transform.pitch, transform.bearing, distance * mercUnitsPerMeter);\n}\n\nexport function cameraDirectionFromPitchBearing(pitch: number, bearing: number): {x: number; y: number; z: number} {\n    const pitchRadians = degreesToRadians(pitch);\n    const bearingRadians = degreesToRadians(bearing);\n    const z = Math.cos(-pitchRadians);\n    const h = Math.sin(pitchRadians);\n    const x = h * Math.sin(bearingRadians);\n    const y = -h * Math.cos(bearingRadians);\n    return {x, y, z};\n}\n\n/**\n * The number of steps a lng/lat box is cut into along each axis by {@link lngLatBoxToWorldSamples}.\n */\nconst BOX_SAMPLE_STEPS = 16;\n\n/**\n * Projects a lng/lat box into the world square as a grid of points, {@link BOX_SAMPLE_STEPS} + 1 on a side,\n * edges and corners included. The corners alone miss most of a box whose edges curve, as a parallel does\n * around a pole, and the inside of the box matters where the projection runs off to infinity, as transverse\n * mercator does on the equator 90 degrees from its central meridian.\n * `bulge` is the farthest an edge strays from the line between two neighboring points, measured halfway\n * between them, which bounds how far an edge reaches past the points. It is 0 where every edge projects to\n * a straight line, as in mercator.\n */\nexport function lngLatBoxToWorldSamples(worldCoordinateHelper: WorldCoordinateHelper, west: number, south: number, east: number, north: number): {points: Point[]; bulge: number} {\n    const toPoint = (lng: number, lat: number) => {\n        const {x, y} = worldCoordinateHelper.worldFromLngLat(lng, lat);\n        return new Point(x, y);\n    };\n    const lngAt = (step: number) => step === BOX_SAMPLE_STEPS ? east : west + (east - west) * step / BOX_SAMPLE_STEPS;\n    const latAt = (step: number) => step === BOX_SAMPLE_STEPS ? south : north + (south - north) * step / BOX_SAMPLE_STEPS;\n    const points: Point[] = [];\n    for (let row = 0; row <= BOX_SAMPLE_STEPS; row++) {\n        for (let column = 0; column <= BOX_SAMPLE_STEPS; column++) {\n            points.push(toPoint(lngAt(column), latAt(row)));\n        }\n    }\n    const pointAt = (row: number, column: number) => points[row * (BOX_SAMPLE_STEPS + 1) + column];\n    let bulge = 0;\n    for (let step = 0; step < BOX_SAMPLE_STEPS; step++) {\n        const lngHalfway = (lngAt(step) + lngAt(step + 1)) / 2;\n        const latHalfway = (latAt(step) + latAt(step + 1)) / 2;\n        const edges: Array<[Point, Point, Point]> = [\n            [pointAt(0, step), pointAt(0, step + 1), toPoint(lngHalfway, north)],\n            [pointAt(BOX_SAMPLE_STEPS, step), pointAt(BOX_SAMPLE_STEPS, step + 1), toPoint(lngHalfway, south)],\n            [pointAt(step, 0), pointAt(step + 1, 0), toPoint(west, latHalfway)],\n            [pointAt(step, BOX_SAMPLE_STEPS), pointAt(step + 1, BOX_SAMPLE_STEPS), toPoint(east, latHalfway)],\n        ];\n        for (const [start, end, halfway] of edges) {\n            const chord = end.sub(start);\n            const toHalfway = halfway.sub(start);\n            const chordLength = chord.mag();\n            const distance = chordLength > 0 ? Math.abs(chord.x * toHalfway.y - chord.y * toHalfway.x) / chordLength : toHalfway.mag();\n            if (distance > bulge) bulge = distance;\n        }\n    }\n    return {points, bulge};\n}\n\n/**\n * Projects a lng/lat box into the world square and returns the axis-aligned rectangle that contains it:\n * the rectangle around {@link lngLatBoxToWorldSamples}, grown by their bulge. In mercator that is exactly\n * the rectangle of the projected corners.\n */\nexport function lngLatBoxToWorldBox(worldCoordinateHelper: WorldCoordinateHelper, west: number, south: number, east: number, north: number): {minX: number; minY: number; maxX: number; maxY: number} {\n    const {points, bulge} = lngLatBoxToWorldSamples(worldCoordinateHelper, west, south, east, north);\n    let minX = Infinity;\n    let minY = Infinity;\n    let maxX = -Infinity;\n    let maxY = -Infinity;\n    for (const {x, y} of points) {\n        if (x < minX) minX = x;\n        if (y < minY) minY = y;\n        if (x > maxX) maxX = x;\n        if (y > maxY) maxY = y;\n    }\n    return {minX: minX - bulge, minY: minY - bulge, maxX: maxX + bulge, maxY: maxY + bulge};\n}\n\n/**\n * Maps the four corners of a world rectangle back to lng/lat and returns the box that contains them.\n * That is exact in mercator. Where `x` and `y` both depend on `lng` and `lat` it can miss a curved edge\n * or a pole inside the rectangle; its one caller is the GeoJSON reload check, which a GeoJSON source skips\n * in a registered projection by reloading every tile on a diff.\n */\nexport function worldBoxToLngLatBox(worldCoordinateHelper: WorldCoordinateHelper, minX: number, minY: number, maxX: number, maxY: number): {west: number; south: number; east: number; north: number} {\n    const corners = [\n        worldCoordinateHelper.lngLatFromWorld(minX, minY),\n        worldCoordinateHelper.lngLatFromWorld(maxX, minY),\n        worldCoordinateHelper.lngLatFromWorld(maxX, maxY),\n        worldCoordinateHelper.lngLatFromWorld(minX, maxY),\n    ];\n    return {\n        west: Math.min(corners[0].lng, corners[1].lng, corners[2].lng, corners[3].lng),\n        south: Math.min(corners[0].lat, corners[1].lat, corners[2].lat, corners[3].lat),\n        east: Math.max(corners[0].lng, corners[1].lng, corners[2].lng, corners[3].lng),\n        north: Math.max(corners[0].lat, corners[1].lat, corners[2].lat, corners[3].lat),\n    };\n}\n\n/**\n * The step in degrees over which {@link degreesPerWorldUnit} measures the size of a degree.\n */\nconst DEGREE_STEP = 1e-4;\n\n/**\n * Returns how many degrees one world unit spans at a location. A world that wraps is 360 degrees wide.\n * Any other world is measured at the location along longitude and along latitude, and the direction\n * with the fewest degrees counts.\n */\nexport function degreesPerWorldUnit(worldCoordinateHelper: WorldCoordinateHelper, lngLat: LngLat): number {\n    if (worldCoordinateHelper.wraps) return 360;\n\n    const latStep = lngLat.lat > 0 ? -DEGREE_STEP : DEGREE_STEP;\n    const world = worldCoordinateHelper.worldFromLngLat(lngLat.lng, lngLat.lat);\n    const alongLng = worldCoordinateHelper.worldFromLngLat(lngLat.lng + DEGREE_STEP, lngLat.lat);\n    const alongLat = worldCoordinateHelper.worldFromLngLat(lngLat.lng, lngLat.lat + latStep);\n    const worldUnits = Math.max(\n        Math.hypot(alongLng.x - world.x, alongLng.y - world.y),\n        Math.hypot(alongLat.x - world.x, alongLat.y - world.y)\n    );\n    return DEGREE_STEP / worldUnits;\n}\n", "import {EXTENT} from '../extent.ts';\nimport {isBoundaryEdge} from '../extent_bounds.ts';\nimport {MercatorCoordinate} from '../../geo/mercator_coordinate.ts';\nimport {tileCoordinatesToLocation} from '../../geo/projection/mercator_utils.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\n\n/**\n * Rounds polygon corners by calculating arc points at each corner vertex.\n * A distance of zero or less disables rounding.\n * @param polygon - Collection of polygon rings (outer ring and hole rings)\n * @param distanceInTileUnits - Corner rounding distance in tile units, as returned by {@link getTileUnitsForMeters}\n */\nexport function roundPolygonCornersIfNeeded(polygon: Point[][], distanceInTileUnits: number): Point[][] {\n    if (distanceInTileUnits <= 0 || !polygon || polygon.length === 0) {\n        return polygon;\n    }\n\n    return polygon.map(ring => roundRing(ring, distanceInTileUnits));\n}\n\n/**\n * Converts a distance in meters to tile units at the center of the given tile. The result only\n * depends on the tile, so it is computed once per tile rather than once per feature.\n * @param distanceInMeters - Distance in meters\n * @param canonical - Canonical tile ID used for meter to tile unit conversion\n */\nexport function getTileUnitsForMeters(distanceInMeters: number, canonical: CanonicalTileID): number {\n    const centerLocation = tileCoordinatesToLocation(EXTENT / 2, EXTENT / 2, canonical);\n    const mercatorCoord = MercatorCoordinate.fromLngLat(centerLocation);\n    const meterInMercator = mercatorCoord.meterInMercatorCoordinateUnits();\n    const tileUnitsPerMercator = (1 << canonical.z) * EXTENT;\n    return distanceInMeters * meterInMercator * tileUnitsPerMercator;\n}\n\n/**\n * The normals at the start and the end of a wall.\n */\ntype WallNormals = {\n    start: Point;\n    end: Point;\n};\n\n/**\n * Cosine of the sharpest turn between two walls that is still shaded as one curved surface, 35 degrees.\n * Rounded corners split their arc into steps of 30 degrees or less.\n */\nconst SMOOTH_WALL_MIN_DOT = Math.cos(35 * Math.PI / 180);\n\n/**\n * How many times longer than its neighbour a wall has to be to keep its own normal where they meet.\n */\nconst LONG_WALL_RATIO = 2;\n\n/**\n * Returns the normals of each wall of a rounded ring, indexed by the wall's end vertex, so that the\n * lighting blends across a rounded corner. Boundary and zero-length walls get `null`.\n * @param ring - Ring as passed to the bucket, closed or open\n */\nexport function roundedWallNormals(ring: Point[]): Array<WallNormals | null> {\n    const perps: Point[] = [null];\n    for (let p = 1; p < ring.length; p++) {\n        const edge = ring[p].sub(ring[p - 1]);\n        const isWall = !isBoundaryEdge(ring[p], ring[p - 1]) && edge.mag() > 0;\n        perps.push(isWall ? edge._perp() : null);\n    }\n\n    const last = ring.length - 1;\n    const isClosed = last > 1 && ring[0].equals(ring[last]);\n    const normals: Array<WallNormals | null> = [null];\n    for (let p = 1; p <= last; p++) {\n        const perp = perps[p];\n        if (!perp) {\n            normals.push(null);\n            continue;\n        }\n        const previous = isClosed && p === 1 ? perps[last] : perps[p - 1];\n        const next = isClosed && p === last ? perps[1] : perps[p + 1];\n        normals.push({start: smoothNormal(perp, previous), end: smoothNormal(perp, next)});\n    }\n    return normals;\n}\n\n/**\n * Returns the normal of a wall at the vertex it shares with a neighbouring wall. At a shallow turn both\n * walls share one normal: the much longer wall's own, which keeps a straight wall evenly lit up to the\n * arc, or else their average weighted by length. At a sharp turn the wall keeps its own.\n * @param perp - Perpendicular of the wall, as long as the wall\n * @param neighbour - Perpendicular of the neighbouring wall, if there is one\n */\nfunction smoothNormal(perp: Point, neighbour?: Point): Point {\n    if (!neighbour) {\n        return perp.unit();\n    }\n    const length = perp.mag();\n    const neighbourLength = neighbour.mag();\n    const isSharpTurn = perp.x * neighbour.x + perp.y * neighbour.y < SMOOTH_WALL_MIN_DOT * length * neighbourLength;\n    if (isSharpTurn || length >= LONG_WALL_RATIO * neighbourLength) {\n        return perp.unit();\n    }\n    if (neighbourLength >= LONG_WALL_RATIO * length) {\n        return neighbour.unit();\n    }\n    return perp.add(neighbour)._unit();\n}\n\n/**\n * Rounds the corners of a single ring.\n *\n * Corners that tile clipping created are left sharp: they belong to the cut rather than to the\n * feature, and the neighbouring tile cuts the same feature elsewhere, so rounding them would leave\n * the two halves out of step. Every vertex ends up on the integer tile grid, because triangulation,\n * subdivision and the vertex buffers snap and deduplicate vertices there - arcs finer than a tile\n * unit would otherwise be merged only after they were triangulated, turning the mesh into spikes.\n *\n * A ring that collapses into fewer than three distinct vertices is returned unchanged.\n * @param ring - Ring to round, closed or open\n * @param distanceInTileUnits - Corner rounding distance, already converted to tile units\n */\nfunction roundRing(ring: Point[], distanceInTileUnits: number): Point[] {\n    if (!ring || ring.length < 3) {\n        return ring;\n    }\n\n    const isClosed = ring[0].x === ring[ring.length - 1].x && ring[0].y === ring[ring.length - 1].y;\n    const vertexCount = isClosed ? ring.length - 1 : ring.length;\n\n    if (vertexCount < 3) {\n        return ring;\n    }\n\n    const newRing: Point[] = [];\n\n    let previousIsBoundary = isBoundaryEdge(ring[vertexCount - 1], ring[0]);\n\n    for (let i = 0; i < vertexCount; i++) {\n        const previous = ring[(i - 1 + vertexCount) % vertexCount];\n        const current = ring[i];\n        const next = ring[(i + 1) % vertexCount];\n        const nextIsBoundary = isBoundaryEdge(current, next);\n\n        if (previousIsBoundary || nextIsBoundary) {\n            newRing.push(current.clone());\n        } else {\n            appendRoundCorner(newRing, previous, current, next, distanceInTileUnits);\n        }\n\n        previousIsBoundary = nextIsBoundary;\n    }\n\n    const snapped = snapToIntegerGrid(newRing);\n\n    if (snapped.length < 3) {\n        return ring;\n    }\n\n    if (isClosed) {\n        snapped.push(snapped[0].clone());\n    }\n\n    return snapped;\n}\n\n/**\n * Rounds every vertex to the integer tile grid, dropping vertices that collapse onto their neighbour.\n * The ring is treated as closed, so the wrap-around duplicate is dropped as well.\n * @param ring - Ring to snap\n */\nfunction snapToIntegerGrid(ring: Point[]): Point[] {\n    const snapped: Point[] = [];\n\n    for (const p of ring) {\n        const point = p.round();\n        const previous = snapped[snapped.length - 1];\n\n        if (previous?.x === point.x && previous?.y === point.y) {\n            continue;\n        }\n\n        snapped.push(point);\n    }\n\n    while (snapped.length > 1 && snapped[0].x === snapped[snapped.length - 1].x && snapped[0].y === snapped[snapped.length - 1].y) {\n        snapped.pop();\n    }\n\n    return snapped;\n}\n\n/**\n * Appends the arc that replaces one corner, or the corner itself when it is too shallow or too sharp\n * to round.\n * @param newRing - Ring being built, the arc points are appended to it\n * @param prev - Vertex before the corner\n * @param current - The corner\n * @param next - Vertex after the corner\n * @param distanceInTileUnits - Corner rounding distance, already converted to tile units\n */\nfunction appendRoundCorner(\n    newRing: Point[],\n    prev: Point,\n    current: Point,\n    next: Point,\n    distanceInTileUnits: number\n): void {\n    // Unit edge vectors from the current vertex towards its neighbours\n    const ua = prev.sub(current);\n    const ub = next.sub(current);\n    const lenA = ua.mag();\n    const lenB = ub.mag();\n\n    if (lenA < 1e-6 || lenB < 1e-6) {\n        newRing.push(current.clone());\n        return;\n    }\n\n    ua._div(lenA);\n    ub._div(lenB);\n\n    // Straight lines or zero-degree turns\n    const dot = ua.x * ub.x + ua.y * ub.y;\n    if (Math.abs(dot) > Math.cos(5 * Math.PI / 180)) {\n        newRing.push(current.clone());\n        return;\n    }\n\n    // we clamp to not have circles in the extremes\n    const maxEdgeLenPercent = 0.2;\n    const r = Math.min(distanceInTileUnits, lenA * maxEdgeLenPercent, lenB * maxEdgeLenPercent);\n\n    // Tangent points on edges to prevPoint and nextPoint\n    const tangentA = current.add(ua.mult(r));\n    const tangentB = current.add(ub.mult(r));\n\n    // Center of the rounding arc, at r / cos(theta/2) along the bisector\n    const cosHalfTheta = Math.sqrt((1 + dot) / 2);\n    const center = current.add(ua.add(ub)._unit()._mult(r / cosHalfTheta));\n\n    // Both tangent points lie on the arc circle, so rotating tangent A around the center by the angle\n    // between the two radii traces the fillet onto tangent B along the shortest arc.\n    const sweepAngle = tangentA.sub(center).angleWith(tangentB.sub(center));\n\n    // ~30 deg per segment; epsilon keeps fp noise from adding one at exact multiples.\n    const numSegments = Math.max(2, Math.ceil(Math.abs(sweepAngle) / (Math.PI / 6) - 1e-6));\n    for (let s = 0; s <= numSegments; s++) {\n        newRing.push(tangentA.rotateAround(sweepAngle * (s / numSegments), center));\n    }\n}\n", "import {FillExtrusionLayoutArray, PosArray} from '../array_types.g.ts';\nimport {members as layoutAttributes, centroidAttributes} from './fill_extrusion_attributes.ts';\nimport {type Segment, SegmentVector} from '../segment.ts';\nimport {ProgramConfigurationSet} from '../program_configuration.ts';\nimport {TriangleIndexArray} from '../index_array_type.ts';\nimport {isBoundaryEdge, isEntirelyOutside} from '../extent_bounds.ts';\nimport {VectorTileFeature} from '@mapbox/vector-tile';\nimport {classifyRings} from '@maplibre/maplibre-gl-style-spec';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer.ts';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features.ts';\nimport {loadGeometry} from '../load_geometry.ts';\nimport {toEvaluationFeature} from '../evaluation_feature.ts';\nimport {EvaluationParameters} from '../../style/evaluation_parameters.ts';\nimport {subdividePolygon, subdivideVertexLine} from '../../render/subdivision.ts';\nimport {fillLargeMeshArrays} from '../../render/fill_large_mesh_arrays.ts';\nimport {getTileUnitsForMeters, roundPolygonCornersIfNeeded, roundedWallNormals} from './round_polygon_corners.ts';\n\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {\n    Bucket,\n    BucketParameters,\n    BucketFeature,\n    BucketDependencyParameters,\n    IndexedFeature,\n    PopulateParameters\n} from '../bucket.ts';\nimport type {FillExtrusionStyleLayer} from '../../style/style_layer/fill_extrusion_style_layer.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {IndexBuffer} from '../../webgl/index_buffer.ts';\nimport type {VertexBuffer} from '../../webgl/vertex_buffer.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state.ts';\nimport type {ImagePosition} from '../../render/image_atlas.ts';\nimport type {SubdivisionGranularitySetting} from '../../render/subdivision_granularity_settings.ts';\nimport type {VectorTileLayerLike} from '@maplibre/vt-pbf';\n\nconst FACTOR = Math.pow(2, 13);\n\nfunction addVertex(vertexArray, x, y, nx, ny, nz, t, e) {\n    vertexArray.emplaceBack(\n        // a_pos\n        x,\n        y,\n        // a_normal_ed: 3-component normal and 1-component edgedistance\n        Math.floor(nx * FACTOR) * 2 + t,\n        ny * FACTOR * 2,\n        nz * FACTOR * 2,\n        // edgedistance (used for wrapping patterns around extrusion sides)\n        Math.round(e)\n    );\n}\n\ntype CentroidAccumulator = {\n    x: number;\n    y: number;\n    sampleCount: number;\n};\n\nexport class FillExtrusionBucket implements Bucket {\n    index: number;\n    zoom: number;\n    overscaling: number;\n    layers: FillExtrusionStyleLayer[];\n    layerIds: string[];\n    stateDependentLayers: FillExtrusionStyleLayer[];\n    stateDependentLayerIds: string[];\n\n    layoutVertexArray: FillExtrusionLayoutArray;\n    layoutVertexBuffer: VertexBuffer;\n\n    centroidVertexArray: PosArray;\n    centroidVertexBuffer: VertexBuffer;\n\n    indexArray: TriangleIndexArray;\n    indexBuffer: IndexBuffer;\n\n    hasDependencies: boolean;\n    programConfigurations: ProgramConfigurationSet<FillExtrusionStyleLayer>;\n    segments: SegmentVector;\n    uploaded: boolean;\n    features: BucketFeature[];\n\n    constructor(options: BucketParameters<FillExtrusionStyleLayer>) {\n        this.zoom = options.zoom;\n        this.overscaling = options.overscaling;\n        this.layers = options.layers;\n        this.layerIds = this.layers.map(layer => layer.id);\n        this.index = options.index;\n        this.hasDependencies = false;\n\n        this.layoutVertexArray = new FillExtrusionLayoutArray();\n        this.centroidVertexArray = new PosArray();\n        this.indexArray = new TriangleIndexArray();\n        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n        this.segments = new SegmentVector();\n        this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n    }\n\n    populate(features: IndexedFeature[], options: PopulateParameters, canonical: CanonicalTileID): void {\n        this.features = [];\n        this.hasDependencies = hasPattern('fill-extrusion', this.layers, options);\n\n        const globalProperties = new EvaluationParameters(this.zoom);\n        const layer = this.layers[0];\n        const roundedCornerDistanceInMeters = layer.layout.get('fill-extrusion-rounded-corner-distance');\n        const roundedCornerDistance = roundedCornerDistanceInMeters > 0 ? getTileUnitsForMeters(roundedCornerDistanceInMeters, canonical) : 0;\n        const needGeometry = layer._featureFilter.needGeometry;\n\n        for (const {feature, id, index, sourceLayerIndex} of features) {\n            const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n            if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue;\n\n            const rawGeometry = needGeometry ? evaluationFeature.geometry : loadGeometry(feature);\n            const geometry = roundPolygonCornersIfNeeded(rawGeometry, roundedCornerDistance);\n\n            const bucketFeature: BucketFeature = {\n                id,\n                sourceLayerIndex,\n                index,\n                geometry,\n                properties: feature.properties,\n                type: feature.type,\n                patterns: {}\n            };\n\n            if (this.hasDependencies) {\n                this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, {zoom: this.zoom}, options));\n            } else {\n                this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}, options.subdivisionGranularity);\n            }\n\n            options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true);\n        }\n    }\n\n    addFeatures({options, canonical, patternPositions}: BucketDependencyParameters): void {\n        for (const feature of this.features) {\n            const {geometry} = feature;\n            this.addFeature(feature, geometry, feature.index, canonical, patternPositions, options.subdivisionGranularity);\n        }\n    }\n\n    update(states: FeatureStates, vtLayer: VectorTileLayerLike, imagePositions: {[_: string]: ImagePosition}): void {\n        if (!this.stateDependentLayers.length) return;\n        this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, {\n            imagePositions\n        });\n    }\n\n    isEmpty(): boolean {\n        return this.layoutVertexArray.length === 0 && this.centroidVertexArray.length === 0;\n    }\n\n    uploadPending(): boolean {\n        return !this.uploaded || this.programConfigurations.needsUpload;\n    }\n\n    upload(context: Context): void {\n        if (!this.uploaded) {\n            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n            this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true);\n            this.indexBuffer = context.createIndexBuffer(this.indexArray);\n        }\n        this.programConfigurations.upload(context);\n        this.uploaded = true;\n    }\n\n    destroy(): void {\n        if (!this.layoutVertexBuffer) return;\n        this.layoutVertexBuffer.destroy();\n        this.indexBuffer.destroy();\n        this.programConfigurations.destroy();\n        this.segments.destroy();\n        this.centroidVertexBuffer.destroy();\n    }\n\n    addFeature(feature: BucketFeature, geometry: Point[][], index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}, subdivisionGranularity: SubdivisionGranularitySetting): void {\n        for (const polygon of classifyRings(geometry, EARCUT_MAX_RINGS)) {\n            // Compute polygon centroid to calculate elevation in GPU\n            const centroid: CentroidAccumulator = {x: 0, y: 0, sampleCount: 0};\n            const oldVertexCount = this.layoutVertexArray.length;\n            this.processPolygon(centroid, canonical, feature, polygon, subdivisionGranularity);\n\n            const addedVertices = this.layoutVertexArray.length - oldVertexCount;\n\n            const centroidX = Math.floor(centroid.x / centroid.sampleCount);\n            const centroidY = Math.floor(centroid.y / centroid.sampleCount);\n\n            for (let i = 0; i < addedVertices; i++) {\n                this.centroidVertexArray.emplaceBack(\n                    centroidX,\n                    centroidY\n                );\n            }\n        }\n\n        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {imagePositions, canonical});\n    }\n\n    private processPolygon(\n        centroid: CentroidAccumulator,\n        canonical: CanonicalTileID,\n        feature: BucketFeature,\n        polygon: Point[][],\n        subdivisionGranularity: SubdivisionGranularitySetting\n    ): void {\n        if (polygon.length < 1) {\n            return;\n        }\n\n        if (isEntirelyOutside(polygon[0])) {\n            return;\n        }\n\n        // Only consider the un-subdivided polygon outer ring for centroid calculation\n        for (const ring of polygon) {\n            if (ring.length === 0) {\n                continue;\n            }\n\n            // Here we don't mind if a hole ring is entirely outside, unlike when generating geometry later.\n            accumulatePointsToCentroid(centroid, ring);\n        }\n\n        const segmentReference = {\n            segment: this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray)\n        };\n        const granularity = subdivisionGranularity.fill.getGranularityForZoomLevel(canonical.z);\n        const isPolygon = VectorTileFeature.types[feature.type] === 'Polygon';\n\n        for (const ring of polygon) {\n            if (ring.length === 0) {\n                continue;\n            }\n\n            if (isEntirelyOutside(ring)) {\n                continue;\n            }\n\n            const subdividedRing = subdivideVertexLine(ring, granularity, isPolygon);\n            this._generateSideFaces(subdividedRing, segmentReference);\n        }\n\n        // Only triangulate and draw the area of the feature if it is a polygon\n        // Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined\n        if (!isPolygon)\n            return;\n\n        // Do not generate outlines, since outlines already got subdivided earlier.\n        const subdividedPolygon = subdividePolygon(polygon, canonical, granularity, false);\n        const vertexArray = this.layoutVertexArray;\n\n        fillLargeMeshArrays(\n            (x, y) => {\n                addVertex(vertexArray, x, y, 0, 0, 1, 1, 0);\n            },\n            this.segments,\n            this.layoutVertexArray,\n            this.indexArray,\n            subdividedPolygon.verticesFlattened,\n            subdividedPolygon.indicesTriangles\n        );\n    }\n\n    /**\n     * Generates side faces for the supplied geometry. Assumes `geometry` to be a line string, like the output of {@link subdivideVertexLine}.\n     * For rings, it is assumed that the first and last vertex of `geometry` are equal.\n     */\n    private _generateSideFaces(geometry: Point[], segmentReference: {segment: Segment}): void {\n        let edgeDistance = 0;\n        const hasRoundedCorners = this.layers[0].layout.get('fill-extrusion-rounded-corner-distance') > 0;\n        const wallNormals = hasRoundedCorners ? roundedWallNormals(geometry) : null;\n\n        for (let p = 1; p < geometry.length; p++) {\n            const p1 = geometry[p];\n            const p2 = geometry[p - 1];\n\n            if (isBoundaryEdge(p1, p2) || (wallNormals && !wallNormals[p])) {\n                continue;\n            }\n\n            if (segmentReference.segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n                segmentReference.segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);\n            }\n\n            const perp = p1.sub(p2)._perp()._unit();\n            const {start, end} = wallNormals ? wallNormals[p] : {start: perp, end: perp};\n            const dist = p2.dist(p1);\n            if (edgeDistance + dist > 32768) edgeDistance = 0;\n\n            addVertex(this.layoutVertexArray, p1.x, p1.y, end.x, end.y, 0, 0, edgeDistance);\n            addVertex(this.layoutVertexArray, p1.x, p1.y, end.x, end.y, 0, 1, edgeDistance);\n\n            edgeDistance += dist;\n\n            addVertex(this.layoutVertexArray, p2.x, p2.y, start.x, start.y, 0, 0, edgeDistance);\n            addVertex(this.layoutVertexArray, p2.x, p2.y, start.x, start.y, 0, 1, edgeDistance);\n\n            const bottomRight = segmentReference.segment.vertexLength;\n\n            // ┌──────┐\n            // │ 0  1 │ Counter-clockwise winding order.\n            // │      │ Triangle 1: 0 => 2 => 1\n            // │ 2  3 │ Triangle 2: 1 => 2 => 3\n            // └──────┘\n            this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1);\n            this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3);\n\n            segmentReference.segment.vertexLength += 4;\n            segmentReference.segment.primitiveLength += 2;\n        }\n    }\n}\n\n/**\n * Accumulates geometry to centroid. Geometry can be either a polygon ring, a line string or a closed line string.\n * In case of a polygon ring or line ring, the last vertex is ignored if it is the same as the first vertex.\n */\nfunction accumulatePointsToCentroid(centroid: CentroidAccumulator, geometry: Point[]): void {\n    for (let i = 0; i < geometry.length; i++) {\n        const p = geometry[i];\n\n        if (i === geometry.length - 1 && geometry[0].x === p.x && geometry[0].y === p.y) {\n            continue;\n        }\n\n        centroid.x += p.x;\n        centroid.y += p.y;\n        centroid.sampleCount++;\n    }\n}\n\nregister('FillExtrusionBucket', FillExtrusionBucket, {omit: ['layers', 'features']});\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type FillExtrusionLayoutProps = {\n    \"fill-extrusion-rounded-corner-distance\": DataConstantProperty<number>,\n};\n\nexport type FillExtrusionLayoutPropsPossiblyEvaluated = {\n    \"fill-extrusion-rounded-corner-distance\": number,\n};\n\nlet layout: Properties<FillExtrusionLayoutProps>;\nconst getLayout = (): Properties<FillExtrusionLayoutProps> => layout = layout || new Properties({\n    \"fill-extrusion-rounded-corner-distance\": new DataConstantProperty(styleSpec[\"layout_fill-extrusion\"][\"fill-extrusion-rounded-corner-distance\"] as any as StylePropertySpecification, \"fill-extrusion-rounded-corner-distance\"),\n});\n\nexport type FillExtrusionPaintProps = {\n    \"fill-extrusion-opacity\": DataConstantProperty<number>,\n    \"fill-extrusion-color\": DataDrivenProperty<Color>,\n    \"fill-extrusion-translate\": DataConstantProperty<[number, number]>,\n    \"fill-extrusion-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"fill-extrusion-pattern\": CrossFadedDataDrivenProperty<ResolvedImage>,\n    \"fill-extrusion-height\": DataDrivenProperty<number>,\n    \"fill-extrusion-base\": DataDrivenProperty<number>,\n    \"fill-extrusion-vertical-gradient\": DataConstantProperty<boolean>,\n};\n\nexport type FillExtrusionPaintPropsPossiblyEvaluated = {\n    \"fill-extrusion-opacity\": number,\n    \"fill-extrusion-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"fill-extrusion-translate\": [number, number],\n    \"fill-extrusion-translate-anchor\": \"map\" | \"viewport\",\n    \"fill-extrusion-pattern\": PossiblyEvaluatedPropertyValue<CrossFaded<ResolvedImage>>,\n    \"fill-extrusion-height\": PossiblyEvaluatedPropertyValue<number>,\n    \"fill-extrusion-base\": PossiblyEvaluatedPropertyValue<number>,\n    \"fill-extrusion-vertical-gradient\": boolean,\n};\n\nlet paint: Properties<FillExtrusionPaintProps>;\nconst getPaint = (): Properties<FillExtrusionPaintProps> => paint = paint || new Properties({\n    \"fill-extrusion-opacity\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-opacity\"] as any as StylePropertySpecification, \"fill-extrusion-opacity\"),\n    \"fill-extrusion-color\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-color\"] as any as StylePropertySpecification, \"fill-extrusion-color\"),\n    \"fill-extrusion-translate\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate\"] as any as StylePropertySpecification, \"fill-extrusion-translate\"),\n    \"fill-extrusion-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate-anchor\"] as any as StylePropertySpecification, \"fill-extrusion-translate-anchor\"),\n    \"fill-extrusion-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-pattern\"] as any as StylePropertySpecification, \"fill-extrusion-pattern\"),\n    \"fill-extrusion-height\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-height\"] as any as StylePropertySpecification, \"fill-extrusion-height\"),\n    \"fill-extrusion-base\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-base\"] as any as StylePropertySpecification, \"fill-extrusion-base\"),\n    \"fill-extrusion-vertical-gradient\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-vertical-gradient\"] as any as StylePropertySpecification, \"fill-extrusion-vertical-gradient\"),\n});\n\nexport default ({ get paint(): Properties<FillExtrusionPaintProps> { return getPaint() }, get layout(): Properties<FillExtrusionLayoutProps> { return getLayout() } });", "import {type QueryIntersectsFeatureParams, StyleLayer} from '../style_layer.ts';\nimport {FillExtrusionBucket} from '../../data/bucket/fill_extrusion_bucket.ts';\nimport {polygonIntersectsPolygon, polygonIntersectsMultiPolygon} from '../../util/intersection_tests.ts';\nimport {translateDistance, translate} from '../query_utils.ts';\nimport properties, {type FillExtrusionLayoutPropsPossiblyEvaluated, type FillExtrusionPaintPropsPossiblyEvaluated} from './fill_extrusion_style_layer_properties.g.ts';\nimport {type mat4, vec4} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\n\nimport type {Layout, Transitionable, Transitioning, PossiblyEvaluated} from '../properties.ts';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {BucketParameters} from '../../data/bucket.ts';\nimport type {FillExtrusionLayoutProps, FillExtrusionPaintProps} from './fill_extrusion_style_layer_properties.g.ts';\n\nexport class Point3D extends Point {\n    z: number;\n}\n\nexport const isFillExtrusionStyleLayer = (layer: StyleLayer): layer is FillExtrusionStyleLayer => layer.type === 'fill-extrusion';\n\nexport class FillExtrusionStyleLayer extends StyleLayer {\n    _unevaluatedLayout: Layout<FillExtrusionLayoutProps>;\n    layout: PossiblyEvaluated<FillExtrusionLayoutProps, FillExtrusionLayoutPropsPossiblyEvaluated>;\n\n    _transitionablePaint: Transitionable<FillExtrusionPaintProps>;\n    _transitioningPaint: Transitioning<FillExtrusionPaintProps>;\n    paint: PossiblyEvaluated<FillExtrusionPaintProps, FillExtrusionPaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n    }\n\n    createBucket(parameters: BucketParameters<FillExtrusionStyleLayer>): FillExtrusionBucket {\n        return new FillExtrusionBucket(parameters);\n    }\n\n    queryRadius(): number {\n        return translateDistance(this.paint.get('fill-extrusion-translate'));\n    }\n\n    is3D(): boolean {\n        return true;\n    }\n\n    queryIntersectsFeature({\n        queryGeometry,\n        feature,\n        featureState,\n        geometry,\n        transform,\n        pixelsToTileUnits,\n        pixelPosMatrix}: QueryIntersectsFeatureParams\n    ): boolean | number {\n\n        const translatedPolygon = translate(queryGeometry,\n            this.paint.get('fill-extrusion-translate'),\n            this.paint.get('fill-extrusion-translate-anchor'),\n            -transform.bearingInRadians, pixelsToTileUnits);\n\n        const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState);\n        const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState);\n\n        const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, 0);\n\n        const projected = projectExtrusion(geometry, base, height, pixelPosMatrix);\n        const projectedBase = projected[0];\n        const projectedTop = projected[1];\n        return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry);\n    }\n}\n\nfunction dot(a, b) {\n    return a.x * b.x + a.y * b.y;\n}\n\nexport function getIntersectionDistance(projectedQueryGeometry: Point3D[], projectedFace: Point3D[]): number {\n\n    if (projectedQueryGeometry.length === 1) {\n        // For point queries calculate the z at which the point intersects the face\n        // using barycentric coordinates.\n\n        // Find the barycentric coordinates of the projected point within the first\n        // triangle of the face, using only the xy plane. It doesn't matter if the\n        // point is outside the first triangle because all the triangles in the face\n        // are in the same plane.\n        //\n        // Check whether points are coincident and use other points if they are.\n        let i = 0;\n        const a = projectedFace[i++];\n        let b;\n        while (!b || a.equals(b)) {\n            b = projectedFace[i++];\n            if (!b) return Infinity;\n        }\n\n        // Loop until point `c` is not colinear with points `a` and `b`.\n        for (; i < projectedFace.length; i++) {\n            const c = projectedFace[i];\n\n            const p = projectedQueryGeometry[0];\n\n            const ab = b.sub(a);\n            const ac = c.sub(a);\n            const ap = p.sub(a);\n\n            const dotABAB = dot(ab, ab);\n            const dotABAC = dot(ab, ac);\n            const dotACAC = dot(ac, ac);\n            const dotAPAB = dot(ap, ab);\n            const dotAPAC = dot(ap, ac);\n            const denom = dotABAB * dotACAC - dotABAC * dotABAC;\n\n            const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom;\n            const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom;\n            const u = 1 - v - w;\n\n            // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection.\n            const distance = a.z * u + b.z * v + c.z * w;\n\n            if (isFinite(distance)) return distance;\n        }\n\n        return Infinity;\n\n    } else {\n        // The counts as closest is less clear when the query is a box. This\n        // returns the distance to the nearest point on the face, whether it is\n        // within the query or not. It could be more correct to return the\n        // distance to the closest point within the query box but this would be\n        // more complicated and expensive to calculate with little benefit.\n        let closestDistance = Infinity;\n        for (const p of projectedFace) {\n            closestDistance = Math.min(closestDistance, p.z);\n        }\n        return closestDistance;\n    }\n}\n\nfunction checkIntersection(projectedBase: Point3D[][], projectedTop: Point3D[][], projectedQueryGeometry: Point3D[]) {\n    let closestDistance = Infinity;\n\n    if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) {\n        closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]);\n    }\n\n    for (let r = 0; r < projectedTop.length; r++) {\n        const ringTop = projectedTop[r];\n        const ringBase = projectedBase[r];\n        for (let p = 0; p < ringTop.length - 1; p++) {\n            const topA = ringTop[p];\n            const topB = ringTop[p + 1];\n            const baseA = ringBase[p];\n            const baseB = ringBase[p + 1];\n            const face = [topA, topB, baseB, baseA, topA];\n            if (polygonIntersectsPolygon(projectedQueryGeometry, face)) {\n                closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face));\n            }\n        }\n    }\n\n    return closestDistance === Infinity ? false : closestDistance;\n}\n\n/*\n * Project the geometry using matrix `m`. This is essentially doing\n * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication\n * is inlined so that parts of the projection that are the same across\n * different points can only be done once. This produced a measurable\n * performance improvement.\n */\nfunction projectExtrusion(geometry: Point[][], zBase: number, zTop: number, m: mat4): [Point3D[][], Point3D[][]] {\n    const projectedBase = [] as Point3D[][];\n    const projectedTop = [] as Point3D[][];\n    const baseXZ = m[8] * zBase;\n    const baseYZ = m[9] * zBase;\n    const baseZZ = m[10] * zBase;\n    const baseWZ = m[11] * zBase;\n    const topXZ = m[8] * zTop;\n    const topYZ = m[9] * zTop;\n    const topZZ = m[10] * zTop;\n    const topWZ = m[11] * zTop;\n\n    for (const r of geometry) {\n        const ringBase = [] as Point3D[];\n        const ringTop = [] as Point3D[];\n        for (const p of r) {\n            const x = p.x;\n            const y = p.y;\n\n            const sX = m[0] * x + m[4] * y + m[12];\n            const sY = m[1] * x + m[5] * y + m[13];\n            const sZ = m[2] * x + m[6] * y + m[14];\n            const sW = m[3] * x + m[7] * y + m[15];\n\n            const baseX = sX + baseXZ;\n            const baseY = sY + baseYZ;\n            const baseZ = sZ + baseZZ;\n            const baseW = sW + baseWZ;\n\n            const topX = sX + topXZ;\n            const topY = sY + topYZ;\n            const topZ = sZ + topZZ;\n            const topW = sW + topWZ;\n\n            const b = new Point(baseX / baseW, baseY / baseW) as Point3D;\n            b.z = baseZ / baseW;\n            ringBase.push(b);\n\n            const t = new Point(topX / topW, topY / topW) as Point3D;\n            t.z = topZ / topW;\n            ringTop.push(t);\n        }\n        projectedBase.push(ringBase);\n        projectedTop.push(ringTop);\n    }\n    return [projectedBase, projectedTop];\n}\n\nfunction projectQueryGeometry(queryGeometry: Point[], pixelPosMatrix: mat4, z: number) {\n    const projectedQueryGeometry = [];\n    for (const p of queryGeometry) {\n        const v = [p.x, p.y, z, 1] as vec4;\n        vec4.transformMat4(v, v, pixelPosMatrix);\n        projectedQueryGeometry.push(new Point(v[0] / v[3], v[1] / v[3]));\n    }\n    return projectedQueryGeometry;\n}\n", "//#region src/simplify.ts\n/**\n* calculate simplification data using optimized Douglas-Peucker algorithm\n* @param coords - flat array of coordinates\n* @param first - index of the first coordinate in the segment\n* @param last - index of the last coordinate in the segment\n* @param sqTolerance - square tolerance value\n*/\nfunction simplify(coords, first, last, sqTolerance) {\n\tconst stack = [first, last];\n\twhile (stack.length) {\n\t\tlast = stack.pop();\n\t\tfirst = stack.pop();\n\t\tsimplifySegment(coords, first, last, sqTolerance, stack);\n\t}\n}\nfunction simplifySegment(coords, first, last, sqTolerance, stack) {\n\tlet maxSqDist = sqTolerance;\n\tconst mid = first + (last - first >> 1);\n\tlet minPosToMid = last - first;\n\tlet index;\n\tconst ax = coords[first];\n\tconst ay = coords[first + 1];\n\tconst bx = coords[last];\n\tconst by = coords[last + 1];\n\tfor (let i = first + 3; i < last; i += 3) {\n\t\tconst d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);\n\t\tif (d > maxSqDist) {\n\t\t\tindex = i;\n\t\t\tmaxSqDist = d;\n\t\t\tcontinue;\n\t\t}\n\t\tif (d === maxSqDist) {\n\t\t\tconst posToMid = Math.abs(i - mid);\n\t\t\tif (posToMid < minPosToMid) {\n\t\t\t\tindex = i;\n\t\t\t\tminPosToMid = posToMid;\n\t\t\t}\n\t\t}\n\t}\n\tif (maxSqDist > sqTolerance) {\n\t\tcoords[index + 2] = maxSqDist;\n\t\tif (index - first > 3) stack.push(first, index);\n\t\tif (last - index > 3) stack.push(index, last);\n\t}\n}\n/**\n* Claculates the square distance from a point to a segment\n* @param px - x coordinate of the point\n* @param py - y coordinate of the point\n* @param x - x coordinate of the first segment endpoint\n* @param y - y coordinate of the first segment endpoint\n* @param bx - x coordinate of the second segment endpoint\n* @param by - y coordinate of the second segment endpoint\n* @returns square distance from a point to a segment\n*/\nfunction getSqSegDist(px, py, x, y, bx, by) {\n\tlet dx = bx - x;\n\tlet dy = by - y;\n\tif (dx !== 0 || dy !== 0) {\n\t\tconst t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);\n\t\tif (t > 1) {\n\t\t\tx = bx;\n\t\t\ty = by;\n\t\t} else if (t > 0) {\n\t\t\tx += dx * t;\n\t\t\ty += dy * t;\n\t\t}\n\t}\n\tdx = px - x;\n\tdy = py - y;\n\treturn dx * dx + dy * dy;\n}\n//#endregion\n//#region src/feature.ts\n/**\n* \n* @param id - the feature's ID\n* @param type - the feature's type\n* @param geom - the feature's geometry\n* @param tags - the feature's properties\n* @returns the created feature\n*/\nfunction createFeature(id, type, geom, tags) {\n\tconst data = {\n\t\ttype,\n\t\tgeom\n\t};\n\tconst feature = {\n\t\tid: id == null ? null : id,\n\t\ttype: data.type,\n\t\tgeometry: data.geom,\n\t\ttags,\n\t\tminX: Infinity,\n\t\tminY: Infinity,\n\t\tmaxX: -Infinity,\n\t\tmaxY: -Infinity\n\t};\n\tswitch (data.type) {\n\t\tcase \"Point\":\n\t\tcase \"MultiPoint\":\n\t\t\tcalcLineBBox(feature, data.geom);\n\t\t\tbreak;\n\t\tcase \"LineString\":\n\t\t\tcalcLineBBox(feature, data.geom.points);\n\t\t\tbreak;\n\t\tcase \"Polygon\":\n\t\t\tcalcLineBBox(feature, data.geom[0].points);\n\t\t\tbreak;\n\t\tcase \"MultiLineString\":\n\t\t\tfor (const line of data.geom) calcLineBBox(feature, line.points);\n\t\t\tbreak;\n\t\tcase \"MultiPolygon\": for (const polygon of data.geom) calcLineBBox(feature, polygon[0].points);\n\t}\n\treturn feature;\n}\nfunction optimizeLineMemory(line) {\n\tconst lineImmutable = line;\n\tif (line.points.length > 64) lineImmutable.points = new Float64Array(line.points);\n}\nfunction calcLineBBox(feature, geom) {\n\tfor (let i = 0; i < geom.length; i += 3) {\n\t\tfeature.minX = Math.min(feature.minX, geom[i]);\n\t\tfeature.minY = Math.min(feature.minY, geom[i + 1]);\n\t\tfeature.maxX = Math.max(feature.maxX, geom[i]);\n\t\tfeature.maxY = Math.max(feature.maxY, geom[i + 1]);\n\t}\n}\n//#endregion\n//#region src/world-coordinate-helper.ts\n/**\n* Longitude and latitude, which spherical mercator puts in the world square.\n*/\nvar MercatorWorldCoordinateHelper = class {\n\tprojectX(lng) {\n\t\treturn lng / 360 + .5;\n\t}\n\tprojectY(lat) {\n\t\tconst sin = Math.sin(lat * Math.PI / 180);\n\t\tconst y = .5 - .25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;\n\t\treturn y < 0 ? 0 : y > 1 ? 1 : y;\n\t}\n\tunprojectX(x) {\n\t\treturn (x - .5) * 360;\n\t}\n\tunprojectY(y) {\n\t\tconst y2 = (180 - y * 360) * Math.PI / 180;\n\t\treturn 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;\n\t}\n};\n/**\n* Positions in the unit square already, see `coordinates` in {@link GeoJSONVTOptions}.\n*/\nvar IdentityWorldCoordinateHelper = class {\n\tprojectX(x) {\n\t\treturn x;\n\t}\n\tprojectY(y) {\n\t\treturn y;\n\t}\n\tunprojectX(x) {\n\t\treturn x;\n\t}\n\tunprojectY(y) {\n\t\treturn y;\n\t}\n};\nconst mercatorWorldCoordinateHelper = new MercatorWorldCoordinateHelper();\nconst identityWorldCoordinateHelper = new IdentityWorldCoordinateHelper();\nfunction getWorldCoordinateHelper(coordinates) {\n\treturn coordinates === \"unitSquare\" ? identityWorldCoordinateHelper : mercatorWorldCoordinateHelper;\n}\n//#endregion\n//#region src/convert.ts\nconst MAX_GEOMETRY_COLLECTION_DEPTH = 1024;\n/**\n* converts GeoJSON to internal source features (an intermediate projected JSON vector format with simplification data)\n* @param data\n* @param options\n* @param unlocated - the features without coordinates, by id: a feature with an id that converts to nothing is set in it, and one that converts to something is deleted from it\n* @returns\n*/\nfunction convertToInternal(data, options, unlocated) {\n\tconst features = [];\n\tswitch (data.type) {\n\t\tcase \"FeatureCollection\":\n\t\t\tfor (let i = 0; i < data.features.length; i++) convertFeature(features, data.features[i], options, unlocated, i);\n\t\t\tbreak;\n\t\tcase \"Feature\":\n\t\t\tconvertFeature(features, data, options, unlocated);\n\t\t\tbreak;\n\t\tdefault: convertFeature(features, {\n\t\t\ttype: \"Feature\",\n\t\t\tgeometry: data,\n\t\t\tproperties: void 0\n\t\t}, options, unlocated);\n\t}\n\treturn features;\n}\nfunction convertFeature(features, geojson, options, unlocated, index) {\n\tconst count = features.length;\n\tfeatureToInternal(features, geojson, options, index);\n\tif (!unlocated) return;\n\tconst id = getFeatureId(geojson, options, index);\n\tif (id == null) return;\n\tif (features.length > count) unlocated.delete(id);\n\telse unlocated.set(id, {\n\t\t...geojson,\n\t\tid\n\t});\n}\nfunction featureToInternal(features, geojson, options, index, depth = 0) {\n\tif (!geojson.geometry) return;\n\tif (depth > MAX_GEOMETRY_COLLECTION_DEPTH) throw new Error(\"GeometryCollection nesting exceeds supported depth: 1024\");\n\tif (geojson.geometry.type === \"GeometryCollection\") {\n\t\tconvertGeometryCollection(features, geojson, geojson.geometry, options, index, depth + 1);\n\t\treturn;\n\t}\n\tif (!geojson.geometry.coordinates?.length) return;\n\tconst id = getFeatureId(geojson, options, index);\n\tconst tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);\n\tconst worldCoordinateHelper = getWorldCoordinateHelper(options.coordinates);\n\tswitch (geojson.geometry.type) {\n\t\tcase \"Point\":\n\t\t\tconvertPointFeature(features, id, geojson.geometry, worldCoordinateHelper, geojson.properties);\n\t\t\treturn;\n\t\tcase \"MultiPoint\":\n\t\t\tconvertMultiPointFeature(features, id, geojson.geometry, worldCoordinateHelper, geojson.properties);\n\t\t\treturn;\n\t\tcase \"LineString\":\n\t\t\tconvertLineStringFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, geojson.properties);\n\t\t\treturn;\n\t\tcase \"MultiLineString\":\n\t\t\tconvertMultiLineStringFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, options, geojson.properties);\n\t\t\treturn;\n\t\tcase \"Polygon\":\n\t\t\tconvertPolygonFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, geojson.properties);\n\t\t\treturn;\n\t\tcase \"MultiPolygon\":\n\t\t\tconvertMultiPolygonFeature(features, id, geojson.geometry, tolerance, worldCoordinateHelper, geojson.properties);\n\t\t\treturn;\n\t\tdefault: throw new Error(\"Input data is not a valid GeoJSON object.\");\n\t}\n}\nfunction getFeatureId(geojson, options, index) {\n\tif (options.promoteId) return geojson.properties?.[options.promoteId];\n\tif (options.generateId) return index || 0;\n\treturn geojson.id;\n}\nfunction convertGeometryCollection(features, geojson, geometry, options, index, depth = 0) {\n\tfor (const geom of geometry.geometries) featureToInternal(features, {\n\t\tid: geojson.id,\n\t\ttype: \"Feature\",\n\t\tgeometry: geom,\n\t\tproperties: geojson.properties\n\t}, options, index, depth);\n}\nfunction convertPointFeature(features, id, geom, worldCoordinateHelper, properties) {\n\tconst out = [];\n\tout.push(worldCoordinateHelper.projectX(geom.coordinates[0]), worldCoordinateHelper.projectY(geom.coordinates[1]), 0);\n\tfeatures.push(createFeature(id, \"Point\", out, properties));\n}\nfunction convertMultiPointFeature(features, id, geom, worldCoordinateHelper, properties) {\n\tconst out = [];\n\tfor (const coords of geom.coordinates) out.push(worldCoordinateHelper.projectX(coords[0]), worldCoordinateHelper.projectY(coords[1]), 0);\n\tfeatures.push(createFeature(id, \"MultiPoint\", out, properties));\n}\nfunction convertLineStringFeature(features, id, geom, tolerance, worldCoordinateHelper, properties) {\n\tconst out = { points: [] };\n\tconvertLine(geom.coordinates, out, tolerance, false, worldCoordinateHelper);\n\tfeatures.push(createFeature(id, \"LineString\", out, properties));\n}\nfunction convertMultiLineStringFeature(features, id, geom, tolerance, worldCoordinateHelper, options, properties) {\n\tif (options.lineMetrics) for (const line of geom.coordinates) {\n\t\tconst out = { points: [] };\n\t\tconvertLine(line, out, tolerance, false, worldCoordinateHelper);\n\t\tfeatures.push(createFeature(id, \"LineString\", out, properties));\n\t}\n\telse {\n\t\tconst out = [];\n\t\tconvertLines(geom.coordinates, out, tolerance, false, worldCoordinateHelper);\n\t\tfeatures.push(createFeature(id, \"MultiLineString\", out, properties));\n\t}\n}\nfunction convertPolygonFeature(features, id, geom, tolerance, worldCoordinateHelper, properties) {\n\tconst out = [];\n\tconvertLines(geom.coordinates, out, tolerance, true, worldCoordinateHelper);\n\tfeatures.push(createFeature(id, \"Polygon\", out, properties));\n}\nfunction convertMultiPolygonFeature(features, id, geom, tolerance, worldCoordinateHelper, properties) {\n\tconst out = [];\n\tfor (const polygon of geom.coordinates) {\n\t\tconst polygonOut = [];\n\t\tconvertLines(polygon, polygonOut, tolerance, true, worldCoordinateHelper);\n\t\tif (!polygonOut.length) continue;\n\t\tout.push(polygonOut);\n\t}\n\tif (!out.length) return;\n\tfeatures.push(createFeature(id, \"MultiPolygon\", out, properties));\n}\nfunction convertLine(ring, out, tolerance, isPolygon, worldCoordinateHelper) {\n\tlet x0, y0;\n\tlet size = 0;\n\tfor (let j = 0; j < ring.length; j++) {\n\t\tconst x = worldCoordinateHelper.projectX(ring[j][0]);\n\t\tconst y = worldCoordinateHelper.projectY(ring[j][1]);\n\t\tout.points.push(x, y, 0);\n\t\tif (j > 0) {\n\t\t\tif (isPolygon) size += (x0 * y - x * y0) / 2;\n\t\t\telse size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2));\n\t\t}\n\t\tx0 = x;\n\t\ty0 = y;\n\t}\n\tconst last = out.points.length - 3;\n\tout.points[2] = 1;\n\tif (tolerance > 0) simplify(out.points, 0, last, tolerance);\n\tout.points[last + 2] = 1;\n\toptimizeLineMemory(out);\n\tout.size = Math.abs(size);\n\tout.start = 0;\n\tout.end = out.size;\n}\nfunction convertLines(rings, out, tolerance, isPolygon, worldCoordinateHelper) {\n\tfor (let i = 0; i < rings.length; i++) {\n\t\tconst geom = { points: [] };\n\t\tconvertLine(rings[i], geom, tolerance, isPolygon, worldCoordinateHelper);\n\t\tout.push(geom);\n\t}\n}\n//#endregion\n//#region src/deconvert.ts\n/**\n* Converts internal source features back to GeoJSON format.\n*/\nfunction convertToGeoJSON(source, worldCoordinateHelper = mercatorWorldCoordinateHelper) {\n\treturn {\n\t\ttype: \"FeatureCollection\",\n\t\tfeatures: source.map((feature) => featureToGeoJSON(feature, worldCoordinateHelper))\n\t};\n}\n/**\n* Converts a single internal feature to GeoJSON format.\n*/\nfunction featureToGeoJSON(feature, worldCoordinateHelper = mercatorWorldCoordinateHelper) {\n\tconst geojsonFeature = {\n\t\ttype: \"Feature\",\n\t\tgeometry: geometryToGeoJSON(feature, worldCoordinateHelper),\n\t\tproperties: feature.tags\n\t};\n\tif (feature.id != null) geojsonFeature.id = feature.id;\n\treturn geojsonFeature;\n}\n/**\n* Converts a single internal feature geometry to GeoJSON format.\n*/\nfunction geometryToGeoJSON(feature, worldCoordinateHelper) {\n\tconst { type, geometry } = feature;\n\tswitch (type) {\n\t\tcase \"Point\": return {\n\t\t\ttype,\n\t\t\tcoordinates: unprojectPoint(geometry[0], geometry[1], worldCoordinateHelper)\n\t\t};\n\t\tcase \"MultiPoint\": return {\n\t\t\ttype,\n\t\t\tcoordinates: unprojectPoints(geometry, worldCoordinateHelper)\n\t\t};\n\t\tcase \"LineString\": return {\n\t\t\ttype,\n\t\t\tcoordinates: unprojectPoints(geometry.points, worldCoordinateHelper)\n\t\t};\n\t\tcase \"MultiLineString\":\n\t\tcase \"Polygon\": return {\n\t\t\ttype,\n\t\t\tcoordinates: geometry.map((ring) => unprojectPoints(ring.points, worldCoordinateHelper))\n\t\t};\n\t\tcase \"MultiPolygon\": return {\n\t\t\ttype,\n\t\t\tcoordinates: geometry.map((polygon) => polygon.map((ring) => unprojectPoints(ring.points, worldCoordinateHelper)))\n\t\t};\n\t}\n}\nfunction unprojectPoints(coords, worldCoordinateHelper = mercatorWorldCoordinateHelper) {\n\tconst result = [];\n\tfor (let i = 0; i < coords.length; i += 3) result.push(unprojectPoint(coords[i], coords[i + 1], worldCoordinateHelper));\n\treturn result;\n}\nfunction unprojectPoint(x, y, worldCoordinateHelper) {\n\treturn [worldCoordinateHelper.unprojectX(x), worldCoordinateHelper.unprojectY(y)];\n}\n//#endregion\n//#region src/clip.ts\n/** \n* clip features between two vertical or horizontal axis-parallel lines:\n*     |        |\n*  ___|___     |     /\n* /   |   \\____|____/\n*     |        |\n*\n* @param features - the features to clip\n* @param scale - the scale to divide start and end inputs\n* @param start - the start of the clip range\n* @param end - the end of the clip range\n* @param axis - which axis to clip against\n* @param minAll - the minimum for all features in the relevant axis\n* @param maxAll - the maximum for all features in the relevant axis\n*/\nfunction clip(features, scale, start, end, axis, minAll, maxAll, options) {\n\tstart /= scale;\n\tend /= scale;\n\tif (minAll >= start && maxAll < end) return features;\n\tif (maxAll < start || minAll >= end) return null;\n\tconst clipped = [];\n\tfor (const feature of features) {\n\t\tconst min = axis === 0 ? feature.minX : feature.minY;\n\t\tconst max = axis === 0 ? feature.maxX : feature.maxY;\n\t\tif (min >= start && max < end) {\n\t\t\tclipped.push(feature);\n\t\t\tcontinue;\n\t\t}\n\t\tif (max < start || min >= end) continue;\n\t\tswitch (feature.type) {\n\t\t\tcase \"Point\":\n\t\t\tcase \"MultiPoint\":\n\t\t\t\tclipPointFeature(feature, clipped, start, end, axis);\n\t\t\t\tcontinue;\n\t\t\tcase \"LineString\":\n\t\t\t\tclipLineStringFeature(feature, clipped, start, end, axis, options);\n\t\t\t\tcontinue;\n\t\t\tcase \"MultiLineString\":\n\t\t\t\tclipMultiLineStringFeature(feature, clipped, start, end, axis);\n\t\t\t\tcontinue;\n\t\t\tcase \"Polygon\":\n\t\t\t\tclipPolygonFeature(feature, clipped, start, end, axis);\n\t\t\t\tcontinue;\n\t\t\tcase \"MultiPolygon\":\n\t\t\t\tclipMultiPolygonFeature(feature, clipped, start, end, axis);\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\tif (!clipped.length) return null;\n\treturn clipped;\n}\nfunction clipPointFeature(feature, clipped, start, end, axis) {\n\tconst geom = [];\n\tclipPoints(feature.geometry, geom, start, end, axis);\n\tif (!geom.length) return;\n\tconst type = geom.length === 3 ? \"Point\" : \"MultiPoint\";\n\tclipped.push(createFeature(feature.id, type, geom, feature.tags));\n}\nfunction clipLineStringFeature(feature, clipped, start, end, axis, options) {\n\tconst geom = [];\n\tclipLine(feature.geometry, geom, start, end, axis, false, options.lineMetrics);\n\tif (!geom.length) return;\n\tif (options.lineMetrics) {\n\t\tfor (const line of geom) clipped.push(createFeature(feature.id, \"LineString\", line, feature.tags));\n\t\treturn;\n\t}\n\tif (geom.length > 1) {\n\t\tclipped.push(createFeature(feature.id, \"MultiLineString\", geom, feature.tags));\n\t\treturn;\n\t}\n\tclipped.push(createFeature(feature.id, \"LineString\", geom[0], feature.tags));\n}\nfunction clipMultiLineStringFeature(feature, clipped, start, end, axis) {\n\tconst geom = [];\n\tclipLines(feature.geometry, geom, start, end, axis, false);\n\tif (!geom.length) return;\n\tif (geom.length === 1) {\n\t\tclipped.push(createFeature(feature.id, \"LineString\", geom[0], feature.tags));\n\t\treturn;\n\t}\n\tclipped.push(createFeature(feature.id, \"MultiLineString\", geom, feature.tags));\n}\nfunction clipPolygonFeature(feature, clipped, start, end, axis) {\n\tconst geom = [];\n\tclipLines(feature.geometry, geom, start, end, axis, true);\n\tif (!geom.length) return;\n\tclipped.push(createFeature(feature.id, \"Polygon\", geom, feature.tags));\n}\nfunction clipMultiPolygonFeature(feature, clipped, start, end, axis) {\n\tconst geom = [];\n\tfor (const polygon of feature.geometry) {\n\t\tconst newPolygon = [];\n\t\tclipLines(polygon, newPolygon, start, end, axis, true);\n\t\tif (!newPolygon.length) continue;\n\t\tgeom.push(newPolygon);\n\t}\n\tif (!geom.length) return;\n\tclipped.push(createFeature(feature.id, \"MultiPolygon\", geom, feature.tags));\n}\nfunction clipPoints(geom, newGeom, start, end, axis) {\n\tfor (let i = 0; i < geom.length; i += 3) {\n\t\tconst a = geom[i + axis];\n\t\tif (a >= start && a <= end) addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]);\n\t}\n}\nfunction clipLine(geom, newGeom, start, end, axis, isPolygon, trackMetrics) {\n\tlet slice = newSlice(geom);\n\tconst intersect = axis === 0 ? intersectX : intersectY;\n\tlet len = geom.start;\n\tlet segLen, t;\n\tfor (let i = 0; i < geom.points.length - 3; i += 3) {\n\t\tconst ax = geom.points[i];\n\t\tconst ay = geom.points[i + 1];\n\t\tconst az = geom.points[i + 2];\n\t\tconst bx = geom.points[i + 3];\n\t\tconst by = geom.points[i + 4];\n\t\tconst a = axis === 0 ? ax : ay;\n\t\tconst b = axis === 0 ? bx : by;\n\t\tlet exited = false;\n\t\tif (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));\n\t\tif (a < start) {\n\t\t\tif (b >= start) {\n\t\t\t\tt = intersect(slice, ax, ay, bx, by, start);\n\t\t\t\tif (trackMetrics) slice.start = len + segLen * t;\n\t\t\t}\n\t\t} else if (a > end) {\n\t\t\tif (b <= end) {\n\t\t\t\tt = intersect(slice, ax, ay, bx, by, end);\n\t\t\t\tif (trackMetrics) slice.start = len + segLen * t;\n\t\t\t}\n\t\t} else addPoint(slice.points, ax, ay, az);\n\t\tif (b < start && a >= start) {\n\t\t\tt = intersect(slice, ax, ay, bx, by, start);\n\t\t\texited = true;\n\t\t}\n\t\tif (b > end && a <= end) {\n\t\t\tt = intersect(slice, ax, ay, bx, by, end);\n\t\t\texited = true;\n\t\t}\n\t\tif (!isPolygon && exited) {\n\t\t\tif (trackMetrics) slice.end = len + segLen * t;\n\t\t\tnewGeom.push(slice);\n\t\t\tslice = newSlice(geom);\n\t\t}\n\t\tif (trackMetrics) len += segLen;\n\t}\n\tlet last = geom.points.length - 3;\n\tconst ax = geom.points[last];\n\tconst ay = geom.points[last + 1];\n\tconst az = geom.points[last + 2];\n\tconst a = axis === 0 ? ax : ay;\n\tif (a >= start && a <= end) addPoint(slice.points, ax, ay, az);\n\tlast = slice.points.length - 3;\n\tif (isPolygon && last >= 3 && (slice.points[last] !== slice.points[0] || slice.points[last + 1] !== slice.points[1])) addPoint(slice.points, slice.points[0], slice.points[1], slice.points[2]);\n\tif (slice.points.length) {\n\t\toptimizeLineMemory(slice);\n\t\tnewGeom.push(slice);\n\t}\n}\nfunction newSlice(line) {\n\treturn {\n\t\tpoints: [],\n\t\tsize: line.size,\n\t\tstart: line.start,\n\t\tend: line.end\n\t};\n}\nfunction clipLines(geom, newGeom, start, end, axis, isPolygon) {\n\tfor (const line of geom) clipLine(line, newGeom, start, end, axis, isPolygon, false);\n}\nfunction addPoint(out, x, y, z) {\n\tout.push(x, y, z);\n}\nfunction intersectX(out, ax, ay, bx, by, x) {\n\tconst t = (x - ax) / (bx - ax);\n\taddPoint(out.points, x, ay + (by - ay) * t, 1);\n\treturn t;\n}\nfunction intersectY(out, ax, ay, bx, by, y) {\n\tconst t = (y - ay) / (by - ay);\n\taddPoint(out.points, ax + (bx - ax) * t, y, 1);\n\treturn t;\n}\n//#endregion\n//#region src/wrap.ts\nfunction wrap(features, options) {\n\tif (!options.wrap) return features;\n\tconst buffer = options.buffer / options.extent;\n\tlet merged = features;\n\tconst left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options);\n\tconst right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options);\n\tif (!left && !right) return merged;\n\tmerged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || [];\n\tif (left) merged = shiftFeatureCoords(left, 1).concat(merged);\n\tif (right) merged = merged.concat(shiftFeatureCoords(right, -1));\n\treturn merged;\n}\nfunction shiftFeatureCoords(features, offset) {\n\tconst newFeatures = [];\n\tfor (const feature of features) switch (feature.type) {\n\t\tcase \"Point\":\n\t\tcase \"MultiPoint\": {\n\t\t\tconst newGeometry = shiftPointCoords(feature.geometry, offset);\n\t\t\tnewFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));\n\t\t\tcontinue;\n\t\t}\n\t\tcase \"LineString\": {\n\t\t\tconst newGeometry = shiftLineCoords(feature.geometry, offset);\n\t\t\tnewFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));\n\t\t\tcontinue;\n\t\t}\n\t\tcase \"MultiLineString\":\n\t\tcase \"Polygon\": {\n\t\t\tconst newGeometry = [];\n\t\t\tfor (const line of feature.geometry) newGeometry.push(shiftLineCoords(line, offset));\n\t\t\tnewFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));\n\t\t\tcontinue;\n\t\t}\n\t\tcase \"MultiPolygon\": {\n\t\t\tconst newGeometry = [];\n\t\t\tfor (const polygon of feature.geometry) {\n\t\t\t\tconst newPolygon = [];\n\t\t\t\tfor (const line of polygon) newPolygon.push(shiftLineCoords(line, offset));\n\t\t\t\tnewGeometry.push(newPolygon);\n\t\t\t}\n\t\t\tnewFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn newFeatures;\n}\nfunction shiftPointCoords(coords, offset) {\n\tconst newCoords = [];\n\tfor (let i = 0; i < coords.length; i += 3) newCoords.push(coords[i] + offset, coords[i + 1], coords[i + 2]);\n\treturn newCoords;\n}\nfunction shiftLineCoords(line, offset) {\n\tconst newLine = {\n\t\tpoints: [],\n\t\tsize: line.size\n\t};\n\tif (line.start !== void 0) {\n\t\tnewLine.start = line.start;\n\t\tnewLine.end = line.end;\n\t}\n\tfor (let i = 0; i < line.points.length; i += 3) newLine.points.push(line.points[i] + offset, line.points[i + 1], line.points[i + 2]);\n\toptimizeLineMemory(newLine);\n\treturn newLine;\n}\n//#endregion\n//#region src/difference.ts\n/**\n* Applies a GeoJSON Source Diff to an existing set of simplified features\n* @param source \n* @param dataDiff \n* @param options \n* @param unlocated - the features without coordinates, by id, so that an update can give them some\n* @returns \n*/\nfunction applySourceDiff(source, dataDiff, options, unlocated) {\n\tconst diff = diffToHashed(dataDiff, options);\n\tlet affected = [];\n\tif (diff.removeAll) {\n\t\taffected = source;\n\t\tsource = [];\n\t\tunlocated?.clear();\n\t}\n\tif (diff.remove.size || diff.add.size) {\n\t\tfor (const id of diff.remove) unlocated?.delete(id);\n\t\tconst removeFeatures = [];\n\t\tfor (const feature of source) if (diff.remove.has(feature.id) || diff.add.has(feature.id)) removeFeatures.push(feature);\n\t\tif (removeFeatures.length) {\n\t\t\taffected = affected.concat(removeFeatures);\n\t\t\tconst removeIds = new Set(removeFeatures.map((f) => f.id));\n\t\t\tsource = source.filter((f) => !removeIds.has(f.id));\n\t\t}\n\t\tif (diff.add.size) {\n\t\t\tlet addFeatures = convertToInternal({\n\t\t\t\ttype: \"FeatureCollection\",\n\t\t\t\tfeatures: Array.from(diff.add.values())\n\t\t\t}, options, unlocated);\n\t\t\taddFeatures = wrap(addFeatures, options);\n\t\t\taffected = affected.concat(addFeatures);\n\t\t\tsource = source.concat(addFeatures);\n\t\t}\n\t}\n\tif (diff.update.size) {\n\t\tconst oldFeaturesMap = /* @__PURE__ */ new Map();\n\t\tlet keepFeatures = [];\n\t\tfor (const feature of source) if (diff.update.has(feature.id)) oldFeaturesMap.set(feature.id, [...oldFeaturesMap.get(feature.id) || [], feature]);\n\t\telse keepFeatures.push(feature);\n\t\tfor (const [id, update] of diff.update) {\n\t\t\tconst oldFeatures = oldFeaturesMap.get(id);\n\t\t\tif (!oldFeatures || oldFeatures.length === 0) {\n\t\t\t\tif (!unlocated?.has(id)) continue;\n\t\t\t\tconst locatedFeatures = getUpdatedUnlocatedFeatures(id, update, options, unlocated);\n\t\t\t\taffected = affected.concat(locatedFeatures);\n\t\t\t\tkeepFeatures = keepFeatures.concat(locatedFeatures);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst updatedFeatures = getUpdatedFeatures(oldFeatures, update, options, unlocated);\n\t\t\taffected = affected.concat(oldFeatures, updatedFeatures);\n\t\t\tkeepFeatures = keepFeatures.concat(updatedFeatures);\n\t\t}\n\t\tsource = keepFeatures;\n\t}\n\treturn {\n\t\taffected,\n\t\tsource\n\t};\n}\n/**\n* Gets updated simplified feature(s) based on a diff update object.\n* @param vtFeatures - the original features\n* @param update - the update object to apply\n* @param options - the options to use for the wrap method\n* @param unlocated - the features without coordinates, by id, which a new geometry without coordinates adds the feature to\n* @returns Updated features. If geometry is updated, returns new feature(s) converted from geojson and wrapped, with the id the feature already has. If only properties are updated, returns feature(s) with tags updated.\n*/\nfunction getUpdatedFeatures(vtFeatures, update, options, unlocated) {\n\tconst changeGeometry = !!update.newGeometry;\n\tconst changeProps = hasPropertyChanges(update);\n\tif (changeGeometry) {\n\t\tconst vtFeature = vtFeatures[0];\n\t\tconst properties = changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags;\n\t\treturn convertNewGeometry(vtFeature.id, update.newGeometry, properties, options, unlocated);\n\t}\n\tif (changeProps) {\n\t\tconst updated = [];\n\t\tfor (const vtFeature of vtFeatures) {\n\t\t\tconst feature = { ...vtFeature };\n\t\t\tfeature.tags = applyPropertyUpdates(feature.tags, update);\n\t\t\tupdated.push(feature);\n\t\t}\n\t\treturn updated;\n\t}\n\treturn vtFeatures;\n}\n/**\n* Gets the features an update gives a feature without coordinates: none, unless its new geometry has some.\n* Its property changes apply either way.\n*/\nfunction getUpdatedUnlocatedFeatures(id, update, options, unlocated) {\n\tconst feature = unlocated.get(id);\n\tconst properties = hasPropertyChanges(update) ? applyPropertyUpdates(feature.properties, update) : feature.properties;\n\tif (!update.newGeometry) {\n\t\tunlocated.set(id, {\n\t\t\t...feature,\n\t\t\tproperties\n\t\t});\n\t\treturn [];\n\t}\n\treturn convertNewGeometry(id, update.newGeometry, properties, options, unlocated);\n}\n/**\n* Converts the new geometry of a feature to internal format, keeping the id the feature already has\n*/\nfunction convertNewGeometry(id, geometry, properties, options, unlocated) {\n\treturn wrap(convertToInternal({\n\t\ttype: \"FeatureCollection\",\n\t\tfeatures: [{\n\t\t\ttype: \"Feature\",\n\t\t\tid,\n\t\t\tgeometry,\n\t\t\tproperties\n\t\t}]\n\t}, {\n\t\t...options,\n\t\tpromoteId: void 0,\n\t\tgenerateId: false\n\t}, unlocated), options);\n}\nfunction hasPropertyChanges(update) {\n\treturn update.removeAllProperties || update.removeProperties?.length > 0 || update.addOrUpdateProperties?.length > 0;\n}\n/**\n* helper to apply property updates from a diff update object to a properties object\n*/\nfunction applyPropertyUpdates(tags, update) {\n\tif (update.removeAllProperties) return {};\n\tconst properties = { ...tags || {} };\n\tif (update.removeProperties) for (const key of update.removeProperties) delete properties[key];\n\tif (update.addOrUpdateProperties) for (const { key, value } of update.addOrUpdateProperties) properties[key] = value;\n\treturn properties;\n}\n/**\n* Convert a GeoJSON Source Diff to an idempotent hashed representation using Sets and Maps\n*/\nfunction diffToHashed(diff, options) {\n\tif (!diff) return {\n\t\tremove: /* @__PURE__ */ new Set(),\n\t\tadd: /* @__PURE__ */ new Map(),\n\t\tupdate: /* @__PURE__ */ new Map()\n\t};\n\treturn {\n\t\tremoveAll: diff.removeAll,\n\t\tremove: new Set(diff.remove || []),\n\t\tadd: new Map(diff.add?.map((feature) => [options.promoteId ? feature.properties?.[options.promoteId] : feature.id, feature])),\n\t\tupdate: new Map(diff.update?.map((update) => [update.id, update]))\n\t};\n}\n//#endregion\n//#region node_modules/kdbush/index.js\nconst ARRAY_TYPES = [\n\tInt8Array,\n\tUint8Array,\n\tUint8ClampedArray,\n\tInt16Array,\n\tUint16Array,\n\tInt32Array,\n\tUint32Array,\n\tFloat32Array,\n\tFloat64Array\n];\n/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */\n/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */\nconst VERSION = 1;\nconst HEADER_SIZE = 8;\nconst STACK = /* @__PURE__ */ new Uint32Array(96);\nvar KDBush = class KDBush {\n\t/**\n\t* Creates an index from raw `ArrayBuffer` data.\n\t* @param {ArrayBufferLike} data\n\t*/\n\tstatic from(data) {\n\t\tif (!data || data.byteLength === void 0 || data.buffer) throw new Error(\"Data must be an instance of ArrayBuffer or SharedArrayBuffer.\");\n\t\tconst [magic, versionAndType] = new Uint8Array(data, 0, 2);\n\t\tif (magic !== 219) throw new Error(\"Data does not appear to be in a KDBush format.\");\n\t\tconst version = versionAndType >> 4;\n\t\tif (version !== VERSION) throw new Error(`Got v${version} data when expected v${VERSION}.`);\n\t\tconst ArrayType = ARRAY_TYPES[versionAndType & 15];\n\t\tif (!ArrayType) throw new Error(\"Unrecognized array type.\");\n\t\tconst [nodeSize] = new Uint16Array(data, 2, 1);\n\t\tconst [numItems] = new Uint32Array(data, 4, 1);\n\t\treturn new KDBush(numItems, nodeSize, ArrayType, void 0, data);\n\t}\n\t/**\n\t* Creates an index that will hold a given number of items.\n\t* @param {number} numItems\n\t* @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).\n\t* @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).\n\t* @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).\n\t* @param {ArrayBufferLike} [data] (For internal use only)\n\t*/\n\tconstructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {\n\t\tif (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);\n\t\tthis.numItems = +numItems;\n\t\tthis.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);\n\t\tthis.ArrayType = ArrayType;\n\t\tthis.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;\n\t\tconst arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);\n\t\tconst coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;\n\t\tconst idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;\n\t\tconst padCoords = (8 - idsByteSize % 8) % 8;\n\t\tif (arrayTypeIndex < 0) throw new Error(`Unexpected typed array class: ${ArrayType}.`);\n\t\tif (data) {\n\t\t\tthis.data = data;\n\t\t\tthis.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n\t\t\tthis.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n\t\t\tthis._pos = numItems * 2;\n\t\t\tthis._finished = true;\n\t\t} else {\n\t\t\tconst data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);\n\t\t\tthis.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n\t\t\tthis.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n\t\t\tthis._pos = 0;\n\t\t\tthis._finished = false;\n\t\t\tnew Uint8Array(data, 0, 2).set([219, 16 + arrayTypeIndex]);\n\t\t\tnew Uint16Array(data, 2, 1)[0] = nodeSize;\n\t\t\tnew Uint32Array(data, 4, 1)[0] = numItems;\n\t\t}\n\t}\n\t/**\n\t* Add a point to the index.\n\t* @param {number} x\n\t* @param {number} y\n\t* @returns {number} An incremental index associated with the added item (starting from `0`).\n\t*/\n\tadd(x, y) {\n\t\tconst index = this._pos >> 1;\n\t\tthis.ids[index] = index;\n\t\tthis.coords[this._pos++] = x;\n\t\tthis.coords[this._pos++] = y;\n\t\treturn index;\n\t}\n\t/**\n\t* Perform indexing of the added points.\n\t*/\n\tfinish() {\n\t\tconst numAdded = this._pos >> 1;\n\t\tif (numAdded !== this.numItems) throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);\n\t\tsort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);\n\t\tthis._finished = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Search the index for items within a given bounding box.\n\t* @param {number} minX\n\t* @param {number} minY\n\t* @param {number} maxX\n\t* @param {number} maxY\n\t* @returns {number[]} An array of indices correponding to the found items.\n\t*/\n\trange(minX, minY, maxX, maxY) {\n\t\tif (!this._finished) throw new Error(\"Data not yet indexed - call index.finish().\");\n\t\tconst { ids, coords, nodeSize } = this;\n\t\tSTACK[0] = 0;\n\t\tSTACK[1] = ids.length - 1;\n\t\tSTACK[2] = 0;\n\t\tlet sp = 3;\n\t\tconst result = [];\n\t\twhile (sp > 0) {\n\t\t\tconst axis = STACK[--sp];\n\t\t\tconst right = STACK[--sp];\n\t\t\tconst left = STACK[--sp];\n\t\t\tif (right - left <= nodeSize) {\n\t\t\t\tfor (let i = left; i <= right; i++) {\n\t\t\t\t\tconst x = coords[2 * i];\n\t\t\t\t\tconst y = coords[2 * i + 1];\n\t\t\t\t\tif (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst m = left + right >> 1;\n\t\t\tconst x = coords[2 * m];\n\t\t\tconst y = coords[2 * m + 1];\n\t\t\tif (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\t\t\tif (axis === 0 ? minX <= x : minY <= y) {\n\t\t\t\tSTACK[sp++] = left;\n\t\t\t\tSTACK[sp++] = m - 1;\n\t\t\t\tSTACK[sp++] = 1 - axis;\n\t\t\t}\n\t\t\tif (axis === 0 ? maxX >= x : maxY >= y) {\n\t\t\t\tSTACK[sp++] = m + 1;\n\t\t\t\tSTACK[sp++] = right;\n\t\t\t\tSTACK[sp++] = 1 - axis;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t* Search the index for items within a given radius.\n\t* @param {number} qx\n\t* @param {number} qy\n\t* @param {number} r Query radius.\n\t* @returns {number[]} An array of indices correponding to the found items.\n\t*/\n\twithin(qx, qy, r) {\n\t\tconst result = [];\n\t\tthis.withinInto(qx, qy, r, result);\n\t\treturn result;\n\t}\n\t/**\n\t* Search the index for items within a given radius, writing matching ids into `out`\n\t* via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —\n\t* a typed array sized to the expected upper bound (allocation-free, fast) or a plain\n\t* `Array` (which will grow as needed). Returns the number of matches written.\n\t* @param {number} qx\n\t* @param {number} qy\n\t* @param {number} r Query radius.\n\t* @param {number[] | TypedArray} out Container to write matching ids into.\n\t* @returns {number} The number of matches written to `out`.\n\t*/\n\twithinInto(qx, qy, r, out) {\n\t\tif (!this._finished) throw new Error(\"Data not yet indexed - call index.finish().\");\n\t\tconst { ids, coords, nodeSize } = this;\n\t\tSTACK[0] = 0;\n\t\tSTACK[1] = ids.length - 1;\n\t\tSTACK[2] = 0;\n\t\tlet sp = 3;\n\t\tlet count = 0;\n\t\tconst r2 = r * r;\n\t\twhile (sp > 0) {\n\t\t\tconst axis = STACK[--sp];\n\t\t\tconst right = STACK[--sp];\n\t\t\tconst left = STACK[--sp];\n\t\t\tif (right - left <= nodeSize) {\n\t\t\t\tfor (let i = left; i <= right; i++) if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst m = left + right >> 1;\n\t\t\tconst x = coords[2 * m];\n\t\t\tconst y = coords[2 * m + 1];\n\t\t\tif (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];\n\t\t\tif (axis === 0 ? qx - r <= x : qy - r <= y) {\n\t\t\t\tSTACK[sp++] = left;\n\t\t\t\tSTACK[sp++] = m - 1;\n\t\t\t\tSTACK[sp++] = 1 - axis;\n\t\t\t}\n\t\t\tif (axis === 0 ? qx + r >= x : qy + r >= y) {\n\t\t\t\tSTACK[sp++] = m + 1;\n\t\t\t\tSTACK[sp++] = right;\n\t\t\t\tSTACK[sp++] = 1 - axis;\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}\n};\n/**\n* @param {Uint16Array | Uint32Array} ids\n* @param {TypedArray} coords\n* @param {number} nodeSize\n* @param {number} left\n* @param {number} right\n* @param {number} axis\n*/\nfunction sort(ids, coords, nodeSize, left, right, axis) {\n\tif (right - left <= nodeSize) return;\n\tconst m = left + right >> 1;\n\tselect(ids, coords, m, left, right, axis);\n\tsort(ids, coords, nodeSize, left, m - 1, 1 - axis);\n\tsort(ids, coords, nodeSize, m + 1, right, 1 - axis);\n}\n/**\n* Custom Floyd-Rivest selection algorithm: sort ids and coords so that\n* [left..k-1] items are smaller than k-th item (on either x or y axis)\n* @param {Uint16Array | Uint32Array} ids\n* @param {TypedArray} coords\n* @param {number} k\n* @param {number} left\n* @param {number} right\n* @param {number} axis\n*/\nfunction select(ids, coords, k, left, right, axis) {\n\twhile (right > left) {\n\t\tif (right - left > 600) {\n\t\t\tconst n = right - left + 1;\n\t\t\tconst m = k - left + 1;\n\t\t\tconst z = Math.log(n);\n\t\t\tconst s = .5 * Math.exp(2 * z / 3);\n\t\t\tconst sd = .5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n\t\t\tselect(ids, coords, k, Math.max(left, Math.floor(k - m * s / n + sd)), Math.min(right, Math.floor(k + (n - m) * s / n + sd)), axis);\n\t\t}\n\t\tconst t = coords[2 * k + axis];\n\t\tlet i = left;\n\t\tlet j = right;\n\t\tswapItem(ids, coords, left, k);\n\t\tif (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);\n\t\twhile (i < j) {\n\t\t\tswapItem(ids, coords, i, j);\n\t\t\ti++;\n\t\t\tj--;\n\t\t\twhile (coords[2 * i + axis] < t) i++;\n\t\t\twhile (coords[2 * j + axis] > t) j--;\n\t\t}\n\t\tif (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);\n\t\telse {\n\t\t\tj++;\n\t\t\tswapItem(ids, coords, j, right);\n\t\t}\n\t\tif (j <= k) left = j + 1;\n\t\tif (k <= j) right = j - 1;\n\t}\n}\n/**\n* @param {Uint16Array | Uint32Array} ids\n* @param {TypedArray} coords\n* @param {number} i\n* @param {number} j\n*/\nfunction swapItem(ids, coords, i, j) {\n\tswap(ids, i, j);\n\tswap(coords, 2 * i, 2 * j);\n\tswap(coords, 2 * i + 1, 2 * j + 1);\n}\n/**\n* @param {TypedArray} arr\n* @param {number} i\n* @param {number} j\n*/\nfunction swap(arr, i, j) {\n\tconst tmp = arr[i];\n\tarr[i] = arr[j];\n\tarr[j] = tmp;\n}\n/**\n* @param {number} ax\n* @param {number} ay\n* @param {number} bx\n* @param {number} by\n*/\nfunction sqDist(ax, ay, bx, by) {\n\tconst dx = ax - bx;\n\tconst dy = ay - by;\n\treturn dx * dx + dy * dy;\n}\n//#endregion\n//#region src/cluster-tile-index.ts\nconst defaultClusterOptions = {\n\tminZoom: 0,\n\tmaxZoom: 16,\n\tminPoints: 2,\n\tradius: 40,\n\textent: 512,\n\tnodeSize: 64,\n\tlog: false,\n\tgenerateId: false,\n\treduce: null,\n\tmap: (props) => props,\n\tcoordinates: \"lngLat\",\n\twrap: true\n};\n/**\n* The highest zoom level to cluster on. A cluster id keeps its zoom level in five bits.\n*/\nconst MAX_ZOOM = 30;\n/**\n* Projected coordinates, which are 0 to 1 inside the world, are stored as integers with this many steps per world,\n* so that they take half the memory of doubles. One step is ~4 cm at the equator.\n*/\nconst SCALE = 1073741824;\n/**\n* The largest value a 32-bit integer holds.\n*/\nconst MAX_INTEGER = 2147483647;\n/**\n* A projected coordinate in steps from the center of the world, see `SCALE`.\n*/\nfunction encode(coord) {\n\treturn (coord - .5) * SCALE;\n}\nfunction decode(value) {\n\treturn value / SCALE + .5;\n}\n/**\n* Whether a projected coordinate fits in a 32-bit integer. One that is more than two worlds from the center of the\n* world does not, and neither does one that is not a number.\n*/\nfunction fitsInteger(coord) {\n\treturn Math.abs(encode(coord)) < MAX_INTEGER;\n}\nconst OFFSET_ZOOM = 0;\nconst OFFSET_ID = 1;\nconst OFFSET_PARENT = 2;\nconst OFFSET_NUM = 3;\nconst OFFSET_PROP = 4;\n/**\n* This class allow clustering of geojson points.\n*/\nvar ClusterTileIndex = class {\n\tconstructor(options) {\n\t\tthis.options = createOptions(options);\n\t\tthis.worldCoordinateHelper = getWorldCoordinateHelper(this.options.coordinates);\n\t\tthis.trees = new Array(this.options.maxZoom + 1);\n\t\tthis.stride = this.options.reduce ? 5 : 4;\n\t\tthis.clusterProps = [];\n\t\tthis.points = [];\n\t}\n\t/**\n\t* Loads GeoJSON Point and MultiPoint features and builds the internal clustering index.\n\t* Each position of a MultiPoint is clustered as a point of its own, with the id and properties of its feature.\n\t* @param points - GeoJSON Point and MultiPoint features to cluster.\n\t*/\n\tload(points) {\n\t\tconst features = [];\n\t\tfor (const point of points) {\n\t\t\tif (!point.geometry) continue;\n\t\t\tconst positions = point.geometry.type === \"MultiPoint\" ? point.geometry.coordinates : [point.geometry.coordinates];\n\t\t\tfor (const [lng, lat] of positions) {\n\t\t\t\tconst [x, y] = [this.worldCoordinateHelper.projectX(lng), this.worldCoordinateHelper.projectY(lat)];\n\t\t\t\tif (!this.options.wrap && !isInWorld([x, y])) continue;\n\t\t\t\tconst feature = {\n\t\t\t\t\tid: point.id,\n\t\t\t\t\ttype: \"Point\",\n\t\t\t\t\tgeometry: [x, y],\n\t\t\t\t\ttags: point.properties\n\t\t\t\t};\n\t\t\t\tfeatures.push(feature);\n\t\t\t}\n\t\t}\n\t\tthis.createIndex(features);\n\t}\n\t/**\n\t* @internal\n\t* Loads internal GeoJSONVT point features from a data source and builds the clustering index.\n\t* Each position of a MultiPoint feature becomes a point of its own, with the id and properties of its feature.\n\t* @param features - {@link GeoJSONVTInternalFeature} data source features to filter and cluster.\n\t*/\n\tinitialize(features) {\n\t\tconst points = [];\n\t\tfor (const feature of features) {\n\t\t\tif (feature.type === \"Point\") {\n\t\t\t\tif (!this.options.wrap && !isInWorld(feature.geometry)) continue;\n\t\t\t\tpoints.push(feature);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (feature.type !== \"MultiPoint\") continue;\n\t\t\tfor (let i = 0; i < feature.geometry.length; i += 3) {\n\t\t\t\tconst geometry = [feature.geometry[i], feature.geometry[i + 1]];\n\t\t\t\tif (!this.options.wrap && !isInWorld(geometry)) continue;\n\t\t\t\tpoints.push({\n\t\t\t\t\tid: feature.id,\n\t\t\t\t\ttype: \"Point\",\n\t\t\t\t\tgeometry,\n\t\t\t\t\ttags: feature.tags\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.createIndex(points);\n\t}\n\t/**\n\t* @internal\n\t* Updates the cluster data by rebuilding.\n\t* @param features \n\t*/\n\tupdateIndex(features, _affected, options) {\n\t\tthis.options = createOptions({\n\t\t\t...options.clusterOptions,\n\t\t\tcoordinates: this.options.coordinates,\n\t\t\twrap: this.options.wrap\n\t\t});\n\t\tthis.initialize(features);\n\t}\n\t/**\n\t* Builds a tree per zoom level from the points. A point whose position does not fit in an integer is left out,\n\t* see `fitsInteger`.\n\t*/\n\tcreateIndex(points) {\n\t\tconst { log, minZoom, maxZoom } = this.options;\n\t\tthis.trees = new Array(maxZoom + 1);\n\t\tthis.stride = this.options.reduce ? 5 : 4;\n\t\tthis.clusterProps = [];\n\t\tif (log) console.time(\"total time\");\n\t\tconst timerId = `prepare ${points.length} points`;\n\t\tif (log) console.time(timerId);\n\t\tthis.points = points;\n\t\tconst stride = this.stride;\n\t\tconst notProcessed = maxZoom + 1;\n\t\tconst coords = new Int32Array(points.length * 2);\n\t\tconst data = new Int32Array(points.length * stride);\n\t\tlet numItems = 0;\n\t\tfor (let i = 0; i < points.length; i++) {\n\t\t\tconst p = points[i];\n\t\t\tif (!p?.geometry || !fitsInteger(p.geometry[0]) || !fitsInteger(p.geometry[1])) continue;\n\t\t\tcoords[numItems * 2] = Math.round(encode(p.geometry[0]));\n\t\t\tcoords[numItems * 2 + 1] = Math.round(encode(p.geometry[1]));\n\t\t\tconst k = numItems * stride;\n\t\t\tdata[k + OFFSET_ZOOM] = notProcessed;\n\t\t\tdata[k + OFFSET_ID] = i;\n\t\t\tdata[k + OFFSET_PARENT] = -1;\n\t\t\tdata[k + OFFSET_NUM] = 1;\n\t\t\tnumItems++;\n\t\t}\n\t\tlet tree = this.trees[maxZoom + 1] = this.createTree(coords, data, numItems);\n\t\tif (log) console.timeEnd(timerId);\n\t\tconst nextCoords = new Int32Array(numItems * 2);\n\t\tconst nextData = new Int32Array(numItems * stride);\n\t\tfor (let z = maxZoom; z >= minZoom; z--) {\n\t\t\tconst now = Date.now();\n\t\t\tconst nextNumItems = this.cluster(tree, z, nextCoords, nextData);\n\t\t\tif (!this.isSameAsTree(tree, nextData, nextNumItems)) tree = this.createTree(nextCoords.slice(0, nextNumItems * 2), nextData.slice(0, nextNumItems * stride), nextNumItems);\n\t\t\tthis.trees[z] = tree;\n\t\t\tif (log) console.log(\"z%d: %d clusters in %dms\", z, tree.numItems, Date.now() - now);\n\t\t}\n\t\tif (log) console.timeEnd(\"total time\");\n\t}\n\t/**\n\t* Returns clusters and/or points within a bounding box at a given zoom level.\n\t* @param bbox - Bounding box in `[westLng, southLat, eastLng, northLat]` order, or `[minX, minY, maxX, maxY]` in the unit square with `coordinates: 'unitSquare'`.\n\t* In a world that wraps, the box can reach across the antimeridian. In one that doesn't, only its part inside the world counts.\n\t* @param zoom - Zoom level to query.\n\t*/\n\tgetClusters(bbox, zoom) {\n\t\treturn (!this.options.wrap ? this.getClustersInWorld(bbox, zoom) : this.options.coordinates === \"unitSquare\" ? this.getClustersAcrossEdge(bbox, zoom) : this.getClustersInternal(bbox, zoom)).map((f) => featureToGeoJSON(f, this.worldCoordinateHelper));\n\t}\n\t/**\n\t* The clusters and points in the part of a box inside a world that ends at its edges.\n\t*/\n\tgetClustersInWorld(bbox, zoom) {\n\t\tconst lngLat = this.options.coordinates !== \"unitSquare\";\n\t\tconst y1 = this.worldCoordinateHelper.projectY(lngLat ? Math.max(-90, Math.min(90, bbox[1])) : bbox[1]);\n\t\tconst y2 = this.worldCoordinateHelper.projectY(lngLat ? Math.max(-90, Math.min(90, bbox[3])) : bbox[3]);\n\t\tconst minX = Math.max(0, this.worldCoordinateHelper.projectX(bbox[0]));\n\t\tconst maxX = Math.min(1, this.worldCoordinateHelper.projectX(bbox[2]));\n\t\tif (minX > maxX) return [];\n\t\treturn this.getClustersInRange([\n\t\t\tminX,\n\t\t\tMath.min(y1, y2),\n\t\t\tmaxX,\n\t\t\tMath.max(y1, y2)\n\t\t], zoom);\n\t}\n\t/**\n\t* The clusters and points in a box of a unit square that wraps, where the box can reach across its left or right edge.\n\t*/\n\tgetClustersAcrossEdge([minX, minY, maxX, maxY], zoom) {\n\t\tif (maxX < minX) maxX += 1;\n\t\tif (maxX - minX >= 1) return this.getClustersInRange([\n\t\t\t0,\n\t\t\tminY,\n\t\t\t1,\n\t\t\tmaxY\n\t\t], zoom);\n\t\tconst shift = Math.floor(minX);\n\t\tconst west = minX - shift;\n\t\tconst east = maxX - shift;\n\t\tif (east <= 1) return this.getClustersInRange([\n\t\t\twest,\n\t\t\tminY,\n\t\t\teast,\n\t\t\tmaxY\n\t\t], zoom);\n\t\treturn this.getClustersInRange([\n\t\t\twest,\n\t\t\tminY,\n\t\t\t1,\n\t\t\tmaxY\n\t\t], zoom).concat(this.getClustersInRange([\n\t\t\t0,\n\t\t\tminY,\n\t\t\teast - 1,\n\t\t\tmaxY\n\t\t], zoom));\n\t}\n\tgetClustersInternal(bbox, zoom) {\n\t\tlet minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;\n\t\tconst minLat = Math.max(-90, Math.min(90, bbox[1]));\n\t\tlet maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;\n\t\tconst maxLat = Math.max(-90, Math.min(90, bbox[3]));\n\t\tif (bbox[2] - bbox[0] >= 360) {\n\t\t\tminLng = -180;\n\t\t\tmaxLng = 180;\n\t\t} else if (minLng > maxLng) {\n\t\t\tconst easternHem = this.getClustersInternal([\n\t\t\t\tminLng,\n\t\t\t\tminLat,\n\t\t\t\t180,\n\t\t\t\tmaxLat\n\t\t\t], zoom);\n\t\t\tconst westernHem = this.getClustersInternal([\n\t\t\t\t-180,\n\t\t\t\tminLat,\n\t\t\t\tmaxLng,\n\t\t\t\tmaxLat\n\t\t\t], zoom);\n\t\t\treturn easternHem.concat(westernHem);\n\t\t}\n\t\treturn this.getClustersInRange([\n\t\t\tthis.worldCoordinateHelper.projectX(minLng),\n\t\t\tthis.worldCoordinateHelper.projectY(maxLat),\n\t\t\tthis.worldCoordinateHelper.projectX(maxLng),\n\t\t\tthis.worldCoordinateHelper.projectY(minLat)\n\t\t], zoom);\n\t}\n\t/**\n\t* The clusters and points in a box of the internal coordinates, `[minX, minY, maxX, maxY]`.\n\t*/\n\tgetClustersInRange([minX, minY, maxX, maxY], zoom) {\n\t\tconst tree = this.trees[this.limitZoom(zoom)];\n\t\tconst ids = tree.range(encode(minX), encode(minY), encode(maxX), encode(maxY));\n\t\tconst coords = tree.flatCoords;\n\t\tconst data = tree.flatData;\n\t\tconst clusters = [];\n\t\tfor (const id of ids) {\n\t\t\tconst k = this.stride * id;\n\t\t\tclusters.push(data[k + OFFSET_NUM] > 1 ? getClusterFeature(coords, id, data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);\n\t\t}\n\t\treturn clusters;\n\t}\n\t/**\n\t* Returns the immediate children (clusters or points) of a cluster as GeoJSON.\n\t* @param clusterId - The target cluster id.\n\t*/\n\tgetChildren(clusterId) {\n\t\tconst originId = this.getOriginId(clusterId);\n\t\tconst originZoom = this.getOriginZoom(clusterId);\n\t\tconst clusterError = /* @__PURE__ */ new Error(\"No cluster with the specified id: \" + clusterId);\n\t\tconst tree = this.trees[originZoom];\n\t\tif (!tree) throw clusterError;\n\t\tconst coords = tree.flatCoords;\n\t\tconst data = tree.flatData;\n\t\tif (originId >= tree.numItems) throw clusterError;\n\t\tconst r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)) * SCALE;\n\t\tconst x = coords[originId * 2];\n\t\tconst y = coords[originId * 2 + 1];\n\t\tconst ids = tree.within(x, y, r);\n\t\tconst children = [];\n\t\tfor (const id of ids) {\n\t\t\tconst k = id * this.stride;\n\t\t\tif (data[k + OFFSET_PARENT] === clusterId) children.push(data[k + OFFSET_NUM] > 1 ? getClusterGeoJSON(coords, id, data, k, this.clusterProps, this.worldCoordinateHelper) : featureToGeoJSON(this.points[data[k + OFFSET_ID]], this.worldCoordinateHelper));\n\t\t}\n\t\tif (children.length === 0) throw clusterError;\n\t\treturn children;\n\t}\n\t/**\n\t* Returns leaf point features under a cluster, paginated by `limit` and `offset`.\n\t* @param clusterId - The target cluster id.\n\t* @param limit - Maximum number of points to return (defaults to `10`).\n\t* @param offset - Number of points to skip before collecting results (defaults to `0`).\n\t*/\n\tgetLeaves(clusterId, limit, offset) {\n\t\tlimit = limit || 10;\n\t\toffset = offset || 0;\n\t\tconst leaves = [];\n\t\tthis.appendLeaves(leaves, clusterId, limit, offset, 0);\n\t\treturn leaves;\n\t}\n\t/**\n\t* Generates a vector-tile-like representation of a single tile.\n\t* @param z - Tile zoom.\n\t* @param x - Tile x coordinate.\n\t* @param y - Tile y coordinate.\n\t*/\n\tgetTile(z, x, y) {\n\t\tconst tree = this.trees[this.limitZoom(z)];\n\t\tif (!tree) return null;\n\t\tconst z2 = Math.pow(2, z);\n\t\tif (!this.options.wrap && (x < 0 || x >= z2 || y < 0 || y >= z2)) return null;\n\t\tconst { extent, radius } = this.options;\n\t\tconst p = radius / extent;\n\t\tconst top = encode((y - p) / z2);\n\t\tconst bottom = encode((y + 1 + p) / z2);\n\t\tconst tile = {\n\t\t\ttransformed: true,\n\t\t\tfeatures: [],\n\t\t\tsource: null,\n\t\t\tx,\n\t\t\ty,\n\t\t\tz\n\t\t};\n\t\tthis.addTileFeatures(tree.range(encode((x - p) / z2), top, encode((x + 1 + p) / z2), bottom), tree, x, y, z2, tile);\n\t\tif (this.options.wrap && x === 0) this.addTileFeatures(tree.range(encode(1 - p / z2), top, encode(1), bottom), tree, z2, y, z2, tile);\n\t\tif (this.options.wrap && x === z2 - 1) this.addTileFeatures(tree.range(encode(0), top, encode(p / z2), bottom), tree, -1, y, z2, tile);\n\t\treturn tile;\n\t}\n\t/**\n\t* Returns the zoom level at which a cluster expands into multiple children.\n\t* @param clusterId - The target cluster id.\n\t*/\n\tgetClusterExpansionZoom(clusterId) {\n\t\treturn this.getOriginZoom(clusterId);\n\t}\n\tappendLeaves(result, clusterId, limit, offset, skipped) {\n\t\tconst children = this.getChildren(clusterId);\n\t\tfor (const child of children) {\n\t\t\tconst props = child.properties;\n\t\t\tif (props?.cluster) {\n\t\t\t\tif (skipped + props.point_count <= offset) skipped += props.point_count;\n\t\t\t\telse skipped = this.appendLeaves(result, props.cluster_id, limit, offset, skipped);\n\t\t\t} else if (skipped < offset) skipped++;\n\t\t\telse result.push(child);\n\t\t\tif (result.length === limit) break;\n\t\t}\n\t\treturn skipped;\n\t}\n\tcreateTree(coords, data, numItems) {\n\t\tconst tree = new KDBush(numItems, this.options.nodeSize, Int32Array);\n\t\tfor (let i = 0; i < numItems; i++) tree.add(coords[i * 2], coords[i * 2 + 1]);\n\t\ttree.finish();\n\t\ttree.flatCoords = coords;\n\t\ttree.flatData = data;\n\t\ttree.data = null;\n\t\treturn tree;\n\t}\n\t/**\n\t* Whether clustering a tree left all its points and clusters as they were, in the same order.\n\t*/\n\tisSameAsTree(tree, nextData, nextNumItems) {\n\t\tif (nextNumItems !== tree.numItems) return false;\n\t\tconst data = tree.flatData;\n\t\tfor (let k = OFFSET_ID; k < nextNumItems * this.stride; k += this.stride) if (nextData[k] !== data[k]) return false;\n\t\treturn true;\n\t}\n\taddTileFeatures(ids, tree, x, y, z2, tile) {\n\t\tconst coords = tree.flatCoords;\n\t\tconst data = tree.flatData;\n\t\tfor (const i of ids) {\n\t\t\tconst k = i * this.stride;\n\t\t\tconst isCluster = data[k + OFFSET_NUM] > 1;\n\t\t\tlet tags;\n\t\t\tlet px;\n\t\t\tlet py;\n\t\t\tif (isCluster) {\n\t\t\t\ttags = getClusterProperties(data, k, this.clusterProps);\n\t\t\t\tpx = decode(coords[i * 2]);\n\t\t\t\tpy = decode(coords[i * 2 + 1]);\n\t\t\t} else {\n\t\t\t\tconst p = this.points[data[k + OFFSET_ID]];\n\t\t\t\ttags = p.tags;\n\t\t\t\t[px, py] = p.geometry;\n\t\t\t}\n\t\t\tconst f = {\n\t\t\t\ttype: 1,\n\t\t\t\tgeometry: [[Math.round(this.options.extent * (px * z2 - x)), Math.round(this.options.extent * (py * z2 - y))]],\n\t\t\t\ttags\n\t\t\t};\n\t\t\tlet id;\n\t\t\tif (isCluster || this.options.generateId) id = data[k + OFFSET_ID];\n\t\t\telse id = this.points[data[k + OFFSET_ID]].id;\n\t\t\tif (id !== void 0) f.id = id;\n\t\t\ttile.features.push(f);\n\t\t}\n\t}\n\tlimitZoom(z) {\n\t\treturn Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));\n\t}\n\t/**\n\t* Clusters the points of a tree on a zoom level, writing the result to `nextCoords` and `nextData`.\n\t* @returns the number of points and clusters written\n\t*/\n\tcluster(tree, zoom, nextCoords, nextData) {\n\t\tconst { radius, extent, reduce, minPoints, maxZoom } = this.options;\n\t\tconst r = radius / (extent * Math.pow(2, zoom)) * SCALE;\n\t\tconst notProcessed = maxZoom + 1;\n\t\tconst coords = tree.flatCoords;\n\t\tconst data = tree.flatData;\n\t\tconst stride = this.stride;\n\t\tconst neighborIds = new Uint32Array(tree.numItems);\n\t\tlet nextNumItems = 0;\n\t\tfor (let index = 0; index < tree.numItems; index++) {\n\t\t\tconst i = index * stride;\n\t\t\tif (data[i + OFFSET_ZOOM] <= zoom) continue;\n\t\t\tdata[i + OFFSET_ZOOM] = zoom;\n\t\t\tconst x = coords[index * 2];\n\t\t\tconst y = coords[index * 2 + 1];\n\t\t\tconst numNeighbors = tree.withinInto(x, y, r, neighborIds);\n\t\t\tconst numPointsOrigin = data[i + OFFSET_NUM];\n\t\t\tlet numPoints = numPointsOrigin;\n\t\t\tfor (let n = 0; n < numNeighbors; n++) {\n\t\t\t\tconst k = neighborIds[n] * stride;\n\t\t\t\tif (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM];\n\t\t\t}\n\t\t\tif (numPoints > numPointsOrigin && numPoints >= minPoints) {\n\t\t\t\tlet wx = x * numPointsOrigin;\n\t\t\t\tlet wy = y * numPointsOrigin;\n\t\t\t\tlet clusterProperties;\n\t\t\t\tlet clusterPropIndex = -1;\n\t\t\t\tconst id = (index << 5) + (zoom + 1) + this.points.length;\n\t\t\t\tfor (let n = 0; n < numNeighbors; n++) {\n\t\t\t\t\tconst neighborIndex = neighborIds[n];\n\t\t\t\t\tconst k = neighborIndex * stride;\n\t\t\t\t\tif (data[k + OFFSET_ZOOM] <= zoom) continue;\n\t\t\t\t\tdata[k + OFFSET_ZOOM] = zoom;\n\t\t\t\t\tconst numPoints2 = data[k + OFFSET_NUM];\n\t\t\t\t\twx += coords[neighborIndex * 2] * numPoints2;\n\t\t\t\t\twy += coords[neighborIndex * 2 + 1] * numPoints2;\n\t\t\t\t\tdata[k + OFFSET_PARENT] = id;\n\t\t\t\t\tif (reduce) {\n\t\t\t\t\t\tif (!clusterProperties) {\n\t\t\t\t\t\t\tclusterProperties = this.map(data, i, true);\n\t\t\t\t\t\t\tclusterPropIndex = this.clusterProps.length;\n\t\t\t\t\t\t\tthis.clusterProps.push(clusterProperties);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treduce(clusterProperties, this.map(data, k));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdata[i + OFFSET_PARENT] = id;\n\t\t\t\tnextCoords[nextNumItems * 2] = Math.round(wx / numPoints);\n\t\t\t\tnextCoords[nextNumItems * 2 + 1] = Math.round(wy / numPoints);\n\t\t\t\tconst next = nextNumItems * stride;\n\t\t\t\tnextData[next + OFFSET_ZOOM] = notProcessed;\n\t\t\t\tnextData[next + OFFSET_ID] = id;\n\t\t\t\tnextData[next + OFFSET_PARENT] = -1;\n\t\t\t\tnextData[next + OFFSET_NUM] = numPoints;\n\t\t\t\tif (reduce) nextData[next + OFFSET_PROP] = clusterPropIndex;\n\t\t\t\tnextNumItems++;\n\t\t\t} else {\n\t\t\t\tnextCoords[nextNumItems * 2] = x;\n\t\t\t\tnextCoords[nextNumItems * 2 + 1] = y;\n\t\t\t\tfor (let j = 0; j < stride; j++) nextData[nextNumItems * stride + j] = data[i + j];\n\t\t\t\tnextNumItems++;\n\t\t\t\tif (numPoints > 1) for (let n = 0; n < numNeighbors; n++) {\n\t\t\t\t\tconst neighborIndex = neighborIds[n];\n\t\t\t\t\tconst k = neighborIndex * stride;\n\t\t\t\t\tif (data[k + OFFSET_ZOOM] <= zoom) continue;\n\t\t\t\t\tdata[k + OFFSET_ZOOM] = zoom;\n\t\t\t\t\tnextCoords[nextNumItems * 2] = coords[neighborIndex * 2];\n\t\t\t\t\tnextCoords[nextNumItems * 2 + 1] = coords[neighborIndex * 2 + 1];\n\t\t\t\t\tfor (let j = 0; j < stride; j++) nextData[nextNumItems * stride + j] = data[k + j];\n\t\t\t\t\tnextNumItems++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nextNumItems;\n\t}\n\tgetOriginId(clusterId) {\n\t\treturn clusterId - this.points.length >> 5;\n\t}\n\tgetOriginZoom(clusterId) {\n\t\treturn (clusterId - this.points.length) % 32;\n\t}\n\tmap(data, i, clone) {\n\t\tif (data[i + OFFSET_NUM] > 1) {\n\t\t\tconst props = this.clusterProps[data[i + OFFSET_PROP]];\n\t\t\treturn clone ? Object.assign({}, props) : props;\n\t\t}\n\t\tconst original = this.points[data[i + OFFSET_ID]].tags;\n\t\tconst result = this.options.map(original);\n\t\treturn clone && result === original ? Object.assign({}, result) : result;\n\t}\n};\nfunction createOptions(options) {\n\tconst result = Object.assign(Object.create(defaultClusterOptions), options);\n\tresult.minZoom = Math.min(result.minZoom, MAX_ZOOM);\n\tresult.maxZoom = Math.min(result.maxZoom, MAX_ZOOM);\n\treturn result;\n}\nfunction getClusterFeature(coords, index, data, i, clusterProps) {\n\treturn {\n\t\tid: data[i + OFFSET_ID],\n\t\ttype: \"Point\",\n\t\ttags: getClusterProperties(data, i, clusterProps),\n\t\tgeometry: [decode(coords[index * 2]), decode(coords[index * 2 + 1])]\n\t};\n}\nfunction getClusterGeoJSON(coords, index, data, i, clusterProps, worldCoordinateHelper) {\n\treturn {\n\t\ttype: \"Feature\",\n\t\tid: data[i + OFFSET_ID],\n\t\tproperties: getClusterProperties(data, i, clusterProps),\n\t\tgeometry: {\n\t\t\ttype: \"Point\",\n\t\t\tcoordinates: [worldCoordinateHelper.unprojectX(decode(coords[index * 2])), worldCoordinateHelper.unprojectY(decode(coords[index * 2 + 1]))]\n\t\t}\n\t};\n}\nfunction getClusterProperties(data, i, clusterProps) {\n\tconst count = data[i + OFFSET_NUM];\n\tconst abbrev = count >= 1e4 ? `${Math.round(count / 1e3)}k` : count >= 1e3 ? `${Math.round(count / 100) / 10}k` : count;\n\tconst propIndex = data[i + OFFSET_PROP];\n\tconst properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);\n\treturn Object.assign(properties, {\n\t\tcluster: true,\n\t\tcluster_id: data[i + OFFSET_ID],\n\t\tpoint_count: count,\n\t\tpoint_count_abbreviated: abbrev\n\t});\n}\nfunction isInWorld(geometry) {\n\treturn geometry[0] >= 0 && geometry[0] <= 1 && geometry[1] >= 0 && geometry[1] <= 1;\n}\n//#endregion\n//#region src/tile.ts\nconst GEOJSONVT_CLIP_START = \"geojsonvt_clip_start\";\nconst GEOJSONVT_CLIP_END = \"geojsonvt_clip_end\";\n/**\n* Creates a tile object from the given features\n* @param features - the features to include in the tile\n* @param z\n* @param tx\n* @param ty\n* @param options - the options object\n* @returns the created tile\n*/\nfunction createTile(features, z, tx, ty, options) {\n\tconst tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);\n\tconst tile = {\n\t\ttransformed: false,\n\t\tfeatures: [],\n\t\tsource: null,\n\t\tx: tx,\n\t\ty: ty,\n\t\tz,\n\t\tminX: 2,\n\t\tminY: 1,\n\t\tmaxX: -1,\n\t\tmaxY: 0,\n\t\tnumPoints: 0,\n\t\tnumSimplified: 0,\n\t\tnumFeatures: features.length\n\t};\n\tfor (const feature of features) addFeature(tile, feature, tolerance, options);\n\treturn tile;\n}\nfunction addFeature(tile, feature, tolerance, options) {\n\ttile.minX = Math.min(tile.minX, feature.minX);\n\ttile.minY = Math.min(tile.minY, feature.minY);\n\ttile.maxX = Math.max(tile.maxX, feature.maxX);\n\ttile.maxY = Math.max(tile.maxY, feature.maxY);\n\tswitch (feature.type) {\n\t\tcase \"Point\":\n\t\tcase \"MultiPoint\":\n\t\t\taddPointsTileFeature(tile, feature);\n\t\t\treturn;\n\t\tcase \"LineString\":\n\t\t\taddLineTileFeautre(tile, feature, tolerance, options);\n\t\t\treturn;\n\t\tcase \"MultiLineString\":\n\t\tcase \"Polygon\":\n\t\t\taddLinesTileFeature(tile, feature, tolerance);\n\t\t\treturn;\n\t\tcase \"MultiPolygon\":\n\t\t\taddMultiPolygonTileFeature(tile, feature, tolerance);\n\t\t\treturn;\n\t}\n}\nfunction addPointsTileFeature(tile, feature) {\n\tconst geometry = [];\n\tfor (let i = 0; i < feature.geometry.length; i += 3) {\n\t\tgeometry.push(feature.geometry[i], feature.geometry[i + 1]);\n\t\ttile.numPoints++;\n\t\ttile.numSimplified++;\n\t}\n\tif (!geometry.length) return;\n\tconst tileFeature = {\n\t\ttype: 1,\n\t\ttags: feature.tags || null,\n\t\tgeometry\n\t};\n\tif (feature.id !== null) tileFeature.id = feature.id;\n\ttile.features.push(tileFeature);\n}\nfunction addLineTileFeautre(tile, feature, tolerance, options) {\n\tconst geometry = [];\n\taddLine(geometry, feature.geometry, tile, tolerance, false, false);\n\tif (!geometry.length) return;\n\tlet tags = feature.tags || null;\n\tif (options.lineMetrics) {\n\t\ttags = {};\n\t\tfor (const key in feature.tags) tags[key] = feature.tags[key];\n\t\ttags[GEOJSONVT_CLIP_START] = feature.geometry.start / feature.geometry.size;\n\t\ttags[GEOJSONVT_CLIP_END] = feature.geometry.end / feature.geometry.size;\n\t}\n\tconst tileFeature = {\n\t\ttype: 2,\n\t\ttags,\n\t\tgeometry\n\t};\n\tif (feature.id !== null) tileFeature.id = feature.id;\n\ttile.features.push(tileFeature);\n}\nfunction addLinesTileFeature(tile, feature, tolerance) {\n\tconst geometry = [];\n\tfor (let i = 0; i < feature.geometry.length; i++) addLine(geometry, feature.geometry[i], tile, tolerance, feature.type === \"Polygon\", i === 0);\n\tif (!geometry.length) return;\n\tconst tileFeature = {\n\t\ttype: feature.type === \"Polygon\" ? 3 : 2,\n\t\ttags: feature.tags || null,\n\t\tgeometry\n\t};\n\tif (feature.id !== null) tileFeature.id = feature.id;\n\ttile.features.push(tileFeature);\n}\nfunction addMultiPolygonTileFeature(tile, feature, tolerance) {\n\tconst geometry = [];\n\tfor (let k = 0; k < feature.geometry.length; k++) {\n\t\tconst polygon = feature.geometry[k];\n\t\tfor (let i = 0; i < polygon.length; i++) addLine(geometry, polygon[i], tile, tolerance, true, i === 0);\n\t}\n\tif (!geometry.length) return;\n\tconst tileFeature = {\n\t\ttype: 3,\n\t\ttags: feature.tags || null,\n\t\tgeometry\n\t};\n\tif (feature.id !== null) tileFeature.id = feature.id;\n\ttile.features.push(tileFeature);\n}\nfunction addLine(result, geom, tile, tolerance, isPolygon, isOuter) {\n\tconst sqTolerance = tolerance * tolerance;\n\tif (tolerance > 0 && geom.size < (isPolygon ? sqTolerance : tolerance)) {\n\t\ttile.numPoints += geom.points.length / 3;\n\t\treturn;\n\t}\n\tconst ring = [];\n\tfor (let i = 0; i < geom.points.length; i += 3) {\n\t\tif (tolerance === 0 || geom.points[i + 2] > sqTolerance) {\n\t\t\ttile.numSimplified++;\n\t\t\tring.push(geom.points[i], geom.points[i + 1]);\n\t\t}\n\t\ttile.numPoints++;\n\t}\n\tif (isPolygon) rewind(ring, isOuter);\n\tresult.push(ring);\n}\nfunction rewind(ring, clockwise) {\n\tlet area = 0;\n\tfor (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);\n\tif (area > 0 !== clockwise) return;\n\tfor (let i = 0, len = ring.length; i < len / 2; i += 2) {\n\t\tconst x = ring[i];\n\t\tconst y = ring[i + 1];\n\t\tring[i] = ring[len - 2 - i];\n\t\tring[i + 1] = ring[len - 1 - i];\n\t\tring[len - 2 - i] = x;\n\t\tring[len - 1 - i] = y;\n\t}\n}\n//#endregion\n//#region src/transform.ts\n/**\n* Transforms the coordinates of each feature in the given tile from\n* mercator-projected space into (extent x extent) tile space.\n* @param tile - the tile to transform, this gets modified in place\n* @param extent - the tile extent (usually 4096)\n* @returns the transformed tile\n*/\nfunction transformTile(tile, extent) {\n\tif (tile.transformed) return tile;\n\tconst z2 = 1 << tile.z;\n\tconst tx = tile.x;\n\tconst ty = tile.y;\n\tfor (const feature of tile.features) if (feature.type === 1) transformPointFeature(feature, extent, z2, tx, ty);\n\telse transformNonPointFeature(feature, extent, z2, tx, ty);\n\ttile.transformed = true;\n\treturn tile;\n}\n/**\n* Transforms a single point feature from mercator-projected space into (extent x extent) tile space.\n*/\nfunction transformPointFeature(feature, extent, z2, tx, ty) {\n\tconst transformed = feature;\n\tconst geometry = feature.geometry;\n\tconst point = [];\n\tfor (let i = 0; i < geometry.length; i += 2) point.push(transformPoint(geometry[i], geometry[i + 1], extent, z2, tx, ty));\n\ttransformed.geometry = point;\n\treturn transformed;\n}\n/**\n* Transforms a single non-point feature from mercator-projected space into (extent x extent) tile space.\n*/\nfunction transformNonPointFeature(feature, extent, z2, tx, ty) {\n\tconst transformed = feature;\n\tconst geometry = feature.geometry;\n\tconst nonPoint = [];\n\tfor (const geom of geometry) {\n\t\tconst ring = [];\n\t\tfor (let i = 0; i < geom.length; i += 2) ring.push(transformPoint(geom[i], geom[i + 1], extent, z2, tx, ty));\n\t\tnonPoint.push(ring);\n\t}\n\ttransformed.geometry = nonPoint;\n\treturn transformed;\n}\nfunction transformPoint(x, y, extent, z2, tx, ty) {\n\treturn [Math.round(extent * (x * z2 - tx)), Math.round(extent * (y * z2 - ty))];\n}\n//#endregion\n//#region src/tile-index.ts\nvar TileIndex = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t\tthis.total = 0;\n\t\tthis.stats = {};\n\t\tthis.tiles = {};\n\t\tthis.tileCoords = [];\n\t\tthis.stats = {};\n\t\tthis.total = 0;\n\t}\n\tinitialize(features) {\n\t\tthis.splitTile(this.clipToWorld(features), 0, 0, 0);\n\t\tif (this.options.debug) {\n\t\t\tif (features.length) console.log(\"features: %d, points: %d\", this.tiles[0].numFeatures, this.tiles[0].numPoints);\n\t\t\tconsole.timeEnd(\"generate tiles\");\n\t\t\tconsole.log(\"tiles generated:\", this.total, JSON.stringify(this.stats));\n\t\t}\n\t}\n\t/** {@inheritdoc} */\n\tupdateIndex(source, affected, options) {\n\t\tif (options.debug > 1) {\n\t\t\tconsole.log(\"invalidating tiles\");\n\t\t\tconsole.time(\"invalidating\");\n\t\t}\n\t\tthis.invalidateTiles(affected);\n\t\tif (options.debug > 1) console.timeEnd(\"invalidating\");\n\t\tconst [z, x, y] = [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0\n\t\t];\n\t\tconst rootSource = this.clipToWorld(source);\n\t\tconst rootTile = createTile(rootSource, z, x, y, options);\n\t\trootTile.source = rootSource;\n\t\tconst id = toID(z, x, y);\n\t\tthis.tiles[id] = rootTile;\n\t\tthis.tileCoords.push({\n\t\t\tz,\n\t\t\tx,\n\t\t\ty,\n\t\t\tid\n\t\t});\n\t\tif (options.debug) {\n\t\t\tconst key = `z${z}`;\n\t\t\tthis.stats[key] = (this.stats[key] || 0) + 1;\n\t\t\tthis.total++;\n\t\t}\n\t}\n\t/** {@inheritdoc} */\n\tgetClusterExpansionZoom(_clusterId) {\n\t\treturn null;\n\t}\n\t/** {@inheritdoc} */\n\tgetChildren(_clusterId) {\n\t\treturn null;\n\t}\n\t/** {@inheritdoc} */\n\tgetLeaves(_clusterId, _limit, _offset) {\n\t\treturn null;\n\t}\n\t/** {@inheritdoc} */\n\tgetTile(z, x, y) {\n\t\tconst { extent, debug } = this.options;\n\t\tconst z2 = 1 << z;\n\t\tif (!this.options.wrap && (x < 0 || x >= z2)) return null;\n\t\tx = x + z2 & z2 - 1;\n\t\tconst id = toID(z, x, y);\n\t\tif (this.tiles[id]) return transformTile(this.tiles[id], extent);\n\t\tif (debug > 1) console.log(\"drilling down to z%d-%d-%d\", z, x, y);\n\t\tlet z0 = z;\n\t\tlet x0 = x;\n\t\tlet y0 = y;\n\t\tlet parent;\n\t\twhile (!parent && z0 > 0) {\n\t\t\tz0--;\n\t\t\tx0 = x0 >> 1;\n\t\t\ty0 = y0 >> 1;\n\t\t\tparent = this.tiles[toID(z0, x0, y0)];\n\t\t}\n\t\tif (!parent?.source) return null;\n\t\tif (debug > 1) {\n\t\t\tconsole.log(\"found parent tile z%d-%d-%d\", z0, x0, y0);\n\t\t\tconsole.time(\"drilling down\");\n\t\t}\n\t\tthis.splitTile(parent.source, z0, x0, y0, z, x, y);\n\t\tif (debug > 1) console.timeEnd(\"drilling down\");\n\t\tif (!this.tiles[id]) return null;\n\t\treturn transformTile(this.tiles[id], extent);\n\t}\n\t/**\n\t* The features the top tile starts from. A world that wraps keeps them all left and right, where wrapping already\n\t* put them inside, and one that doesn't only what lies inside the world square and its buffer. Positions in the\n\t* unit square are also cut above and below in a world that wraps, where lng/lat is clamped already. The index keeps\n\t* the rest, so an update can still move a feature in from outside.\n\t*/\n\tclipToWorld(features) {\n\t\tconst { wrap, coordinates } = this.options;\n\t\tif (wrap && coordinates !== \"unitSquare\") return features;\n\t\tconst buffer = this.options.buffer / this.options.extent;\n\t\treturn clip(wrap ? features : clip(features, 1, -buffer, 1 + buffer, 0, -Infinity, Infinity, this.options) || [], 1, -buffer, 1 + buffer, 1, -Infinity, Infinity, this.options) || [];\n\t}\n\t/**\n\t* splits features from a parent tile to sub-tiles.\n\t* z, x, and y are the coordinates of the parent tile\n\t* cz, cx, and cy are the coordinates of the target tile\n\t* \n\t* If no target tile is specified, splitting stops when we reach the maximum\n\t* zoom or the number of points is low as specified in the options.\n\t* @internal\n\t* @param features - features to split\n\t* @param z - tile zoom level\n\t* @param x - tile x coordinate\n\t* @param y - tile y coordinate\n\t* @param cz - target tile zoom level\n\t* @param cx - target tile x coordinate\n\t* @param cy - target tile y coordinate\n\t*/\n\tsplitTile(features, z, x, y, cz, cx, cy) {\n\t\tconst stack = [\n\t\t\tfeatures,\n\t\t\tz,\n\t\t\tx,\n\t\t\ty\n\t\t];\n\t\tconst options = this.options;\n\t\tconst debug = options.debug;\n\t\twhile (stack.length) {\n\t\t\ty = stack.pop();\n\t\t\tx = stack.pop();\n\t\t\tz = stack.pop();\n\t\t\tfeatures = stack.pop();\n\t\t\tconst z2 = 1 << z;\n\t\t\tconst id = toID(z, x, y);\n\t\t\tlet tile = this.tiles[id];\n\t\t\tif (!tile) {\n\t\t\t\tif (debug > 1) console.time(\"creation\");\n\t\t\t\ttile = this.tiles[id] = createTile(features, z, x, y, options);\n\t\t\t\tthis.tileCoords.push({\n\t\t\t\t\tz,\n\t\t\t\t\tx,\n\t\t\t\t\ty,\n\t\t\t\t\tid\n\t\t\t\t});\n\t\t\t\tif (debug) {\n\t\t\t\t\tif (debug > 1) {\n\t\t\t\t\t\tconsole.log(\"tile z%d-%d-%d (features: %d, points: %d, simplified: %d)\", z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);\n\t\t\t\t\t\tconsole.timeEnd(\"creation\");\n\t\t\t\t\t}\n\t\t\t\t\tconst key = `z${z}`;\n\t\t\t\t\tthis.stats[key] = (this.stats[key] || 0) + 1;\n\t\t\t\t\tthis.total++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttile.source = features;\n\t\t\tif (cz == null) {\n\t\t\t\tif (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;\n\t\t\t} else if (z === options.maxZoom || z === cz) continue;\n\t\t\telse if (cz != null) {\n\t\t\t\tconst zoomSteps = cz - z;\n\t\t\t\tif (x !== cx >> zoomSteps || y !== cy >> zoomSteps) continue;\n\t\t\t}\n\t\t\ttile.source = null;\n\t\t\tif (!features.length) continue;\n\t\t\tif (debug > 1) console.time(\"clipping\");\n\t\t\tconst k1 = .5 * options.buffer / options.extent;\n\t\t\tconst k2 = .5 - k1;\n\t\t\tconst k3 = .5 + k1;\n\t\t\tconst k4 = 1 + k1;\n\t\t\tlet tl = null;\n\t\t\tlet bl = null;\n\t\t\tlet tr = null;\n\t\t\tlet br = null;\n\t\t\tconst left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);\n\t\t\tconst right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);\n\t\t\tif (left) {\n\t\t\t\ttl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);\n\t\t\t\tbl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);\n\t\t\t}\n\t\t\tif (right) {\n\t\t\t\ttr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);\n\t\t\t\tbr = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);\n\t\t\t}\n\t\t\tif (debug > 1) console.timeEnd(\"clipping\");\n\t\t\tstack.push(tl || [], z + 1, x * 2, y * 2);\n\t\t\tstack.push(bl || [], z + 1, x * 2, y * 2 + 1);\n\t\t\tstack.push(tr || [], z + 1, x * 2 + 1, y * 2);\n\t\t\tstack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);\n\t\t}\n\t}\n\t/**\n\t* Invalidates (removes) tiles affected by the provided features\n\t* @internal\n\t* @param features \n\t*/\n\tinvalidateTiles(features) {\n\t\tif (!features.length) return;\n\t\tconst options = this.options;\n\t\tconst { debug } = options;\n\t\tlet minX = Infinity;\n\t\tlet maxX = -Infinity;\n\t\tlet minY = Infinity;\n\t\tlet maxY = -Infinity;\n\t\tfor (const feature of features) {\n\t\t\tminX = Math.min(minX, feature.minX);\n\t\t\tmaxX = Math.max(maxX, feature.maxX);\n\t\t\tminY = Math.min(minY, feature.minY);\n\t\t\tmaxY = Math.max(maxY, feature.maxY);\n\t\t}\n\t\tconst k1 = options.buffer / options.extent;\n\t\tconst removedLookup = /* @__PURE__ */ new Set();\n\t\tfor (const id in this.tiles) {\n\t\t\tconst tile = this.tiles[id];\n\t\t\tconst z2 = 1 << tile.z;\n\t\t\tconst tileMinX = (tile.x - k1) / z2;\n\t\t\tconst tileMaxX = (tile.x + 1 + k1) / z2;\n\t\t\tconst tileMinY = (tile.y - k1) / z2;\n\t\t\tconst tileMaxY = (tile.y + 1 + k1) / z2;\n\t\t\tif (maxX < tileMinX || minX >= tileMaxX || maxY < tileMinY || minY >= tileMaxY) continue;\n\t\t\tlet intersects = false;\n\t\t\tfor (const feature of features) if (feature.maxX >= tileMinX && feature.minX < tileMaxX && feature.maxY >= tileMinY && feature.minY < tileMaxY) {\n\t\t\t\tintersects = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!intersects) continue;\n\t\t\tif (debug) {\n\t\t\t\tif (debug > 1) console.log(\"invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)\", tile.z, tile.x, tile.y, tile.numFeatures, tile.numPoints, tile.numSimplified);\n\t\t\t\tconst key = `z${tile.z}`;\n\t\t\t\tthis.stats[key] = (this.stats[key] || 0) - 1;\n\t\t\t\tthis.total--;\n\t\t\t}\n\t\t\tdelete this.tiles[id];\n\t\t\tremovedLookup.add(id);\n\t\t}\n\t\tif (removedLookup.size) this.tileCoords = this.tileCoords.filter((c) => !removedLookup.has(c.id));\n\t}\n};\nfunction toID(z, x, y) {\n\treturn ((1 << z) * y + x) * 32 + z;\n}\n//#endregion\n//#region src/geojsonvt.ts\nconst defaultOptions = {\n\tmaxZoom: 14,\n\tindexMaxZoom: 5,\n\tindexMaxPoints: 1e5,\n\ttolerance: 3,\n\textent: 4096,\n\tbuffer: 64,\n\tlineMetrics: false,\n\tpromoteId: null,\n\tgenerateId: false,\n\tupdateable: false,\n\tcluster: false,\n\tclusterOptions: defaultClusterOptions,\n\tdebug: 0,\n\tcoordinates: \"lngLat\",\n\twrap: true\n};\n/**\n* Main class for creating and managing a vector tile index from GeoJSON data.\n*/\nvar GeoJSONVT = class {\n\tconstructor(data, options) {\n\t\toptions = this.options = Object.assign({}, defaultOptions, options);\n\t\tthis.worldCoordinateHelper = getWorldCoordinateHelper(options.coordinates);\n\t\tconst debug = options.debug;\n\t\tif (debug) console.time(\"preprocess data\");\n\t\tif (options.maxZoom < 0 || options.maxZoom > 24) throw new Error(\"maxZoom should be in the 0-24 range\");\n\t\tif (options.promoteId && options.generateId) throw new Error(\"promoteId and generateId cannot be used together.\");\n\t\tif (options.updateable) this.unlocated = /* @__PURE__ */ new Map();\n\t\tlet features = convertToInternal(data, options, this.unlocated);\n\t\tif (debug) {\n\t\t\tconsole.timeEnd(\"preprocess data\");\n\t\t\tconsole.log(\"index: maxZoom: %d, maxPoints: %d\", options.indexMaxZoom, options.indexMaxPoints);\n\t\t\tconsole.time(\"generate tiles\");\n\t\t}\n\t\tfeatures = wrap(features, options);\n\t\tif (options.updateable) this.source = features;\n\t\tthis.initializeIndex(features, options);\n\t}\n\tinitializeIndex(features, options) {\n\t\tthis.tileIndex = options.cluster ? new ClusterTileIndex({\n\t\t\t...options.clusterOptions,\n\t\t\tcoordinates: options.coordinates,\n\t\t\twrap: options.wrap\n\t\t}) : new TileIndex(options);\n\t\tif (!features.length) return;\n\t\tthis.tileIndex.initialize(features);\n\t}\n\t/**\n\t* Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored.\n\t* @param z - tile zoom level\n\t* @param x - tile x coordinate\n\t* @param y - tile y coordinate\n\t* @returns the transformed tile or null if not found\n\t*/\n\tgetTile(z, x, y) {\n\t\tz = +z;\n\t\tx = +x;\n\t\ty = +y;\n\t\tif (z < 0 || z > 24) return null;\n\t\treturn this.tileIndex.getTile(z, x, y);\n\t}\n\t/**\n\t* Updates the source data feature set using a {@link GeoJSONVTSourceDiff}\n\t* @param diff - the source diff object\n\t*/\n\tupdateData(diff, filter) {\n\t\tconst options = this.options;\n\t\tif (!options.updateable) throw new Error(\"to update tile geojson `updateable` option must be set to true\");\n\t\tlet { affected, source } = applySourceDiff(this.source, diff, options, this.unlocated);\n\t\tif (filter) ({affected, source} = this.filterUpdate(source, affected, filter));\n\t\tif (!affected.length) return;\n\t\tthis.source = source;\n\t\tthis.tileIndex.updateIndex(source, affected, options);\n\t}\n\t/**\n\t* Filter an update using a predicate function, the features an update emptied included, so that one the filter\n\t* rejects can't come back with a later update. A feature without a geometry at all isn't passed to the predicate.\n\t* Returns the affected and updated source features.\n\t*/\n\tfilterUpdate(source, affected, predicate) {\n\t\tconst removeIds = /* @__PURE__ */ new Set();\n\t\tfor (const feature of source) {\n\t\t\tif (feature.id == void 0) continue;\n\t\t\tif (predicate(featureToGeoJSON(feature, this.worldCoordinateHelper))) continue;\n\t\t\taffected.push(feature);\n\t\t\tremoveIds.add(feature.id);\n\t\t}\n\t\tsource = source.filter((feature) => !removeIds.has(feature.id));\n\t\tfor (const [id, feature] of this.unlocated ?? []) if (feature.geometry && !predicate(feature)) this.unlocated.delete(id);\n\t\treturn {\n\t\t\taffected,\n\t\t\tsource\n\t\t};\n\t}\n\t/**\n\t* Returns source data as GeoJSON - only available when `updateable` option is set to true.\n\t*/\n\tgetData() {\n\t\tif (!this.options.updateable) throw new Error(\"to retrieve data the `updateable` option must be set to true\");\n\t\treturn convertToGeoJSON(this.source, this.worldCoordinateHelper);\n\t}\n\t/**\n\t* Update supercluster options and regenerate the index.\n\t* @param cluster - whether to enable clustering\n\t* @param clusterOptions - {@link SuperclusterOptions} without `coordinates` and `wrap`, which come from the index options\n\t*/\n\tupdateClusterOptions(cluster, clusterOptions) {\n\t\tconst wasCluster = this.options.cluster;\n\t\tthis.options.cluster = cluster;\n\t\tthis.options.clusterOptions = clusterOptions;\n\t\tif (wasCluster == cluster) {\n\t\t\tthis.tileIndex.updateIndex(this.source, [], this.options);\n\t\t\treturn;\n\t\t}\n\t\tthis.initializeIndex(this.source, this.options);\n\t}\n\t/**\n\t* Returns the zoom level at which a cluster expands into multiple children.\n\t* @param clusterId - The target cluster id.\n\t* @returns the expansion zoom or null in case of non-clustered source\n\t*/\n\tgetClusterExpansionZoom(clusterId) {\n\t\treturn this.tileIndex.getClusterExpansionZoom(clusterId);\n\t}\n\t/**\n\t* Returns the immediate children (clusters or points) of a cluster as GeoJSON.\n\t* @param clusterId - The target cluster id.\n\t* @returns the immediate children or null in case of non-clustered source\n\t*/\n\tgetClusterChildren(clusterId) {\n\t\treturn this.tileIndex.getChildren(clusterId);\n\t}\n\t/**\n\t* Returns leaf point features under a cluster, paginated by `limit` and `offset`.\n\t* @param clusterId - The target cluster id.\n\t* @param limit - Maximum number of points to return (defaults to `10`).\n\t* @param offset - Number of points to skip before collecting results (defaults to `0`).\n\t* @returns leaf point features under a cluster or null in case of non-clustered source\n\t*/\n\tgetClusterLeaves(clusterId, limit, offset) {\n\t\treturn this.tileIndex.getLeaves(clusterId, limit, offset);\n\t}\n};\n//#endregion\n//#region src/geojson-to-tile.ts\n/**\n* Converts GeoJSON data directly to a single vector tile without building a tile index.\n*\n* Unlike the {@link GeoJSONVT} class which builds a hierarchical tile index for efficient\n* repeated tile access, this function generates a single tile on-demand. This is useful when:\n* - You only need one specific tile and don't need to query multiple tiles\n* - The source data is already spatially filtered to the tile's bounding box\n* - You want to avoid the overhead of building a full tile index\n*\n* @example\n* ```ts\n* import {geoJSONToTile} from '@maplibre/geojson-vt';\n*\n* const geojson = {\n*   type: 'FeatureCollection',\n*   features: [{\n*     type: 'Feature',\n*     geometry: { type: 'Point', coordinates: [-77.03, 38.90] },\n*     properties: { name: 'Washington, D.C.' }\n*   }]\n* };\n*\n* const tile = geoJSONToTile(geojson, 10, 292, 391, { extent: 4096 });\n* ```\n*\n* @param data - GeoJSON data (Feature, FeatureCollection, or Geometry)\n* @param z - Tile zoom level\n* @param x - Tile x coordinate\n* @param y - Tile y coordinate\n* @param options - Optional configuration for tile generation\n* @returns The generated tile with geometries in tile coordinates, or null if no features\n*/\nfunction geoJSONToTile(data, z, x, y, options = {}) {\n\toptions = {\n\t\t...defaultOptions,\n\t\twrap: false,\n\t\t...options\n\t};\n\tconst { wrap: shouldWrap, clip: shouldClip = false } = options;\n\tlet features = convertToInternal(data, options);\n\tif (shouldWrap) features = wrap(features, options);\n\tif (shouldClip || options.lineMetrics) {\n\t\tconst pow2 = 1 << z;\n\t\tconst buffer = options.buffer / options.extent;\n\t\tfeatures = clip(clip(features, pow2, x - buffer, x + 1 + buffer, 0, -1, 2, options) || [], pow2, y - buffer, y + 1 + buffer, 1, -1, 2, options);\n\t}\n\treturn transformTile(createTile(features ?? [], z, x, y, options), options.extent);\n}\n//#endregion\nexport { GEOJSONVT_CLIP_END, GEOJSONVT_CLIP_START, GeoJSONVT, ClusterTileIndex as Supercluster, geoJSONToTile };\n\n//# sourceMappingURL=geojson-vt.mjs.map", "import {createLayout, type StructArrayLayout, type StructArrayMember} from '../../util/struct_array.ts';\n\nexport const lineLayoutAttributes: StructArrayLayout = createLayout([\n    {name: 'a_pos_normal', components: 2, type: 'Int16'},\n    {name: 'a_data', components: 4, type: 'Uint8'},\n    {name: 'a_offset_normal', components: 2, type: 'Int8'}\n], 2);\n\nexport const members: StructArrayMember[] = lineLayoutAttributes.members;\nexport const size: number = lineLayoutAttributes.size;\nexport const alignment: number = lineLayoutAttributes.alignment;\n", "import {createLayout, type StructArrayLayout, type StructArrayMember} from '../../util/struct_array.ts';\n\nexport const lineLayoutAttributesExt: StructArrayLayout = createLayout([\n    {name: 'a_uv_x', components: 1, type: 'Float32'},\n    {name: 'a_split_index', components: 1, type: 'Float32'},\n]);\n\nexport const members: StructArrayMember[] = lineLayoutAttributesExt.members;\nexport const size: number = lineLayoutAttributesExt.size;\nexport const alignment: number = lineLayoutAttributesExt.alignment;\n", "import {LineLayoutArray, LineExtLayoutArray} from '../array_types.g.ts';\nimport {GEOJSONVT_CLIP_END, GEOJSONVT_CLIP_START} from '@maplibre/geojson-vt';\nimport {members as layoutAttributes} from './line_attributes.ts';\nimport {members as layoutAttributesExt} from './line_attributes_ext.ts';\nimport {SegmentVector} from '../segment.ts';\nimport {ProgramConfigurationSet} from '../program_configuration.ts';\nimport {TriangleIndexArray} from '../array_types.g.ts';\nimport {EXTENT} from '../extent.ts';\nimport {VectorTileFeature} from '@mapbox/vector-tile';\nimport {register} from '../../util/web_worker_transfer.ts';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features.ts';\nimport {loadGeometry} from '../load_geometry.ts';\nimport {toEvaluationFeature} from '../evaluation_feature.ts';\nimport {EvaluationParameters} from '../../style/evaluation_parameters.ts';\nimport {subdivideVertexLine} from '../../render/subdivision.ts';\nimport {clamp} from '../../util/util.ts';\n\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {\n    Bucket,\n    BucketParameters,\n    BucketFeature,\n    BucketDependencyParameters,\n    IndexedFeature,\n    PopulateParameters\n} from '../bucket.ts';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {Segment} from '../segment.ts';\nimport type {RGBAImage} from '../../util/image.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {Texture} from '../../webgl/texture.ts';\nimport type {IndexBuffer} from '../../webgl/index_buffer.ts';\nimport type {VertexBuffer} from '../../webgl/vertex_buffer.ts';\nimport type {FeatureStates} from '../../source/source_state.ts';\nimport type {ImagePosition} from '../../render/image_atlas.ts';\nimport type {SubdivisionGranularitySetting} from '../../render/subdivision_granularity_settings.ts';\nimport type {DashEntry} from '../../render/line_atlas.ts';\nimport type {VectorTileLayerLike} from '@maplibre/vt-pbf';\n\n// NOTE ON EXTRUDE SCALE:\n// scale the extrusion vector so that the normal length is this value.\n// contains the \"texture\" normals (-1..1). this is distinct from the extrude\n// normals for line joins, because the x-value remains 0 for the texture\n// normal array, while the extrude normal actually moves the vertex to create\n// the acute/bevelled line join.\nconst EXTRUDE_SCALE = 63;\n\n/*\n * Sharp corners cause dashed lines to tilt because the distance along the line\n * is the same at both the inner and outer corners. To improve the appearance of\n * dashed lines we add extra points near sharp corners so that a smaller part\n * of the line is tilted.\n *\n * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an\n * extra vertex. The default is 75 degrees.\n *\n * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner.\n */\nconst COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180));\nconst SHARP_CORNER_OFFSET = 15;\n\n// Angle per triangle for approximating round line joins.\nconst DEG_PER_TRIANGLE = 20;\n\n/**\n * Longest miter vector `line-offset` follows into a corner. It is also as far as the vector can be\n * stored: a_offset_normal holds bytes scaled by EXTRUDE_SCALE, which cap out at 127 / 63.\n */\nconst MAX_OFFSET_MITER_LENGTH = 2;\n\n/**\n * Miter length at which `line-offset` starts easing from the miter vector of a join to the plain\n * segment normals. The bisector of a near hairpin points along the line rather than across it, so a\n * corner that sharp is offset forwards past its neighbours instead of sideways.\n */\nconst OFFSET_FALLBACK_START = 3;\n\n/** Miter length at which `line-offset` follows the segment normals alone. */\nconst OFFSET_FALLBACK_END = 8;\n\n// The number of bits that is used to store the line distance in the buffer.\nconst LINE_DISTANCE_BUFFER_BITS = 15;\n\n// We don't have enough bits for the line distance as we'd like to have, so\n// use this value to scale the line distance (in tile units) down to a smaller\n// value. This lets us store longer distances while sacrificing precision.\nconst LINE_DISTANCE_SCALE = 1 / 2;\n\n// The maximum line distance, in tile units, that fits in the buffer.\nconst MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE;\n\ntype LineClips = {\n    start: number;\n    end: number;\n};\n\ntype GradientTexture = {\n    texture?: Texture;\n    gradient?: RGBAImage;\n    version?: number;\n};\n\n/**\n * @internal\n * Line bucket class\n */\nexport class LineBucket implements Bucket {\n    distance: number;\n    totalDistance: number;\n    maxLineLength: number;\n    scaledDistance: number;\n    lineClips?: LineClips;\n\n    e1: number;\n    e2: number;\n\n    index: number;\n    zoom: number;\n    overscaling: number;\n    layers: LineStyleLayer[];\n    layerIds: string[];\n    gradients: {[x: string]: GradientTexture};\n    stateDependentLayers: any[];\n    stateDependentLayerIds: string[];\n    patternFeatures: BucketFeature[];\n    lineClipsArray: LineClips[];\n\n    layoutVertexArray: LineLayoutArray;\n    layoutVertexBuffer: VertexBuffer;\n    layoutVertexArray2: LineExtLayoutArray;\n    layoutVertexBuffer2: VertexBuffer;\n\n    indexArray: TriangleIndexArray;\n    indexBuffer: IndexBuffer;\n\n    hasDependencies: boolean;\n    programConfigurations: ProgramConfigurationSet<LineStyleLayer>;\n    segments: SegmentVector;\n    uploaded: boolean;\n\n    constructor(options: BucketParameters<LineStyleLayer>) {\n        this.zoom = options.zoom;\n        this.overscaling = options.overscaling;\n        this.layers = options.layers;\n        this.layerIds = this.layers.map(layer => layer.id);\n        this.index = options.index;\n        this.hasDependencies = false;\n        this.patternFeatures = [];\n        this.lineClipsArray = [];\n        this.gradients = {};\n        for (const layer of this.layers) {\n            this.gradients[layer.id] = {};\n        }\n\n        this.layoutVertexArray = new LineLayoutArray();\n        this.layoutVertexArray2 = new LineExtLayoutArray();\n        this.indexArray = new TriangleIndexArray();\n        this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n        this.segments = new SegmentVector();\n        this.maxLineLength = 0;\n\n        this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n    }\n\n    populate(features: IndexedFeature[], options: PopulateParameters, canonical: CanonicalTileID): void {\n        this.hasDependencies = hasPattern('line', this.layers, options) || this.hasLineDasharray(this.layers);\n        const lineSortKey = this.layers[0].layout.get('line-sort-key');\n        const sortFeaturesByKey = !lineSortKey.isConstant();\n        const bucketFeatures: BucketFeature[] = [];\n\n        const globalProperties = new EvaluationParameters(this.zoom);\n        const needGeometry = this.layers[0]._featureFilter.needGeometry;\n        for (const {feature, id, index, sourceLayerIndex} of features) {\n            const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n            if (!this.layers[0]._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue;\n\n            const sortKey = sortFeaturesByKey ?\n                lineSortKey.evaluate(evaluationFeature, {}, canonical) :\n                undefined;\n\n            const bucketFeature: BucketFeature = {\n                id,\n                properties: feature.properties,\n                type: feature.type,\n                sourceLayerIndex,\n                index,\n                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),\n                patterns: {},\n                dashes: {},\n                sortKey\n            };\n\n            bucketFeatures.push(bucketFeature);\n        }\n\n        if (sortFeaturesByKey) {\n            bucketFeatures.sort((a, b) => {\n                return (a.sortKey) - (b.sortKey);\n            });\n        }\n\n        for (const bucketFeature of bucketFeatures) {\n            const {geometry, index, sourceLayerIndex} = bucketFeature;\n\n            if (this.hasDependencies) {\n                if (hasPattern('line', this.layers, options)) {\n                    addPatternDependencies('line', this.layers, bucketFeature, {zoom: this.zoom}, options);\n                } else if (this.hasLineDasharray(this.layers)) {\n                    this.addLineDashDependencies(this.layers, bucketFeature, this.zoom, options);\n                }\n\n                // pattern features are added only once the pattern is loaded into the image atlas\n                // so are stored during populate until later updated with positions by tile worker in addFeatures\n                this.patternFeatures.push(bucketFeature);\n            } else {\n                this.addFeature(bucketFeature, geometry, index, canonical, {}, {}, options.subdivisionGranularity);\n            }\n\n            const feature = features[index].feature;\n            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n        }\n    }\n\n    update(states: FeatureStates, vtLayer: VectorTileLayerLike, imagePositions: {[_: string]: ImagePosition}, dashPositions: {[_: string]: DashEntry}): void {\n        if (!this.stateDependentLayers.length) return;\n        this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, {\n            imagePositions,\n            dashPositions\n        });\n    }\n\n    addFeatures({options, canonical, patternPositions, dashPositions}: BucketDependencyParameters): void {\n        for (const feature of this.patternFeatures) {\n            this.addFeature(feature, feature.geometry, feature.index, canonical, patternPositions, dashPositions, options.subdivisionGranularity);\n        }\n    }\n\n    isEmpty(): boolean {\n        return this.layoutVertexArray.length === 0;\n    }\n\n    uploadPending(): boolean {\n        return !this.uploaded || this.programConfigurations.needsUpload;\n    }\n\n    upload(context: Context): void {\n        if (!this.uploaded) {\n            if (this.layoutVertexArray2.length !== 0) {\n                this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, layoutAttributesExt);\n            }\n            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n            this.indexBuffer = context.createIndexBuffer(this.indexArray);\n        }\n        this.programConfigurations.upload(context);\n        this.uploaded = true;\n    }\n\n    destroy(): void {\n        if (!this.layoutVertexBuffer) return;\n        this.layoutVertexBuffer.destroy();\n        this.indexBuffer.destroy();\n        this.programConfigurations.destroy();\n        this.segments.destroy();\n    }\n\n    lineFeatureClips(feature: BucketFeature): LineClips | undefined {\n        if (!!feature.properties && Object.hasOwn(feature.properties, GEOJSONVT_CLIP_START) && Object.hasOwn(feature.properties, GEOJSONVT_CLIP_END)) {\n            const start = +feature.properties[GEOJSONVT_CLIP_START];\n            const end = +feature.properties[GEOJSONVT_CLIP_END];\n            return {start, end};\n        }\n    }\n\n    addFeature(feature: BucketFeature, geometry: Point[][], index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}, dashPositions: Record<string, DashEntry>, subdivisionGranularity: SubdivisionGranularitySetting): void {\n        const layout = this.layers[0].layout;\n        const join = layout.get('line-join').evaluate(feature, {});\n        const cap = layout.get('line-cap').evaluate(feature, {});\n        const miterLimit = layout.get('line-miter-limit').evaluate(feature, {});\n        const roundLimit = layout.get('line-round-limit').evaluate(feature, {});\n        this.lineClips = this.lineFeatureClips(feature);\n\n        for (const line of geometry) {\n            this.addLine(line, feature, join, cap, miterLimit, roundLimit, canonical, subdivisionGranularity);\n        }\n\n        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {imagePositions, dashPositions, canonical});\n    }\n\n    addLine(vertices: Point[], feature: BucketFeature, join: string, cap: string, miterLimit: number, roundLimit: number, canonical: CanonicalTileID | undefined, subdivisionGranularity: SubdivisionGranularitySetting): void {\n        this.distance = 0;\n        this.scaledDistance = 0;\n        this.totalDistance = 0;\n\n        // First, subdivide the line if needed (mostly for globe rendering)\n        const granularity = canonical ? subdivisionGranularity.line.getGranularityForZoomLevel(canonical.z) : 1;\n        vertices = subdivideVertexLine(vertices, granularity);\n\n        if (this.lineClips) {\n            this.lineClipsArray.push(this.lineClips);\n            // Calculate the total distance, in tile units, of this tiled line feature\n            for (let i = 0; i < vertices.length - 1; i++) {\n                this.totalDistance += vertices[i].dist(vertices[i + 1]);\n            }\n            this.updateScaledDistance();\n            this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);\n        }\n\n        const isPolygon = VectorTileFeature.types[feature.type] === 'Polygon';\n\n        // If the line has duplicate vertices at the ends, adjust start/length to remove them.\n        let len = vertices.length;\n        while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {\n            len--;\n        }\n        let first = 0;\n        while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {\n            first++;\n        }\n\n        // Ignore invalid geometry.\n        if (len - first < (isPolygon ? 3 : 2)) return;\n\n        if (join === 'bevel') miterLimit = 1.05;\n\n        const sharpCornerOffset = this.overscaling <= 16 ?\n            SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) :\n            0;\n\n        // we could be more precise, but it would only save a negligible amount of space\n        const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);\n\n        let currentVertex: Point;\n        let prevVertex: Point;\n        let nextVertex: Point;\n        let prevNormal: Point;\n        let nextNormal: Point;\n\n        // the last two vertices added\n        this.e1 = this.e2 = -1;\n\n        if (isPolygon) {\n            currentVertex = vertices[len - 2];\n            nextNormal = vertices[first].sub(currentVertex)._unit()._perp();\n        }\n\n        for (let i = first; i < len; i++) {\n\n            nextVertex = i === len - 1 ?\n                (isPolygon ? vertices[first + 1] : undefined) : // if it's a polygon, treat the last vertex like the first\n                vertices[i + 1]; // just the next vertex\n\n            // if two consecutive vertices exist, skip the current one\n            if (nextVertex && vertices[i].equals(nextVertex)) continue;\n\n            if (nextNormal) prevNormal = nextNormal;\n            if (currentVertex) prevVertex = currentVertex;\n\n            currentVertex = vertices[i];\n\n            // Calculate the normal towards the next vertex in this line. In case\n            // there is no next vertex, pretend that the line is continuing straight,\n            // meaning that we are just using the previous normal.\n            nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;\n\n            // If we still don't have a previous normal, this is the beginning of a\n            // non-closed line, so we're doing a straight \"join\".\n            prevNormal ||= nextNormal;\n\n            // Determine the normal of the join extrusion. It is the angle bisector\n            // of the segments between the previous line and the next line.\n            // In the case of 180° angles, the prev and next normals cancel each other out:\n            // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be\n            // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle\n            // below will also become 0 and miterLength will become Infinity.\n            let joinNormal = prevNormal.add(nextNormal);\n            if (joinNormal.x !== 0 || joinNormal.y !== 0) {\n                joinNormal._unit();\n            }\n            /*  joinNormal     prevNormal\n             *             ↖      ↑\n             *                .________. prevVertex\n             *                |\n             * nextNormal  ←  |  currentVertex\n             *                |\n             *     nextVertex !\n             *\n             */\n\n            // calculate cosines of the angle (and its half) using dot product\n            const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y;\n            const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;\n\n            // Calculate the length of the miter (the ratio of the miter to the width)\n            // as the inverse of cosine of the angle between next and join normals\n            const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;\n\n            // approximate angle from cosine\n            const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle);\n\n            const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex;\n            const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0;\n\n            const offsetNormal = joinNormal.mult(Math.min(miterLength, MAX_OFFSET_MITER_LENGTH));\n            const offsetFallback = clamp((miterLength - OFFSET_FALLBACK_START) / (OFFSET_FALLBACK_END - OFFSET_FALLBACK_START), 0, 1);\n\n            if (isSharpCorner && i > first) {\n                const prevSegmentLength = currentVertex.dist(prevVertex);\n                if (prevSegmentLength > 2 * sharpCornerOffset) {\n                    const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round());\n                    this.updateDistance(prevVertex, newPrevVertex);\n                    this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment);\n                    prevVertex = newPrevVertex;\n                }\n            }\n\n            // The join if a middle vertex, otherwise the cap.\n            const middleVertex = prevVertex && nextVertex;\n            let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap;\n\n            if (middleVertex && currentJoin === 'round') {\n                if (miterLength < roundLimit) {\n                    currentJoin = 'miter';\n                } else if (miterLength <= 2) {\n                    currentJoin = 'fakeround';\n                }\n            }\n\n            if (currentJoin === 'miter' && miterLength > miterLimit) {\n                currentJoin = 'bevel';\n            }\n\n            if (currentJoin === 'bevel') {\n                // The maximum extrude length is 128 / 63 = 2 times the width of the line\n                // so if miterLength >= 2 we need to draw a different type of bevel here.\n                if (miterLength > 2) currentJoin = 'flipbevel';\n\n                // If the miterLength is really small and the line bevel wouldn't be visible,\n                // just draw a miter join to save a triangle.\n                if (miterLength < miterLimit) currentJoin = 'miter';\n            }\n\n            // Calculate how far along the line the currentVertex is\n            if (prevVertex) this.updateDistance(prevVertex, currentVertex);\n\n            if (currentJoin === 'miter') {\n\n                joinNormal._mult(miterLength);\n                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment, false, offsetNormal);\n\n            } else if (currentJoin === 'flipbevel') {\n                // miter is too big, flip the direction to make a beveled join\n\n                if (miterLength > 100) {\n                    // Almost parallel lines\n                    joinNormal = nextNormal.mult(-1);\n\n                } else {\n                    const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag();\n                    joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1));\n                }\n                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment, false, offsetNormal, offsetFallback);\n                this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment, false, offsetNormal, offsetFallback);\n\n            } else if (currentJoin === 'bevel' || currentJoin === 'fakeround') {\n                const offset = -Math.sqrt(miterLength * miterLength - 1);\n                const offsetA = lineTurnsLeft ? offset : 0;\n                const offsetB = lineTurnsLeft ? 0 : offset;\n\n                // Close previous segment with a bevel\n                if (prevVertex) {\n                    this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment, false, offsetNormal);\n                }\n\n                if (currentJoin === 'fakeround') {\n                    // The join angle is sharp enough that a round join would be visible.\n                    // Bevel joins fill the gap between segments with a single pie slice triangle.\n                    // Create a round join by adding multiple pie slices. The join isn't actually round, but\n                    // it looks like it is at the sizes we render lines at.\n\n                    // pick the number of triangles for approximating round join by based on the angle between normals\n                    const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE);\n\n                    for (let m = 1; m < n; m++) {\n                        let t = m / n;\n                        if (t !== 0.5) {\n                            // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp\n                            const t2 = t - 0.5;\n                            const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519));\n                            const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638);\n                            t = t + t * t2 * (t - 1) * (A * t2 * t2 + B);\n                        }\n                        const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1);\n                        this.addHalfVertex(currentVertex, extrude.x, extrude.y,\n                            lineTurnsLeft ? -offsetNormal.x : offsetNormal.x,\n                            lineTurnsLeft ? -offsetNormal.y : offsetNormal.y,\n                            false, lineTurnsLeft, segment);\n                    }\n                }\n\n                if (nextVertex) {\n                    // Start next segment\n                    this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment, false, offsetNormal);\n                }\n\n            } else if (currentJoin === 'butt') {\n                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment, false, offsetNormal); // butt cap\n\n            } else if (currentJoin === 'square') {\n                const offset = prevVertex ? 1 : -1; // closing or starting square cap\n                this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment, false, offsetNormal);\n\n            } else if (currentJoin === 'round') {\n\n                if (prevVertex) {\n                    // Close previous segment with butt\n                    this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment, false, offsetNormal, offsetFallback);\n\n                    // Add round cap or linejoin at end of segment\n                    this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true, offsetNormal, offsetFallback);\n                }\n                if (nextVertex) {\n                    // Add round cap before first segment\n                    this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true, offsetNormal, offsetFallback);\n\n                    // Start next segment with a butt\n                    this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment, false, offsetNormal, offsetFallback);\n                }\n            }\n\n            if (isSharpCorner && i < len - 1) {\n                const nextSegmentLength = currentVertex.dist(nextVertex);\n                if (nextSegmentLength > 2 * sharpCornerOffset) {\n                    const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round());\n                    this.updateDistance(currentVertex, newCurrentVertex);\n                    this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment);\n                    currentVertex = newCurrentVertex;\n                }\n            }\n        }\n    }\n\n    /**\n     * Add two vertices to the buffers.\n     *\n     * @param p - the line vertex to add buffer vertices for\n     * @param normal - vertex normal\n     * @param endLeft - extrude to shift the left vertex along the line\n     * @param endRight - extrude to shift the left vertex along the line\n     * @param segment - the segment object to add the vertex to\n     * @param round - whether this is a round cap\n     * @param offsetNormal - the vector `line-offset` moves this vertex along. An offset line turns its corner where\n     * the two offset segments meet, on the angle bisector `miterLength` away, so every vertex of a join shares that\n     * vector. Defaults to the vertex normal, which is where a vertex outside a join belongs.\n     * @param offsetFallback - how far to ease `offsetNormal` back to the vertex normal, see {@link OFFSET_FALLBACK_START}\n     */\n    addCurrentVertex(p: Point, normal: Point, endLeft: number, endRight: number, segment: Segment, round: boolean = false, offsetNormal: Point = normal, offsetFallback: number = 0): void {\n        // left and right extrude vectors, perpendicularly shifted by endLeft/endRight\n        const leftX = normal.x + normal.y * endLeft;\n        const leftY = normal.y - normal.x * endLeft;\n        const rightX = -normal.x + normal.y * endRight;\n        const rightY = -normal.y - normal.x * endRight;\n\n        const offsetX = offsetNormal.x + (normal.x - offsetNormal.x) * offsetFallback;\n        const offsetY = offsetNormal.y + (normal.y - offsetNormal.y) * offsetFallback;\n\n        this.addHalfVertex(p, leftX, leftY, offsetX, offsetY, round, false, segment);\n        this.addHalfVertex(p, rightX, rightY, -offsetX, -offsetY, round, true, segment);\n\n        // There is a maximum \"distance along the line\" that we can store in the buffers.\n        // When we get close to the distance, reset it to zero and add the vertex again with\n        // a distance of zero. The max distance is determined by the number of bits we allocate\n        // to `linesofar`.\n        if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) {\n            this.distance = 0;\n            this.updateScaledDistance();\n            this.addCurrentVertex(p, normal, endLeft, endRight, segment, round, offsetNormal, offsetFallback);\n        }\n    }\n\n    /**\n     * Add a single vertex to the buffers.\n     *\n     * @param p - the line vertex to add a buffer vertex for\n     * @param extrudeX - x of the vector the vertex is extruded along by half the line width\n     * @param extrudeY - y of the vector the vertex is extruded along by half the line width\n     * @param offsetX - x of the vector `line-offset` moves the vertex along\n     * @param offsetY - y of the vector `line-offset` moves the vertex along\n     * @param round - whether this is a round cap\n     * @param up - whether this is the vertex on the positive side of the normal\n     * @param segment - the segment object to add the vertex to\n     */\n    addHalfVertex({x, y}: Point, extrudeX: number, extrudeY: number, offsetX: number, offsetY: number, round: boolean, up: boolean, segment: Segment): void {\n        const totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance;\n        // scale down so that we can store longer distances while sacrificing precision.\n        const linesofarScaled = totalDistance * LINE_DISTANCE_SCALE;\n\n        this.layoutVertexArray.emplaceBack(\n            // a_pos_normal\n            // Encode round/up the least significant bits\n            (x << 1) + (round ? 1 : 0),\n            (y << 1) + (up ? 1 : 0),\n            // a_data\n            // add 128 to store a byte in an unsigned byte\n            Math.round(EXTRUDE_SCALE * extrudeX) + 128,\n            Math.round(EXTRUDE_SCALE * extrudeY) + 128,\n            // The lower 6 bits of `linesofarScaled`, past the two unused bits of `z`, then the upper 8\n            (linesofarScaled & 0x3F) << 2,\n            linesofarScaled >> 6,\n            // a_offset_normal\n            Math.round(EXTRUDE_SCALE * offsetX),\n            Math.round(EXTRUDE_SCALE * offsetY));\n\n        // Constructs a second vertex buffer with higher precision line progress\n        if (this.lineClips) {\n            const progressRealigned = this.scaledDistance - this.lineClips.start;\n            const endClipRealigned = this.lineClips.end - this.lineClips.start;\n            const uvX = progressRealigned / endClipRealigned;\n            this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length);\n        }\n\n        const e = segment.vertexLength++;\n        if (this.e1 >= 0 && this.e2 >= 0) {\n            this.indexArray.emplaceBack(this.e1, e, this.e2);\n            segment.primitiveLength++;\n        }\n        if (up) {\n            this.e2 = e;\n        } else {\n            this.e1 = e;\n        }\n    }\n\n    updateScaledDistance(): void {\n        // Knowing the ratio of the full linestring covered by this tiled feature, as well\n        // as the total distance (in tile units) of this tiled feature, and the distance\n        // (in tile units) of the current vertex, we can determine the relative distance\n        // of this vertex along the full linestring feature and scale it to [0, 2^15)\n        this.scaledDistance = this.lineClips ?\n            this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance :\n            this.distance;\n    }\n\n    updateDistance(prev: Point, next: Point): void {\n        this.distance += prev.dist(next);\n        this.updateScaledDistance();\n    }\n\n    private hasLineDasharray(layers: LineStyleLayer[]): boolean {\n        for (const layer of layers) {\n            const dasharrayProperty = layer.paint.get('line-dasharray');\n            if (dasharrayProperty && !dasharrayProperty.isConstant()) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    private addLineDashDependencies(layers: LineStyleLayer[], bucketFeature: BucketFeature, zoom: number, options: PopulateParameters) {\n        for (const layer of layers) {\n            const dasharrayProperty = layer.paint.get('line-dasharray');\n\n            if (!dasharrayProperty || dasharrayProperty.value.kind === 'constant') {\n                continue;\n            }\n\n            const round = layer.layout.get('line-cap').evaluate(bucketFeature, {}) === 'round';\n\n            const min = {\n                dasharray: dasharrayProperty.value.evaluate({zoom: zoom - 1}, bucketFeature, {}),\n                round\n            };\n            const mid = {\n                dasharray: dasharrayProperty.value.evaluate({zoom}, bucketFeature, {}),\n                round\n            };\n            const max = {\n                dasharray: dasharrayProperty.value.evaluate({zoom: zoom + 1}, bucketFeature, {}),\n                round\n            };\n\n            const minKey = `${min.dasharray.join(',')},${min.round}`;\n            const midKey = `${mid.dasharray.join(',')},${mid.round}`;\n            const maxKey = `${max.dasharray.join(',')},${max.round}`;\n\n            options.dashDependencies[minKey] = min;\n            options.dashDependencies[midKey] = mid;\n            options.dashDependencies[maxKey] = max;\n\n            bucketFeature.dashes[layer.id] = {min: minKey, mid: midKey, max: maxKey};\n        }\n    }\n}\n\nregister('LineBucket', LineBucket, {omit: ['layers', 'patternFeatures']});\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type LineLayoutProps = {\n    \"line-cap\": DataDrivenProperty<\"butt\" | \"round\" | \"square\">,\n    \"line-join\": DataDrivenProperty<\"bevel\" | \"round\" | \"miter\">,\n    \"line-miter-limit\": DataDrivenProperty<number>,\n    \"line-round-limit\": DataDrivenProperty<number>,\n    \"line-sort-key\": DataDrivenProperty<number>,\n};\n\nexport type LineLayoutPropsPossiblyEvaluated = {\n    \"line-cap\": PossiblyEvaluatedPropertyValue<\"butt\" | \"round\" | \"square\">,\n    \"line-join\": PossiblyEvaluatedPropertyValue<\"bevel\" | \"round\" | \"miter\">,\n    \"line-miter-limit\": PossiblyEvaluatedPropertyValue<number>,\n    \"line-round-limit\": PossiblyEvaluatedPropertyValue<number>,\n    \"line-sort-key\": PossiblyEvaluatedPropertyValue<number>,\n};\n\nlet layout: Properties<LineLayoutProps>;\nconst getLayout = (): Properties<LineLayoutProps> => layout = layout || new Properties({\n    \"line-cap\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-cap\"] as any as StylePropertySpecification, \"line-cap\"),\n    \"line-join\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-join\"] as any as StylePropertySpecification, \"line-join\"),\n    \"line-miter-limit\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-miter-limit\"] as any as StylePropertySpecification, \"line-miter-limit\"),\n    \"line-round-limit\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-round-limit\"] as any as StylePropertySpecification, \"line-round-limit\"),\n    \"line-sort-key\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-sort-key\"] as any as StylePropertySpecification, \"line-sort-key\"),\n});\n\nexport type LinePaintProps = {\n    \"line-opacity\": DataDrivenProperty<number>,\n    \"line-layer-opacity\": DataConstantProperty<number>,\n    \"line-layer-blend\": DataConstantProperty<\"normal\" | \"multiply\" | \"color\" | \"luminosity\" | \"plus-lighter\" | \"screen\" | \"overlay\">,\n    \"line-color\": DataDrivenProperty<Color>,\n    \"line-translate\": DataConstantProperty<[number, number]>,\n    \"line-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"line-width\": DataDrivenProperty<number>,\n    \"line-gap-width\": DataDrivenProperty<number>,\n    \"line-offset\": DataDrivenProperty<number>,\n    \"line-blur\": DataDrivenProperty<number>,\n    \"line-dasharray\": CrossFadedDataDrivenProperty<number[]>,\n    \"line-pattern\": CrossFadedDataDrivenProperty<ResolvedImage>,\n    \"line-gradient\": ColorRampProperty,\n};\n\nexport type LinePaintPropsPossiblyEvaluated = {\n    \"line-opacity\": PossiblyEvaluatedPropertyValue<number>,\n    \"line-layer-opacity\": number,\n    \"line-layer-blend\": \"normal\" | \"multiply\" | \"color\" | \"luminosity\" | \"plus-lighter\" | \"screen\" | \"overlay\",\n    \"line-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"line-translate\": [number, number],\n    \"line-translate-anchor\": \"map\" | \"viewport\",\n    \"line-width\": PossiblyEvaluatedPropertyValue<number>,\n    \"line-gap-width\": PossiblyEvaluatedPropertyValue<number>,\n    \"line-offset\": PossiblyEvaluatedPropertyValue<number>,\n    \"line-blur\": PossiblyEvaluatedPropertyValue<number>,\n    \"line-dasharray\": PossiblyEvaluatedPropertyValue<CrossFaded<number[]>>,\n    \"line-pattern\": PossiblyEvaluatedPropertyValue<CrossFaded<ResolvedImage>>,\n    \"line-gradient\": ColorRampProperty,\n};\n\nlet paint: Properties<LinePaintProps>;\nconst getPaint = (): Properties<LinePaintProps> => paint = paint || new Properties({\n    \"line-opacity\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-opacity\"] as any as StylePropertySpecification, \"line-opacity\"),\n    \"line-layer-opacity\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-layer-opacity\"] as any as StylePropertySpecification, \"line-layer-opacity\"),\n    \"line-layer-blend\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-layer-blend\"] as any as StylePropertySpecification, \"line-layer-blend\"),\n    \"line-color\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-color\"] as any as StylePropertySpecification, \"line-color\"),\n    \"line-translate\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate\"] as any as StylePropertySpecification, \"line-translate\"),\n    \"line-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate-anchor\"] as any as StylePropertySpecification, \"line-translate-anchor\"),\n    \"line-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-width\"] as any as StylePropertySpecification, \"line-width\"),\n    \"line-gap-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-gap-width\"] as any as StylePropertySpecification, \"line-gap-width\"),\n    \"line-offset\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-offset\"] as any as StylePropertySpecification, \"line-offset\"),\n    \"line-blur\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-blur\"] as any as StylePropertySpecification, \"line-blur\"),\n    \"line-dasharray\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_line\"][\"line-dasharray\"] as any as StylePropertySpecification, \"line-dasharray\"),\n    \"line-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_line\"][\"line-pattern\"] as any as StylePropertySpecification, \"line-pattern\"),\n    \"line-gradient\": new ColorRampProperty(styleSpec[\"paint_line\"][\"line-gradient\"] as any as StylePropertySpecification, \"line-gradient\"),\n});\n\nexport default ({ get paint(): Properties<LinePaintProps> { return getPaint() }, get layout(): Properties<LineLayoutProps> { return getLayout() } });", "import {type QueryIntersectsFeatureParams, StyleLayer} from '../style_layer.ts';\nimport {LineBucket} from '../../data/bucket/line_bucket.ts';\nimport {polygonIntersectsBufferedMultiLine} from '../../util/intersection_tests.ts';\nimport {getMaximumPaintValue, translateDistance, translate, offsetLine} from '../query_utils.ts';\nimport properties, {type LineLayoutPropsPossiblyEvaluated, type LinePaintPropsPossiblyEvaluated} from './line_style_layer_properties.g.ts';\nimport {extend} from '../../util/util.ts';\nimport {EvaluationParameters} from '../evaluation_parameters.ts';\nimport {type Transitionable, type Transitioning, type Layout, type PossiblyEvaluated, DataDrivenProperty, type PossiblyEvaluatedPropertyValue} from '../properties.ts';\nimport {isZoomExpression, Step, type Feature, type FeatureState, type StylePropertyExpression} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Bucket, BucketParameters} from '../../data/bucket.ts';\nimport type {LineLayoutProps, LinePaintProps} from './line_style_layer_properties.g.ts';\n\nexport class LineFloorwidthProperty extends DataDrivenProperty<number> {\n    useIntegerZoom: true;\n\n    possiblyEvaluate(value: any, parameters: EvaluationParameters): PossiblyEvaluatedPropertyValue<number> {\n        parameters = new EvaluationParameters(Math.floor(parameters.zoom), {\n            now: parameters.now,\n            fadeDuration: parameters.fadeDuration,\n            zoomHistory: parameters.zoomHistory,\n            transition: parameters.transition\n        });\n        return super.possiblyEvaluate(value, parameters);\n    }\n\n    evaluate(value: any, globals: EvaluationParameters, feature: Feature, featureState: FeatureState): number {\n        globals = extend({}, globals, {zoom: Math.floor(globals.zoom)});\n        return super.evaluate(value, globals, feature, featureState);\n    }\n}\n\nlet lineFloorwidthProperty: LineFloorwidthProperty;\n\nexport const isLineStyleLayer = (layer: StyleLayer): layer is LineStyleLayer => layer.type === 'line';\n\nexport class LineStyleLayer extends StyleLayer {\n    _unevaluatedLayout: Layout<LineLayoutProps>;\n    layout: PossiblyEvaluated<LineLayoutProps, LineLayoutPropsPossiblyEvaluated>;\n\n    gradientVersion: number;\n    stepInterpolant: boolean;\n\n    _transitionablePaint: Transitionable<LinePaintProps>;\n    _transitioningPaint: Transitioning<LinePaintProps>;\n    paint: PossiblyEvaluated<LinePaintProps, LinePaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n        this.gradientVersion = 0;\n        if (!lineFloorwidthProperty) {\n            lineFloorwidthProperty =\n                new LineFloorwidthProperty(properties.paint.properties['line-width'].specification, 'line-floorwidth');\n            lineFloorwidthProperty.useIntegerZoom = true;\n        }\n    }\n\n    _handleSpecialPaintPropertyUpdate(name: string): void {\n        if (name === 'line-gradient') {\n            const expression = this.gradientExpression();\n            if (isZoomExpression(expression)) {\n                this.stepInterpolant = expression._styleExpression.expression instanceof Step;\n            } else {\n                this.stepInterpolant = false;\n            }\n            this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER;\n        }\n    }\n\n    gradientExpression(): StylePropertyExpression {\n        return this._transitionablePaint._values['line-gradient'].value.expression;\n    }\n\n    recalculate(parameters: EvaluationParameters, availableImages: string[]): void {\n        super.recalculate(parameters, availableImages);\n        (this.paint._values as any)['line-floorwidth'] =\n            lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters);\n    }\n\n    createBucket(parameters: BucketParameters<any>): LineBucket {\n        return new LineBucket(parameters);\n    }\n\n    queryRadius(bucket: Bucket): number {\n        const lineBucket: LineBucket = (bucket as any);\n        const width = getLineWidth(\n            getMaximumPaintValue('line-width', this, lineBucket),\n            getMaximumPaintValue('line-gap-width', this, lineBucket));\n        const offset = getMaximumPaintValue('line-offset', this, lineBucket);\n        return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate'));\n    }\n\n    queryIntersectsFeature({\n        queryGeometry,\n        feature,\n        featureState,\n        geometry,\n        transform,\n        pixelsToTileUnits}: QueryIntersectsFeatureParams\n    ): boolean {\n        const translatedPolygon = translate(queryGeometry,\n            this.paint.get('line-translate'),\n            this.paint.get('line-translate-anchor'),\n            -transform.bearingInRadians, pixelsToTileUnits);\n        const halfWidth = pixelsToTileUnits / 2 * getLineWidth(\n            this.paint.get('line-width').evaluate(feature, featureState),\n            this.paint.get('line-gap-width').evaluate(feature, featureState));\n        const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState);\n        if (lineOffset) {\n            geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits);\n        }\n\n        return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth);\n    }\n\n    isTileClipped(): boolean {\n        return true;\n    }\n}\n\nfunction getLineWidth(lineWidth: number, lineGapWidth: number): number {\n    if (lineGapWidth > 0) {\n        return lineGapWidth + 2 * lineWidth;\n    } else {\n        return lineWidth;\n    }\n}\n", "import {createLayout, type StructArrayLayout} from '../../util/struct_array.ts';\n\nexport const symbolLayoutAttributes: StructArrayLayout = createLayout([\n    {name: 'a_pos_offset',  components: 4, type: 'Int16'},\n    {name: 'a_data',        components: 4, type: 'Uint16'},\n    {name: 'a_pixeloffset',        components: 4, type: 'Int16'},\n    {name: 'a_height_offset',   components: 1, type: 'Float32'}\n], 4);\n\nexport const dynamicLayoutAttributes: StructArrayLayout = createLayout([\n    {name: 'a_projected_pos', components: 3, type: 'Float32'}\n], 4);\n\nexport const placementOpacityAttributes: StructArrayLayout = createLayout([\n    {name: 'a_fade_opacity', components: 1, type: 'Uint32'}\n], 4);\n\nexport const collisionVertexAttributes: StructArrayLayout = createLayout([\n    {name: 'a_placed', components: 2, type: 'Uint8'},\n    {name: 'a_shift', components: 2, type: 'Float32'},\n    {name: 'a_box_real', components: 2, type: 'Int16'},\n]);\n\nexport const collisionBox: StructArrayLayout = createLayout([\n    // the box is centered around the anchor point\n    {type: 'Int16', name: 'anchorPointX'},\n    {type: 'Int16', name: 'anchorPointY'},\n\n    // distances to the edges from the anchor\n    {type: 'Int16', name: 'x1'},\n    {type: 'Int16', name: 'y1'},\n    {type: 'Int16', name: 'x2'},\n    {type: 'Int16', name: 'y2'},\n\n    // the index of the feature in the original vectortile\n    {type: 'Uint32', name: 'featureIndex'},\n    // the source layer the feature appears in\n    {type: 'Uint16', name: 'sourceLayerIndex'},\n    // the bucket the feature appears in\n    {type: 'Uint16', name: 'bucketIndex'},\n]);\n\nexport const collisionBoxLayout: StructArrayLayout = createLayout([ // used to render collision boxes for debugging purposes\n    {name: 'a_pos',        components: 2, type: 'Int16'},\n    {name: 'a_anchor_pos', components: 2, type: 'Int16'},\n    {name: 'a_extrude',    components: 2, type: 'Int16'}\n], 4);\n\nexport const collisionCircleLayout: StructArrayLayout = createLayout([ // used to render collision circles for debugging purposes\n    {name: 'a_pos',        components: 2, type: 'Float32'},\n    {name: 'a_radius',     components: 1, type: 'Float32'},\n    {name: 'a_flags',      components: 2, type: 'Int16'}\n], 4);\n\nexport const quadTriangle: StructArrayLayout = createLayout([\n    {name: 'triangle', components: 3, type: 'Uint16'},\n]);\n\nexport const placement: StructArrayLayout = createLayout([\n    {type: 'Int16', name: 'anchorX'},\n    {type: 'Int16', name: 'anchorY'},\n    {type: 'Uint16', name: 'glyphStartIndex'},\n    {type: 'Uint16', name: 'numGlyphs'},\n    {type: 'Uint32', name: 'vertexStartIndex'},\n    {type: 'Uint32', name: 'lineStartIndex'},\n    {type: 'Uint32', name: 'lineLength'},\n    {type: 'Uint16', name: 'segment'},\n    {type: 'Uint16', name: 'lowerSize'},\n    {type: 'Uint16', name: 'upperSize'},\n    {type: 'Float32', name: 'lineOffsetX'},\n    {type: 'Float32', name: 'lineOffsetY'},\n    {type: 'Uint8', name: 'writingMode'},\n    {type: 'Uint8', name: 'placedOrientation'},\n    {type: 'Uint8', name: 'hidden'},\n    {type: 'Uint32', name: 'crossTileID'},\n    {type: 'Int16', name: 'associatedIconIndex'},\n    {type: 'Float32', name: 'heightOffset'}\n]);\n\nexport const symbolInstance: StructArrayLayout = createLayout([\n    {type: 'Int16', name: 'anchorX'},\n    {type: 'Int16', name: 'anchorY'},\n    {type: 'Int16', name: 'rightJustifiedTextSymbolIndex'},\n    {type: 'Int16', name: 'centerJustifiedTextSymbolIndex'},\n    {type: 'Int16', name: 'leftJustifiedTextSymbolIndex'},\n    {type: 'Int16', name: 'verticalPlacedTextSymbolIndex'},\n    {type: 'Int16', name: 'placedIconSymbolIndex'},\n    {type: 'Int16', name: 'verticalPlacedIconSymbolIndex'},\n    {type: 'Uint16', name: 'key'},\n    {type: 'Uint16', name: 'textBoxStartIndex'},\n    {type: 'Uint16', name: 'textBoxEndIndex'},\n    {type: 'Uint16', name: 'verticalTextBoxStartIndex'},\n    {type: 'Uint16', name: 'verticalTextBoxEndIndex'},\n    {type: 'Uint16', name: 'iconBoxStartIndex'},\n    {type: 'Uint16', name: 'iconBoxEndIndex'},\n    {type: 'Uint16', name: 'verticalIconBoxStartIndex'},\n    {type: 'Uint16', name: 'verticalIconBoxEndIndex'},\n    {type: 'Uint16', name: 'featureIndex'},\n    {type: 'Uint16', name: 'numHorizontalGlyphVertices'},\n    {type: 'Uint16', name: 'numVerticalGlyphVertices'},\n    {type: 'Uint16', name: 'numIconVertices'},\n    {type: 'Uint16', name: 'numVerticalIconVertices'},\n    {type: 'Uint16', name: 'useRuntimeCollisionCircles'},\n    {type: 'Uint32', name: 'crossTileID'},\n    {type: 'Float32', name: 'textBoxScale'},\n    {type: 'Float32', name: 'collisionCircleDiameter'},\n    {type: 'Uint16', name: 'textAnchorOffsetStartIndex'},\n    {type: 'Uint16', name: 'textAnchorOffsetEndIndex'},\n    {type: 'Float32', name: 'heightOffset'}\n]);\n\nexport const glyphOffset: StructArrayLayout = createLayout([\n    {type: 'Float32', name: 'offsetX'}\n]);\n\nexport const lineVertex: StructArrayLayout = createLayout([\n    {type: 'Int16', name: 'x'},\n    {type: 'Int16', name: 'y'},\n    {type: 'Int16', name: 'tileUnitDistanceFromAnchor'}\n]);\n\nexport const textAnchorOffset: StructArrayLayout = createLayout([\n    {type: 'Uint16', name: 'textAnchor'},\n    {type: 'Float32', components: 2, name: 'textOffset'}\n]);\n", "import type {PluginState, RTLPluginStatus} from './rtl_text_plugin_status.ts';\n\n/**\n * The three functions a right-to-left text plugin supplies.\n *\n * @deprecated MapLibre implements all three itself. A registered plugin still replaces the built-in\n * implementation, but this will be removed in a future release.\n */\nexport interface RTLTextPlugin {\n    applyArabicShaping: (a: string) => string;\n    processBidirectionalText: ((b: string, a: number[]) => string[]);\n    processStyledBidirectionalText: ((c: string, b: number[], a: number[]) => Array<[string, number[]]>);\n}\n\nclass RTLWorkerPlugin implements RTLTextPlugin {\n    readonly TIMEOUT = 5000;\n\n    applyArabicShaping: (a: string) => string = null;\n    processBidirectionalText: ((b: string, a: number[]) => string[]) = null;\n    processStyledBidirectionalText: ((c: string, b: number[], a: number[]) => Array<[string, number[]]>) = null;\n    pluginStatus: RTLPluginStatus = 'unavailable';\n    pluginURL: string = null;\n    loadScriptResolve: () => void = () => {};\n\n    private setState(state: PluginState): void {\n        this.pluginStatus = state.pluginStatus;\n        this.pluginURL = state.pluginURL;\n    }\n\n    private getState(): PluginState {\n        return {\n            pluginStatus: this.pluginStatus,\n            pluginURL: this.pluginURL\n        };\n    }\n\n    public setMethods(rtlTextPlugin: RTLTextPlugin): void {\n        if (rtlWorkerPlugin.isParsed()) {\n            throw new Error('RTL text plugin already registered.');\n        }\n        this.applyArabicShaping = rtlTextPlugin.applyArabicShaping;\n        this.processBidirectionalText = rtlTextPlugin.processBidirectionalText;\n        this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText;\n        this.loadScriptResolve();\n    }\n\n    public isParsed(): boolean {\n        return this.applyArabicShaping != null &&\n            this.processBidirectionalText != null &&\n            this.processStyledBidirectionalText != null;\n    }\n\n    public getRTLTextPluginStatus(): RTLPluginStatus {\n        return this.pluginStatus;\n    }\n\n    public async syncState(incomingState: PluginState, loadScript: (url: string) => Promise<void>): Promise<PluginState> {\n        // Parsed plugin cannot be changed, so just return its current state.\n        if (this.isParsed()) {\n            return this.getState();\n        }\n\n        if (incomingState.pluginStatus !== 'loading') {\n            // simply sync and done\n            this.setState(incomingState);\n            return incomingState;\n        }\n        const urlToLoad = incomingState.pluginURL;\n        const loadScriptPromise = new Promise<void>((resolve) => {\n            this.loadScriptResolve = resolve;\n        });\n        const dontWaitForeverTimeoutPromise = new Promise<void>((resolve) => setTimeout(() => resolve(), this.TIMEOUT));\n        await loadScript(urlToLoad);\n        await Promise.race([loadScriptPromise, dontWaitForeverTimeoutPromise]);\n        const complete = this.isParsed();\n        if (complete) {\n            const loadedState: PluginState = {\n                pluginStatus: 'loaded',\n                pluginURL: urlToLoad\n            };\n            this.setState(loadedState);\n            return loadedState;\n        }\n\n        // error case\n        this.setState({\n            pluginStatus: 'error',\n            pluginURL: ''\n        });\n        throw new Error(`RTL Text Plugin failed to import scripts from ${urlToLoad}`);\n    }\n}\n\nexport const rtlWorkerPlugin: RTLWorkerPlugin = new RTLWorkerPlugin();\n", "// This file is generated. Edit build/generate-unicode-data.ts, then run `npm run generate-unicode-data`.\n\n/**\n * Returns whether the given codepoint belongs to a script that is written cursively, whose letters\n * therefore cannot be spaced apart.\n */\nexport function codePointIsInCursiveScript(codePoint: number): boolean {\n    return /[\\u0600-\\u0604\\u0606-\\u060B\\u060D-\\u061A\\u061C-\\u061E\\u0620-\\u063F\\u0641-\\u064A\\u0656-\\u066F\\u0671-\\u06DC\\u06DE-\\u070D\\u070F-\\u074A\\u074D-\\u077F\\u07C0-\\u07FA\\u07FD-\\u07FF\\u0840-\\u085B\\u085E\\u0860-\\u086A\\u0870-\\u0891\\u0897-\\u08E1\\u08E3-\\u08FF\\u1800\\u1801\\u1804\\u1806-\\u1819\\u1820-\\u1878\\u1880-\\u18AA\\uA840-\\uA877\\uFB50-\\uFD3D\\uFD40-\\uFDCF\\uFDF0-\\uFDFF\\uFE70-\\uFE74\\uFE76-\\uFEFC]|\\uD802[\\uDEC0-\\uDEE6\\uDEEB-\\uDEF6\\uDF80-\\uDF91\\uDF99-\\uDF9C\\uDFA9-\\uDFAF]|\\uD803[\\uDD00-\\uDD27\\uDD30-\\uDD39\\uDE60-\\uDE7E\\uDEC2-\\uDEC7\\uDED0-\\uDED8\\uDEFA-\\uDEFF\\uDF30-\\uDF59\\uDF70-\\uDF89\\uDFB0-\\uDFCB]|\\uD805[\\uDE60-\\uDE6C]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9C-\\uDC9F]|\\uD83A[\\uDD00-\\uDD4B\\uDD50-\\uDD59\\uDD5E\\uDD5F]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB\\uDEF0\\uDEF1]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns whether the given codepoint belongs to a script that is written horizontally from right\n * to left.\n */\nexport function codePointIsInRTLScript(codePoint: number): boolean {\n    return /[\\u0591-\\u05C7\\u05D0-\\u05EA\\u05EF-\\u05F4\\u0600-\\u0604\\u0606-\\u060B\\u060D-\\u061A\\u061C-\\u061E\\u0620-\\u063F\\u0641-\\u064A\\u0656-\\u066F\\u0671-\\u06DC\\u06DE-\\u070D\\u070F-\\u074A\\u074D-\\u07B1\\u07C0-\\u07FA\\u07FD-\\u082D\\u0830-\\u083E\\u0840-\\u085B\\u085E\\u0860-\\u086A\\u0870-\\u0891\\u0897-\\u08E1\\u08E3-\\u08FF\\uFB1D-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFD3D\\uFD40-\\uFDCF\\uFDF0-\\uFDFF\\uFE70-\\uFE74\\uFE76-\\uFEFC]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC57-\\uDC9E\\uDCA7-\\uDCAF\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDCFB-\\uDD1B\\uDD1F-\\uDD39\\uDD3F-\\uDD59\\uDD80-\\uDDB7\\uDDBC-\\uDDCF\\uDDD2-\\uDE03\\uDE05\\uDE06\\uDE0C-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE35\\uDE38-\\uDE3A\\uDE3F-\\uDE48\\uDE50-\\uDE58\\uDE60-\\uDE9F\\uDEC0-\\uDEE6\\uDEEB-\\uDEF6\\uDF00-\\uDF35\\uDF39-\\uDF55\\uDF58-\\uDF72\\uDF78-\\uDF91\\uDF99-\\uDF9C\\uDFA9-\\uDFAF]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2\\uDCFA-\\uDD27\\uDD30-\\uDD39\\uDD40-\\uDD65\\uDD69-\\uDD85\\uDD8E\\uDD8F\\uDE60-\\uDE7E\\uDE80-\\uDEA9\\uDEAB-\\uDEAD\\uDEB0\\uDEB1\\uDEC2-\\uDEC7\\uDED0-\\uDED8\\uDEFA-\\uDF27\\uDF30-\\uDF59\\uDF70-\\uDF89\\uDFB0-\\uDFCB\\uDFE0-\\uDFF6]|\\uD83A[\\uDC00-\\uDCC4\\uDCC7-\\uDCD6\\uDD00-\\uDD4B\\uDD50-\\uDD59\\uDD5E\\uDD5F]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB\\uDEF0\\uDEF1]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns whether the given codepoint is in a block of a script whose letters combine into clusters.\n */\nexport function codePointIsInComplexShapingScript(codePoint: number): boolean {\n    return /[\\u0900-\\u109F\\u1700-\\u17FF\\u1900-\\u194F\\u19E0-\\u1AAF\\u1B00-\\u1C4F\\u1CC0-\\u1CCF\\uA800-\\uA82F\\uA880-\\uA8FF\\uA930-\\uA95F\\uA980-\\uAAFF\\uABC0-\\uABFF]|\\uD802[\\uDE00-\\uDE5F]|\\uD804[\\uDC00-\\uDCCF\\uDD00-\\uDD4F\\uDD80-\\uDE4F\\uDEB0-\\uDFFF]|\\uD805[\\uDC00-\\uDCDF\\uDD80-\\uDE5F\\uDE80-\\uDF4F]|\\uD806[\\uDC00-\\uDC4F\\uDD00-\\uDD5F\\uDDA0-\\uDEAF\\uDF00-\\uDF7F]|\\uD807[\\uDC00-\\uDCBF\\uDD00-\\uDDAF\\uDEE0-\\uDF5F\\uDFC0-\\uDFFF]|\\uD818[\\uDD00-\\uDD3F]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns whether the fallback fonts specified by the\n * `localIdeographFontFamily` map option apply to the given codepoint. \n */\nexport function codePointUsesLocalIdeographFontFamily(codePoint: number): boolean {\n    return /[\\u02EA\\u02EB\\u1100-\\u11FF\\u2E80-\\u2FDF\\u3000-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u31A0-\\u4DBF\\u4E00-\\uA48C\\uA490-\\uA4C6\\uA960-\\uA97C\\uAC00-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFE10-\\uFE1F\\uFE30-\\uFE4F\\uFF00-\\uFFEF]|\\uD81B[\\uDFE0-\\uDFFF]|[\\uD81C-\\uD822\\uD840-\\uD868\\uD86A-\\uD86D\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883\\uD885-\\uD88C][\\uDC00-\\uDFFF]|\\uD823[\\uDC00-\\uDCD5\\uDCFF-\\uDD1E\\uDD80-\\uDDF2]|\\uD82B[\\uDFF0-\\uDFFF]|\\uD82C[\\uDC00-\\uDEFB]|\\uD83C[\\uDE00-\\uDEFF]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEAD\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0\\uDFF0-\\uDFFF]|\\uD87B[\\uDC00-\\uDE5D]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A\\uDF50-\\uDFFF]|\\uD88D[\\uDC00-\\uDC79]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns whether the given codepoint participates in ideographic line\n * breaking.\n */\nexport function codePointAllowsIdeographicBreaking(codePoint: number): boolean {\n    return /[\\u02EA\\u02EB\\u2E80-\\u2FDF\\u2FF0-\\u303F\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FD-\\u30FF\\u3105-\\u312F\\u31A0-\\u4DBF\\u4E00-\\uA48C\\uA490-\\uA4C6\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFE10-\\uFE1F\\uFE30-\\uFE4F\\uFF00-\\uFFEF]|\\uD81B[\\uDFE0-\\uDFFF]|[\\uD81C-\\uD822\\uD840-\\uD868\\uD86A-\\uD86D\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883\\uD885-\\uD88C][\\uDC00-\\uDFFF]|\\uD823[\\uDC00-\\uDCD5\\uDCFF-\\uDD1E\\uDD80-\\uDDF2]|\\uD82B[\\uDFF0-\\uDFFF]|\\uD82C[\\uDC00-\\uDEFB]|\\uD83C[\\uDE00-\\uDEFF]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEAD\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0\\uDFF0-\\uDFFF]|\\uD87B[\\uDC00-\\uDE5D]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A\\uDF50-\\uDFFF]|\\uD88D[\\uDC00-\\uDC79]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * upright orientation.\n *\n * A character has upright orientation if it is drawn upright (unrotated)\n * whether the line is oriented horizontally or vertically, even if both\n * adjacent characters can be rotated. For example, a Chinese character is\n * always drawn upright. An uprightly oriented character causes an adjacent\n * “neutral” character to be drawn upright as well.\n */\nexport function codePointHasUprightVerticalOrientation(codePoint: number): boolean {\n    return /[\\u02EA\\u02EB\\u1100-\\u11FF\\u1401-\\u167F\\u18B0-\\u18FF\\u2065\\u20DD-\\u20E0\\u20E2-\\u20E4\\u2B97\\u2BF0-\\u2BFF\\u2E50\\u2E51\\u2E80-\\u3007\\u3012\\u3013\\u3020-\\u302F\\u3031-\\u30FB\\u30FD-\\uA4CF\\uA960-\\uA97F\\uAC00-\\uD7FF\\uF900-\\uFAFF\\uFE10-\\uFE1F\\uFE30-\\uFE48\\uFE50-\\uFE57\\uFE5F-\\uFE62\\uFE67-\\uFE6F\\uFF00-\\uFF07\\uFF0A-\\uFF0C\\uFF0E-\\uFF19\\uFF1F-\\uFF3A\\uFF3C\\uFF3E\\uFF40-\\uFF5A\\uFFE0-\\uFFE2\\uFFE4-\\uFFE7\\uFFF0-\\uFFF8]|\\uD802[\\uDD80-\\uDD9F]|\\uD805[\\uDD80-\\uDDFF]|\\uD806[\\uDE00-\\uDEBF]|[\\uD80C-\\uD810\\uD81C-\\uD822\\uD83C\\uD83D\\uD840-\\uD87E\\uD880-\\uD8BE][\\uDC00-\\uDFFF]|\\uD811[\\uDC00-\\uDE7F]|\\uD81B[\\uDFE0-\\uDFFF]|\\uD823[\\uDC00-\\uDDFF]|\\uD82B[\\uDFF0-\\uDFFF]|\\uD82C[\\uDC00-\\uDEFF]|\\uD833[\\uDEC0-\\uDFCF]|\\uD834[\\uDC00-\\uDDFF\\uDEE0-\\uDF7F]|\\uD836[\\uDC00-\\uDEAF]|\\uD83E[\\uDD00-\\uDEFF]|[\\uD87F\\uD8BF][\\uDC00-\\uDFFD]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * neutral orientation.\n *\n * A character has neutral orientation if it may be drawn rotated or unrotated\n * when the line is oriented vertically, depending on the orientation of the\n * adjacent characters. For example, along a vertically oriented line, the\n * vulgar fraction ½ is drawn upright among Chinese characters but rotated among\n * Latin letters. A neutrally oriented character does not influence whether an\n * adjacent character is drawn upright or rotated.\n */\nexport function codePointHasNeutralVerticalOrientation(codePoint: number): boolean {\n    return /[\\xA7\\xA9\\xAE\\xB1\\xBC-\\xBE\\xD7\\xF7\\u2016\\u2020\\u2021\\u2030\\u2031\\u203B\\u203C\\u2042\\u2047-\\u2049\\u2051\\u2100-\\u218F\\u221E\\u2234\\u2235\\u2300-\\u2307\\u230C-\\u231F\\u2324-\\u2328\\u232B\\u237D-\\u239A\\u23BE-\\u23CD\\u23CF\\u23D1-\\u23DB\\u23E2-\\u2422\\u2424-\\u24FF\\u25A0-\\u2619\\u2620-\\u2767\\u2776-\\u2793\\u2B12-\\u2B2F\\u2B50-\\u2B59\\u2BB8-\\u2BEB\\u3000-\\u303F\\u30A0-\\u30FF\\uE000-\\uF8FF\\uFE30-\\uFE6F\\uFF00-\\uFFEF\\uFFFC\\uFFFD]|[\\uDB80-\\uDBFF][\\uDC00-\\uDFFF]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns whether the text could hold a grapheme cluster of more than one codepoint, and so is worth\n * segmenting. A negative answer means every codepoint of it stands alone.\n */\nexport function textCanContainGraphemeClusters(text: string): boolean {\n    return /[\\r\\u0300-\\u036F\\u0483-\\u0489\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0600-\\u0605\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DD\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u070F\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u07FD\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u0890\\u0891\\u0897-\\u089F\\u08CA-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u09FE\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0AFA-\\u0AFF\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B55-\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C00-\\u0C04\\u0C3C\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C81-\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0CF3\\u0D00-\\u0D03\\u0D3B\\u0D3C\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D62\\u0D63\\u0D81-\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E33-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB3-\\u0EBC\\u0EC8-\\u0ECE\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1037\\u1039-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1084-\\u1086\\u108D\\u109D\\u1100-\\u11FF\\u135D-\\u135F\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u180F\\u1885\\u1886\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A7C\\u1A7F\\u1AB0-\\u1ADD\\u1AE0-\\u1AEB\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF4\\u1CF7-\\u1CF9\\u1DC0-\\u1DFF\\u200C\\u200D\\u20D0-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F-\\uA672\\uA674-\\uA67D\\uA69E\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA82C\\uA880\\uA881\\uA8B4-\\uA8C5\\uA8E0-\\uA8F1\\uA8FF\\uA926-\\uA92D\\uA947-\\uA953\\uA960-\\uA97C\\uA980-\\uA983\\uA9B3-\\uA9C0\\uA9E5\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFF9E\\uFF9F]|\\uD800[\\uDDFD\\uDEE0\\uDF76-\\uDF7A]|\\uD802[\\uDE01-\\uDE03\\uDE05\\uDE06\\uDE0C-\\uDE0F\\uDE38-\\uDE3A\\uDE3F\\uDEE5\\uDEE6]|\\uD803[\\uDD24-\\uDD27\\uDD69-\\uDD6D\\uDEAB\\uDEAC\\uDEFA-\\uDEFF\\uDF46-\\uDF50\\uDF82-\\uDF85]|\\uD804[\\uDC00-\\uDC02\\uDC38-\\uDC46\\uDC70\\uDC73\\uDC74\\uDC7F-\\uDC82\\uDCB0-\\uDCBA\\uDCBD\\uDCC2\\uDCCD\\uDD00-\\uDD02\\uDD27-\\uDD34\\uDD45\\uDD46\\uDD73\\uDD80-\\uDD82\\uDDB3-\\uDDC0\\uDDC2\\uDDC3\\uDDC9-\\uDDCC\\uDDCE\\uDDCF\\uDE2C-\\uDE37\\uDE3E\\uDE41\\uDEDF-\\uDEEA\\uDF00-\\u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\\uDDAD\\uDE42-\\uDE44]|\\uD836[\\uDE00-\\uDE36\\uDE3B-\\uDE6C\\uDE75\\uDE84\\uDE9B-\\uDE9F\\uDEA1-\\uDEAF]|\\uD838[\\uDC00-\\uDC06\\uDC08-\\uDC18\\uDC1B-\\uDC21\\uDC23\\uDC24\\uDC26-\\uDC2A\\uDC8F\\uDD30-\\uDD36\\uDEAE\\uDEEC-\\uDEEF]|\\uD839[\\uDCEC-\\uDCEF\\uDDEE\\uDDEF\\uDEE3\\uDEE6\\uDEEE\\uDEEF\\uDEF5]|\\uD83A[\\uDCD0-\\uDCD6\\uDD44-\\uDD4A]|\\uD83C[\\uDDE6-\\uDDFF\\uDFFB-\\uDFFF]|\\uDB40[\\uDC20-\\uDC7F\\uDD00-\\uDDEF]/.test(text);\n}\n\n/**\n * Returns whether the given codepoint belongs to a script that does not put spaces between words,\n * and so can only be wrapped by asking the word segmenter where its words are.\n */\nexport function codePointIsWrittenWithoutSpaces(codePoint: number): boolean {\n    return /[\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECE\\u0EDC-\\u0EDF\\u0F00-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F97\\u0F99-\\u0FBC\\u0FBE-\\u0FCC\\u0FCE-\\u0FD4\\u0FD9\\u0FDA\\u1000-\\u103F\\u1050-\\u108F\\u109A-\\u109F\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19DE\\u19DF\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1AA0-\\u1AAD\\u1B00-\\u1B4C\\u1B4E-\\u1B7F\\uA980-\\uA9CD\\uA9D0-\\uA9D9\\uA9DE-\\uA9EF\\uA9FA-\\uA9FE\\uAA60-\\uAAC2\\uAADB-\\uAADF]|\\uD805[\\uDF00-\\uDF1A\\uDF1D-\\uDF2B\\uDF3A\\uDF3B\\uDF3F-\\uDF46]/gim.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Returns whether two grapheme clusters found by `Intl.Segmenter` are really one unit of writing,\n * and so have to be measured and drawn as a whole.\n *\n * The segmenter follows the tailored rules CLDR uses for stepping a cursor through text, which put a\n * boundary after an invisible stacker and before a spacing mark. Laying text out wants the untailored\n * rules of UAX #29 instead: `လ`, `ာ` and `း` are one Burmese syllable, not three.\n */\nexport function canCombineGraphemes(former: string, latter: string): boolean {\n    return /(?:[\\u1039\\u17D2\\u1A60\\u1BAB\\u200D\\uAAF6]|\\uD802\\uDE3F|\\uD804[\\uDD33\\uDFD0]|\\uD806[\\uDD3E\\uDE47\\uDE99]|\\uD807[\\uDD45\\uDD97\\uDF42])$/.test(former) || /^\\p{gc=Mc}/u.test(latter);\n}\n\n/**\n * The joining type of each Arabic character, as `start,length` code point ranges delta-encoded in\n * base 36, one entry per type. Anything absent from all of them is non-joining.\n */\nexport const ENCODED_JOINING_TYPES: Record<string, string> = {\n    C: '18g,1;g2,3;4nb,1',\n    D: '17k,1;5,1;1,1;1,5;4,d;1,7;1,2;z,2;8,g;i,12;1,2;9,1;1,1;1,2;14,3;2,1;28,9;3,f;2,4;1,1;2,3;2,6;7a,1;2,5;1,1;g,a;5,2;2,6;1,f',\n    R: '17m,4;1,1;1,1;5,4;l,1;14,3;1,3;g,i;12,1;2,9;1,1;1,1;2,2;1,1;o,2;2x,3;f,2;4,1;1,2;3,2;6u,j;b,1;r,3;1,1;2,2;6,1',\n    T: '174,b;1,1;1a,l;g,1;2t,7;2,6;2,2;1,4;bt,9;16,o;1,t;1clb,1',\n};\n\n/**\n * Each Arabic letter's Presentation Forms code points, as `[isolated, final, initial, medial]`.\n * A shape the letter is not written in is 0.\n */\nexport const PRESENTATION_FORMS: Record<number, [number, number, number, number]> = {\n    1569: [65152, 0, 0, 0],\n    1570: [65153, 65154, 0, 0],\n    1571: [65155, 65156, 0, 0],\n    1572: [65157, 65158, 0, 0],\n    1573: [65159, 65160, 0, 0],\n    1574: [65161, 65162, 65163, 65164],\n    1575: [65165, 65166, 0, 0],\n    1576: [65167, 65168, 65169, 65170],\n    1577: [65171, 65172, 0, 0],\n    1578: [65173, 65174, 65175, 65176],\n    1579: [65177, 65178, 65179, 65180],\n    1580: [65181, 65182, 65183, 65184],\n    1581: [65185, 65186, 65187, 65188],\n    1582: [65189, 65190, 65191, 65192],\n    1583: [65193, 65194, 0, 0],\n    1584: [65195, 65196, 0, 0],\n    1585: [65197, 65198, 0, 0],\n    1586: [65199, 65200, 0, 0],\n    1587: [65201, 65202, 65203, 65204],\n    1588: [65205, 65206, 65207, 65208],\n    1589: [65209, 65210, 65211, 65212],\n    1590: [65213, 65214, 65215, 65216],\n    1591: [65217, 65218, 65219, 65220],\n    1592: [65221, 65222, 65223, 65224],\n    1593: [65225, 65226, 65227, 65228],\n    1594: [65229, 65230, 65231, 65232],\n    1601: [65233, 65234, 65235, 65236],\n    1602: [65237, 65238, 65239, 65240],\n    1603: [65241, 65242, 65243, 65244],\n    1604: [65245, 65246, 65247, 65248],\n    1605: [65249, 65250, 65251, 65252],\n    1606: [65253, 65254, 65255, 65256],\n    1607: [65257, 65258, 65259, 65260],\n    1608: [65261, 65262, 0, 0],\n    1609: [65263, 65264, 64488, 64489],\n    1610: [65265, 65266, 65267, 65268],\n    1611: [65136, 0, 0, 65137],\n    1612: [65138, 0, 0, 0],\n    1613: [65140, 0, 0, 0],\n    1614: [65142, 0, 0, 65143],\n    1615: [65144, 0, 0, 65145],\n    1616: [65146, 0, 0, 65147],\n    1617: [65148, 0, 0, 65149],\n    1618: [65150, 0, 0, 65151],\n    1649: [64336, 64337, 0, 0],\n    1655: [64477, 0, 0, 0],\n    1657: [64358, 64359, 64360, 64361],\n    1658: [64350, 64351, 64352, 64353],\n    1659: [64338, 64339, 64340, 64341],\n    1662: [64342, 64343, 64344, 64345],\n    1663: [64354, 64355, 64356, 64357],\n    1664: [64346, 64347, 64348, 64349],\n    1667: [64374, 64375, 64376, 64377],\n    1668: [64370, 64371, 64372, 64373],\n    1670: [64378, 64379, 64380, 64381],\n    1671: [64382, 64383, 64384, 64385],\n    1672: [64392, 64393, 0, 0],\n    1676: [64388, 64389, 0, 0],\n    1677: [64386, 64387, 0, 0],\n    1678: [64390, 64391, 0, 0],\n    1681: [64396, 64397, 0, 0],\n    1688: [64394, 64395, 0, 0],\n    1700: [64362, 64363, 64364, 64365],\n    1702: [64366, 64367, 64368, 64369],\n    1705: [64398, 64399, 64400, 64401],\n    1709: [64467, 64468, 64469, 64470],\n    1711: [64402, 64403, 64404, 64405],\n    1713: [64410, 64411, 64412, 64413],\n    1715: [64406, 64407, 64408, 64409],\n    1722: [64414, 64415, 0, 0],\n    1723: [64416, 64417, 64418, 64419],\n    1726: [64426, 64427, 64428, 64429],\n    1728: [64420, 64421, 0, 0],\n    1729: [64422, 64423, 64424, 64425],\n    1733: [64480, 64481, 0, 0],\n    1734: [64473, 64474, 0, 0],\n    1735: [64471, 64472, 0, 0],\n    1736: [64475, 64476, 0, 0],\n    1737: [64482, 64483, 0, 0],\n    1739: [64478, 64479, 0, 0],\n    1740: [64508, 64509, 64510, 64511],\n    1744: [64484, 64485, 64486, 64487],\n    1746: [64430, 64431, 0, 0],\n    1747: [64432, 64433, 0, 0],\n};\n\n/** The lam-alef ligatures, keyed by the pair of letters they replace, as `[isolated, final]`. */\nexport const LIGATURES: Record<string, [number, number]> = {\n    '\\u0644\\u0622': [65269, 65270],\n    '\\u0644\\u0623': [65271, 65272],\n    '\\u0644\\u0625': [65273, 65274],\n    '\\u0644\\u0627': [65275, 65276],\n};\n", "import {ENCODED_JOINING_TYPES, LIGATURES, PRESENTATION_FORMS} from '../util/unicode_properties.g.ts';\n\n/**\n * How a character joins to the ones beside it.\n *\n * `D` joins on both sides, `R` only to the character before it, `L` only to the one after it, `C`\n * joins without being written itself, `T` is skipped over entirely, and `U` does not join at all.\n */\ntype JoiningType = 'R' | 'L' | 'D' | 'C' | 'U' | 'T';\n\n/** Lam, which is the only letter that has to be written as a ligature with the letter after it. */\nconst LAM = 0x0644;\n\n/**\n * The blocks the Arabic script is written from, which is what makes shaping worth doing at all.\n *\n * Arabic proper, then its supplement and two extensions, then the two blocks of shapes this file\n * rewrites letters into, so that text already shaped is recognised as needing to be looked at again.\n */\nconst ARABIC = /[\\u0600-\\u06ff\\u0750-\\u077f\\u0870-\\u089f\\u08a0-\\u08ff\\ufb50-\\ufdff\\ufe70-\\ufeff]/;\n\n/** The shape a letter takes, as an index into its entry in {@link PRESENTATION_FORMS}. */\nconst enum Form {\n    Isolated = 0,\n    Final = 1,\n    Initial = 2,\n    Medial = 3,\n}\n\n/** One character of the text, with the shape the joining rules gave it. */\ntype ShapedCharacter = {\n    codePoint: number;\n    type: JoiningType;\n    form: Form | null;\n};\n\n/**\n * Unpacks the `start,length` ranges of one joining type into the code points they stand for.\n *\n * The ranges are delta-encoded against the end of the range before them, so each is read relative to\n * where the last one stopped.\n */\nfunction decodeRanges(encoded: string, type: JoiningType, into: Map<number, JoiningType>): void {\n    let previousEnd = 0;\n    for (const range of encoded.split(';')) {\n        const [delta, length] = range.split(',').map(value => parseInt(value, 36));\n        const start = previousEnd + delta;\n        for (let codePoint = start; codePoint < start + length; codePoint++) {\n            into.set(codePoint, type);\n        }\n        previousEnd = start + length;\n    }\n}\n\nconst joiningTypes = new Map<number, JoiningType>();\nfor (const [type, encoded] of Object.entries(ENCODED_JOINING_TYPES)) {\n    decodeRanges(encoded, type as JoiningType, joiningTypes);\n}\n\n/** Anything the Unicode database does not give a joining type stands on its own. */\nfunction joiningType(codePoint: number): JoiningType {\n    return joiningTypes.get(codePoint) ?? 'U';\n}\n\n/** Whether the character before this one reaches forward to touch it. */\nfunction joinsForward(type: JoiningType): boolean {\n    return type === 'D' || type === 'L' || type === 'C';\n}\n\n/** Whether the character after this one reaches back to touch it. */\nfunction joinsBackward(type: JoiningType): boolean {\n    return type === 'D' || type === 'R' || type === 'C';\n}\n\n/**\n * The shape a letter takes given what it can reach on either side.\n *\n * A dual-joining letter takes all four shapes, while one that joins on a single side only ever\n * stands alone or closes a word. A letter that never joins is left as it was written: it has one\n * shape, so naming it by a presentation form would say nothing the code point does not already say.\n */\nfunction formFor(type: JoiningType, joinedBefore: boolean, joinedAfter: boolean): Form | null {\n    if (type === 'D') {\n        if (joinedBefore && joinedAfter) return Form.Medial;\n        if (joinedBefore) return Form.Final;\n        if (joinedAfter) return Form.Initial;\n        return Form.Isolated;\n    }\n    if (type === 'R') return joinedBefore ? Form.Final : Form.Isolated;\n    if (type === 'L') return joinedAfter ? Form.Initial : Form.Isolated;\n    return null;\n}\n\n/** Splits text into characters, noting the joining type of each. */\nfunction toCharacters(text: string): ShapedCharacter[] {\n    return [...text].map(character => {\n        const codePoint = character.codePointAt(0);\n        return {codePoint, type: joiningType(codePoint), form: null};\n    });\n}\n\n/**\n * Works out the shape of every letter in the text.\n *\n * Transparent characters are looked straight through, so a letter joins to its neighbour across any\n * vowel points written between them.\n */\nfunction assignLetterForms(characters: ShapedCharacter[]): void {\n    const visible = characters.filter(character => character.type !== 'T');\n\n    for (let i = 0; i < visible.length; i++) {\n        const character = visible[i];\n        const joinedBefore = i > 0 && joinsForward(visible[i - 1].type);\n        const joinedAfter = i + 1 < visible.length && joinsBackward(visible[i + 1].type);\n        character.form = formFor(character.type, joinedBefore, joinedAfter);\n    }\n}\n\n/**\n * Gives each vowel point the shape it takes over the letter it is written on.\n *\n * A mark sits higher and narrower over a letter that carries on into the next one than it does over\n * one that ends a word, so it takes its shape from whether its letter joins forwards.\n */\nfunction assignMarkForms(characters: ShapedCharacter[]): void {\n    let letterJoinsForward = false;\n\n    for (const character of characters) {\n        if (character.type === 'T') {\n            character.form = letterJoinsForward ? Form.Medial : Form.Isolated;\n        } else {\n            letterJoinsForward = character.form === Form.Initial || character.form === Form.Medial;\n        }\n    }\n}\n\n/**\n * Replaces each lam followed by an alef with the single character the pair is written as.\n *\n * The ligature closes a word when the lam it was made from reached back to the letter before it, and\n * otherwise stands alone. Vowel points written between the two letters are kept, and follow the\n * ligature they belong to.\n */\nfunction applyLigatures(characters: ShapedCharacter[]): ShapedCharacter[] {\n    const result: ShapedCharacter[] = [];\n\n    for (let i = 0; i < characters.length; i++) {\n        const lam = characters[i];\n        if (lam.codePoint !== LAM) {\n            result.push(lam);\n            continue;\n        }\n\n        let next = i + 1;\n        while (next < characters.length && characters[next].type === 'T') next++;\n\n        const alef = characters[next];\n        const ligature = alef && LIGATURES[String.fromCodePoint(LAM, alef.codePoint)];\n        if (!ligature) {\n            result.push(lam);\n            continue;\n        }\n\n        const joinedBefore = lam.form === Form.Medial || lam.form === Form.Final;\n        result.push({codePoint: ligature[joinedBefore ? 1 : 0], type: 'R', form: Form.Isolated});\n        result.push(...characters.slice(i + 1, next));\n        i = next;\n    }\n\n    return result;\n}\n\n/**\n * The presentation form of this character, or the character itself where there is none to use.\n *\n * Not every shape exists to be asked for: a dammatan is only ever encoded as it looks on its own,\n * so a dammatan written over a joined letter falls back to that one shape rather than to the\n * unshaped mark, which is what the letters around it have already been shaped to expect.\n */\nfunction toPresentationForm(character: ShapedCharacter): number {\n    if (character.form === null) return character.codePoint;\n    const forms = PRESENTATION_FORMS[character.codePoint];\n    if (!forms) return character.codePoint;\n    return forms[character.form] || forms[Form.Isolated] || character.codePoint;\n}\n\n/**\n * Rewrites Arabic letters as the shape they take in the word they sit in.\n *\n * Arabic is cursive: a letter is written differently depending on whether the letters beside it\n * reach out to touch it. MapLibre draws one glyph at a time and asks for each by code point, so the\n * shape has to be chosen here and named by the Presentation Forms-B code point that stands for it.\n *\n * Text with no Arabic in it is returned unchanged.\n */\nexport function applyArabicShaping(text: string): string {\n    if (!ARABIC.test(text)) {\n        return text;\n    }\n\n    const characters = toCharacters(text);\n    assignLetterForms(characters);\n    assignMarkForms(characters);\n    return applyLigatures(characters)\n        .map(character => String.fromCodePoint(toPresentationForm(character)))\n        .join('');\n}\n", "import {rtlWorkerPlugin} from '../source/rtl_text_plugin_worker.ts';\nimport {applyArabicShaping} from './arabic_shaping.ts';\n\nimport type {Formatted} from '@maplibre/maplibre-gl-style-spec';\nimport type {SymbolStyleLayer} from '../style/style_layer/symbol_style_layer.ts';\nimport type {Feature} from '@maplibre/maplibre-gl-style-spec';\n\nfunction transformTextInternal(text: string, layer: SymbolStyleLayer, feature: Feature) {\n    const transform = layer.layout.get('text-transform').evaluate(feature, {});\n    if (transform === 'uppercase') {\n        text = text.toLocaleUpperCase();\n    } else if (transform === 'lowercase') {\n        text = text.toLocaleLowerCase();\n    }\n\n    return (rtlWorkerPlugin.applyArabicShaping ?? applyArabicShaping)(text);\n}\n\nexport function transformText(text: Formatted, layer: SymbolStyleLayer, feature: Feature): Formatted {\n    for (const section of text.sections) {\n        section.text = transformTextInternal(section.text, layer, feature);\n    }\n    return text;\n}\n", "import type Point from '@mapbox/point-geometry';\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket.ts';\n\ntype LineChunk = {\n    points: Point[];\n    next: LineChunk | null;\n};\n\ntype MergedLine = {\n    feature: SymbolFeature;\n    first: LineChunk;\n    last: LineChunk;\n};\n\nfunction getKey(text: string, line: MergedLine, onRight?: boolean) {\n    const points = onRight ? line.last.points : line.first.points;\n    const point = onRight ? points[points.length - 1] : points[0];\n    return `${text}:${point.x}:${point.y}`;\n}\n\nfunction joinChunks(line: MergedLine): Point[] {\n    const first = line.first.points;\n    let length = first.length;\n    for (let chunk = line.first.next; chunk; chunk = chunk.next) {\n        length += chunk.points.length - 1;\n    }\n\n    const points = new Array<Point>(length);\n    for (let i = 0; i < first.length; i++) {\n        points[i] = first[i];\n    }\n\n    let at = first.length;\n    for (let chunk = line.first.next; chunk; chunk = chunk.next) {\n        const from = chunk.points;\n        for (let i = 1; i < from.length; i++) {\n            points[at++] = from[i];\n        }\n    }\n    return points;\n}\n\nfunction mergeFromRight(merged: MergedLine[], rightIndex: Record<string, number>, leftKey: string, rightKey: string, line: MergedLine) {\n    const i = rightIndex[leftKey];\n    delete rightIndex[leftKey];\n    rightIndex[rightKey] = i;\n\n    const target = merged[i];\n    target.last.next = line.first;\n    target.last = line.last;\n    return i;\n}\n\nfunction mergeFromLeft(merged: MergedLine[], leftIndex: Record<string, number>, leftKey: string, rightKey: string, line: MergedLine) {\n    const i = leftIndex[rightKey];\n    delete leftIndex[rightKey];\n    leftIndex[leftKey] = i;\n\n    const target = merged[i];\n    line.last.next = target.first;\n    target.first = line.first;\n    return i;\n}\n\nexport function mergeLines(features: SymbolFeature[]): SymbolFeature[] {\n    const leftIndex: Record<string, number> = {};\n    const rightIndex: Record<string, number> = {};\n    const merged: MergedLine[] = [];\n\n    for (const feature of features) {\n        const text = feature.text ? feature.text.toString() : null;\n\n        const chunk: LineChunk = {points: feature.geometry[0], next: null};\n        const line: MergedLine = {feature, first: chunk, last: chunk};\n\n        if (!text) {\n            merged.push(line);\n            continue;\n        }\n\n        const leftKey = getKey(text, line),\n            rightKey = getKey(text, line, true);\n\n        if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) {\n            // found lines with the same text adjacent to both ends of the current line, merge all three\n            const j = mergeFromLeft(merged, leftIndex, leftKey, rightKey, line);\n            const i = mergeFromRight(merged, rightIndex, leftKey, rightKey, merged[j]);\n\n            delete leftIndex[leftKey];\n            delete rightIndex[rightKey];\n\n            rightIndex[getKey(text, merged[i], true)] = i;\n            merged[j].feature.geometry = null;\n\n        } else if (leftKey in rightIndex) {\n            // found mergeable line adjacent to the start of the current line, merge\n            mergeFromRight(merged, rightIndex, leftKey, rightKey, line);\n\n        } else if (rightKey in leftIndex) {\n            // found mergeable line adjacent to the end of the current line, merge\n            mergeFromLeft(merged, leftIndex, leftKey, rightKey, line);\n\n        } else {\n            // no adjacent lines, add as a new item\n            const i = merged.push(line) - 1;\n            leftIndex[leftKey] = i;\n            rightIndex[rightKey] = i;\n        }\n    }\n\n    const result: SymbolFeature[] = [];\n    for (const line of merged) {\n        const feature = line.feature;\n        if (!feature.geometry) continue;\n        if (line.first.next) feature.geometry[0] = joinChunks(line);\n        result.push(feature);\n    }\n    return result;\n}\n", "import {canCombineGraphemes, textCanContainGraphemeClusters} from './unicode_properties.g.ts';\n\nconst hasSegmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl;\n\n/**\n * Decides where the grapheme clusters are, corrected by {@link canCombineGraphemes} where CLDR's\n * cursor rules split a unit of writing. Built on first use: constructing the first `Intl.Segmenter`\n * initializes ICU, which costs several milliseconds that the main thread, which never shapes text,\n * should not pay at import.\n */\nlet graphemeSegmenter: Intl.Segmenter | undefined;\n\n/**\n * Decides where the words are, drawing on the browser's own dictionaries. Built on first use.\n */\nlet wordSegmenter: Intl.Segmenter | undefined;\n\n/**\n * Whether this environment can find grapheme clusters. Without it everything falls back to\n * codepoints, as MapLibre always did.\n */\nexport const supportsGraphemeSegmentation: boolean = hasSegmenter;\n\n/**\n * Splits text into grapheme clusters, or into codepoints where the environment cannot do better.\n *\n * A codepoint is not a unit of writing: `שְׁ` is a letter with two vowel points under it, which comes\n * apart when drawn a codepoint at a time and holds together when drawn as one cluster.\n *\n * Text holding none of the characters a cluster can be built from skips the segmenter, which costs\n * far more than the test that rules it out.\n */\nexport function toGraphemes(text: string): string[] {\n    if (!hasSegmenter || !textCanContainGraphemeClusters(text)) return [...text];\n\n    graphemeSegmenter ??= new Intl.Segmenter(undefined, {granularity: 'grapheme'});\n    const graphemes: string[] = [];\n    for (const {segment} of graphemeSegmenter.segment(text)) {\n        const last = graphemes.length - 1;\n        if (last >= 0 && canCombineGraphemes(graphemes[last], segment)) {\n            graphemes[last] += segment;\n        } else {\n            graphemes.push(segment);\n        }\n    }\n    return graphemes;\n}\n\n/**\n * The offsets, in UTF-16 code units, at which a word begins.\n *\n * Only scripts that do not space their words ask for these, having no punctuation to break a line\n * at. Without a segmenter, falls back to the boundaries a regular expression can find.\n */\nexport function wordBoundaries(text: string): Set<number> {\n    const boundaries = new Set<number>();\n\n    if (hasSegmenter) {\n        wordSegmenter ??= new Intl.Segmenter(undefined, {granularity: 'word'});\n        for (const {index} of wordSegmenter.segment(text)) {\n            boundaries.add(index);\n        }\n        return boundaries;\n    }\n\n    let index = 0;\n    for (const part of text.split(/\\b|(?=\\p{Ideo})/u)) {\n        boundaries.add(index);\n        index += part.length;\n    }\n    return boundaries;\n}\n\n/**\n * Whether a grapheme is more than one codepoint, and so has to be drawn as a whole.\n *\n * Written without allocating: this runs over every grapheme of every label.\n */\nexport function isCluster(grapheme: string): boolean {\n    const first = grapheme.codePointAt(0);\n    return grapheme.length > (first > 0xffff ? 2 : 1);\n}\n", "import {\n    codePointAllowsIdeographicBreaking,\n    codePointHasUprightVerticalOrientation,\n    codePointHasNeutralVerticalOrientation,\n    codePointIsInCursiveScript,\n    codePointIsInRTLScript\n} from '../util/unicode_properties.g.ts';\n\nexport function charIsWhitespace(char: number): boolean {\n    return /\\s/u.test(String.fromCodePoint(char));\n}\n\n/** Returns whether the codepoint is a punctuation or symbol character (`\\p{P}` or `\\p{S}`). */\nexport function charIsSymbolOrPunctuation(codePoint: number): boolean {\n    return /[\\p{P}\\p{S}]/u.test(String.fromCodePoint(codePoint));\n}\n\nexport function allowsIdeographicBreaking(chars: string): boolean {\n    for (const char of chars) {\n        if (!codePointAllowsIdeographicBreaking(char.codePointAt(0))) return false;\n    }\n    return true;\n}\n\nexport function allowsVerticalWritingMode(chars: string): boolean {\n    for (const char of chars) {\n        if (codePointHasUprightVerticalOrientation(char.codePointAt(0))) return true;\n    }\n    return false;\n}\n\nexport function allowsLetterSpacing(chars: string): boolean {\n    for (const char of chars) {\n        if (!charAllowsLetterSpacing(char.codePointAt(0))) return false;\n    }\n    return true;\n}\n\n/**\n * Whether the letters around this character can be spaced apart from it.\n *\n * A cursive script joins its letters up, so spacing them apart takes the word apart.\n */\nexport function charAllowsLetterSpacing(char: number): boolean {\n    return !codePointIsInCursiveScript(char);\n}\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * rotated orientation.\n *\n * A character has rotated orientation if it is drawn rotated when the line is\n * oriented vertically, even if both adjacent characters are upright. For\n * example, a Latin letter is drawn rotated along a vertical line. A rotated\n * character causes an adjacent “neutral” character to be drawn rotated as well.\n */\nexport function charHasRotatedVerticalOrientation(char: number): boolean {\n    return !(codePointHasUprightVerticalOrientation(char) ||\n             codePointHasNeutralVerticalOrientation(char));\n}\n\nexport function charInComplexShapingScript(char: number): boolean {\n    return /\\p{sc=Arab}/u.test(String.fromCodePoint(char));\n}\n\n/** Whether this character belongs to a script that is written horizontally from right to left. */\nexport function charInRTLScript(char: number): boolean {\n    return codePointIsInRTLScript(char);\n}\n\nexport function stringContainsRTLText(chars: string): boolean {\n    for (const char of chars) {\n        if (charInRTLScript(char.codePointAt(0))) {\n            return true;\n        }\n    }\n    return false;\n}\n", "import {charHasRotatedVerticalOrientation} from './script_detection.ts';\n\nexport const verticalizedCharacterMap = {\n    '!': '︕',\n    '#': '＃',\n    '$': '＄',\n    '%': '％',\n    '&': '＆',\n    '(': '︵',\n    ')': '︶',\n    '*': '＊',\n    '+': '＋',\n    ',': '︐',\n    '-': '︲',\n    '.': '・',\n    '/': '／',\n    ':': '︓',\n    ';': '︔',\n    '<': '︿',\n    '=': '＝',\n    '>': '﹀',\n    '?': '︖',\n    '@': '＠',\n    '[': '﹇',\n    '\\\\': '＼',\n    ']': '﹈',\n    '^': '＾',\n    '_': '︳',\n    '`': '｀',\n    '{': '︷',\n    '|': '―',\n    '}': '︸',\n    '~': '～',\n    '¢': '￠',\n    '£': '￡',\n    '¥': '￥',\n    '¦': '￤',\n    '¬': '￢',\n    '¯': '￣',\n    '–': '︲',\n    '—': '︱',\n    '‘': '﹃',\n    '’': '﹄',\n    '“': '﹁',\n    '”': '﹂',\n    '…': '︙',\n    '⋯': '︙',\n    '‧': '・',\n    '₩': '￦',\n    '、': '︑',\n    '。': '︒',\n    '〈': '︿',\n    '〉': '﹀',\n    '《': '︽',\n    '》': '︾',\n    '「': '﹁',\n    '」': '﹂',\n    '『': '﹃',\n    '』': '﹄',\n    '【': '︻',\n    '】': '︼',\n    '〔': '︹',\n    '〕': '︺',\n    '〖': '︗',\n    '〗': '︘',\n    '！': '︕',\n    '（': '︵',\n    '）': '︶',\n    '，': '︐',\n    '－': '︲',\n    '．': '・',\n    '：': '︓',\n    '；': '︔',\n    '＜': '︿',\n    '＞': '﹀',\n    '？': '︖',\n    '［': '﹇',\n    '］': '﹈',\n    '＿': '︳',\n    '｛': '︷',\n    '｜': '―',\n    '｝': '︸',\n    '｟': '︵',\n    '｠': '︶',\n    '｡': '︒',\n    '｢': '﹁',\n    '｣': '﹂'\n};\n\nexport function verticalizePunctuation(input: string): string {\n    let output = '';\n\n    let prevChar = {premature: true, value: undefined};\n    const chars = input[Symbol.iterator]();\n    let char = chars.next();\n    const nextChars = input[Symbol.iterator]();\n    nextChars.next();\n    let nextChar = nextChars.next();\n\n    while (!char.done) {\n        const canReplacePunctuation = (\n            (nextChar.done || !charHasRotatedVerticalOrientation(nextChar.value.codePointAt(0)) || verticalizedCharacterMap[nextChar.value]) &&\n            (prevChar.premature || !charHasRotatedVerticalOrientation(prevChar.value.codePointAt(0)) || verticalizedCharacterMap[prevChar.value])\n        );\n\n        if (canReplacePunctuation && verticalizedCharacterMap[char.value]) {\n            output += verticalizedCharacterMap[char.value];\n        } else {\n            output += char.value;\n        }\n\n        prevChar = {value: char.value, premature: false};\n        char = chars.next();\n        nextChar = nextChars.next();\n    }\n\n    return output;\n}\n\n", "\nimport ONE_EM from './one_em.ts';\nimport {verticalizePunctuation} from '../util/verticalize_punctuation.ts';\nimport {toGraphemes, wordBoundaries} from '../util/graphemes.ts';\nimport {charIsWhitespace} from '../util/script_detection.ts';\nimport {codePointAllowsIdeographicBreaking, codePointIsWrittenWithoutSpaces} from '../util/unicode_properties.g.ts';\nimport {warnOnce} from '../util/util.ts';\n\nimport type {GlyphMap} from '../style/style_glyph.ts';\nimport type {ImagePosition} from '../render/image_atlas.ts';\nimport type {Formatted, FormattedSection, VerticalAlign} from '@maplibre/maplibre-gl-style-spec';\n\nexport type TextSectionOptions = {\n    scale: number;\n    verticalAlign: VerticalAlign;\n    fontStack: string;\n};\n\nexport type ImageSectionOptions = {\n    scale: number;\n    verticalAlign: VerticalAlign;\n    imageName: string;\n};\n\nexport type SectionOptions = TextSectionOptions | ImageSectionOptions;\n\n// Max number of images in label is 6401 U+E000–U+F8FF that covers\n// Basic Multilingual Plane Unicode Private Use Area (PUA).\nconst PUAbegin = 0xE000;\nconst PUAend = 0xF8FF;\n\ntype Break = {\n    index: number;\n    x: number;\n    priorBreak: Break;\n    badness: number;\n};\n\n// using computed properties due to https://github.com/facebook/flow/issues/380\n/* eslint no-useless-computed-key: 0 */\n\n/**\n * Characters a line may end on.\n */\nconst breakable: Record<number, boolean> = {\n    [0x0a]: true, // newline\n    [0x0d]: true, // carriage return, on its own or starting a CRLF cluster\n    [0x20]: true, // space\n    [0x26]: true, // ampersand\n    [0x29]: true, // right parenthesis\n    [0x2b]: true, // plus sign\n    [0x2d]: true, // hyphen-minus\n    [0x2f]: true, // solidus\n    [0xad]: true, // soft hyphen\n    [0xb7]: true, // middle dot\n    [0x200b]: true, // zero-width space\n    [0x2010]: true, // hyphen\n    [0x2013]: true, // en dash\n    [0x2027]: true  // interpunct\n    // Many other characters may be reasonable breakpoints\n    // Consider \"neutral orientation\" characters in codePointHasNeutralVerticalOrientation in unicode_properties\n    // See https://github.com/mapbox/mapbox-gl-js/issues/3658\n};\n\n/**\n * Characters a line may begin with, whatever precedes them.\n */\nconst breakableBefore: Record<number, boolean> = {\n    [0x28]: true, // left parenthesis\n};\n\n/**\n * Returns how far a grapheme cluster advances the pen, including any letter spacing after it.\n *\n * Where a font file covers the cluster it advances as the one shape it is drawn as. Where none does\n * it is drawn a codepoint at a time, and has to be measured the same way. See `shapeLines`.\n */\nfunction getGlyphAdvance(\n    grapheme: string,\n    section: SectionOptions,\n    glyphMap: GlyphMap,\n    imagePositions: Record<string, ImagePosition>,\n    spacing: number,\n    layoutTextSize: number\n): number {\n    if ('fontStack' in section) {\n        const positions = glyphMap[section.fontStack]?.default;\n        const glyph = positions?.[grapheme];\n        if (glyph) return glyph.metrics.advance * section.scale + spacing;\n\n        let advance = 0;\n        for (const char of grapheme) {\n            const fallback = positions?.[char];\n            if (fallback) advance += fallback.metrics.advance * section.scale + spacing;\n        }\n        return advance;\n    } else {\n        const imagePosition = imagePositions[section.imageName];\n        if (!imagePosition) return 0;\n        return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing;\n    }\n}\n\nfunction calculateBadness(lineWidth: number,\n    targetWidth: number,\n    penalty: number,\n    isLastBreak: boolean) {\n    const raggedness = Math.pow(lineWidth - targetWidth, 2);\n    if (isLastBreak) {\n        // Favor finals lines shorter than average over longer than average\n        if (lineWidth < targetWidth) {\n            return raggedness / 2;\n        } else {\n            return raggedness * 2;\n        }\n    }\n\n    return raggedness + Math.abs(penalty) * penalty;\n}\n\n/**\n * Whether a grapheme cluster is entirely whitespace, and so can be trimmed off the end of a line.\n */\nfunction isWhitespaceGrapheme(grapheme: string): boolean {\n    return /^\\s+$/u.test(grapheme);\n}\n\n/**\n * Scores a candidate break, lower being better: a newline is one the text asked for, an opening\n * bracket left at the end of a line is merely allowed.\n *\n * `codePoint` and `nextCodePoint` are the first codepoints of the clusters either side, which is\n * what decides how a cluster breaks -- a CRLF is one cluster, so a newline is seen as its CR.\n *\n * @param penalizableIdeographicBreak - whether this falls between ideographs in text that also\n * carries zero-width space hints, which are the better places to break\n */\nfunction calculatePenalty(codePoint: number, nextCodePoint: number, penalizableIdeographicBreak: boolean) {\n    let penalty = 0;\n    if (codePoint === 0x0a || codePoint === 0x0d) {\n        penalty -= 10000;\n    }\n    if (penalizableIdeographicBreak) {\n        penalty += 150;\n    }\n    if (codePoint === 0x28 || codePoint === 0xff08) {\n        penalty += 50;\n    }\n    if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) {\n        penalty += 50;\n    }\n    return penalty;\n}\n\nfunction evaluateBreak(\n    breakIndex: number,\n    breakX: number,\n    targetWidth: number,\n    potentialBreaks: Break[],\n    penalty: number,\n    isLastBreak: boolean\n): Break {\n    // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth\n    //  ...but in fact we allow lines longer than maxWidth (if there's no break points)\n    //  ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give\n    //     more lopsided results.\n\n    let bestPriorBreak: Break = null;\n    let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak);\n\n    for (const potentialBreak of potentialBreaks) {\n        const lineWidth = breakX - potentialBreak.x;\n        const breakBadness =\n            calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness;\n        if (breakBadness <= bestBreakBadness) {\n            bestPriorBreak = potentialBreak;\n            bestBreakBadness = breakBadness;\n        }\n    }\n\n    return {\n        index: breakIndex,\n        x: breakX,\n        priorBreak: bestPriorBreak,\n        badness: bestBreakBadness\n    };\n}\n\nfunction leastBadBreaks(lastLineBreak?: Break | null): number[] {\n    if (!lastLineBreak) {\n        return [];\n    }\n    return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index);\n}\n\nexport class TaggedString {\n    text: string;\n    sections: SectionOptions[];\n    /** Maps each grapheme cluster in `text` to its corresponding entry in `sections`. */\n    sectionIndex: number[];\n    imageSectionID: number | null;\n    /**\n     * `text` split into the units it is laid out in. Derived from `text`, so anything that changes\n     * `text` clears it.\n     */\n    cachedGraphemes: string[] | null;\n\n    constructor(text: string = '', sections: SectionOptions[] = [], sectionIndex: number[] = []) {\n        this.text = text;\n        this.sections = sections;\n        this.sectionIndex = sectionIndex;\n        this.imageSectionID = null;\n        this.cachedGraphemes = null;\n    }\n\n    /**\n     * The units this text is laid out in: grapheme clusters, so that a letter and the marks that\n     * belong to it stay together.\n     */\n    graphemes(): string[] {\n        this.cachedGraphemes ??= toGraphemes(this.text);\n        return this.cachedGraphemes;\n    }\n\n    /** Creates tagged text, applying vertical punctuation when requested. */\n    static fromFeature(text: Formatted, defaultFontStack: string, vertical: boolean, glyphMap?: GlyphMap): TaggedString {\n        const result = new TaggedString();\n        for (const section of text.sections) {\n            if (!section.image) {\n                result.addTextSection(section, defaultFontStack);\n            } else {\n                result.addImageSection(section);\n            }\n        }\n        if (vertical) result.verticalizePunctuation(glyphMap);\n        return result;\n    }\n\n    length(): number {\n        return this.graphemes().length;\n    }\n\n    getSection(index: number): SectionOptions {\n        return this.sections[this.sectionIndex[index]];\n    }\n\n    getSectionIndex(index: number): number {\n        return this.sectionIndex[index];\n    }\n\n    /**\n     * Uses compatibility punctuation where a font's vertical form is unavailable or unused, preserving\n     * UTF-16 length, keeping whole-text context, cluster boundaries and section indices intact.\n     *\n     * @param glyphMap - glyph variants used to check for font-provided vertical forms\n     * @param verticals - resolved orientations, if available; only upright glyphs use font alternates\n     */\n    verticalizePunctuation(glyphMap: GlyphMap = {}, verticals?: boolean[]): void {\n        const replacements = verticalizePunctuation(this.text);\n        let offset = 0;\n        this.cachedGraphemes = this.graphemes().map((grapheme, index) => {\n            const replacement = replacements.slice(offset, offset + grapheme.length);\n            offset += grapheme.length;\n            const section = this.getSection(index);\n            return verticals?.[index] !== false && 'fontStack' in section && glyphMap[section.fontStack]?.vertical?.[grapheme] ?\n                grapheme : replacement;\n        });\n        this.text = this.cachedGraphemes.join('');\n    }\n\n    /**\n     * Returns whether the text contains zero-width spaces.\n     *\n     * Some tilesets such as Streets insert ZWSPs as hints for line\n     * breaking in CJK text.\n     */\n    hasZeroWidthSpaces(): boolean {\n        return this.text.includes('\\u200b');\n    }\n\n    /**\n     * Drops the whitespace at each end of the line.\n     *\n     * Counted in clusters, which is what `sectionIndex` is indexed by: a CRLF is one cluster of two\n     * code units, so counting code units would leave the sections short of the text.\n     */\n    trim(): void {\n        const graphemes = this.graphemes();\n        let start = 0;\n        while (start < graphemes.length && isWhitespaceGrapheme(graphemes[start])) start++;\n        let end = graphemes.length;\n        while (end > start && isWhitespaceGrapheme(graphemes[end - 1])) end--;\n\n        this.text = graphemes.slice(start, end).join('');\n        this.sectionIndex = this.sectionIndex.slice(start, end);\n        this.cachedGraphemes = null;\n    }\n\n    substring(start: number, end: number): TaggedString {\n        const text = this.graphemes().slice(start, end).join('');\n        const sectionIndex = this.sectionIndex.slice(start, end);\n        return new TaggedString(text, this.sections, sectionIndex);\n    }\n\n    /**\n     * Converts a grapheme cluster index to a UTF-16 code unit (JavaScript character index).\n     */\n    toCodeUnitIndex(graphemeIndex: number): number {\n        return this.graphemes().slice(0, graphemeIndex).join('').length;\n    }\n\n    toString(): string {\n        return this.text;\n    }\n\n    getMaxScale(): number {\n        return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0);\n    }\n\n    getMaxImageSize(imagePositions: Record<string, ImagePosition>): {\n        maxImageWidth: number;\n        maxImageHeight: number;\n    } {\n        let maxImageWidth = 0;\n        let maxImageHeight = 0;\n        for (let i = 0; i < this.length(); i++) {\n            const section = this.getSection(i);\n            if ('imageName' in section) {\n                const imagePosition = imagePositions[section.imageName];\n                if (!imagePosition) continue;\n                const size = imagePosition.displaySize;\n                maxImageWidth = Math.max(maxImageWidth, size[0]);\n                maxImageHeight = Math.max(maxImageHeight, size[1]);\n            }\n        }\n        return {maxImageWidth, maxImageHeight};\n    }\n\n    /**\n     * Appends one section's text, recording which section each cluster it adds belongs to.\n     *\n     * A cluster belongs to the section its first character came from, so a section that only joins\n     * the cluster before it -- an accent given its own formatting -- adds none of its own. Only the\n     * last cluster and the new text are segmented, not the label from the start.\n     */\n    _appendSection(text: string, sectionIndex: number): void {\n        const graphemes = this.graphemes();\n        const tail = graphemes.length > 0 ? graphemes[graphemes.length - 1] : '';\n        const joined = toGraphemes(tail + text);\n\n        this.text += text;\n        this.cachedGraphemes = graphemes.slice(0, tail ? -1 : undefined).concat(joined);\n\n        const added = joined.length - (tail ? 1 : 0);\n        for (let i = 0; i < added; i++) {\n            this.sectionIndex.push(sectionIndex);\n        }\n    }\n\n    addTextSection(section: FormattedSection, defaultFontStack: string): void {\n        this.sections.push({\n            scale: section.scale || 1,\n            verticalAlign: section.verticalAlign || 'bottom',\n            fontStack: section.fontStack || defaultFontStack,\n        });\n        this._appendSection(section.text, this.sections.length - 1);\n    }\n\n    addImageSection(section: FormattedSection): void {\n        const imageName = section.image ? section.image.name : '';\n        if (imageName.length === 0) {\n            warnOnce('Can\\'t add FormattedSection with an empty image.');\n            return;\n        }\n\n        const nextImageSectionCharCode = this.getNextImageSectionCharCode();\n        if (!nextImageSectionCharCode) {\n            warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`);\n            return;\n        }\n\n        this.sections.push({\n            scale: 1,\n            verticalAlign: section.verticalAlign || 'bottom',\n            imageName,\n        });\n        this._appendSection(String.fromCharCode(nextImageSectionCharCode), this.sections.length - 1);\n    }\n\n    getNextImageSectionCharCode(): number | null {\n        if (!this.imageSectionID) {\n            this.imageSectionID = PUAbegin;\n            return this.imageSectionID;\n        }\n\n        if (this.imageSectionID >= PUAend) return null;\n        return ++this.imageSectionID;\n    }\n\n    /**\n     * Returns the cluster indices to break at for lines of roughly `maxWidth`, weighing each\n     * candidate by how ragged it leaves the line.\n     *\n     * Breaks fall between clusters, never inside one, at a character or image a line may end on --\n     * plus, in scripts that do not space their words and so offer no such character, wherever the\n     * word segmenter finds a word. It is not consulted elsewhere, isolating a comma as a word of its\n     * own, nor until such a script turns up, costing more than the rest of this put together.\n     *\n     * Text that fits on one line is left unbroken without weighing any break, unless it asks for a\n     * newline, has no width (which ties with every break) or uses negative spacing (which can make\n     * spaces advance backwards).\n     */\n    determineLineBreaks(\n        spacing: number,\n        maxWidth: number,\n        glyphMap: GlyphMap,\n        imagePositions: Record<string, ImagePosition>,\n        layoutTextSize: number\n    ): number[] {\n        const totalWidth = this.determineTotalWidth(spacing, glyphMap, imagePositions, layoutTextSize);\n        if (spacing >= 0 && totalWidth > 0 && totalWidth <= maxWidth && !/[\\n\\r]/.test(this.text)) {\n            return [this.length()];\n        }\n\n        const potentialLineBreaks = [];\n        const targetWidth = totalWidth / Math.max(1, Math.ceil(totalWidth / maxWidth));\n\n        const hasZeroWidthSpaces = this.hasZeroWidthSpaces();\n\n        const graphemes = this.graphemes();\n        let wordStarts: Set<number> | null = null;\n\n        let currentX = 0;\n        let codeUnit = 0;\n\n        for (let i = 0; i < graphemes.length; i++) {\n            const grapheme = graphemes[i];\n\n            if (i > 0) {\n                const previousCodePoint = graphemes[i - 1].codePointAt(0);\n                const codePoint = grapheme.codePointAt(0);\n                const ideographicBreak = codePointAllowsIdeographicBreaking(previousCodePoint);\n                const withinAWordlessScript = codePointIsWrittenWithoutSpaces(previousCodePoint) &&\n                    codePointIsWrittenWithoutSpaces(codePoint);\n\n                if (breakable[previousCodePoint] ||\n                    ideographicBreak ||\n                    'imageName' in this.getSection(i - 1) ||\n                    (graphemes[i + 1] !== undefined && breakableBefore[codePoint]) ||\n                    (withinAWordlessScript && (wordStarts ??= wordBoundaries(this.text)).has(codeUnit))) {\n                    potentialLineBreaks.push(\n                        evaluateBreak(\n                            i,\n                            currentX,\n                            targetWidth,\n                            potentialLineBreaks,\n                            calculatePenalty(previousCodePoint, codePoint, ideographicBreak && hasZeroWidthSpaces),\n                            false));\n                }\n            }\n\n            const codePoint = grapheme.codePointAt(0);\n            if (!charIsWhitespace(codePoint)) {\n                currentX += getGlyphAdvance(grapheme, this.getSection(i), glyphMap, imagePositions, spacing, layoutTextSize);\n            }\n            codeUnit += grapheme.length;\n        }\n\n        return leastBadBreaks(\n            evaluateBreak(\n                this.length(),\n                currentX,\n                targetWidth,\n                potentialLineBreaks,\n                0,\n                true));\n    }\n\n    determineTotalWidth(\n        spacing: number,\n        glyphMap: GlyphMap,\n        imagePositions: Record<string, ImagePosition>,\n        layoutTextSize: number): number {\n        let totalWidth = 0;\n\n        let index = 0;\n        for (const grapheme of this.graphemes()) {\n            const section = this.getSection(index);\n            totalWidth += getGlyphAdvance(grapheme, section, glyphMap, imagePositions, spacing, layoutTextSize);\n            index++;\n        }\n\n        return totalWidth;\n    }\n}\n", "function bidiFactory() {\nvar bidi = (function (exports) {\n\n  // Bidi character types data, auto generated\n  var DATA = {\n    \"R\": \"13k,1a,2,3,3,2+1j,ch+16,a+1,5+2,2+n,5,a,4,6+16,4+3,h+1b,4mo,179q,2+9,2+11,2i9+7y,2+68,4,3+4,5+13,4+3,2+4k,3+29,8+cf,1t+7z,w+17,3+3m,1t+3z,16o1+5r,8+30,8+mc,29+1r,29+4v,75+73\",\n    \"EN\": \"1c+9,3d+1,6,187+9,513,4+5,7+9,sf+j,175h+9,qw+q,161f+1d,4xt+a,25i+9\",\n    \"ES\": \"17,2,6dp+1,f+1,av,16vr,mx+1,4o,2\",\n    \"ET\": \"z+2,3h+3,b+1,ym,3e+1,2o,p4+1,8,6u,7c,g6,1wc,1n9+4,30+1b,2n,6d,qhx+1,h0m,a+1,49+2,63+1,4+1,6bb+3,12jj\",\n    \"AN\": \"16o+5,2j+9,2+1,35,ed,1ff2+9,87+u\",\n    \"CS\": \"18,2+1,b,2u,12k,55v,l,17v0,2,3,53,2+1,b\",\n    \"B\": \"a,3,f+2,2v,690\",\n    \"S\": \"9,2,k\",\n    \"WS\": \"c,k,4f4,1vk+a,u,1j,335\",\n    \"ON\": \"x+1,4+4,h+5,r+5,r+3,z,5+3,2+1,2+1,5,2+2,3+4,o,w,ci+1,8+d,3+d,6+8,2+g,39+1,9,6+1,2,33,b8,3+1,3c+1,7+1,5r,b,7h+3,sa+5,2,3i+6,jg+3,ur+9,2v,ij+1,9g+9,7+a,8m,4+1,49+x,14u,2+2,c+2,e+2,e+2,e+1,i+n,e+e,2+p,u+2,e+2,36+1,2+3,2+1,b,2+2,6+5,2,2,2,h+1,5+4,6+3,3+f,16+2,5+3l,3+81,1y+p,2+40,q+a,m+13,2r+ch,2+9e,75+hf,3+v,2+2w,6e+5,f+6,75+2a,1a+p,2+2g,d+5x,r+b,6+3,4+o,g,6+1,6+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\"FSI\": \"6eg\",\n    \"PDI\": \"6eh\"\n  };\n\n  var TYPES = {};\n  var TYPES_TO_NAMES = {};\n  TYPES.L = 1; //L is the default\n  TYPES_TO_NAMES[1] = 'L';\n  Object.keys(DATA).forEach(function (type, i) {\n    TYPES[type] = 1 << (i + 1);\n    TYPES_TO_NAMES[TYPES[type]] = type;\n  });\n  Object.freeze(TYPES);\n\n  var ISOLATE_INIT_TYPES = TYPES.LRI | TYPES.RLI | TYPES.FSI;\n  var STRONG_TYPES = TYPES.L | TYPES.R | TYPES.AL;\n  var NEUTRAL_ISOLATE_TYPES = TYPES.B | TYPES.S | TYPES.WS | TYPES.ON | TYPES.FSI | TYPES.LRI | TYPES.RLI | TYPES.PDI;\n  var BN_LIKE_TYPES = TYPES.BN | TYPES.RLE | TYPES.LRE | TYPES.RLO | TYPES.LRO | TYPES.PDF;\n  var TRAILING_TYPES = TYPES.S | TYPES.WS | TYPES.B | ISOLATE_INIT_TYPES | TYPES.PDI | BN_LIKE_TYPES;\n\n  var map = null;\n\n  function parseData () {\n    if (!map) {\n      //const start = performance.now()\n      map = new Map();\n      var start = 0;\n      for (var type in DATA) {\n        if (DATA.hasOwnProperty(type)) {\n          var segments = DATA[type];\n          var temp = '';\n          var end = (void 0);\n          var state = false;\n          var lastCode = 0;\n          for (var i = 0; i <= segments.length + 1; i += 1) {\n            var char = segments[i];\n            if (char !== ',' && i !== segments.length) {\n              if (char === '+') {\n                state = true;\n                lastCode = start = lastCode + parseInt(temp, 36);\n                temp = '';\n              } else {\n                temp += char;\n              }\n            } else {\n              if (!state) {\n                lastCode = start = lastCode + parseInt(temp, 36);\n                end = start;\n              } else {\n                end = start + parseInt(temp, 36);\n              }\n              state = false;\n              temp = '';\n              lastCode = end;\n              for (var j = start; j < end + 1; j += 1) {\n                map.set(j, TYPES[type]);\n              }\n            }\n          }\n        }\n      }\n      //console.log(`char types parsed in ${performance.now() - start}ms`)\n    }\n  }\n\n  /**\n   * @param {string} char\n   * @return {number}\n   */\n  function getBidiCharType (char) {\n    parseData();\n    return map.get(char.codePointAt(0)) || TYPES.L\n  }\n\n  /**\n   * Get Bidi Character Type Name\n   * @param {string} char\n   * @returns { \"L\" | \"R\" | \"EN\" | \"ES\" | \"ET\" | \"AN\" | \"CS\" | \"B\" | \"S\" | \"WS\" | \"ON\" | \"BN\" | \"NSM\" | \"AL\" | \"LRO\" | \"RLO\" | \"LRE\" | \"RLE\" | \"PDF\" | \"LRI\" | \"RLI\" | \"FSI\" | \"PDI\" }\n   */\n  function getBidiCharTypeName(char) {\n    return TYPES_TO_NAMES[getBidiCharType(char)]\n  }\n\n  // Bidi bracket pairs data, auto generated\n  var data$1 = {\n    \"pairs\": \"14>1,1e>2,u>2,2wt>1,1>1,1ge>1,1wp>1,1j>1,f>1,hm>1,1>1,u>1,u6>1,1>1,+5,28>1,w>1,1>1,+3,b8>1,1>1,+3,1>3,-1>-1,3>1,1>1,+2,1s>1,1>1,x>1,th>1,1>1,+2,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,4q>1,1e>2,u>2,2>1,+1\",\n    \"canonical\": \"6f1>-6dx,6dy>-6dx,6ec>-6ed,6ee>-6ed,6ww>2jj,-2ji>2jj,14r4>-1e7l,1e7m>-1e7l,1e7m>-1e5c,1e5d>-1e5b,1e5c>-14qx,14qy>-14qx,14vn>-1ecg,1ech>-1ecg,1edu>-1ecg,1eci>-1ecg,1eda>-1ecg,1eci>-1ecg,1eci>-168q,168r>-168q,168s>-14ye,14yf>-14ye\"\n  };\n\n  /**\n   * Parses an string that holds encoded codepoint mappings, e.g. for bracket pairs or\n   * mirroring characters, as encoded by scripts/generateBidiData.js. Returns an object\n   * holding the `map`, and optionally a `reverseMap` if `includeReverse:true`.\n   * @param {string} encodedString\n   * @param {boolean} includeReverse - true if you want reverseMap in the output\n   * @return {{map: Map<number, number>, reverseMap?: Map<number, number>}}\n   */\n  function parseCharacterMap (encodedString, includeReverse) {\n    var radix = 36;\n    var lastCode = 0;\n    var map = new Map();\n    var reverseMap = includeReverse && new Map();\n    var prevPair;\n    encodedString.split(',').forEach(function visit(entry) {\n      if (entry.indexOf('+') !== -1) {\n        for (var i = +entry; i--;) {\n          visit(prevPair);\n        }\n      } else {\n        prevPair = entry;\n        var ref = entry.split('>');\n        var a = ref[0];\n        var b = ref[1];\n        a = String.fromCodePoint(lastCode += parseInt(a, radix));\n        b = String.fromCodePoint(lastCode += parseInt(b, radix));\n        map.set(a, b);\n        includeReverse && reverseMap.set(b, a);\n      }\n    });\n    return { map: map, reverseMap: reverseMap }\n  }\n\n  var openToClose, closeToOpen, canonical;\n\n  function parse$1 () {\n    if (!openToClose) {\n      //const start = performance.now()\n      var ref = parseCharacterMap(data$1.pairs, true);\n      var map = ref.map;\n      var reverseMap = ref.reverseMap;\n      openToClose = map;\n      closeToOpen = reverseMap;\n      canonical = parseCharacterMap(data$1.canonical, false).map;\n      //console.log(`brackets parsed in ${performance.now() - start}ms`)\n    }\n  }\n\n  /**\n   * Get the opening bracket character corresponding to a given closing bracket character.\n   * @param {string} char\n   * @returns {string | null}\n   */\n  function openingToClosingBracket (char) {\n    parse$1();\n    return openToClose.get(char) || null\n  }\n\n  /**\n   * Get the closing bracket character corresponding to a given opening bracket character.\n   * @param {string} char\n   * @returns {string | null}\n   */\n  function closingToOpeningBracket (char) {\n    parse$1();\n    return closeToOpen.get(char) || null\n  }\n\n  /**\n   * Retrieves the canonical form of a bracket character.\n   * @param {string} char\n   * @returns {string | null}\n   */\n  function getCanonicalBracket (char) {\n    parse$1();\n    return canonical.get(char) || null\n  }\n\n  // Local type aliases\n  var TYPE_L = TYPES.L;\n  var TYPE_R = TYPES.R;\n  var TYPE_EN = TYPES.EN;\n  var TYPE_ES = TYPES.ES;\n  var TYPE_ET = TYPES.ET;\n  var TYPE_AN = TYPES.AN;\n  var TYPE_CS = TYPES.CS;\n  var TYPE_B = TYPES.B;\n  var TYPE_S = TYPES.S;\n  var TYPE_ON = TYPES.ON;\n  var TYPE_BN = TYPES.BN;\n  var TYPE_NSM = TYPES.NSM;\n  var TYPE_AL = TYPES.AL;\n  var TYPE_LRO = TYPES.LRO;\n  var TYPE_RLO = TYPES.RLO;\n  var TYPE_LRE = TYPES.LRE;\n  var TYPE_RLE = TYPES.RLE;\n  var TYPE_PDF = TYPES.PDF;\n  var TYPE_LRI = TYPES.LRI;\n  var TYPE_RLI = TYPES.RLI;\n  var TYPE_FSI = TYPES.FSI;\n  var TYPE_PDI = TYPES.PDI;\n\n  /**\n   * @typedef {object} GetEmbeddingLevelsResult\n   * @property {{start: number, end: number, level: number}[]} paragraphs\n   * @property {Uint8Array} levels\n   */\n\n  /**\n   * This function applies the Bidirectional Algorithm to a string, returning the resolved embedding levels\n   * in a single Uint8Array plus a list of objects holding each paragraph's start and end indices and resolved\n   * base embedding level.\n   *\n   * @param {string} string - The input string\n   * @param {\"ltr\"|\"rtl\"|\"auto\"} [baseDirection] - Use \"ltr\" or \"rtl\" to force a base paragraph direction,\n   *        otherwise a direction will be chosen automatically from each paragraph's contents.\n   * @return {GetEmbeddingLevelsResult}\n   */\n  function getEmbeddingLevels (string, baseDirection) {\n    var MAX_DEPTH = 125;\n\n    // Start by mapping all characters to their unicode type, as a bitmask integer\n    var charTypes = new Uint32Array(string.length);\n    for (var i = 0; i < string.length; i++) {\n      charTypes[i] = getBidiCharType(string[i]);\n    }\n\n    var charTypeCounts = new Map(); //will be cleared at start of each paragraph\n    function changeCharType(i, type) {\n      var oldType = charTypes[i];\n      charTypes[i] = type;\n      charTypeCounts.set(oldType, charTypeCounts.get(oldType) - 1);\n      if (oldType & NEUTRAL_ISOLATE_TYPES) {\n        charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) - 1);\n      }\n      charTypeCounts.set(type, (charTypeCounts.get(type) || 0) + 1);\n      if (type & NEUTRAL_ISOLATE_TYPES) {\n        charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1);\n      }\n    }\n\n    var embedLevels = new Uint8Array(string.length);\n    var isolationPairs = new Map(); //init->pdi and pdi->init\n\n    // === 3.3.1 The Paragraph Level ===\n    // 3.3.1 P1: Split the text into paragraphs\n    var paragraphs = []; // [{start, end, level}, ...]\n    var paragraph = null;\n    for (var i$1 = 0; i$1 < string.length; i$1++) {\n      if (!paragraph) {\n        paragraphs.push(paragraph = {\n          start: i$1,\n          end: string.length - 1,\n          // 3.3.1 P2-P3: Determine the paragraph level\n          level: baseDirection === 'rtl' ? 1 : baseDirection === 'ltr' ? 0 : determineAutoEmbedLevel(i$1, false)\n        });\n      }\n      if (charTypes[i$1] & TYPE_B) {\n        paragraph.end = i$1;\n        paragraph = null;\n      }\n    }\n\n    var FORMATTING_TYPES = TYPE_RLE | TYPE_LRE | TYPE_RLO | TYPE_LRO | ISOLATE_INIT_TYPES | TYPE_PDI | TYPE_PDF | TYPE_B;\n    var nextEven = function (n) { return n + ((n & 1) ? 1 : 2); };\n    var nextOdd = function (n) { return n + ((n & 1) ? 2 : 1); };\n\n    // Everything from here on will operate per paragraph.\n    for (var paraIdx = 0; paraIdx < paragraphs.length; paraIdx++) {\n      paragraph = paragraphs[paraIdx];\n      var statusStack = [{\n        _level: paragraph.level,\n        _override: 0, //0=neutral, 1=L, 2=R\n        _isolate: 0 //bool\n      }];\n      var stackTop = (void 0);\n      var overflowIsolateCount = 0;\n      var overflowEmbeddingCount = 0;\n      var validIsolateCount = 0;\n      charTypeCounts.clear();\n\n      // === 3.3.2 Explicit Levels and Directions ===\n      for (var i$2 = paragraph.start; i$2 <= paragraph.end; i$2++) {\n        var charType = charTypes[i$2];\n        stackTop = statusStack[statusStack.length - 1];\n\n        // Set initial counts\n        charTypeCounts.set(charType, (charTypeCounts.get(charType) || 0) + 1);\n        if (charType & NEUTRAL_ISOLATE_TYPES) {\n          charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1);\n        }\n\n        // Explicit Embeddings: 3.3.2 X2 - X3\n        if (charType & FORMATTING_TYPES) { //prefilter all formatters\n          if (charType & (TYPE_RLE | TYPE_LRE)) {\n            embedLevels[i$2] = stackTop._level; // 5.2\n            var level = (charType === TYPE_RLE ? nextOdd : nextEven)(stackTop._level);\n            if (level <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) {\n              statusStack.push({\n                _level: level,\n                _override: 0,\n                _isolate: 0\n              });\n            } else if (!overflowIsolateCount) {\n              overflowEmbeddingCount++;\n            }\n          }\n\n          // Explicit Overrides: 3.3.2 X4 - X5\n          else if (charType & (TYPE_RLO | TYPE_LRO)) {\n            embedLevels[i$2] = stackTop._level; // 5.2\n            var level$1 = (charType === TYPE_RLO ? nextOdd : nextEven)(stackTop._level);\n            if (level$1 <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) {\n              statusStack.push({\n                _level: level$1,\n                _override: (charType & TYPE_RLO) ? TYPE_R : TYPE_L,\n                _isolate: 0\n              });\n            } else if (!overflowIsolateCount) {\n              overflowEmbeddingCount++;\n            }\n          }\n\n          // Isolates: 3.3.2 X5a - X5c\n          else if (charType & ISOLATE_INIT_TYPES) {\n            // X5c - FSI becomes either RLI or LRI\n            if (charType & TYPE_FSI) {\n              charType = determineAutoEmbedLevel(i$2 + 1, true) === 1 ? TYPE_RLI : TYPE_LRI;\n            }\n\n            embedLevels[i$2] = stackTop._level;\n            if (stackTop._override) {\n              changeCharType(i$2, stackTop._override);\n            }\n            var level$2 = (charType === TYPE_RLI ? nextOdd : nextEven)(stackTop._level);\n            if (level$2 <= MAX_DEPTH && overflowIsolateCount === 0 && overflowEmbeddingCount === 0) {\n              validIsolateCount++;\n              statusStack.push({\n                _level: level$2,\n                _override: 0,\n                _isolate: 1,\n                _isolInitIndex: i$2\n              });\n            } else {\n              overflowIsolateCount++;\n            }\n          }\n\n          // Terminating Isolates: 3.3.2 X6a\n          else if (charType & TYPE_PDI) {\n            if (overflowIsolateCount > 0) {\n              overflowIsolateCount--;\n            } else if (validIsolateCount > 0) {\n              overflowEmbeddingCount = 0;\n              while (!statusStack[statusStack.length - 1]._isolate) {\n                statusStack.pop();\n              }\n              // Add to isolation pairs bidirectional mapping:\n              var isolInitIndex = statusStack[statusStack.length - 1]._isolInitIndex;\n              if (isolInitIndex != null) {\n                isolationPairs.set(isolInitIndex, i$2);\n                isolationPairs.set(i$2, isolInitIndex);\n              }\n              statusStack.pop();\n              validIsolateCount--;\n            }\n            stackTop = statusStack[statusStack.length - 1];\n            embedLevels[i$2] = stackTop._level;\n            if (stackTop._override) {\n              changeCharType(i$2, stackTop._override);\n            }\n          }\n\n\n          // Terminating Embeddings and Overrides: 3.3.2 X7\n          else if (charType & TYPE_PDF) {\n            if (overflowIsolateCount === 0) {\n              if (overflowEmbeddingCount > 0) {\n                overflowEmbeddingCount--;\n              } else if (!stackTop._isolate && statusStack.length > 1) {\n                statusStack.pop();\n                stackTop = statusStack[statusStack.length - 1];\n              }\n            }\n            embedLevels[i$2] = stackTop._level; // 5.2\n          }\n\n          // End of Paragraph: 3.3.2 X8\n          else if (charType & TYPE_B) {\n            embedLevels[i$2] = paragraph.level;\n          }\n        }\n\n        // Non-formatting characters: 3.3.2 X6\n        else {\n          embedLevels[i$2] = stackTop._level;\n          // NOTE: This exclusion of BN seems to go against what section 5.2 says, but is required for test passage\n          if (stackTop._override && charType !== TYPE_BN) {\n            changeCharType(i$2, stackTop._override);\n          }\n        }\n      }\n\n      // === 3.3.3 Preparations for Implicit Processing ===\n\n      // Remove all RLE, LRE, RLO, LRO, PDF, and BN characters: 3.3.3 X9\n      // Note: Due to section 5.2, we won't remove them, but we'll use the BN_LIKE_TYPES bitset to\n      // easily ignore them all from here on out.\n\n      // 3.3.3 X10\n      // Compute the set of isolating run sequences as specified by BD13\n      var levelRuns = [];\n      var currentRun = null;\n      for (var i$3 = paragraph.start; i$3 <= paragraph.end; i$3++) {\n        var charType$1 = charTypes[i$3];\n        if (!(charType$1 & BN_LIKE_TYPES)) {\n          var lvl = embedLevels[i$3];\n          var isIsolInit = charType$1 & ISOLATE_INIT_TYPES;\n          var isPDI = charType$1 === TYPE_PDI;\n          if (currentRun && lvl === currentRun._level) {\n            currentRun._end = i$3;\n            currentRun._endsWithIsolInit = isIsolInit;\n          } else {\n            levelRuns.push(currentRun = {\n              _start: i$3,\n              _end: i$3,\n              _level: lvl,\n              _startsWithPDI: isPDI,\n              _endsWithIsolInit: isIsolInit\n            });\n          }\n        }\n      }\n      var isolatingRunSeqs = []; // [{seqIndices: [], sosType: L|R, eosType: L|R}]\n      for (var runIdx = 0; runIdx < levelRuns.length; runIdx++) {\n        var run = levelRuns[runIdx];\n        if (!run._startsWithPDI || (run._startsWithPDI && !isolationPairs.has(run._start))) {\n          var seqRuns = [currentRun = run];\n          for (var pdiIndex = (void 0); currentRun && currentRun._endsWithIsolInit && (pdiIndex = isolationPairs.get(currentRun._end)) != null;) {\n            for (var i$4 = runIdx + 1; i$4 < levelRuns.length; i$4++) {\n              if (levelRuns[i$4]._start === pdiIndex) {\n                seqRuns.push(currentRun = levelRuns[i$4]);\n                break\n              }\n            }\n          }\n          // build flat list of indices across all runs:\n          var seqIndices = [];\n          for (var i$5 = 0; i$5 < seqRuns.length; i$5++) {\n            var run$1 = seqRuns[i$5];\n            for (var j = run$1._start; j <= run$1._end; j++) {\n              seqIndices.push(j);\n            }\n          }\n          // determine the sos/eos types:\n          var firstLevel = embedLevels[seqIndices[0]];\n          var prevLevel = paragraph.level;\n          for (var i$6 = seqIndices[0] - 1; i$6 >= 0; i$6--) {\n            if (!(charTypes[i$6] & BN_LIKE_TYPES)) { //5.2\n              prevLevel = embedLevels[i$6];\n              break\n            }\n          }\n          var lastIndex = seqIndices[seqIndices.length - 1];\n          var lastLevel = embedLevels[lastIndex];\n          var nextLevel = paragraph.level;\n          if (!(charTypes[lastIndex] & ISOLATE_INIT_TYPES)) {\n            for (var i$7 = lastIndex + 1; i$7 <= paragraph.end; i$7++) {\n              if (!(charTypes[i$7] & BN_LIKE_TYPES)) { //5.2\n                nextLevel = embedLevels[i$7];\n                break\n              }\n            }\n          }\n          isolatingRunSeqs.push({\n            _seqIndices: seqIndices,\n            _sosType: Math.max(prevLevel, firstLevel) % 2 ? TYPE_R : TYPE_L,\n            _eosType: Math.max(nextLevel, lastLevel) % 2 ? TYPE_R : TYPE_L\n          });\n        }\n      }\n\n      // The next steps are done per isolating run sequence\n      for (var seqIdx = 0; seqIdx < isolatingRunSeqs.length; seqIdx++) {\n        var ref = isolatingRunSeqs[seqIdx];\n        var seqIndices$1 = ref._seqIndices;\n        var sosType = ref._sosType;\n        var eosType = ref._eosType;\n        /**\n         * All the level runs in an isolating run sequence have the same embedding level.\n         * \n         * DO NOT change any `embedLevels[i]` within the current scope.\n         */\n        var embedDirection = ((embedLevels[seqIndices$1[0]]) & 1) ? TYPE_R : TYPE_L;\n\n        // === 3.3.4 Resolving Weak Types ===\n\n        // W1 + 5.2. Search backward from each NSM to the first character in the isolating run sequence whose\n        // bidirectional type is not BN, and set the NSM to ON if it is an isolate initiator or PDI, and to its\n        // type otherwise. If the NSM is the first non-BN character, change the NSM to the type of sos.\n        if (charTypeCounts.get(TYPE_NSM)) {\n          for (var si = 0; si < seqIndices$1.length; si++) {\n            var i$8 = seqIndices$1[si];\n            if (charTypes[i$8] & TYPE_NSM) {\n              var prevType = sosType;\n              for (var sj = si - 1; sj >= 0; sj--) {\n                if (!(charTypes[seqIndices$1[sj]] & BN_LIKE_TYPES)) { //5.2 scan back to first non-BN\n                  prevType = charTypes[seqIndices$1[sj]];\n                  break\n                }\n              }\n              changeCharType(i$8, (prevType & (ISOLATE_INIT_TYPES | TYPE_PDI)) ? TYPE_ON : prevType);\n            }\n          }\n        }\n\n        // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sos)\n        // is found. If an AL is found, change the type of the European number to Arabic number.\n        if (charTypeCounts.get(TYPE_EN)) {\n          for (var si$1 = 0; si$1 < seqIndices$1.length; si$1++) {\n            var i$9 = seqIndices$1[si$1];\n            if (charTypes[i$9] & TYPE_EN) {\n              for (var sj$1 = si$1 - 1; sj$1 >= -1; sj$1--) {\n                var prevCharType = sj$1 === -1 ? sosType : charTypes[seqIndices$1[sj$1]];\n                if (prevCharType & STRONG_TYPES) {\n                  if (prevCharType === TYPE_AL) {\n                    changeCharType(i$9, TYPE_AN);\n                  }\n                  break\n                }\n              }\n            }\n          }\n        }\n\n        // W3. Change all ALs to R\n        if (charTypeCounts.get(TYPE_AL)) {\n          for (var si$2 = 0; si$2 < seqIndices$1.length; si$2++) {\n            var i$10 = seqIndices$1[si$2];\n            if (charTypes[i$10] & TYPE_AL) {\n              changeCharType(i$10, TYPE_R);\n            }\n          }\n        }\n\n        // W4. A single European separator between two European numbers changes to a European number. A single common\n        // separator between two numbers of the same type changes to that type.\n        if (charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) {\n          for (var si$3 = 1; si$3 < seqIndices$1.length - 1; si$3++) {\n            var i$11 = seqIndices$1[si$3];\n            if (charTypes[i$11] & (TYPE_ES | TYPE_CS)) {\n              var prevType$1 = 0, nextType = 0;\n              for (var sj$2 = si$3 - 1; sj$2 >= 0; sj$2--) {\n                prevType$1 = charTypes[seqIndices$1[sj$2]];\n                if (!(prevType$1 & BN_LIKE_TYPES)) { //5.2\n                  break\n                }\n              }\n              for (var sj$3 = si$3 + 1; sj$3 < seqIndices$1.length; sj$3++) {\n                nextType = charTypes[seqIndices$1[sj$3]];\n                if (!(nextType & BN_LIKE_TYPES)) { //5.2\n                  break\n                }\n              }\n              if (prevType$1 === nextType && (charTypes[i$11] === TYPE_ES ? prevType$1 === TYPE_EN : (prevType$1 & (TYPE_EN | TYPE_AN)))) {\n                changeCharType(i$11, prevType$1);\n              }\n            }\n          }\n        }\n\n        // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.\n        if (charTypeCounts.get(TYPE_EN)) {\n          for (var si$4 = 0; si$4 < seqIndices$1.length; si$4++) {\n            var i$12 = seqIndices$1[si$4];\n            if (charTypes[i$12] & TYPE_EN) {\n              for (var sj$4 = si$4 - 1; sj$4 >= 0 && (charTypes[seqIndices$1[sj$4]] & (TYPE_ET | BN_LIKE_TYPES)); sj$4--) {\n                changeCharType(seqIndices$1[sj$4], TYPE_EN);\n              }\n              for (si$4++; si$4 < seqIndices$1.length && (charTypes[seqIndices$1[si$4]] & (TYPE_ET | BN_LIKE_TYPES | TYPE_EN)); si$4++) {\n                if (charTypes[seqIndices$1[si$4]] !== TYPE_EN) {\n                  changeCharType(seqIndices$1[si$4], TYPE_EN);\n                }\n              }\n            }\n          }\n        }\n\n        // W6. Otherwise, separators and terminators change to Other Neutral.\n        if (charTypeCounts.get(TYPE_ET) || charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) {\n          for (var si$5 = 0; si$5 < seqIndices$1.length; si$5++) {\n            var i$13 = seqIndices$1[si$5];\n            if (charTypes[i$13] & (TYPE_ET | TYPE_ES | TYPE_CS)) {\n              changeCharType(i$13, TYPE_ON);\n              // 5.2 transform adjacent BNs too:\n              for (var sj$5 = si$5 - 1; sj$5 >= 0 && (charTypes[seqIndices$1[sj$5]] & BN_LIKE_TYPES); sj$5--) {\n                changeCharType(seqIndices$1[sj$5], TYPE_ON);\n              }\n              for (var sj$6 = si$5 + 1; sj$6 < seqIndices$1.length && (charTypes[seqIndices$1[sj$6]] & BN_LIKE_TYPES); sj$6++) {\n                changeCharType(seqIndices$1[sj$6], TYPE_ON);\n              }\n            }\n          }\n        }\n\n        // W7. Search backward from each instance of a European number until the first strong type (R, L, or sos)\n        // is found. If an L is found, then change the type of the European number to L.\n        // NOTE: implemented in single forward pass for efficiency\n        if (charTypeCounts.get(TYPE_EN)) {\n          for (var si$6 = 0, prevStrongType = sosType; si$6 < seqIndices$1.length; si$6++) {\n            var i$14 = seqIndices$1[si$6];\n            var type = charTypes[i$14];\n            if (type & TYPE_EN) {\n              if (prevStrongType === TYPE_L) {\n                changeCharType(i$14, TYPE_L);\n              }\n            } else if (type & STRONG_TYPES) {\n              prevStrongType = type;\n            }\n          }\n        }\n\n        // === 3.3.5 Resolving Neutral and Isolate Formatting Types ===\n\n        if (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES)) {\n          // N0. Process bracket pairs in an isolating run sequence sequentially in the logical order of the text\n          // positions of the opening paired brackets using the logic given below. Within this scope, bidirectional\n          // types EN and AN are treated as R.\n          var R_TYPES_FOR_N_STEPS = (TYPE_R | TYPE_EN | TYPE_AN);\n          var STRONG_TYPES_FOR_N_STEPS = R_TYPES_FOR_N_STEPS | TYPE_L;\n\n          // * Identify the bracket pairs in the current isolating run sequence according to BD16.\n          var bracketPairs = [];\n          {\n            var openerStack = [];\n            for (var si$7 = 0; si$7 < seqIndices$1.length; si$7++) {\n              // NOTE: for any potential bracket character we also test that it still carries a NI\n              // type, as that may have been changed earlier. This doesn't seem to be explicitly\n              // called out in the spec, but is required for passage of certain tests.\n              if (charTypes[seqIndices$1[si$7]] & NEUTRAL_ISOLATE_TYPES) {\n                var char = string[seqIndices$1[si$7]];\n                var oppositeBracket = (void 0);\n                // Opening bracket\n                if (openingToClosingBracket(char) !== null) {\n                  if (openerStack.length < 63) {\n                    openerStack.push({ char: char, seqIndex: si$7 });\n                  } else {\n                    break\n                  }\n                }\n                // Closing bracket\n                else if ((oppositeBracket = closingToOpeningBracket(char)) !== null) {\n                  for (var stackIdx = openerStack.length - 1; stackIdx >= 0; stackIdx--) {\n                    var stackChar = openerStack[stackIdx].char;\n                    if (stackChar === oppositeBracket ||\n                      stackChar === closingToOpeningBracket(getCanonicalBracket(char)) ||\n                      openingToClosingBracket(getCanonicalBracket(stackChar)) === char\n                    ) {\n                      bracketPairs.push([openerStack[stackIdx].seqIndex, si$7]);\n                      openerStack.length = stackIdx; //pop the matching bracket and all following\n                      break\n                    }\n                  }\n                }\n              }\n            }\n            bracketPairs.sort(function (a, b) { return a[0] - b[0]; });\n          }\n          // * For each bracket-pair element in the list of pairs of text positions\n          for (var pairIdx = 0; pairIdx < bracketPairs.length; pairIdx++) {\n            var ref$1 = bracketPairs[pairIdx];\n            var openSeqIdx = ref$1[0];\n            var closeSeqIdx = ref$1[1];\n            // a. Inspect the bidirectional types of the characters enclosed within the bracket pair.\n            // b. If any strong type (either L or R) matching the embedding direction is found, set the type for both\n            // brackets in the pair to match the embedding direction.\n            var foundStrongType = false;\n            var useStrongType = 0;\n            for (var si$8 = openSeqIdx + 1; si$8 < closeSeqIdx; si$8++) {\n              var i$15 = seqIndices$1[si$8];\n              if (charTypes[i$15] & STRONG_TYPES_FOR_N_STEPS) {\n                foundStrongType = true;\n                var lr = (charTypes[i$15] & R_TYPES_FOR_N_STEPS) ? TYPE_R : TYPE_L;\n                if (lr === embedDirection) {\n                  useStrongType = lr;\n                  break\n                }\n              }\n            }\n            // c. Otherwise, if there is a strong type it must be opposite the embedding direction. Therefore, test\n            // for an established context with a preceding strong type by checking backwards before the opening paired\n            // bracket until the first strong type (L, R, or sos) is found.\n            //    1. If the preceding strong type is also opposite the embedding direction, context is established, so\n            //    set the type for both brackets in the pair to that direction.\n            //    2. Otherwise set the type for both brackets in the pair to the embedding direction.\n            if (foundStrongType && !useStrongType) {\n              useStrongType = sosType;\n              for (var si$9 = openSeqIdx - 1; si$9 >= 0; si$9--) {\n                var i$16 = seqIndices$1[si$9];\n                if (charTypes[i$16] & STRONG_TYPES_FOR_N_STEPS) {\n                  var lr$1 = (charTypes[i$16] & R_TYPES_FOR_N_STEPS) ? TYPE_R : TYPE_L;\n                  if (lr$1 !== embedDirection) {\n                    useStrongType = lr$1;\n                  } else {\n                    useStrongType = embedDirection;\n                  }\n                  break\n                }\n              }\n            }\n            if (useStrongType) {\n              charTypes[seqIndices$1[openSeqIdx]] = charTypes[seqIndices$1[closeSeqIdx]] = useStrongType;\n              // * Any number of characters that had original bidirectional character type NSM prior to the application\n              // of W1 that immediately follow a paired bracket which changed to L or R under N0 should change to match\n              // the type of their preceding bracket.\n              if (useStrongType !== embedDirection) {\n                for (var si$10 = openSeqIdx + 1; si$10 < seqIndices$1.length; si$10++) {\n                  if (!(charTypes[seqIndices$1[si$10]] & BN_LIKE_TYPES)) {\n                    if (getBidiCharType(string[seqIndices$1[si$10]]) & TYPE_NSM) {\n                      charTypes[seqIndices$1[si$10]] = useStrongType;\n                    }\n                    break\n                  }\n                }\n              }\n              if (useStrongType !== embedDirection) {\n                for (var si$11 = closeSeqIdx + 1; si$11 < seqIndices$1.length; si$11++) {\n                  if (!(charTypes[seqIndices$1[si$11]] & BN_LIKE_TYPES)) {\n                    if (getBidiCharType(string[seqIndices$1[si$11]]) & TYPE_NSM) {\n                      charTypes[seqIndices$1[si$11]] = useStrongType;\n                    }\n                    break\n                  }\n                }\n              }\n            }\n          }\n\n          // N1. A sequence of NIs takes the direction of the surrounding strong text if the text on both sides has the\n          // same direction.\n          // N2. Any remaining NIs take the embedding direction.\n          for (var si$12 = 0; si$12 < seqIndices$1.length; si$12++) {\n            if (charTypes[seqIndices$1[si$12]] & NEUTRAL_ISOLATE_TYPES) {\n              var niRunStart = si$12, niRunEnd = si$12;\n              var prevType$2 = sosType; //si === 0 ? sosType : (charTypes[seqIndices[si - 1]] & R_TYPES_FOR_N_STEPS) ? TYPE_R : TYPE_L\n              for (var si2 = si$12 - 1; si2 >= 0; si2--) {\n                if (charTypes[seqIndices$1[si2]] & BN_LIKE_TYPES) {\n                  niRunStart = si2; //5.2 treat BNs adjacent to NIs as NIs\n                } else {\n                  prevType$2 = (charTypes[seqIndices$1[si2]] & R_TYPES_FOR_N_STEPS) ? TYPE_R : TYPE_L;\n                  break\n                }\n              }\n              var nextType$1 = eosType;\n              for (var si2$1 = si$12 + 1; si2$1 < seqIndices$1.length; si2$1++) {\n                if (charTypes[seqIndices$1[si2$1]] & (NEUTRAL_ISOLATE_TYPES | BN_LIKE_TYPES)) {\n                  niRunEnd = si2$1;\n                } else {\n                  nextType$1 = (charTypes[seqIndices$1[si2$1]] & R_TYPES_FOR_N_STEPS) ? TYPE_R : TYPE_L;\n                  break\n                }\n              }\n              for (var sj$7 = niRunStart; sj$7 <= niRunEnd; sj$7++) {\n                charTypes[seqIndices$1[sj$7]] = prevType$2 === nextType$1 ? prevType$2 : embedDirection;\n              }\n              si$12 = niRunEnd;\n            }\n          }\n        }\n      }\n\n      // === 3.3.6 Resolving Implicit Levels ===\n\n      for (var i$17 = paragraph.start; i$17 <= paragraph.end; i$17++) {\n        var level$3 = embedLevels[i$17];\n        var type$1 = charTypes[i$17];\n        // I2. For all characters with an odd (right-to-left) embedding level, those of type L, EN or AN go up one level.\n        if (level$3 & 1) {\n          if (type$1 & (TYPE_L | TYPE_EN | TYPE_AN)) {\n            embedLevels[i$17]++;\n          }\n        }\n          // I1. For all characters with an even (left-to-right) embedding level, those of type R go up one level\n        // and those of type AN or EN go up two levels.\n        else {\n          if (type$1 & TYPE_R) {\n            embedLevels[i$17]++;\n          } else if (type$1 & (TYPE_AN | TYPE_EN)) {\n            embedLevels[i$17] += 2;\n          }\n        }\n\n        // 5.2: Resolve any LRE, RLE, LRO, RLO, PDF, or BN to the level of the preceding character if there is one,\n        // and otherwise to the base level.\n        if (type$1 & BN_LIKE_TYPES) {\n          embedLevels[i$17] = i$17 === 0 ? paragraph.level : embedLevels[i$17 - 1];\n        }\n\n        // 3.4 L1.1-4: Reset the embedding level of segment/paragraph separators, and any sequence of whitespace or\n        // isolate formatting characters preceding them or the end of the paragraph, to the paragraph level.\n        // NOTE: this will also need to be applied to each individual line ending after line wrapping occurs.\n        if (i$17 === paragraph.end || getBidiCharType(string[i$17]) & (TYPE_S | TYPE_B)) {\n          for (var j$1 = i$17; j$1 >= 0 && (getBidiCharType(string[j$1]) & TRAILING_TYPES); j$1--) {\n            embedLevels[j$1] = paragraph.level;\n          }\n        }\n      }\n    }\n\n    // DONE! The resolved levels can then be used, after line wrapping, to flip runs of characters\n    // according to section 3.4 Reordering Resolved Levels\n    return {\n      levels: embedLevels,\n      paragraphs: paragraphs\n    }\n\n    function determineAutoEmbedLevel (start, isFSI) {\n      // 3.3.1 P2 - P3\n      for (var i = start; i < string.length; i++) {\n        var charType = charTypes[i];\n        if (charType & (TYPE_R | TYPE_AL)) {\n          return 1\n        }\n        if ((charType & (TYPE_B | TYPE_L)) || (isFSI && charType === TYPE_PDI)) {\n          return 0\n        }\n        if (charType & ISOLATE_INIT_TYPES) {\n          var pdi = indexOfMatchingPDI(i);\n          i = pdi === -1 ? string.length : pdi;\n        }\n      }\n      return 0\n    }\n\n    function indexOfMatchingPDI (isolateStart) {\n      // 3.1.2 BD9\n      var isolationLevel = 1;\n      for (var i = isolateStart + 1; i < string.length; i++) {\n        var charType = charTypes[i];\n        if (charType & TYPE_B) {\n          break\n        }\n        if (charType & TYPE_PDI) {\n          if (--isolationLevel === 0) {\n            return i\n          }\n        } else if (charType & ISOLATE_INIT_TYPES) {\n          isolationLevel++;\n        }\n      }\n      return -1\n    }\n  }\n\n  // Bidi mirrored chars data, auto generated\n  var data = \"14>1,j>2,t>2,u>2,1a>g,2v3>1,1>1,1ge>1,1wd>1,b>1,1j>1,f>1,ai>3,-2>3,+1,8>1k0,-1jq>1y7,-1y6>1hf,-1he>1h6,-1h5>1ha,-1h8>1qi,-1pu>1,6>3u,-3s>7,6>1,1>1,f>1,1>1,+2,3>1,1>1,+13,4>1,1>1,6>1eo,-1ee>1,3>1mg,-1me>1mk,-1mj>1mi,-1mg>1mi,-1md>1,1>1,+2,1>10k,-103>1,1>1,4>1,5>1,1>1,+10,3>1,1>8,-7>8,+1,-6>7,+1,a>1,1>1,u>1,u6>1,1>1,+5,26>1,1>1,2>1,2>2,8>1,7>1,4>1,1>1,+5,b8>1,1>1,+3,1>3,-2>1,2>1,1>1,+2,c>1,3>1,1>1,+2,h>1,3>1,a>1,1>1,2>1,3>1,1>1,d>1,f>1,3>1,1a>1,1>1,6>1,7>1,13>1,k>1,1>1,+19,4>1,1>1,+2,2>1,1>1,+18,m>1,a>1,1>1,lk>1,1>1,4>1,2>1,f>1,3>1,1>1,+3,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,6>1,4j>1,j>2,t>2,u>2,2>1,+1\";\n\n  var mirrorMap;\n\n  function parse () {\n    if (!mirrorMap) {\n      //const start = performance.now()\n      var ref = parseCharacterMap(data, true);\n      var map = ref.map;\n      var reverseMap = ref.reverseMap;\n      // Combine both maps into one\n      reverseMap.forEach(function (value, key) {\n        map.set(key, value);\n      });\n      mirrorMap = map;\n      //console.log(`mirrored chars parsed in ${performance.now() - start}ms`)\n    }\n  }\n\n  /**\n   * Get the mirrored character for a given character, if one exists.\n   * @param {string} char\n   * @return {string|null}\n   */\n  function getMirroredCharacter (char) {\n    parse();\n    return mirrorMap.get(char) || null\n  }\n\n  /**\n   * Given a string and its resolved embedding levels, build a map of indices to replacement chars\n   * for any characters in right-to-left segments that have defined mirrored characters.\n   * @param {string} string\n   * @param {Uint8Array} embeddingLevels\n   * @param {number?} [start]\n   * @param {number?} [end]\n   * @return {Map<number, string>}\n   */\n  function getMirroredCharactersMap(string, embeddingLevels, start, end) {\n    var strLen = string.length;\n    start = Math.max(0, start == null ? 0 : +start);\n    end = Math.min(strLen - 1, end == null ? strLen - 1 : +end);\n\n    var map = new Map();\n    for (var i = start; i <= end; i++) {\n      if (embeddingLevels[i] & 1) { //only odd (rtl) levels\n        var mirror = getMirroredCharacter(string[i]);\n        if (mirror !== null) {\n          map.set(i, mirror);\n        }\n      }\n    }\n    return map\n  }\n\n  /**\n   * Given a start and end denoting a single line within a string, and a set of precalculated\n   * bidi embedding levels, produce a list of segments whose ordering should be flipped, in sequence.\n   * @param {string} string - the full input string\n   * @param {GetEmbeddingLevelsResult} embeddingLevelsResult - the result object from getEmbeddingLevels\n   * @param {number} [start] - first character in a subset of the full string\n   * @param {number} [end] - last character in a subset of the full string\n   * @return {number[][]} - the list of start/end segments that should be flipped, in order.\n   */\n  function getReorderSegments(string, embeddingLevelsResult, start, end) {\n    var strLen = string.length;\n    start = Math.max(0, start == null ? 0 : +start);\n    end = Math.min(strLen - 1, end == null ? strLen - 1 : +end);\n\n    var segments = [];\n    embeddingLevelsResult.paragraphs.forEach(function (paragraph) {\n      var lineStart = Math.max(start, paragraph.start);\n      var lineEnd = Math.min(end, paragraph.end);\n      if (lineStart < lineEnd) {\n        // Local slice for mutation\n        var lineLevels = embeddingLevelsResult.levels.slice(lineStart, lineEnd + 1);\n\n        // 3.4 L1.4: Reset any sequence of whitespace characters and/or isolate formatting characters at the\n        // end of the line to the paragraph level.\n        for (var i = lineEnd; i >= lineStart && (getBidiCharType(string[i]) & TRAILING_TYPES); i--) {\n          lineLevels[i] = paragraph.level;\n        }\n\n        // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels\n        // not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.\n        var maxLevel = paragraph.level;\n        var minOddLevel = Infinity;\n        for (var i$1 = 0; i$1 < lineLevels.length; i$1++) {\n          var level = lineLevels[i$1];\n          if (level > maxLevel) { maxLevel = level; }\n          if (level < minOddLevel) { minOddLevel = level | 1; }\n        }\n        for (var lvl = maxLevel; lvl >= minOddLevel; lvl--) {\n          for (var i$2 = 0; i$2 < lineLevels.length; i$2++) {\n            if (lineLevels[i$2] >= lvl) {\n              var segStart = i$2;\n              while (i$2 + 1 < lineLevels.length && lineLevels[i$2 + 1] >= lvl) {\n                i$2++;\n              }\n              if (i$2 > segStart) {\n                segments.push([segStart + lineStart, i$2 + lineStart]);\n              }\n            }\n          }\n        }\n      }\n    });\n    return segments\n  }\n\n  /**\n   * @param {string} string\n   * @param {GetEmbeddingLevelsResult} embedLevelsResult\n   * @param {number} [start]\n   * @param {number} [end]\n   * @return {string} the new string with bidi segments reordered\n   */\n  function getReorderedString(string, embedLevelsResult, start, end) {\n    var indices = getReorderedIndices(string, embedLevelsResult, start, end);\n    var chars = [].concat( string );\n    indices.forEach(function (charIndex, i) {\n      chars[i] = (\n        (embedLevelsResult.levels[charIndex] & 1) ? getMirroredCharacter(string[charIndex]) : null\n      ) || string[charIndex];\n    });\n    return chars.join('')\n  }\n\n  /**\n   * @param {string} string\n   * @param {GetEmbeddingLevelsResult} embedLevelsResult\n   * @param {number} [start]\n   * @param {number} [end]\n   * @return {number[]} an array with character indices in their new bidi order\n   */\n  function getReorderedIndices(string, embedLevelsResult, start, end) {\n    var segments = getReorderSegments(string, embedLevelsResult, start, end);\n    // Fill an array with indices\n    var indices = [];\n    for (var i = 0; i < string.length; i++) {\n      indices[i] = i;\n    }\n    // Reverse each segment in order\n    segments.forEach(function (ref) {\n      var start = ref[0];\n      var end = ref[1];\n\n      var slice = indices.slice(start, end + 1);\n      for (var i = slice.length; i--;) {\n        indices[end - i] = slice[i];\n      }\n    });\n    return indices\n  }\n\n  exports.closingToOpeningBracket = closingToOpeningBracket;\n  exports.getBidiCharType = getBidiCharType;\n  exports.getBidiCharTypeName = getBidiCharTypeName;\n  exports.getCanonicalBracket = getCanonicalBracket;\n  exports.getEmbeddingLevels = getEmbeddingLevels;\n  exports.getMirroredCharacter = getMirroredCharacter;\n  exports.getMirroredCharactersMap = getMirroredCharactersMap;\n  exports.getReorderSegments = getReorderSegments;\n  exports.getReorderedIndices = getReorderedIndices;\n  exports.getReorderedString = getReorderedString;\n  exports.openingToClosingBracket = openingToClosingBracket;\n\n  Object.defineProperty(exports, '__esModule', { value: true });\n\n  return exports;\n\n})({});\nreturn bidi}\n\nexport { bidiFactory as default };\n", "import bidiFactory, {type BidiCharTypeName} from 'bidi-js';\nimport {toGraphemes} from '../util/graphemes.ts';\n\nconst bidi = bidiFactory();\n\n/**\n * The characters that steer the bidirectional algorithm without being written.\n *\n * They have done their work by the time the text has been reordered, and no font draws them, so\n * they are dropped rather than passed on to be looked up in a glyph atlas.\n */\nconst BIDI_CONTROLS = /[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/;\n\n/**\n * The character types rule L1 resets to the paragraph's own direction.\n *\n * Trailing spaces belong to the paragraph rather than to the run they follow, so a line of Hebrew\n * ending in a space does not put that space on the wrong end of the line.\n */\nconst NEUTRAL_AT_END_OF_LINE = new Set<BidiCharTypeName>(['WS', 'FSI', 'LRI', 'RLI', 'PDI']);\n\n/** The character types rule L1 resets wherever they appear, along with the whitespace before them. */\nconst ALWAYS_RESET = new Set<BidiCharTypeName>(['S', 'B']);\n\n/** One grapheme cluster of the text, with everything the reordering rules need to place it. */\ntype Cluster = {\n    /** Where the cluster starts, in UTF-16 code units. */\n    index: number;\n    text: string;\n    level: number;\n};\n\n/**\n * Splits a line into grapheme clusters, tagging each with the embedding level of its first character.\n *\n * Reordering whole clusters is what rule L3 asks for by another route: a letter and the marks\n * written on it move as one, so reversing a right-to-left run cannot leave the marks stranded before\n * their letter, and layout gets back the same units of writing it asked for glyphs for.\n */\nfunction toClusters(text: string, levels: Uint8Array, start: number, end: number): Cluster[] {\n    const clusters: Cluster[] = [];\n    let index = start;\n    for (const cluster of toGraphemes(text.slice(start, end))) {\n        clusters.push({index, text: cluster, level: levels[index]});\n        index += cluster.length;\n    }\n    return clusters;\n}\n\n/**\n * Applies rule L1, which hands whitespace at the end of a line back to the paragraph's direction.\n *\n * Without it a line of right-to-left text that ends in a space would be drawn with that space on\n * its left, where the reader does not expect it.\n */\nfunction resetTrailingNeutrals(clusters: Cluster[], paragraphLevel: number): void {\n    let trailing = true;\n    for (let i = clusters.length - 1; i >= 0; i--) {\n        const type = bidi.getBidiCharTypeName(clusters[i].text[0]);\n        if (ALWAYS_RESET.has(type)) {\n            clusters[i].level = paragraphLevel;\n            trailing = true;\n        } else if (trailing && NEUTRAL_AT_END_OF_LINE.has(type)) {\n            clusters[i].level = paragraphLevel;\n        } else {\n            trailing = false;\n        }\n    }\n}\n\n/**\n * Applies rule L2, which turns embedding levels into the order the text is read on screen.\n *\n * Each level from the deepest down to the shallowest odd one reverses every run of characters at\n * that level or deeper, so nesting a quotation in one direction inside a sentence in the other comes\n * out right however far the nesting goes.\n */\nfunction reorder(clusters: Cluster[], paragraphLevel: number): Cluster[] {\n    let highest = paragraphLevel;\n    let lowestOdd = Infinity;\n    for (const {level} of clusters) {\n        if (level > highest) highest = level;\n        if ((level | 1) < lowestOdd) lowestOdd = level | 1;\n    }\n\n    const ordered = clusters.slice();\n    for (let level = highest; level >= lowestOdd; level--) {\n        for (let start = 0; start < ordered.length; start++) {\n            if (ordered[start].level < level) continue;\n            let end = start;\n            while (end + 1 < ordered.length && ordered[end + 1].level >= level) end++;\n            for (let i = start, j = end; i < j; i++, j--) {\n                [ordered[i], ordered[j]] = [ordered[j], ordered[i]];\n            }\n            start = end;\n        }\n    }\n    return ordered;\n}\n\n/**\n * Swaps a bracket for its mirror image where it is read right to left.\n *\n * An opening parenthesis in Hebrew text is drawn as the shape that opens in that direction, which is\n * the one Unicode calls a closing parenthesis.\n */\nfunction mirror(cluster: Cluster): string {\n    if (cluster.level % 2 === 0) return cluster.text;\n    return bidi.getMirroredCharacter(cluster.text) ?? cluster.text;\n}\n\n/** The paragraph a line falls in, which is what its direction is taken from. */\nfunction paragraphLevelAt(paragraphs: Array<{ start: number; end: number; level: number }>, start: number): number {\n    return paragraphs.find(paragraph => start >= paragraph.start && start <= paragraph.end)?.level ?? 0;\n}\n\n/** A line of a label, put into the order it is read and stripped of the characters nothing draws. */\ntype ReorderedLine = {\n    text: string;\n    /** The code unit of the original text each code unit of {@link ReorderedLine.text} came from. */\n    sourceIndices: number[];\n};\n\n/**\n * Puts one line into visual order.\n *\n * Reordering happens a grapheme cluster at a time, so a letter and the marks written on it stay\n * together however the line is rearranged.\n */\nfunction reorderLine(\n    text: string,\n    levels: Uint8Array,\n    paragraphLevel: number,\n    start: number,\n    end: number\n): ReorderedLine {\n    const clusters = toClusters(text, levels, start, end);\n    resetTrailingNeutrals(clusters, paragraphLevel);\n\n    let reorderedText = '';\n    const sourceIndices: number[] = [];\n    for (const cluster of reorder(clusters, paragraphLevel)) {\n        if (BIDI_CONTROLS.test(cluster.text)) continue;\n        const mirrored = mirror(cluster);\n        reorderedText += mirrored;\n        sourceIndices.push(...Array(mirrored.length).fill(cluster.index));\n    }\n    return {text: reorderedText, sourceIndices};\n}\n\n/**\n * The `[start, end)` code unit range of each line, given every offset the label is to be broken at.\n *\n * The offsets are put in order and duplicates dropped, because a line asked to break where a\n * paragraph already ends should be one line rather than an empty one and a full one.\n */\nfunction lineRanges(text: string, breakPoints: number[]): Array<[number, number]> {\n    const inside = breakPoints.filter(point => point > 0 && point < text.length);\n    const bounds = [...new Set([0, ...inside, text.length])].sort((a, b) => a - b);\n\n    const ranges: Array<[number, number]> = [];\n    for (let i = 0; i + 1 < bounds.length; i++) {\n        ranges.push([bounds[i], bounds[i + 1]]);\n    }\n    return ranges;\n}\n\n/**\n * Reorders every line of a label, keeping where each code unit came from.\n *\n * A label is broken where it was asked to be broken and wherever a paragraph ends. The separators\n * that end a paragraph are the ones the bidirectional algorithm reads its direction afresh after,\n * so a line may not run across one however wide it is.\n */\nfunction processLines(text: string, lineBreakPoints: number[]): ReorderedLine[] {\n    const {levels, paragraphs} = bidi.getEmbeddingLevels(text);\n    const breakPoints = lineBreakPoints.concat(paragraphs.map(paragraph => paragraph.start));\n\n    return lineRanges(text, breakPoints).map(([start, end]) =>\n        reorderLine(text, levels, paragraphLevelAt(paragraphs, start), start, end));\n}\n\n/**\n * Puts text into the order it is read on screen, and breaks it into lines.\n *\n * @param text - a whole label in logical order\n * @param lineBreakPoints - the code unit offsets the label is to be broken at\n * @returns one string per line, each in visual order\n */\nexport function processBidirectionalText(text: string, lineBreakPoints: number[]): string[] {\n    return processLines(text, lineBreakPoints).map(line => line.text);\n}\n\n/**\n * The same as {@link processBidirectionalText}, carrying each code unit's formatting section with it\n * so that a label built out of several `format` sections keeps its styling once reordered.\n *\n * @param text - a whole label in logical order\n * @param styleIndices - the section each code unit of `text` belongs to\n * @param lineBreakPoints - the code unit offsets the label is to be broken at\n * @returns one `[line, styleIndices]` pair per line, each in visual order\n */\nexport function processStyledBidirectionalText(\n    text: string,\n    styleIndices: number[],\n    lineBreakPoints: number[]\n): Array<[string, number[]]> {\n    return processLines(text, lineBreakPoints).map(line =>\n        [line.text, line.sourceIndices.map(index => styleIndices[index] ?? 0)]);\n}\n", "\nconst SHIFT_LEFT_32 = (1 << 16) * (1 << 16);\nconst SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;\n\n// Threshold chosen based on both benchmarking and knowledge about browser string\n// data structures (which currently switch structure types at 12 bytes or more)\nconst TEXT_DECODER_MIN_LENGTH = 12;\nconst utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8');\n\nconst PBF_VARINT  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum\nconst PBF_FIXED64 = 1; // 64-bit: double, fixed64, sfixed64\nconst PBF_BYTES   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields\nconst PBF_FIXED32 = 5; // 32-bit: float, fixed32, sfixed32\n\nexport class PbfReader {\n    /**\n     * @param {Uint8Array | ArrayBuffer} buf\n     */\n    constructor(buf) {\n        this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf);\n        this.dataView = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength);\n        this.pos = 0;\n        this.type = 0;\n        this._valueStart = -1;\n        this.length = this.buf.length;\n    }\n\n    /**\n     * @template T\n     * @param {(tag: number, result: T, pbf: PbfReader) => void} readField\n     * @param {T} result\n     * @param {number} [end]\n     */\n    readFields(readField, result, end = this.length) {\n        let field;\n        while ((field = this.nextField(end))) {\n            readField(field, result, this);\n        }\n        return result;\n    }\n\n    /**\n     * @template T\n     * @param {(tag: number, result: T, pbf: PbfReader) => void} readField\n     * @param {T} result\n     */\n    readMessage(readField, result) {\n        return this.readFields(readField, result, this.readVarint() + this.pos);\n    }\n\n    readFixed32() {\n        const val = this.dataView.getUint32(this.pos, true);\n        this.pos += 4;\n        return val;\n    }\n\n    readSFixed32() {\n        const val = this.dataView.getInt32(this.pos, true);\n        this.pos += 4;\n        return val;\n    }\n\n    // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)\n\n    readFixed64() {\n        const val = this.dataView.getUint32(this.pos, true) + this.dataView.getUint32(this.pos + 4, true) * SHIFT_LEFT_32;\n        this.pos += 8;\n        return val;\n    }\n\n    readSFixed64() {\n        const val = this.dataView.getUint32(this.pos, true) + this.dataView.getInt32(this.pos + 4, true) * SHIFT_LEFT_32;\n        this.pos += 8;\n        return val;\n    }\n\n    readFloat() {\n        const val = this.dataView.getFloat32(this.pos, true);\n        this.pos += 4;\n        return val;\n    }\n\n    readDouble() {\n        const val = this.dataView.getFloat64(this.pos, true);\n        this.pos += 8;\n        return val;\n    }\n\n    /**\n     * @param {boolean} [isSigned]\n     */\n    readVarint(isSigned) {\n        const buf = this.buf;\n        const b0 = buf[this.pos++];\n        if (b0 < 0x80) return b0;\n\n        let val = b0 & 0x7f, b;\n        b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;\n        b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;\n        b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;\n        b = buf[this.pos];   val |= (b & 0x0f) << 28;\n\n        return readVarintRemainder(val, isSigned, this);\n    }\n\n    readSVarint() {\n        const num = this.readVarint();\n        return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding\n    }\n\n    readBoolean() {\n        return Boolean(this.readVarint());\n    }\n\n    readString() {\n        const end = this.readVarint() + this.pos;\n        const pos = this.pos;\n        this.pos = end;\n\n        if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) {\n            // longer strings are fast with the built-in browser TextDecoder API\n            return utf8TextDecoder.decode(this.buf.subarray(pos, end));\n        }\n        // short strings are fast with our custom implementation\n        return readUtf8(this.buf, pos, end);\n    }\n\n    readBytes() {\n        const end = this.readVarint() + this.pos,\n            buffer = this.buf.subarray(this.pos, end);\n        this.pos = end;\n        return buffer;\n    }\n\n    // verbose for performance reasons; doesn't affect gzipped size\n\n    /**\n     * @param {number[]} [arr]\n     * @param {boolean} [isSigned]\n     */\n    readPackedVarint(arr = [], isSigned) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readVarint(isSigned));\n        return arr;\n    }\n    /** @param {number[]} [arr] */\n    readPackedSVarint(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readSVarint());\n        return arr;\n    }\n    /** @param {boolean[]} [arr] */\n    readPackedBoolean(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readBoolean());\n        return arr;\n    }\n    /** @param {number[]} [arr] */\n    readPackedFloat(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readFloat());\n        return arr;\n    }\n    /** @param {number[]} [arr] */\n    readPackedDouble(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readDouble());\n        return arr;\n    }\n    /** @param {number[]} [arr] */\n    readPackedFixed32(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readFixed32());\n        return arr;\n    }\n    /** @param {number[]} [arr] */\n    readPackedSFixed32(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readSFixed32());\n        return arr;\n    }\n    /** @param {number[]} [arr] */\n    readPackedFixed64(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readFixed64());\n        return arr;\n    }\n    /** @param {number[]} [arr] */\n    readPackedSFixed64(arr = []) {\n        const end = this.readPackedEnd();\n        while (this.pos < end) arr.push(this.readSFixed64());\n        return arr;\n    }\n    readPackedEnd() {\n        return this.type === PBF_BYTES ? this.readVarint() + this.pos : this.pos + 1;\n    }\n\n    /**\n     * Advance to the next field. Returns the field number, or 0 at end-of-message.\n     * @param {number} [end]\n     */\n    nextField(end = this.length) {\n        if (this.pos === this._valueStart) this.skip(this.type);\n        if (this.pos >= end) return 0;\n        const tag = this.readVarint();\n        this.type = tag & 0x7;\n        this._valueStart = this.pos;\n        return tag >>> 3;\n    }\n\n    /** @param {number} val */\n    skip(val) {\n        const type = val & 0x7;\n        if (type === PBF_VARINT) while (this.buf[this.pos++] > 0x7f) {}\n        else if (type === PBF_BYTES) this.pos = this.readVarint() + this.pos;\n        else if (type === PBF_FIXED32) this.pos += 4;\n        else if (type === PBF_FIXED64) this.pos += 8;\n        else throw new Error(`Unimplemented type: ${type}`);\n    }\n}\n\nexport class PbfWriter {\n    /**\n     * @param {Uint8Array | ArrayBuffer} [buf]\n     */\n    constructor(buf = new Uint8Array(16)) {\n        this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf);\n        this.dataView = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength);\n        this.pos = 0;\n        this.length = this.buf.length;\n    }\n\n    /**\n     * @param {number} tag\n     * @param {number} type\n     */\n    writeTag(tag, type) {\n        this.writeVarint((tag << 3) | type);\n    }\n\n    /** @param {number} min */\n    realloc(min) {\n        let length = this.length || 16;\n\n        while (length < this.pos + min) length *= 2;\n\n        if (length !== this.length) {\n            const buf = new Uint8Array(length);\n            buf.set(this.buf);\n            this.buf = buf;\n            this.dataView = new DataView(buf.buffer);\n            this.length = length;\n        }\n    }\n\n    finish() {\n        this.length = this.pos;\n        this.pos = 0;\n        return this.buf.subarray(0, this.length);\n    }\n\n    /** @param {number} val */\n    writeFixed32(val) {\n        this.realloc(4);\n        this.dataView.setInt32(this.pos, val, true);\n        this.pos += 4;\n    }\n\n    /** @param {number} val */\n    writeSFixed32(val) {\n        this.realloc(4);\n        this.dataView.setInt32(this.pos, val, true);\n        this.pos += 4;\n    }\n\n    /** @param {number} val */\n    writeFixed64(val) {\n        this.realloc(8);\n        this.dataView.setInt32(this.pos, val & -1, true);\n        this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);\n        this.pos += 8;\n    }\n\n    /** @param {number} val */\n    writeSFixed64(val) {\n        this.realloc(8);\n        this.dataView.setInt32(this.pos, val & -1, true);\n        this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);\n        this.pos += 8;\n    }\n\n    /** @param {number} val */\n    writeVarint(val) {\n        val = +val || 0;\n\n        if (val >= 0 && val < 0x80) {\n            if (this.pos >= this.length) this.realloc(1);\n            this.buf[this.pos++] = val;\n            return;\n        }\n\n        if (val > 0xfffffff || val < 0) {\n            writeBigVarint(val, this);\n            return;\n        }\n\n        this.realloc(4);\n\n        this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n        this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n        this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n        this.buf[this.pos++] =   (val >>> 7) & 0x7f;\n    }\n\n    /** @param {number} val */\n    writeSVarint(val) {\n        this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);\n    }\n\n    /** @param {boolean} val */\n    writeBoolean(val) {\n        this.writeVarint(+val);\n    }\n\n    /** @param {string} str */\n    writeString(str) {\n        str = String(str);\n        this.realloc(str.length * 4);\n\n        this.pos++; // reserve 1 byte for short string length\n\n        const startPos = this.pos;\n        // write the string directly to the buffer and see how much was written\n        this.pos = writeUtf8(this.buf, str, this.pos);\n        const len = this.pos - startPos;\n\n        if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);\n\n        // finally, write the message length in the reserved place and restore the position\n        this.pos = startPos - 1;\n        this.writeVarint(len);\n        this.pos += len;\n    }\n\n    /** @param {number} val */\n    writeFloat(val) {\n        this.realloc(4);\n        this.dataView.setFloat32(this.pos, val, true);\n        this.pos += 4;\n    }\n\n    /** @param {number} val */\n    writeDouble(val) {\n        this.realloc(8);\n        this.dataView.setFloat64(this.pos, val, true);\n        this.pos += 8;\n    }\n\n    /** @param {Uint8Array} buffer */\n    writeBytes(buffer) {\n        const len = buffer.length;\n        this.writeVarint(len);\n        this.realloc(len);\n        this.buf.set(buffer, this.pos);\n        this.pos += len;\n    }\n\n    /**\n     * @template T\n     * @param {(obj: T, pbf: PbfWriter) => void} fn\n     * @param {T} obj\n     */\n    writeRawMessage(fn, obj) {\n        this.pos++; // reserve 1 byte for short message length\n\n        // write the message directly to the buffer and see how much was written\n        const startPos = this.pos;\n        fn(obj, this);\n        const len = this.pos - startPos;\n\n        if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);\n\n        // finally, write the message length in the reserved place and restore the position\n        this.pos = startPos - 1;\n        this.writeVarint(len);\n        this.pos += len;\n    }\n\n    /**\n     * @template T\n     * @param {number} tag\n     * @param {(obj: T, pbf: PbfWriter) => void} fn\n     * @param {T} obj\n     */\n    writeMessage(tag, fn, obj) {\n        this.writeTag(tag, PBF_BYTES);\n        this.writeRawMessage(fn, obj);\n    }\n\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedVarint(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedVarint, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedSVarint(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedSVarint, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {boolean[]} arr\n     */\n    writePackedBoolean(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedBoolean, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedFloat(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedFloat, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedDouble(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedDouble, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedFixed32(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedFixed32, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedSFixed32(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedFixed64(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedFixed64, arr);\n    }\n    /**\n     * @param {number} tag\n     * @param {number[]} arr\n     */\n    writePackedSFixed64(tag, arr) {\n        if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr);\n    }\n\n    /**\n     * @param {number} tag\n     * @param {Uint8Array} buffer\n     */\n    writeBytesField(tag, buffer) {\n        this.writeTag(tag, PBF_BYTES);\n        this.writeBytes(buffer);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeFixed32Field(tag, val) {\n        this.writeTag(tag, PBF_FIXED32);\n        this.writeFixed32(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeSFixed32Field(tag, val) {\n        this.writeTag(tag, PBF_FIXED32);\n        this.writeSFixed32(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeFixed64Field(tag, val) {\n        this.writeTag(tag, PBF_FIXED64);\n        this.writeFixed64(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeSFixed64Field(tag, val) {\n        this.writeTag(tag, PBF_FIXED64);\n        this.writeSFixed64(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeVarintField(tag, val) {\n        this.writeTag(tag, PBF_VARINT);\n        this.writeVarint(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeSVarintField(tag, val) {\n        this.writeTag(tag, PBF_VARINT);\n        this.writeSVarint(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {string} str\n     */\n    writeStringField(tag, str) {\n        this.writeTag(tag, PBF_BYTES);\n        this.writeString(str);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeFloatField(tag, val) {\n        this.writeTag(tag, PBF_FIXED32);\n        this.writeFloat(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {number} val\n     */\n    writeDoubleField(tag, val) {\n        this.writeTag(tag, PBF_FIXED64);\n        this.writeDouble(val);\n    }\n    /**\n     * @param {number} tag\n     * @param {boolean} val\n     */\n    writeBooleanField(tag, val) {\n        this.writeVarintField(tag, +val);\n    }\n}\n\n/**\n * @param {number} l\n * @param {boolean | undefined} s\n * @param {PbfReader} p\n */\nfunction readVarintRemainder(l, s, p) {\n    const buf = p.buf;\n    let h, b;\n\n    b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);\n    b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);\n    b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);\n    b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);\n    b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);\n    b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);\n\n    throw new Error('Expected varint not more than 10 bytes');\n}\n\n/**\n * @param {number} low\n * @param {number} high\n * @param {boolean} [isSigned]\n */\nfunction toNum(low, high, isSigned) {\n    return isSigned ? high * 0x100000000 + (low >>> 0) : ((high >>> 0) * 0x100000000) + (low >>> 0);\n}\n\n/**\n * @param {number} val\n * @param {PbfWriter} pbf\n */\nfunction writeBigVarint(val, pbf) {\n    let low, high;\n\n    if (val >= 0) {\n        low  = (val % 0x100000000) | 0;\n        high = (val / 0x100000000) | 0;\n    } else {\n        low  = ~(-val % 0x100000000);\n        high = ~(-val / 0x100000000);\n\n        if (low ^ 0xffffffff) {\n            low = (low + 1) | 0;\n        } else {\n            low = 0;\n            high = (high + 1) | 0;\n        }\n    }\n\n    if (val >= 0x10000000000000000 || val < -0x10000000000000000) {\n        throw new Error('Given varint doesn\\'t fit into 10 bytes');\n    }\n\n    pbf.realloc(10);\n\n    writeBigVarintLow(low, high, pbf);\n    writeBigVarintHigh(high, pbf);\n}\n\n/**\n * @param {number} high\n * @param {number} low\n * @param {PbfWriter} pbf\n */\nfunction writeBigVarintLow(low, high, pbf) {\n    pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n    pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n    pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n    pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n    pbf.buf[pbf.pos]   = low & 0x7f;\n}\n\n/**\n * @param {number} high\n * @param {PbfWriter} pbf\n */\nfunction writeBigVarintHigh(high, pbf) {\n    const lsb = (high & 0x07) << 4;\n\n    pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;\n    pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n    pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n    pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n    pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n    pbf.buf[pbf.pos++]  = high & 0x7f;\n}\n\n/**\n * @param {number} startPos\n * @param {number} len\n * @param {PbfWriter} pbf\n */\nfunction makeRoomForExtraLength(startPos, len, pbf) {\n    const extraLen =\n        len <= 0x3fff ? 1 :\n        len <= 0x1fffff ? 2 :\n        len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7));\n\n    // if 1 byte isn't enough for encoding message length, shift the data to the right\n    pbf.realloc(extraLen);\n    pbf.buf.copyWithin(startPos + extraLen, startPos, pbf.pos);\n}\n\n/**\n * Packed varints often dominate encode time, so write the bytes inline\n * through a local buffer pointer rather than calling writeVarint per element,\n * falling back to writeVarint only for negatives or near the buffer's end.\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedVarint(arr, pbf) {\n    const n = arr.length;\n    let buf = pbf.buf, pos = pbf.pos, limit = pbf.length;\n    for (let i = 0; i < n; i++) {\n        let val = arr[i];\n        if (val < 0 || pos + 10 > limit) { // slow path: grows the buffer, handles 10-byte values\n            pbf.pos = pos;\n            pbf.writeVarint(val);\n            buf = pbf.buf; pos = pbf.pos; limit = pbf.length;\n            continue;\n        }\n        while (val > 0x7f) { buf[pos++] = (val % 0x80) | 0x80; val = Math.floor(val / 0x80); }\n        buf[pos++] = val;\n    }\n    pbf.pos = pos;\n}\n/**\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedSVarint(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);\n}\n/**\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedFloat(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);\n}\n/**\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedDouble(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);\n}\n/**\n * @param {boolean[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedBoolean(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);\n}\n/**\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedFixed32(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);\n}\n/**\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedSFixed32(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]);\n}\n/**\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedFixed64(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);\n}\n/**\n * @param {number[]} arr\n * @param {PbfWriter} pbf\n */\nfunction writePackedSFixed64(arr, pbf) {\n    for (let i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]);\n}\n\n// Buffer code below from https://github.com/feross/buffer, MIT-licensed\n\n/**\n * @param {Uint8Array} buf\n * @param {number} pos\n * @param {number} end\n */\nfunction readUtf8(buf, pos, end) {\n    let str = '';\n    let i = pos;\n\n    while (i < end) {\n        const b0 = buf[i];\n        let c = null; // codepoint\n        let bytesPerSequence =\n            b0 > 0xEF ? 4 :\n            b0 > 0xDF ? 3 :\n            b0 > 0xBF ? 2 : 1;\n\n        if (i + bytesPerSequence > end) break;\n\n        let b1, b2, b3;\n\n        if (bytesPerSequence === 1) {\n            if (b0 < 0x80) {\n                c = b0;\n            }\n        } else if (bytesPerSequence === 2) {\n            b1 = buf[i + 1];\n            if ((b1 & 0xC0) === 0x80) {\n                c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);\n                if (c <= 0x7F) {\n                    c = null;\n                }\n            }\n        } else if (bytesPerSequence === 3) {\n            b1 = buf[i + 1];\n            b2 = buf[i + 2];\n            if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {\n                c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);\n                if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {\n                    c = null;\n                }\n            }\n        } else if (bytesPerSequence === 4) {\n            b1 = buf[i + 1];\n            b2 = buf[i + 2];\n            b3 = buf[i + 3];\n            if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {\n                c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);\n                if (c <= 0xFFFF || c >= 0x110000) {\n                    c = null;\n                }\n            }\n        }\n\n        if (c === null) {\n            c = 0xFFFD;\n            bytesPerSequence = 1;\n\n        } else if (c > 0xFFFF) {\n            c -= 0x10000;\n            str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);\n            c = 0xDC00 | c & 0x3FF;\n        }\n\n        str += String.fromCharCode(c);\n        i += bytesPerSequence;\n    }\n\n    return str;\n}\n\n/**\n * @param {Uint8Array} buf\n * @param {string} str\n * @param {number} pos\n */\nfunction writeUtf8(buf, str, pos) {\n    for (let i = 0, c, lead; i < str.length; i++) {\n        c = str.charCodeAt(i); // code point\n\n        if (c > 0xD7FF && c < 0xE000) {\n            if (lead) {\n                if (c < 0xDC00) {\n                    buf[pos++] = 0xEF;\n                    buf[pos++] = 0xBF;\n                    buf[pos++] = 0xBD;\n                    lead = c;\n                    continue;\n                } else {\n                    c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;\n                    lead = null;\n                }\n            } else {\n                if (c > 0xDBFF || (i + 1 === str.length)) {\n                    buf[pos++] = 0xEF;\n                    buf[pos++] = 0xBF;\n                    buf[pos++] = 0xBD;\n                } else {\n                    lead = c;\n                }\n                continue;\n            }\n        } else if (lead) {\n            buf[pos++] = 0xEF;\n            buf[pos++] = 0xBF;\n            buf[pos++] = 0xBD;\n            lead = null;\n        }\n\n        if (c < 0x80) {\n            buf[pos++] = c;\n        } else {\n            if (c < 0x800) {\n                buf[pos++] = c >> 0x6 | 0xC0;\n            } else {\n                if (c < 0x10000) {\n                    buf[pos++] = c >> 0xC | 0xE0;\n                } else {\n                    buf[pos++] = c >> 0x12 | 0xF0;\n                    buf[pos++] = c >> 0xC & 0x3F | 0x80;\n                }\n                buf[pos++] = c >> 0x6 & 0x3F | 0x80;\n            }\n            buf[pos++] = c & 0x3F | 0x80;\n        }\n    }\n    return pos;\n}\n", "import {AlphaImage} from '../util/image.ts';\nimport {PbfReader} from 'pbf';\nconst border = 3;\n\nimport type {StyleGlyph} from './style_glyph.ts';\n\ntype RawGlyph = {\n    id: number;\n    bitmap: Uint8Array;\n    width: number;\n    height: number;\n    left: number;\n    top: number;\n    advance: number;\n};\n\nfunction readFontstacks(tag: number, glyphs: StyleGlyph[], pbf: PbfReader) {\n    if (tag === 1) {\n        pbf.readMessage(readFontstack, glyphs);\n    }\n}\n\nfunction readFontstack(tag: number, glyphs: StyleGlyph[], pbf: PbfReader) {\n    if (tag === 3) {\n        const {id, bitmap, width, height, left, top, advance} = pbf.readMessage(readGlyph, {} as RawGlyph);\n        glyphs.push({\n            id,\n            bitmap: new AlphaImage({\n                width: width + 2 * border,\n                height: height + 2 * border\n            }, bitmap),\n            metrics: {width, height, left, top, advance}\n        });\n    }\n}\n\nfunction readGlyph(tag: number, glyph: RawGlyph, pbf: PbfReader) {\n    if (tag === 1) glyph.id = pbf.readVarint();\n    else if (tag === 2) glyph.bitmap = pbf.readBytes();\n    else if (tag === 3) glyph.width = pbf.readVarint();\n    else if (tag === 4) glyph.height = pbf.readVarint();\n    else if (tag === 5) glyph.left = pbf.readSVarint();\n    else if (tag === 6) glyph.top = pbf.readSVarint();\n    else if (tag === 7) glyph.advance = pbf.readVarint();\n}\n\nexport function parseGlyphPbf(data: ArrayBuffer | Uint8Array): StyleGlyph[] {\n    return new PbfReader(data).readFields(readFontstacks, []);\n}\n\nexport const GLYPH_PBF_BORDER: 3 = border;\n", "import type {RGBAImage} from '../util/image.ts';\nimport type {Map} from '../ui/map.ts';\n\nexport type SpriteJSON = {[id: string]: StyleImageMetadata & {\n    width: number;\n    height: number;\n    x: number;\n    y: number;\n};};\n\n/**\n * The sprite data\n */\nexport type SpriteOnDemandStyleImage = {\n    width: number;\n    height: number;\n    x: number;\n    y: number;\n    context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n};\n\n/**\n * The style's image metadata\n */\nexport type StyleImageData = {\n    data: RGBAImage;\n    version?: number;\n    hasRenderCallback?: boolean;\n    isWebGLImage?: boolean;\n    userImage?: StyleImageInterface;\n    spriteData?: SpriteOnDemandStyleImage;\n};\n\n/**\n * Enumeration of possible values for StyleImageMetadata.textFitWidth and textFitHeight.\n */\nexport const enum TextFit {\n    /**\n     * The image will be resized on the specified axis to tightly fit the content rectangle to target text.\n     * This is the same as not being defined.\n     */\n    stretchOrShrink = 'stretchOrShrink',\n    /**\n     * The image will be resized on the specified axis to fit the content rectangle to the target text, but will not\n     * fall below the aspect ratio of the original content rectangle if the other axis is set to proportional.\n     */\n    stretchOnly = 'stretchOnly',\n    /**\n     * The image will be resized on the specified axis to fit the content rectangle to the target text and\n     * will resize the other axis to maintain the aspect ratio of the content rectangle.\n     */\n    proportional = 'proportional'\n}\n\n/**\n * The style's image metadata\n */\nexport type StyleImageMetadata = {\n    /**\n     * The ratio of pixels in the image to physical pixels on the screen\n     */\n    pixelRatio: number;\n    /**\n     * Whether the image should be interpreted as an SDF image\n     */\n    sdf: boolean;\n    /**\n     * 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.\n     */\n    stretchX?: Array<[number, number]>;\n    /**\n     * 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.\n     */\n    stretchY?: Array<[number, number]>;\n    /**\n     * 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`.\n     */\n    content?: [number, number, number, number];\n    /**\n     * If `icon-text-fit` is used in a layer with this image, this option defines constraints on the horizontal scaling of the image.\n     */\n    textFitWidth?: TextFit;\n    /**\n     * If `icon-text-fit` is used in a layer with this image, this option defines constraints on the vertical scaling of the image.\n     */\n    textFitHeight?: TextFit;\n};\n\n/**\n * the style's image, including data and metedata\n */\nexport type StyleImage = StyleImageData & StyleImageMetadata;\n\n/**\n * Where a {@link StyleImageWebGLData.renderWithWebGL} callback writes its pixels.\n */\nexport type StyleImageWebGLTarget = {\n    gl: WebGL2RenderingContext;\n    /**\n     * The icon atlas to write into. MapLibre does not bind it for you, so start with\n     * `gl.bindTexture(gl.TEXTURE_2D, texture)` or attach it to your own framebuffer.\n     */\n    texture: WebGLTexture;\n    x: number;\n    y: number;\n    width: number;\n    height: number;\n};\n\n/**\n * What a {@link StyleImageInterface} gives as its `data` when it renders itself with WebGL rather\n * than handing over an array of pixels.\n *\n * @see [Animate an icon on the GPU.](https://maplibre.org/maplibre-gl-js/docs/examples/animate-an-icon-on-the-gpu/)\n */\nexport type StyleImageWebGLData = {\n    /**\n     * Render exactly `width` x `height` premultiplied-alpha pixels at (`x`, `y`) of\n     * `target.texture`. That rectangle is the only part of the shared atlas that belongs to this\n     * image; drawing outside it corrupts the others.\n     *\n     * This is the image's counterpart to {@link CustomLayerInterface.render}, and the context\n     * arrives in the same state a custom layer's is given: cull face, active texture and the pixel\n     * store settings at their WebGL defaults, and no vertex array bound. Everything is yours to\n     * change, and MapLibre restores its own state afterwards. The scissor test is the one\n     * exception: MapLibre leaves it disabled rather than restoring it, so an image that enables\n     * it has to disable it again.\n     *\n     * Called before the first frame the image is used in, again whenever\n     * {@link StyleImageInterface.render} returns `true`, and again for each atlas holding a slot\n     * this image has never rendered into, so one change may mean several calls with different\n     * targets.\n     */\n    renderWithWebGL: (target: StyleImageWebGLTarget) => void;\n};\n\n/**\n * Interface for dynamically generated style images. This is a specification for\n * implementers to model: it is not an exported method or class.\n *\n * Images implementing this interface can be redrawn for every frame. They can be used to animate\n * icons and patterns or make them respond to user input. Style images can implement a\n * {@link StyleImageInterface.render} method. The method is called every frame and\n * can be used to update the image.\n *\n * @see [Add an animated icon to the map.](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/)\n *\n * @example\n * ```ts\n * let flashingSquare = {\n *     width: 64,\n *     height: 64,\n *     data: new Uint8Array(64 * 64 * 4),\n *\n *     onAdd: function(map) {\n *         this.map = map;\n *     },\n *\n *     render: function() {\n *         // keep repainting while the icon is on the map\n *         this.map.triggerRepaint();\n *\n *         // alternate between black and white based on the time\n *         let value = Math.round(Date.now() / 1000) % 2 === 0  ? 255 : 0;\n *\n *         // check if image needs to be changed\n *         if (value !== this.previousValue) {\n *             this.previousValue = value;\n *\n *             let bytesPerPixel = 4;\n *             for (let x = 0; x < this.width; x++) {\n *                 for (let y = 0; y < this.height; y++) {\n *                     let offset = (y * this.width + x) * bytesPerPixel;\n *                     this.data[offset + 0] = value;\n *                     this.data[offset + 1] = value;\n *                     this.data[offset + 2] = value;\n *                     this.data[offset + 3] = 255;\n *                 }\n *             }\n *\n *             // return true to indicate that the image changed\n *             return true;\n *         }\n *     }\n *  }\n *\n *  map.addImage('flashing_square', flashingSquare);\n * ```\n */\n\nexport interface StyleImageInterface {\n    width: number;\n    height: number;\n    /**\n     * The image's pixels, in the same format as `ImageData`, or a {@link StyleImageWebGLData}\n     * callback that renders them with WebGL. A WebGL image renders straight into its slot of the\n     * shared icon atlas. Nothing new is possible that pixels could not express, but an image that\n     * changes often, such as an animated icon, gets much cheaper: no CPU pixel work and no upload.\n     */\n    data: Uint8Array | Uint8ClampedArray | StyleImageWebGLData;\n    /**\n     * This method is called once before every frame where the icon will be used.\n     * The method can optionally update the image's `data` member with a new image.\n     *\n     * If the method updates the image it must return `true` to commit the change.\n     * If the method returns `false` or nothing the image is assumed to not have changed.\n     *\n     * An animated image schedules its next frame by calling {@link Map.triggerRepaint}, typically\n     * from a timer; returning `false` in between lets the map rest and fire `idle`.\n     *\n     * An image whose `data` renders with WebGL has nothing to update here; returning `true` is how\n     * it asks for {@link StyleImageWebGLData.renderWithWebGL} to be called again.\n     *\n     * If updates are infrequent it maybe easier to use {@link Map.updateImage} to update\n     * the image instead of implementing this method.\n     *\n     * @returns `true` if this method updated the image. `false` if the image was not changed.\n     */\n    render?: () => boolean;\n    /**\n     * Optional method called when the layer has been added to the Map with {@link Map.addImage}.\n     *\n     * @param map - The Map this custom layer was just added to.\n     */\n    onAdd?: (map: Map, id: string) => void;\n    /**\n     * Optional method called when the icon is removed from the map with {@link Map.removeImage}.\n     * This gives the image a chance to clean up resources and event listeners.\n     *\n     * This also fires when the WebGL context is lost, after which the same image is added back\n     * without a matching `onAdd`, so the image has to be able to build again whatever it\n     * released here.\n     */\n    onRemove?: () => void;\n}\n\nexport function isStyleImageWebGLData(data: StyleImageInterface['data']): data is StyleImageWebGLData {\n    return typeof (data as StyleImageWebGLData)?.renderWithWebGL === 'function';\n}\n\nexport function renderStyleImage(image: StyleImage): boolean {\n    const {userImage} = image;\n    if (!userImage?.render) return false;\n    const updated = userImage.render();\n    if (!updated) return false;\n\n    if (!isStyleImageWebGLData(userImage.data)) image.data.replace(new Uint8Array(userImage.data.buffer));\n    return true;\n}\n", "/**\n * @typedef {Object} PotpackBox\n * @property {number} w Box width.\n * @property {number} h Box height.\n * @property {number} [x] X coordinate in the resulting container.\n * @property {number} [y] Y coordinate in the resulting container.\n */\n\n/**\n * @typedef {Object} PotpackStats\n * @property {number} w Width of the resulting container.\n * @property {number} h Height of the resulting container.\n * @property {number} fill The space utilization value (0 to 1). Higher is better.\n */\n\n/**\n * Packs 2D rectangles into a near-square container.\n *\n * Mutates the {@link boxes} array: it's sorted (by height/width),\n * and box objects are augmented with `x`, `y` coordinates.\n *\n * @param {PotpackBox[]} boxes\n * @return {PotpackStats}\n */\nexport default function potpack(boxes) {\n\n    // calculate total box area and maximum box width\n    let area = 0;\n    let maxWidth = 0;\n\n    for (const box of boxes) {\n        area += box.w * box.h;\n        maxWidth = Math.max(maxWidth, box.w);\n    }\n\n    // sort the boxes for insertion by height, descending\n    boxes.sort((a, b) => b.h - a.h);\n\n    // aim for a squarish resulting container,\n    // slightly adjusted for sub-100% space utilization\n    const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth);\n\n    // start with a single empty space, unbounded at the bottom\n    const spaces = [{x: 0, y: 0, w: startWidth, h: Infinity}];\n\n    let width = 0;\n    let height = 0;\n\n    for (const box of boxes) {\n        // look through spaces backwards so that we check smaller spaces first\n        for (let i = spaces.length - 1; i >= 0; i--) {\n            const space = spaces[i];\n\n            // look for empty spaces that can accommodate the current box\n            if (box.w > space.w || box.h > space.h) continue;\n\n            // found the space; add the box to its top-left corner\n            // |-------|-------|\n            // |  box  |       |\n            // |_______|       |\n            // |         space |\n            // |_______________|\n            box.x = space.x;\n            box.y = space.y;\n\n            height = Math.max(height, box.y + box.h);\n            width = Math.max(width, box.x + box.w);\n\n            if (box.w === space.w && box.h === space.h) {\n                // space matches the box exactly; remove it\n                const last = spaces.pop();\n                if (last && i < spaces.length) spaces[i] = last;\n\n            } else if (box.h === space.h) {\n                // space matches the box height; update it accordingly\n                // |-------|---------------|\n                // |  box  | updated space |\n                // |_______|_______________|\n                space.x += box.w;\n                space.w -= box.w;\n\n            } else if (box.w === space.w) {\n                // space matches the box width; update it accordingly\n                // |---------------|\n                // |      box      |\n                // |_______________|\n                // | updated space |\n                // |_______________|\n                space.y += box.h;\n                space.h -= box.h;\n\n            } else {\n                // otherwise the box splits the space into two spaces\n                // |-------|-----------|\n                // |  box  | new space |\n                // |_______|___________|\n                // | updated space     |\n                // |___________________|\n                spaces.push({\n                    x: space.x + box.w,\n                    y: space.y,\n                    w: space.w - box.w,\n                    h: box.h\n                });\n                space.y += box.h;\n                space.h -= box.h;\n            }\n            break;\n        }\n    }\n\n    return {\n        w: width, // container width\n        h: height, // container height\n        fill: (area / (width * height)) || 0 // space utilization\n    };\n}\n", "/* eslint-disable key-spacing */\nimport {RGBAImage} from '../util/image.ts';\nimport {register} from '../util/web_worker_transfer.ts';\nimport {isStyleImageWebGLData} from '../style/style_image.ts';\nimport potpack from 'potpack';\n\nimport type {TextFit} from '../style/style_image.ts';\nimport type {StyleImage} from '../style/style_image.ts';\nimport type {ImageManager} from './image_manager.ts';\nimport type {Texture} from '../webgl/texture.ts';\nimport type {Rect} from './glyph_atlas.ts';\nimport type {GetImagesResponse} from '../util/actor_messages.ts';\n\nconst IMAGE_PADDING: number = 1;\nexport {IMAGE_PADDING};\n\nexport class ImagePosition {\n    paddedRect: Rect;\n    pixelRatio: number;\n    version: number;\n    needsFirstWebGLRender: boolean;\n    stretchY: Array<[number, number]>;\n    stretchX: Array<[number, number]>;\n    content: [number, number, number, number];\n    textFitWidth: TextFit;\n    textFitHeight: TextFit;\n\n    constructor(paddedRect: Rect, {\n        pixelRatio,\n        version,\n        isWebGLImage = false,\n        stretchX,\n        stretchY,\n        content,\n        textFitWidth,\n        textFitHeight\n    }: StyleImage) {\n        this.paddedRect = paddedRect;\n        this.pixelRatio = pixelRatio;\n        this.stretchX = stretchX;\n        this.stretchY = stretchY;\n        this.content = content;\n        this.version = version;\n        this.needsFirstWebGLRender = isWebGLImage;\n        this.textFitWidth = textFitWidth;\n        this.textFitHeight = textFitHeight;\n    }\n\n    get tl(): [number, number] {\n        return [\n            this.paddedRect.x + IMAGE_PADDING,\n            this.paddedRect.y + IMAGE_PADDING\n        ];\n    }\n\n    get br(): [number, number] {\n        return [\n            this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING,\n            this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING\n        ];\n    }\n\n    get tlbr(): number[] {\n        return this.tl.concat(this.br);\n    }\n\n    get displaySize(): [number, number] {\n        return [\n            (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio,\n            (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio\n        ];\n    }\n}\n\n/**\n * A single tile's packed copy of the icons and patterns its features reference, built in the\n * worker so that the symbol layout can bake the positions within it straight into the vertex\n * buffers. Each tile owns one, along with the texture it is uploaded to - as opposed to\n * {@link ImageManager}, which owns the images of the whole style.\n * @internal\n */\nexport class ImageAtlas {\n    image: RGBAImage;\n    iconPositions: Record<string, ImagePosition>;\n    patternPositions: Record<string, ImagePosition>;\n    haveRenderCallbacks: string[];\n    uploaded: boolean;\n    /**\n     * The {@link ImageManager.updateVersion} this atlas' texture was last patched against.\n     * Starts out at `-1` so that a freshly transferred atlas always patches once: images may have\n     * been updated between the moment the worker snapshotted them and the moment the atlas arrives.\n     */\n    patchedUpdateVersion: number;\n\n    constructor(icons: GetImagesResponse, patterns: GetImagesResponse) {\n        const iconPositions = {}, patternPositions = {};\n        this.haveRenderCallbacks = [];\n        this.patchedUpdateVersion = -1;\n\n        const bins = [];\n\n        this.addImages(icons, iconPositions, bins);\n        this.addImages(patterns, patternPositions, bins);\n\n        const {w, h} = potpack(bins);\n        const image = new RGBAImage({width: w || 1, height: h || 1});\n\n        for (const id in icons) {\n            const src = icons[id];\n            if (src.isWebGLImage) continue;\n            const bin = iconPositions[id].paddedRect;\n            RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING}, src.data);\n        }\n\n        for (const id in patterns) {\n            const src = patterns[id];\n            const bin = patternPositions[id].paddedRect;\n            const x = bin.x + IMAGE_PADDING,\n                y = bin.y + IMAGE_PADDING,\n                w = src.data.width,\n                h = src.data.height;\n\n            RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x, y}, src.data);\n            // Add 1 pixel wrapped padding on each side of the image.\n            RGBAImage.copy(src.data, image, {x: 0, y: h - 1}, {x, y: y - 1}, {width: w, height: 1}); // T\n            RGBAImage.copy(src.data, image, {x: 0, y:     0}, {x, y: y + h}, {width: w, height: 1}); // B\n            RGBAImage.copy(src.data, image, {x: w - 1, y: 0}, {x: x - 1, y}, {width: 1, height: h}); // L\n            RGBAImage.copy(src.data, image, {x: 0,     y: 0}, {x: x + w, y}, {width: 1, height: h}); // R\n        }\n\n        this.image = image;\n        this.iconPositions = iconPositions;\n        this.patternPositions = patternPositions;\n    }\n\n    addImages(images: {[_: string]: StyleImage}, positions: {[_: string]: ImagePosition}, bins: Rect[]): void {\n        for (const id in images) {\n            const src = images[id];\n            const bin = {\n                x: 0,\n                y: 0,\n                w: src.data.width + 2 * IMAGE_PADDING,\n                h: src.data.height + 2 * IMAGE_PADDING,\n            };\n            bins.push(bin);\n            positions[id] = new ImagePosition(bin, src);\n\n            if (src.hasRenderCallback) {\n                this.haveRenderCallbacks.push(id);\n            }\n        }\n    }\n\n    /**\n     * Brings this atlas' texture back in sync with the images it was built from, re-uploading the\n     * ones that were replaced in the meantime.\n     *\n     * This runs for every in-view tile on every frame, so the common case of nothing having\n     * changed has to cost nothing: a single comparison against {@link ImageManager.updateVersion}\n     * ends the call. When something did change, only the images this atlas actually holds are\n     * looked at - a handful per tile - and {@link ImageAtlas.patchUpdatedImage} then skips the\n     * ones whose version still matches, leaving just the genuinely stale ones to upload.\n     *\n     * The render callbacks are dispatched first because they may update images themselves, and\n     * those updates have to be part of the version this call catches up with - otherwise an\n     * animated image would always be uploaded a frame late.\n     */\n    patchUpdatedImages(imageManager: ImageManager, texture: Texture): void {\n        imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks);\n\n        if (this.patchedUpdateVersion === imageManager.updateVersion) return;\n        this.patchedUpdateVersion = imageManager.updateVersion;\n\n        for (const name in this.iconPositions) {\n            this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture);\n        }\n        for (const name in this.patternPositions) {\n            this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture);\n        }\n    }\n\n    patchUpdatedImage(position: ImagePosition, image: StyleImage, texture: Texture): void {\n        if (!position || !image) return;\n\n        if (!position.needsFirstWebGLRender && position.version === image.version) return;\n\n        position.needsFirstWebGLRender = false;\n        position.version = image.version;\n        const [x, y] = position.tl;\n        const data = image.userImage?.data;\n        if (!isStyleImageWebGLData(data)) {\n            texture.update(image.data, undefined, {x, y});\n            return;\n        }\n\n        const {width, height} = image.data;\n        texture.context.setCustomLayerDefaults();\n        data.renderWithWebGL({gl: texture.context.gl, texture: texture.texture, x, y, width, height});\n        texture.context.setDirty();\n    }\n\n}\n\nregister('ImagePosition', ImagePosition);\nregister('ImageAtlas', ImageAtlas);\n", "import {\n    codePointHasUprightVerticalOrientation\n} from '../util/unicode_properties.g.ts';\nimport {\n    charIsWhitespace,\n    charIsSymbolOrPunctuation,\n    charHasRotatedVerticalOrientation,\n    charInComplexShapingScript,\n    charInRTLScript,\n    stringContainsRTLText\n} from '../util/script_detection.ts';\nimport {rtlWorkerPlugin} from '../source/rtl_text_plugin_worker.ts';\nimport {processBidirectionalText, processStyledBidirectionalText} from './bidi.ts';\nimport {isCluster} from '../util/graphemes.ts';\nimport {verticalizedCharacterMap} from '../util/verticalize_punctuation.ts';\nimport ONE_EM from './one_em.ts';\nimport {TaggedString, type SectionOptions, type TextSectionOptions, type ImageSectionOptions} from './tagged_string.ts';\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf.ts';\nimport {TextFit} from '../style/style_image.ts';\nimport {IMAGE_PADDING} from '../render/image_atlas.ts';\n\nimport type {ImagePosition} from '../render/image_atlas.ts';\nimport type {StyleGlyph, GlyphMap, GlyphMetrics} from '../style/style_glyph.ts';\nimport type {Rect, GlyphPosition, GlyphPositions} from '../render/glyph_atlas.ts';\nimport type {Formatted, VerticalAlign} from '@maplibre/maplibre-gl-style-spec';\n\nenum WritingMode {\n    none = 0,\n    horizontal = 1,\n    vertical = 2,\n    horizontalOnly = 3\n}\n\nconst SHAPING_DEFAULT_OFFSET = -17;\nexport {shapeText, shapeIcon, applyTextFit, fitIconToText, getAnchorAlignment, mayUseVerticalGlyph, WritingMode, SHAPING_DEFAULT_OFFSET};\n\n// The position of a glyph relative to the text's anchor point.\nexport type PositionedGlyph = {\n    /**\n     * The first codepoint of {@link grapheme}. Kept because it has always been here; it cannot name\n     * a cluster of several codepoints, so prefer `grapheme`.\n     */\n    glyph: number;\n    /**\n     * What this glyph draws: a grapheme cluster, which is usually one character but is a letter with\n     * its marks where the two are written as one shape.\n     */\n    grapheme: string;\n    imageName: string | null;\n    x: number;\n    y: number;\n    vertical: boolean;\n    scale: number;\n    fontStack: string;\n    sectionIndex: number;\n    metrics: GlyphMetrics;\n    rect: Rect | null;\n};\n\nexport type PositionedLine = {\n    positionedGlyphs: PositionedGlyph[];\n    lineOffset: number;\n};\n\n// A collection of positioned glyphs and some metadata\nexport type Shaping = {\n    positionedLines: PositionedLine[];\n    top: number;\n    bottom: number;\n    left: number;\n    right: number;\n    writingMode: WritingMode.horizontal | WritingMode.vertical;\n    text: string;\n    iconsInText: boolean;\n    verticalizable: boolean;\n};\n\ntype ShapingSectionAttributes = {\n    rect: Rect | null;\n    metrics: GlyphMetrics;\n    baselineOffset: number;\n    imageOffset?: number;\n};\n\ntype LineShapingSize = {\n    verticalLineContentWidth: number;\n    horizontalLineContentHeight: number;\n};\n\nfunction isEmpty(positionedLines: PositionedLine[]) {\n    for (const line of positionedLines) {\n        if (line.positionedGlyphs.length !== 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nexport type SymbolAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\nexport type TextJustify = 'left' | 'center' | 'right';\n\nfunction breakLines(input: TaggedString, lineBreakPoints: number[]): TaggedString[] {\n    const lines = [];\n    let start = 0;\n    for (const lineBreak of lineBreakPoints) {\n        lines.push(input.substring(start, lineBreak));\n        start = lineBreak;\n    }\n\n    if (start < input.length()) {\n        lines.push(input.substring(start, input.length()));\n    }\n    return lines;\n}\n\n/** A character that is written on another one rather than beside it. */\nconst COMBINING_MARK = /^\\p{gc=M}$/u;\n\n/**\n * Puts the marks written on a letter back after the letter, and returns the new order as indices\n * into `chars`.\n *\n * This is rule L3 of the Unicode Bidirectional Algorithm. Reversing a right-to-left run leaves each\n * mark before its letter, and next to the letter before that -- so undoing it is what lets a letter\n * and its marks be one grapheme cluster again.\n *\n * Only marks followed by a right-to-left letter move; in a left-to-right run they already follow\n * their base. They come back in writing order, `m2 m1 base` to `base m1 m2`, since any other order\n * is a different cluster from the one the tile asked for a glyph for.\n */\nfunction combiningMarksAfterTheirBase(chars: string[]): number[] {\n    const order: number[] = [];\n\n    let i = 0;\n    while (i < chars.length) {\n        if (!COMBINING_MARK.test(chars[i])) {\n            order.push(i);\n            i++;\n            continue;\n        }\n\n        let end = i;\n        while (end < chars.length && COMBINING_MARK.test(chars[end])) end++;\n\n        const base = chars[end];\n        if (base !== undefined && charInRTLScript(base.codePointAt(0))) {\n            order.push(end);\n            for (let mark = end - 1; mark >= i; mark--) order.push(mark);\n            i = end + 1;\n        } else {\n            for (let mark = i; mark < end; mark++) order.push(mark);\n            i = end;\n        }\n    }\n\n    return order;\n}\n\n/**\n * Spreads each cluster's style section across the code units it takes, which is what a text plugin\n * counts in.\n */\nfunction sectionForEachCodeUnit(input: TaggedString): number[] {\n    const sectionIndex: number[] = [];\n    let i = 0;\n    for (const grapheme of input.graphemes()) {\n        sectionIndex.push(...Array(grapheme.length).fill(input.sectionIndex[i]));\n        i++;\n    }\n    return sectionIndex;\n}\n\n/**\n * Puts a label that reads in both directions into the order it is drawn, and breaks it into lines.\n *\n * The bidirectional algorithm works in code units rather than in the graphemes the rest of layout\n * counts in, so the line breaks are converted on the way in and the sections on the way out. A\n * plugin registered through the deprecated {@link setRTLTextPlugin} is used in place of the built-in\n * implementation, so that a map relying on one keeps the behaviour it had.\n */\nfunction bidiLines(logicalInput: TaggedString, lineBreaks: number[]): TaggedString[] {\n    const codeUnitBreaks = lineBreaks.map(index => logicalInput.toCodeUnitIndex(index));\n    const plugin = rtlWorkerPlugin.isParsed() ? rtlWorkerPlugin : null;\n\n    if (logicalInput.sections.length === 1) {\n        if (plugin) {\n            return plugin.processBidirectionalText(logicalInput.toString(), codeUnitBreaks)\n                .map(line => taggedLineFromPlugin(line, logicalInput.sections, [...line].map(() => 0)));\n        }\n        return processBidirectionalText(logicalInput.toString(), codeUnitBreaks)\n            .map(line => taggedLine([...line], logicalInput.sections, [...line].map(() => 0)));\n    }\n\n    const sectionForCodeUnit = sectionForEachCodeUnit(logicalInput);\n    if (plugin) {\n        return plugin.processStyledBidirectionalText(logicalInput.text, sectionForCodeUnit, codeUnitBreaks)\n            .map(([line, sections]) => taggedLineFromPlugin(line, logicalInput.sections, sections));\n    }\n    return processStyledBidirectionalText(logicalInput.text, sectionForCodeUnit, codeUnitBreaks)\n        .map(([line, sections]) => {\n            const chars = [...line];\n            return taggedLine(chars, logicalInput.sections, codeUnitOfEachCharacter(chars).map(at => sections[at] ?? 0));\n        });\n}\n\n/**\n * Builds a line out of what a text plugin returned: the text in reading order, and the section of\n * each code unit. A cluster belongs to the section its first character does.\n */\n/**\n * Builds a line of a label from text that is already in the order it is drawn.\n *\n * The sections arrive one per code unit, as the bidirectional algorithm counts, and are handed on\n * one per grapheme cluster, as the rest of layout counts.\n */\nfunction taggedLine(chars: string[], sections: SectionOptions[], sectionOfChar: number[]): TaggedString {\n    const tagged = new TaggedString(chars.join(''), sections, []);\n\n    let at = 0;\n    for (const grapheme of tagged.graphemes()) {\n        tagged.sectionIndex.push(sectionOfChar[at] ?? 0);\n        at += [...grapheme].length;\n    }\n\n    return tagged;\n}\n\n/** The code unit each character of a line starts at. */\nfunction codeUnitOfEachCharacter(chars: string[]): number[] {\n    const offsets: number[] = [];\n    let codeUnit = 0;\n    for (const char of chars) {\n        offsets.push(codeUnit);\n        codeUnit += char.length;\n    }\n    return offsets;\n}\n\n/**\n * Builds a line from what a plugin registered through the deprecated `setRTLTextPlugin` returned.\n *\n * A plugin reorders one code point at a time, as ICU does, which leaves the marks of a right-to-left\n * run before the letter they are written on, so rule L3 has to be applied here. The built-in\n * implementation reorders whole grapheme clusters and needs none of this.\n */\nfunction taggedLineFromPlugin(\n    line: string,\n    sections: SectionOptions[],\n    sectionForCodeUnit: number[]\n): TaggedString {\n    const chars = [...line];\n    const codeUnitOf = codeUnitOfEachCharacter(chars);\n    const order = combiningMarksAfterTheirBase(chars);\n\n    return taggedLine(\n        order.map(index => chars[index]),\n        sections,\n        order.map(index => sectionForCodeUnit[codeUnitOf[index]] ?? 0));\n}\n\nfunction shapeText(\n    text: Formatted,\n    glyphMap: GlyphMap,\n    glyphPositions: GlyphPositions,\n    imagePositions: Record<string, ImagePosition>,\n    defaultFontStack: string,\n    maxWidth: number,\n    lineHeight: number,\n    textAnchor: SymbolAnchor,\n    textJustify: TextJustify,\n    spacing: number,\n    translate: [number, number],\n    writingMode: WritingMode.horizontal | WritingMode.vertical,\n    allowVerticalPlacement: boolean,\n    layoutTextSize: number,\n    layoutTextSizeThisZoom: number\n): Shaping | false {\n    const logicalInput = TaggedString.fromFeature(text, defaultFontStack, writingMode === WritingMode.vertical, glyphMap);\n\n    const lineBreaks = logicalInput.determineLineBreaks(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);\n    const lines = stringContainsRTLText(logicalInput.text) ?\n        bidiLines(logicalInput, lineBreaks) :\n        breakLines(logicalInput, lineBreaks);\n\n    const positionedLines = [];\n    const shaping = {\n        positionedLines,\n        text: logicalInput.toString(),\n        top: translate[1],\n        bottom: translate[1],\n        left: translate[0],\n        right: translate[0],\n        writingMode,\n        iconsInText: false,\n        verticalizable: false\n    };\n\n    shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom);\n    if (isEmpty(positionedLines)) return false;\n\n    return shaping;\n}\n\nfunction getAnchorAlignment(anchor: SymbolAnchor): {horizontalAlign: number; verticalAlign: number} {\n    let horizontalAlign = 0.5, verticalAlign = 0.5;\n\n    switch (anchor) {\n        case 'right':\n        case 'top-right':\n        case 'bottom-right':\n            horizontalAlign = 1;\n            break;\n        case 'left':\n        case 'top-left':\n        case 'bottom-left':\n            horizontalAlign = 0;\n            break;\n    }\n\n    switch (anchor) {\n        case 'bottom':\n        case 'bottom-right':\n        case 'bottom-left':\n            verticalAlign = 1;\n            break;\n        case 'top':\n        case 'top-right':\n        case 'top-left':\n            verticalAlign = 0;\n            break;\n    }\n\n    return {horizontalAlign, verticalAlign};\n}\n\nfunction calculateLineContentSize(\n    imagePositions: Record<string, ImagePosition>,\n    line: TaggedString,\n    layoutTextSizeFactor: number\n): LineShapingSize {\n    const maxGlyphSize = line.getMaxScale() * ONE_EM;\n    const {maxImageWidth, maxImageHeight} = line.getMaxImageSize(imagePositions);\n\n    const horizontalLineContentHeight = Math.max(maxGlyphSize, maxImageHeight * layoutTextSizeFactor);\n    const verticalLineContentWidth = Math.max(maxGlyphSize, maxImageWidth * layoutTextSizeFactor);\n\n    return {verticalLineContentWidth, horizontalLineContentHeight};\n}\n\nfunction getVerticalAlignFactor(\n    verticalAlign: VerticalAlign\n) {\n    switch (verticalAlign) {\n        case 'top':\n            return 0;\n        case 'center':\n            return 0.5;\n        default:\n            return 1;\n    }\n}\n\nfunction getRectAndMetrics(\n    glyphPosition: GlyphPosition,\n    glyph: StyleGlyph\n): GlyphPosition | null {\n    if (glyphPosition?.rect) {\n        return glyphPosition;\n    }\n\n    if (!glyph) return null;\n\n    const metrics = glyph.metrics;\n    return {rect: null, metrics};\n}\n\nfunction isLineVertical(\n    writingMode: WritingMode.horizontal | WritingMode.vertical,\n    allowVerticalPlacement: boolean,\n    codePoint: number\n): boolean {\n    return !(writingMode === WritingMode.horizontal ||\n        // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled.\n        (!allowVerticalPlacement && !codePointHasUprightVerticalOrientation(codePoint)) ||\n        // If vertical placement is enabled, don't verticalize glyphs that\n        // are from complex text layout script, or whitespaces.\n        (allowVerticalPlacement && (charIsWhitespace(codePoint) || charInComplexShapingScript(codePoint))));\n}\n\n/** Returns whether the codepoint is a decimal digit of any script (`\\p{Nd}`). */\nfunction charIsDecimalDigit(codePoint: number): boolean {\n    return /\\p{Nd}/u.test(String.fromCodePoint(codePoint));\n}\n\n/** Returns whether the codepoint is an uppercase letter of any script (`\\p{Lu}`). */\nfunction charIsUppercaseLetter(codePoint: number): boolean {\n    return /\\p{Lu}/u.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * Uppercase runs longer than this are words (e.g. “ISHIKAWA” in a dual name),\n * which read better lying along the line; shorter runs are codes (“JR”, “A1”).\n */\nconst MAX_UPRIGHT_LETTER_RUN = 3;\n\n/**\n * Returns whether a run qualifies for upright treatment: numbers of any length,\n * optionally combined with symbols (“21”, “1-2”), and codes of up to\n * {@link MAX_UPRIGHT_LETTER_RUN} uppercase letters and digits (“JR”, “A1”).\n */\nfunction runIsUpright(run: number[]): boolean {\n    const isNumber = run.some(charIsDecimalDigit) &&\n        run.every(codePoint => charIsDecimalDigit(codePoint) || charIsSymbolOrPunctuation(codePoint));\n    const isShortUppercaseCode = run.length <= MAX_UPRIGHT_LETTER_RUN &&\n        run.every(codePoint => charIsUppercaseLetter(codePoint) || charIsDecimalDigit(codePoint));\n    return isNumber || isShortUppercaseCode;\n}\n\n/**\n * Returns whether a letter or digit in a qualifying run is drawn upright.\n * Punctuation and symbols are handled separately by\n * {@link verticalizeSurroundedPunctuation}; complex-shaping scripts keep\n * following the line.\n */\nfunction charIsUprightInRun(codePoint: number): boolean {\n    return (charIsDecimalDigit(codePoint) || charIsUppercaseLetter(codePoint)) &&\n        !charInComplexShapingScript(codePoint);\n}\n\n/**\n * Checks whether a cluster's first codepoint may need a vertical glyph.\n * Line labels determine the final orientation from the surrounding run.\n */\nfunction mayUseVerticalGlyph(codePoint: number, allowVerticalPlacement: boolean): boolean {\n    if (allowVerticalPlacement) return isLineVertical(WritingMode.vertical, true, codePoint);\n    return !charHasRotatedVerticalOrientation(codePoint) ||\n        charIsUprightInRun(codePoint) || charIsSymbolOrPunctuation(codePoint);\n}\n\n/**\n * Marks punctuation surrounded by upright characters as upright. Uses a compatibility\n * character when the font has no vertical alternate.\n *\n * @returns whether any character in `chars` was replaced\n */\nfunction verticalizeSurroundedPunctuation(chars: string[], verticals: boolean[], verticalForms: boolean[]): boolean {\n    let replaced = false;\n    for (let i = 0; i < chars.length; i++) {\n        if (verticals[i]) continue;\n        const verticalizedChar = verticalizedCharacterMap[chars[i]];\n        if (!verticalizedChar) continue;\n        if ((i === 0 || verticals[i - 1]) && (i === chars.length - 1 || verticals[i + 1])) {\n            verticals[i] = true;\n            if (verticalForms[i]) continue;\n\n            chars[i] = verticalizedChar;\n            replaced = true;\n        }\n    }\n    return replaced;\n}\n\n/** Checks the adjacent run across whitespace for sideways text, excluding upright numbers and codes. */\nfunction hasSidewaysTextBeside(codePoints: number[], index: number, step: -1 | 1): boolean {\n    while (index >= 0 && index < codePoints.length && charIsWhitespace(codePoints[index])) index += step;\n    const run: number[] = [];\n    while (index >= 0 && index < codePoints.length &&\n        !codePointHasUprightVerticalOrientation(codePoints[index]) && !charIsWhitespace(codePoints[index])) {\n        run.push(codePoints[index]);\n        index += step;\n    }\n    return !runIsUpright(run) && !run.every(charIsSymbolOrPunctuation) && run.some(charHasRotatedVerticalOrientation);\n}\n\n/**\n * Returns an upright flag for each grapheme cluster and applies vertical punctuation to `line`.\n * Runs use each cluster's first codepoint and end at upright characters, whitespace or inline images.\n * Font alternates do not split runs. Runs are reclassified after unused alternates fall back\n * to compatibility characters.\n */\nfunction determineLineVerticals(line: TaggedString, glyphMap: GlyphMap): boolean[] {\n    const chars = line.graphemes().slice();\n    const codePoints = chars.map(char => char.codePointAt(0));\n    const verticalForms = chars.map((char, index) => {\n        const section = line.getSection(index);\n        return 'fontStack' in section && !!glyphMap[section.fontStack]?.vertical?.[char];\n    });\n    const verticals = codePoints.map(codePointHasUprightVerticalOrientation);\n\n    const isRunCharacter = (i: number): boolean =>\n        !verticals[i] && !charIsWhitespace(codePoints[i]) && !('imageName' in line.getSection(i));\n\n    for (let start = 0; start < codePoints.length; start++) {\n        if (!isRunCharacter(start)) continue;\n        let end = start;\n        while (end + 1 < codePoints.length && isRunCharacter(end + 1)) end++;\n\n        const run = codePoints.slice(start, end + 1);\n        const upright = runIsUpright(run);\n        const punctuationOnly = run.every(charIsSymbolOrPunctuation);\n        const besideSidewaysText = punctuationOnly &&\n            (hasSidewaysTextBeside(codePoints, start - 1, -1) || hasSidewaysTextBeside(codePoints, end + 1, 1));\n        const sideways = !upright && run.some(charHasRotatedVerticalOrientation);\n        for (let i = start; i <= end; i++) {\n            verticals[i] = (upright && charIsUprightInRun(codePoints[i])) ||\n                (verticalForms[i] && !besideSidewaysText &&\n                    (punctuationOnly || (!sideways && !charHasRotatedVerticalOrientation(codePoints[i]))));\n        }\n        start = end;\n    }\n\n    if (verticalForms.some((form, index) => form && !verticals[index])) {\n        const previousText = line.text;\n        line.verticalizePunctuation(glyphMap, verticals);\n        if (line.text !== previousText) return determineLineVerticals(line, glyphMap);\n    }\n\n    if (verticalizeSurroundedPunctuation(chars, verticals, verticalForms)) {\n        line.text = chars.join('');\n        line.cachedGraphemes = chars;\n    }\n\n    return verticals;\n}\n\n/**\n * Places every glyph of every line, filling in `shaping`.\n *\n * A cluster is drawn as one shape where a font file covers it, and a codepoint at a time where none\n * does -- which is what a style declaring no `font-faces` keeps doing.\n */\nfunction shapeLines(shaping: Shaping,\n    glyphMap: GlyphMap,\n    glyphPositions: GlyphPositions,\n    imagePositions: Record<string, ImagePosition>,\n    lines: TaggedString[],\n    lineHeight: number,\n    textAnchor: SymbolAnchor,\n    textJustify: TextJustify,\n    writingMode: WritingMode.horizontal | WritingMode.vertical,\n    spacing: number,\n    allowVerticalPlacement: boolean,\n    layoutTextSizeThisZoom: number) {\n\n    let x = 0;\n    let y = 0;\n\n    let maxLineLength = 0;\n    let maxLineHeight = 0;\n\n    const justify =\n        textJustify === 'right' ? 1 :\n            textJustify === 'left' ? 0 : 0.5;\n    const layoutTextSizeFactor = ONE_EM / layoutTextSizeThisZoom;\n\n    let lineIndex = 0;\n    for (const line of lines) {\n        line.trim();\n\n        const lineMaxScale = line.getMaxScale();\n        const positionedLine = {positionedGlyphs: [], lineOffset: 0};\n        shaping.positionedLines[lineIndex] = positionedLine;\n        const positionedGlyphs = positionedLine.positionedGlyphs;\n        let imageOffset = 0.0;\n\n        if (!line.length()) {\n            y += lineHeight; // Still need a line feed after empty line\n            ++lineIndex;\n            continue;\n        }\n\n        const lineShapingSize = calculateLineContentSize(imagePositions, line, layoutTextSizeFactor);\n        const lineVerticals = writingMode === WritingMode.vertical && !allowVerticalPlacement ?\n            determineLineVerticals(line, glyphMap) : null;\n\n        const graphemes = line.graphemes();\n        for (let i = 0; i < graphemes.length; i++) {\n            const section = line.getSection(i);\n            const grapheme = graphemes[i];\n            const codePoint = grapheme.codePointAt(0);\n            const vertical = lineVerticals ? lineVerticals[i] : isLineVertical(writingMode, allowVerticalPlacement, codePoint);\n\n            const keys = 'fontStack' in section && isCluster(grapheme) && !glyphMap[section.fontStack]?.default?.[grapheme] ?\n                [...grapheme] :\n                [grapheme];\n\n            for (const key of keys) {\n                const positionedGlyph: PositionedGlyph = {\n                    glyph: key.codePointAt(0),\n                    grapheme: key,\n                    imageName: null,\n                    x,\n                    y: y + SHAPING_DEFAULT_OFFSET,\n                    vertical,\n                    scale: 1,\n                    fontStack: '',\n                    sectionIndex: line.getSectionIndex(i),\n                    metrics: null,\n                    rect: null\n                };\n\n                let sectionAttributes: ShapingSectionAttributes;\n                if ('fontStack' in section) {\n                    sectionAttributes = shapeTextSection(section, key, vertical, lineShapingSize, glyphMap, glyphPositions);\n                    if (!sectionAttributes) continue;\n                    positionedGlyph.fontStack = section.fontStack;\n                } else {\n                    shaping.iconsInText = true;\n                    // If needed, allow to set scale factor for an image using\n                    // alias \"image-scale\" that could be alias for \"font-scale\"\n                    // when FormattedSection is an image section.\n                    section.scale *= layoutTextSizeFactor;\n\n                    sectionAttributes = shapeImageSection(section, vertical, lineMaxScale, lineShapingSize, imagePositions);\n                    if (!sectionAttributes) continue;\n                    imageOffset = Math.max(imageOffset, sectionAttributes.imageOffset);\n                    positionedGlyph.imageName = section.imageName;\n                }\n\n                const {rect, metrics, baselineOffset} = sectionAttributes;\n                positionedGlyph.y += baselineOffset;\n                positionedGlyph.scale = section.scale;\n                positionedGlyph.metrics = metrics;\n                positionedGlyph.rect = rect;\n                positionedGlyphs.push(positionedGlyph);\n\n                if (!vertical) {\n                    x += metrics.advance * section.scale + spacing;\n                } else {\n                    shaping.verticalizable = true;\n                    const verticalAdvance = 'imageName' in section ? metrics.advance : ONE_EM;\n                    x += verticalAdvance * section.scale + spacing;\n                }\n            }\n        }\n\n        // Only justify if we placed at least one glyph\n        if (positionedGlyphs.length !== 0) {\n            const lineLength = x - spacing;\n            maxLineLength = Math.max(lineLength, maxLineLength);\n            justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify);\n        }\n\n        x = 0;\n        const maxLineOffset = (lineMaxScale - 1) * ONE_EM;\n        positionedLine.lineOffset = Math.max(imageOffset, maxLineOffset);\n        const currentLineHeight = lineHeight * lineMaxScale + imageOffset;\n        y += currentLineHeight;\n        maxLineHeight = Math.max(currentLineHeight, maxLineHeight);\n        ++lineIndex;\n    }\n\n    // Calculate the bounding box and justify / align text block.\n    const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor);\n    align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, y, lines.length);\n\n    // Calculate the bounding box\n    // shaping.top & shaping.left already include text offset (text-radial-offset or text-offset)\n    shaping.top += -verticalAlign * y;\n    shaping.bottom = shaping.top + y;\n    shaping.left += -horizontalAlign * maxLineLength;\n    shaping.right = shaping.left + maxLineLength;\n}\n\nfunction shapeTextSection(\n    section: TextSectionOptions,\n    key: string,\n    vertical: boolean,\n    lineShapingSize: LineShapingSize,\n    glyphMap: GlyphMap,\n    glyphPositions: GlyphPositions,\n): ShapingSectionAttributes | null {\n    const variant = vertical && glyphMap[section.fontStack]?.vertical?.[key] ? 'vertical' : 'default';\n    const glyphPosition = glyphPositions[section.fontStack]?.[variant]?.[key];\n    const glyph = glyphMap[section.fontStack]?.[variant]?.[key];\n    const rectAndMetrics = getRectAndMetrics(glyphPosition, glyph);\n\n    if (rectAndMetrics === null) return null;\n\n    let baselineOffset: number;\n    if (vertical) {\n        baselineOffset = lineShapingSize.verticalLineContentWidth - section.scale * ONE_EM;\n    } else {\n        const verticalAlignFactor = getVerticalAlignFactor(section.verticalAlign);\n        baselineOffset = (lineShapingSize.horizontalLineContentHeight - section.scale * ONE_EM) * verticalAlignFactor;\n    }\n\n    return {\n        rect: rectAndMetrics.rect,\n        metrics: rectAndMetrics.metrics,\n        baselineOffset\n    };\n}\n\nfunction shapeImageSection(\n    section: ImageSectionOptions,\n    vertical: boolean,\n    lineMaxScale: number,\n    lineShapingSize: LineShapingSize,\n    imagePositions: Record<string, ImagePosition>,\n): ShapingSectionAttributes | null {\n    const imagePosition = imagePositions[section.imageName];\n    if (!imagePosition) return null;\n    const rect = imagePosition.paddedRect;\n    const size = imagePosition.displaySize;\n\n    const metrics = {width: size[0],\n        height: size[1],\n        left: IMAGE_PADDING,\n        top: -GLYPH_PBF_BORDER,\n        advance: vertical ? size[1] : size[0]};\n\n    let baselineOffset: number;\n    if (vertical) {\n        baselineOffset = lineShapingSize.verticalLineContentWidth - size[1] * section.scale;\n    } else {\n        const verticalAlignFactor = getVerticalAlignFactor(section.verticalAlign);\n        baselineOffset = (lineShapingSize.horizontalLineContentHeight - size[1] * section.scale) * verticalAlignFactor;\n    }\n\n    // Difference between height of an image and one EM at max line scale.\n    // Pushes current line down if an image size is over 1 EM at max line scale.\n    const imageOffset = (vertical ? size[0] : size[1]) * section.scale - ONE_EM * lineMaxScale;\n\n    return {rect, metrics, baselineOffset, imageOffset};\n}\n\n// justify right = 1, left = 0, center = 0.5\nfunction justifyLine(positionedGlyphs: PositionedGlyph[],\n    start: number,\n    end: number,\n    justify: 1 | 0 | 0.5) {\n    if (justify === 0)\n        return;\n\n    const lastPositionedGlyph = positionedGlyphs[end];\n    const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale;\n    const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify;\n\n    for (let j = start; j <= end; j++) {\n        positionedGlyphs[j].x -= lineIndent;\n    }\n}\n\n/**\n * Aligns the lines based on horizontal and vertical alignment.\n */\nfunction align(positionedLines: PositionedLine[],\n    justify: number,\n    horizontalAlign: number,\n    verticalAlign: number,\n    maxLineLength: number,\n    maxLineHeight: number,\n    lineHeight: number,\n    blockHeight: number,\n    lineCount: number) {\n    const shiftX = (justify - horizontalAlign) * maxLineLength;\n    let shiftY = 0;\n\n    if (maxLineHeight !== lineHeight) {\n        shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET;\n    } else {\n        shiftY = -verticalAlign * lineCount * lineHeight + 0.5 * lineHeight;\n    }\n\n    for (const line of positionedLines) {\n        for (const positionedGlyph of line.positionedGlyphs) {\n            positionedGlyph.x += shiftX;\n            positionedGlyph.y += shiftY;\n        }\n    }\n}\n\nexport type PositionedIcon = {\n    image: ImagePosition;\n    top: number;\n    bottom: number;\n    left: number;\n    right: number;\n    collisionPadding?: [number, number, number, number];\n};\n\nfunction shapeIcon(\n    image: ImagePosition,\n    iconOffset: [number, number],\n    iconAnchor: SymbolAnchor\n): PositionedIcon {\n    const {horizontalAlign, verticalAlign} = getAnchorAlignment(iconAnchor);\n    const dx = iconOffset[0];\n    const dy = iconOffset[1];\n    const x1 = dx - image.displaySize[0] * horizontalAlign;\n    const x2 = x1 + image.displaySize[0];\n    const y1 = dy - image.displaySize[1] * verticalAlign;\n    const y2 = y1 + image.displaySize[1];\n    return {image, top: y1, bottom: y2, left: x1, right: x2};\n}\n\nexport type Box = {\n    x1: number;\n    y1: number;\n    x2: number;\n    y2: number;\n};\n\n/**\n * Called after a PositionedIcon has already been run through fitIconToText,\n * but needs further adjustment to apply textFitWidth and textFitHeight.\n * @param shapedIcon - The icon that will be adjusted.\n * @returns Extents of the shapedIcon with text fit adjustments if necessary.\n */\nfunction applyTextFit(shapedIcon: PositionedIcon): Box {\n    // Assume shapedIcon.image is set or this wouldn't be called.\n    // Size of the icon after it was adjusted using stretchX and Y\n    let iconLeft = shapedIcon.left;\n    let iconTop = shapedIcon.top;\n    let iconWidth = shapedIcon.right - iconLeft;\n    let iconHeight = shapedIcon.bottom - iconTop;\n    // Size of the original content area\n    const contentWidth = shapedIcon.image.content[2] - shapedIcon.image.content[0];\n    const contentHeight = shapedIcon.image.content[3] - shapedIcon.image.content[1];\n    const textFitWidth = shapedIcon.image.textFitWidth ?? TextFit.stretchOrShrink;\n    const textFitHeight = shapedIcon.image.textFitHeight ?? TextFit.stretchOrShrink;\n    const contentAspectRatio = contentWidth / contentHeight;\n    // Scale to the proportional axis first note that height takes precedence if\n    // both axes are set to proportional.\n    if (textFitHeight === TextFit.proportional) {\n        if ((textFitWidth === TextFit.stretchOnly && iconWidth / iconHeight < contentAspectRatio) || textFitWidth === TextFit.proportional) {\n            // Push the width of the icon back out to match the content aspect ratio\n            const newIconWidth = Math.ceil(iconHeight * contentAspectRatio);\n            iconLeft *= newIconWidth / iconWidth;\n            iconWidth = newIconWidth;\n        }\n    } else if (textFitWidth === TextFit.proportional) {\n        if (textFitHeight === TextFit.stretchOnly && contentAspectRatio !== 0 && iconWidth / iconHeight > contentAspectRatio) {\n            // Push the height of the icon back out to match the content aspect ratio\n            const newIconHeight = Math.ceil(iconWidth / contentAspectRatio);\n            iconTop *= newIconHeight / iconHeight;\n            iconHeight = newIconHeight;\n        }\n    } else {\n        // If neither textFitHeight nor textFitWidth are proportional then\n        // there is no effect since the content rectangle should be precisely\n        // matched to the content\n    }\n    return {x1: iconLeft, y1: iconTop, x2: iconLeft + iconWidth, y2: iconTop + iconHeight};\n}\n\nfunction fitIconToText(\n    shapedIcon: PositionedIcon,\n    shapedText: Shaping,\n    textFit: string,\n    padding: [number, number, number, number],\n    iconOffset: [number, number],\n    fontScale: number\n): PositionedIcon {\n\n    const image = shapedIcon.image;\n\n    let collisionPadding;\n    if (image.content) {\n        const content = image.content;\n        const pixelRatio = image.pixelRatio || 1;\n        collisionPadding = [\n            content[0] / pixelRatio,\n            content[1] / pixelRatio,\n            image.displaySize[0] - content[2] / pixelRatio,\n            image.displaySize[1] - content[3] / pixelRatio\n        ];\n    }\n\n    // We don't respect the icon-anchor, because icon-text-fit is set. Instead,\n    // the icon will be centered on the text, then stretched in the given\n    // dimensions.\n\n    const textLeft = shapedText.left * fontScale;\n    const textRight = shapedText.right * fontScale;\n\n    let top, right, bottom, left;\n    if (textFit === 'width' || textFit === 'both') {\n        // Stretched horizontally to the text width\n        left = iconOffset[0] + textLeft - padding[3];\n        right = iconOffset[0] + textRight + padding[1];\n    } else {\n        // Centered on the text\n        left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2;\n        right = left + image.displaySize[0];\n    }\n\n    const textTop = shapedText.top * fontScale;\n    const textBottom = shapedText.bottom * fontScale;\n    if (textFit === 'height' || textFit === 'both') {\n        // Stretched vertically to the text height\n        top = iconOffset[1] + textTop - padding[0];\n        bottom = iconOffset[1] + textBottom + padding[2];\n    } else {\n        // Centered on the text\n        top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2;\n        bottom = top + image.displaySize[1];\n    }\n\n    return {image, top, right, bottom, left, collisionPadding};\n}\n", "import {Interpolate, interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {clamp} from '../util/util.ts';\nimport {EvaluationParameters} from '../style/evaluation_parameters.ts';\n\nimport type {PropertyValue, PossiblyEvaluatedPropertyValue} from '../style/properties.ts';\nimport type {InterpolationType, StylePropertyExpression} from '@maplibre/maplibre-gl-style-spec';\n\nconst MAX_GLYPH_ICON_SIZE = 255;\nconst SIZE_PACK_FACTOR = 128;\nconst MAX_PACKED_SIZE: number = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR;\n/**\n * The maximum number of glyphs per symbol bucket. UInt16 `glyphOffsetArrayStart`\n * is the first index that can overflow at 65,535; see\n * https://github.com/mapbox/mapbox-gl-js/issues/2907 for the motivation.\n * Line and text-box starts could in theory overflow too, but there are far\n * fewer boxes and lines than glyphs.\n */\nexport const MAX_GLYPHS = 65535;\n\nexport {getSizeData, evaluateSizeForFeature, evaluateSizeForZoom, SIZE_PACK_FACTOR, MAX_GLYPH_ICON_SIZE, MAX_PACKED_SIZE};\n\n/**\n * Per-bucket data for `text-size` or `icon-size`. Built in the worker, so it holds\n * plain transferable values, not the size expression itself.\n */\nexport type SizeData = {\n    kind: 'constant';\n    layoutSize: number;\n} | {\n    kind: 'source';\n} | {\n    kind: 'camera';\n    zoomStops: number[];\n    sizes: number[];\n    layoutSize: number;\n    interpolationType: InterpolationType;\n} | {\n    kind: 'composite';\n    minZoom: number;\n    maxZoom: number;\n    interpolationType: InterpolationType;\n};\n\ntype CameraSizeData = Extract<SizeData, {kind: 'camera'}>;\ntype CompositeSizeData = Extract<SizeData, {kind: 'composite'}>;\ntype CameraSizeExpression = Extract<StylePropertyExpression, {kind: 'camera'}>;\n\nexport type EvaluatedZoomSize = {uSizeT: number; uSize: number};\n\n/**\n * Gets the bucket-level size data the painter needs to set symbol size uniforms.\n */\nfunction getSizeData(\n    tileZoom: number,\n    value: PropertyValue<number, PossiblyEvaluatedPropertyValue<number>>\n): SizeData {\n    const {expression} = value;\n\n    if (expression.kind === 'constant') {\n        const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1));\n        return {kind: 'constant', layoutSize};\n\n    } else if (expression.kind === 'source') {\n        return {kind: 'source'};\n\n    } else if (expression.kind === 'composite') {\n        const {minZoom, maxZoom} = getCoveringZoomStops(expression.zoomStops, tileZoom);\n        return {kind: 'composite', minZoom, maxZoom, interpolationType: expression.interpolationType};\n\n    } else {\n        const sizes = evaluateSizesAtZoomStops(expression);\n        const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1));\n        return {kind: 'camera', zoomStops: expression.zoomStops, sizes, layoutSize, interpolationType: expression.interpolationType};\n    }\n}\n\n/**\n * Finds the pair of zoom stops covering `[tileZoom, tileZoom + 1]`. A composite size\n * bakes each feature's size at these two zooms into the vertex data.\n */\nfunction getCoveringZoomStops(zoomStops: number[], tileZoom: number): {minZoom: number; maxZoom: number} {\n    let lower = 0;\n    while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) lower++;\n    lower = Math.max(0, lower - 1);\n    let upper = lower;\n    while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) upper++;\n    upper = Math.min(zoomStops.length - 1, upper);\n    return {minZoom: zoomStops[lower], maxZoom: zoomStops[upper]};\n}\n\n/**\n * Evaluates a camera size expression at each of its zoom stops. A step's first stop is\n * `-Infinity`, so its base value is sampled just below the second stop instead.\n */\nfunction evaluateSizesAtZoomStops(expression: CameraSizeExpression): number[] {\n    return expression.zoomStops.map((zoomStop) => expression.evaluate(\n        new EvaluationParameters(zoomStop === -Infinity ? expression.zoomStops[1] - 1 : zoomStop)));\n}\n\nfunction evaluateSizeForFeature(sizeData: SizeData,\n    {\n        uSize,\n        uSizeT\n    }: {\n        uSize: number;\n        uSizeT: number;\n    },\n    {\n        lowerSize,\n        upperSize\n    }: {\n        lowerSize: number;\n        upperSize: number;\n    }): number {\n    if (sizeData.kind === 'source') {\n        return lowerSize / SIZE_PACK_FACTOR;\n    } else if (sizeData.kind === 'composite') {\n        return interpolates.number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT);\n    }\n    return uSize;\n}\n\n/**\n * Computes a bucket's size uniforms at the zoom being drawn, which on a retained tile\n * differs from the zoom the bucket was built for.\n */\nfunction evaluateSizeForZoom(sizeData: SizeData, zoom: number): EvaluatedZoomSize {\n    let uSizeT = 0;\n    let uSize = 0;\n\n    if (sizeData.kind === 'constant') {\n        uSize = sizeData.layoutSize;\n    } else if (sizeData.kind === 'camera') {\n        uSize = evaluateCameraSize(sizeData, zoom);\n    } else if (sizeData.kind === 'composite') {\n        uSizeT = evaluateCompositeInterpolationFactor(sizeData, zoom);\n    }\n\n    return {uSizeT, uSize};\n}\n\n/**\n * Evaluates a camera size at the drawn zoom, interpolating between the stops around it.\n * Capped at `layoutSize`, the size the tile's collision boxes were built for: drawing\n * larger than that would let labels overlap.\n */\nfunction evaluateCameraSize({zoomStops, sizes, layoutSize, interpolationType}: CameraSizeData, zoom: number): number {\n    let lower = zoomStops.length - 1;\n    while (lower > 0 && zoomStops[lower] > zoom) lower--;\n    const upper = Math.min(lower + 1, zoomStops.length - 1);\n\n    const t = !interpolationType ? 0 : clamp(\n        Interpolate.interpolationFactor(interpolationType, zoom, zoomStops[lower], zoomStops[upper]), 0, 1);\n    return Math.min(interpolates.number(sizes[lower], sizes[upper], t), layoutSize);\n}\n\n/**\n * Computes how far the drawn zoom sits between a composite size's two stops, clamped\n * into `[0, 1]`: each feature only stores its size at those two stops, so all the\n * renderer can do is blend between them.\n */\nfunction evaluateCompositeInterpolationFactor({interpolationType, minZoom, maxZoom}: CompositeSizeData, zoom: number): number {\n    return !interpolationType ? 0 : clamp(\n        Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1);\n}\n", "import Point from '@mapbox/point-geometry';\nimport {register} from '../util/web_worker_transfer.ts';\n\nexport class Anchor extends Point {\n    angle: any;\n    segment?: number;\n\n    constructor(x: number, y: number, angle: number, segment?: number) {\n        super(x, y);\n        this.angle = angle;\n        if (segment !== undefined) {\n            this.segment = segment;\n        }\n    }\n\n    clone(): Anchor {\n        return new Anchor(this.x, this.y, this.angle, this.segment);\n    }\n}\n\nregister('Anchor', Anchor);\n", "import type Point from '@mapbox/point-geometry';\nimport type {Anchor} from './anchor.ts';\n\n/**\n * Labels placed around really sharp angles aren't readable. Check if any\n * part of the potential label has a combined angle that is too big.\n *\n * @param line - The line to check\n * @param anchor - The point on the line around which the label is anchored.\n * @param labelLength - The length of the label in geometry units.\n * @param windowSize - The check fails if the combined angles within a part of the line that is `windowSize` long is too big.\n * @param maxAngle - The maximum combined angle that any window along the label is allowed to have.\n *\n * @returns whether the label should be placed\n */\nexport function checkMaxAngle(line: Point[], anchor: Anchor, labelLength: number, windowSize: number, maxAngle: number): boolean {\n\n    // horizontal labels and labels with length 0 always pass\n    if (anchor.segment === undefined || labelLength === 0) return true;\n\n    let p = anchor;\n    let index = anchor.segment + 1;\n    let anchorDistance = 0;\n\n    // move backwards along the line to the first segment the label appears on\n    while (anchorDistance > -labelLength / 2) {\n        index--;\n\n        // there isn't enough room for the label after the beginning of the line\n        if (index < 0) return false;\n\n        anchorDistance -= line[index].dist(p);\n        p = line[index];\n    }\n\n    anchorDistance += line[index].dist(line[index + 1]);\n    index++;\n\n    // store recent corners and their total angle difference\n    const recentCorners = [];\n    let recentAngleDelta = 0;\n\n    // move forwards by the length of the label and check angles along the way\n    while (anchorDistance < labelLength / 2) {\n        const prev = line[index - 1];\n        const current = line[index];\n        const next = line[index + 1];\n\n        // there isn't enough room for the label before the end of the line\n        if (!next) return false;\n\n        let angleDelta = prev.angleTo(current) - current.angleTo(next);\n        // restrict angle to -pi..pi range\n        angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI);\n\n        recentCorners.push({\n            distance: anchorDistance,\n            angleDelta\n        });\n        recentAngleDelta += angleDelta;\n\n        // remove corners that are far enough away from the list of recent anchors\n        while (anchorDistance - recentCorners[0].distance > windowSize) {\n            recentAngleDelta -= recentCorners.shift().angleDelta;\n        }\n\n        // the sum of angles within the window area exceeds the maximum allowed value. check fails.\n        if (recentAngleDelta > maxAngle) return false;\n\n        index++;\n        anchorDistance += current.dist(next);\n    }\n\n    // no part of the line had an angle greater than the maximum allowed. check passes.\n    return true;\n}\n", "import {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {Anchor} from '../symbol/anchor.ts';\nimport {checkMaxAngle} from './check_max_angle.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Shaping, PositionedIcon} from './shaping.ts';\n\nexport {getAnchors, getCenterAnchor};\n\nfunction getLineLength(line: Point[]): number {\n    let lineLength = 0;\n    for (let k = 0; k < line.length - 1; k++) {\n        lineLength += line[k].dist(line[k + 1]);\n    }\n    return lineLength;\n}\n\nfunction getAngleWindowSize(\n    shapedText: Shaping,\n    glyphSize: number,\n    boxScale: number\n): number {\n    return shapedText ?\n        3 / 5 * glyphSize * boxScale :\n        0;\n}\n\nfunction getShapedLabelLength(shapedText?: Shaping | null, shapedIcon?: PositionedIcon | null): number {\n    return Math.max(\n        shapedText ? shapedText.right - shapedText.left : 0,\n        shapedIcon ? shapedIcon.right - shapedIcon.left : 0);\n}\n\nfunction getCenterAnchor(line: Point[],\n    maxAngle: number,\n    shapedText: Shaping,\n    shapedIcon: PositionedIcon,\n    glyphSize: number,\n    boxScale: number): Anchor {\n    const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);\n    const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale;\n\n    let prevDistance = 0;\n    const centerDistance = getLineLength(line) / 2;\n\n    for (let i = 0; i < line.length - 1; i++) {\n\n        const a = line[i],\n            b = line[i + 1];\n\n        const segmentDistance = a.dist(b);\n\n        if (prevDistance + segmentDistance > centerDistance) {\n            // The center is on this segment\n            const t = (centerDistance - prevDistance) / segmentDistance,\n                x = interpolates.number(a.x, b.x, t),\n                y = interpolates.number(a.y, b.y, t);\n\n            const anchor = new Anchor(x, y, b.angleTo(a), i);\n            anchor._round();\n            if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {\n                return anchor;\n            } else {\n                return;\n            }\n        }\n\n        prevDistance += segmentDistance;\n    }\n}\n\nfunction getAnchors(line: Point[],\n    spacing: number,\n    maxAngle: number,\n    shapedText: Shaping,\n    shapedIcon: PositionedIcon,\n    glyphSize: number,\n    boxScale: number,\n    overscaling: number,\n    tileExtent: number): Anchor[] {\n\n    // Resample a line to get anchor points for labels and check that each\n    // potential label passes text-max-angle check and has enough room to fit\n    // on the line.\n\n    const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);\n    const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon);\n    const labelLength = shapedLabelLength * boxScale;\n\n    // Is the line continued from outside the tile boundary?\n    const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent;\n\n    // Is the label long, relative to the spacing?\n    // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges.\n    if (spacing - labelLength < spacing / 4) {\n        spacing = labelLength + spacing / 4;\n    }\n\n    // Offset the first anchor by:\n    // Either half the label length plus a fixed extra offset if the line is not continued\n    // Or half the spacing if the line is continued.\n\n    // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections.\n    const fixedExtraOffset = glyphSize * 2;\n\n    const offset = !isLineContinued ?\n        ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing :\n        (spacing / 2 * overscaling) % spacing;\n\n    return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent);\n}\n\nfunction resample(line: Point[], offset: number, spacing: number, angleWindowSize: number, maxAngle: number, labelLength: number, isLineContinued: boolean, placeAtMiddle: boolean, tileExtent: number): Anchor[] {\n\n    const halfLabelLength = labelLength / 2;\n    const lineLength = getLineLength(line);\n\n    let distance = 0;\n    let markedDistance = offset - spacing;\n\n    let anchors: Anchor[] = [];\n\n    for (let i = 0; i < line.length - 1; i++) {\n\n        const a = line[i],\n            b = line[i + 1];\n\n        const segmentDist = a.dist(b),\n            angle = b.angleTo(a);\n\n        while (markedDistance + spacing < distance + segmentDist) {\n            markedDistance += spacing;\n\n            const t = (markedDistance - distance) / segmentDist,\n                x = interpolates.number(a.x, b.x, t),\n                y = interpolates.number(a.y, b.y, t);\n\n            // Check that the point is within the tile boundaries and that\n            // the label would fit before the beginning and end of the line\n            // if placed at this point.\n            if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent &&\n                    markedDistance - halfLabelLength >= 0 &&\n                    markedDistance + halfLabelLength <= lineLength) {\n                const anchor = new Anchor(x, y, angle, i);\n                anchor._round();\n\n                if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {\n                    anchors.push(anchor);\n                }\n            }\n        }\n\n        distance += segmentDist;\n    }\n\n    if (!placeAtMiddle && !anchors.length && !isLineContinued) {\n        // The first attempt at finding anchors at which labels can be placed failed.\n        // Try again, but this time just try placing one anchor at the middle of the line.\n        // This has the most effect for short lines in overscaled tiles, since the\n        // initial offset used in overscaled tiles is calculated to align labels with positions in\n        // parent tiles instead of placing the label as close to the beginning as possible.\n        anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent);\n    }\n\n    return anchors;\n}\n", "import Point from '@mapbox/point-geometry';\n\n/**\n * Returns the part of a multiline that intersects with the provided rectangular box.\n *\n * @param lines - the lines to check\n * @param x1 - the left edge of the box\n * @param y1 - the top edge of the box\n * @param x2 - the right edge of the box\n * @param y2 - the bottom edge of the box\n * @returns lines\n */\nexport function clipLine(lines: Point[][], x1: number, y1: number, x2: number, y2: number): Point[][] {\n    const clippedLines: Point[][] = [];\n\n    for (const line of lines) {\n        let clippedLine: Point[] | undefined;\n\n        for (let i = 0; i < line.length - 1; i++) {\n            let p0 = line[i];\n            let p1 = line[i + 1];\n\n            if (p0.x < x1 && p1.x < x1) {\n                continue;\n            } else if (p0.x < x1) {\n                p0 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n            } else if (p1.x < x1) {\n                p1 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n            }\n\n            if (p0.y < y1 && p1.y < y1) {\n                continue;\n            } else if (p0.y < y1) {\n                p0 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n            } else if (p1.y < y1) {\n                p1 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n            }\n\n            if (p0.x >= x2 && p1.x >= x2) {\n                continue;\n            } else if (p0.x >= x2) {\n                p0 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n            } else if (p1.x >= x2) {\n                p1 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n            }\n\n            if (p0.y >= y2 && p1.y >= y2) {\n                continue;\n            } else if (p0.y >= y2) {\n                p0 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n            } else if (p1.y >= y2) {\n                p1 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n            }\n\n            if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) {\n                clippedLine = [p0];\n                clippedLines.push(clippedLine);\n            }\n\n            clippedLine.push(p1);\n        }\n    }\n\n    return clippedLines;\n}\n\n/**\n * Clips the geometry to the given bounds.\n * @param geometry - the geometry to clip\n * @param type - the geometry type (1=POINT, 2=LINESTRING, 3=POLYGON)\n * @param x1 - the left edge of the clipping box\n * @param y1 - the top edge of the clipping box\n * @param x2 - the right edge of the clipping box\n * @param y2 - the bottom edge of the clipping box\n * @returns the clipped geometry\n */\nexport function clipGeometry(geometry: Point[][], type: 0 | 1 | 2 | 3, x1: number, y1: number, x2: number, y2: number): Point[][] {\n    let clippedGeometry = clipGeometryOnAxis(geometry, type, x1, x2, AxisType.X);\n    clippedGeometry = clipGeometryOnAxis(clippedGeometry, type, y1, y2, AxisType.Y);\n    return clippedGeometry;\n}\n\n/**\n * On which axis to clip\n */\nconst enum AxisType {\n    X = 0,\n    Y = 1\n}\n\n/**\n * Clip features between two vertical or horizontal axis-parallel lines:\n * ```\n *     |        |\n *  ___|___     |     /\n * /   |   \\____|____/\n *     |        |\n *```\n * @param geometry - the geometry to clip\n * @param type - the geometry type (1=POINT, 2=LINESTRING, 3=POLYGON)\n * @param start - the start line coordinate (x or y) to clip against\n * @param end - the end line coordinate (x or y) to clip against\n * @param axis - the axis to clip on (X or Y)\n * @returns the clipped geometry\n */\nfunction clipGeometryOnAxis(geometry: Point[][], type: 0 | 1 | 2 | 3, start: number, end: number, axis: AxisType): Point[][] {\n    switch (type) {\n        case 1: // POINT\n            return clipPoints(geometry, start, end, axis);\n        case 2: // LINESTRING\n            return clipLines(geometry, start, end, axis, false);\n        case 3: // POLYGON\n            return clipLines(geometry, start, end, axis, true);\n    }\n\n    return [];\n}\n\nfunction clipPoints(geometry: Point[][], start: number, end: number, axis: AxisType): Point[][] {\n    const newGeometry: Point[][] = [];\n    for (const ring of geometry) {\n        for (const point of ring) {\n            const a = axis === AxisType.X ? point.x : point.y;\n            if (a >= start && a <= end) {\n                newGeometry.push([point]);\n            }\n        }\n    }\n    return newGeometry;\n}\n\n/**\n * Clips a line to the given start and end coordinates.\n * @param line - the line to clip\n * @param start - the start line coordinate (x or y) to clip against\n * @param end - the end line coordinate (x or y) to clip against\n * @param axis - the axis to clip on (X or Y)\n * @param isPolygon - whether the line is part of a polygon\n * @returns the clipped line(s)\n */\nfunction clipLineInternal(line: Point[], start: number, end: number, axis: AxisType, isPolygon: boolean): Point[][] {\n    const intersectionPoint = axis === AxisType.X ? intersectionPointX : intersectionPointY;\n\n    let slice: Point[] = [];\n    const newLine: Point[][] = [];\n    for (let i = 0; i < line.length - 1; i++) {\n        const p1 = line[i];\n        const p2 = line[i + 1];\n        const pos1 = axis === AxisType.X ? p1.x : p1.y;\n        const pos2 = axis === AxisType.X ? p2.x : p2.y;\n        let exited = false;\n\n        if (pos1 < start) {\n            // ---|-->  | (line enters the clip region from the left)\n            if (pos2 >= start) {\n                slice.push(intersectionPoint(p1, p2, start));\n            }\n        } else if (pos1 > end) {\n            // |  <--|--- (line enters the clip region from the right)\n            if (pos2 <= end) {\n                slice.push(intersectionPoint(p1, p2, end));\n            }\n        } else {\n            slice.push(p1);\n        }\n        if (pos2 < start && pos1 >= start) {\n            // <--|---  | or <--|-----|--- (line exits the clip region on the left)\n            slice.push(intersectionPoint(p1, p2, start));\n            exited = true;\n        }\n        if (pos2 > end && pos1 <= end) {\n            // |  ---|--> or ---|-----|--> (line exits the clip region on the right)\n            slice.push(intersectionPoint(p1, p2, end));\n            exited = true;\n        }\n\n        if (!isPolygon && exited) {\n            newLine.push(slice);\n            slice = [];\n        }\n    }\n\n    // add the last point\n    const last = line.length - 1;\n    const lastPos = axis === AxisType.X ? line[last].x : line[last].y;\n    if (lastPos >= start && lastPos <= end) {\n        slice.push(line[last]);\n    }\n\n    // close the polygon if its endpoints are not the same after clipping\n    if (isPolygon && slice.length > 0 && !slice[0].equals(slice[slice.length - 1])) {\n        slice.push(new Point(slice[0].x, slice[0].y));\n    }\n    if (slice.length > 0) {\n        newLine.push(slice);\n    }\n    return newLine;\n}\n\nfunction clipLines(geometry: Point[][], start: number, end: number, axis: AxisType, isPolygon: boolean): Point[][] {\n    const newGeometry: Point[][] = [];\n    for (const line of geometry) {\n        const clippedLines = clipLineInternal(line, start, end, axis, isPolygon);\n        if (clippedLines.length > 0) {\n            newGeometry.push(...clippedLines);\n        }\n    }\n    return newGeometry;\n}\n\nfunction intersectionPointX(p1: Point, p2: Point, x: number): Point {\n    const t = (x - p1.x) / (p2.x - p1.x);\n    return new Point(x, p1.y + (p2.y - p1.y) * t);\n}\n\nfunction intersectionPointY(p1: Point, p2: Point, y: number): Point {\n    const t = (y - p1.y) / (p2.y - p1.y);\n    return new Point(p1.x + (p2.x - p1.x) * t, y);\n}\n", "import Point from '@mapbox/point-geometry';\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf.ts';\nimport {SHAPING_DEFAULT_OFFSET, applyTextFit} from './shaping.ts';\nimport {IMAGE_PADDING} from '../render/image_atlas.ts';\nimport ONE_EM from './one_em.ts';\n\nimport type {Anchor} from './anchor.ts';\nimport type {Box, PositionedIcon, Shaping} from './shaping.ts';\nimport type {SymbolStyleLayer} from '../style/style_layer/symbol_style_layer.ts';\nimport type {Feature} from '@maplibre/maplibre-gl-style-spec';\nimport type {StyleImage} from '../style/style_image.ts';\nimport type {Rect} from '../render/glyph_atlas.ts';\n\n/**\n * A textured quad for rendering a single icon or glyph.\n *\n * The zoom range the glyph can be shown is defined by minScale and maxScale.\n *\n * @param tl - The offset of the top left corner from the anchor.\n * @param tr - The offset of the top right corner from the anchor.\n * @param bl - The offset of the bottom left corner from the anchor.\n * @param br - The offset of the bottom right corner from the anchor.\n * @param tex - The texture coordinates.\n */\nexport type SymbolQuad = {\n    tl: Point;\n    tr: Point;\n    bl: Point;\n    br: Point;\n    tex: {\n        x: number;\n        y: number;\n        w: number;\n        h: number;\n    };\n    pixelOffsetTL: Point;\n    pixelOffsetBR: Point;\n    writingMode: any | void;\n    glyphOffset: [number, number];\n    sectionIndex: number;\n    isSDF: boolean;\n    minFontScaleX: number;\n    minFontScaleY: number;\n};\n\n// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual\n// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped\n// on one edge in some cases.\nconst border = IMAGE_PADDING;\n\n/**\n * Create the quads used for rendering an icon.\n */\nexport function getIconQuads(\n    shapedIcon: PositionedIcon,\n    iconRotate: number,\n    isSDFIcon: boolean,\n    hasIconTextFit: boolean\n): SymbolQuad[] {\n    const quads = [];\n\n    const image = shapedIcon.image;\n    const pixelRatio = image.pixelRatio;\n    const imageWidth = image.paddedRect.w - 2 * border;\n    const imageHeight = image.paddedRect.h - 2 * border;\n\n    let icon: Box = {\n        x1: shapedIcon.left,\n        y1: shapedIcon.top,\n        x2: shapedIcon.right,\n        y2: shapedIcon.bottom\n    };\n\n    const stretchX = image.stretchX || [[0, imageWidth]];\n    const stretchY = image.stretchY || [[0, imageHeight]];\n\n    const reduceRanges = (sum, range) => sum + range[1] - range[0];\n    const stretchWidth = stretchX.reduce(reduceRanges, 0);\n    const stretchHeight = stretchY.reduce(reduceRanges, 0);\n    const fixedWidth = imageWidth - stretchWidth;\n    const fixedHeight = imageHeight - stretchHeight;\n\n    let stretchOffsetX = 0;\n    let stretchContentWidth = stretchWidth;\n    let stretchOffsetY = 0;\n    let stretchContentHeight = stretchHeight;\n    let fixedOffsetX = 0;\n    let fixedContentWidth = fixedWidth;\n    let fixedOffsetY = 0;\n    let fixedContentHeight = fixedHeight;\n\n    if (image.content && hasIconTextFit) {\n        const content = image.content;\n        const contentWidth = content[2] - content[0];\n        const contentHeight = content[3] - content[1];\n        // Constrict content area to fit target aspect ratio\n        if (image.textFitWidth || image.textFitHeight) {\n            icon = applyTextFit(shapedIcon);\n        }\n        stretchOffsetX = sumWithinRange(stretchX, 0, content[0]);\n        stretchOffsetY = sumWithinRange(stretchY, 0, content[1]);\n        stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]);\n        stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]);\n        fixedOffsetX = content[0] - stretchOffsetX;\n        fixedOffsetY = content[1] - stretchOffsetY;\n        fixedContentWidth = contentWidth - stretchContentWidth;\n        fixedContentHeight = contentHeight - stretchContentHeight;\n    }\n\n    const iconLeft = icon.x1;\n    const iconTop = icon.y1;\n    const iconWidth = icon.x2 - iconLeft;\n    const iconHeight = icon.y2 - iconTop;\n\n    const makeBox = (left, top, right, bottom) => {\n\n        const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft);\n        const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth);\n\n        const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop);\n        const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight);\n\n        const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft);\n        const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth);\n\n        const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop);\n        const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight);\n\n        const tl = new Point(leftEm, topEm);\n        const tr = new Point(rightEm, topEm);\n        const br = new Point(rightEm, bottomEm);\n        const bl = new Point(leftEm, bottomEm);\n        const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio);\n        const pixelOffsetBR = new Point(rightPx / pixelRatio, bottomPx / pixelRatio);\n\n        const angle = iconRotate * Math.PI / 180;\n\n        if (angle) {\n            const sin = Math.sin(angle),\n                cos = Math.cos(angle),\n                matrix = [cos, -sin, sin, cos] as [number, number, number, number];\n\n            tl._matMult(matrix);\n            tr._matMult(matrix);\n            bl._matMult(matrix);\n            br._matMult(matrix);\n        }\n\n        const x1 = left.stretch + left.fixed;\n        const x2 = right.stretch + right.fixed;\n        const y1 = top.stretch + top.fixed;\n        const y2 = bottom.stretch + bottom.fixed;\n\n        const subRect = {\n            x: image.paddedRect.x + border + x1,\n            y: image.paddedRect.y + border + y1,\n            w: x2 - x1,\n            h: y2 - y1\n        };\n\n        const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth;\n        const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight;\n\n        // Icon quad is padded, so texture coordinates also need to be padded.\n        return {tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon};\n    };\n\n    if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) {\n        quads.push(makeBox(\n            {fixed: 0, stretch: -1},\n            {fixed: 0, stretch: -1},\n            {fixed: 0, stretch: imageWidth + 1},\n            {fixed: 0, stretch: imageHeight + 1}));\n    } else {\n        const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth);\n        const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight);\n\n        for (let xi = 0; xi < xCuts.length - 1; xi++) {\n            const x1 = xCuts[xi];\n            const x2 = xCuts[xi + 1];\n            for (let yi = 0; yi < yCuts.length - 1; yi++) {\n                const y1 = yCuts[yi];\n                const y2 = yCuts[yi + 1];\n                quads.push(makeBox(x1, y1, x2, y2));\n            }\n        }\n    }\n\n    return quads;\n}\n\nfunction sumWithinRange(ranges, min, max) {\n    let sum = 0;\n    for (const range of ranges) {\n        sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0]));\n    }\n    return sum;\n}\n\nfunction stretchZonesToCuts(stretchZones, fixedSize, stretchSize) {\n    const cuts = [{fixed: -border, stretch: 0}];\n\n    for (const [c1, c2] of stretchZones) {\n        const last = cuts[cuts.length - 1];\n        cuts.push({\n            fixed: c1 - last.stretch,\n            stretch: last.stretch\n        });\n        cuts.push({\n            fixed: c1 - last.stretch,\n            stretch: last.stretch + (c2 - c1)\n        });\n    }\n    cuts.push({\n        fixed: fixedSize + border,\n        stretch: stretchSize\n    });\n    return cuts;\n}\n\nfunction getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) {\n    return stretchOffset / stretchSize * iconSize + iconOffset;\n}\n\nfunction getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) {\n    return fixedOffset - fixedSize * stretchOffset / stretchSize;\n}\n\n/**\n * Create the quads used for rendering a text label.\n */\nexport function getGlyphQuads(\n    anchor: Anchor,\n    shaping: Shaping,\n    textOffset: [number, number],\n    layer: SymbolStyleLayer,\n    alongLine: boolean,\n    feature: Feature,\n    imageMap: {[_: string]: StyleImage},\n    allowVerticalPlacement: boolean\n): SymbolQuad[] {\n\n    const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180;\n    const quads = [];\n\n    for (const line of shaping.positionedLines) {\n        for (const positionedGlyph of line.positionedGlyphs) {\n            if (!positionedGlyph.rect) continue;\n            const textureRect: Rect = positionedGlyph.rect || {} as Rect;\n\n            // The rects have an additional buffer that is not included in their size.\n            const glyphPadding = 1.0;\n            let rectBuffer = GLYPH_PBF_BORDER + glyphPadding;\n            let isSDF = true;\n            let pixelRatio = 1.0;\n            let lineOffset = 0.0;\n\n            const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical;\n            const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2;\n\n            // Align images and scaled glyphs in the middle of a vertical line.\n            if (allowVerticalPlacement && shaping.verticalizable) {\n                const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM;\n                const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2;\n                lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset);\n            }\n\n            if (positionedGlyph.imageName) {\n                const image = imageMap[positionedGlyph.imageName];\n                isSDF = image.sdf;\n                pixelRatio = image.pixelRatio;\n                rectBuffer = IMAGE_PADDING / pixelRatio;\n            }\n\n            const glyphOffset = alongLine ?\n                [positionedGlyph.x + halfAdvance, positionedGlyph.y] :\n                [0, 0];\n\n            let builtInOffset: [number, number] = alongLine ?\n                [0, 0] :\n                [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset];\n\n            let verticalizedLabelOffset = [0, 0] as [number, number];\n            if (rotateVerticalGlyph) {\n                // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation\n                // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset.\n                verticalizedLabelOffset = builtInOffset;\n                builtInOffset = [0, 0];\n            }\n\n            const textureScale = positionedGlyph.metrics.isDoubleResolution ? 2 : 1;\n\n            const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0];\n            const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1];\n            const x2 = x1 + textureRect.w / textureScale * positionedGlyph.scale / pixelRatio;\n            const y2 = y1 + textureRect.h / textureScale * positionedGlyph.scale / pixelRatio;\n\n            const tl = new Point(x1, y1);\n            const tr = new Point(x2, y1);\n            const bl = new Point(x1, y2);\n            const br = new Point(x2, y2);\n\n            if (rotateVerticalGlyph) {\n                // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em)\n                // In horizontal orientation, the y values for glyphs are below the midline\n                // and we use a \"yOffset\" of -17 to pull them up to the middle.\n                // By rotating counter-clockwise around the point at the center of the left\n                // edge of a 24x24 layout box centered below the midline, we align the center\n                // of the glyphs with the horizontal midline, so the yOffset is no longer\n                // necessary, but we also pull the glyph to the left along the x axis.\n                // The y coordinate includes baseline yOffset, thus needs to be accounted\n                // for when glyph is rotated and translated.\n                const center = new Point(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET);\n                const verticalRotation = -Math.PI / 2;\n\n                // xHalfWidthOffsetCorrection is a difference between full-width and half-width\n                // advance, should be 0 for full-width glyphs and will pull up half-width glyphs.\n                const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance;\n                const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0;\n                const halfWidthOffsetCorrection = new Point(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection);\n                const verticalOffsetCorrection = new Point(...verticalizedLabelOffset);\n                tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n                tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n                bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n                br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n            }\n\n            if (textRotate) {\n                const sin = Math.sin(textRotate),\n                    cos = Math.cos(textRotate),\n                    matrix = [cos, -sin, sin, cos] as [number, number, number, number];\n\n                tl._matMult(matrix);\n                tr._matMult(matrix);\n                bl._matMult(matrix);\n                br._matMult(matrix);\n            }\n\n            const pixelOffsetTL = new Point(0, 0);\n            const pixelOffsetBR = new Point(0, 0);\n            const minFontScaleX = 0;\n            const minFontScaleY = 0;\n            quads.push({tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY});\n        }\n    }\n\n    return quads;\n}\n", "import Point from '@mapbox/point-geometry';\nimport {applyTextFit} from './shaping.ts';\n\nimport type {SymbolPadding} from '../style/style_layer/symbol_style_layer.ts';\nimport type {Anchor} from './anchor.ts';\nimport type {CollisionBoxArray} from '../data/array_types.g.ts';\n\n/**\n * A CollisionFeature represents the area of the tile covered by a single label.\n * It is used with CollisionIndex to check if the label overlaps with any\n * previous labels. A CollisionFeature is mostly just a set of CollisionBox\n * objects.\n */\nexport class CollisionFeature {\n    boxStartIndex: number;\n    boxEndIndex: number;\n    circleDiameter: number;\n\n    /**\n     * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process.\n     * For line aligned labels a collision circle diameter is computed instead.\n     *\n     * @param anchor - The point along the line around which the label is anchored.\n     * @param shaped - The text or icon shaping results.\n     * @param boxScale - A magic number used to convert from glyph metrics units to geometry units.\n     * @param padding - The amount of padding to add around the label edges.\n     * @param alignLine - Whether the label is aligned with the line or the viewport.\n     */\n    constructor(collisionBoxArray: CollisionBoxArray,\n        anchor: Anchor,\n        featureIndex: number,\n        sourceLayerIndex: number,\n        bucketIndex: number,\n        shaped: any,\n        boxScale: number,\n        padding: SymbolPadding,\n        alignLine: boolean,\n        rotate: number) {\n\n        this.boxStartIndex = collisionBoxArray.length;\n\n        if (alignLine) {\n            // Compute height of the shape in glyph metrics and apply collision padding.\n            // Note that the pixel based 'text-padding' is applied at runtime\n            let top = shaped.top;\n            let bottom = shaped.bottom;\n            const collisionPadding = shaped.collisionPadding;\n\n            if (collisionPadding) {\n                top -= collisionPadding[1];\n                bottom += collisionPadding[3];\n            }\n\n            let height = bottom - top;\n\n            if (height > 0) {\n                // set minimum box height to avoid very many small labels\n                height = Math.max(10, height);\n                this.circleDiameter = height;\n            }\n        } else {\n            const icon = shaped.image?.content && (shaped.image.textFitWidth || shaped.image.textFitHeight) ?\n                applyTextFit(shaped) :\n                {\n                    x1: shaped.left,\n                    y1: shaped.top,\n                    x2: shaped.right,\n                    y2: shaped.bottom\n                };\n\n            // margin is in CSS order: [top, right, bottom, left]\n            icon.y1 = icon.y1 * boxScale - padding[0];\n            icon.y2 = icon.y2 * boxScale + padding[2];\n            icon.x1 = icon.x1 * boxScale - padding[3];\n            icon.x2 = icon.x2 * boxScale + padding[1];\n\n            const collisionPadding = shaped.collisionPadding;\n            if (collisionPadding) {\n                icon.x1 -= collisionPadding[0] * boxScale;\n                icon.y1 -= collisionPadding[1] * boxScale;\n                icon.x2 += collisionPadding[2] * boxScale;\n                icon.y2 += collisionPadding[3] * boxScale;\n            }\n\n            if (rotate) {\n                // Account for *-rotate in point collision boxes\n                // See https://github.com/mapbox/mapbox-gl-js/issues/6075\n                // Doesn't account for icon-text-fit\n\n                const tl = new Point(icon.x1, icon.y1);\n                const tr = new Point(icon.x2, icon.y1);\n                const bl = new Point(icon.x1, icon.y2);\n                const br = new Point(icon.x2, icon.y2);\n\n                const rotateRadians = rotate * Math.PI / 180;\n\n                tl._rotate(rotateRadians);\n                tr._rotate(rotateRadians);\n                bl._rotate(rotateRadians);\n                br._rotate(rotateRadians);\n\n                // Collision features require an \"on-axis\" geometry,\n                // so take the envelope of the rotated geometry\n                // (may be quite large for wide labels rotated 45 degrees)\n                icon.x1 = Math.min(tl.x, tr.x, bl.x, br.x);\n                icon.x2 = Math.max(tl.x, tr.x, bl.x, br.x);\n                icon.y1 = Math.min(tl.y, tr.y, bl.y, br.y);\n                icon.y2 = Math.max(tl.y, tr.y, bl.y, br.y);\n            }\n            collisionBoxArray.emplaceBack(anchor.x, anchor.y, icon.x1, icon.y1, icon.x2, icon.y2, featureIndex, sourceLayerIndex, bucketIndex);\n        }\n\n        this.boxEndIndex = collisionBoxArray.length;\n    }\n}\n", "\nexport default class TinyQueue {\n    constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {\n        this.data = data;\n        this.length = this.data.length;\n        this.compare = compare;\n\n        if (this.length > 0) {\n            for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i);\n        }\n    }\n\n    push(item) {\n        this.data.push(item);\n        this._up(this.length++);\n    }\n\n    pop() {\n        if (this.length === 0) return undefined;\n\n        const top = this.data[0];\n        const bottom = this.data.pop();\n\n        if (--this.length > 0) {\n            this.data[0] = bottom;\n            this._down(0);\n        }\n\n        return top;\n    }\n\n    peek() {\n        return this.data[0];\n    }\n\n    _up(pos) {\n        const {data, compare} = this;\n        const item = data[pos];\n\n        while (pos > 0) {\n            const parent = (pos - 1) >> 1;\n            const current = data[parent];\n            if (compare(item, current) >= 0) break;\n            data[pos] = current;\n            pos = parent;\n        }\n\n        data[pos] = item;\n    }\n\n    _down(pos) {\n        const {data, compare} = this;\n        const halfLength = this.length >> 1;\n        const item = data[pos];\n\n        while (pos < halfLength) {\n            let bestChild = (pos << 1) + 1; // initially it is the left child\n            const right = bestChild + 1;\n\n            if (right < this.length && compare(data[right], data[bestChild]) < 0) {\n                bestChild = right;\n            }\n            if (compare(data[bestChild], item) >= 0) break;\n\n            data[pos] = data[bestChild];\n            pos = bestChild;\n        }\n\n        data[pos] = item;\n    }\n}\n", "import Queue from 'tinyqueue';\nimport Point from '@mapbox/point-geometry';\nimport {distToSegmentSquared} from './intersection_tests.ts';\nimport {Bounds} from '../geo/bounds.ts';\n\n/**\n * Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility\n * This is a copy of https://github.com/mapbox/polylabel adapted to use Points\n *\n * @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\n * @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\n * @returns Pole of Inaccessibility.\n */\nexport function findPoleOfInaccessibility(\n    polygonRings: Point[][],\n    precision: number = 1,\n): Point {\n    const bounds = Bounds.fromPoints(polygonRings[0]);\n\n    const cellSize = Math.min(bounds.width(), bounds.height());\n    let h = cellSize / 2;\n\n    // a priority queue of cells in order of their \"potential\" (max distance to polygon)\n    const cellQueue = new Queue([], compareMax);\n\n    const {minX, minY, maxX, maxY} = bounds;\n    if (cellSize === 0) return new Point(minX, minY);\n\n    // cover polygon with initial cells\n    for (let x = minX; x < maxX; x += cellSize) {\n        for (let y = minY; y < maxY; y += cellSize) {\n            cellQueue.push(new Cell(x + h, y + h, h, polygonRings));\n        }\n    }\n\n    // take centroid as the first best guess\n    const centroidCell = getCentroidCell(polygonRings);\n    let bestCell = centroidCell;\n\n    while (cellQueue.length) {\n        // pick the most promising cell from the queue\n        const cell = cellQueue.pop();\n\n        // update the best cell if we found a better one\n        if (cell.d > bestCell.d || !bestCell.d) {\n            bestCell = cell;\n        }\n\n        // do not drill down further if there's no chance of a better solution\n        if (cell.max - bestCell.d <= precision) continue;\n\n        // split the cell into four cells\n        h = cell.h / 2;\n        cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings));\n        cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings));\n        cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings));\n        cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings));\n    }\n\n    // For convex or nearly-convex polygons, the centroid provides visually\n    // better label placement than the mathematical POI.\n    // Coordinate rounding (e.g. in geojson-vt) can break polygon symmetry and cause the POI to\n    // drift far from center even though its distance-to-edge is only marginally better.\n    // Prefer the centroid when it is inside the polygon\n    // and its distance is within `precision` of the best found.\n    if (centroidCell.d > 0 && bestCell.d - centroidCell.d <= precision) {\n        return centroidCell.p;\n    }\n    return bestCell.p;\n}\n\nfunction compareMax(a: Cell, b: Cell) {\n    return b.max - a.max;\n}\n\nclass Cell {\n    p: Point;\n    h: number;\n    d: number;\n    max: number;\n\n    constructor(x: number, y: number, h: number, polygon: Point[][]) {\n        this.p = new Point(x, y);\n        this.h = h; // half the cell size\n        this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon\n        this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell\n    }\n}\n\n// signed distance from point to polygon outline (negative if point is outside)\nfunction pointToPolygonDist(p: Point, polygon: Point[][]) {\n    let inside = false;\n    let minDistSq = Infinity;\n\n    for (const ring of polygon) {\n\n        for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) {\n            const a = ring[i];\n            const b = ring[j];\n\n            if ((a.y > p.y !== b.y > p.y) &&\n                (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) inside = !inside;\n\n            minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b));\n        }\n    }\n\n    return (inside ? 1 : -1) * Math.sqrt(minDistSq);\n}\n\n// get polygon centroid\nexport function getCentroidCell(polygon: Point[][]): Cell {\n    let area = 0;\n    let x = 0;\n    let y = 0;\n    const points = polygon[0];\n    for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) {\n        const a = points[i];\n        const b = points[j];\n        const f = a.x * b.y - b.x * a.y;\n        x += (a.x + b.x) * f;\n        y += (a.y + b.y) * f;\n        area += f * 3;\n    }\n    return new Cell(x / area, y / area, 0, polygon);\n}\n", "import {VariableAnchorOffsetCollection, type VariableAnchorOffsetCollectionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport ONE_EM from '../../symbol/one_em.ts';\n\nimport type {SymbolFeature} from '../../data/bucket/symbol_bucket.ts';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {SymbolStyleLayer} from './symbol_style_layer.ts';\n\nexport enum TextAnchorEnum {\n    'center' = 1,\n    'left' = 2,\n    'right' = 3,\n    'top' = 4,\n    'bottom' = 5,\n    'top-left' = 6,\n    'top-right' = 7,\n    'bottom-left' = 8,\n    'bottom-right' = 9\n}\n\nexport type TextAnchor = keyof typeof TextAnchorEnum;\n\n// The radial offset is to the edge of the text box\n// In the horizontal direction, the edge of the text box is where glyphs start\n// But in the vertical direction, the glyphs appear to \"start\" at the baseline\n// We don't actually load baseline data, but we assume an offset of ONE_EM - 17\n// (see \"yOffset\" in shaping.js)\nconst baselineOffset = 7;\nexport const INVALID_TEXT_OFFSET: number = Number.POSITIVE_INFINITY;\n\nexport function evaluateVariableOffset(anchor: TextAnchor, offset: [number, number]): [number, number] {\n\n    function fromRadialOffset(anchor: TextAnchor, radialOffset: number): [number, number] {\n        let x = 0, y = 0;\n        if (radialOffset < 0) radialOffset = 0; // Ignore negative offset.\n        // solve for r where r^2 + r^2 = radialOffset^2\n        const hypotenuse = radialOffset / Math.SQRT2;\n        switch (anchor) {\n            case 'top-right':\n            case 'top-left':\n                y = hypotenuse - baselineOffset;\n                break;\n            case 'bottom-right':\n            case 'bottom-left':\n                y = -hypotenuse + baselineOffset;\n                break;\n            case 'bottom':\n                y = -radialOffset + baselineOffset;\n                break;\n            case 'top':\n                y = radialOffset - baselineOffset;\n                break;\n        }\n\n        switch (anchor) {\n            case 'top-right':\n            case 'bottom-right':\n                x = -hypotenuse;\n                break;\n            case 'top-left':\n            case 'bottom-left':\n                x = hypotenuse;\n                break;\n            case 'left':\n                x = radialOffset;\n                break;\n            case 'right':\n                x = -radialOffset;\n                break;\n        }\n\n        return [x, y];\n    }\n\n    function fromTextOffset(anchor: TextAnchor, offsetX: number, offsetY: number): [number, number] {\n        let x = 0, y = 0;\n        // Use absolute offset values.\n        offsetX = Math.abs(offsetX);\n        offsetY = Math.abs(offsetY);\n\n        switch (anchor) {\n            case 'top-right':\n            case 'top-left':\n            case 'top':\n                y = offsetY - baselineOffset;\n                break;\n            case 'bottom-right':\n            case 'bottom-left':\n            case 'bottom':\n                y = -offsetY + baselineOffset;\n                break;\n        }\n\n        switch (anchor) {\n            case 'top-right':\n            case 'bottom-right':\n            case 'right':\n                x = -offsetX;\n                break;\n            case 'top-left':\n            case 'bottom-left':\n            case 'left':\n                x = offsetX;\n                break;\n        }\n\n        return [x, y];\n    }\n\n    return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]);\n}\n\n// Helper to support both text-variable-anchor and text-variable-anchor-offset. Offset values converted from EMs to PXs\nexport function getTextVariableAnchorOffset(layer: SymbolStyleLayer, feature: SymbolFeature, canonical: CanonicalTileID): VariableAnchorOffsetCollection | null {\n    const layout = layer.layout;\n    // If style specifies text-variable-anchor-offset, just return it\n    const variableAnchorOffset = layout.get('text-variable-anchor-offset')?.evaluate(feature, {}, canonical);\n\n    if (variableAnchorOffset) {\n        const sourceValues = variableAnchorOffset.values;\n        const destValues: VariableAnchorOffsetCollectionSpecification = [];\n\n        // Convert offsets from EM to PX, and apply baseline shift\n        for (let i = 0; i < sourceValues.length; i += 2) {\n            const anchor = destValues[i] = sourceValues[i] as TextAnchor;\n            const offset = (sourceValues[i + 1] as [number, number]).map(t => t * ONE_EM) as [number, number];\n\n            if (anchor.startsWith('top')) {\n                offset[1] -= baselineOffset;\n            } else if (anchor.startsWith('bottom')) {\n                offset[1] += baselineOffset;\n            }\n\n            destValues[i + 1] = offset;\n        }\n\n        return new VariableAnchorOffsetCollection(destValues);\n    }\n\n    // If style specifies text-variable-anchor, convert to the new format\n    const variableAnchor = layout.get('text-variable-anchor');\n\n    if (variableAnchor) {\n        let textOffset: [number, number];\n        const unevaluatedLayout = layer._unevaluatedLayout;\n\n        // The style spec says don't use `text-offset` and `text-radial-offset` together\n        // but doesn't actually specify what happens if you use both. We go with the radial offset.\n        if (unevaluatedLayout.getValue('text-radial-offset') !== undefined) {\n            textOffset = [layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM, INVALID_TEXT_OFFSET];\n        } else {\n            textOffset = layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM) as [number, number];\n        }\n\n        const anchorOffsets: VariableAnchorOffsetCollectionSpecification = [];\n\n        for (const anchor of variableAnchor) {\n            anchorOffsets.push(anchor, evaluateVariableOffset(anchor, textOffset));\n        }\n\n        return new VariableAnchorOffsetCollection(anchorOffsets);\n    }\n\n    return null;\n}\n", "import murmur3 from 'murmurhash-js';\nimport ONE_EM from './one_em.ts';\nimport {Anchor} from './anchor.ts';\nimport {getAnchors, getCenterAnchor} from './get_anchors.ts';\nimport {clipLine} from './clip_line.ts';\nimport {shapeText, shapeIcon, WritingMode, fitIconToText} from './shaping.ts';\nimport {getGlyphQuads, getIconQuads} from './quads.ts';\nimport {CollisionFeature} from './collision_feature.ts';\nimport {warnOnce} from '../util/util.ts';\nimport {allowsVerticalWritingMode, allowsLetterSpacing} from '../util/script_detection.ts';\nimport {findPoleOfInaccessibility} from '../util/find_pole_of_inaccessibility.ts';\nimport {EXTENT} from '../data/extent.ts';\nimport {isOutsideTile} from '../data/extent_bounds.ts';\nimport {EvaluationParameters} from '../style/evaluation_parameters.ts';\nimport {SIZE_PACK_FACTOR, MAX_PACKED_SIZE, MAX_GLYPH_ICON_SIZE} from './symbol_size.ts';\nimport {getIconPadding, type SymbolPadding} from '../style/style_layer/symbol_style_layer.ts';\nimport {getTextVariableAnchorOffset, evaluateVariableOffset, INVALID_TEXT_OFFSET, type TextAnchor, TextAnchorEnum} from '../style/style_layer/variable_text_anchor.ts';\nimport {type VariableAnchorOffsetCollection, classifyRings} from '@maplibre/maplibre-gl-style-spec';\nimport {subdivideVertexLine} from '../render/subdivision.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {SymbolBucket} from '../data/bucket/symbol_bucket.ts';\nimport type {CanonicalTileID} from '../tile/tile_id.ts';\nimport type {Shaping, PositionedIcon, TextJustify} from './shaping.ts';\nimport type {CollisionBoxArray, TextAnchorOffsetArray} from '../data/array_types.g.ts';\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket.ts';\nimport type {StyleImage} from '../style/style_image.ts';\nimport type {GlyphMap} from '../style/style_glyph.ts';\nimport type {SymbolStyleLayer} from '../style/style_layer/symbol_style_layer.ts';\nimport type {ImagePosition} from '../render/image_atlas.ts';\nimport type {GlyphPositions} from '../render/glyph_atlas.ts';\nimport type {PossiblyEvaluatedPropertyValue} from '../style/properties.ts';\nimport type {SubdivisionGranularitySetting} from '../render/subdivision_granularity_settings.ts';\n\n// The symbol layout process needs `text-size` evaluated at up to five different zoom levels, and\n// `icon-size` at up to three:\n//\n//   1. `text-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `text-size`\n//       expressions, and to calculate the box dimensions for icon-text-fit.\n//   2. `icon-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `icon-size`\n//       expressions.\n//   3. `text-size` and `icon-size` at the zoom level of the bucket, plus one. Used to calculate collision boxes.\n//   4. `text-size` at zoom level 18. Used for something line-symbol-placement-related.\n//   5.  For composite `*-size` expressions: two zoom levels of curve stops that \"cover\" the zoom level of the\n//       bucket. These go into a vertex buffer and are used by the shader to interpolate the size at render time.\n//\n// (1) and (2) are stored in `bucket.layers[0].layout`. The remainder are below.\n//\ntype Sizes = {\n    layoutTextSize: PossiblyEvaluatedPropertyValue<number>; // (3),\n    layoutIconSize: PossiblyEvaluatedPropertyValue<number>; // (3),\n    textMaxSize: PossiblyEvaluatedPropertyValue<number>;    // (4),\n    compositeTextSizes: [PossiblyEvaluatedPropertyValue<number>, PossiblyEvaluatedPropertyValue<number>]; // (5),\n    compositeIconSizes: [PossiblyEvaluatedPropertyValue<number>, PossiblyEvaluatedPropertyValue<number>]; // (5)\n};\n\ntype ShapedTextOrientations = {\n    vertical: Shaping | false;\n    horizontal: Record<TextJustify, Shaping>;\n};\n\nexport function performSymbolLayout(args: {\n    bucket: SymbolBucket;\n    glyphMap: GlyphMap;\n    glyphPositions: GlyphPositions;\n    imageMap: {[_: string]: StyleImage};\n    imagePositions: {[_: string]: ImagePosition};\n    showCollisionBoxes: boolean;\n    canonical: CanonicalTileID;\n    subdivisionGranularity: SubdivisionGranularitySetting;\n    /**\n     * Whether the source promotes a feature property to the feature id. A promoted id names the same feature in every\n     * tile, so the cross-tile symbol key can carry it and a label is only ever matched against the same feature's label at\n     * other zoom levels, see {@link keyWithFeatureId}.\n     */\n    hasPromoteId: boolean;\n}): void {\n    args.bucket.createArrays();\n\n    const tileSize = 512 * args.bucket.overscaling;\n    args.bucket.tilePixelRatio = EXTENT / tileSize;\n    args.bucket.compareText = {};\n    args.bucket.iconsNeedLinear = false;\n\n    const layer = args.bucket.layers[0];\n    const layout = layer.layout;\n    const unevaluatedLayoutValues = layer._unevaluatedLayout._values;\n\n    const sizes: Sizes = {\n        // Filled in below, if *SizeData.kind is 'composite'\n        // compositeIconSizes: undefined,\n        // compositeTextSizes: undefined,\n        layoutIconSize: unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical),\n        layoutTextSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical),\n        textMaxSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18))\n    } as Sizes;\n\n    if (args.bucket.textSizeData.kind === 'composite') {\n        const {minZoom, maxZoom} = args.bucket.textSizeData;\n        sizes.compositeTextSizes = [\n            unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical),\n            unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical)\n        ];\n    }\n\n    if (args.bucket.iconSizeData.kind === 'composite') {\n        const {minZoom, maxZoom} = args.bucket.iconSizeData;\n        sizes.compositeIconSizes = [\n            unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical),\n            unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical)\n        ];\n    }\n\n    const lineHeight = layout.get('text-line-height') * ONE_EM;\n    const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point';\n    const keepUpright = layout.get('text-keep-upright');\n    const textSize = layout.get('text-size');\n\n    for (const feature of args.bucket.features) {\n        const fontstack = layout.get('text-font').evaluate(feature, {}, args.canonical).join(',');\n        const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, args.canonical);\n        const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, args.canonical);\n        const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, args.canonical);\n\n        const shapedTextOrientations: ShapedTextOrientations = {\n            horizontal: {} as Record<TextJustify, Shaping>,\n            vertical: undefined\n        };\n        const text = feature.text;\n        let textOffset: [number, number] = [0, 0];\n        if (text) {\n            const unformattedText = text.toString();\n            const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, args.canonical) * ONE_EM;\n            const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0;\n\n            const textAnchor = layout.get('text-anchor').evaluate(feature, {}, args.canonical);\n            const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, args.canonical);\n\n            if (!variableAnchorOffset) {\n                const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, args.canonical);\n                // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector\n                // is calculated at placement time instead of layout time\n                if (radialOffset) {\n                    // The style spec says don't use `text-offset` and `text-radial-offset` together\n                    // but doesn't actually specify what happens if you use both. We go with the radial offset.\n                    textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]);\n                } else {\n                    textOffset = (layout.get('text-offset').evaluate(feature, {}, args.canonical).map(t => t * ONE_EM) as [number, number]);\n                }\n            }\n\n            let textJustify = textAlongLine ?\n                'center' :\n                layout.get('text-justify').evaluate(feature, {}, args.canonical);\n\n            const symbolPlacement = layout.get('symbol-placement');\n            const maxWidth = symbolPlacement === 'point' ?\n                layout.get('text-max-width').evaluate(feature, {}, args.canonical) * ONE_EM :\n                Infinity;\n\n            const addVerticalShapingForPointLabelIfNeeded = () => {\n                if (args.bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) {\n                    // Vertical POI label placement is meant to be used for scripts that support vertical\n                    // writing mode, thus, default left justification is used. If Latin\n                    // scripts would need to be supported, this should take into account other justifications.\n                    shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor,\n                        'left', spacingIfAllowed, textOffset, WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom);\n                }\n            };\n\n            // If this layer uses text-variable-anchor, generate shapings for all justification possibilities.\n            if (!textAlongLine && variableAnchorOffset) {\n                const justifications = new Set<TextJustify>();\n\n                if (textJustify === 'auto') {\n                    for (let i = 0; i < variableAnchorOffset.values.length; i += 2) {\n                        justifications.add(getAnchorJustification(variableAnchorOffset.values[i] as TextAnchor));\n                    }\n                } else {\n                    justifications.add(textJustify);\n                }\n\n                let singleLine = false;\n                for (const justification of justifications) {\n                    if (shapedTextOrientations.horizontal[justification]) continue;\n                    if (singleLine) {\n                        // If the shaping for the first justification was only a single line, we\n                        // can re-use it for the other justifications\n                        shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0];\n                    } else {\n                        // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply\n                        // the offsets for the anchor in the placement step.\n                        const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, 'center',\n                            justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);\n                        if (shaping) {\n                            shapedTextOrientations.horizontal[justification] = shaping;\n                            singleLine = shaping.positionedLines.length === 1;\n                        }\n                    }\n                }\n\n                addVerticalShapingForPointLabelIfNeeded();\n            } else {\n                if (textJustify === 'auto') {\n                    textJustify = getAnchorJustification(textAnchor);\n                }\n\n                // Horizontal point or line label.\n                const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed,\n                    textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);\n                if (shaping) shapedTextOrientations.horizontal[textJustify] = shaping;\n\n                // Vertical point label (if allowVerticalPlacement is enabled).\n                addVerticalShapingForPointLabelIfNeeded();\n\n                // Verticalized line label.\n                if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) {\n                    shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify,\n                        spacingIfAllowed, textOffset, WritingMode.vertical, false, layoutTextSize, layoutTextSizeThisZoom);\n                }\n            }\n        }\n\n        let shapedIcon;\n        let isSDFIcon = false;\n        if (feature.icon?.name) {\n            const image = args.imageMap[feature.icon.name];\n            if (image) {\n                shapedIcon = shapeIcon(\n                    args.imagePositions[feature.icon.name],\n                    layout.get('icon-offset').evaluate(feature, {}, args.canonical),\n                    layout.get('icon-anchor').evaluate(feature, {}, args.canonical));\n                // null/undefined SDF property treated same as default (false)\n                isSDFIcon = !!image.sdf;\n                if (args.bucket.sdfIcons === undefined) {\n                    args.bucket.sdfIcons = isSDFIcon;\n                } else if (args.bucket.sdfIcons !== isSDFIcon) {\n                    warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer');\n                }\n                if (image.pixelRatio !== args.bucket.pixelRatio) {\n                    args.bucket.iconsNeedLinear = true;\n                } else if (layout.get('icon-rotate').constantOr(1) !== 0) {\n                    args.bucket.iconsNeedLinear = true;\n                }\n            }\n        }\n\n        const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical;\n        args.bucket.iconsInText ||= shapedText ? shapedText.iconsInText : false;\n        if (shapedText || shapedIcon) {\n            addFeature(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical, args.subdivisionGranularity, args.hasPromoteId);\n        }\n    }\n\n    if (args.showCollisionBoxes) {\n        args.bucket.generateCollisionDebugBuffers();\n    }\n}\n\n// Choose the justification that matches the direction of the TextAnchor\nexport function getAnchorJustification(anchor: TextAnchor): TextJustify {\n    switch (anchor) {\n        case 'right':\n        case 'top-right':\n        case 'bottom-right':\n            return 'right';\n        case 'left':\n        case 'top-left':\n        case 'bottom-left':\n            return 'left';\n    }\n    return 'center';\n}\n\n/**\n * Given a feature and its shaped text and icon data, add a 'symbol\n * instance' for each _possible_ placement of the symbol feature.\n * (At render it selects which of these instances to\n * show or hide based on collisions with symbols in other layers.)\n */\nfunction addFeature(bucket: SymbolBucket,\n    feature: SymbolFeature,\n    shapedTextOrientations: ShapedTextOrientations,\n    shapedIcon: PositionedIcon,\n    imageMap: {[_: string]: StyleImage},\n    sizes: Sizes,\n    layoutTextSize: number,\n    layoutIconSize: number,\n    textOffset: [number, number],\n    isSDFIcon: boolean,\n    canonical: CanonicalTileID,\n    subdivisionGranularity: SubdivisionGranularitySetting,\n    hasPromoteId: boolean) {\n    // To reduce the number of labels that jump around when zooming we need\n    // to use a text-size value that is the same for all zoom levels.\n    // bucket calculates text-size at a high zoom level so that all tiles can\n    // use the same value when calculating anchor positions.\n    let textMaxSize = sizes.textMaxSize.evaluate(feature, {});\n    if (textMaxSize === undefined) {\n        textMaxSize = layoutTextSize;\n    }\n    const layout = bucket.layers[0].layout;\n    const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical);\n    const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal);\n    const glyphSize = 24,\n        fontScale = layoutTextSize / glyphSize,\n        textBoxScale = bucket.tilePixelRatio * fontScale,\n        textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize,\n        iconBoxScale = bucket.tilePixelRatio * layoutIconSize,\n        symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'),\n        textPadding = layout.get('text-padding') * bucket.tilePixelRatio,\n        iconPadding = getIconPadding(layout, feature, canonical, bucket.tilePixelRatio),\n        textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI,\n        textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point',\n        iconAlongLine = layout.get('icon-rotation-alignment').constantOr('viewport') === 'map' && layout.get('symbol-placement') !== 'point',\n        symbolPlacement = layout.get('symbol-placement'),\n        textRepeatDistance = symbolMinDistance / 2;\n\n    const iconTextFit = layout.get('icon-text-fit');\n    let verticallyShapedIcon: PositionedIcon | undefined;\n    // Adjust shaped icon size when icon-text-fit is used.\n    if (shapedIcon && iconTextFit !== 'none') {\n        if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n            verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit,\n                layout.get('icon-text-fit-padding'), iconOffset, fontScale);\n        }\n        if (defaultHorizontalShaping) {\n            shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit,\n                layout.get('icon-text-fit-padding'), iconOffset, fontScale);\n        }\n    }\n\n    const granularity = (canonical) ? subdivisionGranularity.line.getGranularityForZoomLevel(canonical.z) : 1;\n\n    const addSymbolAtAnchor = (line, anchor) => {\n        if (isOutsideTile(anchor)) {\n            // Symbol layers are drawn across tile boundaries, We filter out symbols\n            // outside our tile boundaries (which may be included in vector tile buffers)\n            // to prevent double-drawing symbols.\n            return;\n        }\n        addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0],\n            bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index,\n            textBoxScale, [textPadding, textPadding, textPadding, textPadding], textAlongLine, textOffset,\n            iconBoxScale, iconPadding, iconAlongLine, iconOffset,\n            feature, sizes, isSDFIcon, canonical, layoutTextSize, hasPromoteId);\n    };\n\n    if (symbolPlacement === 'line') {\n        for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) {\n            const subdividedLine = subdivideVertexLine(line, granularity);\n            const anchors = getAnchors(\n                subdividedLine,\n                symbolMinDistance,\n                textMaxAngle,\n                shapedTextOrientations.vertical || defaultHorizontalShaping,\n                shapedIcon,\n                glyphSize,\n                textMaxBoxScale,\n                bucket.overscaling,\n                EXTENT\n            );\n            for (const anchor of anchors) {\n                const shapedText = defaultHorizontalShaping;\n                if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) {\n                    addSymbolAtAnchor(subdividedLine, anchor);\n                }\n            }\n        }\n    } else if (symbolPlacement === 'line-center') {\n        // No clipping, multiple lines per feature are allowed\n        // \"lines\" with only one point are ignored as in clipLines\n        for (const line of feature.geometry) {\n            if (line.length > 1) {\n                const subdividedLine = subdivideVertexLine(line, granularity);\n                const anchor = getCenterAnchor(\n                    subdividedLine,\n                    textMaxAngle,\n                    shapedTextOrientations.vertical || defaultHorizontalShaping,\n                    shapedIcon,\n                    glyphSize,\n                    textMaxBoxScale);\n                if (anchor) {\n                    addSymbolAtAnchor(subdividedLine, anchor);\n                }\n            }\n        }\n    } else if (feature.type === 'Polygon') {\n        for (const polygon of classifyRings(feature.geometry, 0)) {\n            // 16 here represents 2 pixels\n            const poi = findPoleOfInaccessibility(polygon, 16);\n            const subdividedLine = subdivideVertexLine(polygon[0], granularity, true);\n            addSymbolAtAnchor(subdividedLine, new Anchor(poi.x, poi.y, 0));\n        }\n    } else if (feature.type === 'LineString') {\n        // https://github.com/mapbox/mapbox-gl-js/issues/3808\n        for (const line of feature.geometry) {\n            const subdividedLine = subdivideVertexLine(line, granularity);\n            addSymbolAtAnchor(subdividedLine, new Anchor(subdividedLine[0].x, subdividedLine[0].y, 0));\n        }\n    } else if (feature.type === 'Point') {\n        for (const points of feature.geometry) {\n            for (const point of points) {\n                addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0));\n            }\n        }\n    }\n}\n\nfunction addTextVariableAnchorOffsets(textAnchorOffsets: TextAnchorOffsetArray, variableAnchorOffset: VariableAnchorOffsetCollection): [number, number] {\n    const startIndex = textAnchorOffsets.length;\n    const values = variableAnchorOffset?.values;\n\n    if (values?.length > 0) {\n        for (let i = 0; i < values.length; i += 2) {\n            const anchor = TextAnchorEnum[values[i] as TextAnchor];\n            const offset = values[i + 1] as [number, number];\n\n            textAnchorOffsets.emplaceBack(anchor, offset[0], offset[1]);\n        }\n    }\n\n    return [startIndex, textAnchorOffsets.length];\n}\n\nfunction addTextVertices(bucket: SymbolBucket,\n    anchor: Point,\n    shapedText: Shaping,\n    imageMap: {[_: string]: StyleImage},\n    layer: SymbolStyleLayer,\n    textAlongLine: boolean,\n    feature: SymbolFeature,\n    textOffset: [number, number],\n    elevation: number,\n    lineArray: {\n        lineStartIndex: number;\n        lineLength: number;\n    },\n    writingMode: WritingMode,\n    placementTypes: Array<'vertical' | 'center' | 'left' | 'right'>,\n    placedTextSymbolIndices: {[_: string]: number},\n    placedIconIndex: number,\n    sizes: Sizes,\n    canonical: CanonicalTileID) {\n    const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset,\n        layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement);\n\n    const sizeData = bucket.textSizeData;\n    let textSizeData = null;\n\n    if (sizeData.kind === 'source') {\n        textSizeData = [\n            SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {})\n        ];\n        if (textSizeData[0] > MAX_PACKED_SIZE) {\n            warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n        }\n    } else if (sizeData.kind === 'composite') {\n        textSizeData = [\n            SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical),\n            SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical)\n        ];\n        if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) {\n            warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n        }\n    }\n\n    bucket.addSymbols(\n        bucket.text,\n        glyphQuads,\n        textSizeData,\n        textOffset,\n        textAlongLine,\n        feature,\n        writingMode,\n        anchor,\n        lineArray.lineStartIndex,\n        lineArray.lineLength,\n        placedIconIndex,\n        canonical,\n        elevation);\n\n    // The placedSymbolArray is used at render time in drawTileSymbols\n    // These indices allow access to the array at collision detection time\n    for (const placementType of placementTypes) {\n        placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1;\n    }\n\n    return glyphQuads.length * 4;\n}\n\nfunction getDefaultHorizontalShaping(\n    horizontalShaping: Record<TextJustify, Shaping>\n): Shaping | null {\n    // We don't care which shaping we get because this is used for collision purposes\n    // and all the justifications have the same collision box\n    for (const justification in horizontalShaping) {\n        return horizontalShaping[justification];\n    }\n    return null;\n}\n\n/**\n * Add a single label & icon placement.\n */\nfunction addSymbol(bucket: SymbolBucket,\n    anchor: Anchor,\n    line: Point[],\n    shapedTextOrientations: ShapedTextOrientations,\n    shapedIcon: PositionedIcon | undefined,\n    imageMap: {[_: string]: StyleImage},\n    verticallyShapedIcon: PositionedIcon | undefined,\n    layer: SymbolStyleLayer,\n    collisionBoxArray: CollisionBoxArray,\n    featureIndex: number,\n    sourceLayerIndex: number,\n    bucketIndex: number,\n    textBoxScale: number,\n    textPadding: SymbolPadding,\n    textAlongLine: boolean,\n    textOffset: [number, number],\n    iconBoxScale: number,\n    iconPadding: SymbolPadding,\n    iconAlongLine: boolean,\n    iconOffset: [number, number],\n    feature: SymbolFeature,\n    sizes: Sizes,\n    isSDFIcon: boolean,\n    canonical: CanonicalTileID,\n    layoutTextSize: number,\n    hasPromoteId: boolean) {\n\n    const lineArray = bucket.addToLineVertexArray(anchor, line);\n    const elevation = layer.layout.get('symbol-height-offset').evaluate(feature, {}, canonical);\n    if (elevation > bucket.maxHeightOffset) {\n        bucket.maxHeightOffset = elevation;\n    }\n\n    let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature;\n\n    let numIconVertices = 0;\n    let numVerticalIconVertices = 0;\n    let numHorizontalGlyphVertices = 0;\n    let numVerticalGlyphVertices = 0;\n    let placedIconSymbolIndex = -1;\n    let verticalPlacedIconSymbolIndex = -1;\n    const placedTextSymbolIndices: {[k: string]: number} = {};\n    let key = murmur3('');\n\n    if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n        const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n        const verticalTextRotation = textRotation + 90.0;\n        const verticalShaping = shapedTextOrientations.vertical;\n        verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation);\n\n        if (verticallyShapedIcon) {\n            verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation);\n        }\n    }\n\n    //Place icon first, so text can have a reference to its index in the placed symbol array.\n    //Text symbols can lazily shift at render-time because of variable anchor placement.\n    //If the style specifies an `icon-text-fit` then the icon would have to shift along with it.\n    // For more info check `updateVariableAnchors` in `draw_symbol.js` .\n    if (shapedIcon) {\n        const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {});\n        const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none';\n        const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit);\n        const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined;\n        iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/false, iconRotate);\n\n        numIconVertices = iconQuads.length * 4;\n\n        const sizeData = bucket.iconSizeData;\n        let iconSizeData = null;\n\n        if (sizeData.kind === 'source') {\n            iconSizeData = [\n                SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {})\n            ];\n            if (iconSizeData[0] > MAX_PACKED_SIZE) {\n                warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n            }\n        } else if (sizeData.kind === 'composite') {\n            iconSizeData = [\n                SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical),\n                SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical)\n            ];\n            if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) {\n                warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n            }\n        }\n\n        bucket.addSymbols(\n            bucket.icon,\n            iconQuads,\n            iconSizeData,\n            iconOffset,\n            iconAlongLine,\n            feature,\n            WritingMode.none,\n            anchor,\n            lineArray.lineStartIndex,\n            lineArray.lineLength,\n            // The icon itself does not have an associated symbol since the text isn't placed yet\n            -1, \n            canonical, \n            elevation);\n\n        placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;\n\n        if (verticalIconQuads) {\n            numVerticalIconVertices = verticalIconQuads.length * 4;\n\n            bucket.addSymbols(\n                bucket.icon,\n                verticalIconQuads,\n                iconSizeData,\n                iconOffset,\n                iconAlongLine,\n                feature,\n                WritingMode.vertical,\n                anchor,\n                lineArray.lineStartIndex,\n                lineArray.lineLength,\n                // The icon itself does not have an associated symbol since the text isn't placed yet\n                -1, \n                canonical, \n                elevation);\n\n            verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;\n        }\n    }\n\n    const justifications = Object.keys(shapedTextOrientations.horizontal) as TextJustify[];\n    for (const justification of justifications) {\n        const shaping = shapedTextOrientations.horizontal[justification];\n\n        if (!textCollisionFeature) {\n            key = murmur3(shaping.text);\n            const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n            // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature\n            // We're counting on all versions having similar dimensions\n            textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate);\n        }\n\n        const singleLine = shaping.positionedLines.length === 1;\n        numHorizontalGlyphVertices += addTextVertices(\n            bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, elevation, lineArray,\n            shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly,\n            singleLine ? justifications : [justification],\n            placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical);\n\n        if (singleLine) {\n            break;\n        }\n    }\n\n    if (shapedTextOrientations.vertical) {\n        numVerticalGlyphVertices += addTextVertices(\n            bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature,\n            textOffset, elevation, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical);\n    }\n\n    const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n    const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n    const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n    const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n    const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n    const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n    const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n    const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n    // Check if runtime collision circles should be used for any of the collision features.\n    // It is enough to choose the tallest feature shape as circles are always placed on a line.\n    // All measurements are in glyph metrics and later converted into pixels using proper font size \"layoutTextSize\"\n    let collisionCircleDiameter = -1;\n\n    const getCollisionCircleHeight = (feature: CollisionFeature, prevHeight: number): number => {\n        if (feature?.circleDiameter)\n            return Math.max(feature.circleDiameter, prevHeight);\n        return prevHeight;\n    };\n\n    collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter);\n    collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter);\n    collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter);\n    collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter);\n    const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0;\n\n    // Convert circle collision height into pixels\n    if (useRuntimeCollisionCircles)\n        collisionCircleDiameter *= layoutTextSize / ONE_EM;\n\n    if (bucket.glyphOffsetArray.length >= bucket.maxGlyphs) warnOnce(\n        'Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907'\n    );\n\n    if (feature.sortKey !== undefined) {\n        bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey as number);\n    }\n\n    const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, canonical);\n    const [textAnchorOffsetStartIndex, textAnchorOffsetEndIndex] = addTextVariableAnchorOffsets(bucket.textAnchorOffsets, variableAnchorOffset);\n\n    if (hasPromoteId) {\n        key = keyWithFeatureId(key, feature);\n    }\n\n    bucket.symbolInstances.emplaceBack(\n        anchor.x,\n        anchor.y,\n        placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1,\n        placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1,\n        placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1,\n        placedTextSymbolIndices.vertical || -1,\n        placedIconSymbolIndex,\n        verticalPlacedIconSymbolIndex,\n        key,\n        textBoxStartIndex,\n        textBoxEndIndex,\n        verticalTextBoxStartIndex,\n        verticalTextBoxEndIndex,\n        iconBoxStartIndex,\n        iconBoxEndIndex,\n        verticalIconBoxStartIndex,\n        verticalIconBoxEndIndex,\n        featureIndex,\n        numHorizontalGlyphVertices,\n        numVerticalGlyphVertices,\n        numIconVertices,\n        numVerticalIconVertices,\n        useRuntimeCollisionCircles,\n        0,\n        textBoxScale,\n        collisionCircleDiameter,\n        textAnchorOffsetStartIndex,\n        textAnchorOffsetEndIndex,\n        elevation);\n}\n\nfunction anchorIsTooClose(bucket: SymbolBucket, text: string, repeatDistance: number, anchor: Point) {\n    const compareText = bucket.compareText;\n    if (!(text in compareText)) {\n        compareText[text] = [];\n    } else {\n        const otherAnchors = compareText[text];\n        for (let k = otherAnchors.length - 1; k >= 0; k--) {\n            if (anchor.dist(otherAnchors[k]) < repeatDistance) {\n                // If it's within repeatDistance of one anchor, stop looking\n                return true;\n            }\n        }\n    }\n    // If anchor is not within repeatDistance of any other anchor, add to array\n    compareText[text].push(anchor);\n    return false;\n}\n\n/**\n * Hashes a promoted feature id into a symbol's cross-tile key, so that labels of different features never compete for\n * a match in the `CrossTileSymbolIndex` even when their text and anchors coincide. Clusters keep the text-only\n * key: supercluster gives a cluster an id that encodes the zoom it formed at, so the same cluster has a different id in\n * every zoom level's tile.\n */\nfunction keyWithFeatureId(key: number, feature: SymbolFeature): number {\n    if (feature.id == null || feature.properties?.cluster) {\n        return key;\n    }\n    return murmur3(String(feature.id), key);\n}\n", "import type {PossiblyEvaluated} from '../properties.ts';\nimport type {SymbolLayoutPropsPossiblyEvaluated} from './symbol_style_layer_properties.g.ts';\nimport type {SymbolLayoutProps} from './symbol_style_layer_properties.g.ts';\n\n/**\n * The overlap mode for properties like `icon-overlap`and `text-overlap`\n */\nexport type OverlapMode = 'never' | 'always' | 'cooperative';\n\nexport function getOverlapMode(layout: PossiblyEvaluated<SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated>, overlapProp: 'icon-overlap', allowOverlapProp: 'icon-allow-overlap'): OverlapMode;\nexport function getOverlapMode(layout: PossiblyEvaluated<SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated>, overlapProp: 'text-overlap', allowOverlapProp: 'text-allow-overlap'): OverlapMode;\nexport function getOverlapMode(layout: PossiblyEvaluated<SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated>, overlapProp: 'icon-overlap' | 'text-overlap', allowOverlapProp: 'icon-allow-overlap' | 'text-allow-overlap'): OverlapMode {\n    let result: OverlapMode = 'never';\n    const overlap = layout.get(overlapProp);\n\n    if (overlap) {\n        // if -overlap is set, use it\n        result = overlap;\n    } else if (layout.get(allowOverlapProp)) {\n        // fall back to -allow-overlap, with false='never', true='always'\n        result = 'always';\n    }\n\n    return result;\n}\n", "import {\n    symbolLayoutAttributes,\n    collisionVertexAttributes,\n    collisionBoxLayout,\n    dynamicLayoutAttributes,\n} from './symbol_attributes.ts';\nimport {SymbolLayoutArray,\n    SymbolDynamicLayoutArray,\n    SymbolOpacityArray,\n    CollisionBoxLayoutArray,\n    CollisionVertexArray,\n    PlacedSymbolArray,\n    SymbolInstanceArray,\n    GlyphOffsetArray,\n    SymbolLineVertexArray,\n    TextAnchorOffsetArray\n} from '../array_types.g.ts';\nimport Point from '@mapbox/point-geometry';\nimport {SegmentVector} from '../segment.ts';\nimport {ProgramConfigurationSet} from '../program_configuration.ts';\nimport {TriangleIndexArray, LineIndexArray} from '../array_types.g.ts';\nimport {transformText} from '../../symbol/transform_text.ts';\nimport {mergeLines} from '../../symbol/merge_lines.ts';\nimport {isCluster} from '../../util/graphemes.ts';\nimport {TaggedString} from '../../symbol/tagged_string.ts';\nimport {allowsVerticalWritingMode, stringContainsRTLText} from '../../util/script_detection.ts';\nimport {mayUseVerticalGlyph, WritingMode} from '../../symbol/shaping.ts';\nimport {loadGeometry} from '../load_geometry.ts';\nimport {toEvaluationFeature} from '../evaluation_feature.ts';\nimport {VectorTileFeature} from '@mapbox/vector-tile';\nimport {verticalizedCharacterMap} from '../../util/verticalize_punctuation.ts';\nimport {getSizeData, MAX_PACKED_SIZE, MAX_GLYPHS} from '../../symbol/symbol_size.ts';\nimport {performSymbolLayout} from '../../symbol/symbol_layout.ts';\nimport {isOutsideTile} from '../extent_bounds.ts';\nimport {register} from '../../util/web_worker_transfer.ts';\nimport {EvaluationParameters} from '../../style/evaluation_parameters.ts';\nimport {Formatted, ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\nimport {getOverlapMode} from '../../style/style_layer/overlap_mode.ts';\n\nimport type {Anchor} from '../../symbol/anchor.ts';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {\n    Bucket,\n    BucketParameters,\n    BucketDependencyParameters,\n    IndexedFeature,\n    PopulateParameters\n} from '../bucket.ts';\nimport type {CollisionBoxArray, CollisionBox, SymbolInstance} from '../array_types.g.ts';\nimport type {StructArray, StructArrayMember, ViewType} from '../../util/struct_array.ts';\nimport type {SymbolStyleLayer} from '../../style/style_layer/symbol_style_layer.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {IndexBuffer} from '../../webgl/index_buffer.ts';\nimport type {VertexBuffer} from '../../webgl/vertex_buffer.ts';\nimport type {SymbolQuad} from '../../symbol/quads.ts';\nimport type {SizeData} from '../../symbol/symbol_size.ts';\nimport type {FeatureStates} from '../../source/source_state.ts';\nimport type {ImagePosition} from '../../render/image_atlas.ts';\nimport type {VectorTileLayerLike} from '@maplibre/vt-pbf';\n\nexport type SingleCollisionBox = {\n    x1: number;\n    y1: number;\n    x2: number;\n    y2: number;\n    anchorPointX: number;\n    anchorPointY: number;\n};\n\nexport type CollisionArrays = {\n    textBox?: SingleCollisionBox;\n    verticalTextBox?: SingleCollisionBox;\n    iconBox?: SingleCollisionBox;\n    verticalIconBox?: SingleCollisionBox;\n    textFeatureIndex?: number;\n    verticalTextFeatureIndex?: number;\n    iconFeatureIndex?: number;\n    verticalIconFeatureIndex?: number;\n};\n\nexport type SymbolFeature = {\n    sortKey: number | void;\n    text: Formatted | void;\n    icon: ResolvedImage;\n    index: number;\n    sourceLayerIndex: number;\n    geometry: Point[][];\n    properties: any;\n    type: 'Unknown' | 'Point' | 'LineString' | 'Polygon';\n    id?: any;\n};\n\nexport type SortKeyRange = {\n    sortKey: number;\n    symbolInstanceStart: number;\n    symbolInstanceEnd: number;\n};\n\n// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them\n// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph\n// 7 bits are for the current opacity, and the lowest bit is the target opacity\n\n// actually defined in symbol_attributes.js\n// const placementOpacityAttributes = [\n//     { name: 'a_fade_opacity', components: 1, type: 'Uint32' }\n// ];\nconst shaderOpacityAttributes = [\n    {name: 'a_fade_opacity', components: 1, type: 'Uint8' as ViewType, offset: 0}\n];\n\nfunction addVertex(\n    array: StructArray,\n    anchorX: number,\n    anchorY: number,\n    ox: number,\n    oy: number,\n    tx: number,\n    ty: number,\n    sizeVertex: number,\n    isSDF: boolean,\n    pixelOffsetX: number,\n    pixelOffsetY: number,\n    minFontScaleX: number,\n    minFontScaleY: number,\n    elevation: number\n) {\n    const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0;\n    const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0;\n    array.emplaceBack(\n        // a_pos_offset\n        anchorX,\n        anchorY,\n        Math.round(ox * 32),\n        Math.round(oy * 32),\n\n        // a_data\n        tx, // x coordinate of symbol on glyph atlas texture\n        ty, // y coordinate of symbol on glyph atlas texture\n        (aSizeX << 1) + (isSDF ? 1 : 0),\n        aSizeY,\n        pixelOffsetX * 16,\n        pixelOffsetY * 16,\n        minFontScaleX * 256,\n        minFontScaleY * 256,\n        elevation\n    );\n}\n\nfunction addDynamicAttributes(dynamicLayoutVertexArray: StructArray, p: Point, angle: number): void {\n    dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n    dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n    dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n    dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n}\n\nfunction containsRTLText(formattedText: Formatted): boolean {\n    for (const section of formattedText.sections) {\n        if (stringContainsRTLText(section.text)) {\n            return true;\n        }\n    }\n    return false;\n}\n\nexport class SymbolBuffers {\n    layoutVertexArray: SymbolLayoutArray;\n    layoutVertexBuffer: VertexBuffer;\n\n    indexArray: TriangleIndexArray;\n    indexBuffer: IndexBuffer;\n\n    programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>;\n    segments: SegmentVector;\n\n    dynamicLayoutVertexArray: SymbolDynamicLayoutArray;\n    dynamicLayoutVertexBuffer: VertexBuffer;\n\n    opacityVertexArray: SymbolOpacityArray;\n    opacityVertexBuffer: VertexBuffer;\n    hasVisibleVertices: boolean;\n\n    collisionVertexArray: CollisionVertexArray;\n    collisionVertexBuffer: VertexBuffer;\n\n    placedSymbolArray: PlacedSymbolArray;\n\n    constructor(programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>) {\n        this.layoutVertexArray = new SymbolLayoutArray();\n        this.indexArray = new TriangleIndexArray();\n        this.programConfigurations = programConfigurations;\n        this.segments = new SegmentVector();\n        this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray();\n        this.opacityVertexArray = new SymbolOpacityArray();\n        this.hasVisibleVertices = false;\n        this.placedSymbolArray = new PlacedSymbolArray();\n    }\n\n    isEmpty(): boolean {\n        return this.layoutVertexArray.length === 0 &&\n            this.indexArray.length === 0 &&\n            this.dynamicLayoutVertexArray.length === 0 &&\n            this.opacityVertexArray.length === 0;\n    }\n\n    upload(context: Context, dynamicIndexBuffer: boolean, upload?: boolean, update?: boolean): void {\n        if (this.isEmpty()) {\n            return;\n        }\n\n        if (upload) {\n            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members);\n            this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer);\n            this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true);\n            this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true);\n            // This is a performance hack so that we can write to opacityVertexArray with uint32s\n            // even though the shaders read uint8s\n            this.opacityVertexBuffer.itemSize = 1;\n        }\n        if (upload || update) {\n            this.programConfigurations.upload(context);\n        }\n    }\n\n    destroy(): void {\n        if (!this.layoutVertexBuffer) return;\n        this.layoutVertexBuffer.destroy();\n        this.indexBuffer.destroy();\n        this.programConfigurations.destroy();\n        this.segments.destroy();\n        this.dynamicLayoutVertexBuffer.destroy();\n        this.opacityVertexBuffer.destroy();\n    }\n}\n\nregister('SymbolBuffers', SymbolBuffers);\n\nclass CollisionBuffers {\n    layoutVertexArray: StructArray;\n    layoutAttributes: StructArrayMember[];\n    layoutVertexBuffer: VertexBuffer;\n\n    indexArray: TriangleIndexArray | LineIndexArray;\n    indexBuffer: IndexBuffer;\n\n    segments: SegmentVector;\n\n    collisionVertexArray: CollisionVertexArray;\n    collisionVertexBuffer: VertexBuffer;\n\n    constructor(LayoutArray: {\n        new (...args: any): StructArray;\n    },\n    layoutAttributes: StructArrayMember[],\n    IndexArray: {\n        new (...args: any): TriangleIndexArray | LineIndexArray;\n    }) {\n        this.layoutVertexArray = new LayoutArray();\n        this.layoutAttributes = layoutAttributes;\n        this.indexArray = new IndexArray();\n        this.segments = new SegmentVector();\n        this.collisionVertexArray = new CollisionVertexArray();\n    }\n\n    upload(context: Context): void {\n        this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes);\n        this.indexBuffer = context.createIndexBuffer(this.indexArray);\n        this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true);\n    }\n\n    destroy(): void {\n        if (!this.layoutVertexBuffer) return;\n        this.layoutVertexBuffer.destroy();\n        this.indexBuffer.destroy();\n        this.segments.destroy();\n        this.collisionVertexBuffer.destroy();\n    }\n}\n\nregister('CollisionBuffers', CollisionBuffers);\n\n/**\n * @internal\n * Unlike other buckets, which simply implement `addFeature` with type-specific\n * logic for (essentially) triangulating feature geometries, SymbolBucket\n * requires specialized behavior:\n *\n * 1. WorkerTile.parse(), the logical owner of the bucket creation process,\n *    calls SymbolBucket.populate(), which resolves text and icon tokens on\n *    each feature, adds each glyphs and symbols needed to the passed-in\n *    collections options.glyphDependencies and options.iconDependencies, and\n *    stores the feature data for use in subsequent step (this.features).\n *\n * 2. WorkerTile asynchronously requests from the main thread all of the glyphs\n *    and icons needed (by this bucket and any others).\n *\n * 3. WorkerTile calls SymbolBucket.addFeatures(), which delegates text shaping\n *    and layout to performSymbolLayout(). This step populates:\n *      `this.symbolInstances`: metadata on generated symbols\n *      `this.collisionBoxArray`: collision data for use by foreground\n *      `this.text`: SymbolBuffers for text symbols\n *      `this.icons`: SymbolBuffers for icons\n *      `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes\n *      `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes\n *    The results are sent to the foreground for rendering\n *\n * 4. placement.ts is run on the foreground,\n *    and uses the CollisionIndex along with current camera settings to determine\n *    which symbols can actually show on the map. Collided symbols are hidden\n *    using a dynamic \"OpacityVertexArray\".\n */\nexport class SymbolBucket implements Bucket {\n    collisionBoxArray: CollisionBoxArray;\n    zoom: number;\n    overscaling: number;\n    layers: SymbolStyleLayer[];\n    layerIds: string[];\n    stateDependentLayers: SymbolStyleLayer[];\n    stateDependentLayerIds: string[];\n\n    index: number;\n    sdfIcons: boolean;\n    iconsInText: boolean;\n    iconsNeedLinear: boolean;\n    bucketInstanceId: number;\n    justReloaded: boolean;\n    hasDependencies: boolean;\n\n    textSizeData: SizeData;\n    iconSizeData: SizeData;\n\n    glyphOffsetArray: GlyphOffsetArray;\n    /**\n     * The glyph cap for this bucket, normally {@link MAX_GLYPHS}. Tests lower it to\n     * exercise the overflow warning without filling a bucket with 65,535 glyphs.\n     */\n    maxGlyphs: number;\n    lineVertexArray: SymbolLineVertexArray;\n    features: SymbolFeature[];\n    symbolInstances: SymbolInstanceArray;\n    textAnchorOffsets: TextAnchorOffsetArray;\n    collisionArrays: CollisionArrays[];\n    sortKeyRanges: SortKeyRange[];\n    pixelRatio: number;\n    tilePixelRatio: number;\n    compareText: {[_: string]: Point[]};\n    fadeStartTime: number;\n    sortFeaturesByKey: boolean;\n    sortFeaturesByY: boolean;\n    canOverlap: boolean;\n    sortedAngle: number;\n    featureSortOrder: number[];\n    maxHeightOffset: number;\n\n    collisionCircleArray: number[];\n\n    text: SymbolBuffers;\n    icon: SymbolBuffers;\n    textCollisionBox: CollisionBuffers;\n    iconCollisionBox: CollisionBuffers;\n    uploaded: boolean;\n    sourceLayerIndex: number;\n    sourceID: string;\n    symbolInstanceIndexes: number[];\n    writingModes: WritingMode[];\n    allowVerticalPlacement: boolean;\n    hasRTLText: boolean;\n\n    constructor(options: BucketParameters<SymbolStyleLayer>) {\n        this.collisionBoxArray = options.collisionBoxArray;\n        this.zoom = options.zoom;\n        this.overscaling = options.overscaling;\n        this.layers = options.layers;\n        this.layerIds = this.layers.map(layer => layer.id);\n        this.index = options.index;\n        this.pixelRatio = options.pixelRatio;\n        this.sourceLayerIndex = options.sourceLayerIndex;\n        this.hasDependencies = true;\n        this.hasRTLText = false;\n        this.maxHeightOffset = 0;\n        this.sortKeyRanges = [];\n\n        this.collisionCircleArray = [];\n        this.maxGlyphs = MAX_GLYPHS;\n\n        const layer = this.layers[0];\n        const unevaluatedLayoutValues = layer._unevaluatedLayout._values;\n\n        this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']);\n        this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']);\n\n        const layout = this.layers[0].layout;\n        const sortKey = layout.get('symbol-sort-key');\n        const zOrder = layout.get('symbol-z-order');\n        this.canOverlap =\n            getOverlapMode(layout, 'text-overlap', 'text-allow-overlap') !== 'never' ||\n            getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap') !== 'never' ||\n            layout.get('text-ignore-placement') ||\n            layout.get('icon-ignore-placement');\n        this.sortFeaturesByKey = zOrder !== 'viewport-y' && !sortKey.isConstant();\n        const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey);\n        this.sortFeaturesByY = zOrderByViewportY && this.canOverlap;\n\n        if (layout.get('symbol-placement') === 'point') {\n            this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]);\n        }\n\n        this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n\n        this.sourceID = options.sourceID;\n    }\n\n    createArrays(): void {\n        this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => property.startsWith('text')));\n        this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => property.startsWith('icon')));\n\n        this.glyphOffsetArray = new GlyphOffsetArray();\n        this.lineVertexArray = new SymbolLineVertexArray();\n        this.symbolInstances = new SymbolInstanceArray();\n        this.textAnchorOffsets = new TextAnchorOffsetArray();\n    }\n\n    /**\n     * Collects a label's default and vertical glyph dependencies into `stacks` for the tile to request.\n     *\n     * A cluster of several codepoints is asked for as a whole, so that it can be drawn as the one\n     * shape it is written as. Its codepoints are asked for as well, to give layout something to draw\n     * a codepoint at a time where the cluster itself yields no glyph. See `shapeLines`.\n     *\n     * A cluster can span two sections, a letter in one and the accent written on it in the next, so\n     * the label is taken as a whole and each cluster attributed to the section its first character\n     * came from -- the same way layout attributes it. Collecting each section's text on its own\n     * would ask for glyphs no cluster is ever looked up by.\n     *\n     * @param text - label text and section formatting\n     * @param stacks - destination for dependencies grouped by font stack and variant\n     * @param fontStack - default font stack for sections without a font override\n     * @param needsVerticalForms - whether to request vertical alternates and compatibility punctuation\n     */\n    private calculateGlyphDependencies(\n        text: Formatted,\n        stacks: PopulateParameters['glyphDependencies'],\n        fontStack: string,\n        needsVerticalForms: boolean): void {\n\n        const tagged = TaggedString.fromFeature(text, fontStack, false);\n        const graphemes = tagged.graphemes();\n\n        for (let i = 0; i < graphemes.length; i++) {\n            const section = tagged.getSection(i);\n            if ('imageName' in section) continue;\n\n            stacks[section.fontStack] ||= {default: {}, vertical: {}};\n            const stack = stacks[section.fontStack];\n            const grapheme = graphemes[i];\n            const needsVerticalGlyph = needsVerticalForms && mayUseVerticalGlyph(grapheme.codePointAt(0), this.allowVerticalPlacement);\n            if (isCluster(grapheme)) stack.default[grapheme] = true;\n            if (needsVerticalGlyph) stack.vertical[grapheme] = true;\n\n            for (const char of grapheme) {\n                stack.default[char] = true;\n                if (!needsVerticalForms) continue;\n\n                if (needsVerticalGlyph && isCluster(grapheme)) stack.vertical[char] = true;\n                const verticalChar = verticalizedCharacterMap[char];\n                if (verticalChar) stack.default[verticalChar] = true;\n            }\n        }\n    }\n\n    populate(features: IndexedFeature[], options: PopulateParameters, canonical: CanonicalTileID): void {\n        const layer = this.layers[0];\n        const layout = layer.layout;\n\n        const textFont = layout.get('text-font');\n        const textField = layout.get('text-field');\n        const iconImage = layout.get('icon-image');\n        const hasText =\n            (textField.value.kind !== 'constant' ||\n                (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) ||\n                textField.value.value.toString().length > 0) &&\n            (textFont.value.kind !== 'constant' || textFont.value.value.length > 0);\n        // we should always resolve the icon-image value if the property was defined in the style\n        // this allows us to fire the styleimagemissing event if image evaluation returns null\n        // the only way to distinguish between null returned from a coalesce statement with no valid images\n        // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object\n        const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0;\n        const symbolSortKey = layout.get('symbol-sort-key');\n        const pointPlacement = layout.get('symbol-placement') === 'point';\n\n        this.features = [];\n\n        if (!hasText && !hasIcon) {\n            return;\n        }\n\n        const icons = options.iconDependencies;\n        const stacks = options.glyphDependencies;\n        const availableImages = options.availableImages;\n        const globalProperties = new EvaluationParameters(this.zoom);\n        const keepUpright = layout.get('text-keep-upright');\n\n        for (const {feature, id, index, sourceLayerIndex} of features) {\n\n            const needGeometry = layer._featureFilter.needGeometry;\n            const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n            if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {\n                continue;\n            }\n\n            if (!needGeometry)  evaluationFeature.geometry = loadGeometry(feature);\n\n            if (pointPlacement && feature.type === 1 && isEveryPointOutsideTile(evaluationFeature.geometry)) continue;\n\n            let text: Formatted | void;\n            if (hasText) {\n                // Expression evaluation will automatically coerce to Formatted\n                // but plain string token evaluation skips that pathway so do the\n                // conversion here.\n                const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages);\n                const formattedText = Formatted.factory(resolvedTokens);\n\n                this.hasRTLText ||= containsRTLText(formattedText);\n                text = transformText(formattedText, layer, evaluationFeature);\n            }\n\n            let icon: ResolvedImage;\n            if (hasIcon) {\n                // Expression evaluation will automatically coerce to Image\n                // but plain string token evaluation skips that pathway so do the\n                // conversion here.\n                const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages);\n                if (resolvedTokens instanceof ResolvedImage) {\n                    icon = resolvedTokens;\n                } else {\n                    icon = ResolvedImage.fromString(resolvedTokens);\n                }\n            }\n\n            if (!text && !icon) {\n                continue;\n            }\n            const sortKey = this.sortFeaturesByKey ?\n                symbolSortKey.evaluate(evaluationFeature, {}, canonical) :\n                undefined;\n\n            const symbolFeature: SymbolFeature = {\n                id,\n                text,\n                icon,\n                index,\n                sourceLayerIndex,\n                geometry: evaluationFeature.geometry,\n                properties: feature.properties,\n                type: VectorTileFeature.types[feature.type],\n                sortKey\n            };\n            this.features.push(symbolFeature);\n\n            if (icon) {\n                icons[icon.name] = true;\n            }\n\n            if (text) {\n                const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(',');\n                const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point';\n                this.allowVerticalPlacement = this.writingModes?.includes(WritingMode.vertical);\n                const needsVerticalForms = ((textAlongLine && keepUpright) || this.allowVerticalPlacement) &&\n                    allowsVerticalWritingMode(text.toString());\n                this.calculateGlyphDependencies(text, stacks, fontStack, needsVerticalForms);\n\n                for (const section of text.sections) {\n                    if (section.image) icons[section.image.name] = true;\n                }\n            }\n        }\n\n        if (layout.get('symbol-placement') === 'line') {\n            // Merge adjacent lines with the same text to improve labeling.\n            // It's better to place labels on one long line than on many short segments.\n            this.features = mergeLines(this.features);\n        }\n\n        if (this.sortFeaturesByKey) {\n            this.features.sort((a, b) => {\n                // a.sortKey is always a number when sortFeaturesByKey is true\n                return (a.sortKey as number) - (b.sortKey as number);\n            });\n        }\n    }\n\n    update(states: FeatureStates, vtLayer: VectorTileLayerLike, imagePositions: {[_: string]: ImagePosition}): void {\n        if (!this.stateDependentLayers.length) return;\n        this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, {\n            imagePositions\n        });\n        this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, {\n            imagePositions\n        });\n    }\n\n    addFeatures({options, canonical, glyphMap, glyphPositions, iconMap, iconPositions, showCollisionBoxes}: BucketDependencyParameters): void {\n        performSymbolLayout({\n            bucket: this,\n            glyphMap,\n            glyphPositions,\n            imageMap: iconMap,\n            imagePositions: iconPositions,\n            showCollisionBoxes,\n            canonical,\n            subdivisionGranularity: options.subdivisionGranularity,\n            hasPromoteId: options.featureIndex.promoteId != null\n        });\n    }\n\n    isEmpty(): boolean {\n        return this.symbolInstances.length === 0;\n    }\n\n    uploadPending(): boolean {\n        return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload;\n    }\n\n    upload(context: Context): void {\n        if (!this.uploaded && this.hasDebugData()) {\n            this.textCollisionBox.upload(context);\n            this.iconCollisionBox.upload(context);\n        }\n        this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload);\n        this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload);\n        this.uploaded = true;\n    }\n\n    destroyDebugData(): void {\n        this.textCollisionBox.destroy();\n        this.iconCollisionBox.destroy();\n    }\n\n    destroy(): void {\n        this.text.destroy();\n        this.icon.destroy();\n\n        if (this.hasDebugData()) {\n            this.destroyDebugData();\n        }\n    }\n\n    addToLineVertexArray(anchor: Anchor, line: Point[]): {lineStartIndex: number; lineLength: number} {\n        const lineStartIndex = this.lineVertexArray.length;\n        if (anchor.segment !== undefined) {\n            let sumForwardLength = anchor.dist(line[anchor.segment + 1]);\n            let sumBackwardLength = anchor.dist(line[anchor.segment]);\n            const vertices = {};\n            for (let i = anchor.segment + 1; i < line.length; i++) {\n                vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength};\n                if (i < line.length - 1) {\n                    sumForwardLength += line[i + 1].dist(line[i]);\n                }\n            }\n            for (let i = anchor.segment || 0; i >= 0; i--) {\n                vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength};\n                if (i > 0) {\n                    sumBackwardLength += line[i - 1].dist(line[i]);\n                }\n            }\n            for (let i = 0; i < line.length; i++) {\n                const vertex = vertices[i];\n                this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor);\n            }\n        }\n        const result: {lineStartIndex: number; lineLength: number} = {\n            lineStartIndex,\n            lineLength: this.lineVertexArray.length - lineStartIndex\n        };\n        return result;\n    }\n\n    addSymbols(arrays: SymbolBuffers,\n        quads: SymbolQuad[],\n        sizeVertex: any,\n        lineOffset: [number, number],\n        alongLine: boolean,\n        feature: SymbolFeature,\n        writingMode: WritingMode,\n        labelAnchor: Anchor,\n        lineStartIndex: number,\n        lineLength: number,\n        associatedIconIndex: number,\n        canonical: CanonicalTileID,\n        elevation: number): void {\n        const indexArray = arrays.indexArray;\n        const layoutVertexArray = arrays.layoutVertexArray;\n\n        const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey as number : undefined);\n        const glyphOffsetArrayStart = this.glyphOffsetArray.length;\n        const vertexStartIndex = segment.vertexLength;\n\n        const angle = (this.allowVerticalPlacement && writingMode === WritingMode.vertical) ? Math.PI / 2 : 0;\n\n        const sections = feature.text && feature.text.sections;\n\n        for (let i = 0; i < quads.length; i++) {\n            const {tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex} = quads[i];\n            const index = segment.vertexLength;\n\n            const y = glyphOffset[1];\n            addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY, elevation);\n            addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY, elevation);\n            addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY, elevation);\n            addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY, elevation);\n\n            addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle);\n\n            indexArray.emplaceBack(index, index + 2, index + 1);\n            indexArray.emplaceBack(index + 1, index + 2, index + 3);\n\n            segment.vertexLength += 4;\n            segment.primitiveLength += 2;\n\n            this.glyphOffsetArray.emplaceBack(glyphOffset[0]);\n\n            if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) {\n                arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {imagePositions: {}, canonical, formattedSection: sections?.[sectionIndex]});\n            }\n        }\n\n        arrays.placedSymbolArray.emplaceBack(\n            labelAnchor.x, labelAnchor.y,\n            glyphOffsetArrayStart,\n            this.glyphOffsetArray.length - glyphOffsetArrayStart,\n            vertexStartIndex,\n            lineStartIndex,\n            lineLength,\n            labelAnchor.segment,\n            sizeVertex ? sizeVertex[0] : 0,\n            sizeVertex ? sizeVertex[1] : 0,\n            lineOffset[0], lineOffset[1],\n            writingMode,\n            // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed\n            0,\n            false as unknown as number,\n            // The crossTileID is only filled/used on the foreground for dynamic text anchors\n            0,\n            associatedIconIndex,\n            elevation\n        );\n    }\n\n    _addCollisionDebugVertex(layoutVertexArray: StructArray, collisionVertexArray: StructArray, point: Point, anchorX: number, anchorY: number, extrude: Point): number {\n        collisionVertexArray.emplaceBack(0, 0);\n        return layoutVertexArray.emplaceBack(\n            // pos\n            point.x,\n            point.y,\n            // a_anchor_pos\n            anchorX,\n            anchorY,\n            // extrude\n            Math.round(extrude.x),\n            Math.round(extrude.y));\n    }\n\n    addCollisionDebugVertices(x1: number, y1: number, x2: number, y2: number, arrays: CollisionBuffers, boxAnchorPoint: Point, symbolInstance: SymbolInstance): void {\n        const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);\n        const index = segment.vertexLength;\n\n        const layoutVertexArray = arrays.layoutVertexArray;\n        const collisionVertexArray = arrays.collisionVertexArray;\n\n        const anchorX = symbolInstance.anchorX;\n        const anchorY = symbolInstance.anchorY;\n\n        this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y1));\n        this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y1));\n        this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y2));\n        this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y2));\n\n        segment.vertexLength += 4;\n\n        const indexArray = arrays.indexArray as LineIndexArray;\n        indexArray.emplaceBack(index, index + 1);\n        indexArray.emplaceBack(index + 1, index + 2);\n        indexArray.emplaceBack(index + 2, index + 3);\n        indexArray.emplaceBack(index + 3, index);\n\n        segment.primitiveLength += 4;\n    }\n\n    addDebugCollisionBoxes(startIndex: number, endIndex: number, symbolInstance: SymbolInstance, isText: boolean): void {\n        for (let b = startIndex; b < endIndex; b++) {\n            const box: CollisionBox = this.collisionBoxArray.get(b);\n            const x1 = box.x1;\n            const y1 = box.y1;\n            const x2 = box.x2;\n            const y2 = box.y2;\n\n            this.addCollisionDebugVertices(x1, y1, x2, y2,\n                isText ? this.textCollisionBox : this.iconCollisionBox,\n                box.anchorPoint, symbolInstance);\n        }\n    }\n\n    generateCollisionDebugBuffers(): void {\n        if (this.hasDebugData()) {\n            this.destroyDebugData();\n        }\n\n        this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n        this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n\n        for (let i = 0; i < this.symbolInstances.length; i++) {\n            const symbolInstance = this.symbolInstances.get(i);\n            this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true);\n            this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true);\n            this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false);\n            this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false);\n        }\n    }\n\n    // These flat arrays are meant to be quicker to iterate over than the source\n    // CollisionBoxArray\n    _deserializeCollisionBoxesForSymbol(\n        collisionBoxArray: CollisionBoxArray,\n        textStartIndex: number,\n        textEndIndex: number,\n        verticalTextStartIndex: number,\n        verticalTextEndIndex: number,\n        iconStartIndex: number,\n        iconEndIndex: number,\n        verticalIconStartIndex: number,\n        verticalIconEndIndex: number\n    ): CollisionArrays {\n\n        const collisionArrays = {} as CollisionArrays;\n        for (let k = textStartIndex; k < textEndIndex; k++) {\n            const box: CollisionBox = collisionBoxArray.get(k);\n            collisionArrays.textBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n            collisionArrays.textFeatureIndex = box.featureIndex;\n            break; // Only one box allowed per instance\n        }\n        for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) {\n            const box: CollisionBox = collisionBoxArray.get(k);\n            collisionArrays.verticalTextBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n            collisionArrays.verticalTextFeatureIndex = box.featureIndex;\n            break; // Only one box allowed per instance\n        }\n        for (let k = iconStartIndex; k < iconEndIndex; k++) {\n            // An icon can only have one box now, so this indexing is a bit vestigial...\n            const box: CollisionBox = collisionBoxArray.get(k);\n            collisionArrays.iconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n            collisionArrays.iconFeatureIndex = box.featureIndex;\n            break; // Only one box allowed per instance\n        }\n        for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) {\n            // An icon can only have one box now, so this indexing is a bit vestigial...\n            const box: CollisionBox = collisionBoxArray.get(k);\n            collisionArrays.verticalIconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n            collisionArrays.verticalIconFeatureIndex = box.featureIndex;\n            break; // Only one box allowed per instance\n        }\n        return collisionArrays;\n    }\n\n    deserializeCollisionBoxes(collisionBoxArray: CollisionBoxArray): void {\n        this.collisionArrays = [];\n        for (let i = 0; i < this.symbolInstances.length; i++) {\n            const symbolInstance = this.symbolInstances.get(i);\n            this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(\n                collisionBoxArray,\n                symbolInstance.textBoxStartIndex,\n                symbolInstance.textBoxEndIndex,\n                symbolInstance.verticalTextBoxStartIndex,\n                symbolInstance.verticalTextBoxEndIndex,\n                symbolInstance.iconBoxStartIndex,\n                symbolInstance.iconBoxEndIndex,\n                symbolInstance.verticalIconBoxStartIndex,\n                symbolInstance.verticalIconBoxEndIndex\n            ));\n        }\n    }\n\n    hasTextData(): boolean {\n        return this.text.segments.get().length > 0;\n    }\n\n    hasIconData(): boolean {\n        return this.icon.segments.get().length > 0;\n    }\n\n    hasDebugData(): CollisionBuffers {\n        return this.textCollisionBox && this.iconCollisionBox;\n    }\n\n    hasTextCollisionBoxData(): boolean {\n        return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;\n    }\n\n    hasIconCollisionBoxData(): boolean {\n        return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0;\n    }\n\n    addIndicesForPlacedSymbol(iconOrText: SymbolBuffers, placedSymbolIndex: number): void {\n        const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex);\n\n        const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;\n        for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {\n            iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 2, vertexIndex + 1);\n            iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);\n        }\n    }\n\n    getSortedSymbolIndexes(angle: number): number[] {\n        if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) {\n            return this.symbolInstanceIndexes;\n        }\n        const sin = Math.sin(angle);\n        const cos = Math.cos(angle);\n        const rotatedYs: number[] = [];\n        const featureIndexes: number[] = [];\n        const result: number[] = [];\n\n        for (let i = 0; i < this.symbolInstances.length; ++i) {\n            result.push(i);\n            const symbolInstance = this.symbolInstances.get(i);\n            rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0);\n            featureIndexes.push(symbolInstance.featureIndex);\n        }\n\n        result.sort((aIndex, bIndex) => {\n            return (rotatedYs[aIndex] - rotatedYs[bIndex]) ||\n                   (featureIndexes[bIndex] - featureIndexes[aIndex]);\n        });\n\n        return result;\n    }\n\n    addToSortKeyRanges(symbolInstanceIndex: number, sortKey: number): void {\n        const last = this.sortKeyRanges[this.sortKeyRanges.length - 1];\n        if (last?.sortKey === sortKey) {\n            last.symbolInstanceEnd = symbolInstanceIndex + 1;\n        } else {\n            this.sortKeyRanges.push({\n                sortKey,\n                symbolInstanceStart: symbolInstanceIndex,\n                symbolInstanceEnd: symbolInstanceIndex + 1\n            });\n        }\n    }\n\n    sortFeatures(angle: number): void {\n        if (!this.sortFeaturesByY) return;\n        if (this.sortedAngle === angle) return;\n\n        // The current approach to sorting doesn't sort across segments so don't try.\n        // Sorting within segments separately seemed not to be worth the complexity.\n        if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) return;\n\n        // If the symbols are allowed to overlap sort them by their vertical screen position.\n        // The index array buffer is rewritten to reference the (unchanged) vertices in the\n        // sorted order.\n\n        // To avoid sorting the actual symbolInstance array we sort an array of indexes.\n        this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle);\n        this.sortedAngle = angle;\n\n        this.text.indexArray.clear();\n        this.icon.indexArray.clear();\n\n        this.featureSortOrder = [];\n\n        for (const i of this.symbolInstanceIndexes) {\n            const symbolInstance = this.symbolInstances.get(i);\n            this.featureSortOrder.push(symbolInstance.featureIndex);\n\n            const textIndices = [\n                symbolInstance.rightJustifiedTextSymbolIndex,\n                symbolInstance.centerJustifiedTextSymbolIndex,\n                symbolInstance.leftJustifiedTextSymbolIndex\n            ];\n            for (let i = 0; i < textIndices.length; i++) {\n                const index = textIndices[i];\n                // Only add a given index the first time it shows up,\n                // to avoid duplicate opacity entries when multiple justifications\n                // share the same glyphs.\n                if (index >= 0 && textIndices.indexOf(index) === i) {\n                    this.addIndicesForPlacedSymbol(this.text, index);\n                }\n            }\n\n            if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n                this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex);\n            }\n\n            if (symbolInstance.placedIconSymbolIndex >= 0) {\n                this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex);\n            }\n\n            if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {\n                this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex);\n            }\n        }\n\n        if (this.text.indexBuffer) this.text.indexBuffer.updateData(this.text.indexArray);\n        if (this.icon.indexBuffer) this.icon.indexBuffer.updateData(this.icon.indexArray);\n    }\n}\n\n/**\n * Whether every point lies outside the tile. A point label is anchored on the point itself, and\n * `addSymbolAtAnchor` in symbol_layout.ts drops an anchor outside the tile, so such a feature gets no label here.\n */\nfunction isEveryPointOutsideTile(geometry: Point[][]): boolean {\n    return geometry.every(ring => ring.every(isOutsideTile));\n}\n\nregister('SymbolBucket', SymbolBucket, {\n    omit: ['layers', 'collisionBoxArray', 'features', 'compareText']\n});\n\nexport {addDynamicAttributes};\n", "/**\n * Replace tokens in a string template with values in an object\n *\n * @param properties - a key/value relationship between tokens and replacements\n * @param text - the template string\n * @returns the template with tokens replaced\n */\nexport function resolveTokens(\n    properties: {\n        readonly [x: string]: unknown;\n    } | null,\n    text: string\n): string {\n    return text.replace(/{([^{}]+)}/g, (match, key: string) => {\n        return properties && key in properties ? String(properties[key]) : '';\n    });\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n            ColorType\n        } from '@maplibre/maplibre-gl-style-spec';\n        \n\nexport type SymbolLayoutProps = {\n    \"symbol-placement\": DataConstantProperty<\"point\" | \"line\" | \"line-center\">,\n    \"symbol-spacing\": DataConstantProperty<number>,\n    \"symbol-avoid-edges\": DataConstantProperty<boolean>,\n    \"symbol-sort-key\": DataDrivenProperty<number>,\n    \"symbol-z-order\": DataConstantProperty<\"auto\" | \"viewport-y\" | \"source\">,\n    \"icon-allow-overlap\": DataConstantProperty<boolean>,\n    \"icon-overlap\": DataConstantProperty<\"never\" | \"always\" | \"cooperative\">,\n    \"icon-ignore-placement\": DataConstantProperty<boolean>,\n    \"icon-optional\": DataConstantProperty<boolean>,\n    \"icon-rotation-alignment\": DataDrivenProperty<\"map\" | \"viewport\" | \"auto\">,\n    \"icon-size\": DataDrivenProperty<number>,\n    \"icon-text-fit\": DataConstantProperty<\"none\" | \"width\" | \"height\" | \"both\">,\n    \"icon-text-fit-padding\": DataConstantProperty<[number, number, number, number]>,\n    \"icon-image\": DataDrivenProperty<ResolvedImage>,\n    \"icon-rotate\": DataDrivenProperty<number>,\n    \"icon-padding\": DataDrivenProperty<Padding>,\n    \"icon-keep-upright\": DataConstantProperty<boolean>,\n    \"icon-offset\": DataDrivenProperty<[number, number]>,\n    \"icon-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n    \"icon-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n    \"text-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n    \"text-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"viewport-glyph\" | \"auto\">,\n    \"text-field\": DataDrivenProperty<Formatted>,\n    \"text-font\": DataDrivenProperty<string[]>,\n    \"text-size\": DataDrivenProperty<number>,\n    \"text-max-width\": DataDrivenProperty<number>,\n    \"text-line-height\": DataConstantProperty<number>,\n    \"text-letter-spacing\": DataDrivenProperty<number>,\n    \"text-justify\": DataDrivenProperty<\"auto\" | \"left\" | \"center\" | \"right\">,\n    \"text-radial-offset\": DataDrivenProperty<number>,\n    \"text-variable-anchor\": DataConstantProperty<Array<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">>,\n    \"text-variable-anchor-offset\": DataDrivenProperty<VariableAnchorOffsetCollection>,\n    \"text-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n    \"text-max-angle\": DataConstantProperty<number>,\n    \"text-writing-mode\": DataConstantProperty<Array<\"horizontal\" | \"vertical\">>,\n    \"text-rotate\": DataDrivenProperty<number>,\n    \"text-padding\": DataConstantProperty<number>,\n    \"text-keep-upright\": DataConstantProperty<boolean>,\n    \"text-transform\": DataDrivenProperty<\"none\" | \"uppercase\" | \"lowercase\">,\n    \"text-offset\": DataDrivenProperty<[number, number]>,\n    \"text-allow-overlap\": DataConstantProperty<boolean>,\n    \"text-overlap\": DataConstantProperty<\"never\" | \"always\" | \"cooperative\">,\n    \"text-ignore-placement\": DataConstantProperty<boolean>,\n    \"text-optional\": DataConstantProperty<boolean>,\n    \"symbol-height-offset\": DataDrivenProperty<number>,\n    \"symbol-height-anchor\": DataConstantProperty<\"ground\" | \"absolute\">,\n};\n\nexport type SymbolLayoutPropsPossiblyEvaluated = {\n    \"symbol-placement\": \"point\" | \"line\" | \"line-center\",\n    \"symbol-spacing\": number,\n    \"symbol-avoid-edges\": boolean,\n    \"symbol-sort-key\": PossiblyEvaluatedPropertyValue<number>,\n    \"symbol-z-order\": \"auto\" | \"viewport-y\" | \"source\",\n    \"icon-allow-overlap\": boolean,\n    \"icon-overlap\": \"never\" | \"always\" | \"cooperative\",\n    \"icon-ignore-placement\": boolean,\n    \"icon-optional\": boolean,\n    \"icon-rotation-alignment\": PossiblyEvaluatedPropertyValue<\"map\" | \"viewport\" | \"auto\">,\n    \"icon-size\": PossiblyEvaluatedPropertyValue<number>,\n    \"icon-text-fit\": \"none\" | \"width\" | \"height\" | \"both\",\n    \"icon-text-fit-padding\": [number, number, number, number],\n    \"icon-image\": PossiblyEvaluatedPropertyValue<ResolvedImage>,\n    \"icon-rotate\": PossiblyEvaluatedPropertyValue<number>,\n    \"icon-padding\": PossiblyEvaluatedPropertyValue<Padding>,\n    \"icon-keep-upright\": boolean,\n    \"icon-offset\": PossiblyEvaluatedPropertyValue<[number, number]>,\n    \"icon-anchor\": PossiblyEvaluatedPropertyValue<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n    \"icon-pitch-alignment\": \"map\" | \"viewport\" | \"auto\",\n    \"text-pitch-alignment\": \"map\" | \"viewport\" | \"auto\",\n    \"text-rotation-alignment\": \"map\" | \"viewport\" | \"viewport-glyph\" | \"auto\",\n    \"text-field\": PossiblyEvaluatedPropertyValue<Formatted>,\n    \"text-font\": PossiblyEvaluatedPropertyValue<string[]>,\n    \"text-size\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-max-width\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-line-height\": number,\n    \"text-letter-spacing\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-justify\": PossiblyEvaluatedPropertyValue<\"auto\" | \"left\" | \"center\" | \"right\">,\n    \"text-radial-offset\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-variable-anchor\": Array<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n    \"text-variable-anchor-offset\": PossiblyEvaluatedPropertyValue<VariableAnchorOffsetCollection>,\n    \"text-anchor\": PossiblyEvaluatedPropertyValue<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n    \"text-max-angle\": number,\n    \"text-writing-mode\": Array<\"horizontal\" | \"vertical\">,\n    \"text-rotate\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-padding\": number,\n    \"text-keep-upright\": boolean,\n    \"text-transform\": PossiblyEvaluatedPropertyValue<\"none\" | \"uppercase\" | \"lowercase\">,\n    \"text-offset\": PossiblyEvaluatedPropertyValue<[number, number]>,\n    \"text-allow-overlap\": boolean,\n    \"text-overlap\": \"never\" | \"always\" | \"cooperative\",\n    \"text-ignore-placement\": boolean,\n    \"text-optional\": boolean,\n    \"symbol-height-offset\": PossiblyEvaluatedPropertyValue<number>,\n    \"symbol-height-anchor\": \"ground\" | \"absolute\",\n};\n\nlet layout: Properties<SymbolLayoutProps>;\nconst getLayout = (): Properties<SymbolLayoutProps> => layout = layout || new Properties({\n    \"symbol-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-placement\"] as any as StylePropertySpecification, \"symbol-placement\"),\n    \"symbol-spacing\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-spacing\"] as any as StylePropertySpecification, \"symbol-spacing\"),\n    \"symbol-avoid-edges\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-avoid-edges\"] as any as StylePropertySpecification, \"symbol-avoid-edges\"),\n    \"symbol-sort-key\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"symbol-sort-key\"] as any as StylePropertySpecification, \"symbol-sort-key\"),\n    \"symbol-z-order\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-z-order\"] as any as StylePropertySpecification, \"symbol-z-order\"),\n    \"icon-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-allow-overlap\"] as any as StylePropertySpecification, \"icon-allow-overlap\"),\n    \"icon-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-overlap\"] as any as StylePropertySpecification, \"icon-overlap\"),\n    \"icon-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-ignore-placement\"] as any as StylePropertySpecification, \"icon-ignore-placement\"),\n    \"icon-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-optional\"] as any as StylePropertySpecification, \"icon-optional\"),\n    \"icon-rotation-alignment\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-rotation-alignment\"] as any as StylePropertySpecification, \"icon-rotation-alignment\"),\n    \"icon-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-size\"] as any as StylePropertySpecification, \"icon-size\"),\n    \"icon-text-fit\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit\"] as any as StylePropertySpecification, \"icon-text-fit\"),\n    \"icon-text-fit-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit-padding\"] as any as StylePropertySpecification, \"icon-text-fit-padding\"),\n    \"icon-image\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-image\"] as any as StylePropertySpecification, \"icon-image\"),\n    \"icon-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-rotate\"] as any as StylePropertySpecification, \"icon-rotate\"),\n    \"icon-padding\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-padding\"] as any as StylePropertySpecification, \"icon-padding\"),\n    \"icon-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-keep-upright\"] as any as StylePropertySpecification, \"icon-keep-upright\"),\n    \"icon-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-offset\"] as any as StylePropertySpecification, \"icon-offset\"),\n    \"icon-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-anchor\"] as any as StylePropertySpecification, \"icon-anchor\"),\n    \"icon-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-pitch-alignment\"] as any as StylePropertySpecification, \"icon-pitch-alignment\"),\n    \"text-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-pitch-alignment\"] as any as StylePropertySpecification, \"text-pitch-alignment\"),\n    \"text-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-rotation-alignment\"] as any as StylePropertySpecification, \"text-rotation-alignment\"),\n    \"text-field\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-field\"] as any as StylePropertySpecification, \"text-field\"),\n    \"text-font\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-font\"] as any as StylePropertySpecification, \"text-font\"),\n    \"text-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-size\"] as any as StylePropertySpecification, \"text-size\"),\n    \"text-max-width\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-max-width\"] as any as StylePropertySpecification, \"text-max-width\"),\n    \"text-line-height\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-line-height\"] as any as StylePropertySpecification, \"text-line-height\"),\n    \"text-letter-spacing\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-letter-spacing\"] as any as StylePropertySpecification, \"text-letter-spacing\"),\n    \"text-justify\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-justify\"] as any as StylePropertySpecification, \"text-justify\"),\n    \"text-radial-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-radial-offset\"] as any as StylePropertySpecification, \"text-radial-offset\"),\n    \"text-variable-anchor\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-variable-anchor\"] as any as StylePropertySpecification, \"text-variable-anchor\"),\n    \"text-variable-anchor-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-variable-anchor-offset\"] as any as StylePropertySpecification, \"text-variable-anchor-offset\"),\n    \"text-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-anchor\"] as any as StylePropertySpecification, \"text-anchor\"),\n    \"text-max-angle\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-max-angle\"] as any as StylePropertySpecification, \"text-max-angle\"),\n    \"text-writing-mode\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-writing-mode\"] as any as StylePropertySpecification, \"text-writing-mode\"),\n    \"text-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-rotate\"] as any as StylePropertySpecification, \"text-rotate\"),\n    \"text-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-padding\"] as any as StylePropertySpecification, \"text-padding\"),\n    \"text-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-keep-upright\"] as any as StylePropertySpecification, \"text-keep-upright\"),\n    \"text-transform\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-transform\"] as any as StylePropertySpecification, \"text-transform\"),\n    \"text-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-offset\"] as any as StylePropertySpecification, \"text-offset\"),\n    \"text-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-allow-overlap\"] as any as StylePropertySpecification, \"text-allow-overlap\"),\n    \"text-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-overlap\"] as any as StylePropertySpecification, \"text-overlap\"),\n    \"text-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-ignore-placement\"] as any as StylePropertySpecification, \"text-ignore-placement\"),\n    \"text-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-optional\"] as any as StylePropertySpecification, \"text-optional\"),\n    \"symbol-height-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"symbol-height-offset\"] as any as StylePropertySpecification, \"symbol-height-offset\"),\n    \"symbol-height-anchor\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-height-anchor\"] as any as StylePropertySpecification, \"symbol-height-anchor\"),\n});\n\nexport type SymbolPaintProps = {\n    \"icon-opacity\": DataDrivenProperty<number>,\n    \"icon-color\": DataDrivenProperty<Color>,\n    \"icon-halo-color\": DataDrivenProperty<Color>,\n    \"icon-halo-width\": DataDrivenProperty<number>,\n    \"icon-halo-blur\": DataDrivenProperty<number>,\n    \"icon-translate\": DataConstantProperty<[number, number]>,\n    \"icon-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"text-opacity\": DataDrivenProperty<number>,\n    \"text-color\": DataDrivenProperty<Color>,\n    \"text-halo-color\": DataDrivenProperty<Color>,\n    \"text-halo-width\": DataDrivenProperty<number>,\n    \"text-halo-blur\": DataDrivenProperty<number>,\n    \"text-translate\": DataConstantProperty<[number, number]>,\n    \"text-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n};\n\nexport type SymbolPaintPropsPossiblyEvaluated = {\n    \"icon-opacity\": PossiblyEvaluatedPropertyValue<number>,\n    \"icon-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"icon-halo-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"icon-halo-width\": PossiblyEvaluatedPropertyValue<number>,\n    \"icon-halo-blur\": PossiblyEvaluatedPropertyValue<number>,\n    \"icon-translate\": [number, number],\n    \"icon-translate-anchor\": \"map\" | \"viewport\",\n    \"text-opacity\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"text-halo-color\": PossiblyEvaluatedPropertyValue<Color>,\n    \"text-halo-width\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-halo-blur\": PossiblyEvaluatedPropertyValue<number>,\n    \"text-translate\": [number, number],\n    \"text-translate-anchor\": \"map\" | \"viewport\",\n};\n\nlet paint: Properties<SymbolPaintProps>;\nconst getPaint = (): Properties<SymbolPaintProps> => paint = paint || new Properties({\n    \"icon-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-opacity\"] as any as StylePropertySpecification, \"icon-opacity\"),\n    \"icon-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-color\"] as any as StylePropertySpecification, \"icon-color\"),\n    \"icon-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-color\"] as any as StylePropertySpecification, \"icon-halo-color\"),\n    \"icon-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-width\"] as any as StylePropertySpecification, \"icon-halo-width\"),\n    \"icon-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-blur\"] as any as StylePropertySpecification, \"icon-halo-blur\"),\n    \"icon-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate\"] as any as StylePropertySpecification, \"icon-translate\"),\n    \"icon-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate-anchor\"] as any as StylePropertySpecification, \"icon-translate-anchor\"),\n    \"text-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-opacity\"] as any as StylePropertySpecification, \"text-opacity\"),\n    \"text-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-color\"] as any as StylePropertySpecification, \"text-color\", { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }),\n    \"text-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-color\"] as any as StylePropertySpecification, \"text-halo-color\"),\n    \"text-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-width\"] as any as StylePropertySpecification, \"text-halo-width\"),\n    \"text-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-blur\"] as any as StylePropertySpecification, \"text-halo-blur\"),\n    \"text-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate\"] as any as StylePropertySpecification, \"text-translate\"),\n    \"text-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate-anchor\"] as any as StylePropertySpecification, \"text-translate-anchor\"),\n});\n\nexport default ({ get paint(): Properties<SymbolPaintProps> { return getPaint() }, get layout(): Properties<SymbolLayoutProps> { return getLayout() } });", "import {NullType} from '@maplibre/maplibre-gl-style-spec';\nimport {register} from '../util/web_worker_transfer.ts';\n\nimport type {PossiblyEvaluatedPropertyValue} from './properties.ts';\nimport type {Expression, EvaluationContext, Type, ZoomConstantExpression} from '@maplibre/maplibre-gl-style-spec';\n\n// This is an internal expression class. It is only used in GL JS and\n// has GL JS dependencies which can break the standalone style-spec module\nexport class FormatSectionOverride<T> implements Expression {\n    type: Type;\n    defaultValue: PossiblyEvaluatedPropertyValue<T>;\n\n    constructor(defaultValue: PossiblyEvaluatedPropertyValue<T>) {\n        if (defaultValue.property.overrides === undefined) throw new Error('overrides must be provided to instantiate FormatSectionOverride class');\n        this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType;\n        this.defaultValue = defaultValue;\n    }\n\n    evaluate(ctx: EvaluationContext): any {\n        if (ctx.formattedSection) {\n            const overrides = this.defaultValue.property.overrides;\n            if (overrides?.hasOverride(ctx.formattedSection)) {\n                return overrides.getOverride(ctx.formattedSection);\n            }\n        }\n\n        if (ctx.feature && ctx.featureState) {\n            return this.defaultValue.evaluate(ctx.feature, ctx.featureState);\n        }\n\n        return this.defaultValue.property.specification.default;\n    }\n\n    eachChild(fn: (_: Expression) => void): void {\n        if (!this.defaultValue.isConstant()) {\n            const expr: ZoomConstantExpression<'source'> = (this.defaultValue.value as any);\n            fn(expr._styleExpression.expression);\n        }\n    }\n\n    // Cannot be statically evaluated, as the output depends on the evaluation context.\n    outputDefined() {\n        return false;\n    }\n\n    serialize() {\n        return null;\n    }\n}\n\nregister('FormatSectionOverride', FormatSectionOverride, {omit: ['defaultValue']});\n", "import {StyleLayer} from '../style_layer.ts';\nimport {SymbolBucket, type SymbolFeature} from '../../data/bucket/symbol_bucket.ts';\nimport {resolveTokens} from '../../util/resolve_tokens.ts';\nimport properties, {type SymbolLayoutPropsPossiblyEvaluated, type SymbolPaintPropsPossiblyEvaluated} from './symbol_style_layer_properties.g.ts';\nimport {\n    type Transitionable,\n    type Transitioning,\n    type Layout,\n    type PossiblyEvaluated,\n    PossiblyEvaluatedPropertyValue,\n    type PropertyValue\n} from '../properties.ts';\nimport {\n    isExpression,\n    StyleExpression,\n    ZoomConstantExpression,\n    ZoomDependentExpression,\n    FormattedType,\n    typeOf,\n    Formatted,\n    FormatExpression,\n    Literal} from '@maplibre/maplibre-gl-style-spec';\nimport {FormatSectionOverride} from '../format_section_override.ts';\n\nimport type {BucketParameters} from '../../data/bucket.ts';\nimport type {SymbolLayoutProps, SymbolPaintProps} from './symbol_style_layer_properties.g.ts';\nimport type {EvaluationParameters} from '../evaluation_parameters.ts';\nimport type {Expression, Feature, SourceExpression, LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\n\nexport const isSymbolStyleLayer = (layer: StyleLayer): layer is SymbolStyleLayer => layer.type === 'symbol';\n\nexport class SymbolStyleLayer extends StyleLayer {\n    _unevaluatedLayout: Layout<SymbolLayoutProps>;\n    layout: PossiblyEvaluated<SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated>;\n\n    _transitionablePaint: Transitionable<SymbolPaintProps>;\n    _transitioningPaint: Transitioning<SymbolPaintProps>;\n    paint: PossiblyEvaluated<SymbolPaintProps, SymbolPaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n    }\n\n    recalculate(parameters: EvaluationParameters, availableImages: string[]): void {\n        super.recalculate(parameters, availableImages);\n\n        const iconRotationAlignment = this.layout.get('icon-rotation-alignment');\n        if (iconRotationAlignment.value.kind !== 'constant' || iconRotationAlignment.value.value === 'auto') {\n            this.layout._values['icon-rotation-alignment'] = new PossiblyEvaluatedPropertyValue(\n                iconRotationAlignment.property,\n                {kind: 'constant', value: this.layout.get('symbol-placement') !== 'point' ? 'map' : 'viewport'},\n                iconRotationAlignment.parameters);\n        }\n\n        if (this.layout.get('text-rotation-alignment') === 'auto') {\n            if (this.layout.get('symbol-placement') !== 'point') {\n                this.layout._values['text-rotation-alignment'] = 'map';\n            } else {\n                this.layout._values['text-rotation-alignment'] = 'viewport';\n            }\n        }\n\n        // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment`\n        if (this.layout.get('text-pitch-alignment') === 'auto') {\n            this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment') === 'map' ? 'map' : 'viewport';\n        }\n        if (this.layout.get('icon-pitch-alignment') === 'auto') {\n            this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment').constantOr('viewport');\n        }\n\n        if (this.layout.get('symbol-placement') === 'point') {\n            const writingModes = this.layout.get('text-writing-mode');\n            if (writingModes) {\n                // remove duplicates, preserving order\n                const deduped = [];\n                for (const m of writingModes) {\n                    if (!deduped.includes(m)) deduped.push(m);\n                }\n                this.layout._values['text-writing-mode'] = deduped;\n            } else {\n                this.layout._values['text-writing-mode'] = ['horizontal'];\n            }\n        }\n\n        this._setPaintOverrides();\n    }\n\n    getValueAndResolveTokens(name: any, feature: Feature, canonical: CanonicalTileID, availableImages: string[]): any {\n        const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages);\n        const unevaluated = this._unevaluatedLayout._values[name];\n        if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) {\n            return resolveTokens(feature.properties, value);\n        }\n\n        return value;\n    }\n\n    createBucket(parameters: BucketParameters<any>): SymbolBucket {\n        return new SymbolBucket(parameters);\n    }\n\n    queryRadius(): number {\n        return 0;\n    }\n\n    queryIntersectsFeature(): boolean {\n        throw new Error('Should take a different path in FeatureIndex');\n    }\n\n    _setPaintOverrides(): void {\n        for (const overridable of properties.paint.overridableProperties) {\n            if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) {\n                continue;\n            }\n            const overridden = this.paint.get(overridable as keyof SymbolPaintPropsPossiblyEvaluated) as PossiblyEvaluatedPropertyValue<number>;\n            const override = new FormatSectionOverride(overridden);\n            const styleExpression = new StyleExpression(override, `layers[${this.id}].paint.${overridden.property.name}`, overridden.property.specification);\n            let expression = null;\n            if (overridden.value.kind === 'constant' || overridden.value.kind === 'source') {\n                expression = new ZoomConstantExpression('source', styleExpression) as SourceExpression;\n            } else {\n                expression = new ZoomDependentExpression('composite',\n                    styleExpression,\n                    overridden.value.zoomStops);\n            }\n            this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overridden.property,\n                expression,\n                overridden.parameters);\n        }\n    }\n\n    _handleOverridablePaintPropertyUpdate<T, R>(name: string, oldValue: PropertyValue<T, R>, newValue: PropertyValue<T, R>): boolean {\n        if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {\n            return false;\n        }\n        return SymbolStyleLayer.hasPaintOverride(this.layout, name);\n    }\n\n    static hasPaintOverride(layout: PossiblyEvaluated<SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated>, propertyName: string): boolean {\n        const textField = layout.get('text-field');\n        const property = properties.paint.properties[propertyName];\n        let hasOverrides = false;\n\n        const checkSections = (sections) => {\n            for (const section of sections) {\n                if (property.overrides?.hasOverride(section)) {\n                    hasOverrides = true;\n                    return;\n                }\n            }\n        };\n\n        if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) {\n            checkSections(textField.value.value.sections);\n        } else if (textField.value.kind === 'source' || textField.value.kind === 'composite') {\n\n            const checkExpression = (expression: Expression) => {\n                if (hasOverrides) return;\n\n                if (expression instanceof Literal && typeOf(expression.value) === FormattedType) {\n                    const formatted: Formatted = (expression.value as any);\n                    checkSections(formatted.sections);\n                } else if (expression instanceof FormatExpression) {\n                    checkSections(expression.sections);\n                } else {\n                    expression.eachChild(checkExpression);\n                }\n            };\n\n            const expr: ZoomConstantExpression<'source'> = (textField.value as any);\n            if (expr._styleExpression) {\n                checkExpression(expr._styleExpression.expression);\n            }\n        }\n\n        return hasOverrides;\n    }\n}\n\nexport type SymbolPadding = [number, number, number, number];\n\nexport function getIconPadding(layout: PossiblyEvaluated<SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated>, feature: SymbolFeature, canonical: CanonicalTileID, pixelRatio = 1): SymbolPadding {\n    // Support text-padding in addition to icon-padding? Unclear how to apply asymmetric text-padding to the radius for collision circles.\n    const result = layout.get('icon-padding').evaluate(feature, {}, canonical);\n    const values = result?.values;\n\n    return [\n        values[0] * pixelRatio,\n        values[1] * pixelRatio,\n        values[2] * pixelRatio,\n        values[3] * pixelRatio,\n    ];\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from '../properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type BackgroundPaintProps = {\n    \"background-color\": DataConstantProperty<Color>,\n    \"background-pattern\": CrossFadedProperty<ResolvedImage>,\n    \"background-opacity\": DataConstantProperty<number>,\n};\n\nexport type BackgroundPaintPropsPossiblyEvaluated = {\n    \"background-color\": Color,\n    \"background-pattern\": CrossFaded<ResolvedImage>,\n    \"background-opacity\": number,\n};\n\nlet paint: Properties<BackgroundPaintProps>;\nconst getPaint = (): Properties<BackgroundPaintProps> => paint = paint || new Properties({\n    \"background-color\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-color\"] as any as StylePropertySpecification, \"background-color\"),\n    \"background-pattern\": new CrossFadedProperty(styleSpec[\"paint_background\"][\"background-pattern\"] as any as StylePropertySpecification, \"background-pattern\"),\n    \"background-opacity\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-opacity\"] as any as StylePropertySpecification, \"background-opacity\"),\n});\n\nexport default ({ get paint(): Properties<BackgroundPaintProps> { return getPaint() } });", "import {StyleLayer} from '../style_layer.ts';\nimport properties, {type BackgroundPaintPropsPossiblyEvaluated} from './background_style_layer_properties.g.ts';\n\nimport type {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.ts';\nimport type {BackgroundPaintProps} from './background_style_layer_properties.g.ts';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport const isBackgroundStyleLayer = (layer: StyleLayer): layer is BackgroundStyleLayer => layer.type === 'background';\n\nexport class BackgroundStyleLayer extends StyleLayer {\n    _transitionablePaint: Transitionable<BackgroundPaintProps>;\n    _transitioningPaint: Transitioning<BackgroundPaintProps>;\n    paint: PossiblyEvaluated<BackgroundPaintProps, BackgroundPaintPropsPossiblyEvaluated>;\n\n    constructor(layer: LayerSpecification, globalState: Record<string, any>) {\n        super(layer, properties, globalState);\n    }\n}\n", "import {StyleLayer} from '../style_layer.ts';\nimport {ValidationError} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {Map} from '../../ui/map.ts';\nimport type {mat4} from 'gl-matrix';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {CustomLayerProjectionData, RendererProjectionData} from '../../geo/projection/projection_data.ts';\nimport type {TerrainHeightMapTarget} from '../../render/terrain.ts';\n\n/**\n * Type for an object literal that specifies a map tile.\n */\nexport type UnwrappedTileIDLiteral = {\n    /**\n     * An optional wrap values.\n     * Useful in scenarios when multiple world copies are visible, such as a zoomed out map or a map centered around the antimeridian.\n     * Tiles from each world copy should have different wrap values, with wrap increasing for each copy from west to east.\n     */\n    wrap?: number;\n    /**\n     * The tile's XY coordinates and zoom level.\n     */\n    canonical: {\n        x: number;\n        y: number;\n        z: number;\n    };\n};\n\n/**\n * Parameters object for the {@link CustomRenderMethodInput.getProjectionData} function.\n * Contains the requested tile ID and more.\n */\nexport type CustomLayerProjectionDataParams = {\n    /**\n     * The coordinates of the current tile.\n     */\n    tileID: UnwrappedTileIDLiteral | null;\n    /**\n     * Set to true if a pixel-aligned matrix should be used, if possible.\n     * This flag is mostly used for raster tiles under mercator projection.\n     */\n    aligned?: boolean;\n    /**\n     * Set to true if the terrain matrix should be applied when pre-rendering tiles into textures for 3D terrain.\n     */\n    applyTerrainMatrix?: boolean;\n    /**\n     * Set to true if the globe matrix should be applied when using globe projection.\n     */\n    applyGlobeMatrix?: boolean;\n};\n\n/**\n* Input arguments exposed by custom render function.\n*/\nexport type CustomRenderMethodInput = {\n    /**\n     * This value represents the distance from the camera to the far clipping plane.\n     * It is used in the calculation of the projection matrix to determine which objects are visible.\n     * farZ should be larger than nearZ.\n     */\n    farZ: number;\n    /**\n     * This value represents the distance from the camera to the near clipping plane.\n     * It is used in the calculation of the projection matrix to determine which objects are visible.\n     * nearZ should be smaller than farZ.\n     */\n    nearZ: number;\n    /**\n     * Vertical field of view in radians.\n     */\n    fov: number;\n    /**\n    * Model view projection matrix.\n    * Represents the matrix converting from world space to clip space.\n    * https://learnopengl.com/Getting-started/Coordinate-Systems\n    * **/\n    modelViewProjectionMatrix: mat4;\n    /**\n    * Projection matrix.\n    * Represents the matrix converting from view space to clip space.\n    * https://learnopengl.com/Getting-started/Coordinate-Systems\n    */\n    projectionMatrix: mat4;\n    /**\n     * Data required for picking and compiling a custom shader for the current projection.\n     */\n    shaderData: {\n        /**\n         * Name of the shader variant that should be used.\n         * Depends on current projection.\n         * Whenever the other shader properties change, this string changes as well,\n         * and can be used as a key with which to cache compiled shaders.\n         */\n        variantName: string;\n        /**\n         * The prelude code to add to the vertex shader to access MapLibre's `projectTile` projection function.\n         * Depends on current projection.\n         * @example\n         * ```\n         * const vertexSource = `#version 300 es\n         * ${shaderData.vertexShaderPrelude}\n         * ${shaderData.define}\n         * in vec2 a_pos;\n         * void main() {\n         *     gl_Position = projectTile(a_pos);\n         * }`;\n         * ```\n         */\n        vertexShaderPrelude: string;\n        /**\n         * Defines to add to the shader code.\n         * Depends on current projection.\n         * @example\n         * ```\n         * const vertexSource = `#version 300 es\n         * ${shaderData.vertexShaderPrelude}\n         * ${shaderData.define}\n         * in vec2 a_pos;\n         * void main() {\n         *     gl_Position = projectTile(a_pos);\n         *     #ifdef GLOBE\n         *     // Do globe-specific things\n         *     #endif\n         * }`;\n         * ```\n         */\n        define: string;\n    };\n    /**\n     * Uniforms that should be passed to the vertex shader, if MapLibre's projection code is used.\n     * For more details of this object's internals, see its doc comments in `src/geo/projection/projection_data.ts`.\n     *\n     * These uniforms are set so that `projectTile` in shader accepts a vec2 in range 0..1 in web mercator coordinates.\n     * Use `getProjectionData({overscaledTileID: tileID})` to get uniforms for a given tile and pass vec2 in tile-local range 0..EXTENT instead.\n     *\n     * For projection 3D features, use `projectTileFor3D` in the shader.\n     *\n     * If you just need a projection matrix, use `defaultProjectionData.mainMatrix`.\n     * A projection matrix is sufficient for simple custom layers that only support mercator projection.\n     *\n     * Under mercator projection, when these uniforms are used, the shader's `projectTile` function projects spherical mercator\n     * coordinates to gl clip space coordinates. The spherical mercator coordinate `[0, 0]` represents the\n     * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When\n     * the `renderingMode` is `\"3d\"`, the z coordinate is conformal. A box with identical x, y, and z\n     * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate.fromLngLat}\n     * can be used to project a `LngLat` to a mercator coordinate.\n     *\n     * Under a projection registered with {@link addProjection}, these uniforms take the same range in the world square\n     * of its tile matrix set instead, where `[0, 0]` is the top left corner of tile 0/0/0, and one meter is\n     * `1 / extentAtZoom0` in x, y and z. {@link MercatorCoordinate} does not apply there. The custom CRS guide shows\n     * how to compute the positions.\n     *\n     * Under globe projection, when these uniforms are used, the `elevation` parameter\n     * passed to `projectTileFor3D` in the shader is elevation in meters above \"sea level\",\n     * or more accurately for globe, elevation above the surface of the perfect sphere used to render the planet.\n     */\n    defaultProjectionData: CustomLayerProjectionData;\n\n    /**\n     * Generates a {@link ProjectionData} instance to be used while rendering a given tile.\n     * In custom layers, this function is only needed when rendering tiles in a completely custom way and with shaders that are compatible with both projections.\n     *\n     * @see [Add a custom layer with tiles to a globe](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-custom-layer-with-tiles-to-a-globe)\n     * @param params - Parameters for the projection data generation.\n     */\n    getProjectionData: (params: CustomLayerProjectionDataParams) => RendererProjectionData;\n\n    /**\n     * @experimental\n     * Draws the elevation of the terrain as the map draws it into a texture, so that the layer can place many\n     * objects on the ground on the GPU. Only set in {@link CustomLayerInterface.prerender}, while terrain is enabled.\n     * Call it again after the camera moves, terrain tiles load or the terrain changes, and set up your WebGL state afterwards.\n     */\n    renderTerrainHeightMap?: (target: TerrainHeightMapTarget) => void;\n};\n\n/**\n * @param gl - The map's gl context.\n * @param options - Argument object with render inputs like camera properties.\n */\nexport type CustomRenderMethod = (gl: WebGL2RenderingContext, options: CustomRenderMethodInput) => void;\n\n/**\n * @experimental\n * Input for {@link CustomLayerInterface.renderToTerrainTile}.\n */\nexport type CustomTerrainRenderInput = {\n    /** The terrain tile to draw. */\n    tileID: UnwrappedTileIDLiteral;\n    /** The width of the tile's framebuffer in pixels. */\n    width: number;\n    /** The height of the tile's framebuffer in pixels. */\n    height: number;\n};\n\n/**\n * Interface for custom style layers. This is a specification for\n * implementers to model: it is not an exported method or class.\n *\n * Custom layers allow a user to render directly into the map's GL context using the map's camera.\n * These layers can be added between any regular layers using {@link Map.addLayer}.\n *\n * Custom layers must have a unique `id` and must have the `type` of `\"custom\"`.\n * They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`.\n * They can trigger rendering using {@link Map.triggerRepaint}\n * and they should appropriately handle {@link MapContextEvent} with `webglcontextlost` and `webglcontextrestored`.\n *\n * The `renderingMode` property controls whether the layer is treated as a `\"2d\"` or `\"3d\"` map layer. Use:\n *\n * - `\"renderingMode\": \"3d\"` to use the depth buffer and share it with other layers\n * - `\"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\n *   framebuffer and {@link CustomLayerInterface.prerender}\n *\n * @example\n * Custom layer implemented as ES6 class\n * ```ts\n * class NullIslandLayer {\n *     constructor() {\n *         this.id = 'null-island';\n *         this.type = 'custom';\n *         this.renderingMode = '2d';\n *     }\n *\n *      onAdd(map: maplibregl.Map, gl: WebGL2RenderingContext) {\n *         const vertexSource = `\n *         uniform mat4 u_matrix;\n *         void main() {\n *             gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);\n *             gl_PointSize = 20.0;\n *         }`;\n *\n *         const fragmentSource = `\n *         void main() {\n *             fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n *         }`;\n *\n *         const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n *         gl.shaderSource(vertexShader, vertexSource);\n *         gl.compileShader(vertexShader);\n *         const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n *         gl.shaderSource(fragmentShader, fragmentSource);\n *         gl.compileShader(fragmentShader);\n *\n *         this.program = gl.createProgram();\n *         gl.attachShader(this.program, vertexShader);\n *         gl.attachShader(this.program, fragmentShader);\n *         gl.linkProgram(this.program);\n *     }\n *\n *     render({\n *      gl,\n *      modelViewProjectionMatrix: matrix\n *      }: {\n *      gl: WebGL2RenderingContext;\n *      modelViewProjectionMatrix: Float32Array;\n *      }) {\n *         gl.useProgram(this.program);\n *         gl.uniformMatrix4fv(gl.getUniformLocation(this.program, \"u_matrix\"), false, matrix);\n *         gl.drawArrays(gl.POINTS, 0, 1);\n *     }\n * }\n *\n * map.on('load', () => {\n *     map.addLayer(new NullIslandLayer());\n * });\n * ```\n */\nexport interface CustomLayerInterface {\n    /**\n     * A unique layer id.\n     */\n    id: string;\n    /**\n     * The layer's type. Must be `\"custom\"`.\n     */\n    type: 'custom';\n    /**\n     * Either `\"2d\"` or `\"3d\"`. Defaults to `\"2d\"`.\n     */\n    renderingMode?: '2d' | '3d';\n    /**\n     * Called during a render frame allowing the layer to draw into the GL context.\n     *\n     * The layer can assume blending and depth state is set to allow the layer to properly\n     * blend and clip other layers. The layer cannot make any other assumptions about the\n     * current GL state.\n     *\n     * If the layer needs to render to a texture, it should implement the `prerender` method\n     * to do this and only use the `render` method for drawing directly into the main framebuffer.\n     *\n     * The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects\n     * colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already\n     * multiplied by the `a` value. If you are unable to provide colors in premultiplied form you\n     * may want to change the blend function to\n     * `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`.\n     */\n    render: CustomRenderMethod;\n    /**\n     * Optional method called during a render frame to allow a layer to prepare resources or render into a texture.\n     *\n     * The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering.\n     */\n    prerender?: CustomRenderMethod;\n    /**\n     * @experimental\n     * Optional method called instead of `render` while terrain is enabled, to draw the layer into a terrain tile that\n     * MapLibre drapes over the terrain with the fill, line and raster layers around the layer in the style.\n     * Clip space `(-1, -1)` is the tile's south-west corner and `(1, 1)` its north-east corner. Draw over what the\n     * framebuffer holds, with the same blending as `render` and without depth or stencil testing. MapLibre calls it\n     * again when it redraws the tile, and after {@link CustomLayerInterface.terrainTileRevision} changes.\n     */\n    renderToTerrainTile?: (gl: WebGL2RenderingContext, options: CustomTerrainRenderInput) => void;\n    /**\n     * @experimental\n     * Optional number that the layer changes when what it draws in {@link CustomLayerInterface.renderToTerrainTile}\n     * changes, before calling {@link Map.triggerRepaint}, so that MapLibre draws the terrain tiles again.\n     */\n    terrainTileRevision?: number;\n    /**\n     * Optional method called when the layer has been added to the Map with {@link Map.addLayer}. This\n     * gives the layer a chance to initialize gl resources and register event listeners.\n     *\n     * @param map - The Map this custom layer was just added to.\n     * @param gl - The gl context for the map.\n     */\n    onAdd?(map: Map, gl: WebGL2RenderingContext): void;\n    /**\n     * Optional method called when the layer has been removed from the Map with {@link Map.removeLayer}. This\n     * gives the layer a chance to clean up gl resources and event listeners.\n     *\n     * @param map - The Map this custom layer was just added to.\n     * @param gl - The gl context for the map.\n     */\n    onRemove?(map: Map, gl: WebGL2RenderingContext): void;\n}\n\nexport function validateCustomStyleLayer(layerObject: CustomLayerInterface): ValidationError[] {\n    const errors: ValidationError[] = [];\n    const id = layerObject.id;\n\n    if (id === undefined) {\n        errors.push(new ValidationError(`layers.${id}`, null, 'missing required property \"id\"'));\n    }\n\n    if (layerObject.render === undefined) {\n        errors.push(new ValidationError(`layers.${id}`, null, 'missing required method \"render\"'));\n    }\n\n    if (layerObject.renderingMode &&\n        layerObject.renderingMode !== '2d' &&\n        layerObject.renderingMode !== '3d') {\n        errors.push(new ValidationError(`layers.${id}`, null, 'property \"renderingMode\" must be either \"2d\" or \"3d\"'));\n    }\n\n    return errors;\n}\n\nexport const isCustomStyleLayer = (layer: StyleLayer): layer is CustomStyleLayer => layer.type === 'custom';\n\nexport class CustomStyleLayer extends StyleLayer {\n\n    implementation: CustomLayerInterface;\n\n    constructor(implementation: CustomLayerInterface, globalState: Record<string, any>) {\n        super(implementation, {}, globalState);\n        this.implementation = implementation;\n    }\n\n    is3D(): boolean {\n        return this.implementation.renderingMode === '3d';\n    }\n\n    hasOffscreenPass(): boolean {\n        return this.implementation.prerender !== undefined;\n    }\n\n    recalculate(): void {}\n    updateTransitions(): void {}\n    hasTransition(): boolean { return false; }\n\n    serialize(): LayerSpecification {\n        throw new Error('Custom layers cannot be serialized');\n    }\n\n    onAdd: (map: Map) => void = (map: Map) => {\n        if (this.implementation.onAdd) {\n            this.implementation.onAdd(map, map.painter.context.gl);\n        }\n    };\n\n    onRemove: (map: Map) => void = (map: Map) => {\n        if (this.implementation.onRemove) {\n            this.implementation.onRemove(map, map.painter.context.gl);\n        }\n    };\n}\n", "import {CircleStyleLayer} from './style_layer/circle_style_layer.ts';\nimport {HeatmapStyleLayer} from './style_layer/heatmap_style_layer.ts';\nimport {HillshadeStyleLayer} from './style_layer/hillshade_style_layer.ts';\nimport {ColorReliefStyleLayer} from './style_layer/color_relief_style_layer.ts';\nimport {FillStyleLayer} from './style_layer/fill_style_layer.ts';\nimport {FillExtrusionStyleLayer} from './style_layer/fill_extrusion_style_layer.ts';\nimport {LineStyleLayer} from './style_layer/line_style_layer.ts';\nimport {SymbolStyleLayer} from './style_layer/symbol_style_layer.ts';\nimport {BackgroundStyleLayer} from './style_layer/background_style_layer.ts';\nimport {RasterStyleLayer} from './style_layer/raster_style_layer.ts';\nimport {CustomStyleLayer, type CustomLayerInterface} from './style_layer/custom_style_layer.ts';\n\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type AnyStyleLayer =\n    | HeatmapStyleLayer\n    | CircleStyleLayer\n    | HillshadeStyleLayer\n    | ColorReliefStyleLayer\n    | FillExtrusionStyleLayer\n    | FillStyleLayer\n    | LineStyleLayer\n    | SymbolStyleLayer\n    | BackgroundStyleLayer\n    | RasterStyleLayer\n    | CustomStyleLayer;\n\nexport function createStyleLayer(layer: LayerSpecification | CustomLayerInterface, globalState: Record<string, any>): AnyStyleLayer {\n    if (layer.type === 'custom') {\n        return new CustomStyleLayer(layer, globalState);\n    }\n    switch (layer.type) {\n        case 'background':\n            return new BackgroundStyleLayer(layer, globalState);\n        case 'circle':\n            return new CircleStyleLayer(layer, globalState);\n        case 'color-relief':\n            return new ColorReliefStyleLayer(layer, globalState);\n        case 'fill':\n            return new FillStyleLayer(layer, globalState);\n        case 'fill-extrusion':\n            return new FillExtrusionStyleLayer(layer, globalState);\n        case 'heatmap':\n            return new HeatmapStyleLayer(layer, globalState);\n        case 'hillshade':\n            return new HillshadeStyleLayer(layer, globalState);\n        case 'line':\n            return new LineStyleLayer(layer, globalState);\n        case 'raster':\n            return new RasterStyleLayer(layer, globalState);\n        case 'symbol':\n            return new SymbolStyleLayer(layer, globalState);\n    }\n}\n\n", "import type {SpriteSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * Takes a SpriteSpecification value and returns it in its array form. If `undefined` is passed as an input value, an\n * empty array is returned.\n * duplicated entries with identical id/url will be removed in returned array\n * @param sprite - optional sprite to coerce\n * @returns an empty array in case `undefined` is passed; id-url pairs otherwise\n */\nexport function coerceSpriteToArray(sprite?: SpriteSpecification): Array<{id: string; url: string}> {\n    const resultArray: Array<{id: string; url: string}>  = [];\n\n    if (typeof sprite === 'string') {\n        resultArray.push({id: 'default', url: sprite});\n    } else if (sprite && sprite.length > 0) {\n        const dedupArray: string[] = [];\n        for (const {id, url} of sprite) {\n            const key = `${id}${url}`;\n            if (!dedupArray.includes(key)) {\n                dedupArray.push(key);\n                resultArray.push({id, url});\n            }\n        }\n    }\n\n    return resultArray;\n\n}\n", "import {type GetResourceResponse, getJSON} from '../util/ajax.ts';\nimport {ImageRequest} from '../util/image_request.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {browser} from '../util/browser.ts';\nimport {coerceSpriteToArray} from '../util/style.ts';\n\nimport type {SpriteSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {SpriteJSON, StyleImage} from './style_image.ts';\nimport type {RequestManager} from '../util/request_manager.ts';\n\nexport type LoadSpriteResult = {\n    [spriteName: string]: {\n        [id: string]: StyleImage;\n    };\n};\n\nexport function normalizeSpriteURL(url: string, format: string, extension: string): string {\n    try {\n        const parsed = new URL(url);\n        parsed.pathname += `${format}${extension}`;\n        return parsed.toString();\n    }\n    catch {\n        throw new Error(`Invalid sprite URL \"${url}\", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`);\n    }\n}\n\nexport async function loadSprite(\n    originalSprite: SpriteSpecification,\n    requestManager: RequestManager,\n    pixelRatio: number,\n    abortController: AbortController,\n): Promise<LoadSpriteResult> {\n    const spriteArray = coerceSpriteToArray(originalSprite);\n    const format = pixelRatio > 1 ? '@2x' : '';\n\n    const jsonsMap: {[id: string]: Promise<GetResourceResponse<SpriteJSON>>} = {};\n    const imagesMap: {[id: string]: Promise<GetResourceResponse<HTMLImageElement | ImageBitmap>>} = {};\n\n    for (const {id, url} of spriteArray) {\n        const jsonRequestParameters = await requestManager.transformRequest(normalizeSpriteURL(url, format, '.json'), ResourceType.SpriteJSON);\n        jsonsMap[id] = getJSON<SpriteJSON>(jsonRequestParameters, abortController);\n\n        const imageRequestParameters = await requestManager.transformRequest(normalizeSpriteURL(url, format, '.png'), ResourceType.SpriteImage);\n        imagesMap[id] = ImageRequest.getImage(imageRequestParameters, abortController);\n    }\n\n    await Promise.all([...Object.values(jsonsMap), ...Object.values(imagesMap)]);\n    return doOnceCompleted(jsonsMap, imagesMap);\n}\n\n/**\n * @param jsonsMap - JSON data map\n * @param imagesMap - image data map\n */\nasync function doOnceCompleted(\n    jsonsMap:{[id: string]: Promise<GetResourceResponse<SpriteJSON>>},\n    imagesMap:{[id: string]: Promise<GetResourceResponse<HTMLImageElement | ImageBitmap>>}): Promise<LoadSpriteResult> {\n\n    const result = {} as {[spriteName: string]: {[id: string]: StyleImage}};\n    for (const spriteName in jsonsMap) {\n        result[spriteName] = {};\n\n        const image = (await imagesMap[spriteName]).data;\n        if (!image) {\n            throw new Error(`Could not load sprite image for ${spriteName}: the response is empty`);\n        }\n        const context = browser.getImageCanvasContext(image);\n        const json = (await jsonsMap[spriteName]).data;\n\n        for (const id in json) {\n            const {width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight} = json[id];\n            const spriteData = {width, height, x, y, context};\n            result[spriteName][id] = {data: null, pixelRatio, sdf, stretchX, stretchY, content, textFitWidth, textFitHeight, spriteData};\n        }\n    }\n\n    return result;\n}\n", "import {ErrorEvent, Evented} from '../util/evented.ts';\nimport {MapStyleImageMissingEvent} from '../ui/events.ts';\nimport {RGBAImage} from '../util/image.ts';\nimport {renderStyleImage} from '../style/style_image.ts';\nimport {warnOnce} from '../util/util.ts';\n\nimport type {StyleImage} from '../style/style_image.ts';\nimport type {GetImagesResponse} from '../util/actor_messages.ts';\n\nexport type MissingImageRequestHandler = (id: string) => void | Promise<void>;\n\ntype ImageManagerEventType = {\n    error: ErrorEvent;\n    styleimagemissing: MapStyleImageMissingEvent;\n};\n\n/**\n * Owns every image of the style - the ones the sprites bring in as well as the ones added at\n * runtime - and tracks requests for them from the tile workers, sending responses when the\n * requests are fulfilled.\n*/\nexport class ImageManager extends Evented<ImageManagerEventType> {\n    images: Record<string, StyleImage>;\n    /**\n     * Incremented on every {@link ImageManager.updateImage} call. {@link ImageAtlas} instances\n     * compare it against the value they last patched against, so that a tile whose atlas is up to\n     * date can skip its patching work entirely.\n     */\n    updateVersion: number;\n    loaded: boolean;\n    /**\n     * This is used to track requests for images that are not yet available. When the image is loaded,\n     * the requestors will be notified.\n     */\n    requestors: Array<{\n        ids: string[];\n        promiseResolve: (value: GetImagesResponse | PromiseLike<GetImagesResponse>) => void;\n    }>;\n    missingImageResolver: MissingImageRequestHandler | null;\n    /**\n     * The images whose `render` callback already ran in the current frame. A given image usually\n     * sits in the atlas of several tiles, so it would otherwise be asked to re-render once per\n     * tile that holds it.\n     */\n    private _renderCallbacksDispatchedThisFrame: Record<string, boolean>;\n    /**\n     * The ids of the images each sprite has brought in, keyed by sprite id, so that they can be\n     * removed again when that sprite is reloaded or removed.\n     */\n    private _spriteImagesIds: Record<string, string[]>;\n    /** Cached result of {@link ImageManager.listImages}, invalidated whenever an image is added or removed */\n    private _imagesIds: string[] | null;\n\n    constructor() {\n        super();\n        this.images = {};\n        this.updateVersion = 0;\n        this.loaded = false;\n        this.requestors = [];\n        this.missingImageResolver = null;\n        this._spriteImagesIds = {};\n        this._imagesIds = null;\n        this._renderCallbacksDispatchedThisFrame = {};\n    }\n\n    destroy(): void {\n        for (const id of Object.keys(this.images)) {\n            this.removeImage(id);\n        }\n        this._spriteImagesIds = {};\n    }\n    isLoaded(): boolean {\n        return this.loaded;\n    }\n\n    setLoaded(loaded: boolean): void {\n        if (this.loaded === loaded) {\n            return;\n        }\n\n        this.loaded = loaded;\n\n        if (loaded) {\n            for (const {ids, promiseResolve} of this.requestors) {\n                promiseResolve(this._getImagesForIds(ids));\n            }\n            this.requestors = [];\n        }\n    }\n\n    getImage(id: string): StyleImage {\n        const image = this.images[id];\n        // Extract sprite image data on demand\n        if (image && !image.data && image.spriteData) {\n            const spriteData = image.spriteData;\n            image.data = new RGBAImage({\n                width: spriteData.width,\n                height: spriteData.height\n            }, spriteData.context.getImageData(\n                spriteData.x,\n                spriteData.y,\n                spriteData.width,\n                spriteData.height).data);\n            image.spriteData = null;\n        }\n\n        return image;\n    }\n\n    addImage(id: string, image: StyleImage): void {\n        if (this.images[id]) throw new Error(`Image id ${id} already exist, use updateImage instead`);\n        if (this._validate(id, image)) {\n            this.images[id] = image;\n            this._imagesIds = null;\n            if (image.isWebGLImage) this.updateImage(id, image, false);\n        }\n    }\n\n    _validate(id: string, image: StyleImage): boolean {\n        let valid = true;\n        const data = image.data || image.spriteData;\n        if (!this._validateStretch(image.stretchX, data?.width)) {\n            this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"stretchX\" value`)));\n            valid = false;\n        }\n        if (!this._validateStretch(image.stretchY, data?.height)) {\n            this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"stretchY\" value`)));\n            valid = false;\n        }\n        if (!this._validateContent(image.content, image)) {\n            this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"content\" value`)));\n            valid = false;\n        }\n        return valid;\n    }\n\n    _validateStretch(stretch: Array<[number, number]>, size: number): boolean {\n        if (!stretch) return true;\n        let last = 0;\n        for (const part of stretch) {\n            if (part[0] < last || part[1] < part[0] || size < part[1]) return false;\n            last = part[1];\n        }\n        return true;\n    }\n\n    _validateContent(content: [number, number, number, number], image: StyleImage): boolean {\n        if (!content) return true;\n        if (content.length !== 4) return false;\n        const spriteData = image.spriteData;\n        const width = (spriteData?.width) || image.data.width;\n        const height = (spriteData?.height) || image.data.height;\n        if (content[0] < 0 || width < content[0]) return false;\n        if (content[1] < 0 || height < content[1]) return false;\n        if (content[2] < 0 || width < content[2]) return false;\n        if (content[3] < 0 || height < content[3]) return false;\n        if (content[2] < content[0]) return false;\n        return content[3] >= content[1];\n    }\n\n    /**\n     * Replaces an image that is already known under this id, bumping its version so that the\n     * atlases holding it notice.\n     *\n     * The old record is read directly rather than through {@link ImageManager.getImage}, which\n     * would force a synchronous decode of the sprite data of the very image being replaced. Its\n     * size therefore comes from whichever of the two the pixels are still in, since an image that\n     * came from a sprite and was never rendered has not been decoded yet, and its version is\n     * defaulted, since images start out without one.\n     *\n     * @param validate - whether to reject an image of a different size than the one it replaces\n     */\n    updateImage(id: string, image: StyleImage, validate: boolean = true): void {\n        const oldImage = this.images[id];\n        if (validate) {\n            const oldData = oldImage.data || oldImage.spriteData;\n            if (oldData.width !== image.data.width || oldData.height !== image.data.height) {\n                throw new Error(`size mismatch between old image (${oldData.width}x${oldData.height}) and new image (${image.data.width}x${image.data.height}).`);\n            }\n        }\n        image.version = (oldImage.version ?? 0) + 1;\n        this.images[id] = image;\n        this.updateVersion++;\n    }\n\n    removeImage(id: string): void {\n        const image = this.images[id];\n        if (!image) return;\n        delete this.images[id];\n        this._imagesIds = null;\n\n        if (image.userImage?.onRemove) {\n            image.userImage.onRemove();\n        }\n    }\n\n    /**\n     * @returns the ids of every image currently held, sprite images and runtime ones alike. The\n     * returned array is shared between callers and must not be modified.\n     */\n    listImages(): string[] {\n        this._imagesIds ??= Object.keys(this.images);\n        return this._imagesIds;\n    }\n\n    /**\n     * Images of the `default` sprite keep their plain id, the ones of any other sprite are\n     * namespaced by their sprite's id.\n     */\n    private _getSpriteImageId(spriteId: string, imageId: string): string {\n        return spriteId === 'default' ? imageId : `${spriteId}:${imageId}`;\n    }\n\n    /**\n     * Takes over the images of a single sprite: adds the new ones, updates the ones that are\n     * already known, and removes the ones that a previous load of this same sprite had brought in\n     * but that are not part of it anymore.\n     *\n     * @param spriteId - the id of the sprite the images belong to\n     * @param images - the sprite's images, keyed by their id within the sprite\n     * @returns the ids of the images that this sprite now provides, and the ids of the ones that\n     * were removed because they are no longer part of it\n     */\n    setSpriteImages(spriteId: string, images: Record<string, StyleImage>): {loaded: string[]; removed: string[]} {\n        const previousIds = this._spriteImagesIds[spriteId] ?? [];\n        const loaded: string[] = [];\n\n        for (const id in images) {\n            const imageId = this._getSpriteImageId(spriteId, id);\n            loaded.push(imageId);\n\n            if (imageId in this.images) {\n                this.updateImage(imageId, images[id], false);\n            } else {\n                this.addImage(imageId, images[id]);\n            }\n        }\n\n        const loadedIds = new Set(loaded);\n        const removed = previousIds.filter(imageId => !loadedIds.has(imageId));\n        for (const imageId of removed) {\n            this.removeImage(imageId);\n        }\n\n        this._spriteImagesIds[spriteId] = loaded;\n        return {loaded, removed};\n    }\n\n    /**\n     * Removes all the images a single sprite has brought in.\n     * @returns the ids of the removed images\n     */\n    removeSpriteImages(spriteId: string): string[] {\n        const removed = this._spriteImagesIds[spriteId] ?? [];\n        for (const imageId of removed) {\n            this.removeImage(imageId);\n        }\n\n        delete this._spriteImagesIds[spriteId];\n        return removed;\n    }\n\n    /**\n     * Removes the images of every sprite, leaving the images added at runtime alone.\n     * @returns the ids of the removed images\n     */\n    removeAllSpriteImages(): string[] {\n        const removed = Object.values(this._spriteImagesIds).flat();\n        for (const imageId of removed) {\n            this.removeImage(imageId);\n        }\n\n        this._spriteImagesIds = {};\n        return removed;\n    }\n\n    setMissingImageResolver(resolver: MissingImageRequestHandler | null): void {\n        this.missingImageResolver = resolver;\n    }\n\n    getImages(ids: string[]): Promise<GetImagesResponse> {\n        return new Promise<GetImagesResponse>((resolve, _reject) => {\n            // If the sprite has been loaded, or if all the icon dependencies are already present\n            // (i.e. if they've been added via runtime styling), then notify the requestor immediately.\n            // Otherwise, delay notification until the sprite is loaded. At that point, if any of the\n            // dependencies are still unavailable, we'll just assume they are permanently missing.\n            let hasAllDependencies = true;\n            if (!this.isLoaded()) {\n                for (const id of ids) {\n                    if (!this.images[id]) {\n                        hasAllDependencies = false;\n                    }\n                }\n            }\n            if (this.isLoaded() || hasAllDependencies) {\n                resolve(this._getImagesForIds(ids));\n            } else {\n                this.requestors.push({ids, promiseResolve: resolve});\n            }\n        });\n    }\n\n    async _getImagesForIds(ids: string[]): Promise<GetImagesResponse> {\n        const unresolvedIds = new Set(ids.filter((id) => !this.getImage(id)));\n        const resolver = this.missingImageResolver;\n\n        if (resolver) {\n            await Promise.allSettled(Array.from(unresolvedIds, (id) => resolver(id)));\n        }\n\n        const response: GetImagesResponse = {};\n\n        for (const id of ids) {\n            const image = this.getImage(id);\n\n            if (image) {\n                unresolvedIds.delete(id);\n                // Clone the image so that our own copy of its ArrayBuffer doesn't get transferred.\n                response[id] = {\n                    data: image.data.clone(),\n                    pixelRatio: image.pixelRatio,\n                    sdf: image.sdf,\n                    version: image.version,\n                    stretchX: image.stretchX,\n                    stretchY: image.stretchY,\n                    content: image.content,\n                    textFitWidth: image.textFitWidth,\n                    textFitHeight: image.textFitHeight,\n                    hasRenderCallback: Boolean(image.userImage?.render),\n                    isWebGLImage: image.isWebGLImage\n                };\n            }\n        }\n\n        for (const id of unresolvedIds) {\n            this.fire(new MapStyleImageMissingEvent({id}));\n            warnOnce(`Image \"${id}\" could not be loaded. Please make sure you have added the image before it is needed with map.addImage(), resolved it with map.setMissingStyleImageResolver(), or included it in a \"sprite\" property in your style.`);\n        }\n\n        return response;\n    }\n\n    beginFrame(): void {\n        this._renderCallbacksDispatchedThisFrame = {};\n    }\n\n    /**\n     * Re-renders the images among `ids` that were added with a `render` callback (see\n     * `StyleImageInterface`), at most once per frame each.\n     */\n    dispatchRenderCallbacks(ids: string[]): void {\n        for (const id of ids) {\n            if (this._renderCallbacksDispatchedThisFrame[id]) continue;\n            this._renderCallbacksDispatchedThisFrame[id] = true;\n\n            const image = this.getImage(id);\n            if (!image) warnOnce(`Image with ID: \"${id}\" was not found`);\n\n            const updated = renderStyleImage(image);\n            if (updated) {\n                this.updateImage(id, image);\n            }\n        }\n    }\n\n    cloneImages(): Record<string, StyleImage> {\n        const clonedImages: Record<string, StyleImage> = {};\n        for (const id in this.images) {\n            const image = this.images[id];\n            clonedImages[id] = {\n                ...image,\n                data: image.data ? image.data.clone() : null\n            };\n        }\n        return clonedImages;\n    }\n}\n", "/* eslint-disable key-spacing */\nimport potpack from 'potpack';\nimport {RGBAImage} from '../util/image.ts';\nimport {ImagePosition} from './image_atlas.ts';\nimport {Texture} from '../webgl/texture.ts';\n\nimport type {ImageManager} from './image_manager.ts';\nimport type {StyleImage} from '../style/style_image.ts';\nimport type {CrossFaded} from '../style/properties.ts';\nimport type {Context} from '../webgl/context.ts';\nimport type {PotpackBox} from 'potpack';\nimport type {ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\n\ntype Pattern = {\n    bin: PotpackBox;\n    position: ImagePosition;\n    /**\n     * The image this entry was packed from. Kept to notice when an image was removed and added\n     * again under the same id, in which case the entry has to be rebuilt even though the version\n     * of the new image may happen to match the one of the old.\n     */\n    image: StyleImage;\n};\n\n/**\n * When copied into the atlas texture, pattern images are padded by one pixel on each side with a\n * copy of the image data wrapped from the opposite side. This ensures the correct behavior of\n * GL_LINEAR texture sampling mode.\n */\nconst PADDING = 1;\n\n/**\n * A texture atlas of the pattern images that are drawn without a tile's own {@link ImageAtlas},\n * i.e. `background-pattern`. Entries are packed on demand and re-packed whenever one of them is\n * added or changes, which is rare enough for the repacking cost not to matter.\n */\nexport class PatternAtlas {\n    private _imageManager: ImageManager;\n    private _entries: Record<string, Pattern>;\n    private _image: RGBAImage;\n    private _texture: Texture;\n    private _dirty: boolean;\n\n    constructor(imageManager: ImageManager) {\n        this._imageManager = imageManager;\n        this._entries = {};\n        this._image = new RGBAImage({width: 1, height: 1});\n        this._dirty = true;\n    }\n\n    destroy(): void {\n        if (this._texture) {\n            this._texture.destroy();\n            this._texture = null;\n        }\n\n        this._entries = {};\n        this._image = new RGBAImage({width: 1, height: 1});\n        this._dirty = true;\n    }\n\n    getPixelSize(): {width: number; height: number} {\n        const {width, height} = this._image;\n        return {width, height};\n    }\n\n    /**\n     * @returns the position of the pattern within the atlas, or `null` if there is no such image\n     */\n    getPattern(id: string): ImagePosition {\n        const image = this._imageManager.getImage(id);\n        if (!image) {\n            return null;\n        }\n\n        const entry = this._entries[id];\n        if (entry?.image !== image) {\n            // there is no entry yet, or the image was replaced by another one under the same id,\n            // in which case the slot has to be packed anew - the new image may have another size\n            const w = image.data.width + PADDING * 2;\n            const h = image.data.height + PADDING * 2;\n            const bin = {w, h, x: 0, y: 0};\n            this._entries[id] = {bin, position: new ImagePosition(bin, image), image};\n        } else if (entry.position.version !== image.version) {\n            entry.position.version = image.version;\n        } else {\n            return entry.position;\n        }\n\n        this._update();\n\n        return this._entries[id].position;\n    }\n\n    /**\n     * Checks whether a pattern image is needed, and if it is, whether it is not loaded.\n     *\n     * @returns true if a needed image is missing and rendering needs to be skipped.\n     */\n    isPatternMissing(image?: CrossFaded<ResolvedImage> | null): boolean {\n        if (!image) return false;\n        if (!image.from || !image.to) return true;\n        const imagePosA = this.getPattern(image.from.toString());\n        const imagePosB = this.getPattern(image.to.toString());\n        return !imagePosA || !imagePosB;\n    }\n\n    bind(context: Context): void {\n        const gl = context.gl;\n        if (!this._texture) {\n            this._texture = new Texture(context, this._image, gl.RGBA);\n            this._dirty = false;\n        } else if (this._dirty) {\n            this._texture.update(this._image);\n            this._dirty = false;\n        }\n\n        this._texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n    }\n\n    private _update(): void {\n        // drop the entries whose image is gone - they hold on to a slot of the atlas for nothing\n        for (const id in this._entries) {\n            if (!this._imageManager.getImage(id)) {\n                delete this._entries[id];\n            }\n        }\n\n        const bins = [];\n        for (const id in this._entries) {\n            bins.push(this._entries[id].bin);\n        }\n\n        const {w, h} = potpack(bins);\n\n        const dst = this._image;\n        dst.resize({width: w || 1, height: h || 1});\n\n        for (const id in this._entries) {\n            const {bin} = this._entries[id];\n            const x = bin.x + PADDING;\n            const y = bin.y + PADDING;\n            const src = this._entries[id].image.data;\n            const w = src.width;\n            const h = src.height;\n\n            RGBAImage.copy(src, dst, {x: 0, y: 0}, {x, y}, {width: w, height: h});\n\n            // Add 1 pixel wrapped padding on each side of the image.\n            RGBAImage.copy(src, dst, {x: 0, y: h - 1}, {x, y: y - 1}, {width: w, height: 1}); // T\n            RGBAImage.copy(src, dst, {x: 0, y:     0}, {x, y: y + h}, {width: w, height: 1}); // B\n            RGBAImage.copy(src, dst, {x: w - 1, y: 0}, {x: x - 1, y}, {width: 1, height: h}); // L\n            RGBAImage.copy(src, dst, {x: 0,     y: 0}, {x: x + w, y}, {width: 1, height: h}); // R\n        }\n\n        this._dirty = true;\n    }\n}\n", "import {getArrayBuffer} from '../util/ajax.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {ensureError, warnOnce} from '../util/util.ts';\n\nimport type {FontFacesSpecification, MLFontFace} from '@maplibre/maplibre-gl-style-spec';\nimport type {RequestManager} from '../util/request_manager.ts';\n\n/**\n * An inclusive range of Unicode codepoints, parsed out of a `unicode-range` entry.\n */\nexport type UnicodeRange = {\n    start: number;\n    end: number;\n};\n\nconst MAX_CODE_POINT = 0x10FFFF;\n\n/**\n * What a font file covers when the style does not narrow it down with `unicode-range`.\n */\nconst DEFAULT_UNICODE_RANGE: UnicodeRange = {start: 0, end: MAX_CODE_POINT};\n\n/** OpenType feature to enable, or `normal` for default settings. */\nexport type FontFeature = 'normal' | 'vert';\n\n/**\n * A font file declared by the style, along with the bookkeeping needed to draw with it.\n */\ntype DeclaredFontFace = {\n    /**\n     * The font file's URL, as written in the style.\n     */\n    url: string;\n    /**\n     * The codepoints the style lets this file cover.\n     */\n    ranges: UnicodeRange[];\n    /**\n     * The CSS family name the file is registered under. It is generated rather than taken from the\n     * style so that a style cannot restyle the surrounding page by declaring a font face named\n     * after one the page uses, and so that each file can be selected on its own.\n     */\n    family: string;\n    /** Cached load results by feature: the CSS family, or `null` if unavailable. */\n    loads: Partial<Record<FontFeature, Promise<string | null>>>;\n    /** Font download temporarily shared by overlapping face loads. */\n    data?: Promise<ArrayBuffer>;\n};\n\n/**\n * Makes the family names unique across every map on the page, since `document.fonts` is shared.\n */\nlet nextFamilyId = 0;\n\n/**\n * Parses one `unicode-range` entry, in the CSS grammar the style specification borrows: `U+A5`,\n * `U+0-10FFFF` or `U+4??`.\n * @param value - a single `unicode-range` entry\n * @returns the codepoints it covers, or `null` if it is not a range this can make sense of\n */\nfunction parseUnicodeRange(value: string): UnicodeRange | null {\n    const wildcard = /^u\\+([0-9a-f]*)(\\?+)$/i.exec(value);\n    if (wildcard) {\n        const [, prefix, questionMarks] = wildcard;\n        if (prefix.length + questionMarks.length > 6) return null;\n        return clampRange(\n            parseInt(`${prefix}${'0'.repeat(questionMarks.length)}`, 16),\n            parseInt(`${prefix}${'f'.repeat(questionMarks.length)}`, 16)\n        );\n    }\n\n    const explicit = /^u\\+([0-9a-f]{1,6})(?:-([0-9a-f]{1,6}))?$/i.exec(value);\n    if (!explicit) return null;\n\n    const start = parseInt(explicit[1], 16);\n    return clampRange(start, explicit[2] === undefined ? start : parseInt(explicit[2], 16));\n}\n\nfunction clampRange(start: number, end: number): UnicodeRange | null {\n    if (start > end || start > MAX_CODE_POINT) return null;\n    return {start, end: Math.min(end, MAX_CODE_POINT)};\n}\n\n/**\n * Whether the style lets this file cover the given codepoint.\n */\nfunction covers(face: DeclaredFontFace, codePoint: number): boolean {\n    return face.ranges.some(({start, end}) => codePoint >= start && codePoint <= end);\n}\n\n/**\n * Keeps the font files a style declares in its\n * [`font-faces`](https://maplibre.org/maplibre-style-spec/root/#font-faces) property, and hands the\n * {@link GlyphManager} the CSS family to draw a given codepoint with.\n *\n * The files go to the browser's CSS Font Loading API, so any format it can render text with works.\n * Each is registered under a family name of our own making, so that a style cannot restyle the\n * surrounding page and a codepoint can be pinned to one file rather than to whatever font matching\n * picks.\n *\n * Rasterizing happens a grapheme cluster at a time, so a letter reaches the browser's text engine\n * with its marks. Shaping across cluster boundaries still needs the RTL text plugin.\n */\nexport class FontFaceManager {\n    requestManager: RequestManager;\n    /**\n     * The declared files by the font name used in `text-font`, in the order the style listed them.\n     */\n    _faces: Record<string, DeclaredFontFace[]>;\n    /**\n     * Everything handed to `document.fonts`, so that it can all be handed back on destroy.\n     */\n    _registered: Set<FontFace>;\n\n    constructor(requestManager: RequestManager) {\n        this.requestManager = requestManager;\n        this._faces = {};\n        this._registered = new Set();\n    }\n\n    /**\n     * Replaces the declared font faces. Nothing is downloaded here: each file waits until a\n     * codepoint it covers is actually drawn.\n     */\n    setFontFaces(fontFaces?: FontFacesSpecification | null): void {\n        this._unregisterAll();\n        this._faces = {};\n\n        for (const [fontName, declaration] of Object.entries(fontFaces ?? {})) {\n            const declarations = Array.isArray(declaration) ? declaration : [declaration];\n            this._faces[fontName] = declarations\n                .map(entry => this._declareFontFace(fontName, entry))\n                .filter(face => face !== null);\n        }\n    }\n\n    /**\n     * Whether the style declared any font face at all, so that the common case of a style without\n     * `font-faces` costs nothing.\n     */\n    hasFontFaces(): boolean {\n        return Object.keys(this._faces).length > 0;\n    }\n\n    /**\n     * Finds the font file to draw a codepoint with: each name of the `text-font` stack in turn, and\n     * within a name each declared file, until one covers it. A file that fails to load is skipped,\n     * the specification asking for unsupported fonts to be ignored.\n     *\n     * Requests with a feature enabled use the normal face's file and return `null` if loading fails.\n     *\n     * @param fontStack - comma-separated font names, in fallback order\n     * @param codePoint - codepoint to match against the declared Unicode ranges\n     * @param feature - OpenType feature to enable, or `normal` for default settings\n     * @returns the loaded CSS family, or `null` if the requested face is unavailable\n     */\n    async getFontFamily(fontStack: string, codePoint: number, feature: FontFeature): Promise<string | null> {\n        for (const fontName of fontStack.split(',')) {\n            for (const face of this._faces[fontName.trim()] ?? []) {\n                if (!covers(face, codePoint)) continue;\n\n                face.loads.normal ??= this._loadFontFace(face, 'normal');\n                const data = face.data;\n                const family = await face.loads.normal;\n                if (!family) continue;\n\n                if (feature === 'normal') return family;\n\n                face.loads[feature] ??= this._loadFontFace(face, feature, data);\n                return face.loads[feature];\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Turns one declaration into a face to draw with, or `null` if there is nothing usable in it.\n     *\n     * A bare URL is the same as a face that names no `unicode-range`: it covers every codepoint.\n     */\n    _declareFontFace(fontName: string, declaration: string | MLFontFace): DeclaredFontFace | null {\n        const face: MLFontFace = typeof declaration === 'string' ? {url: declaration} : declaration;\n\n        if (typeof face?.url !== 'string') {\n            warnOnce(`Ignoring the font face declared for \"${fontName}\": it has no URL.`);\n            return null;\n        }\n\n        const family = `maplibre-gl-font-face-${nextFamilyId++}`;\n        const unicodeRange = face['unicode-range'];\n        if (!unicodeRange?.length) {\n            return {url: face.url, ranges: [DEFAULT_UNICODE_RANGE], family, loads: {}};\n        }\n\n        const ranges: UnicodeRange[] = [];\n        for (const entry of unicodeRange) {\n            const range = parseUnicodeRange(entry);\n            if (!range) {\n                warnOnce(`Ignoring the unicode range \"${entry}\" of the font face at ${face.url}: it is not a valid range.`);\n                continue;\n            }\n            ranges.push(range);\n        }\n        if (!ranges.length) return null;\n\n        return {url: face.url, ranges, family, loads: {}};\n    }\n\n    /**\n     * Loads and registers a declared font with the requested OpenType feature.\n     *\n     * @param face - font file declaration and CSS family to register\n     * @param feature - OpenType feature to enable, or `normal` for default settings\n     * @param data - a download retained by a concurrent request while the normal face loads\n     * @returns the registered CSS family, or `null` on failure, ignored feature settings or disposal\n     */\n    async _loadFontFace(face: DeclaredFontFace, feature: FontFeature, data?: Promise<ArrayBuffer>): Promise<string | null> {\n        const description = feature === 'normal' ? 'font face' : `font face with \"${feature}\" enabled`;\n        if (typeof FontFace === 'undefined' || typeof document === 'undefined' || !document.fonts) {\n            warnOnce(`Ignoring the ${description} at ${face.url}: this environment has no CSS Font Loading API.`);\n            return null;\n        }\n\n        let fontFace: FontFace;\n        try {\n            if (!data) {\n                face.data ??= this._downloadFontFile(face.url);\n                data = face.data;\n            }\n            const family = feature === 'normal' ? face.family : `${face.family}-${feature}`;\n            fontFace = new FontFace(family, await data,\n                {featureSettings: feature === 'normal' ? 'normal' : `\"${feature}\" 1`});\n            if (!Object.values(this._faces).some(faces => faces.includes(face))) return null;\n            if (feature !== 'normal' && (!fontFace.featureSettings || fontFace.featureSettings === 'normal')) return null;\n            document.fonts.add(fontFace);\n            this._registered.add(fontFace);\n            await fontFace.load();\n            return this._registered.has(fontFace) ? family : null;\n        } catch (e) {\n            if (fontFace) this._unregister(fontFace);\n            warnOnce(`Ignoring the ${description} at ${face.url}: ${ensureError(e).message}`);\n            return null;\n        } finally {\n            if (face.data === data) delete face.data;\n        }\n    }\n\n    /**\n     * Downloads a font file, giving the map's `transformRequest` a chance to rewrite the request the\n     * same way it gets one for a glyph range.\n     */\n    async _downloadFontFile(url: string): Promise<ArrayBuffer> {\n        const request = await this.requestManager.transformRequest(url, ResourceType.Glyphs);\n        const response = await getArrayBuffer(request, new AbortController());\n        if (!response?.data) {\n            throw new Error(`the response was empty for the font file at ${url}`);\n        }\n        return response.data;\n    }\n\n    _unregister(fontFace: FontFace): void {\n        document.fonts?.delete(fontFace);\n        this._registered.delete(fontFace);\n    }\n\n    _unregisterAll(): void {\n        for (const faces of Object.values(this._faces)) {\n            for (const face of faces) delete face.data;\n        }\n        for (const fontFace of this._registered) {\n            document.fonts?.delete(fontFace);\n        }\n        this._registered.clear();\n    }\n\n    destroy(): void {\n        this._unregisterAll();\n        this._faces = {};\n    }\n}\n", "const INF = 1e20;\n\n// lookup table for gamma-corrected, signed squared alpha distance values\nconst alphaTable = new Float64Array(256);\nfor (let i = 0; i < 256; i++) {\n    const d = 0.5 - Math.pow(i / 255, 1 / 2.2);\n    alphaTable[i] = d * Math.abs(d);\n}\nalphaTable[255] = -INF;\n\nexport default class TinySDF {\n    constructor({\n        fontSize = 24,\n        buffer = 3,\n        radius = 8,\n        cutoff = 0.25,\n        fontFamily = 'sans-serif',\n        fontWeight = 'normal',\n        fontStyle = 'normal',\n        lang = null\n    } = {}) {\n        buffer = this.buffer = Math.round(buffer); // padding around a glyph's bounding box; integer to keep the grid pixel-aligned\n        this.radius = radius; // how many pixels around the glyph edge are encoded as signed distances\n        this.cutoff = cutoff; // how much of the SDF byte range represents inside vs outside the edge\n        this.lang = lang; // language of the Canvas drawing context\n\n        // make the canvas size big enough to both have the specified buffer around the glyph\n        // for \"halo\", and account for some glyphs possibly being larger than their font size\n        const size = this.size = Math.ceil(fontSize) + buffer * 4;\n\n        const canvas = this._createCanvas(size);\n        const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true});\n        ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;\n\n        ctx.textBaseline = 'alphabetic';\n        ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment\n        ctx.fillStyle = 'black';\n        if (lang) ctx.lang = lang;\n\n        // the glyph is rasterized at (buffer, buffer), so the canvas clips it to this\n        const maxGlyphDim = this.maxGlyphDim = size - buffer;\n        const gridDim = maxGlyphDim + 2 * buffer;\n\n        // two grids of squared distances: one for the outside of the glyph shape, one for the inside;\n        // the signed distance is derived as sqrt(outer) - sqrt(inner)\n        this.gridOuter = new Float64Array(gridDim * gridDim);\n        this.gridInner = new Float64Array(gridDim * gridDim);\n        this.f = new Float64Array(gridDim);\n        this.z = new Float64Array(gridDim + 1);\n        this.v = new Uint16Array(gridDim);\n    }\n\n    _createCanvas(size) {\n        if (typeof OffscreenCanvas !== 'undefined') {\n            return new OffscreenCanvas(size, size);\n        }\n        const canvas = document.createElement('canvas');\n        canvas.width = canvas.height = size;\n        return canvas;\n    }\n\n    draw(char) {\n        const {\n            width: glyphAdvance,\n            actualBoundingBoxAscent,\n            actualBoundingBoxDescent,\n            actualBoundingBoxLeft,\n            actualBoundingBoxRight\n        } = this.ctx.measureText(char);\n\n        // The integer/pixel part of the alignment is encoded in metrics.glyphTop/glyphLeft\n        // The remainder is implicitly encoded in the rasterization\n        const glyphTop = Math.ceil(actualBoundingBoxAscent);\n        // actualBoundingBoxLeft is positive when ink extends LEFT of the origin (per spec),\n        // so negate to get the ink's left edge in canvas x-coords (positive = right of origin)\n        const glyphLeft = Math.floor(-actualBoundingBoxLeft);\n\n        // If the glyph overflows the canvas size, it will be clipped at the bottom/right\n        const glyphWidth = Math.max(0, Math.min(this.maxGlyphDim, Math.ceil(actualBoundingBoxRight) - glyphLeft));\n        const glyphHeight = Math.max(0, Math.min(this.maxGlyphDim, glyphTop + Math.ceil(actualBoundingBoxDescent)));\n\n        const width = glyphWidth + 2 * this.buffer;\n        const height = glyphHeight + 2 * this.buffer;\n\n        const len = width * height;\n        const data = new Uint8ClampedArray(len);\n        const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance};\n        if (glyphWidth === 0 || glyphHeight === 0) return glyph;\n\n        const {ctx, buffer, gridInner, gridOuter} = this;\n        ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);\n        ctx.fillText(char, buffer - glyphLeft, buffer + glyphTop);\n        const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);\n\n        // default: outside the glyph (INF distance) for outer, inside (0 distance) for inner\n        gridOuter.fill(INF, 0, len);\n        gridInner.fill(0, 0, len);\n\n        // for anti-aliased pixels, treat partial coverage as a distance approximation:\n        // a fully covered pixel gets 0 outer / INF inner; a partial pixel gets a small\n        // non-zero outer or inner distance based on how far its coverage deviates from 0.5\n        let imgIdx = 3; // start at the alpha channel of the first pixel\n        for (let y = 0; y < glyphHeight; y++) {\n            let j = (y + buffer) * width + buffer;\n            for (let x = 0; x < glyphWidth; x++, imgIdx += 4, j++) {\n                const a = imgData.data[imgIdx]; // alpha value\n                if (a === 0) continue; // empty pixels\n                const t = alphaTable[a];\n                gridOuter[j] = Math.max(0, t);\n                gridInner[j] = Math.max(0, -t);\n            }\n        }\n\n        // columns left and right of the glyph have no seeds and stay INF in the column pass, so skip them\n        edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z, buffer);\n        // Pad the inner EDT region by 1 px so ink pixels touching the bbox edge can see the\n        // outside-ink seeds in the buffer region; clamp to buffer so we don't underflow when buffer=0\n        const pad = Math.min(buffer, 1);\n        edt(gridInner, buffer - pad, buffer - pad, glyphWidth + 2 * pad, glyphHeight + 2 * pad, width, this.f, this.v, this.z);\n\n        // encode signed distance as a byte: inside the glyph maps to high values, outside to low,\n        // with the edge gradient spanning [-radius * cutoff, radius * (1 - cutoff)] pixels around the edge;\n        // Uint8ClampedArray rounds and clamps beyond that\n        const scale = 255 / this.radius;\n        const base = 255 * (1 - this.cutoff);\n        for (let i = 0; i < len; i++) {\n            const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);\n            data[i] = base - scale * d;\n        }\n\n        return glyph;\n    }\n}\n\n// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, x0, y0, width, height, gridSize, f, v, z, skipCols = 0) {\n    for (let x = x0 + skipCols; x < x0 + width - skipCols; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);\n    for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z);\n}\n\n// 1D squared distance transform\nfunction edt1d(grid, offset, stride, length, f, v, z) {\n    v[0] = 0;\n    z[0] = -INF;\n    z[1] = INF;\n    f[0] = grid[offset];\n\n    for (let q = 1, k = 0; q < length; q++) {\n        const fq = f[q] = grid[offset + q * stride];\n        const q2 = q * q;\n        let s;\n        do {\n            const r = v[k];\n            s = (fq - f[r] + q2 - r * r) / (q - r) / 2;\n        } while (s <= z[k] && --k > -1);\n\n        k++;\n        v[k] = q;\n        z[k] = s;\n        z[k + 1] = INF;\n    }\n\n    for (let q = 0, k = 0; q < length; q++) {\n        while (z[k + 1] < q) k++;\n        const r = v[k];\n        const qr = q - r;\n        grid[offset + q * stride] = f[r] + qr * qr;\n    }\n}\n", "import {FontFaceManager, type FontFeature} from './font_face_manager.ts';\nimport TinySDF, {type TinySDFOptions} from '@mapbox/tiny-sdf';\nimport {codePointIsInComplexShapingScript, codePointUsesLocalIdeographFontFamily} from '../util/unicode_properties.g.ts';\nimport {isCluster} from '../util/graphemes.ts';\nimport {AlphaImage} from '../util/image.ts';\nimport {ensureError, warnOnce} from '../util/util.ts';\nimport {getArrayBuffer} from '../util/ajax.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {parseGlyphPbf} from '../style/parse_glyph_pbf.ts';\nimport {v8} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {GlyphMap, GlyphRequests, StyleGlyph} from '../style/style_glyph.ts';\nimport type {RequestManager} from '../util/request_manager.ts';\nimport type {FontFacesSpecification} from '@maplibre/maplibre-gl-style-spec';\n\ntype Entry = {\n    /**\n     * The glyphs requested so far, keyed by variant and grapheme cluster.\n     * `null` means the requested glyph is unavailable.\n     */\n    glyphs: Record<string, Record<string, StyleGlyph | null>>;\n    /** The PBF ranges downloaded or being downloaded, keyed by range number. */\n    requests: Record<number, Promise<Record<number, StyleGlyph | null>>>;\n    tinySDF?: Promise<Rasterizer>;\n    ideographTinySDF?: Promise<Rasterizer>;\n    /**\n     * One TinySDF per `font-faces` file this stack draws with, keyed by the file's CSS family.\n     */\n    fontFaceTinySDFs?: Record<string, Promise<Rasterizer>>;\n    /**\n     * One TinySDF per font selection used to draw whole grapheme clusters, which need a wider canvas\n     * to fit in than a single codepoint does.\n     */\n    clusterTinySDFs?: Record<string, Promise<Rasterizer>>;\n};\n\n/** A requested glyph with its lookup keys; `null` means unavailable. */\ntype GlyphResult = {\n    stack: string;\n    id: string;\n    variant: string;\n    glyph: StyleGlyph | null;\n};\n\n/**\n * The style specification hard-codes some last resort fonts as a default fontstack.\n */\nconst defaultStack = v8.layout_symbol['text-font'].default.join(',');\n/**\n * The CSS generic font family closest to `defaultStack`.\n */\nconst defaultGenericFontFamily = 'sans-serif';\n\n/**\n * Scale factor for client-generated glyphs.\n *\n * Client-generated glyphs are rendered at 2× because CJK glyphs are more detailed than others.\n */\nconst textureScale = 2;\n\n/**\n * TinySDF's \"top\" is the distance from the alphabetic baseline to the top of the glyph.\n * Server-generated fonts specify \"top\" relative to an origin above the em box (the origin\n * comes from FreeType, but I'm unclear on exactly how it's derived)\n * ref: https://github.com/mapbox/sdf-glyph-foundry\n *\n * Server fonts don't yet include baseline information, so we can't line up exactly with them\n * (and they don't line up with each other)\n * ref: https://github.com/mapbox/node-fontnik/pull/160\n *\n * To approximately align TinySDF glyphs with server-provided glyphs, we use this baseline adjustment\n * factor calibrated to be in between DIN Pro and Arial Unicode (but closer to Arial Unicode)\n */\nconst topAdjustment = 27.5;\n\nconst leftAdjustment = 0.5;\n\n/**\n * The rasterizer, as it really is. TinySDF carries the `buffer` it was built with, which its type\n * declaration leaves out and which the canvas has to be widened through.\n */\nexport type Rasterizer = TinySDF & {buffer: number};\n\n/**\n * Builds the thing that rasterizes a glyph. Taken as a dependency so that a test can stand in for\n * the canvas it would otherwise need to draw on.\n *\n * @param options - what to draw with, whose `buffer` sizes the canvas\n * @param padding - the room to leave around each glyph in the bitmap, which is not that buffer\n */\nexport type CreateRasterizer = (options: TinySDFOptions, padding: number) => Rasterizer;\n\nconst defaultCreateRasterizer: CreateRasterizer = (options, padding) => {\n    const tinySDF = new TinySDF(options) as Rasterizer;\n    tinySDF.buffer = padding;\n    return tinySDF;\n};\n\n/**\n * How wide a grapheme cluster may be drawn, in multiples of the font size.\n *\n * TinySDF sizes its canvas for a single character and cuts off the rest, but a cluster is a whole\n * syllable: Burmese `လား` is nearly twice the font size. Three ems fits the ones that occur.\n */\nconst clusterEmsWide = 3;\n\n/**\n * The OpenType feature each alternate variant is drawn with. A variant is `null` where the font has\n * no distinct alternate, so that layout can fall back to rotation or a compatibility character.\n */\nconst variantFeatures: Record<string, FontFeature> = {\n    vertical: 'vert'\n};\n\n/** Whether two glyphs have identical bitmaps and metrics. */\nfunction glyphsEqual(a: StyleGlyph, b: StyleGlyph): boolean {\n    return a.bitmap.width === b.bitmap.width && a.bitmap.height === b.bitmap.height &&\n        a.metrics.width === b.metrics.width && a.metrics.height === b.metrics.height &&\n        a.metrics.left === b.metrics.left && a.metrics.top === b.metrics.top &&\n        a.metrics.advance === b.metrics.advance &&\n        a.bitmap.data.every((value, index) => value === b.bitmap.data[index]);\n}\n\nexport class GlyphManager {\n    requestManager: RequestManager;\n    localIdeographFontFamily: string | false;\n    entries: Record<string, Entry>;\n    url: string;\n    lang?: string;\n    fontFaceManager: FontFaceManager;\n    createRasterizer: CreateRasterizer;\n    /** Default glyphs shared by requests and alternate comparisons, keyed by rasterizer. */\n    rasterizedGlyphs: WeakMap<Rasterizer, Record<string, StyleGlyph>> = new WeakMap();\n\n    constructor(\n        requestManager: RequestManager,\n        localIdeographFontFamily?: string | false,\n        lang?: string,\n        createRasterizer: CreateRasterizer = defaultCreateRasterizer\n    ) {\n        this.requestManager = requestManager;\n        this.localIdeographFontFamily = localIdeographFontFamily;\n        this.entries = {};\n        this.lang = lang;\n        this.fontFaceManager = new FontFaceManager(requestManager);\n        this.createRasterizer = createRasterizer;\n    }\n\n    setURL(url?: string | null): void {\n        this.url = url;\n    }\n\n    /**\n     * Replaces the font files the style declares in its `font-faces` property, dropping every glyph\n     * drawn with the previous ones.\n     */\n    setFontFaces(fontFaces?: FontFacesSpecification | null): void {\n        this.fontFaceManager.setFontFaces(fontFaces);\n        this.entries = {};\n    }\n\n    async getGlyphs(glyphs: GlyphRequests): Promise<GlyphMap> {\n        const glyphsPromises: Array<Promise<GlyphResult>> = [];\n        const hasFontFaces = this.fontFaceManager.hasFontFaces();\n\n        for (const stack in glyphs) {\n            for (const variant in glyphs[stack]) {\n                if (variantFeatures[variant] && !hasFontFaces) continue;\n                for (const id of glyphs[stack][variant]) {\n                    glyphsPromises.push(this._getAndCacheGlyphsPromise(stack, id, variant));\n                }\n            }\n        }\n\n        const updatedGlyphs = await Promise.all(glyphsPromises);\n\n        const result: GlyphMap = {};\n\n        for (const {stack, id, variant, glyph} of updatedGlyphs) {\n            result[stack] ||= {};\n            result[stack][variant] ||= {};\n            // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred.\n            result[stack][variant][id] = glyph && {\n                id: glyph.id,\n                bitmap: glyph.bitmap.clone(),\n                metrics: glyph.metrics\n            };\n        }\n\n        return result;\n    }\n\n    /**\n     * Gets one glyph, asked for by grapheme cluster so that a letter and its marks are drawn as the\n     * one shape they are written as.\n     *\n     * A cluster is drawn from a font rather than fetched, because a glyphs URL serves codepoints and\n     * has no way to serve the one shape they are written as. A file the style pinned with\n     * `font-faces` draws it where one covers it, and the local fonts otherwise. For a single\n     * codepoint a declared file still wins over the glyphs URL and the local fallbacks.\n     *\n     * Lone letters of scripts that form clusters are drawn locally too, so a word isn't split across\n     * two fonts.\n     *\n     * Other variants use only declared font files and variantFeatures; unknown ones return `null`.\n     */\n    async _getAndCacheGlyphsPromise(stack: string, id: string, variant: string): Promise<GlyphResult> {\n        // Create an entry for this fontstack if it doesn’t already exist.\n        this.entries[stack] ??= {glyphs: {default: {}}, requests: {}};\n        const entry = this.entries[stack];\n        const glyphs = (entry.glyphs[variant] ||= {});\n\n        // Try to get the glyph from the cache of client-side glyphs.\n        let glyph = glyphs[id];\n        if (glyph !== undefined) {\n            return {stack, id, variant, glyph};\n        }\n\n        if (variant !== 'default') {\n            const feature = variantFeatures[variant];\n            glyph = feature ? await this._drawAlternateGlyph(entry, stack, id, feature) : null;\n            glyphs[id] = glyph;\n            return {stack, id, variant, glyph};\n        }\n\n        const codePoint = id.codePointAt(0);\n        const fontFaceFamily = this.fontFaceManager.hasFontFaces() ?\n            await this.fontFaceManager.getFontFamily(stack, codePoint, 'normal') :\n            null;\n\n        if (fontFaceFamily) {\n            glyph = await this._drawGlyph(entry, stack, id, fontFaceFamily);\n            glyphs[id] = glyph;\n            return {stack, id, variant, glyph};\n        }\n\n        // If the style hasn’t opted into server-side fonts, this codepoint is CJK or in a script that\n        // forms clusters, or this is a cluster that a codepoint-keyed glyphs URL cannot serve, draw the\n        // glyph locally and cache it.\n        if (!this.url || isCluster(id) || this._charUsesLocalIdeographFontFamily(codePoint) ||\n            codePointIsInComplexShapingScript(codePoint)) {\n            glyph = await this._drawGlyph(entry, stack, id);\n            glyphs[id] = glyph;\n            return {stack, id, variant, glyph};\n        }\n\n        return {...await this._downloadAndCacheRangePromise(stack, id), variant};\n    }\n\n    /**\n     * Draws a font's glyph with `feature` enabled and compares it with its default glyph.\n     * Returns the alternate, or `null` if it is missing, empty, identical, or its font was replaced.\n     */\n    async _drawAlternateGlyph(entry: Entry, stack: string, id: string, feature: FontFeature): Promise<StyleGlyph | null> {\n        const alternateTinySDF = await this._getFontFaceTinySDF(entry, stack, id, feature);\n        if (!alternateTinySDF || this.entries[stack] !== entry) return null;\n\n        const char = alternateTinySDF.draw(id);\n        if (!char.glyphWidth || !char.glyphHeight) return null;\n\n        const defaultTinySDF = await this._getFontFaceTinySDF(entry, stack, id, 'normal');\n        if (!defaultTinySDF || this.entries[stack] !== entry) return null;\n\n        const glyph = this._createGlyph(id, char);\n        const original = this._getRasterizedGlyph(defaultTinySDF, id);\n        return glyphsEqual(original, glyph) ? null : glyph;\n    }\n\n    /**\n     * Gets a glyph from the server-side cache, downloading the PBF range it falls in if need be.\n     *\n     * Only reached for a single codepoint. What comes back is keyed by codepoint, as the file is,\n     * and is cached by cluster -- which for one codepoint is the character itself. Only the\n     * requested glyph is cached, because the rest of the range may be covered by a declared font.\n     */\n    async _downloadAndCacheRangePromise(stack: string, id: string): Promise<{stack: string; id: string; glyph: StyleGlyph}> {\n        const codePoint = id.codePointAt(0);\n        const entry = this.entries[stack];\n        const range = Math.floor(codePoint / 256);\n\n        // Start downloading this range unless we’re currently downloading it.\n        entry.requests[range] ||= this._loadGlyphRange(stack, range);\n\n        try {\n            const response = await entry.requests[range];\n            const glyph = response[codePoint] || null;\n            entry.glyphs.default[id] = glyph;\n            return {stack, id, glyph};\n        } catch (e) {\n            // Fall back to drawing the glyph locally and caching it.\n            const glyph = await this._drawGlyph(entry, stack, id);\n            entry.glyphs.default[id] = glyph;\n            this._warnOnMissingGlyphRange(glyph, range, codePoint, ensureError(e));\n            return {stack, id, glyph};\n        }\n    }\n\n    /**\n     * Downloads one range of 256 codepoints from the glyphs URL and parses the glyphs out of it.\n     */\n    async _loadGlyphRange(fontstack: string, range: number): Promise<Record<number, StyleGlyph | null>> {\n        const begin = range * 256;\n        const end = begin + 255;\n\n        const request = await this.requestManager.transformRequest(\n            this.url.replace('{fontstack}', fontstack).replace('{range}', `${begin}-${end}`),\n            ResourceType.Glyphs\n        );\n\n        const response = await getArrayBuffer(request, new AbortController());\n        if (!response?.data) {\n            throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`);\n        }\n\n        const glyphs = {};\n        for (const glyph of parseGlyphPbf(response.data)) {\n            glyphs[glyph.id] = glyph;\n        }\n        return glyphs;\n    }\n\n    _warnOnMissingGlyphRange(glyph: StyleGlyph, range: number, id: number, err: Error): void {\n        const begin = range * 256;\n        const end = begin + 255;\n        const codePoint = id.toString(16).padStart(4, '0').toUpperCase();\n        warnOnce(`Unable to load glyph range ${range}, ${begin}-${end}. Rendering codepoint U+${codePoint} locally instead. ${err}`);\n    }\n\n    /**\n     * Returns whether the given codepoint should be rendered locally.\n     */\n    _charUsesLocalIdeographFontFamily(id: number): boolean {\n        return !!this.localIdeographFontFamily && codePointUsesLocalIdeographFontFamily(id);\n    }\n\n    /**\n     * Draws a glyph offscreen using TinySDF, created lazily. The whole cluster goes to TinySDF, which\n     * is what lets the browser's text engine place a letter's marks on it.\n     *\n     * @param entry - cached glyphs and rasterizers for this font stack\n     * @param stack - font stack used for local font fallback\n     * @param id - grapheme cluster to rasterize\n     * @param fontFaceFamily - the CSS family of the selected declared font, if any\n     * @returns the rasterized glyph with metrics at the atlas's base resolution\n     */\n    async _drawGlyph(entry: Entry, stack: string, id: string, fontFaceFamily?: string): Promise<StyleGlyph> {\n        const tinySDF = await this._getTinySDF(entry, stack, id, fontFaceFamily);\n        return this._getRasterizedGlyph(tinySDF, id);\n    }\n\n    /** Draws each default glyph once per rasterizer, including concurrent requests. */\n    _getRasterizedGlyph(tinySDF: Rasterizer, id: string): StyleGlyph {\n        let glyphs = this.rasterizedGlyphs.get(tinySDF);\n        if (!glyphs) {\n            glyphs = {};\n            this.rasterizedGlyphs.set(tinySDF, glyphs);\n        }\n        glyphs[id] ??= this._createGlyph(id, tinySDF.draw(id));\n        return glyphs[id];\n    }\n\n    /** Converts a TinySDF bitmap and metrics to a style glyph. */\n    _createGlyph(id: string, char: ReturnType<TinySDF['draw']>): StyleGlyph {\n        // By definition, control characters are invisible and nonspacing.\n        const isControl = /^\\p{gc=Cf}+$/u.test(id);\n\n        return {\n            id: id.codePointAt(0),\n            bitmap: new AlphaImage({width: char.width || 30 * textureScale, height: char.height || 30 * textureScale}, char.data),\n            metrics: {\n                width: isControl ? 0 : (char.glyphWidth / textureScale || 24),\n                height: char.glyphHeight / textureScale || 24,\n                left: (char.glyphLeft / textureScale + leftAdjustment) || 0,\n                top: char.glyphTop / textureScale - topAdjustment || -8,\n                advance: isControl ? 0 : (char.glyphAdvance / textureScale || 24),\n                isDoubleResolution: true\n            }\n        };\n    }\n\n    /** Resolves a declared font and its rasterizer, skipping obsolete cache entries. */\n    async _getFontFaceTinySDF(entry: Entry, stack: string, id: string, feature: FontFeature): Promise<Rasterizer | null> {\n        if (this.entries[stack] !== entry) return null;\n\n        const family = await this.fontFaceManager.getFontFamily(stack, id.codePointAt(0), feature);\n        if (!family || this.entries[stack] !== entry) return null;\n\n        return this._getTinySDF(entry, stack, id, family);\n    }\n\n    /**\n     * Returns the TinySDF that draws this grapheme, created lazily. A stack keeps one per font\n     * selection, so a fallback cannot bleed into the rest of the text, and one more per font file\n     * for the clusters drawn from it, which need a wider canvas.\n     *\n     * A font file carries its own weight and style, so neither is sniffed out of the family name.\n     * Where no file covers the grapheme, `localIdeographFontFamily` beats the last resort fontstack.\n     */\n    _getTinySDF(entry: Entry, stack: string, id: string, fontFaceFamily?: string): Promise<Rasterizer> {\n        const cluster = isCluster(id);\n\n        if (fontFaceFamily) {\n            const cache = cluster ? 'clusterTinySDFs' : 'fontFaceTinySDFs';\n\n            entry[cache] ??= {};\n            entry[cache][fontFaceFamily] ||= this._createTinySDF(fontFaceFamily, false, cluster ? clusterEmsWide : 1);\n            return entry[cache][fontFaceFamily];\n        }\n\n        const usesLocalIdeographFontFamily = stack === defaultStack &&\n            this.localIdeographFontFamily !== '' &&\n            this._charUsesLocalIdeographFontFamily(id.codePointAt(0));\n        const family = usesLocalIdeographFontFamily ? this.localIdeographFontFamily as string : stack;\n\n        if (cluster) {\n            entry.clusterTinySDFs ??= {};\n            entry.clusterTinySDFs[family] ||= this._createTinySDF(family, true, clusterEmsWide);\n            return entry.clusterTinySDFs[family];\n        }\n\n        const cache = usesLocalIdeographFontFamily ? 'ideographTinySDF' : 'tinySDF';\n        entry[cache] ||= this._createTinySDF(family);\n        return entry[cache];\n    }\n\n    /**\n     * Builds the TinySDF that draws with a given font selection.\n     *\n     * TinySDF derives its canvas from `fontSize + buffer * 4`, so the buffer is the only way in to a\n     * wider one. It also stands for the padding the atlas expects to be `GLYPH_PBF_BORDER`, so the\n     * two are passed separately.\n     *\n     * @param emsWide - how wide the glyphs may be, in font sizes, before TinySDF cuts them off\n     */\n    async _createTinySDF(stack: String | false, sniffFontStyles: boolean = true, emsWide: number = 1): Promise<Rasterizer> {\n        // Escape and quote the font family list for use in CSS.\n        const fontFamilies = stack ? stack.split(',') : [];\n        fontFamilies.push(defaultGenericFontFamily);\n        const fontFamily = fontFamilies.map(fontName =>\n            /[-\\w]+/.test(fontName) ? fontName : `'${CSS.escape(fontName)}'`\n        ).join(',');\n\n        const fontSize = 24 * textureScale;\n        const fontWeight = sniffFontStyles ? this._fontWeight(fontFamilies[0]) : undefined;\n        const fontStyle = sniffFontStyles ? this._fontStyle(fontFamilies[0]) : 'normal';\n\n        // Await web font load so TinySDF doesn't cache a fallback bitmap. See #7307.\n        if (typeof document !== 'undefined' && document.fonts?.load) {\n            try {\n                await document.fonts.load(`${fontStyle} ${fontWeight || 'normal'} ${fontSize}px ${fontFamily}`);\n            } catch (e) {\n                warnOnce(`Failed to load font \"${fontFamily}\": ${ensureError(e).message}`);\n            }\n        }\n\n        const padding = 3 * textureScale;\n        return this.createRasterizer({\n            fontSize,\n            buffer: Math.max(padding, Math.ceil(fontSize * (emsWide - 1) / 4)),\n            radius: 8 * textureScale,\n            cutoff: 0.25,\n            fontFamily,\n            fontWeight,\n            fontStyle,\n            lang: this.lang\n        }, padding);\n    }\n\n    /**\n     * Sniffs the font style out of a font family name.\n     */\n    _fontStyle(fontFamily: string): string {\n        if (/italic/i.test(fontFamily)) {\n            return 'italic';\n        } else if (/oblique/i.test(fontFamily)) {\n            return 'oblique';\n        }\n        return 'normal';\n    }\n\n    /**\n     * Sniffs the font weight out of a font family name.\n     */\n    _fontWeight(fontFamily: string): string {\n        // Based on the OpenType specification\n        // https://learn.microsoft.com/en-us/typography/opentype/spec/os2#usweightclass\n        const weightsByName = {\n            thin: 100, hairline: 100,\n            'extra light': 200, 'ultra light': 200,\n            light: 300,\n            normal: 400, regular: 400,\n            medium: 500,\n            semibold: 600, demibold: 600,\n            bold: 700,\n            'extra bold': 800, 'ultra bold': 800,\n            black: 900, heavy: 900,\n            'extra black': 950, 'ultra black': 950\n        };\n        let match;\n        for (const [name, weight] of Object.entries(weightsByName)) {\n            if (new RegExp(`\\\\b${name}\\\\b`, 'i').test(fontFamily)) {\n                match = `${weight}`;\n            }\n        }\n        return match;\n    }\n\n    destroy(): void {\n        for (const stack in this.entries) {\n            const entry = this.entries[stack];\n            entry.tinySDF = null;\n            entry.ideographTinySDF = null;\n            entry.fontFaceTinySDFs = {};\n            entry.glyphs = {default: {}};\n            entry.requests = {};\n        }\n        this.entries = {};\n        this.fontFaceManager.destroy();\n    }\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from './properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type LightProps = {\n    \"anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n    \"position\": DataConstantProperty<[number, number, number]>,\n    \"color\": DataConstantProperty<Color>,\n    \"intensity\": DataConstantProperty<number>,\n};\n\nexport type LightPropsPossiblyEvaluated = {\n    \"anchor\": \"map\" | \"viewport\",\n    \"position\": [number, number, number],\n    \"color\": Color,\n    \"intensity\": number,\n};\n\nlet properties: Properties<LightProps>;\nexport const getProperties = (): Properties<LightProps> => properties = properties || new Properties({\n    \"anchor\": new DataConstantProperty(styleSpec[\"light\"][\"anchor\"] as any as StylePropertySpecification, \"anchor\"),\n    \"position\": new DataConstantProperty(styleSpec[\"light\"][\"position\"] as any as StylePropertySpecification, \"position\"),\n    \"color\": new DataConstantProperty(styleSpec[\"light\"][\"color\"] as any as StylePropertySpecification, \"color\"),\n    \"intensity\": new DataConstantProperty(styleSpec[\"light\"][\"intensity\"] as any as StylePropertySpecification, \"intensity\"),\n});", "import {Evented} from '../util/evented.ts';\nimport {validateStyle, validateAndEmit, type Validator} from './validate_style.ts';\nimport {getProperties, type LightProps, type LightPropsPossiblyEvaluated} from './light_properties.g.ts';\nimport {Transitionable, type Transitioning, type PossiblyEvaluated} from './properties.ts';\nimport {EvaluationParameters} from './evaluation_parameters.ts';\n\nimport type {LightSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {StyleSetterOptions} from '../style/style.ts';\nimport type {TransitionParameters} from './properties.ts';\n\n/*\n * Represents the light used to light extruded features.\n */\nexport class Light extends Evented {\n    _transitionable: Transitionable<LightProps>;\n    _transitioning: Transitioning<LightProps>;\n    properties: PossiblyEvaluated<LightProps, LightPropsPossiblyEvaluated>;\n\n    constructor(lightOptions: LightSpecification, globalState: Record<string, any>) {\n        super();\n        this._transitionable = new Transitionable(getProperties(), 'light', globalState);\n        this.setLight(lightOptions);\n        this._transitioning = this._transitionable.untransitioned();\n        this.recalculate(new EvaluationParameters(0));\n    }\n\n    getLight(): LightSpecification {\n        return this._transitionable.serialize();\n    }\n\n    /** The light's values for drawing, as evaluated last. */\n    getEvaluated(): LightPropsPossiblyEvaluated {\n        return {\n            anchor: this.properties.get('anchor'),\n            position: this.properties.get('position'),\n            color: this.properties.get('color'),\n            intensity: this.properties.get('intensity'),\n        };\n    }\n\n    setLight(light: LightSpecification, options: StyleSetterOptions = {}): void {\n        if (this._validate(validateStyle.light, light, options)) {\n            return;\n        }\n\n        this._transitionable.setValues(light);\n    }\n\n    updateTransitions(parameters: TransitionParameters): void {\n        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);\n    }\n\n    hasTransition(): boolean {\n        return this._transitioning.hasTransition();\n    }\n\n    applyGlobalStateChange(refs: string[], priorGlobalState: Record<string, any>, parameters: TransitionParameters): void {\n        this._transitioning = this._transitionable.applyGlobalStateChange(refs, priorGlobalState, this._transitioning, parameters);\n    }\n\n    recalculate(parameters: EvaluationParameters): void {\n        this.properties = this._transitioning.possiblyEvaluate(parameters);\n    }\n\n    _validate(validate: Validator, value: unknown, options?: StyleSetterOptions): boolean {\n        return validateAndEmit(this, validate, {value}, options);\n    }\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from './properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type SkyProps = {\n    \"sky-color\": DataConstantProperty<Color>,\n    \"horizon-color\": DataConstantProperty<Color>,\n    \"fog-color\": DataConstantProperty<Color>,\n    \"fog-ground-blend\": DataConstantProperty<number>,\n    \"horizon-fog-blend\": DataConstantProperty<number>,\n    \"sky-horizon-blend\": DataConstantProperty<number>,\n    \"atmosphere-blend\": DataConstantProperty<number>,\n};\n\nexport type SkyPropsPossiblyEvaluated = {\n    \"sky-color\": Color,\n    \"horizon-color\": Color,\n    \"fog-color\": Color,\n    \"fog-ground-blend\": number,\n    \"horizon-fog-blend\": number,\n    \"sky-horizon-blend\": number,\n    \"atmosphere-blend\": number,\n};\n\nlet properties: Properties<SkyProps>;\nexport const getProperties = (): Properties<SkyProps> => properties = properties || new Properties({\n    \"sky-color\": new DataConstantProperty(styleSpec[\"sky\"][\"sky-color\"] as any as StylePropertySpecification, \"sky-color\"),\n    \"horizon-color\": new DataConstantProperty(styleSpec[\"sky\"][\"horizon-color\"] as any as StylePropertySpecification, \"horizon-color\"),\n    \"fog-color\": new DataConstantProperty(styleSpec[\"sky\"][\"fog-color\"] as any as StylePropertySpecification, \"fog-color\"),\n    \"fog-ground-blend\": new DataConstantProperty(styleSpec[\"sky\"][\"fog-ground-blend\"] as any as StylePropertySpecification, \"fog-ground-blend\"),\n    \"horizon-fog-blend\": new DataConstantProperty(styleSpec[\"sky\"][\"horizon-fog-blend\"] as any as StylePropertySpecification, \"horizon-fog-blend\"),\n    \"sky-horizon-blend\": new DataConstantProperty(styleSpec[\"sky\"][\"sky-horizon-blend\"] as any as StylePropertySpecification, \"sky-horizon-blend\"),\n    \"atmosphere-blend\": new DataConstantProperty(styleSpec[\"sky\"][\"atmosphere-blend\"] as any as StylePropertySpecification, \"atmosphere-blend\"),\n});", "import {type PossiblyEvaluated, Transitionable, type Transitioning, type TransitionParameters} from './properties.ts';\nimport {Evented} from '../util/evented.ts';\nimport {EvaluationParameters} from './evaluation_parameters.ts';\nimport {validateStyle, validateAndEmit, type Validator} from './validate_style.ts';\nimport {getProperties, type SkyProps, type SkyPropsPossiblyEvaluated} from './sky_properties.g.ts';\n\nimport type {SkySpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {StyleSetterOptions} from './style.ts';\n\nexport class Sky extends Evented {\n    properties: PossiblyEvaluated<SkyProps, SkyPropsPossiblyEvaluated>;\n    _transitionable: Transitionable<SkyProps>;\n    _transitioning: Transitioning<SkyProps>;\n\n    constructor(sky: SkySpecification | undefined, globalState: Record<string, any>) {\n        super();\n        this._transitionable = new Transitionable(getProperties(), 'sky', globalState);\n        this.setSky(sky);\n        this._transitioning = this._transitionable.untransitioned();\n        this.recalculate(new EvaluationParameters(0));\n    }\n\n    /**\n     * Validates and applies the sky. Returns false, after firing `error`, when\n     * the value was rejected and nothing changed.\n     */\n    setSky(sky?: SkySpecification, options: StyleSetterOptions = {}): boolean {\n        if (this._validate(validateStyle.sky, sky, options)) return false;\n\n        sky ||= {\n            'sky-color': 'transparent',\n            'horizon-color': 'transparent',\n            'fog-color': 'transparent',\n            'fog-ground-blend': 1,\n            'atmosphere-blend': 0,\n        };\n\n        this._transitionable.setValues(sky);\n        return true;\n    }\n\n    getSky(): SkySpecification {\n        return this._transitionable.serialize();\n    }\n\n    updateTransitions(parameters: TransitionParameters): void {\n        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);\n    }\n\n    hasTransition(): boolean {\n        return this._transitioning.hasTransition();\n    }\n\n    applyGlobalStateChange(refs: string[], priorGlobalState: Record<string, any>, parameters: TransitionParameters): void {\n        this._transitioning = this._transitionable.applyGlobalStateChange(refs, priorGlobalState, this._transitioning, parameters);\n    }\n\n    recalculate(parameters: EvaluationParameters): void {\n        this.properties = this._transitioning.possiblyEvaluate(parameters);\n    }\n\n    _validate(validate: Validator, value: unknown, options: StyleSetterOptions = {}): boolean {\n        return validateAndEmit(this, validate, {value}, options);\n    }\n\n    /** The sky's values for drawing, as evaluated last. */\n    getEvaluated(): SkyPropsPossiblyEvaluated {\n        return {\n            'sky-color': this.properties.get('sky-color'),\n            'horizon-color': this.properties.get('horizon-color'),\n            'fog-color': this.properties.get('fog-color'),\n            'fog-ground-blend': this.properties.get('fog-ground-blend'),\n            'horizon-fog-blend': this.properties.get('horizon-fog-blend'),\n            'sky-horizon-blend': this.properties.get('sky-horizon-blend'),\n            'atmosphere-blend': this.properties.get('atmosphere-blend'),\n        };\n    }\n}\n\n/**\n * Currently fog is a very simple implementation, and should only used\n * to create an atmosphere near the horizon.\n * But because the fog is drawn from the far-clipping-plane to\n * map-center, and because the fog does nothing know about the horizon,\n * this function does a fadeout in respect of pitch. So, when the horizon\n * gets out of view, which is at about pitch 70, this methods calculates\n * the corresponding opacity values. Below pitch 60 the fog is completely\n * invisible.\n */\nexport function calculateFogBlendOpacity(pitch: number): number {\n    if (pitch < 60) return 0; // disable\n    if (pitch < 70) return (pitch - 60) / 10; // fade in\n    return 1;\n}\n", "import {warnOnce} from '../util/util.ts';\n\nimport type {Context} from '../webgl/context.ts';\n\ntype DashRange = {left: number; right: number; isDash: boolean; zeroLength: boolean};\n\n/**\n * A dash entry\n */\nexport type DashEntry = {\n    y: number;\n    height: number;\n    width: number;\n};\n\n/**\n * @internal\n * A LineAtlas lets us reuse rendered dashed lines\n * by writing many of them to a texture and then fetching their positions\n * using {@link LineAtlas.getDash}.\n *\n * @param width - the width\n * @param height - the height\n */\nexport class LineAtlas {\n    width: number;\n    height: number;\n    nextRow: number;\n    bytes: number;\n    data: Uint8Array;\n    dashEntry: {[_: string]: DashEntry};\n    dirty: boolean;\n    texture: WebGLTexture;\n\n    constructor(width: number, height: number) {\n        this.width = width;\n        this.height = height;\n        this.nextRow = 0;\n\n        this.data = new Uint8Array(this.width * this.height);\n\n        this.dashEntry = {};\n    }\n\n    /**\n     * Get or create a dash line pattern.\n     *\n     * @param dasharray - the key (represented by numbers) to get the dash texture\n     * @param round - whether to add circle caps in between dash segments\n     * @returns position of dash texture in {@link DashEntry}\n     */\n    getDash(dasharray: number[], round: boolean): DashEntry {\n        const key = dasharray.join(',') + String(round);\n\n        this.dashEntry[key] ||= this.addDash(dasharray, round);\n        return this.dashEntry[key];\n    }\n\n    getDashRanges(dasharray: number[], lineAtlasWidth: number, stretch: number): DashRange[] {\n        // If dasharray has an odd length, both the first and last parts\n        // are dashes and should be joined seamlessly.\n        const oddDashArray = dasharray.length % 2 === 1;\n\n        const ranges = [];\n\n        let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0;\n        let right = dasharray[0] * stretch;\n        let isDash = true;\n\n        ranges.push({left, right, isDash, zeroLength: dasharray[0] === 0});\n\n        let currentDashLength = dasharray[0];\n        for (let i = 1; i < dasharray.length; i++) {\n            isDash = !isDash;\n\n            const dashLength = dasharray[i];\n            left = currentDashLength * stretch;\n            currentDashLength += dashLength;\n            right = currentDashLength * stretch;\n\n            ranges.push({left, right, isDash, zeroLength: dashLength === 0});\n        }\n\n        return ranges;\n    }\n\n    addRoundDash(ranges: DashRange[], stretch: number, n: number): void {\n        const halfStretch = stretch / 2;\n\n        for (let y = -n; y <= n; y++) {\n            const row = this.nextRow + n + y;\n            const index = this.width * row;\n            let currIndex = 0;\n            let range = ranges[currIndex];\n\n            for (let x = 0; x < this.width; x++) {\n                if (x / range.right > 1) { range = ranges[++currIndex]; }\n\n                const distLeft = Math.abs(x - range.left);\n                const distRight = Math.abs(x - range.right);\n                const minDist = Math.min(distLeft, distRight);\n                let signedDistance;\n\n                const distMiddle =  y / n * (halfStretch + 1);\n                if (range.isDash) {\n                    const distEdge = halfStretch - Math.abs(distMiddle);\n                    signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge);\n                } else {\n                    signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle);\n                }\n\n                this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n            }\n        }\n    }\n\n    addRegularDash(ranges: DashRange[]): void {\n\n        // Collapse any zero-length range\n        // Collapse neighbouring same-type parts into a single part\n        for (let i = ranges.length - 1; i >= 0; --i) {\n            const part = ranges[i];\n            const next = ranges[i + 1];\n            if (part.zeroLength) {\n                ranges.splice(i, 1);\n            } else if (next?.isDash === part.isDash) {\n                next.left = part.left;\n                ranges.splice(i, 1);\n            }\n        }\n\n        // Combine the first and last parts if possible\n        const first = ranges[0];\n        const last = ranges[ranges.length - 1];\n        if (first.isDash === last.isDash) {\n            first.left = last.left - this.width;\n            last.right = first.right + this.width;\n        }\n\n        const index = this.width * this.nextRow;\n        let currIndex = 0;\n        let range = ranges[currIndex];\n\n        for (let x = 0; x < this.width; x++) {\n            if (x / range.right > 1) {\n                range = ranges[++currIndex];\n            }\n\n            const distLeft = Math.abs(x - range.left);\n            const distRight = Math.abs(x - range.right);\n\n            const minDist = Math.min(distLeft, distRight);\n            const signedDistance = range.isDash ? minDist : -minDist;\n\n            this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n        }\n    }\n\n    addDash(dasharray: number[], round: boolean): DashEntry {\n        const n = round ? 7 : 0;\n        const height = 2 * n + 1;\n\n        if (this.nextRow + height > this.height) {\n            warnOnce('LineAtlas out of space');\n            return null;\n        }\n\n        let length = 0;\n        for (const dash of dasharray) { length += dash; }\n\n        if (length !== 0) {\n            const stretch = this.width / length;\n            const ranges = this.getDashRanges(dasharray, this.width, stretch);\n\n            if (round) {\n                this.addRoundDash(ranges, stretch, n);\n            } else {\n                this.addRegularDash(ranges);\n            }\n        }\n\n        const dashEntry = {\n            y: this.nextRow + n,\n            height: 2 * n,\n            width: length\n        };\n\n        this.nextRow += height;\n        this.dirty = true;\n\n        return dashEntry;\n    }\n\n    bind(context: Context): void {\n        const gl = context.gl;\n        if (!this.texture) {\n            this.texture = gl.createTexture();\n            gl.bindTexture(gl.TEXTURE_2D, this.texture);\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n            gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);\n\n        } else {\n            gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n            if (this.dirty) {\n                this.dirty = false;\n                gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);\n            }\n        }\n    }\n}\n", "import {type Actor, createActors, type MessageHandler} from './actor.ts';\nimport {Evented, type ErrorEventType} from './evented.ts';\n\nimport type {Subscription} from './util.ts';\nimport type {WorkerPool} from './worker_pool.ts';\nimport type {MessageType, RequestResponseMessageMap} from './actor_messages.ts';\n\n/**\n * Responsible for sending messages from a {@link Source} to an associated worker source (usually with the same name).\n */\nexport class Dispatcher extends Evented<ErrorEventType> {\n    workerPool: WorkerPool;\n    actors: Actor[];\n    private actorsPromise: Promise<Actor[]>;\n    currentActor: number;\n    id: string | number;\n    private removed: boolean;\n    private workerErrorSubscriptions: Subscription[];\n\n    constructor(workerPool: WorkerPool, mapId: string | number) {\n        super();\n        this.workerPool = workerPool;\n        this.actors = [];\n        this.currentActor = 0;\n        this.id = mapId;\n        this.removed = false;\n        this.workerErrorSubscriptions = [];\n        this.actorsPromise = this.initActors(mapId);\n    }\n\n    private async initActors(mapId: string | number): Promise<Actor[]> {\n        const workers = await this.workerPool.acquire(mapId);\n        if (this.removed) return [];\n        const {actors, workerErrorSubscriptions} = createActors(workers, mapId, this);\n        this.actors = actors;\n        this.workerErrorSubscriptions = workerErrorSubscriptions;\n        if (!this.actors.length) throw new Error('No actors found');\n        return this.actors;\n    }\n\n    /**\n     * Broadcast a message to all Workers.\n     */\n    async broadcast<T extends MessageType>(type: T, data: RequestResponseMessageMap[T][0]): Promise<Array<RequestResponseMessageMap[T][1]>> {\n        const actors = await this.actorsPromise;\n        return Promise.all(actors.map(actor => actor.sendAsync({type, data})));\n    }\n\n    /**\n     * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion.\n     * @returns An actor object backed by a web worker for processing messages.\n     */\n    async getActor(): Promise<Actor> {\n        const actors = await this.actorsPromise;\n        this.currentActor = (this.currentActor + 1) % actors.length;\n        return actors[this.currentActor];\n    }\n\n    async waitForInitComplete(): Promise<void> {\n        if (this.actors.length === 0) {\n            await this.actorsPromise;\n        }\n    }\n\n    getReadyActor(): Actor {\n        this.currentActor = (this.currentActor + 1) % this.actors.length;\n        return this.actors[this.currentActor];\n    }\n\n    remove(mapRemoved: boolean = true): void {\n        this.removed = true;\n        for (const actor of this.actors) {\n            actor.remove();\n        }\n        for (const subscription of this.workerErrorSubscriptions) {\n            subscription.unsubscribe();\n        }\n        this.actors = [];\n        this.workerErrorSubscriptions = [];\n        this.setEventedParent(null);\n        if (mapRemoved) this.workerPool.release(this.id);\n    }\n\n    public async registerMessageHandler<T extends MessageType>(type: T, handler: MessageHandler<T>): Promise<void> {\n        const actors = await this.actorsPromise;\n        for (const actor of actors) {\n            actor.registerMessageHandler(type, handler);\n        }\n    }\n\n    public async unregisterMessageHandler<T extends MessageType>(type: T): Promise<void> {\n        const actors = await this.actorsPromise;\n        for (const actor of actors) {\n            actor.unregisterMessageHandler(type);\n        }\n    }\n}\n", "import {mat4} from 'gl-matrix';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {TileManager} from '../tile/tile_manager.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {CollisionIndex} from '../symbol/collision_index.ts';\nimport type {IReadonlyTransform, WorldCoordinateHelper} from '../geo/transform_interface.ts';\nimport type {RetainedQueryData} from '../symbol/placement.ts';\nimport type {FilterSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {GeoJSONFeature, MapGeoJSONFeature} from '../util/vectortile_to_geojson.ts';\nimport type {QueryResults, QueryResultsItem} from '../data/feature_index.ts';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\n\ntype RenderedFeatureLayer = {\n    wrappedTileID: string;\n    queryResults: QueryResults;\n};\n\n/**\n * Options to pass to query the map for the rendered features\n */\nexport type QueryRenderedFeaturesOptions = {\n    /**\n     * An array or set of [style layer IDs](https://maplibre.org/maplibre-style-spec/#layer-id) for the query to inspect.\n     * Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.\n     */\n    layers?: string[] | Set<string>;\n    /**\n     * A [filter](https://maplibre.org/maplibre-style-spec/layers/#filter) to limit query results.\n     */\n    filter?: FilterSpecification;\n    /**\n     * An array of string representing the available images\n     */\n    availableImages?: string[];\n    /**\n     * Whether to check if the `options.filter` conforms to the MapLibre 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.\n     */\n    validate?: boolean;\n};\n\n/**\n * @internal\n * A version of QueryRenderedFeaturesOptions used internally\n */\nexport type QueryRenderedFeaturesOptionsStrict = Omit<QueryRenderedFeaturesOptions, 'layers'> & {\n    layers: Set<string> | null;\n    globalState?: Record<string, any>;\n};\n\n/**\n * The options object related to the {@link Map.querySourceFeatures} method\n */\nexport type QuerySourceFeatureOptions = {\n    /**\n     * The name of the source layer to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored.\n     */\n    sourceLayer?: string;\n    /**\n     * A [filter](https://maplibre.org/maplibre-style-spec/layers/#filter)\n     * to limit query results.\n     */\n    filter?: FilterSpecification;\n    /**\n     * Whether to check if the `parameters.filter` conforms to the MapLibre 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.\n     * @defaultValue true\n     */\n    validate?: boolean;\n};\n\n/**\n * @internal\n * A version of QuerySourceFeatureOptions used internally\n */\nexport type QuerySourceFeatureOptionsStrict = QuerySourceFeatureOptions & {\n    globalState?: Record<string, any>;\n    /**\n     * The map projection's world-to-lng/lat mapping for the returned geometry.\n     */\n    worldCoordinateHelper: WorldCoordinateHelper;\n};\n\nexport type QueryRenderedFeaturesResults = {\n    [key: string]: QueryRenderedFeaturesResultsItem[];\n};\n\nexport type QueryRenderedFeaturesResultsItem = QueryResultsItem & { feature: MapGeoJSONFeature };\n\n/*\n * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates.\n * While the globe renders as a sphere there is no such matrix, so extrusions are hit-tested by their footprint only.\n */\nfunction getPixelPosMatrix(transform: IReadonlyTransform, tileID: OverscaledTileID): mat4 {\n    const t = mat4.create();\n    mat4.translate(t, t, [1, 1, 0]);\n    mat4.scale(t, t, [transform.width * 0.5, transform.height * 0.5, 1]);\n    const posMatrix = transform.getFastPathSimpleProjectionMatrix(tileID);\n    return posMatrix ? mat4.multiply(t, t, posMatrix) : t;\n}\n\nfunction queryIncludes3DLayer(layers: Set<string> | undefined, styleLayers: {[_: string]: StyleLayer}, sourceID: string) {\n    if (layers) {\n        for (const layerID of layers) {\n            const layer = styleLayers[layerID];\n            if (layer?.source === sourceID && layer.type === 'fill-extrusion') {\n                return true;\n            }\n        }\n    } else {\n        for (const key in styleLayers) {\n            const layer = styleLayers[key];\n            if (layer.source === sourceID && layer.type === 'fill-extrusion') {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nexport function queryRenderedFeatures(\n    tileManager: TileManager,\n    styleLayers: {[_: string]: StyleLayer},\n    serializedLayers: {[_: string]: any},\n    queryGeometry: Point[],\n    params: QueryRenderedFeaturesOptionsStrict | undefined,\n    transform: IReadonlyTransform,\n    getElevation: undefined | ((id: OverscaledTileID, x: number, y: number) => number)\n): QueryRenderedFeaturesResults {\n\n    const has3DLayer = queryIncludes3DLayer(params?.layers ?? null, styleLayers, tileManager.id);\n    const maxPitchScaleFactor = transform.maxPitchScaleFactor();\n    const tilesIn = tileManager.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer);\n\n    tilesIn.sort(sortTilesIn);\n    const renderedFeatureLayers: RenderedFeatureLayer[] = [];\n    for (const tileIn of tilesIn) {\n        renderedFeatureLayers.push({\n            wrappedTileID: tileIn.tileID.wrapped().key,\n            queryResults: tileIn.tile.queryRenderedFeatures(\n                styleLayers,\n                serializedLayers,\n                tileManager.getState(),\n                tileIn.queryGeometry,\n                tileIn.cameraQueryGeometry,\n                tileIn.scale,\n                params,\n                transform,\n                maxPitchScaleFactor,\n                getPixelPosMatrix(transform, tileIn.tileID),\n                getElevation ? (x: number, y: number) => getElevation(tileIn.tileID, x, y) : undefined,\n            )\n        });\n    }\n\n    const result = mergeRenderedFeatureLayers(renderedFeatureLayers);\n\n    return convertFeaturesToMapFeatures(result, tileManager);\n}\n\nexport function queryRenderedSymbols(styleLayers: {[_: string]: StyleLayer},\n    serializedLayers: {[_: string]: StyleLayer},\n    tileManagers: {[_: string]: TileManager},\n    queryGeometry: Point[],\n    params: QueryRenderedFeaturesOptionsStrict,\n    collisionIndex: CollisionIndex,\n    retainedQueryData: {\n        [_: number]: RetainedQueryData;\n    }): QueryRenderedFeaturesResults {\n    const result: QueryResults = {};\n    const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry);\n    const bucketQueryData: RetainedQueryData[] = [];\n    for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) {\n        bucketQueryData.push(retainedQueryData[bucketInstanceId]);\n    }\n    bucketQueryData.sort(sortTilesIn);\n\n    for (const queryData of bucketQueryData) {\n        const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(\n            renderedSymbols[queryData.bucketInstanceId],\n            serializedLayers,\n            queryData.bucketIndex,\n            queryData.sourceLayerIndex,\n            {\n                filterSpec: params.filter,\n                globalState: params.globalState,\n                worldCoordinateHelper: collisionIndex.transform.worldCoordinateHelper\n            },\n            params.layers,\n            params.availableImages,\n            styleLayers);\n\n        for (const layerID in bucketSymbols) {\n            result[layerID] ||= [];\n            const layerSymbols = bucketSymbols[layerID];\n            layerSymbols.sort((a, b) => {\n                // Match topDownFeatureComparator from FeatureIndex, but using\n                // most recent sorting of features from bucket.sortFeatures\n                const featureSortOrder = queryData.featureSortOrder;\n                if (featureSortOrder) {\n                    // queryRenderedSymbols documentation says we'll return features in\n                    // \"top-to-bottom\" rendering order (aka last-to-first).\n                    // Actually, there can be multiple symbol instances per feature, so\n                    // we sort each feature based on the first matching symbol instance.\n                    const sortedA = featureSortOrder.indexOf(a.featureIndex);\n                    const sortedB = featureSortOrder.indexOf(b.featureIndex);\n                    return sortedB - sortedA;\n                } else {\n                    // Bucket hasn't been re-sorted based on angle, so use the\n                    // reverse of the order the features appeared in the data.\n                    return b.featureIndex - a.featureIndex;\n                }\n            });\n            for (const symbolFeature of layerSymbols) {\n                result[layerID].push(symbolFeature);\n            }\n        }\n    }\n\n    return convertFeaturesToMapFeaturesMultiple(result, styleLayers, tileManagers);\n}\n\nexport function querySourceFeatures(tileManager: TileManager, params: QuerySourceFeatureOptionsStrict): GeoJSONFeature[] {\n    const tiles = tileManager.getRenderableIds().map((id) => {\n        return tileManager.getTileByID(id);\n    });\n\n    const result: GeoJSONFeature[] = [];\n\n    const dataTiles = {};\n    for (const tile of tiles) {\n        const dataID = tile.tileID.canonical.key;\n        if (!dataTiles[dataID]) {\n            dataTiles[dataID] = true;\n            tile.querySourceFeatures(result, params);\n        }\n    }\n\n    return result;\n}\n\nfunction sortTilesIn(a: {tileID: OverscaledTileID}, b: {tileID: OverscaledTileID}) {\n    const idA = a.tileID;\n    const idB = b.tileID;\n    return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x);\n}\n\nfunction mergeRenderedFeatureLayers(tiles: RenderedFeatureLayer[]): QueryResults {\n    // Merge results from all tiles, but if two tiles share the same\n    // wrapped ID, don't duplicate features between the two tiles\n    const result: QueryResults = {};\n    const wrappedIDLayerMap = {};\n    for (const {queryResults, wrappedTileID} of tiles) {\n        wrappedIDLayerMap[wrappedTileID] ||= {};\n        const wrappedIDLayers = wrappedIDLayerMap[wrappedTileID];\n        for (const layerID in queryResults) {\n            const tileFeatures = queryResults[layerID];\n            wrappedIDLayers[layerID] ||= {};\n            const wrappedIDFeatures = wrappedIDLayers[layerID];\n            result[layerID] ||= [];\n            for (const tileFeature of tileFeatures) {\n                if (!wrappedIDFeatures[tileFeature.featureIndex]) {\n                    wrappedIDFeatures[tileFeature.featureIndex] = true;\n                    result[layerID].push(tileFeature);\n                }\n            }\n        }\n    }\n    return result;\n}\n\nfunction convertFeaturesToMapFeatures(result: QueryResults, tileManager: TileManager): QueryRenderedFeaturesResults {\n    // Merge state from TileManager into the results\n    for (const layerID in result) {\n        for (const featureWrapper of result[layerID]) {\n            convertFeatureToMapFeature(featureWrapper, tileManager);\n        }\n    }\n    return result as QueryRenderedFeaturesResults;\n}\n\nfunction convertFeaturesToMapFeaturesMultiple(result: QueryResults, styleLayers: {[_: string]: StyleLayer}, tileManagers: {[_: string]: TileManager}): QueryRenderedFeaturesResults {\n    // Merge state from TileManager into the results\n    for (const layerName in result) {\n        for (const featureWrapper of result[layerName]) {\n            const layer = styleLayers[layerName];\n            const tileManager = tileManagers[layer.source];\n            convertFeatureToMapFeature(featureWrapper, tileManager);\n        };\n    }\n    return result as QueryRenderedFeaturesResults;\n}\n\nfunction convertFeatureToMapFeature(featureWrapper: QueryResultsItem, tileManager: TileManager) {\n    const feature = featureWrapper.feature as MapGeoJSONFeature;\n    const state = tileManager.getFeatureState(feature.layer['source-layer'], feature.id);\n    feature.source = feature.layer.source;\n    if (feature.layer['source-layer']) {\n        feature.sourceLayer = feature.layer['source-layer'];\n    }\n    feature.state = state;\n}\n", "import {pick, extend, type TileJSON} from '../util/util.ts';\nimport {getJSON} from '../util/ajax.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {browser} from '../util/browser.ts';\n\nimport type {RequestManager} from '../util/request_manager.ts';\nimport type {RasterDEMSourceSpecification, RasterSourceSpecification, VectorSourceSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type LoadTileJsonResponse = {\n    tiles: string[];\n    minzoom: number;\n    maxzoom: number;\n    attribution: string;\n    bounds: RasterSourceSpecification['bounds'];\n    scheme: RasterSourceSpecification['scheme'];\n    tileSize: number;\n    encoding: RasterDEMSourceSpecification['encoding'];\n    sparse?: boolean;\n    vectorLayerIds?: string[];\n};\n\nexport async function loadTileJson(\n    options: RasterSourceSpecification | RasterDEMSourceSpecification | VectorSourceSpecification,\n    requestManager: RequestManager,\n    abortController: AbortController,\n    targetWindow?: Window,\n): Promise<LoadTileJsonResponse | null> {\n    let tileJSON: TileJSON | typeof options = options;\n    if (options.url) {\n        const response = await getJSON<TileJSON>(await requestManager.transformRequest(options.url, ResourceType.Source), abortController);\n        tileJSON = response.data;\n    } else {\n        await browser.frameAsync(abortController, targetWindow);\n    }\n    if (!tileJSON) {\n        return null;\n    }\n    const result = pick(\n        // explicit source options take precedence over TileJSON\n        extend(tileJSON, options),\n        ['tiles', 'minzoom', 'maxzoom', 'attribution', 'bounds', 'scheme', 'tileSize', 'encoding', 'sparse']\n    ) as LoadTileJsonResponse;\n\n    if ('vector_layers' in tileJSON && tileJSON.vector_layers) {\n        result.vectorLayerIds = tileJSON.vector_layers.map((layer) => layer.id);\n    }\n\n    return result;\n}\n", "import {LngLat} from './lng_lat.ts';\nimport {wrap} from '../util/util.ts';\n\nimport type {LngLatLike} from './lng_lat.ts';\n\n/**\n * A {@link LngLatBounds} object, an array of {@link LngLatLike} objects in `[sw, ne]` order,\n * or an array of numbers in `[west, south, east, north]` order.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let v1 = new LngLatBounds(\n *   new LngLat(-73.9876, 40.7661),\n *   new LngLat(-73.9397, 40.8002)\n * );\n * let v2 = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])\n * let v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n * ```\n */\nexport type LngLatBoundsLike = LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number];\n\n/**\n * A `LngLatBounds` object represents a geographical bounding box,\n * defined by its southwest and northeast points in longitude and latitude.\n *\n * If no arguments are provided to the constructor, a `null` bounding box is created.\n *\n * Note that any MapLibre GL method that accepts a `LngLatBounds` object as an argument or option\n * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion.\n * This flexible type is documented as {@link LngLatBoundsLike}.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let sw = new LngLat(-73.9876, 40.7661);\n * let ne = new LngLat(-73.9397, 40.8002);\n * let llb = new LngLatBounds(sw, ne);\n * ```\n * @see [Fit to the bounds of a LineString](https://maplibre.org/maplibre-gl-js/docs/examples/fit-to-the-bounds-of-a-linestring/)\n */\nexport class LngLatBounds {\n    _ne: LngLat;\n    _sw: LngLat;\n\n    /**\n     * @param sw - The southwest corner of the bounding box.\n     * OR array of 4 numbers in the order of  west, south, east, north\n     * OR array of 2 LngLatLike: `[sw, ne]`\n     * @param ne - The northeast corner of the bounding box.\n     * @example\n     * ```ts\n     * let sw = new LngLat(-73.9876, 40.7661);\n     * let ne = new LngLat(-73.9397, 40.8002);\n     * let llb = new LngLatBounds(sw, ne);\n     * ```\n     * OR\n     * ```ts\n     * let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]);\n     * ```\n     * OR\n     * ```ts\n     * let llb = new LngLatBounds([sw, ne]);\n     * ```\n     */\n    constructor(sw?: LngLatLike | [number, number, number, number] | [LngLatLike, LngLatLike], ne?: LngLatLike) {\n        if (!sw) {\n            // noop\n        } else if (ne) {\n            this.setSouthWest(<LngLatLike>sw).setNorthEast(ne);\n        } else if (Array.isArray(sw)) {\n            if (sw.length === 4) {\n            // 4 element array: west, south, east, north\n                this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]);\n            } else {\n                this.setSouthWest(sw[0] as LngLatLike).setNorthEast(sw[1] as LngLatLike);\n            }\n        }\n    }\n\n    /**\n     * Set the northeast corner of the bounding box\n     *\n     * @param ne - a {@link LngLatLike} object describing the northeast corner of the bounding box.\n     */\n    setNorthEast(ne: LngLatLike): this {\n        this._ne = ne instanceof LngLat ? new LngLat(ne.lng, ne.lat) : LngLat.convert(ne);\n        return this;\n    }\n\n    /**\n     * Set the southwest corner of the bounding box\n     *\n     * @param sw - a {@link LngLatLike} object describing the southwest corner of the bounding box.\n     */\n    setSouthWest(sw: LngLatLike): this {\n        this._sw = sw instanceof LngLat ? new LngLat(sw.lng, sw.lat) : LngLat.convert(sw);\n        return this;\n    }\n\n    /**\n     * Extend the bounds to include a given LngLatLike or LngLatBoundsLike.\n     *\n     * @param obj - object to extend to\n     */\n    extend(obj: LngLatLike | LngLatBoundsLike): this {\n        const sw = this._sw,\n            ne = this._ne;\n        let sw2, ne2;\n\n        if (obj instanceof LngLat) {\n            sw2 = obj;\n            ne2 = obj;\n\n        } else if (obj instanceof LngLatBounds) {\n            sw2 = obj._sw;\n            ne2 = obj._ne;\n\n            if (!sw2 || !ne2) return this;\n\n        } else {\n            if (Array.isArray(obj)) {\n                if (obj.length === 4 || (obj as any[]).every(Array.isArray)) {\n                    const lngLatBoundsObj = (obj as any as LngLatBoundsLike);\n                    return this.extend(LngLatBounds.convert(lngLatBoundsObj));\n                } else {\n                    const lngLatObj = (obj as any as LngLatLike);\n                    return this.extend(LngLat.convert(lngLatObj));\n                }\n\n            } else if (obj && ('lng' in obj || 'lon' in obj) && 'lat' in obj) {\n                return this.extend(LngLat.convert(obj));\n            }\n\n            return this;\n        }\n\n        if (!sw && !ne) {\n            this._sw = new LngLat(sw2.lng, sw2.lat);\n            this._ne = new LngLat(ne2.lng, ne2.lat);\n\n        } else {\n            sw.lng = Math.min(sw2.lng, sw.lng);\n            sw.lat = Math.min(sw2.lat, sw.lat);\n            ne.lng = Math.max(ne2.lng, ne.lng);\n            ne.lat = Math.max(ne2.lat, ne.lat);\n        }\n\n        return this;\n    }\n\n    /**\n     * Returns the geographical coordinate equidistant from the bounding box's corners.\n     *\n     * @returns The bounding box's center.\n     * @example\n     * ```ts\n     * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n     * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}\n     * ```\n     */\n    getCenter(): LngLat {\n        return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);\n    }\n\n    /**\n     * Returns the southwest corner of the bounding box.\n     *\n     * @returns The southwest corner of the bounding box.\n     */\n    getSouthWest(): LngLat { return this._sw; }\n\n    /**\n     * Returns the northeast corner of the bounding box.\n     *\n     * @returns The northeast corner of the bounding box.\n     */\n    getNorthEast(): LngLat { return this._ne; }\n\n    /**\n     * Returns the northwest corner of the bounding box.\n     *\n     * @returns The northwest corner of the bounding box.\n     */\n    getNorthWest(): LngLat { return new LngLat(this.getWest(), this.getNorth()); }\n\n    /**\n     * Returns the southeast corner of the bounding box.\n     *\n     * @returns The southeast corner of the bounding box.\n     */\n    getSouthEast(): LngLat { return new LngLat(this.getEast(), this.getSouth()); }\n\n    /**\n     * Returns the west edge of the bounding box.\n     *\n     * @returns The west edge of the bounding box.\n     */\n    getWest(): number { return this._sw.lng; }\n\n    /**\n     * Returns the south edge of the bounding box.\n     *\n     * @returns The south edge of the bounding box.\n     */\n    getSouth(): number { return this._sw.lat; }\n\n    /**\n     * Returns the east edge of the bounding box.\n     *\n     * @returns The east edge of the bounding box.\n     */\n    getEast(): number { return this._ne.lng; }\n\n    /**\n     * Returns the north edge of the bounding box.\n     *\n     * @returns The north edge of the bounding box.\n     */\n    getNorth(): number { return this._ne.lat; }\n\n    /**\n     * Returns the bounding box represented as an array.\n     *\n     * @returns The bounding box represented as an array, consisting of the\n     * southwest and northeast coordinates of the bounding represented as arrays of numbers.\n     * @example\n     * ```ts\n     * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n     * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]\n     * ```\n     */\n    toArray(): [[number, number], [number, number]] {\n        return [this._sw.toArray(), this._ne.toArray()];\n    }\n\n    /**\n     * Return the bounding box represented as a string.\n     *\n     * @returns The bounding box represents as a string of the format\n     * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`.\n     * @example\n     * ```ts\n     * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n     * llb.toString(); // = \"LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))\"\n     * ```\n     */\n    toString() {\n        return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`;\n    }\n\n    /**\n     * Check if the bounding box is an empty/`null`-type box.\n     *\n     * @returns True if bounds have been defined, otherwise false.\n     */\n    isEmpty(): boolean {\n        return !(this._sw && this._ne);\n    }\n\n    /**\n     * Check if the point is within the bounding box.\n     *\n     * @param lnglat - geographic point to check against.\n     * @returns `true` if the point is within the bounding box.\n     * @example\n     * ```ts\n     * let llb = new LngLatBounds(\n     *   new LngLat(-73.9876, 40.7661),\n     *   new LngLat(-73.9397, 40.8002)\n     * );\n     *\n     * let ll = new LngLat(-73.9567, 40.7789);\n     *\n     * console.log(llb.contains(ll)); // = true\n     * ```\n     */\n    contains(lnglat: LngLatLike): boolean {\n        const {lng, lat} = LngLat.convert(lnglat);\n\n        const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat;\n        let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng;\n        if (this._sw.lng > this._ne.lng) { // wrapped coordinates\n            containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng;\n        }\n\n        return containsLatitude && containsLongitude;\n    }\n\n    /**\n     * Checks if this bounding box intersects with another bounding box.\n     *\n     * Returns true if the bounding boxes share any area, including cases where\n     * they only touch along an edge or at a corner.\n     *\n     * This method properly handles cases where either or both bounding boxes cross\n     * the antimeridian (date line).\n     */\n    intersects(other: LngLatBoundsLike): boolean {\n        other = LngLatBounds.convert(other);\n\n        const latIntersects =\n            other.getNorth() >= this.getSouth() &&\n            other.getSouth() <= this.getNorth();\n\n        if (!latIntersects) return false;\n\n        // Check if either bound covers the full world (|span| >= 360°)\n        // This must be done before wrapping to preserve the span information\n        const thisSpan = Math.abs(this.getEast() - this.getWest());\n        const otherSpan = Math.abs(other.getEast() - other.getWest());\n\n        if (thisSpan >= 360 || otherSpan >= 360) {\n            return true;\n        }\n\n        // Normalize longitudes to [-180, 180] range\n        const thisWest = wrap(this.getWest(), -180, 180);\n        const thisEast = wrap(this.getEast(), -180, 180);\n        const otherWest = wrap(other.getWest(), -180, 180);\n        const otherEast = wrap(other.getEast(), -180, 180);\n\n        // Check if either bounds wraps around the antimeridian\n        // Use strict inequality: equal values indicate zero-width bounds (e.g., a point), not wrapping\n        const thisWraps = thisWest > thisEast;\n        const otherWraps = otherWest > otherEast;\n\n        // Both wrap: they always intersect\n        if (thisWraps && otherWraps) {\n            return true;\n        }\n\n        // Only this wraps: intersects if other is outside the gap\n        if (thisWraps) {\n            return otherEast >= thisWest || otherWest <= thisEast;\n        }\n\n        if (otherWraps) {\n            // Only other wraps: intersects if this is outside the gap\n            return thisEast >= otherWest || thisWest <= otherEast;\n        }\n\n        // Neither wraps: standard intersection check\n        return otherWest <= thisEast && otherEast >= thisWest;\n    }\n\n    /**\n     * Converts an array to a `LngLatBounds` object.\n     *\n     * If a `LngLatBounds` object is passed in, the function returns it unchanged.\n     *\n     * Internally, the function calls {@link LngLat.convert} to convert arrays to `LngLat` values.\n     *\n     * @param input - An array of two coordinates to convert, or a `LngLatBounds` object to return.\n     * @returns A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object.\n     * @example\n     * ```ts\n     * let arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n     * let llb = LngLatBounds.convert(arr); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}\n     * ```\n     */\n    static convert(input: LngLatBoundsLike | null): LngLatBounds {\n        if (input instanceof LngLatBounds) return input;\n        if (!input) return input as null;\n        return new LngLatBounds(input);\n    }\n\n    /**\n     * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`.\n     *\n     * @param center - center coordinates of the new bounds.\n     * @param radius - Distance in meters from the coordinates to extend the bounds.\n     * @returns A new `LngLatBounds` object representing the coordinates extended by the `radius`.\n     * @example\n     * ```ts\n     * let center = new LngLat(-73.9749, 40.7736);\n     * LngLatBounds.fromLngLat(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]\n     * ```\n     */\n    static fromLngLat(center: LngLat, radius:number = 0): LngLatBounds {\n        const earthCircumferenceInMetersAtEquator = 40075017;\n        const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator,\n            lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * center.lat);\n\n        return new LngLatBounds(new LngLat(center.lng - lngAccuracy, center.lat - latAccuracy),\n            new LngLat(center.lng + lngAccuracy, center.lat + latAccuracy));\n    }\n\n    /**\n     * Adjusts the given bounds to handle the case where the bounds cross the 180th meridian (antimeridian).\n     *\n     * @returns The adjusted LngLatBounds\n     * @example\n     * ```ts\n     * let bounds = new LngLatBounds([175.813127, -20.157768], [-178. 340903, -15.449124]);\n     * let adjustedBounds = bounds.adjustAntiMeridian();\n     * // adjustedBounds will be: [[175.813127, -20.157768], [181.659097, -15.449124]]\n     * ```\n     */\n    adjustAntiMeridian(): LngLatBounds {\n        const sw = new LngLat(this._sw.lng, this._sw.lat);\n        const ne = new LngLat(this._ne.lng, this._ne.lat);\n\n        if (sw.lng > ne.lng) {\n            return new LngLatBounds(\n                sw,\n                new LngLat(ne.lng + 360, ne.lat)\n            );\n        }\n\n        return new LngLatBounds(sw, ne);\n    }\n\n}\n", "import {LngLatBounds, type LngLatBoundsLike} from '../geo/lng_lat_bounds.ts';\nimport {lngLatBoxToWorldBox} from '../geo/projection/mercator_utils.ts';\n\nimport type {WorldCoordinateHelper} from '../geo/transform_interface.ts';\nimport type {CanonicalTileID} from './tile_id.ts';\n\nexport class TileBounds {\n    bounds: LngLatBounds;\n    minzoom: number;\n    maxzoom: number;\n    /** `bounds` in the world square of the map's projection, projected once since the bounds never change. */\n    private _worldBox: {minX: number; minY: number; maxX: number; maxY: number};\n\n    constructor(bounds: [number, number, number, number], minzoom: number | null | undefined, maxzoom: number | null | undefined, worldCoordinateHelper: WorldCoordinateHelper) {\n        this.bounds = LngLatBounds.convert(this.validateBounds(bounds));\n        this.minzoom = minzoom || 0;\n        this.maxzoom = maxzoom || 24;\n        this._worldBox = lngLatBoxToWorldBox(worldCoordinateHelper, this.bounds.getWest(), this.bounds.getSouth(), this.bounds.getEast(), this.bounds.getNorth());\n    }\n\n    validateBounds(bounds: [number, number, number, number]): LngLatBoundsLike {\n        // make sure the bounds property contains valid longitude and latitudes\n        if (!Array.isArray(bounds) || bounds.length !== 4) return [-180, -90, 180, 90];\n        return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])];\n    }\n\n    contains(tileID: CanonicalTileID): boolean {\n        const worldSize = Math.pow(2, tileID.z);\n        const level = {\n            minX: Math.floor(this._worldBox.minX * worldSize),\n            minY: Math.floor(this._worldBox.minY * worldSize),\n            maxX: Math.ceil(this._worldBox.maxX * worldSize),\n            maxY: Math.ceil(this._worldBox.maxY * worldSize)\n        };\n        return tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;\n    }\n}\n", "import {ErrorEvent, Evented} from '../util/evented.ts';\nimport {MapSourceDataEvent, type SourceEventType} from '../ui/events.ts';\nimport {ensureError, extend, pick} from '../util/util.ts';\nimport {loadTileJson} from './load_tilejson.ts';\nimport {TileBounds} from '../tile/tile_bounds.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {MessageType} from '../util/actor_messages.ts';\nimport {isAbortError} from '../util/abort_error.ts';\nimport {TileManager} from '../tile/tile_manager.ts';\n\nimport type {Source} from './source.ts';\nimport type {CanonicalTileID, OverscaledTileID} from '../tile/tile_id.ts';\nimport type {Map} from '../ui/map.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {VectorSourceSpecification, PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {RequestParameters} from '../util/ajax';\nimport type {WorkerTileParameters, OverzoomParameters, WorkerTileResult, TileEncoding} from './worker_source.ts';\n\nexport type VectorTileSourceOptions = VectorSourceSpecification & {\n    collectResourceTiming?: boolean;\n    tileSize?: number;\n    /**\n     * Whether the tileset leaves tiles out. When `true`, a tile the server answers with a 404 shows the part of the\n     * nearest ancestor that exists, up to 10 zoom levels up and no lower than the source's minzoom, sliced the way an\n     * overzoomed tile is sliced from the source's maxzoom tile. When `false`, a missing tile loads empty. The source's\n     * TileJSON can set it too, with the source option winning.\n     * @defaultValue false\n     * @experimental\n     */\n    sparse?: boolean;\n};\n\nexport type LoadTileResult = {\n    /**\n     * Indicates that the tile requested was not modified.\n     */\n    unmodified?: boolean;\n};\n\n/**\n * A source containing vector tiles in [Maplibre Vector Tile format](https://maplibre.org/maplibre-tile-spec/) or [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/).\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n *     type: 'vector',\n *     url: 'https://demotiles.maplibre.org/tiles/tiles.json'\n * });\n * ```\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n *     type: 'vector',\n *     tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'],\n *     minzoom: 6,\n *     maxzoom: 14\n * });\n * ```\n *\n * @example\n * ```ts\n * map.getSource('some id').setUrl(\"https://demotiles.maplibre.org/tiles/tiles.json\");\n * ```\n *\n * @example\n * ```ts\n * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']);\n * ```\n * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-vector-tile-source/)\n */\nexport class VectorTileSource extends Evented<SourceEventType> implements Source {\n    type: 'vector';\n    id: string;\n    minzoom: number;\n    maxzoom: number;\n    url: string;\n    scheme: string;\n    encoding: TileEncoding;\n    tileSize: number;\n    sparse: boolean;\n    promoteId: PromoteIdSpecification;\n\n    _options: VectorSourceSpecification;\n    _collectResourceTiming: boolean;\n    dispatcher: Dispatcher;\n    map: Map;\n    bounds: [number, number, number, number];\n    tiles: string[];\n    tileBounds: TileBounds;\n    reparseOverscaled: boolean;\n    isTileClipped: boolean;\n    _tileJSONRequest: AbortController;\n    _loaded: boolean;\n\n    constructor(id: string, options: VectorTileSourceOptions, dispatcher: Dispatcher, eventedParent: Evented) {\n        super();\n        this.id = id;\n        this.dispatcher = dispatcher;\n\n        this.type = 'vector';\n        this.minzoom = 0;\n        this.maxzoom = 22;\n        this.scheme = 'xyz';\n        this.tileSize = 512;\n        this.sparse = false;\n        this.reparseOverscaled = true;\n        this.isTileClipped = true;\n        this._loaded = false;\n\n        extend(this, pick(options, ['url', 'scheme', 'tileSize', 'promoteId', 'encoding']));\n        this._options = extend({type: 'vector'}, options);\n\n        this._collectResourceTiming = options.collectResourceTiming;\n\n        if (this.tileSize !== 512) {\n            throw new Error('vector tile sources must have a tileSize of 512');\n        }\n\n        this.setEventedParent(eventedParent);\n    }\n\n    async load(sourceDataChanged: boolean = false): Promise<void> {\n        this._loaded = false;\n        this.fire(new MapSourceDataEvent('dataloading'));\n        this._tileJSONRequest = new AbortController();\n        try {\n            const tileJSON = await loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest, this.map._ownerWindow);\n            this._tileJSONRequest = null;\n            this._loaded = true;\n            if (tileJSON) {\n                extend(this, tileJSON);\n                if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom, this.map.style.projection.worldCoordinateHelper);\n\n                // `content` is included here to prevent a race condition where `Style._updateSources` is called\n                // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives\n                // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088\n                this.fire(new MapSourceDataEvent('data', {sourceDataType: 'metadata'}));\n                this.fire(new MapSourceDataEvent('data', {sourceDataType: 'content', sourceDataChanged}));\n            }\n        } catch (err) {\n            this._tileJSONRequest = null;\n            this._loaded = true; // let's pretend it's loaded so the source will be ignored\n\n            // only fire error event if it is not due to aborting the request\n            if (!isAbortError(err)) {\n                this.fire(new ErrorEvent(ensureError(err)));\n            }\n        }\n    }\n\n    loaded(): boolean {\n        return this._loaded;\n    }\n\n    hasTile(tileID: OverscaledTileID): boolean {\n        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);\n    }\n\n    onAdd(map: Map): void {\n        this.map = map;\n        this.load();\n    }\n\n    setSourceProperty(callback: Function): void {\n        if (this._tileJSONRequest) {\n            this._tileJSONRequest.abort();\n        }\n\n        callback();\n\n        this.load(true);\n    }\n\n    /**\n     * Sets the source `tiles` property and re-renders the map.\n     *\n     * @param tiles - An array of one or more tile source URLs, as in the TileJSON spec.\n     */\n    setTiles(tiles: string[]): this {\n        this.setSourceProperty(() => {\n            this.tiles = tiles;\n            this._options.tiles = tiles;\n        });\n\n        return this;\n    }\n\n    /**\n     * Sets the source `url` property and re-renders the map.\n     *\n     * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`.\n     */\n    setUrl(url: string): this {\n        this.setSourceProperty(() => {\n            this.url = url;\n            this._options.url = url;\n        });\n\n        return this;\n    }\n\n    onRemove(): void {\n        if (this._tileJSONRequest) {\n            this._tileJSONRequest.abort();\n            this._tileJSONRequest = null;\n        }\n    }\n\n    serialize(): VectorSourceSpecification {\n        return extend({}, this._options);\n    }\n\n    async loadTile(tile: Tile): Promise<LoadTileResult | void> {\n        const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme, this.map.style.projection.worldCoordinateHelper.tileMatrixSet);\n        const params: WorkerTileParameters = {\n            request: await this.map._requestManager.transformRequest(url, ResourceType.Tile),\n            uid: tile.uid,\n            tileID: tile.tileID,\n            zoom: tile.tileID.overscaledZ,\n            tileSize: this.tileSize * tile.tileID.overscaleFactor(),\n            type: this.type,\n            source: this.id,\n            pixelRatio: this.map.getPixelRatio(),\n            showCollisionBoxes: this.map.showCollisionBoxes,\n            promoteId: this.promoteId,\n            subdivisionGranularity: this.map.style.projection.subdivisionGranularity,\n            encoding: this.encoding,\n            overzoomParameters: await this._getOverzoomParameters(tile),\n            etag: tile.etag\n        };\n        this._setAcceptHeader(params.request);\n        params.request.collectResourceTiming = this._collectResourceTiming;\n        await this.dispatcher.waitForInitComplete();\n        if (tile.aborted) {\n            return;\n        }\n        let messageType: MessageType.loadTile | MessageType.reloadTile = MessageType.reloadTile;\n        if (!tile.actor || tile.state === 'expired') {\n            tile.actor = this.dispatcher.getReadyActor();\n            messageType = MessageType.loadTile;\n        } else if (tile.state === 'loading') {\n            return new Promise<void>((resolve, reject) => {\n                tile.reloadPromise = {resolve, reject};\n            });\n        }\n        tile.abortController = new AbortController();\n        let data: WorkerTileResult | null;\n        try {\n            data = await tile.actor.sendAsync({type: messageType, data: params}, tile.abortController);\n        } catch (err) {\n            delete tile.abortController;\n\n            if (tile.aborted || isAbortError(err)) {\n                return;\n            }\n            if (err && err.status !== 404) {\n                throw err;\n            }\n            data = null;\n        }\n        delete tile.abortController;\n\n        if (tile.aborted) {\n            return;\n        }\n        const result: LoadTileResult = {};\n        if (data?.resourceTiming) {\n            tile.resourceTiming = data.resourceTiming;\n        }\n        if (data === null && this.sparse) {\n            data = await this._loadFromNearestAncestor(tile, params);\n            if (tile.aborted) {\n                return;\n            }\n        }\n        this._afterTileLoadWorkerResponse(tile, data);\n        if (data?.etagUnmodified) result.unmodified = true;\n        this._reloadIfRequestedWhileLoading(tile);\n        return result;\n    }\n\n    /**\n     * Loads a tile the server answered with a 404 from the nearest ancestor that exists, sliced to the tile the way an\n     * overzoomed tile is sliced from the source's maxzoom tile. The search starts one level above the tile that was fetched\n     * (the maxzoom tile when the tile is overzoomed) and goes up at most `TileManager.maxUnderzooming` levels, as far as\n     * the tile manager looks for a loaded parent to show in place of a missing raster tile, and no further than the\n     * source's minzoom. Returns null when every ancestor in reach answered with a 404 too: the tile then loads empty and\n     * draws nothing, as it does after a 404 when the source is not sparse.\n     */\n    private async _loadFromNearestAncestor(tile: Tile, params: WorkerTileParameters): Promise<WorkerTileResult | null> {\n        const fetchedZ = Math.min(tile.tileID.canonical.z, this.maxzoom);\n        const lowestZ = Math.max(fetchedZ - TileManager.maxUnderzooming, this.minzoom);\n        for (let z = fetchedZ - 1; z >= lowestZ; z--) {\n            const ancestorID = tile.tileID.scaledTo(z).canonical;\n            params.overzoomParameters = {\n                maxZoomTileID: ancestorID,\n                overzoomRequest: await this._getTileRequest(ancestorID)\n            };\n            tile.abortController = new AbortController();\n            try {\n                const data = await tile.actor.sendAsync({type: MessageType.loadTile, data: params}, tile.abortController);\n                delete tile.abortController;\n                return data;\n            } catch (err) {\n                delete tile.abortController;\n                if (tile.aborted || isAbortError(err)) {\n                    return null;\n                }\n                if (err && err.status !== 404) {\n                    throw err;\n                }\n            }\n        }\n        return null;\n    }\n\n    /**\n     * When the requested tile has a higher canonical Z than source maxzoom, pass overzoom parameters so worker can load the\n     * deepest tile at source max zoom to generate sub tiles using geojsonvt for highest performance on vector overscaling\n     */\n    private async _getOverzoomParameters(tile: Tile): Promise<OverzoomParameters | undefined> {\n        if (tile.tileID.canonical.z <= this.maxzoom) {\n            return undefined;\n        }\n        if (this.map._zoomLevelsToOverscale === undefined) {\n            return undefined;\n        }\n        const maxZoomTileID = tile.tileID.scaledTo(this.maxzoom).canonical;\n        return {\n            maxZoomTileID,\n            overzoomRequest: await this._getTileRequest(maxZoomTileID)\n        };\n    }\n\n    private async _getTileRequest(tileID: CanonicalTileID): Promise<RequestParameters> {\n        const url = tileID.url(this.tiles, this.map.getPixelRatio(), this.scheme, this.map.style.projection.worldCoordinateHelper.tileMatrixSet);\n        const request = await this.map._requestManager.transformRequest(url, ResourceType.Tile);\n        this._setAcceptHeader(request);\n        return request;\n    }\n\n    /**\n     * Sets the Accept header specifically for MLT requests.\n     * \n     * @param request - parameters to update.\n     * @see {@link https://github.com/maplibre/maplibre-native/pull/4231#discussion_r4216650681}\n     */\n    private _setAcceptHeader(request: RequestParameters) {\n        if (this.encoding === 'mlt') {\n            request.headers ??= {};\n            request.headers.Accept ??= 'application/vnd.maplibre-tile';\n        }\n    }\n\n    private _afterTileLoadWorkerResponse(tile: Tile, data: WorkerTileResult | null) {\n        if (data && this.map._refreshExpiredTiles) {\n            tile.setExpiryData(data);\n        }\n        tile.etag = data?.etag;\n        tile.loadVectorData(data, this.map.style);\n    }\n\n    private _reloadIfRequestedWhileLoading(tile: Tile) {\n        if (tile.reloadPromise) {\n            const reloadPromise = tile.reloadPromise;\n            tile.reloadPromise = null;\n            this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject);\n        }\n    }\n\n    async abortTile(tile: Tile): Promise<void> {\n        if (tile.abortController) {\n            tile.abortController.abort();\n            delete tile.abortController;\n        }\n        if (tile.actor) {\n            await tile.actor.sendAsync({\n                type: MessageType.abortTile,\n                data: {uid: tile.uid, type: this.type, source: this.id}\n            });\n        }\n    }\n\n    /**\n     * Removes the tile from every worker, since an expired tile may be reloaded on a different worker.\n     */\n    async unloadTile(tile: Tile): Promise<void> {\n        tile.unloadVectorData();\n        if (tile.actor) {\n            await this.dispatcher.broadcast(MessageType.removeTile, {uid: tile.uid, type: this.type, source: this.id});\n        }\n    }\n\n    hasTransition() {\n        return false;\n    }\n}\n", "import {ensureError, extend, pick} from '../util/util.ts';\nimport {ImageRequest} from '../util/image_request.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {ErrorEvent, Evented} from '../util/evented.ts';\nimport {MapSourceDataEvent, type SourceEventType} from '../ui/events.ts';\nimport {loadTileJson} from './load_tilejson.ts';\nimport {TileBounds} from '../tile/tile_bounds.ts';\nimport {Texture} from '../webgl/texture.ts';\nimport {RGBAImage} from '../util/image.ts';\nimport {isAbortError} from '../util/abort_error.ts';\n\nimport type {Source} from './source.ts';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\nimport type {Map} from '../ui/map.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {\n    RasterSourceSpecification,\n    RasterDEMSourceSpecification\n} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A source containing raster tiles (See the [raster source documentation](https://maplibre.org/maplibre-style-spec/sources/#raster) for detailed documentation of options.)\n *\n * @group Sources\n *\n * \\> ℹ️ **Note:** The default `tileSize` is `512`. If your tile provider (such as OpenStreetMap or Stadia Maps) serves 256px tiles, set `tileSize: 256` manually to avoid blurry rendering due to upscaling.\n *\n * @example\n * ```ts\n * map.addSource('raster-source', {\n *     'type': 'raster',\n *     'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'],\n *     'tileSize': 256, // Set this to match tile server output to avoid blurry rendering\n * });\n * ```\n *\n * @example\n * ```ts\n * map.addSource('wms-test-source', {\n *      'type': 'raster',\n * // use the tiles option to specify a WMS tile source URL\n *      'tiles': [\n *          'https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015'\n *      ],\n *      'tileSize': 256 // Important for WMS if tiles are 256px\n * });\n * ```\n * @see [Add a raster tile source](https://maplibre.org/maplibre-gl-js/docs/examples/map-tiles/)\n * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-wms-source/)\n * @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-satellite-map/)\n */\nexport class RasterTileSource extends Evented<SourceEventType> implements Source {\n    type: 'raster' | 'raster-dem';\n    id: string;\n    minzoom: number;\n    maxzoom: number;\n    url: string;\n    scheme: string;\n    tileSize: number;\n\n    bounds: [number, number, number, number];\n    tileBounds: TileBounds;\n    roundZoom: boolean;\n    dispatcher: Dispatcher;\n    map: Map;\n    tiles: string[];\n\n    _loaded: boolean;\n    _options: RasterSourceSpecification | RasterDEMSourceSpecification;\n    _premultiplyAlpha: boolean;\n    _tileJSONRequest: AbortController;\n\n    constructor(id: string, options: RasterSourceSpecification | RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n        super();\n        this.id = id;\n        this.dispatcher = dispatcher;\n        this.setEventedParent(eventedParent);\n\n        this.type = 'raster';\n        this.minzoom = 0;\n        this.maxzoom = 22;\n        this.roundZoom = true;\n        this.scheme = 'xyz';\n        this.tileSize = 512;\n        this._loaded = false;\n        this._premultiplyAlpha = true;\n\n        this._options = extend({type: 'raster'}, options);\n        extend(this, pick(options, ['url', 'scheme', 'tileSize']));\n    }\n\n    async load(sourceDataChanged: boolean = false): Promise<void> {\n        this._loaded = false;\n        this.fire(new MapSourceDataEvent('dataloading'));\n        this._tileJSONRequest = new AbortController();\n        try {\n            const tileJSON = await loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest, this.map._ownerWindow);\n            this._tileJSONRequest = null;\n            this._loaded = true;\n            if (tileJSON) {\n                extend(this, tileJSON);\n                if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom, this.map.style.projection.worldCoordinateHelper);\n\n                // `content` is included here to prevent a race condition where `Style._updateSources` is called\n                // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives\n                // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088\n                this.fire(new MapSourceDataEvent('data', {sourceDataType: 'metadata'}));\n                this.fire(new MapSourceDataEvent('data', {sourceDataType: 'content', sourceDataChanged}));\n            }\n        } catch (err) {\n            this._tileJSONRequest = null;\n            this._loaded = true; // let's pretend it's loaded so the source will be ignored\n\n            // only fire error event if it is not due to aborting the request\n            if (!isAbortError(err)) {\n                this.fire(new ErrorEvent(ensureError(err)));\n            }\n        }\n    }\n\n    loaded(): boolean {\n        return this._loaded;\n    }\n\n    onAdd(map: Map): void {\n        this.map = map;\n        this.load();\n    }\n\n    onRemove(): void {\n        if (this._tileJSONRequest) {\n            this._tileJSONRequest.abort();\n            this._tileJSONRequest = null;\n        }\n    }\n\n    setSourceProperty(callback: Function): void {\n        if (this._tileJSONRequest) {\n            this._tileJSONRequest.abort();\n            this._tileJSONRequest = null;\n        }\n\n        callback();\n\n        this.load(true);\n    }\n\n    /**\n     * Sets the source `tiles` property and re-renders the map.\n     *\n     * @param tiles - An array of one or more tile source URLs, as in the raster tiles spec (See the [Style Specification](https://maplibre.org/maplibre-style-spec/)\n     */\n    setTiles(tiles: string[]): this {\n        this.setSourceProperty(() => {\n            this.tiles = tiles;\n            this._options.tiles = tiles;\n        });\n\n        return this;\n    }\n\n    /**\n     * Sets the source `url` property and re-renders the map.\n     *\n     * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`.\n     */\n    setUrl(url: string): this {\n        this.setSourceProperty(() => {\n            this.url = url;\n            this._options.url = url;\n        });\n\n        return this;\n    }\n\n    serialize(): RasterSourceSpecification | RasterDEMSourceSpecification {\n        return extend({}, this._options);\n    }\n\n    /**\n     * Sets whether alpha premultiplication is applied to raster tile images.\n     * Set to `false` to preserve exact RGBA byte values when alpha carries data instead of opacity.\n     *\n     * @param premultiplyAlpha - If `false`, disables alpha premultiplication for raster tile image decode and texture upload.\n     * @example\n     * ```ts\n     * map.getSource<RasterTileSource>('raster-source').setPremultiplyAlpha(false);\n     * ```\n     */\n    setPremultiplyAlpha(premultiplyAlpha: boolean): this {\n        if (this._premultiplyAlpha === premultiplyAlpha) return this;\n\n        this.setSourceProperty(() => {\n            this._premultiplyAlpha = premultiplyAlpha;\n        });\n\n        return this;\n    }\n\n    hasTile(tileID: OverscaledTileID): boolean {\n        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);\n    }\n\n    async loadTile(tile: Tile): Promise<void> {\n        const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme, this.map.style.projection.worldCoordinateHelper.tileMatrixSet);\n        const premultiply = this._premultiplyAlpha;\n        const imageBitmapOptions = premultiply ? undefined : {premultiplyAlpha: 'none'} as const;\n        tile.abortController = new AbortController();\n        try {\n            const response = await ImageRequest.transformAndGetImage(\n                this.map._requestManager,\n                url,\n                ResourceType.Tile,\n                tile.abortController,\n                this.map._refreshExpiredTiles,\n                imageBitmapOptions\n            );\n            delete tile.abortController;\n            if (tile.aborted) {\n                tile.state = 'unloaded';\n                return;\n            }\n            if (response) {\n                if (this.map._refreshExpiredTiles && (response.cacheControl || response.expires)) {\n                    tile.setExpiryData({cacheControl: response.cacheControl, expires: response.expires});\n                }\n                const context = this.map.painter.context;\n                const gl = context.gl;\n                // An empty response (e.g. HTTP 204) is a tile that exists but has no content:\n                // it is drawn as fully transparent, which keeps it distinct from a missing\n                // tile (404), where the parent tile shows through instead.\n                const img = response.data ?? new RGBAImage({width: 1, height: 1}, new Uint8Array(4));\n                tile.texture = this.map.painter.getTileTexture(img.width);\n                if (tile.texture) {\n                    tile.texture.update(img, {useMipmap: true, premultiply});\n                } else {\n                    tile.texture = new Texture(context, img, gl.RGBA, {useMipmap: true, premultiply});\n                    tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n                }\n                tile.state = 'loaded';\n            }\n        } catch (err) {\n            delete tile.abortController;\n            if (tile.aborted) {\n                tile.state = 'unloaded';\n            } else if (err) {\n                tile.state = 'errored';\n                throw err;\n            }\n        }\n    }\n\n    async abortTile(tile: Tile): Promise<void> {\n        if (tile.abortController) {\n            tile.abortController.abort();\n            delete tile.abortController;\n        }\n    }\n\n    async unloadTile(tile: Tile): Promise<void> {\n        if (tile.texture) {\n            this.map.painter.saveTileTexture(tile.texture);\n        }\n    }\n\n    hasTransition(): boolean {\n        return false;\n    }\n}\n", "import {MAX_TILE_ZOOM, MIN_TILE_ZOOM} from './util.ts';\n\nimport type {LngLat} from '../geo/lng_lat.ts';\nimport type {WorldCoordinateHelper} from '../geo/transform_interface.ts';\n\n/**\n * Returns true if a given tile zoom (Z), X, and Y are in the bounds of the world.\n * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive).\n * X and Y bounds are 0 (inclusive) to their respective zoom-dependent maxima (exclusive).\n *\n * @param zoom - the tile zoom (Z)\n * @param x - the tile X\n * @param y - the tile Y\n * @returns `true` if a given tile zoom, X, and Y are in the bounds of the world.\n */\nexport function isInBoundsForTileZoomXY(zoom: number, x: number, y: number): boolean {\n    return !(\n        zoom < MIN_TILE_ZOOM ||\n        zoom > MAX_TILE_ZOOM ||\n        y < 0 ||\n        y >= Math.pow(2, zoom) ||\n        x < 0 ||\n        x >= Math.pow(2, zoom)\n    );\n}\n\n/**\n * Returns true if a given zoom and `LngLat` are in the bounds of the world.\n * Does not wrap `LngLat` when checking if in bounds.\n * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive).\n * `LngLat` bounds are the world's north-west corner (inclusive) to its south-east corner (exclusive).\n *\n * @param zoom - the tile zoom (Z)\n * @param LngLat - the `LngLat` object containing the longitude and latitude\n * @param worldCoordinateHelper - the lng/lat to world mapping to use\n * @returns `true` if a given zoom and `LngLat` are in the bounds of the world.\n */\nexport function isInBoundsForZoomLngLat(zoom: number, lnglat: LngLat, worldCoordinateHelper: WorldCoordinateHelper): boolean {\n    const {x, y} = worldCoordinateHelper.worldFromLngLat(lnglat.lng, lnglat.lat);\n    return !(\n        zoom < MIN_TILE_ZOOM ||\n        zoom > MAX_TILE_ZOOM ||\n        y < 0 ||\n        y >= 1 ||\n        x < 0 ||\n        x >= 1\n    );\n}\n", "import {EXTENT} from '../data/extent.ts';\nimport Point from '@mapbox/point-geometry';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate.ts';\nimport {register} from '../util/web_worker_transfer.ts';\nimport {type Mat4f32, MAX_TILE_ZOOM, MIN_TILE_ZOOM} from '../util/util.ts';\nimport {isInBoundsForTileZoomXY} from '../util/world_bounds.ts';\nimport {mercatorTileMatrixSet, type TileMatrixSet} from '../geo/projection/tile_matrix_set.ts';\n\nimport type {ICanonicalTileID, IMercatorCoordinate} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A canonical way to define a tile ID\n */\nexport class CanonicalTileID implements ICanonicalTileID {\n    z: number;\n    x: number;\n    y: number;\n    key: string;\n\n    constructor(z: number, x: number, y: number) {\n\n        if (!isInBoundsForTileZoomXY(z, x, y)) {\n            throw new Error(`x=${x}, y=${y}, z=${z} outside of bounds. 0<=x<${Math.pow(2, z)}, 0<=y<${Math.pow(2, z)} ${MIN_TILE_ZOOM}<=z<=${MAX_TILE_ZOOM} `);\n        }\n\n        this.z = z;\n        this.x = x;\n        this.y = y;\n        this.key = calculateTileKey(0, z, z, x, y);\n    }\n\n    equals(id: ICanonicalTileID): boolean {\n        return this.z === id.z && this.x === id.x && this.y === id.y;\n    }\n\n    /**\n     * given a list of urls, choose a url template and return a tile URL\n     * @param tileMatrixSet - the tile grid the `{bbox}` token is expressed in, the map projection's; optional only because\n     * the style spec's `ICanonicalTileID.url` has three parameters, and absent means the EPSG:3857 grid of `{bbox-epsg-3857}`\n     */\n    url(urls: string[], pixelRatio: number, scheme?: string | null, tileMatrixSet: TileMatrixSet = mercatorTileMatrixSet): string {\n        const quadkey = getQuadkey(this.z, this.x, this.y);\n\n        return urls[(this.x + this.y) % urls.length]\n            .replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16))\n            .replace(/{z}/g, String(this.z))\n            .replace(/{x}/g, String(this.x))\n            .replace(/{y}/g, String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y))\n            .replace(/{ratio}/g, pixelRatio > 1 ? '@2x' : '')\n            .replace(/{quadkey}/g, quadkey)\n            .replace(/{bbox-epsg-3857}/g, () => getTileBBox(this.x, this.y, this.z, mercatorTileMatrixSet))\n            .replace(/{bbox}/g, () => getTileBBox(this.x, this.y, this.z, tileMatrixSet));\n    }\n\n    isChildOf(parent: ICanonicalTileID): boolean {\n        const dz = this.z - parent.z;\n        return  dz > 0 && parent.x === (this.x >> dz) && parent.y === (this.y >> dz);\n    }\n\n    getTilePoint(coord: IMercatorCoordinate): Point {\n        const tilesAtZoom = Math.pow(2, this.z);\n        return new Point(\n            (coord.x * tilesAtZoom - this.x) * EXTENT,\n            (coord.y * tilesAtZoom - this.y) * EXTENT);\n    }\n\n    toString(): string {\n        return `${this.z}/${this.x}/${this.y}`;\n    }\n}\n\n/**\n * @internal\n * An unwrapped tile identifier\n */\nexport class UnwrappedTileID {\n    wrap: number;\n    canonical: CanonicalTileID;\n    key: string;\n\n    constructor(wrap: number, canonical: CanonicalTileID) {\n        this.wrap = wrap;\n        this.canonical = canonical;\n        this.key = calculateTileKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y);\n    }\n}\n\n/**\n * An overscaled tile identifier\n */\nexport class OverscaledTileID {\n    overscaledZ: number;\n    wrap: number;\n    canonical: CanonicalTileID;\n    key: string;\n    /**\n     * This matrix is used during terrain's render-to-texture stage only.\n     * If the render-to-texture stage is active, this matrix will be present\n     * and should be used, otherwise this matrix will be null.\n     * The matrix should be float32 in order to avoid slow WebGL calls in Chrome.\n     */\n    terrainRttPosMatrix32f: Mat4f32 | null = null;\n\n    constructor(overscaledZ: number, wrap: number, z: number, x: number, y: number) {\n        if (overscaledZ < z) throw new Error(`overscaledZ should be >= z; overscaledZ = ${overscaledZ}; z = ${z}`);\n        this.overscaledZ = overscaledZ;\n        this.wrap = wrap;\n        this.canonical = new CanonicalTileID(z, +x, +y);\n        this.key = calculateTileKey(wrap, overscaledZ, z, x, y);\n    }\n\n    clone(): OverscaledTileID {\n        return new OverscaledTileID(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n    }\n\n    equals(id: OverscaledTileID): boolean {\n        return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical);\n    }\n\n    /**\n     * Returns a new `OverscaledTileID` representing the tile at the target zoom level.\n     * When targetZ is greater than the current canonical z, the canonical coordinates are unchanged.\n     * When targetZ is less than the current canonical z, the canonical coordinates are updated.\n     * @param targetZ - the zoom level to scale to. Must be less than or equal to this.overscaledZ\n     * @returns a new OverscaledTileID representing the tile at the target zoom level\n     * @throws if targetZ is greater than this.overscaledZ\n     */\n    scaledTo(targetZ: number): OverscaledTileID {\n        if (targetZ > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);\n        const zDifference = this.canonical.z - targetZ;\n        if (targetZ > this.canonical.z) {\n            return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n        } else {\n            return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n        }\n    }\n\n    isOverscaled(): boolean {\n        return (this.overscaledZ > this.canonical.z);\n    }\n\n    /*\n     * calculateScaledKey is an optimization:\n     * when withWrap == true, implements the same as this.scaledTo(z).key,\n     * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key.\n     */\n    calculateScaledKey(targetZ: number, withWrap: boolean): string {\n        if (targetZ > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);\n        const zDifference = this.canonical.z - targetZ;\n        if (targetZ > this.canonical.z) {\n            return calculateTileKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);\n        } else {\n            return calculateTileKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n        }\n    }\n\n    isChildOf(parent: OverscaledTileID): boolean {\n        if (parent.wrap !== this.wrap) return false; // different world copy\n\n        const zDifference = this.overscaledZ - parent.overscaledZ;\n        if (zDifference <= 0) return false; // must be deeper zoom\n\n        //special case for root tile (bitwise math doesn't work for root)\n        if (parent.overscaledZ === 0) return this.overscaledZ > 0;\n\n        const dz = this.canonical.z - parent.canonical.z;\n        if (dz < 0) return false; // parent can't be deeper canonically\n\n        return (\n            parent.canonical.x === (this.canonical.x >> dz) &&\n            parent.canonical.y === (this.canonical.y >> dz)\n        );\n    }\n\n    children(sourceMaxZoom: number): OverscaledTileID[] {\n        if (this.overscaledZ >= sourceMaxZoom) {\n            // return a single tile coord representing a an overscaled tile\n            return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];\n        }\n\n        const z = this.canonical.z + 1;\n        const x = this.canonical.x * 2;\n        const y = this.canonical.y * 2;\n        return [\n            new OverscaledTileID(z, this.wrap, z, x, y),\n            new OverscaledTileID(z, this.wrap, z, x + 1, y),\n            new OverscaledTileID(z, this.wrap, z, x, y + 1),\n            new OverscaledTileID(z, this.wrap, z, x + 1, y + 1)\n        ];\n    }\n\n    isLessThan(rhs: OverscaledTileID): boolean {\n        if (this.wrap < rhs.wrap) return true;\n        if (this.wrap > rhs.wrap) return false;\n\n        if (this.overscaledZ < rhs.overscaledZ) return true;\n        if (this.overscaledZ > rhs.overscaledZ) return false;\n\n        if (this.canonical.x < rhs.canonical.x) return true;\n        if (this.canonical.x > rhs.canonical.x) return false;\n\n        return this.canonical.y < rhs.canonical.y;\n\n    }\n\n    wrapped(): OverscaledTileID {\n        return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);\n    }\n\n    unwrapTo(wrap: number): OverscaledTileID {\n        return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n    }\n\n    overscaleFactor(): number {\n        return Math.pow(2, this.overscaledZ - this.canonical.z);\n    }\n\n    toUnwrapped(): UnwrappedTileID {\n        return new UnwrappedTileID(this.wrap, this.canonical);\n    }\n\n    toString(): string {\n        return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`;\n    }\n\n    getTilePoint(coord: MercatorCoordinate): Point {\n        return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y));\n    }\n\n    /**\n     * Maps tile-local coordinates that may fall outside the `[0, extent)` range\n     * to the correct neighbor tile and the corresponding in-tile position.\n     *\n     * Coordinates can exceed tile bounds when geometry (e.g. symbol labels along\n     * lines) extends across tile edges. This method resolves such coordinates to\n     * the appropriate adjacent tile, wrapping horizontally across world boundaries\n     * and returning `null` when the target falls beyond the polar tile-grid limits.\n     *\n     * When the coordinates are already in bounds, the original tile ID is returned.\n     *\n     * @param x - x coordinate relative to this tile, may be outside `[0, extent)`\n     * @param y - y coordinate relative to this tile, may be outside `[0, extent)`\n     * @param extent - tile coordinate extent, default {@link EXTENT}\n     * @returns the resolved tile ID and in-tile coordinates, or `null` if the\n     *          target is beyond the tile grid (e.g. past the poles)\n     */\n    normalizeCoordinates(x: number, y: number, extent: number = EXTENT): {tileID: OverscaledTileID; x: number; y: number} | null {\n        if (x >= 0 && x < extent && y >= 0 && y < extent) {\n            return {tileID: this, x, y};\n        }\n\n        const tileOffsetX = Math.floor(x / extent);\n        const tileOffsetY = Math.floor(y / extent);\n        const newX = x - tileOffsetX * extent;\n        const newY = y - tileOffsetY * extent;\n\n        const z = this.canonical.z;\n        const dim = 1 << z;\n        const newCanonicalY = this.canonical.y + tileOffsetY;\n\n        if (newCanonicalY < 0 || newCanonicalY >= dim) return null;\n\n        let newCanonicalX = this.canonical.x + tileOffsetX;\n        let newWrap = this.wrap;\n        if (newCanonicalX < 0) {\n            newWrap -= Math.ceil(-newCanonicalX / dim);\n            newCanonicalX = ((newCanonicalX % dim) + dim) % dim;\n        } else if (newCanonicalX >= dim) {\n            newWrap += Math.floor(newCanonicalX / dim);\n            newCanonicalX = newCanonicalX % dim;\n        }\n\n        return {\n            tileID: new OverscaledTileID(this.overscaledZ, newWrap, z, newCanonicalX, newCanonicalY),\n            x: newX,\n            y: newY,\n        };\n    }\n}\n\nexport function calculateTileKey(wrap: number, overscaledZ: number, z: number, x: number, y: number): string {\n    wrap *= 2;\n    if (wrap < 0) wrap = wrap * -1 - 1;\n    const dim = 1 << z;\n    return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36);\n}\n\n/**\n * Builds the `{bbox}` and `{bbox-epsg-3857}` tokens used in WMS tile URLs: the tile's bounding box in the tile matrix set's\n * CRS units as a `minX,minY,maxX,maxY` string, y up.\n *\n * The EPSG:3857 form of this formula was inlined from the archived \\@mapbox/whoots-js (ISC, Copyright (c) 2017 Mapbox).\n */\nfunction getTileBBox(x: number, y: number, z: number, tileMatrixSet: TileMatrixSet): string {\n    const tilesAtZoom = Math.pow(2, z);\n    const tileExtent = tileMatrixSet.extentAtZoom0 / tilesAtZoom;\n    const [gridMinX, gridMaxY] = tileMatrixSet.origin;\n    const gridMinY = gridMaxY - tileMatrixSet.extentAtZoom0;\n    const rowFromBottom = tilesAtZoom - y - 1;\n\n    return `${gridMinX + x * tileExtent},${gridMinY + rowFromBottom * tileExtent},${gridMinX + (x + 1) * tileExtent},${gridMinY + (rowFromBottom + 1) * tileExtent}`;\n}\n\nfunction getQuadkey(z:number, x:number, y:number): string {\n    let quadkey = '';\n    for (let i = z; i > 0; i--) {\n        const mask = 1 << (i - 1);\n        quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0));\n    }\n    return quadkey;\n}\n\nexport function compareTileId(a: OverscaledTileID, b: OverscaledTileID): number {\n    // Different copies of the world are sorted based on their distance to the center.\n    // Wrap values are converted to unsigned distances by reserving odd number for copies\n    // with negative wrap and even numbers for copies with positive wrap.\n    const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0);\n    const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0);\n    return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x;\n}\n\nregister('CanonicalTileID', CanonicalTileID);\nregister('OverscaledTileID', OverscaledTileID, {omit: ['terrainRttPosMatrix32f']});\n", "import {ImageRequest} from '../util/image_request.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {extend, isImageBitmap, readImageUsingVideoFrame} from '../util/util.ts';\nimport {browser} from '../util/browser.ts';\nimport {offscreenCanvasSupported} from '../util/offscreen_canvas_supported.ts';\nimport {OverscaledTileID} from '../tile/tile_id.ts';\nimport {RasterTileSource} from './raster_tile_source.ts';\n// ensure DEMData is registered for worker transfer on main thread:\nimport '../data/dem_data.ts';\nimport {isOffscreenCanvasDistorted} from '../util/offscreen_canvas_distorted.ts';\nimport {RGBAImage} from '../util/image.ts';\nimport {MessageType} from '../util/actor_messages.ts';\n\nimport type {DEMEncoding} from '../data/dem_data.ts';\nimport type {Source} from './source.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {RasterDEMSourceSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Evented} from '../util/evented.ts';\n\n/**\n * A source containing raster DEM tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.)\n * This source can be used to show hillshading and 3D terrain\n *\n * @group Sources\n *\n * @example\n * ```ts\n * map.addSource('raster-dem-source', {\n *      type: 'raster-dem',\n *      url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json',\n *      tileSize: 256\n * });\n * ```\n * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/)\n */\nexport class RasterDEMTileSource extends RasterTileSource implements Source {\n    encoding: DEMEncoding;\n    redFactor?: number;\n    greenFactor?: number;\n    blueFactor?: number;\n    baseShift?: number;\n\n    constructor(id: string, options: RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n        super(id, options, dispatcher, eventedParent);\n        this.type = 'raster-dem';\n        this.maxzoom = 22;\n        this._options = extend({type: 'raster-dem'}, options);\n        this.encoding = options.encoding || 'mapbox';\n        this.redFactor = options.redFactor;\n        this.greenFactor = options.greenFactor;\n        this.blueFactor = options.blueFactor;\n        this.baseShift = options.baseShift;\n    }\n\n    override async loadTile(tile: Tile): Promise<void> {\n        const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme, this.map.style.projection.worldCoordinateHelper.tileMatrixSet);\n        tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);\n        tile.abortController = new AbortController();\n        try {\n            const response = await ImageRequest.transformAndGetImage(this.map._requestManager, url, ResourceType.Tile, tile.abortController, this.map._refreshExpiredTiles, {colorSpaceConversion: 'none'});\n            delete tile.abortController;\n            if (tile.aborted) {\n                tile.state = 'unloaded';\n                return;\n            }\n            if (response) {\n                if (this.map._refreshExpiredTiles && (response.cacheControl || response.expires)) {\n                    tile.setExpiryData({cacheControl: response.cacheControl, expires: response.expires});\n                }\n                // An empty response (e.g. HTTP 204 for a missing DEM tile) carries no elevation\n                // data: treat the tile as loaded without a DEM instead of building a degenerate\n                // one that would fail against its neighbors in backfillBorder (#1551).\n                if (!response.data) {\n                    tile.state = 'loaded';\n                    return;\n                }\n                const img = response.data;\n                const transfer = isImageBitmap(img) && offscreenCanvasSupported();\n                const rawImageData = transfer ? img : await this.readImageNow(img);\n                const params = {\n                    type: this.type,\n                    uid: tile.uid,\n                    source: this.id,\n                    rawImageData,\n                    encoding: this.encoding,\n                    redFactor: this.redFactor,\n                    greenFactor: this.greenFactor,\n                    blueFactor: this.blueFactor,\n                    baseShift: this.baseShift\n                };\n\n                if (tile.actor && tile.state !== 'expired' && tile.state !== 'reloading') {\n                    return;\n                }\n                await this.dispatcher.waitForInitComplete();\n                if (!tile.actor || tile.state === 'expired') {\n                    tile.actor = this.dispatcher.getReadyActor();\n                }\n                tile.dem = await tile.actor.sendAsync({type: MessageType.loadDEMTile, data: params});\n                tile.needsHillshadePrepare = true;\n                tile.needsTerrainPrepare = true;\n                tile.needsColorReliefPrepare = true;\n                tile.state = 'loaded';\n            }\n        } catch (err) {\n            delete tile.abortController;\n            if (tile.aborted) {\n                tile.state = 'unloaded';\n            } else if (err) {\n                tile.state = 'errored';\n                throw err;\n            }\n        }\n    }\n\n    async readImageNow(img: ImageBitmap | HTMLImageElement): Promise<RGBAImage | ImageData> {\n        if (typeof VideoFrame !== 'undefined' && isOffscreenCanvasDistorted()) {\n            const width = img.width + 4;\n            const height = img.height + 4;\n            try {\n                return new RGBAImage({width, height}, await readImageUsingVideoFrame(img, -2, -2, width, height));\n            } catch {\n                // fall-back to browser canvas decoding\n            }\n        }\n        return browser.getImageData(img, 2);\n    }\n\n    _getNeighboringTiles(tileID: OverscaledTileID): Record<string, {backfilled: boolean}> {\n        const canonical = tileID.canonical;\n        const dim = Math.pow(2, canonical.z);\n\n        const px = (canonical.x - 1 + dim) % dim;\n        const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap;\n        const nx = (canonical.x + 1 + dim) % dim;\n        const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap;\n\n        const neighboringTiles: Record<string, {backfilled: boolean}> = {};\n        // add adjacent tiles\n        neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = {backfilled: false};\n        neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = {backfilled: false};\n\n        // Add upper neighboringTiles\n        if (canonical.y > 0) {\n            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = {backfilled: false};\n            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = {backfilled: false};\n            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = {backfilled: false};\n        }\n        // Add lower neighboringTiles\n        if (canonical.y + 1 < dim) {\n            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = {backfilled: false};\n            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = {backfilled: false};\n            neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = {backfilled: false};\n        }\n\n        return neighboringTiles;\n    }\n\n    async unloadTile(tile: Tile): Promise<void> {\n        if (tile.demTexture) this.map.painter.saveTileTexture(tile.demTexture);\n        if (tile.fbo) {\n            tile.fbo.destroy();\n            delete tile.fbo;\n        }\n        if (tile.dem) delete tile.dem;\n        delete tile.neighboringTiles;\n\n        tile.state = 'unloaded';\n        if (tile.actor) {\n            await tile.actor.sendAsync({type: MessageType.removeDEMTile, data: {type: this.type, uid: tile.uid, source: this.id}});\n        }\n    }\n}\n", "/**\n * A way to identify a feature, either by string or by number\n */\nexport type GeoJSONFeatureId = number | string;\n\n/**\n * The geojson source diff object - processed in the following order: remove, add, update. Provides an efficient\n * way to update GeoJSON data in a map source without having to replace the entire dataset.\n */\nexport type GeoJSONSourceDiff = {\n    /**\n     * When set to `true` it will remove all features\n     */\n    removeAll?: boolean;\n    /**\n     * An array of features IDs to remove\n     */\n    remove?: GeoJSONFeatureId[];\n    /**\n     * An array of features to add\n     */\n    add?: GeoJSON.Feature[];\n    /**\n     * An array of update objects\n     */\n    update?: GeoJSONFeatureDiff[];\n};\n\n/**\n * A geojson feature diff object - processed in the following order: new geometry, remove properties, add/update properties.\n * Provides an efficient way to update GeoJSON features in a map source without replacing the entire feature.\n */\nexport type GeoJSONFeatureDiff = {\n    /**\n     * The feature ID\n     */\n    id: GeoJSONFeatureId;\n    /**\n     * If it's a new geometry, place it here\n     */\n    newGeometry?: GeoJSON.Geometry;\n    /**\n     * Setting to `true` will remove all preperties\n     */\n    removeAllProperties?: boolean;\n    /**\n     * The properties keys to remove\n     */\n    removeProperties?: string[];\n    /**\n     * The properties to add or update along side their values\n     */\n    addOrUpdateProperties?: Array<{key: string; value: any}>;\n};\n\nexport type UpdateableGeoJSON = GeoJSON.Feature | GeoJSON.FeatureCollection | undefined;\n\nfunction getFeatureId(feature: GeoJSON.Feature, promoteId?: string): GeoJSONFeatureId | undefined {\n    return promoteId ? feature.properties[promoteId] : feature.id;\n}\n\n/**\n * Converts a GeoJSON object into a map of feature IDs to GeoJSON features.\n * @param data - The GeoJSON object to convert.\n * @param promoteId - If set, the feature id will be set to the promoteId property value.\n * @returns A map of feature IDs to GeoJSON features, or `undefined` if the GeoJSON object is not a valid updateable object.\n *\n * Features must have unique identifiers to be updateable. IDs can come from:\n * - The feature's `id` property (standard GeoJSON)\n * - A promoted property specified by `promoteId` (e.g., a \"name\" property)\n */\nexport function toUpdateable(data: GeoJSON.GeoJSON | undefined, promoteId?: string): Map<GeoJSONFeatureId, GeoJSON.Feature> | undefined {\n    const updateable = new Map<GeoJSONFeatureId, GeoJSON.Feature>();\n\n    // null can be updated - empty updateable\n    if (data == null) {\n        return updateable;\n    }\n\n    // {} can be updated - empty updateable\n    if (data.type == null) {\n        return updateable;\n    }\n\n    // a single feature with an id can be updated, need to explicitly check against null because 0 is a valid feature id that is falsy\n    if (data.type === 'Feature') {\n        const id = getFeatureId(data, promoteId);\n        if (id == null) return undefined;\n\n        updateable.set(id, data);\n        return updateable;\n    }\n\n    // a feature collection can be updated if every feature has a unique id, which prevents the silent dropping of features\n    if (data.type === 'FeatureCollection') {\n        const seenIds = new Set<GeoJSONFeatureId>();\n\n        for (const feature of data.features) {\n            const id = getFeatureId(feature, promoteId);\n            if (id == null) return undefined;\n\n            if (seenIds.has(id)) return undefined;\n            seenIds.add(id);\n\n            updateable.set(id, feature);\n        }\n\n        return updateable;\n    }\n\n    return undefined;\n}\n\n/**\n * Mutates updateable and applies a {@link GeoJSONSourceDiff}. Operations are processed in a specific order to ensure predictable behavior:\n * 1. Remove operations (removeAll, remove)\n * 2. Add operations (add)\n * 3. Update operations (update)\n * @returns an array of geometries that were affected by the diff - with the exception of removeAll which does not track any affected geometries.\n */\nexport function applySourceDiff(updateable: Map<GeoJSONFeatureId, GeoJSON.Feature>, diff: GeoJSONSourceDiff, promoteId?: string): GeoJSON.Geometry[] {\n    const affectedGeometries: GeoJSON.Geometry[] = [];\n\n    if (diff.removeAll) {\n        updateable.clear();\n    }\n    else if (diff.remove) {\n        for (const id of diff.remove) {\n            const existing = updateable.get(id);\n            if (!existing) continue;\n\n            affectedGeometries.push(existing.geometry);\n            updateable.delete(id);\n        }\n    }\n\n    if (diff.add) {\n        for (const feature of diff.add) {\n            const id = getFeatureId(feature, promoteId);\n            if (id == null) continue;\n\n            const existing = updateable.get(id);\n            if (existing) affectedGeometries.push(existing.geometry);\n\n            affectedGeometries.push(feature.geometry);\n            updateable.set(id, feature);\n        }\n    }\n\n    if (diff.update) {\n        for (const update of diff.update) {\n            const existing = updateable.get(update.id);\n            if (!existing) continue;\n\n            const changeGeometry = !!update.newGeometry;\n\n            const changeProps =\n                update.removeAllProperties ||\n                update.removeProperties?.length > 0 ||\n                update.addOrUpdateProperties?.length > 0;\n\n            // nothing to do\n            if (!changeGeometry && !changeProps) continue;\n\n            // clone once since we'll mutate\n            affectedGeometries.push(existing.geometry);\n            const feature = {...existing};\n            updateable.set(update.id, feature);\n\n            if (changeGeometry) {\n                affectedGeometries.push(update.newGeometry);\n                feature.geometry = update.newGeometry;\n            }\n\n            if (changeProps) {\n                if (update.removeAllProperties) {\n                    feature.properties = {};\n                } else {\n                    feature.properties = {...feature.properties || {}};\n                }\n\n                if (update.removeProperties) {\n                    for (const key of update.removeProperties) {\n                        delete feature.properties[key];\n                    }\n                }\n\n                if (update.addOrUpdateProperties) {\n                    for (const {key, value} of update.addOrUpdateProperties) {\n                        feature.properties[key] = value;\n                    }\n                }\n            }\n        }\n    }\n\n    return affectedGeometries;\n}\n\n/**\n * Merge two GeoJSONSourceDiffs, considering the order of operations as specified above (remove, add, update).\n *\n * `add` features of a promoteId source carry their id in a property, so `promoteId` is needed to key them.\n */\nexport function mergeSourceDiffs(\n    prevDiff: GeoJSONSourceDiff | undefined,\n    nextDiff: GeoJSONSourceDiff | undefined,\n    promoteId?: string\n): GeoJSONSourceDiff {\n    if (!prevDiff) return nextDiff || {};\n    if (!nextDiff) return prevDiff || {};\n\n    // Hash for o(1) lookups while creating a mutatable copy of the collections\n    const prev = diffToHashed(prevDiff, promoteId);\n    const next = diffToHashed(nextDiff, promoteId);\n\n    // Resolve merge conflicts\n    resolveMergeConflicts(prev, next);\n\n    // Simply merge the two diffs now that conflicts have been resolved\n    const merged: GeoJSONSourceDiffHashed = {};\n    if (prev.removeAll || next.removeAll) merged.removeAll = true;\n    merged.remove = new Set([...prev.remove , ...next.remove]);\n    merged.add    = new Map([...prev.add    , ...next.add]);\n    merged.update = new Map([...prev.update , ...next.update]);\n\n    // Squash the merge - removing then adding the same feature\n    if (merged.remove.size && merged.add.size) {\n        for (const id of merged.add.keys()) {\n            merged.remove.delete(id);\n        }\n    }\n\n    // Convert back to array-based representation\n    return hashedToDiff(merged);\n}\n\n/**\n * Resolve merge conflicts between two GeoJSONSourceDiffs considering the ordering above (remove/add/update).\n *\n * - If you `removeAll` and then `add` features in the same diff, the added features will be kept.\n * - Updates only apply to features that exist after removes and adds have been processed.\n * - An `add` replaces the whole feature, so earlier updates to the same id are dropped before updates are merged.\n */\nfunction resolveMergeConflicts(prev: GeoJSONSourceDiffHashed, next: GeoJSONSourceDiffHashed) {\n    // Removing all features with added or updated features in previous - and clear no-op removes\n    if (next.removeAll) {\n        prev.add.clear();\n        prev.update.clear();\n        prev.remove.clear();\n        next.remove.clear();\n    }\n\n    // Removing features that were added or updated in previous\n    for (const id of next.remove) {\n        prev.add.delete(id);\n        prev.update.delete(id);\n    }\n\n    // Adding features that were updated in previous - the add replaces them\n    for (const id of next.add.keys()) {\n        prev.update.delete(id);\n    }\n\n    // Updating features that were updated in previous\n    for (const [id, nextUpdate] of next.update) {\n        const prevUpdate = prev.update.get(id);\n        if (!prevUpdate) continue;\n\n        next.update.set(id, mergeFeatureDiffs(prevUpdate, nextUpdate));\n        prev.update.delete(id);\n    }\n}\n\n/**\n * Merge two feature diffs for the same feature id, considering the order of operations as specified above (remove, add/update).\n */\nfunction mergeFeatureDiffs(prev: GeoJSONFeatureDiff, next: GeoJSONFeatureDiff): GeoJSONFeatureDiff {\n    const merged: GeoJSONFeatureDiff = {id: prev.id};\n\n    // Removing all properties with added or updated properties in previous - and clear no-op removes\n    if (next.removeAllProperties) {\n        delete prev.removeProperties;\n        delete prev.addOrUpdateProperties;\n        delete next.removeProperties;\n    }\n    // Removing properties that were added or updated in previous\n    if (next.removeProperties && prev.addOrUpdateProperties) {\n        const removedProperties = new Set(next.removeProperties);\n        prev.addOrUpdateProperties = prev.addOrUpdateProperties.filter(prop => !removedProperties.has(prop.key));\n    }\n\n    // Merge the two diffs\n    if (prev.removeAllProperties || next.removeAllProperties) {\n        merged.removeAllProperties = true;\n    }\n    if (prev.removeProperties || next.removeProperties) {\n        merged.removeProperties = [...prev.removeProperties || [], ...next.removeProperties || []];\n    }\n    if (prev.addOrUpdateProperties || next.addOrUpdateProperties) {\n        merged.addOrUpdateProperties = [...prev.addOrUpdateProperties || [], ...next.addOrUpdateProperties || []];\n    }\n    if (prev.newGeometry || next.newGeometry) {\n        merged.newGeometry = next.newGeometry || prev.newGeometry;\n    }\n\n    return merged;\n}\n\n/**\n * @internal\n * Internal representation of GeoJSONSourceDiff using Sets and Maps for efficient operations\n */\ntype GeoJSONSourceDiffHashed = {\n    removeAll?: boolean;\n    remove?: Set<GeoJSONFeatureId>;\n    add?: Map<GeoJSONFeatureId, GeoJSON.Feature>;\n    update?: Map<GeoJSONFeatureId, GeoJSONFeatureDiff>;\n};\n\n/**\n * @internal\n * Convert a GeoJSONSourceDiff to an idempotent hashed representation using Sets and Maps\n * @param promoteId - If set, `add` features are keyed by that property instead of by `id`.\n */\nfunction diffToHashed(diff: GeoJSONSourceDiff | undefined, promoteId?: string): GeoJSONSourceDiffHashed {\n    if (!diff) return {};\n\n    const hashed: GeoJSONSourceDiffHashed = {};\n\n    hashed.removeAll = diff.removeAll;\n    hashed.remove = new Set(diff.remove || []);\n    hashed.add    = new Map(diff.add?.map(feature => [getFeatureId(feature, promoteId), feature]));\n    hashed.update = new Map(diff.update?.map(update => [update.id, update]));\n\n    return hashed;\n}\n\n/**\n * @internal\n * Convert a hashed GeoJSONSourceDiff back to the array-based representation\n */\nfunction hashedToDiff(hashed: GeoJSONSourceDiffHashed): GeoJSONSourceDiff {\n    const diff: GeoJSONSourceDiff = {};\n\n    if (hashed.removeAll) {\n        diff.removeAll = hashed.removeAll;\n    }\n    if (hashed.remove) {\n        diff.remove = Array.from(hashed.remove);\n    }\n    if (hashed.add) {\n        diff.add = Array.from(hashed.add.values());\n    }\n    if (hashed.update) {\n        diff.update = Array.from(hashed.update.values());\n    }\n\n    return diff;\n}\n", "import {LngLatBounds} from '../geo/lng_lat_bounds.ts';\n\ntype DeepCoordinates = GeoJSON.Position | DeepCoordinates[];\n\nfunction extractCoordinates(coords: DeepCoordinates): number[][] {\n    if (!coords || coords.length === 0) return [];\n\n    if (typeof coords[0] === 'number') {\n        return [coords as number[]];\n    }\n\n    return coords.flatMap(c => extractCoordinates(c));\n}\n\nfunction getCoordinatesFromGeometry(geometry: GeoJSON.Geometry | null): number[][] {\n    if (!geometry) return [];\n\n    if (geometry.type === 'GeometryCollection') {\n        return geometry.geometries.flatMap(g => getCoordinatesFromGeometry(g));\n    }\n\n    return extractCoordinates(geometry.coordinates);\n}\n\n/**\n * Calculates the bounding box of GeoJSON data.\n * @param data - The GeoJSON data to calculate bounds for\n * @returns The bounding box of the GeoJSON data\n */\nexport function getGeoJSONBounds(data: GeoJSON.GeoJSON): LngLatBounds {\n    const bounds = new LngLatBounds();\n    let coordinates: number[][];\n\n    switch (data.type) {\n        case 'FeatureCollection':\n            coordinates = data.features.flatMap(f => getCoordinatesFromGeometry(f.geometry));\n            break;\n        case 'Feature':\n            coordinates = getCoordinatesFromGeometry(data.geometry);\n            break;\n        default:\n            coordinates = getCoordinatesFromGeometry(data);\n            break;\n    }\n\n    if (coordinates.length === 0) {\n        return bounds;\n    }\n\n    for (const coordinate of coordinates) {\n        const [lng, lat] = coordinate;\n\n        bounds.extend([lng, lat]);\n    }\n    return bounds;\n}\n", "import {LngLatBounds} from '../geo/lng_lat_bounds.ts';\nimport {worldBoxToLngLatBox} from '../geo/projection/mercator_utils.ts';\n\nimport type {WorldCoordinateHelper} from '../geo/transform_interface.ts';\nimport type {CanonicalTileID} from './tile_id.ts';\n\n/**\n * The lng/lat box of a tile, grown by `buffer` tile units (0 for the bare tile), in the given world mapping.\n * The four tile corners are mapped back and their hull is returned, see {@link worldBoxToLngLatBox}: exact for\n * mercator, but where both axes depend on lng and lat it can miss part of the tile, such as a pole inside it.\n */\nexport function tileIdToLngLatBounds(\n    {x,y,z}: CanonicalTileID,\n    buffer: number,\n    worldCoordinateHelper: WorldCoordinateHelper,\n): LngLatBounds {\n    const worldSize = Math.pow(2, z);\n    const {west, south, east, north} = worldBoxToLngLatBox(\n        worldCoordinateHelper,\n        (x - buffer) / worldSize,\n        (y - buffer) / worldSize,\n        (x + 1 + buffer) / worldSize,\n        (y + 1 + buffer) / worldSize);\n\n    return new LngLatBounds([west, south], [east, north]);\n}\n", "/**\n * The functions an {@link UpdateQueue} calls for each update.\n */\nexport type UpdateQueueHandlers<T, R> = {\n    /**\n     * Sends an update. The next one is not sent before the returned promise settles.\n     */\n    send: (update: T) => Promise<R>;\n    /**\n     * Called with the result of an update, once it is no longer being sent.\n     * `replaced` is whether {@link UpdateQueue#replace} was called while the update was being sent, in which case\n     * the result describes a state that has since been replaced.\n     */\n    onResult: (update: T, result: R, replaced: boolean) => void;\n    /**\n     * Called when sending an update, or handling its result, failed.\n     */\n    onError: (update: T, error: unknown) => void;\n};\n\n/**\n * Sends updates one at a time, in the order they were queued.\n * An update that is still waiting can be changed in place, through {@link UpdateQueue#top}, until it is sent.\n */\nexport class UpdateQueue<T, R> {\n    private readonly _handlers: UpdateQueueHandlers<T, R>;\n    private _waiting: T[] = [];\n    private _sending = false;\n    /**\n     * Whether {@link UpdateQueue#replace} was called since the update being sent was sent.\n     */\n    private _replacedWhileSending = false;\n    /**\n     * What every {@link UpdateQueue#flush} call returns until the queue is idle again.\n     * It is created by the first flush after the queue was idle, shared by the flushes that follow,\n     * and resolved and cleared once no update is left, so it is only set while a flush is in progress.\n     */\n    private _flushing: {promise: Promise<void>; resolve: () => void} | undefined;\n\n    constructor(handlers: UpdateQueueHandlers<T, R>) {\n        this._handlers = handlers;\n    }\n\n    /**\n     * Whether no update is being sent or waiting to be.\n     */\n    isIdle(): boolean {\n        return !this._sending && this._waiting.length === 0;\n    }\n\n    /**\n     * The update queued last, if it is still waiting to be sent.\n     * The update being sent is not waiting, so it is never returned.\n     */\n    top(): T | undefined {\n        return this._waiting.length ? this._waiting[this._waiting.length - 1] : undefined;\n    }\n\n    /**\n     * Whether any waiting update matches the predicate. The update being sent is not waiting, so it is never tested.\n     */\n    some(predicate: (update: T) => boolean): boolean {\n        return this._waiting.some(predicate);\n    }\n\n    /**\n     * Queues an update without sending it.\n     */\n    enqueue(update: T): void {\n        this._waiting.push(update);\n    }\n\n    /**\n     * Drops the waiting updates and queues this one instead.\n     */\n    replace(update: T): void {\n        this._waiting = [update];\n        this._replacedWhileSending = this._sending;\n    }\n\n    /**\n     * Drops the waiting updates. The update being sent, if any, still runs to its end.\n     */\n    clear(): void {\n        this._waiting = [];\n    }\n\n    /**\n     * Sends the waiting updates.\n     * @returns a promise that resolves once no update is being sent or waiting to be.\n     */\n    flush(): Promise<void> {\n        if (this.isIdle()) return Promise.resolve();\n        if (!this._flushing) {\n            let resolve: () => void;\n            const promise = new Promise<void>((r) => { resolve = r; });\n            this._flushing = {promise, resolve};\n        }\n        const {promise} = this._flushing;\n        this._next();\n        return promise;\n    }\n\n    private _next(): void {\n        if (this._sending) return;\n        const update = this._waiting.shift();\n        if (update === undefined) {\n            this._flushing?.resolve();\n            this._flushing = undefined;\n            return;\n        }\n        this._sending = true;\n        this._replacedWhileSending = false;\n        this._send(update).finally(() => this._next());\n    }\n\n    /**\n     * Sends one update and hands its result, or the error that sending or handling it raised, to the handlers.\n     *\n     * The update stops counting as being sent once, before either handler runs, so that an update a handler\n     * starts is still counted as being sent when that handler throws.\n     */\n    private async _send(update: T): Promise<void> {\n        let result: R;\n        try {\n            result = await this._handlers.send(update);\n        } catch (error) {\n            this._sending = false;\n            this._handlers.onError(update, error);\n            return;\n        }\n        this._sending = false;\n        try {\n            this._handlers.onResult(update, result, this._replacedWhileSending);\n        } catch (error) {\n            this._handlers.onError(update, error);\n        }\n    }\n}\n", "import {LngLat} from '../lng_lat.ts';\nimport {MercatorCoordinate} from '../mercator_coordinate.ts';\nimport {clamp} from '../../util/util.ts';\n\nimport type {WorldCoordinateHelper} from '../transform_interface.ts';\nimport type {TileMatrixSet} from './tile_matrix_set.ts';\n\n/**\n * How far `forward` may take an inverse from the position it came from, as a fraction of `extentAtZoom0`,\n * for the inverse to count as that position's answer: loose enough for a converter that is only approximately\n * invertible, tight enough to reject an answer from the other side of the world.\n */\nconst ROUND_TRIP_TOLERANCE = 1e-3;\n\n/**\n * How many times the line to the center of the world square is halved in the search for the last position\n * with an answer, enough to place it within a billionth of the line.\n */\nconst EDGE_SEARCH_STEPS = 30;\n\n/**\n * @experimental\n * Describes a planar coordinate reference system (CRS) together with the square, power-of-two\n * quad tile grid laid over it, so a map can render tiles that were pre-projected in that CRS.\n * Register one with {@link addProjection} and select it with the style's `projection.type`\n * or `map.setProjection({type: name})`.\n *\n * Every tile source of the map is taken to be cut in `tileMatrixSet`, and the tiles are used as they are,\n * without reprojecting their content. The map positions that grid on screen and maps lng/lat to and from it\n * through `projection`. CRS units are taken as meters wherever the map converts meters: altitudes, elevations,\n * and the camera distance.\n */\nexport type CRS = {\n    /**\n     * Name used in `projection.type`, e.g. `'EPSG:2193'` or `'custom:floor-plan'`. It must contain a colon: names\n     * without one, like `'mercator'`, `'globe'`, `'vertical-perspective'` and the pre-registered `'identity'`, are\n     * reserved for built-in projections.\n     */\n    name: string;\n    /**\n     * Converts between lng/lat (degrees) and CRS coordinates (e.g. meters easting/northing): `forward([lng, lat])`\n     * returns `[x, y]` and `inverse([x, y])` returns `[lng, lat]`. This is the shape of a proj4 converter such as\n     * `proj4('EPSG:4326', 'EPSG:2193')`, which deck.gl's custom projection view takes as well.\n     * Where `inverse` has no answer, `null`, a value that is not finite, one that `forward` does not take back to the\n     * position, or an error, as proj4 gives past the edge of world projections, the map uses the edge of the answers on the\n     * line to the center of the tile matrix set. It assumes they form one stretch from the center outwards, so a world\n     * projection's tile matrix set should be centered on its world.\n     */\n    projection: {\n        forward(position: number[]): number[];\n        inverse(position: number[]): number[] | null;\n    };\n    /**\n     * The quad tile matrix set over the CRS plane.\n     */\n    tileMatrixSet: TileMatrixSet;\n    /**\n     * The CRS as a string the workers' projection handler accepts, such as WKT or a PROJ string.\n     * GeoJSON sources need it: their data is parsed and tiled in the workers, where `projection` cannot go,\n     * so a handler set there builds the same converter from this string, see the custom CRS guide.\n     * Without it, GeoJSON sources warn and draw in the wrong place.\n     */\n    definition?: string;\n};\n\n/**\n * How many times as much as at the center of its tile matrix set a projection may stretch distances along the meridian\n * before GeoJSON sources stop placing data there, see {@link CRSWorldCoordinateHelper.latitudeRange}.\n */\nconst MAX_MERIDIAN_STRETCH = 10;\n\n/**\n * @internal\n * The world coordinate mapping for a CRS: world x/y are the CRS coordinates relative\n * to the tile matrix set origin, scaled so tile 0/0/0 is the 0..1 square, with y growing down.\n * One world unit is the zoom 0 extent, so meters per world unit is constant across the plane.\n */\nexport class CRSWorldCoordinateHelper implements WorldCoordinateHelper {\n    private readonly _crs: CRS;\n    private readonly _originX: number;\n    private readonly _originY: number;\n    private readonly _extent: number;\n    private _latitudeRange: [number, number] | undefined;\n    /** A CRS is a bounded plane: no world copies, no wrapping, and no latitude clamp. */\n    readonly wraps = false;\n\n    constructor(crs: CRS) {\n        this._crs = crs;\n        this._originX = crs.tileMatrixSet.origin[0];\n        this._originY = crs.tileMatrixSet.origin[1];\n        this._extent = crs.tileMatrixSet.extentAtZoom0;\n    }\n\n    get name(): string {\n        return this._crs.name;\n    }\n    get tileMatrixSet(): TileMatrixSet {\n        return this._crs.tileMatrixSet;\n    }\n    worldFromLngLat(lng: number, lat: number, altitude?: number): MercatorCoordinate {\n        const [crsX, crsY] = this._crs.projection.forward([lng, lat]);\n        return new MercatorCoordinate((crsX - this._originX) / this._extent, (this._originY - crsY) / this._extent, altitude === undefined ? 0 : altitude / this._extent);\n    }\n    /**\n     * World square coordinates to lng/lat. A position without an answer (the far edge of a pitched view, a drag\n     * past the edge, the buffer of a tile at the square's edge, the space around a world projection) uses the\n     * nearest position inside the world square instead, or else the last position with an answer on the line to\n     * the square's center, or else, for a converter that never leads back within the tolerance, the converter's own\n     * finite answer. A latitude past the poles is clamped to the range {@link LngLat} accepts, so the mapping is\n     * total the way the mercator inverse is.\n     */\n    lngLatFromWorld(x: number, y: number): LngLat {\n        const insideX = clamp(x, 0, 1);\n        const insideY = clamp(y, 0, 1);\n        const position = this._inverse(x, y) ?? this._inverse(insideX, insideY) ?? this._inverseTowardCenter(insideX, insideY) ?? this._finiteInverse(insideX, insideY);\n        if (!position) {\n            throw new Error(`The inverse of the projection \"${this._crs.name}\" has no answer inside its tile matrix set.`);\n        }\n        return new LngLat(position[0], clamp(position[1], -90, 90));\n    }\n    hasLngLat(x: number, y: number): boolean {\n        return this._inverse(x, y) !== null;\n    }\n    /**\n     * The CRS's inverse at a world position, or `null` where it has no answer: no finite answer, or one that\n     * `forward` does not take back to the position, as proj4 gives past the edge of a world projection.\n     */\n    private _inverse(x: number, y: number): number[] | null {\n        const position = this._finiteInverse(x, y);\n        if (!position) {\n            return null;\n        }\n        const crsX = this._originX + x * this._extent;\n        const crsY = this._originY - y * this._extent;\n        const [forwardX, forwardY] = this._crs.projection.forward(position);\n        return Math.hypot(forwardX - crsX, forwardY - crsY) <= ROUND_TRIP_TOLERANCE * this._extent ? position : null;\n    }\n    /**\n     * The converter's own inverse at a world position, or `null` where it gives `null`, a value that is not\n     * finite or an error, as proj4 does past the edge of some projections.\n     */\n    private _finiteInverse(x: number, y: number): number[] | null {\n        let position: number[] | null;\n        try {\n            position = this._crs.projection.inverse([this._originX + x * this._extent, this._originY - y * this._extent]);\n        } catch {\n            return null;\n        }\n        return position && Number.isFinite(position[0]) && Number.isFinite(position[1]) ? position : null;\n    }\n    /**\n     * The inverse at the edge of the answers on the line from a world position to the center of the world square,\n     * found by halving the line, which assumes the answers form one stretch from the center outwards; `null` when the\n     * center has no answer either.\n     */\n    private _inverseTowardCenter(x: number, y: number): number[] | null {\n        let answered = 0;\n        let unanswered = 1;\n        for (let step = 0; step < EDGE_SEARCH_STEPS; step++) {\n            const fraction = (answered + unanswered) / 2;\n            if (this._inverse(0.5 + (x - 0.5) * fraction, 0.5 + (y - 0.5) * fraction)) {\n                answered = fraction;\n            } else {\n                unanswered = fraction;\n            }\n        }\n        return this._inverse(0.5 + (x - 0.5) * answered, 0.5 + (y - 0.5) * answered);\n    }\n    metersPerWorldUnit(_x: number, _y: number): number {\n        return this._extent;\n    }\n    worldZFromAltitude(altitude: number, _lngLat: LngLat): number {\n        return altitude / this._extent;\n    }\n    /**\n     * The latitudes, `[south, north]`, from the center of the tile matrix set toward each pole, up to which the\n     * projection stretches distances along the meridian less than {@link MAX_MERIDIAN_STRETCH} times as much as at the\n     * center. GeoJSON sources move the positions past them onto them before projecting, so that what the projection\n     * cannot place, like the opposite pole of a polar projection, which projects to infinity, never reaches the map.\n     * `[-90, 90]` for a projection that stretches neither pole that much, like transverse mercator.\n     */\n    get latitudeRange(): [number, number] {\n        this._latitudeRange ??= [this._findLatitudeLimit(-90), this._findLatitudeLimit(90)];\n        return this._latitudeRange;\n    }\n    /**\n     * Walks the meridian through the center of the tile matrix set toward the pole at `pole`, a degree at a time, and\n     * returns the last latitude before the projection stretches distances along it more than\n     * {@link MAX_MERIDIAN_STRETCH} times as much as at the center, or the pole when it never does.\n     */\n    private _findLatitudeLimit(pole: number): number {\n        const center = this.lngLatFromWorld(0.5, 0.5);\n        const maxStretch = MAX_MERIDIAN_STRETCH * this._meridianStretch(center.lng, center.lat);\n        if (!(maxStretch > 0)) return pole;\n        const step = Math.sign(pole - center.lat);\n        for (let lat = center.lat; Math.abs(pole - lat) > 1; lat += step) {\n            if (!(this._meridianStretch(center.lng, lat + step) <= maxStretch)) return lat;\n        }\n        return pole;\n    }\n    /**\n     * The distance the projection puts between the position at `lng`, `lat` and the one a hundredth of a degree from\n     * it toward the equator, in CRS units.\n     */\n    private _meridianStretch(lng: number, lat: number): number {\n        const [x, y] = this._crs.projection.forward([lng, lat]);\n        const [towardEquatorX, towardEquatorY] = this._crs.projection.forward([lng, lat >= 0 ? lat - 0.01 : lat + 0.01]);\n        return Math.hypot(towardEquatorX - x, towardEquatorY - y);\n    }\n}\n\n/**\n * The identity conversion of the built-in `'identity'` projection, whose CRS coordinates are lng/lat degrees.\n */\nclass IdentityConversion {\n    forward(position: number[]): number[] {\n        return [position[0], position[1]];\n    }\n\n    inverse(position: number[]): number[] {\n        return [position[0], position[1]];\n    }\n}\n\n/**\n * The CRS behind the built-in `'identity'` projection: CRS coordinates are lng/lat degrees unchanged and\n * tile 0/0/0 spans -90..90 on both axes. It exists for image-space maps, where a square root tile keeps\n * the quad tree uniform in both directions; image coordinates are scaled into -90..90.\n */\nclass IdentityCRS implements CRS {\n    readonly name = 'identity';\n    readonly projection = new IdentityConversion();\n    readonly tileMatrixSet: TileMatrixSet = {origin: [-90, 90], extentAtZoom0: 180};\n}\n\n/**\n * @internal\n * The one identity CRS: it holds no state, so the registry and every test share this instance.\n */\nexport const identityCrs: CRS = new IdentityCRS();\n", "import {identityCrs, type CRS} from './crs.ts';\n\nimport type {ProjectionSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nconst registeredProjections = new Map<string, CRS>([[identityCrs.name, identityCrs]]);\n\n/**\n * @internal\n * Returns the registered CRS for a projection name, or `undefined` if the name is not registered\n * (an unset or expression-valued projection type is never registered).\n */\nexport function getRegisteredProjection(name: ProjectionSpecification['type']): CRS | undefined {\n    return typeof name === 'string' ? registeredProjections.get(name) : undefined;\n}\n\n/**\n * @experimental\n * Registers a planar coordinate reference system so it can be used as a map projection.\n * After registration the CRS name is accepted, as a plain name, by the style's `projection.type` and by\n * `map.setProjection({type: name})`. Every tile source of such a map is taken to be cut in the quad tile grid\n * described by `tileMatrixSet`, and the map does not reproject tile content.\n * The pre-registered `'identity'` projection is an identity CRS over lng/lat degrees, where tile 0/0/0\n * spans -90..90 on both axes. The name of a registered CRS needs a colon, like `'EPSG:2193'` or\n * `'custom:floor-plan'`: names without one are reserved for built-in projections.\n *\n * A map in a registered projection never renders world copies and never wraps across an antimeridian.\n *\n * @param crs - the CRS\n * @throws Error if the name has no colon, is already registered, or if `tileMatrixSet.extentAtZoom0` is not positive\n * @example\n * ```ts\n * // NZTM2000 (EPSG:2193) with the LINZ NZTM2000Quad tile matrix set, using proj4js for the math.\n * // The origin and extent below come from the NZTM2000Quad TileMatrixSet definition;\n * // copy them from that definition rather than from this example.\n * proj4.defs('EPSG:2193', '+proj=tmerc +lat_0=0 +lon_0=173 +k=0.9996 +x_0=1600000 +y_0=10000000 +ellps=GRS80 +units=m +no_defs');\n * addProjection({\n *     name: 'EPSG:2193',\n *     projection: proj4('EPSG:4326', 'EPSG:2193'),\n *     tileMatrixSet: {\n *         origin: [-3260586.7284, 10438190.1652], // top-left of tile 0/0/0, from the NZTM2000Quad TileMatrixSet\n *         extentAtZoom0: 10018754.1714 // width of tile 0/0/0 in meters, from the NZTM2000Quad TileMatrixSet\n *     }\n * });\n * const map = new Map({\n *     container: 'map',\n *     style: {version: 8, projection: {type: 'EPSG:2193'}, sources: {}, layers: []}\n * });\n * ```\n */\nexport function addProjection(crs: CRS): void {\n    if (!crs.name.includes(':')) {\n        throw new Error(`The projection name \"${crs.name}\" needs a colon, like \"EPSG:2193\" or \"custom:equal-earth\": names without one are reserved for built-in projections.`);\n    }\n    if (registeredProjections.has(crs.name)) {\n        throw new Error(`A projection called \"${crs.name}\" already exists.`);\n    }\n    if (!(crs.tileMatrixSet.extentAtZoom0 > 0)) {\n        throw new Error(`The projection \"${crs.name}\" needs a tileMatrixSet.extentAtZoom0 greater than zero.`);\n    }\n    registeredProjections.set(crs.name, crs);\n}\n\n/**\n * @experimental\n * Removes a projection registered with {@link addProjection}. Maps currently using it keep working\n * until their projection changes. Built-in projections, whose names have no colon, cannot be removed.\n *\n * @param name - the name the projection was registered with\n * @throws Error if the name has no colon\n * @example\n * ```ts\n * removeProjection('EPSG:2193');\n * ```\n */\nexport function removeProjection(name: string): void {\n    if (!name.includes(':')) {\n        throw new Error(`The projection name \"${name}\" has no colon, so it is reserved for built-in projections, which cannot be removed.`);\n    }\n    registeredProjections.delete(name);\n}\n", "import {ErrorEvent, Evented} from '../util/evented.ts';\nimport {MapSourceDataEvent, type SourceEventType} from '../ui/events.ts';\nimport {ensureError, extend, warnOnce, type ExactlyOne} from '../util/util.ts';\nimport {EXTENT} from '../data/extent.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {browser} from '../util/browser.ts';\nimport {applySourceDiff, mergeSourceDiffs, toUpdateable} from './geojson_source_diff.ts';\nimport {getGeoJSONBounds} from '../util/geojson_bounds.ts';\nimport {isAbortError} from '../util/abort_error.ts';\nimport {MessageType} from '../util/actor_messages.ts';\nimport {tileIdToLngLatBounds} from '../tile/tile_id_to_lng_lat_bounds.ts';\nimport {UpdateQueue} from '../util/update_queue.ts';\nimport {getRegisteredProjection} from '../geo/projection/projection_crud.ts';\nimport {identityCrs} from '../geo/projection/crs.ts';\n\nimport type {LngLatBounds} from '../geo/lng_lat_bounds.ts';\nimport type {Source} from './source.ts';\nimport type {Map} from '../ui/map.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {Actor} from '../util/actor.ts';\nimport type {GeoJSONWorkerSourceLoadDataResult} from '../util/actor_messages.ts';\nimport type {GeoJSONSourceSpecification, PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {GeoJSONFeatureId, GeoJSONSourceDiff} from './geojson_source_diff.ts';\nimport type {GeoJSONWorkerOptions, LoadGeoJSONParameters} from './geojson_worker_source.ts';\nimport type {WorkerTileParameters} from './worker_source.ts';\n\n/**\n * Options object for GeoJSONSource.\n */\nexport type GeoJSONSourceOptions = GeoJSONSourceSpecification & {\n    workerOptions?: GeoJSONWorkerOptions;\n    collectResourceTiming?: boolean;\n    data: GeoJSON.GeoJSON | string;\n};\n\nexport type GeoJSONSourceInternalOptions = {\n    data?: GeoJSON.GeoJSON | string | undefined;\n    cluster?: boolean;\n    clusterMaxZoom?: number;\n    clusterRadius?: number;\n    clusterMinPoints?: number;\n    generateId?: boolean;\n};\n\n/**\n * @internal\n */\nexport type GeoJSONSourceShouldReloadTileOptions = {\n    /**\n     * Refresh all tiles that WILL contain these bounds.\n     */\n    affectedBounds: LngLatBounds[];\n};\n\n/**\n * The cluster options to set\n */\nexport type SetClusterOptions = {\n    /**\n     * Whether or not to cluster\n     */\n    cluster?: boolean;\n    /**\n     * The cluster's max zoom.\n     * Non-integer values are rounded to the closest integer due to supercluster integer value requirements.\n     */\n    clusterMaxZoom?: number;\n    /**\n     * The cluster's radius\n     */\n    clusterRadius?: number;\n};\n\n/**\n * The cluster options currently configured on a source, as returned by `getClusterOptions`\n */\nexport type GetClusterOptions = {\n    /**\n     * Whether or not the source is clustered\n     */\n    cluster: boolean;\n    /**\n     * The cluster's max zoom\n     */\n    clusterMaxZoom: number;\n    /**\n     * The cluster's radius, in pixels\n     */\n    clusterRadius: number;\n};\n\n/**\n * A change to the data a source's worker already has: a diff to it and a refresh of its clusters, applied in\n * that order.\n */\ntype GeoJSONWorkerChange = {\n    diff?: GeoJSONSourceDiff;\n    /**\n     * Whether the worker has to regroup its clusters with the current options. New data needs no such\n     * refresh, since it is sent with the options current at that time.\n     */\n    updateCluster?: true;\n};\n\n/**\n * One update of a source's data in the worker: either new data, or a change to the data it has.\n */\ntype GeoJSONWorkerUpdate = {data: GeoJSON.GeoJSON | string} | GeoJSONWorkerChange;\n\n/**\n * A source containing GeoJSON.\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.)\n *\n * GeoJSON is tiled internally for rendering. Features exposed from rendered tiles and related events come from vector-tile data, so GeoJSON foreign members that cannot be represented by the vector-tile format are not preserved there. Keep that data separately, or map it to supported feature properties, if you need it after tiling.\n *\n * @group Sources\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n *     type: 'geojson',\n *     data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'\n * });\n * ```\n *\n * @example\n * ```ts\n * map.addSource('some id', {\n *    type: 'geojson',\n *    data: {\n *        \"type\": \"FeatureCollection\",\n *        \"features\": [{\n *            \"type\": \"Feature\",\n *            \"properties\": {},\n *            \"geometry\": {\n *                \"type\": \"Point\",\n *                \"coordinates\": [\n *                    -76.53063297271729,\n *                    39.18174077994108\n *                ]\n *            }\n *        }]\n *    }\n * });\n * ```\n *\n * @example\n * ```ts\n * map.getSource('some id').setData({\n *   \"type\": \"FeatureCollection\",\n *   \"features\": [{\n *       \"type\": \"Feature\",\n *       \"properties\": { \"name\": \"Null Island\" },\n *       \"geometry\": {\n *           \"type\": \"Point\",\n *           \"coordinates\": [ 0, 0 ]\n *       }\n *   }]\n * });\n * ```\n * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/draw-geojson-points/)\n * @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-geojson-line/)\n * @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-heatmap-layer/)\n * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/create-and-style-clusters/)\n */\nexport class GeoJSONSource extends Evented<SourceEventType> implements Source {\n    type: 'geojson';\n    id: string;\n    minzoom: number;\n    maxzoom: number;\n    tileSize: number;\n    attribution: string;\n    promoteId: PromoteIdSpecification;\n\n    isTileClipped: boolean;\n    reparseOverscaled: boolean;\n    _data: ExactlyOne<{\n        url: string;\n        geojson: GeoJSON.GeoJSON;\n        updateable: globalThis.Map<GeoJSONFeatureId, GeoJSON.Feature>;\n    }>;\n    _options: GeoJSONSourceInternalOptions;\n    workerOptions: GeoJSONWorkerOptions;\n    map: Map;\n    actorPromise: Promise<Actor>;\n    _workerUpdates: UpdateQueue<GeoJSONWorkerUpdate, GeoJSONWorkerSourceLoadDataResult>;\n    _collectResourceTiming: boolean;\n    _removed: boolean;\n\n    /** @internal */\n    constructor(id: string, options: GeoJSONSourceOptions, dispatcher: Dispatcher, eventedParent: Evented) {\n        super();\n\n        this.id = id;\n\n        // `type` is a property rather than a constant to make it easy for 3rd\n        // parties to use GeoJSONSource to build their own source types.\n        this.type = 'geojson';\n\n        this.minzoom = 0;\n        this.maxzoom = 18;\n        this.tileSize = 512;\n        this.isTileClipped = true;\n        this.reparseOverscaled = true;\n        this._removed = false;\n        this._workerUpdates = new UpdateQueue({\n            send: (update) => this._sendWorkerUpdate(update),\n            onResult: (update, result, replaced) => this._onWorkerUpdateResult(update, result, replaced),\n            onError: (_update, error) => this._onWorkerUpdateError(error)\n        });\n        if (options.data !== undefined) this._workerUpdates.enqueue({data: options.data});\n\n        this.actorPromise = dispatcher.getActor();\n        this.setEventedParent(eventedParent);\n\n        this._data = typeof options.data === 'string' ? {url: options.data} : {geojson: options.data};\n        this._options = extend({}, options);\n\n        this._collectResourceTiming = options.collectResourceTiming;\n\n        if (options.maxzoom !== undefined) this.maxzoom = options.maxzoom;\n        if (options.type) this.type = options.type;\n        if (options.attribution) this.attribution = options.attribution;\n        this.promoteId = options.promoteId;\n\n        if (options.clusterMaxZoom !== undefined && this.maxzoom <= options.clusterMaxZoom) {\n            warnOnce(`The maxzoom value \"${this.maxzoom}\" is expected to be greater than the clusterMaxZoom value \"${options.clusterMaxZoom}\".`);\n        }\n\n        // sent to the worker, along with `url: ...` or `data: literal geojson`,\n        // so that it can load/parse/index the geojson data\n        // extending with `options.workerOptions` helps to make it easy for\n        // third-party sources to hack/reuse GeoJSONSource.\n        this.workerOptions = extend({\n            source: this.id,\n            geojsonVtOptions: {\n                buffer: this._pixelsToTileUnits(options.buffer !== undefined ? options.buffer : 128),\n                tolerance: this._pixelsToTileUnits(options.tolerance !== undefined ? options.tolerance : 0.375),\n                extent: EXTENT,\n                maxZoom: this.maxzoom,\n                lineMetrics: options.lineMetrics || false,\n                generateId: options.generateId || false,\n                promoteId: this._promoteIdKey,\n                cluster: options.cluster || false,\n                clusterOptions: {\n                    maxZoom: this._getClusterMaxZoom(options.clusterMaxZoom),\n                    minPoints: Math.max(2, options.clusterMinPoints || 2),\n                    extent: EXTENT,\n                    radius: this._pixelsToTileUnits(options.clusterRadius || 50),\n                    log: false,\n                    generateId: options.generateId || false\n                },\n            },\n            clusterProperties: options.clusterProperties,\n            filter: options.filter\n        }, options.workerOptions);\n    }\n\n    /** The `promoteId` property name, when it is a plain string. */\n    private get _promoteIdKey(): string | undefined {\n        return typeof this.promoteId === 'string' ? this.promoteId : undefined;\n    }\n\n    private _pixelsToTileUnits(pixelValue: number): number {\n        return pixelValue * (EXTENT / this.tileSize);\n    }\n\n    private _tileUnitsToPixels(tileUnitValue: number): number {\n        return tileUnitValue / (EXTENT / this.tileSize);\n    }\n\n    private _getClusterMaxZoom(clusterMaxZoom: number): number {\n        const effectiveClusterMaxZoom = clusterMaxZoom ? Math.round(clusterMaxZoom) : this.maxzoom - 1;\n        if (!(Number.isInteger(clusterMaxZoom) || clusterMaxZoom === undefined)) {\n            warnOnce(`Integer expected for option 'clusterMaxZoom': provided value \"${clusterMaxZoom}\" rounded to \"${effectiveClusterMaxZoom}\"`);\n        }\n        return effectiveClusterMaxZoom;\n    }\n\n    async load(): Promise<void> {\n        if (this._workerUpdates.isIdle()) {\n            warnOnce(`No pending worker updates for GeoJSONSource ${this.id}.`);\n            return;\n        }\n        await this._workerUpdates.flush();\n    }\n\n    onAdd(map: Map): void {\n        this.map = map;\n        this.load();\n    }\n\n    /**\n     * Sets the GeoJSON data and re-renders the map.\n     *\n     * @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.\n     */\n    setData(data: GeoJSON.GeoJSON | string): Promise<void> {\n        this._data = typeof data === 'string' ? {url: data} : {geojson: data};\n        this._workerUpdates.replace({data});\n        return this._workerUpdates.flush();\n    }\n\n    /**\n     * Updates the source's GeoJSON, and re-renders the map.\n     *\n     * For sources with lots of features, this method can be used to make updates more quickly.\n     *\n     * This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature,\n     * or by using the promoteId option to specify which property should be used as the ID.\n     *\n     * It is an error to call updateData on a source that did not have unique IDs for each of its features already.\n     *\n     * Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error.\n     *\n     * @param diff - The changes that need to be applied.\n     */\n    updateData(diff: GeoJSONSourceDiff): Promise<void> {\n        const waiting = this._getWaitingWorkerChange();\n        if (waiting) {\n            waiting.diff = mergeSourceDiffs(waiting.diff, diff, this._promoteIdKey);\n        } else {\n            this._workerUpdates.enqueue({diff});\n        }\n        return this._workerUpdates.flush();\n    }\n\n    /**\n     * Allows to get the source's actual GeoJSON data.\n     *\n     * Data set as a URL is returned once it has loaded.\n     *\n     * @returns a promise which resolves to the source's actual GeoJSON data\n     */\n    async getData(): Promise<GeoJSON.GeoJSON> {\n        while (this._data.url) {\n            await this.once('data');\n        }\n        if (this._data.geojson) {\n            return this._data.geojson;\n        }\n        return {\n            type: 'FeatureCollection',\n            features: Array.from(this._data.updateable.values())\n        };\n    }\n\n    /**\n     * Allows getting the source's boundaries.\n     * If there's a problem with the source's data, it will return an empty {@link LngLatBounds}.\n     * @returns a promise which resolves to the source's boundaries\n     */\n    async getBounds(): Promise<LngLatBounds> {\n        return getGeoJSONBounds(await this.getData());\n    }\n\n    /**\n     * To disable/enable clustering on the source options\n     * @param options - The options to set\n     * @example\n     * ```ts\n     * map.getSource('some id').setClusterOptions({cluster: false});\n     * map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14});\n     * ```\n     */\n    setClusterOptions(options: SetClusterOptions): Promise<void> {\n        this.workerOptions.geojsonVtOptions.cluster = options.cluster;\n        if (options.clusterRadius !== undefined) {\n            this.workerOptions.geojsonVtOptions.clusterOptions.radius = this._pixelsToTileUnits(options.clusterRadius);\n        }\n        if (options.clusterMaxZoom !== undefined) {\n            this.workerOptions.geojsonVtOptions.clusterOptions.maxZoom = this._getClusterMaxZoom(options.clusterMaxZoom);\n        }\n        if (!this._workerUpdates.some((update) => 'data' in update)) {\n            const waiting = this._getWaitingWorkerChange();\n            if (waiting) {\n                waiting.updateCluster = true;\n            } else {\n                this._workerUpdates.enqueue({updateCluster: true});\n            }\n        }\n        return this._workerUpdates.flush();\n    }\n\n    /**\n     * The change queued last for the worker, which a later change merges into, if it is still waiting to be sent.\n     * Returns `undefined` when nothing is waiting or the update queued last is new data, which a change has to\n     * wait behind instead.\n     */\n    private _getWaitingWorkerChange(): GeoJSONWorkerChange | undefined {\n        const top = this._workerUpdates.top();\n        return top && !('data' in top) ? top : undefined;\n    }\n\n    /**\n     * Gets the cluster options currently configured on the source.\n     * The returned values mirror the options accepted by `setClusterOptions`.\n     *\n     * @returns the source's current cluster options\n     * @example\n     * ```ts\n     * const {cluster, clusterMaxZoom, clusterRadius} = map.getSource('some id').getClusterOptions();\n     * ```\n     */\n    getClusterOptions(): GetClusterOptions {\n        const {cluster, clusterOptions} = this.workerOptions.geojsonVtOptions;\n        return {\n            cluster,\n            clusterMaxZoom: clusterOptions.maxZoom,\n            clusterRadius: this._tileUnitsToPixels(clusterOptions.radius)\n        };\n    }\n\n    /**\n     * For clustered sources, fetches the zoom at which the given cluster expands.\n     *\n     * @param clusterId - The value of the cluster's `cluster_id` property.\n     * @returns a promise that is resolved with the zoom number\n     */\n    async getClusterExpansionZoom(clusterId: number): Promise<number> {\n        return (await this.actorPromise).sendAsync({type: MessageType.getClusterExpansionZoom, data: {type: this.type, clusterId, source: this.id}});\n    }\n\n    /**\n     * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).\n     *\n     * @param clusterId - The value of the cluster's `cluster_id` property.\n     * @returns a promise that is resolved when the features are retrieved\n     */\n    async getClusterChildren(clusterId: number): Promise<GeoJSON.Feature[]> {\n        return (await this.actorPromise).sendAsync({type: MessageType.getClusterChildren, data: {type: this.type, clusterId, source: this.id}});\n    }\n\n    /**\n     * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).\n     *\n     * @param clusterId - The value of the cluster's `cluster_id` property.\n     * @param limit - The maximum number of features to return.\n     * @param offset - The number of features to skip (e.g. for pagination).\n     * @returns a promise that is resolved when the features are retrieved\n     * @example\n     * Retrieve cluster leaves on click\n     * ```ts\n     * map.on('click', 'clusters', (e) => {\n     *   let features = map.queryRenderedFeatures(e.point, {\n     *     layers: ['clusters']\n     *   });\n     *\n     *   let clusterId = features[0].properties.cluster_id;\n     *   let pointCount = features[0].properties.point_count;\n     *   let clusterSource = map.getSource('clusters');\n     *\n     *   const features = await clusterSource.getClusterLeaves(clusterId, pointCount);\n     *   // Print cluster leaves in the console\n     *   console.log('Cluster leaves:', features);\n     * });\n     * ```\n     */\n    async getClusterLeaves(clusterId: number, limit: number, offset: number): Promise<GeoJSON.Feature[]> {\n        return (await this.actorPromise).sendAsync({type: MessageType.getClusterLeaves, data: {\n            type: this.type,\n            source: this.id,\n            clusterId,\n            limit,\n            offset\n        }});\n    }\n\n    /**\n     * Create the parameters object that will be sent to the worker and used to load GeoJSON.\n     */\n    private async _getLoadGeoJSONParameters(update: GeoJSONWorkerUpdate): Promise<LoadGeoJSONParameters> {\n        const params: LoadGeoJSONParameters = extend({type: this.type, source: this.id}, this.workerOptions);\n        const crs = this._getCRSParameters();\n        if (crs) params.crs = crs;\n\n        if (!('data' in update)) {\n            if (update.diff) params.dataDiff = update.diff;\n            if (update.updateCluster) params.updateCluster = true;\n            return params;\n        }\n\n        if (typeof update.data === 'string') {\n            params.request = await this.map._requestManager.transformRequest(browser.resolveURL(update.data), ResourceType.Source);\n            params.request.collectResourceTiming = this._collectResourceTiming;\n            return params;\n        }\n\n        params.data = update.data;\n        return params;\n    }\n\n    /**\n     * The map's registered projection as the workers take it, see {@link LoadGeoJSONParameters.crs}. The workers can\n     * build a projection's converter from its `definition`, or the built-in identity one without, so any other\n     * projection is left out with a warning.\n     */\n    private _getCRSParameters(): LoadGeoJSONParameters['crs'] | undefined {\n        const crs = getRegisteredProjection(this.map?.style?.projection?.name);\n        if (!crs) return undefined;\n        if (!crs.definition && crs !== identityCrs) {\n            warnOnce(`GeoJSON source \"${this.id}\" is drawn in the wrong place: the projection \"${crs.name}\" has no \\`definition\\` to project its data with.`);\n            return undefined;\n        }\n        return {name: crs.name, definition: crs.definition, tileMatrixSet: crs.tileMatrixSet};\n    }\n\n    /**\n     * Responsible for invoking WorkerSource's geojson.loadData target, which\n     * handles loading the geojson data and preparing to serve it up as tiles,\n     * using geojson-vt or supercluster as appropriate.\n     */\n    private async _sendWorkerUpdate(update: GeoJSONWorkerUpdate): Promise<GeoJSONWorkerSourceLoadDataResult> {\n        this.fire(new MapSourceDataEvent('dataloading'));\n        const params = await this._getLoadGeoJSONParameters(update);\n        return (await this.actorPromise).sendAsync({type: MessageType.loadData, data: params});\n    }\n\n    /**\n     * Applies the result of a worker update to this source and fires the events that reload its tiles.\n     *\n     * The worker sends back the data it loaded from a URL, which becomes this source's copy of the data.\n     *\n     * An update that a `setData` call replaced while it was being sent leaves this source's copy of the data alone,\n     * since the data its result describes is no longer the source's, and still fires its events.\n     *\n     * A diff reloads only the tiles it touches, but a cluster refresh can regroup points on any tile,\n     * so an update that carries one reloads every tile, whatever diff comes with it. So does any diff on a map in a\n     * registered projection, where the lng/lat box of a tile, see {@link tileIdToLngLatBounds}, can miss part of it.\n     */\n    private _onWorkerUpdateResult(update: GeoJSONWorkerUpdate, result: GeoJSONWorkerSourceLoadDataResult, replaced: boolean) {\n        if (this._removed || result.abandoned) {\n            this.fire(new MapSourceDataEvent('dataabort'));\n            return;\n        }\n\n        if (result.data && !replaced) {\n            this._data = {geojson: result.data};\n        }\n\n        const diff = 'data' in update || replaced ? undefined : update.diff;\n        const affectedGeometries = this._applyDiffToSource(diff);\n        const refreshesClusters = !('data' in update) && update.updateCluster;\n        const reloadsEveryTile = refreshesClusters || this.map?.style?.projection?.worldCoordinateHelper.wraps === false;\n        const shouldReloadTileOptions = reloadsEveryTile ? undefined : this._getShouldReloadTileOptions(affectedGeometries);\n\n        const eventData: {resourceTiming?: PerformanceResourceTiming[]} = {};\n        this._applyResourceTiming(eventData, result);\n\n        // Fire the metadata event to let the TileManager know it's ok to start requesting tiles.\n        this.fire(new MapSourceDataEvent('data', {...eventData, sourceDataType: 'metadata'}));\n        this.fire(new MapSourceDataEvent('data', {...eventData, sourceDataType: 'content', shouldReloadTileOptions}));\n    }\n\n    private _onWorkerUpdateError(error: unknown) {\n        if (this._removed) {\n            this.fire(new MapSourceDataEvent('dataabort'));\n            return;\n        }\n        this.fire(new ErrorEvent(ensureError(error)));\n    }\n\n    /**\n     * Apply resource timing data to the event object.\n     */\n    private _applyResourceTiming(eventData: {resourceTiming?: PerformanceResourceTiming[]}, result: GeoJSONWorkerSourceLoadDataResult) {\n        if (!this._collectResourceTiming) return;\n\n        const timingData = result.resourceTiming?.[this.id];\n        if (!timingData) return;\n\n        const resourceTiming = timingData.slice(0);\n        if (!resourceTiming?.length) return;\n\n        extend(eventData, {resourceTiming});\n    }\n\n    /**\n     * Apply a diff to this source's data and return the affected feature geometries.\n     * @param diff - The {@link GeoJSONSourceDiff} to apply.\n     * @returns The affected geometries, or undefined if the diff is not applicable or all geometries are affected,\n     * as they are whenever the source is clustered: a changed point can regroup clusters on any tile.\n     */\n    private _applyDiffToSource(diff: GeoJSONSourceDiff): GeoJSON.Geometry[] | undefined {\n        if (!diff) {\n            return undefined;\n        }\n\n        const promoteId = this._promoteIdKey;\n\n        // Lazily convert `this._data` to updateable if it's not already\n        if (!this._data.url && !this._data.updateable) {\n            const updateable = toUpdateable(this._data.geojson, promoteId);\n            if (!updateable) throw new Error(`GeoJSONSource \"${this.id}\": GeoJSON data is not compatible with updateData`);\n            this._data = {updateable};\n        }\n\n        if (!this._data.updateable) {\n            return undefined;\n        }\n        const affectedGeometries = applySourceDiff(this._data.updateable, diff, promoteId);\n\n        if (diff.removeAll || this.workerOptions.geojsonVtOptions.cluster) {\n            return undefined;\n        }\n\n        return affectedGeometries;\n    }\n\n    /**\n     * Get options for use in determining whether to reload a tile based on the modified features.\n     * @param affectedGeometries - The feature geometries affected by the update.\n     * @returns A {@link GeoJSONSourceShouldReloadTileOptions} object which contains an array of affected bounds caused by the update.\n     */\n    private _getShouldReloadTileOptions(affectedGeometries: GeoJSON.Geometry[]): GeoJSONSourceShouldReloadTileOptions | undefined {\n        if (!affectedGeometries) return undefined;\n\n        const affectedBounds = affectedGeometries\n            .filter(Boolean)\n            .map(g => getGeoJSONBounds(g));\n\n        return {affectedBounds};\n    }\n\n    /**\n     * Determine whether a tile should be reloaded based on a set of options associated with a {@link MapSourceDataChangedEvent}.\n     * @internal\n     */\n    shouldReloadTile(tile: Tile, {affectedBounds}: GeoJSONSourceShouldReloadTileOptions): boolean {\n        if (tile.state === 'loading') {\n            return true;\n        }\n        if (tile.state === 'unloaded') {\n            return false;\n        }\n\n        // Update the tile if contained or will contain an updated feature.\n        const {buffer, extent} = this.workerOptions.geojsonVtOptions;\n        const tileBounds = tileIdToLngLatBounds(\n            tile.tileID.canonical,\n            buffer / extent,\n            this.map.style.projection.worldCoordinateHelper\n        );\n        for (const bounds of affectedBounds) {\n            if (tileBounds.intersects(bounds)) {\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n    loaded(): boolean {\n        return this._workerUpdates.isIdle();\n    }\n\n    async loadTile(tile: Tile): Promise<void> {\n        const message = !tile.actor ?  MessageType.loadTile :  MessageType.reloadTile;\n        tile.actor = await this.actorPromise;\n        const params: WorkerTileParameters = {\n            type: this.type,\n            uid: tile.uid,\n            tileID: tile.tileID,\n            zoom: tile.tileID.overscaledZ,\n            maxZoom: this.maxzoom,\n            tileSize: this.tileSize,\n            source: this.id,\n            pixelRatio: this.map.getPixelRatio(),\n            showCollisionBoxes: this.map.showCollisionBoxes,\n            promoteId: this.promoteId,\n            subdivisionGranularity: this.map.style.projection.subdivisionGranularity\n        };\n\n        tile.abortController = new AbortController();\n        try {\n            const data = await (await this.actorPromise).sendAsync({type: message, data: params}, tile.abortController);\n            delete tile.abortController;\n            tile.unloadVectorData();\n\n            if (!tile.aborted) {\n                tile.loadVectorData(data, this.map.style, message ===  MessageType.reloadTile);\n            }\n        } catch (err) {\n            delete tile.abortController;\n            if (tile.aborted || isAbortError(err)) {\n                return;\n            }\n            throw err;\n        }\n    }\n\n    async abortTile(tile: Tile): Promise<void> {\n        if (tile.abortController) {\n            tile.abortController.abort();\n            delete tile.abortController;\n        }\n        tile.aborted = true;\n    }\n\n    async unloadTile(tile: Tile): Promise<void> {\n        tile.unloadVectorData();\n        await (await this.actorPromise).sendAsync({type: MessageType.removeTile, data: {uid: tile.uid, type: this.type, source: this.id}});\n    }\n\n    /**\n     * Drops the worker updates waiting to be sent, which would otherwise rebuild the worker's state for a source\n     * that is gone. The update being sent ends in a `dataabort` event.\n     */\n    onRemove(): void {\n        this._removed = true;\n        this._workerUpdates.clear();\n        this.actorPromise.then(actor => actor.sendAsync({type: MessageType.removeSource, data: {type: this.type, source: this.id}}));\n    }\n\n    serialize(): GeoJSONSourceSpecification {\n        return extend({}, this._options, {\n            type: this.type,\n            data: this._data.updateable ?\n                {\n                    type: 'FeatureCollection',\n                    features: Array.from(this._data.updateable.values())\n                } :\n                this._data.url || this._data.geojson\n        });\n    }\n\n    hasTransition() {\n        return false;\n    }\n}\n", "import {Uniform1i, Uniform1f, Uniform2f, Uniform3f, Uniform4f} from '../uniform_binding.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {RasterStyleLayer} from '../../style/style_layer/raster_style_layer.ts';\nimport type Point from '@mapbox/point-geometry';\n\n/**\n * How the image of a raster tile or image source is warped onto its corner coordinates: the two\n * perspective terms of the projective mapping from the unit square onto them, followed by how far\n * that mapping is blended towards the bilinear one.\n */\nexport type RasterImageWarp = [number, number, number];\n\n/** The bilinear warp, which is also the affine one that a rectangle or a parallelogram needs. */\nexport const bilinearImageWarp: RasterImageWarp = [0, 0, 1];\n\nexport type RasterUniformsType = {\n    'u_tl_parent': Uniform2f;\n    'u_scale_parent': Uniform1f;\n    'u_buffer_scale': Uniform1f;\n    'u_image_warp': Uniform3f;\n    'u_fade_t': Uniform1f;\n    'u_opacity': Uniform1f;\n    'u_image0': Uniform1i;\n    'u_image1': Uniform1i;\n    'u_brightness_low': Uniform1f;\n    'u_brightness_high': Uniform1f;\n    'u_saturation_factor': Uniform1f;\n    'u_contrast_factor': Uniform1f;\n    'u_spin_weights': Uniform3f;\n    'u_coords_top': Uniform4f;\n    'u_coords_bottom': Uniform4f;\n};\n\nconst rasterUniforms = (context: Context, locations: UniformLocations): RasterUniformsType => ({\n    'u_tl_parent': new Uniform2f(context, locations.u_tl_parent),\n    'u_scale_parent': new Uniform1f(context, locations.u_scale_parent),\n    'u_buffer_scale': new Uniform1f(context, locations.u_buffer_scale),\n    'u_image_warp': new Uniform3f(context, locations.u_image_warp),\n    'u_fade_t': new Uniform1f(context, locations.u_fade_t),\n    'u_opacity': new Uniform1f(context, locations.u_opacity),\n    'u_image0': new Uniform1i(context, locations.u_image0),\n    'u_image1': new Uniform1i(context, locations.u_image1),\n    'u_brightness_low': new Uniform1f(context, locations.u_brightness_low),\n    'u_brightness_high': new Uniform1f(context, locations.u_brightness_high),\n    'u_saturation_factor': new Uniform1f(context, locations.u_saturation_factor),\n    'u_contrast_factor': new Uniform1f(context, locations.u_contrast_factor),\n    'u_spin_weights': new Uniform3f(context, locations.u_spin_weights),\n    'u_coords_top': new Uniform4f(context, locations.u_coords_top),\n    'u_coords_bottom': new Uniform4f(context, locations.u_coords_bottom)\n});\n\nconst rasterUniformValues = (\n    parentTL: [number, number],\n    parentScaleBy: number,\n    fade: {\n        mix: number;\n        opacity: number;\n    },\n    layer: RasterStyleLayer,\n    cornerCoords: Point[],\n    imageWarp: RasterImageWarp,\n): UniformValues<RasterUniformsType> => ({\n    'u_tl_parent': parentTL,\n    'u_scale_parent': parentScaleBy,\n    // If u_buffer_scale is ever something else than a constant 1,\n    // the north/south pole handling in the vertex shader might need modification\n    // so that the texture coordinares for poles always lie beyond the edge of the texture.\n    // Right now the coordinates are placed right at the texture border.\n    'u_buffer_scale': 1,\n    'u_image_warp': imageWarp,\n    'u_fade_t': fade.mix,\n    'u_opacity': fade.opacity * layer.paint.get('raster-opacity'),\n    'u_image0': 0,\n    'u_image1': 1,\n    'u_brightness_low': layer.paint.get('raster-brightness-min'),\n    'u_brightness_high': layer.paint.get('raster-brightness-max'),\n    'u_saturation_factor': saturationFactor(layer.paint.get('raster-saturation')),\n    'u_contrast_factor': contrastFactor(layer.paint.get('raster-contrast')),\n    'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate')),\n    'u_coords_top': [cornerCoords[0].x, cornerCoords[0].y, cornerCoords[1].x, cornerCoords[1].y],\n    'u_coords_bottom': [cornerCoords[3].x, cornerCoords[3].y, cornerCoords[2].x, cornerCoords[2].y]\n});\n\nfunction spinWeights(angle) {\n    angle *= Math.PI / 180;\n    const s = Math.sin(angle);\n    const c = Math.cos(angle);\n    return [\n        (2 * c + 1) / 3,\n        (-Math.sqrt(3) * s - c + 1) / 3,\n        (Math.sqrt(3) * s - c + 1) / 3\n    ];\n}\n\nfunction contrastFactor(contrast) {\n    return contrast > 0 ?\n        1 / (1 - contrast) :\n        1 + contrast;\n}\n\nfunction saturationFactor(saturation) {\n    return saturation > 0 ?\n        1 - 1 / (1.001 - saturation) :\n        -saturation;\n}\n\nexport {rasterUniforms, rasterUniformValues};\n", "import type {SegmentVector} from '../data/segment.ts';\nimport type {VertexBuffer} from '../webgl/vertex_buffer.ts';\nimport type {IndexBuffer} from '../webgl/index_buffer.ts';\n\nexport class Mesh {\n    vertexBuffer: VertexBuffer;\n    indexBuffer: IndexBuffer;\n    segments: SegmentVector;\n\n    constructor(vertexBuffer: VertexBuffer, indexBuffer: IndexBuffer, segments: SegmentVector) {\n        this.vertexBuffer = vertexBuffer;\n        this.indexBuffer = indexBuffer;\n        this.segments = segments;\n    }\n\n    destroy(): void {\n        this.vertexBuffer.destroy();\n        this.indexBuffer.destroy();\n        this.segments.destroy();\n\n        this.vertexBuffer = null;\n        this.indexBuffer = null;\n        this.segments = null;\n    }\n}\n", "import {createLayout, type StructArrayLayout} from '../util/struct_array.ts';\n\nconst posAttributes: StructArrayLayout = createLayout([\n    {name: 'a_pos', type: 'Int16', components: 2}\n]);\n\nexport default posAttributes;\n", "import {Mesh} from '../render/mesh.ts';\nimport {PosArray, TriangleIndexArray} from '../data/array_types.g.ts';\nimport {SegmentVector} from '../data/segment.ts';\nimport {NORTH_POLE_Y, SOUTH_POLE_Y} from '../render/subdivision.ts';\nimport {EXTENT} from '../data/extent.ts';\nimport posAttributes from '../data/pos_attributes.ts';\n\nimport type {Context} from '../webgl/context.ts';\n\n/**\n * The size of border region for stencil masks, in internal tile coordinates.\n * Used for globe rendering.\n */\nconst EXTENT_STENCIL_BORDER = EXTENT / 128;\n\n/**\n * Options for generating a tile mesh.\n * Can optionally configure any of the following:\n * - mesh subdivision granularity\n * - border presence\n * - special geometry for the north and/or south pole\n */\nexport type CreateTileMeshOptions = {\n    /**\n     * Specifies how much should the tile mesh be subdivided.\n     * A value of 1 leads to a simple quad, a value of 4 will result in a grid of 4x4 quads.\n     */\n    granularity?: number;\n    /**\n     * When true, an additional ring of quads is generated along the border, always extending `EXTENT_STENCIL_BORDER` units away from the main mesh.\n     */\n    generateBorders?: boolean;\n    /**\n     * When true, additional geometry is generated along the north edge of the mesh, connecting it to the pole special vertex position.\n     * This geometry replaces the mesh border along this edge, if one is present.\n     */\n    extendToNorthPole?: boolean;\n    /**\n     * When true, additional geometry is generated along the south edge of the mesh, connecting it to the pole special vertex position.\n     * This geometry replaces the mesh border along this edge, if one is present.\n     */\n    extendToSouthPole?: boolean;\n};\n\n/**\n * Stores the prepared vertex and index buffer bytes for a mesh.\n */\nexport type TileMesh = {\n    /**\n     * The vertex data. Each vertex is two 16 bit signed integers, one for X, one for Y.\n     */\n    vertices: ArrayBuffer;\n    /**\n     * The index data. Each triangle is defined by three indices. The indices may either be 16 bit or 32 bit unsigned integers,\n     * depending on the mesh creation arguments and on whether the mesh can fit into 16 bit indices.\n     */\n    indices: ArrayBuffer;\n    /**\n     * A helper boolean indicating whether the indices are 32 bit.\n     */\n    uses32bitIndices: boolean;\n};\n\n/**\n * Describes desired type of vertex indices, either 16 bit uint, 32 bit uint, or, if undefined, any of the two options.\n */\nexport type IndicesType = '32bit' | '16bit' | undefined;\n\n/**\n * @internal\n * Creates a mesh of a quad that covers the entire tile (covering positions in range 0..EXTENT),\n * is optionally subdivided into finer quads, optionally includes a border\n * and optionally extends to the north and/or special pole vertices.\n * Also allocates and populates WebGL buffers for the mesh.\n * Forces 16 bit indices that are used throughout MapLibre.\n * @param context - The WebGL context wrapper.\n * @param options - Specify options for tile mesh creation such as granularity or border.\n * @returns The mesh vertices and indices, already allocated and uploaded into WebGL buffers.\n */\nexport function createTileMeshWithBuffers(context: Context, options: CreateTileMeshOptions): Mesh {\n    const tileMesh = createTileMesh(options, '16bit');\n    const vertices = PosArray.deserialize({\n        arrayBuffer: tileMesh.vertices,\n        length: tileMesh.vertices.byteLength / 2 / 2, // Two values per vertex, 16 bit\n    });\n    const indices = TriangleIndexArray.deserialize({\n        arrayBuffer: tileMesh.indices,\n        length: tileMesh.indices.byteLength / 2 / 3, // Three values per triangle, 16 bit\n    });\n    return new Mesh(\n        context.createVertexBuffer(vertices, posAttributes.members),\n        context.createIndexBuffer(indices),\n        SegmentVector.simpleSegment(0, 0, vertices.length, indices.length)\n    );\n}\n\n/**\n * Creates a mesh of a quad that covers the entire tile (covering positions in range 0..EXTENT),\n * is optionally subdivided into finer quads, optionally includes a border\n * and optionally extends to the north and/or special pole vertices.\n * Additionally the resulting mesh indices type can be specified using `forceIndicesSize`.\n * @example\n * ```\n * // Creating a mesh for a tile that can be used for raster layers, hillshade, etc.\n * const meshBuffers = createTileMesh({\n *     granularity: map.style.projection.subdivisionGranularity.tile.getGranularityForZoomLevel(tileID.z),\n *     generateBorders: true,\n *     extendToNorthPole: tileID.y === 0,\n *     extendToSouthPole: tileID.y === (1 << tileID.z) - 1,\n * }, '16bit');\n * ```\n * @see [Add a custom layer with tiles to a globe](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-custom-layer-with-tiles-to-a-globe/)\n * @param options - Specify options for tile mesh creation such as granularity or border.\n * @param forceIndicesSize - Specifies what indices type to use. The values '32bit' and '16bit' force their respective indices size. If undefined, the mesh may use either size, and will pick 16 bit indices if possible. If '16bit' is specified and the mesh exceeds 65536 vertices, an exception is thrown.\n * @returns Typed arrays of the mesh vertices and indices.\n */\nexport function createTileMesh(options: CreateTileMeshOptions, forceIndicesSize?: IndicesType): TileMesh {\n    // We only want to generate the north/south border if the tile\n    // does NOT border the north/south edge of the mercator range.\n    const granularity = options.granularity !== undefined ? Math.max(options.granularity, 1) : 1;\n\n    const quadsPerAxisX = granularity + (options.generateBorders ? 2 : 0); // two extra quads for border\n    const quadsPerAxisY = granularity + ((options.extendToNorthPole || options.generateBorders) ? 1 : 0) + (options.extendToSouthPole || options.generateBorders ? 1 : 0);\n    const verticesPerAxisX = quadsPerAxisX + 1; // one more vertex than quads\n    const verticesPerAxisY = quadsPerAxisY + 1; // one more vertex than quads\n    const offsetX = options.generateBorders ? -1 : 0;\n    const offsetY = (options.generateBorders || options.extendToNorthPole) ? -1 : 0;\n    const endX = granularity + (options.generateBorders ? 1 : 0);\n    const endY = granularity + ((options.generateBorders || options.extendToSouthPole) ? 1 : 0);\n\n    const vertexCount = verticesPerAxisX * verticesPerAxisY;\n    const indexCount = quadsPerAxisX * quadsPerAxisY * 6;\n\n    const overflows16bitIndices = verticesPerAxisX * verticesPerAxisY > (1 << 16);\n\n    if (overflows16bitIndices && forceIndicesSize === '16bit') {\n        throw new Error('Granularity is too large and meshes would not fit inside 16 bit vertex indices.');\n    }\n\n    const use32bitIndices = overflows16bitIndices || forceIndicesSize === '32bit';\n\n    const vertices = new Int16Array(vertexCount * 2);\n\n    let vertexId = 0;\n\n    for (let y = offsetY; y <= endY; y++) {\n        for (let x = offsetX; x <= endX; x++) {\n            let vx = x / granularity * EXTENT;\n            if (x === -1) {\n                vx = -EXTENT_STENCIL_BORDER;\n            }\n            if (x === granularity + 1) {\n                vx = EXTENT + EXTENT_STENCIL_BORDER;\n            }\n            let vy = y / granularity * EXTENT;\n            if (y === -1) {\n                vy = options.extendToNorthPole ? NORTH_POLE_Y : (-EXTENT_STENCIL_BORDER);\n            }\n            if (y === granularity + 1) {\n                vy = options.extendToSouthPole ? SOUTH_POLE_Y : EXTENT + EXTENT_STENCIL_BORDER;\n            }\n\n            vertices[vertexId++] = vx;\n            vertices[vertexId++] = vy;\n        }\n    }\n\n    const indices = use32bitIndices ? new Uint32Array(indexCount) : new Uint16Array(indexCount);\n\n    let indexId = 0;\n\n    for (let y = 0; y < quadsPerAxisY; y++) {\n        for (let x = 0; x < quadsPerAxisX; x++) {\n            const v0 = x + y * verticesPerAxisX;\n            const v1 = (x + 1) + y * verticesPerAxisX;\n            const v2 = x + (y + 1) * verticesPerAxisX;\n            const v3 = (x + 1) + (y + 1) * verticesPerAxisX;\n\n            // v0----v1\n            //  |  / |\n            //  | /  |\n            // v2----v3\n            indices[indexId++] = v0;\n            indices[indexId++] = v2;\n            indices[indexId++] = v1;\n\n            indices[indexId++] = v1;\n            indices[indexId++] = v2;\n            indices[indexId++] = v3;\n        }\n    }\n\n    return {\n        vertices: vertices.buffer.slice(0),\n        indices: indices.buffer.slice(0),\n        uses32bitIndices: use32bitIndices,\n    };\n}\n", "import {CanonicalTileID} from '../tile/tile_id.ts';\nimport {ErrorEvent, Evented} from '../util/evented.ts';\nimport {MapSourceDataEvent, type SourceEventType} from '../ui/events.ts';\nimport {ImageRequest} from '../util/image_request.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {Texture} from '../webgl/texture.ts';\nimport {LngLat} from '../geo/lng_lat.ts';\nimport {ensureError, MAX_TILE_ZOOM} from '../util/util.ts';\nimport {Bounds} from '../geo/bounds.ts';\nimport {isAbortError} from '../util/abort_error.ts';\nimport {\n    bilinearImageWarp,\n    type RasterImageWarp\n} from '../webgl/program/raster_program.ts';\nimport {mat2} from 'gl-matrix';\nimport {createTileMeshWithBuffers} from '../util/create_tile_mesh.ts';\n\nimport type {Source} from './source.ts';\nimport type {MercatorCoordinate} from '../geo/mercator_coordinate.ts';\nimport type {CanvasSourceSpecification} from './canvas_source.ts';\nimport type {Map} from '../ui/map.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {\n    ImageSourceSpecification,\n    VideoSourceSpecification\n} from '@maplibre/maplibre-gl-style-spec';\nimport type Point from '@mapbox/point-geometry';\nimport type {Context} from '../webgl/context.ts';\nimport type {Mesh} from '../render/mesh.ts';\n\n/**\n * How many grid cells per axis the mesh of a subdivided quad has. Within a cell the bilinear warp\n * is still approximated by one mapping per triangle, so the error falls off with the cell size.\n */\nconst SUBDIVIDED_QUAD_GRANULARITY = 16;\n\n/**\n * How much a warp may foreshorten the image, as the ratio between the largest and the smallest\n * homogeneous denominator over the quad, while staying purely projective. Ordinary oblique imagery\n * stays well below it.\n */\nconst PROJECTIVE_FORESHORTENING = 4;\n\n/**\n * The foreshortening at which a warp is taken to be purely bilinear.\n *\n * The denominator vanishes on the warp's vanishing line, and that line touches the quad exactly when\n * the quad degenerates into a triangle, so foreshortening grows without bound as a corner approaches\n * the diagonal between its neighbours. Left alone, such a quad keeps a valid but wildly lopsided\n * warp, squeezing nearly the whole image into a sliver along one edge and magnifying a handful of\n * texels over the rest of the quad.\n */\nconst BILINEAR_FORESHORTENING = 512;\n\n/**\n * Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the image.\n * The coordinates start at the top left corner of the image and proceed in clockwise order.\n * They do not have to represent a rectangle.\n */\nexport type Coordinates = [[number, number], [number, number], [number, number], [number, number]];\n\n/**\n * @experimental\n * How an {@link ImageSource} warps its image onto its four coordinates, for the cases where the\n * coordinates do not form a rectangle.\n *\n * - `perspective` maps the image as the perspective view of a plane, which is what georeferenced\n *   photography and any other image of a flat scene wants: straight lines in the image stay\n *   straight, and the image foreshortens towards its more distant edge.\n * - `flat` interpolates the image between the four coordinates bilinearly, pinning it like a rubber\n *   sheet, which is what an image being reshaped by hand wants: every corner moves the image only\n *   near itself, and the result is stable no matter how far a corner is dragged. Straight lines in\n *   the image only stay straight while they run parallel to its edges, and there is no\n *   foreshortening, in the same sense as the CSS `transform-style: flat`.\n * - `auto`, the default, is `perspective` while the coordinates plausibly describe a perspective\n *   view, and blends continuously towards `flat` as they stop doing so, which they do as a corner\n *   approaches the diagonal between its two neighbours.\n *\n * Coordinates with no perspective view at all - a concave, self-crossing or collinear quad - are\n * always warped flat, whichever of these is set.\n */\nexport type ImageSourceWarp = 'auto' | 'perspective' | 'flat';\n\n/**\n * An already-decoded image that can be handed to an {@link ImageSource} directly,\n * without a network request.\n */\nexport type ImageSourceImage = HTMLImageElement | HTMLCanvasElement | ImageBitmap | ImageData;\n\n/**\n * The options object for the {@link ImageSource.updateImage} method.\n *\n * Provide exactly one of `url` (to load an image over the network) or `image`\n * (an already-decoded image to display directly, without a network request).\n */\nexport type UpdateImageOptions = {\n    /**\n     * The image coordinates\n     */\n    coordinates?: Coordinates;\n} & ({\n    /**\n     * The image URL to load.\n     */\n    url: string;\n} | {\n    /**\n     * An already-decoded image (`HTMLImageElement`, `HTMLCanvasElement`, `ImageBitmap` or `ImageData`)\n     * to display directly, without a network request.\n     */\n    image: ImageSourceImage;\n});\n\nexport type CanonicalTileRange = {\n    minTileY: number;\n    maxTileY: number;\n\n    /**\n     * Image can exceed the boundary of a single \"world\" (tile 0/0/0),\n     * so we need to know the tile range for wrapping.\n     */\n    minTileXWrapped: number;\n    maxTileXWrapped: number;\n    minWrap: number;\n    maxWrap: number;\n};\n\n/**\n * A data source containing an image.\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-image) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * // add to map\n * map.addSource('some id', {\n *    type: 'image',\n *    url: 'https://www.maplibre.org/images/foo.png',\n *    coordinates: [\n *        [-76.54, 39.18],\n *        [-76.52, 39.18],\n *        [-76.52, 39.17],\n *        [-76.54, 39.17]\n *    ]\n * });\n *\n * // update coordinates\n * let mySource = map.getSource('some id');\n * mySource.setCoordinates([\n *     [-76.54335737228394, 39.18579907229748],\n *     [-76.52803659439087, 39.1838364847587],\n *     [-76.5295386314392, 39.17683392507606],\n *     [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * // update url and coordinates simultaneously\n * mySource.updateImage({\n *    url: 'https://www.maplibre.org/images/bar.png',\n *    coordinates: [\n *        [-76.54335737228394, 39.18579907229748],\n *        [-76.52803659439087, 39.1838364847587],\n *        [-76.5295386314392, 39.17683392507606],\n *        [-76.54520273208618, 39.17876344106642]\n *    ]\n * })\n *\n * // update with an already-decoded image (no network request)\n * const bitmap = await createImageBitmap(myCanvas);\n * mySource.updateImage({image: bitmap});\n *\n * // create an empty source (no url), then feed it entirely via updateImage\n * map.addSource('empty id', {\n *    type: 'image',\n *    coordinates: [\n *        [-76.54, 39.18],\n *        [-76.52, 39.18],\n *        [-76.52, 39.17],\n *        [-76.54, 39.17]\n *    ]\n * });\n * (map.getSource('empty id') as ImageSource).updateImage({image: bitmap});\n *\n * map.removeSource('some id');  // remove\n * ```\n */\nexport class ImageSource extends Evented<SourceEventType> implements Source {\n    type: string;\n    id: string;\n    minzoom: number;\n    maxzoom: number;\n    tileSize: number;\n    url: string;\n    /**\n     * This object is used to store the range of terrain tiles that overlap with this tile.\n     * It is relevant for image tiles, as the image exceeds single tile boundaries.\n     */\n    terrainTileRanges: {[zoom: string]: CanonicalTileRange};\n\n    coordinates: Coordinates;\n    tiles: {[_: string]: Tile};\n    options: any;\n    dispatcher: Dispatcher;\n    map: Map;\n    texture: Texture | null;\n    image: ImageSourceImage;\n    tileID: CanonicalTileID;\n    tileCoords: Point[];\n    imageWarp: RasterImageWarp = bilinearImageWarp;\n    flippedWindingOrder: boolean = false;\n    _loaded: boolean;\n    _abortController: AbortController;\n    private _warp: ImageSourceWarp = 'auto';\n    private _imageDirty: boolean = false;\n    /**\n     * Whether the image has to be warped over a subdivided mesh instead of a pair of triangles,\n     * because {@link imageWarp} is not the affine mapping that a parallelogram gets.\n     */\n    private _subdividedQuad: boolean = false;\n    private _subdividedMesh: Mesh | null = null;\n\n    /** @internal */\n    constructor(id: string, options: ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n        super();\n        this.id = id;\n        this.dispatcher = dispatcher;\n        this.coordinates = options.coordinates;\n\n        this.type = 'image';\n        this.minzoom = 0;\n        this.maxzoom = 22;\n        this.tileSize = 512;\n        this.tiles = {};\n        this._loaded = false;\n\n        this.setEventedParent(eventedParent);\n\n        this.options = options;\n    }\n\n    async load(newCoordinates?: Coordinates): Promise<void> {\n        if (this.options.url === undefined) {\n            // A url-less source starts empty and displays nothing until updateImage provides content.\n            this._loaded = true;\n            this._finishLoading();\n            return;\n        }\n\n        this._loaded = false;\n        this.fire(new MapSourceDataEvent('dataloading'));\n\n        this.url = this.options.url;\n\n        this._abortController = new AbortController();\n        try {\n            const image = await ImageRequest.transformAndGetImage(this.map._requestManager, this.url, ResourceType.Image, this._abortController);\n            this._abortController = null;\n            this._loaded = true;\n\n            if (image?.data) {\n                this._setImage(image.data);\n                if (newCoordinates) {\n                    this.coordinates = newCoordinates;\n                }\n                this._finishLoading();\n            } else {\n                this.fire(new ErrorEvent(new Error(`Could not load image ${this.url}: the response is empty`)));\n            }\n        } catch (err) {\n            // In case of abort error, the aborter may have started a new request so we don't want to clear its abort controller.\n            if (isAbortError(err)) return;\n            this._abortController = null;\n            this._loaded = true;\n            this.fire(new ErrorEvent(ensureError(err)));\n        }\n    }\n\n    loaded(): boolean {\n        return this._loaded;\n    }\n\n    /**\n     * Updates the image and, optionally, the coordinates. To avoid having the image flash after changing,\n     * set the `raster-fade-duration` paint property on the raster layer to 0.\n     *\n     * Provide exactly one of `url` (to fetch a new image over the network) or `image` (an\n     * already-decoded `HTMLImageElement`, `HTMLCanvasElement`, `ImageBitmap` or `ImageData` to\n     * display directly, without a network request).\n     *\n     * @param options - The options object.\n     */\n    updateImage(options: UpdateImageOptions): this {\n        if (this._abortController) {\n            this._abortController.abort();\n            this._abortController = null;\n        }\n\n        if ('image' in options) {\n            // Use the already-decoded image directly, skipping the network request.\n            this._loaded = true;\n            this._setImage(options.image);\n            if (options.coordinates) {\n                this.coordinates = options.coordinates;\n            }\n            this._finishLoading();\n            return this;\n        }\n\n        if (!options.url) {\n            return this;\n        }\n\n        this.options.url = options.url;\n        this.load(options.coordinates);\n        return this;\n    }\n\n    /** Loaded tiles hold `this.texture`, so the wrapper has to outlive the images in it. */\n    private _setImage(image: ImageSourceImage): void {\n        this.image = image;\n        this._imageDirty = true;\n    }\n\n    /**\n     * @internal\n     * The mesh the image is drawn with, or null to use the tile mesh of the current projection.\n     *\n     * The raster vertex shader evaluates {@link imageWarp} per vertex, so a pair of triangles only\n     * samples it at the four corners. That is enough for the affine mapping of a parallelogram, and\n     * for a purely projective mapping, whose straight lines survive linear interpolation across the\n     * diagonal. Anything in between is neither, and would be textured as two independently warped\n     * halves with a visible seam along that diagonal, so it needs the warp evaluated per grid cell.\n     *\n     * A projection that subdivides its own tile meshes already does this, so it keeps them.\n     */\n    getMesh(context: Context, projectionSubdividesTiles: boolean): Mesh | null {\n        if (!this._subdividedQuad || projectionSubdividesTiles) {\n            return null;\n        }\n        this._subdividedMesh ??= createTileMeshWithBuffers(context, {granularity: SUBDIVIDED_QUAD_GRANULARITY});\n        return this._subdividedMesh;\n    }\n\n    /** Teardown only: dropping the reference alone leaves the allocation to the GC. */\n    private _disposeTexture(): void {\n        this.texture?.destroy();\n        this.texture = null;\n    }\n\n    _finishLoading(): void {\n        if (this.map) {\n            try {\n                this.setCoordinates(this.coordinates);\n                this.fire(new MapSourceDataEvent('data', {sourceDataType: 'metadata'}));\n            } catch (err) {\n                this.fire(new ErrorEvent(ensureError(err)));\n            }\n        }\n    }\n\n    onAdd(map: Map): void {\n        this.map = map;\n        this.load();\n    }\n\n    onRemove(): void {\n        if (this._abortController) {\n            this._abortController.abort();\n            this._abortController = null;\n        }\n        this._disposeTexture();\n        this._subdividedMesh?.destroy();\n        this._subdividedMesh = null;\n        this.image = null;\n        this.tiles = {};\n    }\n\n    /**\n     * @experimental\n     * Sets how the image is warped onto its coordinates and re-renders the map.\n     *\n     * This only has an effect while the coordinates do not form a rectangle, and it is not part of\n     * the style specification, so it does not survive `map.setStyle`.\n     *\n     * @param warp - The warp to use, see {@link ImageSourceWarp}.\n     *\n     * @example\n     * ```ts\n     * // Keep the image pinned to its corners while the user drags them around.\n     * map.getSource('some id').setWarp('flat');\n     * ```\n     */\n    setWarp(warp: ImageSourceWarp): this {\n        if (this._warp === warp) {\n            return this;\n        }\n        this._warp = warp;\n        if (this.tileCoords) {\n            this.setCoordinates(this.coordinates);\n        }\n        return this;\n    }\n\n    /**\n     * @experimental\n     * Returns how the image is warped onto its coordinates.\n     *\n     * @returns The warp in use, see {@link ImageSourceWarp}.\n     */\n    getWarp(): ImageSourceWarp {\n        return this._warp;\n    }\n\n    /**\n     * Sets the image's coordinates and re-renders the map.\n     *\n     * @param coordinates - Four geographical coordinates,\n     * represented as arrays of longitude and latitude numbers, which define the corners of the image.\n     * The coordinates start at the top left corner of the image and proceed in clockwise order.\n     * They do not have to represent a rectangle.\n     */\n    setCoordinates(coordinates: Coordinates): this {\n        this.coordinates = coordinates;\n\n        // Calculate which mercator tile is suitable for rendering the video in\n        // and create a buffer with the corner coordinates. These coordinates\n        // may be outside the tile, because raster tiles aren't clipped when rendering.\n\n        // transform the geo coordinates into (zoom 0) tile space coordinates of the map's projection\n        const worldCoordinateHelper = this.map.style.projection.worldCoordinateHelper;\n        const cornerCoords = coordinates.map(coordinate => {\n            const lngLat = LngLat.convert(coordinate);\n            return worldCoordinateHelper.worldFromLngLat(lngLat.lng, lngLat.lat);\n        });\n\n        // Compute the coordinates of the tile we'll use to hold this image's\n        // render data\n        this.tileID = getCoordinatesCenterTileID(cornerCoords);\n\n        // Compute tiles overlapping with the image. We need to know for which\n        // terrain tiles we have to render the image.\n        this.terrainTileRanges = this._getOverlappingTileRanges(cornerCoords);\n\n        // Constrain min/max zoom to our tile's zoom level in order to force\n        // TileManager to request this tile (no matter what the map's zoom\n        // level)\n        this.minzoom = this.maxzoom = this.tileID.z;\n\n        // Transform the corner coordinates into the coordinate space of our\n        // tile.\n        this.tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round());\n        this.imageWarp = calculateImageWarp(this.tileCoords, this._warp);\n        // A purely projective warp survives a pair of triangles, because its straight lines are\n        // straight in both, and so does any warp of a parallelogram, which is affine either way.\n        // Anything else is textured as two independently warped halves without a subdivided mesh.\n        this._subdividedQuad = this.imageWarp[2] > 0 && !isParallelogram(this.tileCoords);\n        this.flippedWindingOrder = hasWrongWindingOrder(this.tileCoords);\n\n        this.fire(new MapSourceDataEvent('data', {sourceDataType: 'content'}));\n        return this;\n    }\n\n    prepare(): void {\n        if (Object.keys(this.tiles).length === 0 || !this.image) {\n            return;\n        }\n\n        const context = this.map.painter.context;\n        const gl = context.gl;\n\n        if (!this.texture) {\n            this.texture = new Texture(context, this.image, gl.RGBA);\n            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n        } else if (this._imageDirty) {\n            this.texture.update(this.image);\n            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n        }\n        this._imageDirty = false;\n\n        let newTilesLoaded = false;\n        for (const w in this.tiles) {\n            const tile = this.tiles[w];\n            if (tile.state !== 'loaded') {\n                tile.state = 'loaded';\n                tile.texture = this.texture;\n                newTilesLoaded = true;\n            }\n        }\n\n        if (newTilesLoaded) {\n            this.fire(new MapSourceDataEvent('data', {sourceDataType: 'idle', sourceId: this.id}));\n        }\n    }\n\n    async loadTile(tile: Tile): Promise<void> {\n        // We have a single tile -- whose coordinates are this.tileID -- that\n        // covers the image we want to render.  If that's the one being\n        // requested, set it up with the image; otherwise, mark the tile as\n        // `errored` to indicate that we have no data for it.\n        // If the world wraps, we may have multiple \"wrapped\" copies of the\n        // single tile.\n        if (this.tileID?.equals(tile.tileID.canonical)) {\n            this.tiles[String(tile.tileID.wrap)] = tile;\n            tile.buckets = {};\n        } else {\n            tile.state = 'errored';\n        }\n    }\n\n    serialize(): ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification {\n        const spec: ImageSourceSpecification = {\n            type: 'image',\n            coordinates: this.coordinates\n        };\n        if (this.options.url !== undefined) {\n            spec.url = this.options.url;\n        }\n        return spec;\n    }\n\n    hasTransition() {\n        return false;\n    }\n\n    /**\n     * Given a list of coordinates, determine overlapping tile ranges for all zoom levels.\n     *\n     * @returns Overlapping tile ranges for all zoom levels.\n     * @internal\n     */\n    private _getOverlappingTileRanges(\n        coords: MercatorCoordinate[]\n    ): {[zoom: string]: CanonicalTileRange} {\n        const {minX, minY, maxX, maxY} = Bounds.fromPoints(coords);\n\n        const ranges: {[zoom: string]: CanonicalTileRange} = {};\n\n        for (let z = 0; z <= MAX_TILE_ZOOM; z++) {\n            const tilesAtZoom = Math.pow(2, z);\n            const minTileX = Math.floor(minX * tilesAtZoom);\n            const minTileY = Math.floor(minY * tilesAtZoom);\n            const maxTileX = Math.floor(maxX * tilesAtZoom);\n            const maxTileY = Math.floor(maxY * tilesAtZoom);\n\n            const minTileXWrapped = ((minTileX % tilesAtZoom) + tilesAtZoom) % tilesAtZoom;\n            const maxTileXWrapped = maxTileX % tilesAtZoom;\n            const minWrap = Math.floor(minTileX / tilesAtZoom);\n            const maxWrap = Math.floor(maxTileX / tilesAtZoom);\n\n            ranges[z] = {\n                minWrap,\n                maxWrap,\n                minTileXWrapped,\n                maxTileXWrapped,\n                minTileY,\n                maxTileY\n            };\n        }\n\n        return ranges;\n    }\n}\n\n/**\n * Given a list of coordinates, get their center as a coordinate.\n *\n * @returns centerpoint\n * @internal\n */\nexport function getCoordinatesCenterTileID(coords: MercatorCoordinate[]): CanonicalTileID {\n    const bounds = Bounds.fromPoints(coords);\n\n    const dx = bounds.width();\n    const dy = bounds.height();\n    const dMax = Math.max(dx, dy);\n    const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2));\n    const tilesAtZoom = Math.pow(2, zoom);\n\n    return new CanonicalTileID(\n        zoom,\n        Math.floor((bounds.minX + bounds.maxX) / 2 * tilesAtZoom),\n        Math.floor((bounds.minY + bounds.maxY) / 2 * tilesAtZoom));\n}\n\nfunction hasWrongWindingOrder(coords: Point[]) {\n    const e0x = coords[1].x - coords[0].x;\n    const e0y = coords[1].y - coords[0].y;\n    const e1x = coords[2].x - coords[0].x;\n    const e1y = coords[2].y - coords[0].y;\n\n    const crossProduct = e0x * e1y - e0y * e1x;\n\n    return crossProduct < 0;\n}\n\n/**\n * How the image is warped onto its coordinates, given the corners in tile space and what the user\n * asked for. The projective warp is the perspective view of a plane, so it is the one a photograph\n * wants; the bilinear warp is a rubber sheet pinned at the corners, and is the only one left once\n * the corners stop describing a perspective view at all.\n *\n * Based on Paul S. Heckbert, \"Fundamentals of Texture Mapping and Image\n * Warping\", UCB/CSD-89-516, 1989, section 2.2.3 and appendix A.2.\n *\n * @see https://www2.eecs.berkeley.edu/Pubs/TechRpts/1989/5504.html\n * @see https://www.cs.cmu.edu/~ph/texfund/texfund.pdf\n */\nfunction calculateImageWarp(cornerCoords: Point[], warp: ImageSourceWarp): RasterImageWarp {\n    // A parallelogram is warped affinely either way, and skipping the math keeps the common case of\n    // a rectangle free of the signed zeroes that dividing an exactly zero numerator produces.\n    if (warp === 'flat' || isParallelogram(cornerCoords)) {\n        return bilinearImageWarp;\n    }\n\n    const [topLeft, topRight, bottomRight, bottomLeft] = cornerCoords;\n    const sumX = topLeft.x - topRight.x + bottomRight.x - bottomLeft.x;\n    const sumY = topLeft.y - topRight.y + bottomRight.y - bottomLeft.y;\n    const basis: mat2 = [\n        topRight.x - bottomRight.x, topRight.y - bottomRight.y,\n        bottomLeft.x - bottomRight.x, bottomLeft.y - bottomRight.y\n    ];\n    const [rightX, rightY, downX, downY] = basis;\n    const determinant = mat2.determinant(basis);\n    const perspectiveX = (sumX * downY - downX * sumY) / determinant;\n    const perspectiveY = (rightX * sumY - sumX * rightY) / determinant;\n\n    // The homogeneous denominator at the four corners of the unit square, normalized to one at the\n    // top left. Its spread is how much the warp foreshortens the image, and it stays finite and\n    // positive over the whole quad exactly while the quad is a perspective view of the image, so\n    // this one comparison also rejects a collinear, concave or self-crossing quad. A degenerate\n    // determinant reaches it as an infinite or not-a-number spread.\n    const denominators = [1, 1 + perspectiveX, 1 + perspectiveX + perspectiveY, 1 + perspectiveY];\n    const foreshortening = Math.max(...denominators) / Math.min(...denominators);\n    const blend = warp === 'perspective' ? 0 : bilinearBlend(foreshortening);\n    if (!(foreshortening >= 1 && foreshortening <= BILINEAR_FORESHORTENING) || blend >= 1) {\n        return bilinearImageWarp;\n    }\n\n    return [perspectiveX, perspectiveY, blend];\n}\n\n/**\n * How far a warp of the given foreshortening is blended towards the bilinear one, ramping from\n * purely projective at {@link PROJECTIVE_FORESHORTENING} to purely bilinear at\n * {@link BILINEAR_FORESHORTENING}. Blending rather than switching keeps the image continuous as the\n * quad is reshaped: the two warps only agree for a parallelogram, and diverge by roughly a tenth of\n * the quad per unit of foreshortening, so a switch would visibly displace the image.\n */\nfunction bilinearBlend(foreshortening: number): number {\n    const ramp = (1 - PROJECTIVE_FORESHORTENING / foreshortening) /\n        (1 - PROJECTIVE_FORESHORTENING / BILINEAR_FORESHORTENING);\n    return Math.max(0, ramp);\n}\n\nfunction isParallelogram(cornerCoords: Point[]): boolean {\n    const [topLeft, topRight, bottomRight, bottomLeft] = cornerCoords;\n    return topLeft.x + bottomRight.x === topRight.x + bottomLeft.x &&\n        topLeft.y + bottomRight.y === topRight.y + bottomLeft.y;\n}\n", "import {getVideo} from '../util/ajax.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {ImageSource} from './image_source.ts';\nimport {Texture} from '../webgl/texture.ts';\nimport {ErrorEvent} from '../util/evented.ts';\nimport {MapSourceDataEvent} from '../ui/events.ts';\nimport {ensureError} from '../util/util.ts';\nimport {ValidationError} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {Map} from '../ui/map.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {Evented} from '../util/evented.ts';\nimport type {VideoSourceSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A data source containing video.\n * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-video) for detailed documentation of options.)\n *\n * @group Sources\n *\n * @example\n * ```ts\n * // add to map\n * map.addSource('some id', {\n *    type: 'video',\n *    url: [\n *        'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',\n *        'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'\n *    ],\n *    coordinates: [\n *        [-76.54, 39.18],\n *        [-76.52, 39.18],\n *        [-76.52, 39.17],\n *        [-76.54, 39.17]\n *    ]\n * });\n *\n * // update\n * let mySource = map.getSource('some id');\n * mySource.setCoordinates([\n *     [-76.54335737228394, 39.18579907229748],\n *     [-76.52803659439087, 39.1838364847587],\n *     [-76.5295386314392, 39.17683392507606],\n *     [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * map.removeSource('some id');  // remove\n * ```\n * @see [Add a video](https://maplibre.org/maplibre-gl-js/docs/examples/video-on-a-map/)\n *\n * Note that when rendered as a raster layer, the layer's `raster-fade-duration` property will cause the video to fade in.\n * This happens when playback is started, paused and resumed, or when the video's coordinates are updated. To avoid this behavior,\n * set the layer's `raster-fade-duration` property to `0`.\n */\nexport class VideoSource extends ImageSource {\n    options: VideoSourceSpecification;\n    urls: string[];\n    video: HTMLVideoElement;\n    roundZoom: boolean;\n\n    private _onPlayingHandler = () => {\n        this.map?.triggerRepaint();\n    };\n\n    constructor(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n        super(id, options, dispatcher, eventedParent);\n        this.roundZoom = true;\n        this.type = 'video';\n        this.options = options;\n    }\n\n    async load(): Promise<void> {\n        this._loaded = false;\n        const options = this.options;\n\n        this.urls = [];\n        for (const url of options.urls) {\n            this.urls.push((await this.map._requestManager.transformRequest(url, ResourceType.Source)).url);\n        }\n        try {\n            const video = await getVideo(this.urls);\n            this._loaded = true;\n            if (!video) {\n                return;\n            }\n            this.video = video;\n            this.video.loop = true;\n\n            // Start repainting when video starts playing. hasTransition() will then return\n            // true to trigger additional frames as long as the videos continues playing.\n            this.video.addEventListener('playing', this._onPlayingHandler);\n\n            if (this.map) {\n                this.video.play();\n            }\n\n            this._finishLoading();\n        } catch (err) {\n            this.fire(new ErrorEvent(ensureError(err)));\n        }\n    }\n\n    /**\n     * Pauses the video.\n     */\n    pause(): void {\n        if (this.video) {\n            this.video.pause();\n        }\n    }\n\n    /**\n     * Plays the video.\n     */\n    play(): void {\n        if (this.video) {\n            this.video.play();\n        }\n    }\n\n    /**\n     * Sets playback to a timestamp, in seconds.\n     */\n    seek(seconds: number): void {\n        if (this.video) {\n            const seekableRange = this.video.seekable;\n            if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) {\n                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.`)));\n            } else this.video.currentTime = seconds;\n        }\n    }\n\n    /**\n     * Returns the HTML `video` element.\n     *\n     * @returns The HTML `video` element.\n     */\n    getVideo(): HTMLVideoElement {\n        return this.video;\n    }\n\n    onAdd(map: Map): void {\n        if (this.map) return;\n        this.map = map;\n        this.load();\n        if (this.video) {\n            this.video.play();\n            this.setCoordinates(this.coordinates);\n        }\n    }\n\n    onRemove(): void {\n        super.onRemove();\n        if (this.video) {\n            this.video.removeEventListener('playing', this._onPlayingHandler);\n            this.video.pause();\n        }\n    }\n\n    /**\n     * Sets the video's coordinates and re-renders the map.\n     */\n    prepare(): this {\n        if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) {\n            return; // not enough data for current position\n        }\n\n        const context = this.map.painter.context;\n        const gl = context.gl;\n\n        if (!this.texture) {\n            this.texture = new Texture(context, this.video, gl.RGBA);\n            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n        } else if (!this.video.paused) {\n            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n            gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video);\n        }\n\n        let newTilesLoaded = false;\n        for (const w in this.tiles) {\n            const tile = this.tiles[w];\n            if (tile.state !== 'loaded') {\n                tile.state = 'loaded';\n                tile.texture = this.texture;\n                newTilesLoaded = true;\n            }\n        }\n\n        if (newTilesLoaded) {\n            this.fire(new MapSourceDataEvent('data', {sourceDataType: 'idle', sourceId: this.id}));\n        }\n    }\n\n    serialize(): VideoSourceSpecification {\n        return {\n            type: 'video',\n            urls: this.urls,\n            coordinates: this.coordinates\n        };\n    }\n\n    hasTransition(): boolean {\n        return this.video && !this.video.paused;\n    }\n}\n", "import {ImageSource} from './image_source.ts';\nimport {Texture} from '../webgl/texture.ts';\nimport {ErrorEvent} from '../util/evented.ts';\nimport {MapSourceDataEvent} from '../ui/events.ts';\nimport {ValidationError} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {Map} from '../ui/map.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {Evented} from '../util/evented.ts';\n\n/**\n * Options to add a canvas source type to the map.\n */\nexport type CanvasSourceSpecification = {\n    /**\n     * Source type. Must be `\"canvas\"`.\n     */\n    type: 'canvas';\n    /**\n     * Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs.\n     */\n    coordinates: [[number, number], [number, number], [number, number], [number, number]];\n    /**\n     * 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.\n     * @defaultValue true\n     */\n    animate?: boolean;\n    /**\n     * Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the `HTMLCanvasElement` itself.\n     */\n    canvas?: string | HTMLCanvasElement;\n};\n\n/**\n * A data source containing the contents of an HTML canvas. See {@link CanvasSourceSpecification} for detailed documentation of options.\n *\n * @group Sources\n *\n * @example\n * ```ts\n * // add to map\n * map.addSource('some id', {\n *    type: 'canvas',\n *    canvas: 'idOfMyHTMLCanvas',\n *    animate: true,\n *    coordinates: [\n *        [-76.54, 39.18],\n *        [-76.52, 39.18],\n *        [-76.52, 39.17],\n *        [-76.54, 39.17]\n *    ]\n * });\n *\n * // update\n * let mySource = map.getSource('some id');\n * mySource.setCoordinates([\n *     [-76.54335737228394, 39.18579907229748],\n *     [-76.52803659439087, 39.1838364847587],\n *     [-76.5295386314392, 39.17683392507606],\n *     [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * map.removeSource('some id');  // remove\n * ```\n */\nexport class CanvasSource extends ImageSource {\n    options: CanvasSourceSpecification;\n    animate: boolean;\n    canvas: HTMLCanvasElement;\n    width: number;\n    height: number;\n    /**\n     * Enables animation. The image will be copied from the canvas to the map on each frame.\n     */\n    play: () => void;\n    /**\n     * Disables animation. The map will display a static copy of the canvas image.\n     */\n    pause: () => void;\n    _playing: boolean;\n\n    /** @internal */\n    constructor(id: string, options: CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n        super(id, options, dispatcher, eventedParent);\n\n        // We build in some validation here, since canvas sources aren't included in the style spec:\n        if (!options.coordinates) {\n            this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property \"coordinates\"')));\n        } else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 ||\n                options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) {\n            this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '\"coordinates\" property must be an array of 4 longitude/latitude array pairs')));\n        }\n\n        if (options.animate && typeof options.animate !== 'boolean') {\n            this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'optional \"animate\" property must be a boolean value')));\n        }\n\n        if (!options.canvas) {\n            this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property \"canvas\"')));\n        } else if (typeof options.canvas !== 'string' && !(options.canvas instanceof HTMLCanvasElement)) {\n            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')));\n        }\n\n        this.options = options;\n        this.animate = options.animate !== undefined ? options.animate : true;\n    }\n\n    async load(): Promise<void> {\n        this._loaded = true;\n        this.canvas ||= (this.options.canvas instanceof HTMLCanvasElement) ?\n            this.options.canvas :\n            document.getElementById(this.options.canvas) as HTMLCanvasElement;\n        // cast to HTMLCanvasElement in else of ternary\n        // should we do a safety check and throw if it's not actually HTMLCanvasElement?\n        this.width = this.canvas.width;\n        this.height = this.canvas.height;\n\n        if (this._hasInvalidDimensions()) {\n            this.fire(new ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.')));\n            return;\n        }\n\n        this.play = function() {\n            this._playing = true;\n            this.map.triggerRepaint();\n        };\n\n        this.pause = function() {\n            if (this._playing) {\n                this.prepare();\n                this._playing = false;\n            }\n        };\n\n        this._finishLoading();\n    }\n\n    /**\n     * Returns the HTML `canvas` element.\n     *\n     * @returns The HTML `canvas` element.\n     */\n    getCanvas(): HTMLCanvasElement {\n        return this.canvas;\n    }\n\n    onAdd(map: Map): void {\n        this.map = map;\n        this.load();\n        if (this.canvas) {\n            if (this.animate) this.play();\n        }\n    }\n\n    onRemove(): void {\n        this._playing = false;\n        super.onRemove();\n    }\n\n    prepare(): void {\n        let resize = false;\n        if (this.canvas.width !== this.width) {\n            this.width = this.canvas.width;\n            resize = true;\n        }\n        if (this.canvas.height !== this.height) {\n            this.height = this.canvas.height;\n            resize = true;\n        }\n\n        if (this._hasInvalidDimensions()) return;\n\n        if (Object.keys(this.tiles).length === 0) return; // not enough data for current position\n\n        const context = this.map.painter.context;\n        const gl = context.gl;\n\n        if (!this.texture) {\n            this.texture = new Texture(context, this.canvas, gl.RGBA, {premultiply: true});\n            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n        } else if (resize || this._playing) {\n            this.texture.update(this.canvas, {premultiply: true});\n        }\n\n        let newTilesLoaded = false;\n        for (const w in this.tiles) {\n            const tile = this.tiles[w];\n            if (tile.state !== 'loaded') {\n                tile.state = 'loaded';\n                tile.texture = this.texture;\n                newTilesLoaded = true;\n            }\n        }\n\n        if (newTilesLoaded) {\n            this.fire(new MapSourceDataEvent('data', {sourceDataType: 'idle', sourceId: this.id}));\n        }\n    }\n\n    serialize(): CanvasSourceSpecification {\n        return {\n            type: 'canvas',\n            animate: this.animate,\n            canvas: this.options.canvas,\n            coordinates: this.coordinates\n        };\n    }\n\n    hasTransition(): boolean {\n        return this._playing;\n    }\n\n    _hasInvalidDimensions(): boolean {\n        for (const x of [this.canvas.width, this.canvas.height]) {\n            if (isNaN(x) || x <= 0) return true;\n        }\n        return false;\n    }\n}\n", "import {VectorTileSource} from '../source/vector_tile_source.ts';\nimport {RasterTileSource} from '../source/raster_tile_source.ts';\nimport {RasterDEMTileSource} from '../source/raster_dem_tile_source.ts';\nimport {GeoJSONSource, type GeoJSONSourceShouldReloadTileOptions} from '../source/geojson_source.ts';\nimport {VideoSource} from '../source/video_source.ts';\nimport {ImageSource} from '../source/image_source.ts';\nimport {CanvasSource} from '../source/canvas_source.ts';\n\nimport type {CalculateTileZoomFunction} from '../geo/projection/covering_tiles.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {SourceSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Event, Evented} from '../util/evented.ts';\nimport type {Map} from '../ui/map.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {OverscaledTileID, CanonicalTileID} from '../tile/tile_id.ts';\nimport type {LoadTileResult} from '../source/vector_tile_source.ts';\nimport type {CanvasSourceSpecification} from '../source/canvas_source.ts';\n\nconst registeredSources = {} as {[key:string]: SourceClass};\n\n/**\n * The `Source` interface must be implemented by each source type, including \"core\" types (`vector`, `raster`,\n * `video`, etc.) and all custom, third-party types.\n *\n * **Event** `data` - Fired with `{dataType: 'source', sourceDataType: 'metadata'}` to indicate that any necessary metadata\n * has been loaded so that it's okay to call `loadTile`; and with `{dataType: 'source', sourceDataType: 'content'}`\n * to indicate that the source data has changed, so that any current caches should be flushed.\n *\n * @group Sources\n */\nexport interface Source {\n    readonly type: string;\n    /**\n     * The id for the source. Must not be used by any existing source.\n     */\n    id: string;\n    /**\n     * The minimum zoom level for the source.\n     */\n    minzoom: number;\n    /**\n     * The maximum zoom level for the source.\n     */\n    maxzoom: number;\n    /**\n     * The tile size for the source.\n     */\n    tileSize: number;\n    /**\n     * The attribution for the source.\n     */\n    attribution?: string;\n    /**\n     * `true` if zoom levels are rounded to the nearest integer in the source data, `false` if they are floor-ed to the nearest integer.\n     */\n    roundZoom?: boolean;\n    /**\n     * `false` if tiles can be drawn outside their boundaries, `true` if they cannot.\n     */\n    isTileClipped?: boolean;\n    tileID?: CanonicalTileID;\n    /**\n     * `true` if tiles should be sent back to the worker for each overzoomed zoom level, `false` if not.\n     */\n    reparseOverscaled?: boolean;\n    vectorLayerIds?: string[];\n    /**\n     * True if the source has transition, false otherwise.\n     */\n    hasTransition(): boolean;\n    /**\n     * True if the source is loaded, false otherwise.\n     */\n    loaded(): boolean;\n    /**\n     * An ability to fire an event to all the listeners, see {@link Evented}\n     * @param event - The event to fire\n     */\n    fire(event: Event): unknown;\n    /**\n     * This method is called when the source is added to the map.\n     * @param map - The map instance\n     */\n    onAdd?(map: Map): void;\n    /**\n     * This method is called when the source is removed from the map.\n     * @param map - The map instance\n     */\n    onRemove?(map: Map): void;\n    /**\n     * This method does the heavy lifting of loading a tile.\n     * In most cases it will defer the work to the relevant worker source.\n     * @param tile - The tile to load\n     */\n    loadTile(tile: Tile): Promise<LoadTileResult | void>;\n    /**\n     * True is the tile is part of the source, false otherwise.\n     * @param tileID - The tile ID\n     */\n    hasTile?(tileID: OverscaledTileID): boolean;\n    /**\n     * Allows to abort a tile loading.\n     * @param tile - The tile to abort\n     */\n    abortTile?(tile: Tile): Promise<void>;\n    /**\n     * Allows to unload a tile.\n     * @param tile - The tile to unload\n     */\n    unloadTile?(tile: Tile): Promise<void>;\n    /**\n     * @returns A plain (stringifiable) JS object representing the current state of the source.\n     * Creating a source using the returned object as the `options` should result in a Source that is\n     * equivalent to this one.\n     */\n    serialize(): any;\n    /**\n     * Allows to execute a prepare step before the source is used.\n     */\n    prepare?(): void;\n    /**\n     * Optional function to redefine how tiles are loaded at high pitch angles.\n     */\n    calculateTileZoom?: CalculateTileZoomFunction;\n    /**\n     * Optional function to determine whether a tile should be reloaded, given a\n     * set of options associated with a `MapSourceDataChangedEvent`.\n     * @internal\n     */\n    shouldReloadTile?(tile: Tile, options: GeoJSONSourceShouldReloadTileOptions): boolean;\n}\n\n/**\n * A general definition of a {@link Source} class for factory usage\n */\nexport type SourceClass = {\n    new (id: string, specification: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented): Source;\n};\n\n/**\n * Creates a tiled data source instance given an options object.\n *\n * @param id - The id for the source. Must not be used by any existing source.\n * @param specification - Source options, specific to the source type (except for `options.type`, which is always required).\n * @param source - A source definition object compliant with\n * [`maplibre-gl-style-spec`](https://maplibre.org/maplibre-style-spec/#sources) or, for a third-party source type,\n  * with that type's requirements.\n * @param dispatcher - A {@link Dispatcher} instance, which can be used to send messages to the workers.\n * @returns a newly created source\n */\nexport const create = (id: string, specification: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented): Source => {\n\n    const Class = getSourceType(specification.type);\n    const source = new Class(id, specification, dispatcher, eventedParent);\n\n    if (source.id !== id) {\n        throw new Error(`Expected Source id to be ${id} instead of ${source.id}`);\n    }\n\n    return source;\n};\n\nconst getSourceType = (name: string): SourceClass => {\n    switch (name) {\n        case 'geojson':\n            return GeoJSONSource;\n        case 'image':\n            return ImageSource;\n        case 'raster':\n            return RasterTileSource;\n        case 'raster-dem':\n            return RasterDEMTileSource;\n        case 'vector':\n            return VectorTileSource;\n        case 'video':\n            return VideoSource;\n        case 'canvas':\n            return CanvasSource;\n    }\n    return registeredSources[name];\n};\n\nconst setSourceType = (name: string, type: SourceClass) => {\n    registeredSources[name] = type;\n};\n\n/**\n * Adds a custom source type, making it available for use with {@link Map.addSource}.\n * @param name - The name of the source type; source definition objects use this name in the `{type: ...}` field.\n * @param SourceType - A {@link SourceClass} - which is a constructor for the `Source` interface.\n * @returns a promise that is resolved when the source type is ready or rejected with an error.\n */\nexport const addSourceType = async (name: string, SourceType: SourceClass): Promise<void> => {\n    if (getSourceType(name)) {\n        throw new Error(`A source type called \"${name}\" already exists.`);\n    }\n    setSourceType(name, SourceType);\n};\n", "import type {CollisionBoxArray} from './array_types.g.ts';\nimport type {Style} from '../style/style.ts';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer.ts';\nimport type {FeatureIndex} from './feature_index.ts';\nimport type {Context} from '../webgl/context.ts';\nimport type {FeatureStates} from '../source/source_state.ts';\nimport type {ImagePosition} from '../render/image_atlas.ts';\nimport type {CanonicalTileID} from '../tile/tile_id.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {SubdivisionGranularitySetting} from '../render/subdivision_granularity_settings.ts';\nimport type {DashEntry} from '../render/line_atlas.ts';\nimport type {Feature as StyleFeature} from '@maplibre/maplibre-gl-style-spec';\nimport type {VectorTileFeatureLike, VectorTileLayerLike} from '@maplibre/vt-pbf';\nimport type {GetImagesResponse} from '../util/actor_messages.ts';\nimport type {GlyphPositions} from '../render/glyph_atlas.ts';\nimport type {GlyphMap} from '../style/style_glyph.ts';\n\nexport type BucketParameters<Layer extends TypedStyleLayer> = {\n    index: number;\n    layers: Layer[];\n    zoom: number;\n    pixelRatio: number;\n    overscaling: number;\n    collisionBoxArray: CollisionBoxArray;\n    sourceLayerIndex: number;\n    sourceID: string;\n};\n\nexport type PopulateParameters = {\n    featureIndex: FeatureIndex;\n    iconDependencies: Record<string, boolean>;\n    patternDependencies: Record<string, boolean>;\n    /**\n     * The glyphs each fontstack is asked for, keyed by grapheme cluster: usually a single character,\n     * but sometimes a letter with the marks written on it, which no single codepoint stands for.\n     * Glyphs are requested separately for each variant.\n     * @example\n     * ```json\n     * {\"SomeFontName\": {\"default\": {\"a\": true, \"b\": true}}}\n     * ```\n     */\n    glyphDependencies: Record<string, Record<string, Record<string, boolean>>>;\n    dashDependencies: Record<string, {round: boolean; dasharray: number[]}>;\n    availableImages: string[];\n    subdivisionGranularity: SubdivisionGranularitySetting;\n};\n\n/**\n * The asynchronously loaded tile content a bucket may need to finalize its\n * features. Every image, glyph, and dash entry referenced by the bucket's\n * layers arrives here after the worker has fetched it; pattern maps belong to\n * fill, fill-extrusion, and line buckets, icon maps and glyph maps to symbol\n * buckets.\n */\nexport type BucketDependencyParameters = {\n    options: PopulateParameters;\n    canonical: CanonicalTileID;\n    glyphMap: GlyphMap;\n    glyphPositions: GlyphPositions;\n    iconMap: GetImagesResponse;\n    iconPositions: Record<string, ImagePosition>;\n    patternMap: GetImagesResponse;\n    patternPositions: Record<string, ImagePosition>;\n    dashPositions: Record<string, DashEntry>;\n    showCollisionBoxes: boolean;\n};\n\nexport type IndexedFeature = {\n    feature: VectorTileFeatureLike;\n    id: number | string;\n    index: number;\n    sourceLayerIndex: number;\n};\n\nexport type BucketFeature = {\n    index: number;\n    sourceLayerIndex: number;\n    geometry: Point[][];\n    properties: any;\n    type: 0 | 1 | 2 | 3;\n    id?: any;\n    readonly patterns: {\n        [_: string]: {\n            'min': string;\n            'mid': string;\n            'max': string;\n        };\n    };\n    readonly dashes?: NonNullable<StyleFeature['dashes']>;\n    sortKey?: number;\n};\n\n/**\n * @hidden\n * The `Bucket` interface is the single point of knowledge about turning vector\n * tiles into WebGL buffers.\n *\n * `Bucket` is an abstract interface. An implementation exists for each style layer type.\n * Create a bucket via the `StyleLayer.createBucket` method.\n *\n * The concrete bucket types, using layout options from the style layer,\n * transform feature geometries into vertex and index data for use by the\n * vertex shader.  They also (via `ProgramConfiguration`) use feature\n * properties and the zoom level to populate the attributes needed for\n * data-driven styling.\n *\n * Buckets are designed to be built on a worker thread and then serialized and\n * transferred back to the main thread for rendering.  On the worker side, a\n * bucket's vertex, index, and attribute data is stored in `bucket.arrays: ArrayGroup`.\n * When a bucket's data is serialized and sent back to the main thread,\n * is gets deserialized (using `new Bucket(serializedBucketData)`, with\n * the array data now stored in `bucket.buffers: BufferGroup`. BufferGroups\n * hold the same data as ArrayGroups, but are tuned for consumption by WebGL.\n */\nexport interface Bucket {\n    layerIds: string[];\n    hasDependencies: boolean;\n    readonly layers: any[];\n    readonly stateDependentLayers: any[];\n    readonly stateDependentLayerIds: string[];\n    populate(features: IndexedFeature[], options: PopulateParameters, canonical: CanonicalTileID): void;\n    addFeatures(parameters: BucketDependencyParameters): void;\n    update(states: FeatureStates, vtLayer: VectorTileLayerLike, imagePositions: {[_: string]: ImagePosition}, dashPositions: Record<string, DashEntry>): void;\n    isEmpty(): boolean;\n    upload(context: Context): void;\n    uploadPending(): boolean;\n    /**\n     * Release the WebGL resources associated with the buffers. Note that because\n     * buckets are shared between layers having the same layout properties, they\n     * must be destroyed in groups (all buckets for a tile, or all symbol buckets).\n     */\n    destroy(): void;\n}\n\nexport function deserialize(input: Bucket[], style: Style): {[_: string]: Bucket} {\n    const output = {};\n\n    // Guard against the case where the map's style has been set to null while\n    // this bucket has been parsing.\n    if (!style) return output;\n\n    for (const bucket of input) {\n        const layers = bucket.layerIds\n            .map((id) => style.getLayer(id))\n            .filter(Boolean);\n\n        if (layers.length === 0) {\n            continue;\n        }\n\n        // look up StyleLayer objects from layer ids (since we don't\n        // want to waste time serializing/copying them from the worker)\n        (bucket as any).layers = layers;\n        if (bucket.stateDependentLayerIds) {\n            (bucket as any).stateDependentLayers = bucket.stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]);\n        }\n        for (const layer of layers) {\n            output[layer.id] = bucket;\n        }\n    }\n\n    return output;\n}\n", "import { PbfWriter } from \"pbf\";\nimport Point from \"@mapbox/point-geometry\";\n// lib/geojson_wrapper.ts\nvar FeatureWrapper = class {\n\tconstructor(feature, extent) {\n\t\tthis.feature = feature;\n\t\tthis.type = feature.type;\n\t\tthis.properties = feature.tags ? feature.tags : {};\n\t\tthis.extent = extent;\n\t\tif (\"id\" in feature) {\n\t\t\tif (typeof feature.id === \"string\") this.id = parseInt(feature.id, 10);\n\t\t\telse if (typeof feature.id === \"number\" && !isNaN(feature.id)) this.id = feature.id;\n\t\t}\n\t}\n\tloadGeometry() {\n\t\tconst geometry = [];\n\t\tconst rawGeo = this.feature.type === 1 ? [this.feature.geometry] : this.feature.geometry;\n\t\tfor (const ring of rawGeo) {\n\t\t\tconst newRing = [];\n\t\t\tfor (const point of ring) newRing.push(new Point(point[0], point[1]));\n\t\t\tgeometry.push(newRing);\n\t\t}\n\t\treturn geometry;\n\t}\n};\nconst GEOJSON_TILE_LAYER_NAME = \"_geojsonTileLayer\";\nvar GeoJSONWrapper = class {\n\tconstructor(features, options) {\n\t\tthis.layers = { [GEOJSON_TILE_LAYER_NAME]: this };\n\t\tthis.name = GEOJSON_TILE_LAYER_NAME;\n\t\tthis.version = options ? options.version : 1;\n\t\tthis.extent = options ? options.extent : 4096;\n\t\tthis.length = features.length;\n\t\tthis.features = features;\n\t}\n\tfeature(i) {\n\t\treturn new FeatureWrapper(this.features[i], this.extent);\n\t}\n};\n// index.ts\n/**\n* Serialize a vector-tile-js-created tile to pbf\n*\n* @param tile - the tile to serialize\n* @param jsonPrefix - a string prefix to prepend to JSON-stringified non-primitive property values, used to distinguish them from regular string values when parsing the tile later. Default is \"\".\n* @return uncompressed, pbf-serialized tile data\n*/\nfunction fromVectorTileJs(tile, jsonPrefix = \"\") {\n\tconst out = new PbfWriter();\n\twriteTile(tile, out, jsonPrefix);\n\treturn out.finish();\n}\n/**\n* Serialized a geojson-vt-created tile to pbf.\n*\n* @param layers - An object mapping layer names to geojson-vt-created vector tile objects\n* @param options - An object specifying the vector-tile specification version and extent that were used to create `layers`.\n* @return uncompressed, pbf-serialized tile data\n*/\nfunction fromGeojsonVt(layers, options) {\n\tconst l = {};\n\tfor (const k in layers) {\n\t\tl[k] = new GeoJSONWrapper(layers[k].features, options);\n\t\tl[k].name = k;\n\t\tl[k].version = options ? options.version : 1;\n\t\tl[k].extent = options ? options.extent : 4096;\n\t}\n\treturn fromVectorTileJs({ layers: l });\n}\nfunction writeTile(tile, pbf, jsonPrefix = \"\") {\n\tfor (const key in tile.layers) pbf.writeMessage(3, (layer, pbf) => writeLayer(layer, pbf, jsonPrefix), tile.layers[key]);\n}\nfunction writeLayer(layer, pbf, jsonPrefix = \"\") {\n\tpbf.writeVarintField(15, layer.version || 1);\n\tpbf.writeStringField(1, layer.name || \"\");\n\tpbf.writeVarintField(5, layer.extent || 4096);\n\tconst context = {\n\t\tjsonPrefix,\n\t\tkeys: [],\n\t\tvalues: [],\n\t\tkeycache: {},\n\t\tvaluecache: {}\n\t};\n\tfor (let i = 0; i < layer.length; i++) {\n\t\tcontext.feature = layer.feature(i);\n\t\tpbf.writeMessage(2, writeFeature, context);\n\t}\n\tconst keys = context.keys;\n\tfor (const key of keys) pbf.writeStringField(3, key);\n\tconst values = context.values;\n\tfor (const value of values) pbf.writeMessage(4, writeValue, value);\n}\nfunction writeFeature(context, pbf) {\n\tif (!context.feature) return;\n\tconst feature = context.feature;\n\tif (feature.id !== void 0) pbf.writeVarintField(1, feature.id);\n\tpbf.writeMessage(2, writeProperties, context);\n\tpbf.writeVarintField(3, feature.type);\n\tpbf.writeMessage(4, writeGeometry, feature);\n}\nfunction writeProperties(context, pbf) {\n\tfor (const key in context.feature?.properties) {\n\t\tlet value = context.feature.properties[key];\n\t\tlet keyIndex = context.keycache[key];\n\t\tif (value == null) continue;\n\t\tif (typeof keyIndex === \"undefined\") {\n\t\t\tcontext.keys.push(key);\n\t\t\tkeyIndex = context.keys.length - 1;\n\t\t\tcontext.keycache[key] = keyIndex;\n\t\t}\n\t\tpbf.writeVarint(keyIndex);\n\t\tif (typeof value !== \"string\" && typeof value !== \"boolean\" && typeof value !== \"number\") value = context.jsonPrefix + JSON.stringify(value);\n\t\tconst valueKey = typeof value + \":\" + value;\n\t\tlet valueIndex = context.valuecache[valueKey];\n\t\tif (typeof valueIndex === \"undefined\") {\n\t\t\tcontext.values.push(value);\n\t\t\tvalueIndex = context.values.length - 1;\n\t\t\tcontext.valuecache[valueKey] = valueIndex;\n\t\t}\n\t\tpbf.writeVarint(valueIndex);\n\t}\n}\nfunction command(cmd, length) {\n\treturn (length << 3) + (cmd & 7);\n}\nfunction zigzag(num) {\n\treturn num << 1 ^ num >> 31;\n}\nfunction writeGeometry(feature, pbf) {\n\tconst geometry = feature.loadGeometry();\n\tconst type = feature.type;\n\tlet x = 0;\n\tlet y = 0;\n\tfor (const ring of geometry) {\n\t\tlet count = 1;\n\t\tif (type === 1) count = ring.length;\n\t\tpbf.writeVarint(command(1, count));\n\t\tconst last = ring[ring.length - 1];\n\t\tconst lineCount = type === 3 && ring.length > 1 && last.x === ring[0].x && last.y === ring[0].y ? ring.length - 1 : ring.length;\n\t\tfor (let i = 0; i < lineCount; i++) {\n\t\t\tif (i === 1 && type !== 1) pbf.writeVarint(command(2, lineCount - 1));\n\t\t\tconst dx = ring[i].x - x;\n\t\t\tconst dy = ring[i].y - y;\n\t\t\tpbf.writeVarint(zigzag(dx));\n\t\t\tpbf.writeVarint(zigzag(dy));\n\t\t\tx += dx;\n\t\t\ty += dy;\n\t\t}\n\t\tif (feature.type === 3) pbf.writeVarint(command(7, 1));\n\t}\n}\nfunction writeValue(value, pbf) {\n\tconst type = typeof value;\n\tif (type === \"string\") pbf.writeStringField(1, value);\n\telse if (type === \"boolean\") pbf.writeBooleanField(7, value);\n\telse if (type === \"number\") {\n\t\tif (value % 1 !== 0) pbf.writeDoubleField(3, value);\n\t\telse if (value < 0) pbf.writeSVarintField(6, value);\n\t\telse pbf.writeVarintField(5, value);\n\t}\n}\nexport { GEOJSON_TILE_LAYER_NAME, GeoJSONWrapper, fromGeojsonVt, fromVectorTileJs };\n\n//# sourceMappingURL=index.es.js.map", "export class DictionaryCoder {\n    _stringToNumber: {[_: string]: number};\n    _numberToString: string[];\n\n    constructor(strings: string[]) {\n        this._stringToNumber = {};\n        this._numberToString = [];\n        for (let i = 0; i < strings.length; i++) {\n            const string = strings[i];\n            this._stringToNumber[string] = i;\n            this._numberToString[i] = string;\n        }\n    }\n\n    encode(string: string): number {\n        return this._stringToNumber[string];\n    }\n\n    decode(n: number): string {\n        if (n >= this._numberToString.length) throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`);\n        return this._numberToString[n];\n    }\n}\n", "import {classifyRings} from '@mapbox/vector-tile';\nimport {JSON_PREFIX} from './util.ts';\nimport {mercatorWorldCoordinateHelper} from '../geo/mercator_coordinate.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {VectorTileFeatureLike} from '@maplibre/vt-pbf';\nimport type {WorldCoordinateHelper} from '../geo/transform_interface.ts';\n\n/**\n * A helper for type to omit a property from a type\n */\nexport type DistributiveKeys<T> = T extends T ? keyof T : never;\n/**\n * A helper for type to omit a property from a type\n */\nexport type DistributiveOmit<T, K extends DistributiveKeys<T>> = T extends unknown\n    ? Omit<T, K>\n    : never;\n\n/**\n * An extended geojson feature used by the events to return data to the listener\n */\nexport type MapGeoJSONFeature = GeoJSONFeature & {\n    layer: DistributiveOmit<LayerSpecification, 'source'> & {source: string};\n    source: string;\n    sourceLayer?: string;\n    state: { [key: string]: any };\n};\n\n/**\n * A geojson feature\n */\nexport class GeoJSONFeature {\n    /**\n     * The map projection's world-to-lng/lat mapping of each feature, kept only when it is not the mercator one so\n     * mercator query output stays float-identical to the inline formula in `projectPoint`. It is held here and not\n     * on the feature because a registered projection's definition holds functions, which would keep the feature\n     * from being cloned with `structuredClone` or sent with `postMessage`.\n     */\n    private static readonly worldCoordinateHelpers = new WeakMap<GeoJSONFeature, WorldCoordinateHelper>();\n\n    type: 'Feature';\n    _geometry: GeoJSON.Geometry;\n    properties: { [name: string]: any };\n    id: number | string | undefined;\n    _x: number;\n    _y: number;\n    _z: number;\n\n    _vectorTileFeature: VectorTileFeatureLike;\n\n    constructor(vectorTileFeature: VectorTileFeatureLike, z: number, x: number, y: number, id: string | number | undefined, worldCoordinateHelper: WorldCoordinateHelper) {\n        this.type = 'Feature';\n        this._vectorTileFeature = vectorTileFeature;\n        this._x = x;\n        this._y = y;\n        this._z = z;\n        if (worldCoordinateHelper !== mercatorWorldCoordinateHelper) {\n            GeoJSONFeature.worldCoordinateHelpers.set(this, worldCoordinateHelper);\n        }\n\n        for (const key in vectorTileFeature.properties) {\n            if (typeof vectorTileFeature.properties[key] !== 'string' || !vectorTileFeature.properties[key].startsWith(JSON_PREFIX)) {\n                continue;\n            }\n            // JSON parsing the special case of a json prefix that is serialized in geojson worker source.\n            vectorTileFeature.properties[key] = JSON.parse(vectorTileFeature.properties[key].slice(JSON_PREFIX.length));\n        }\n        this.properties = vectorTileFeature.properties;\n        this.id = id;\n    }\n\n    private projectPoint(p: Point, x0: number, y0: number, size: number, worldCoordinateHelper: WorldCoordinateHelper | undefined): [number, number] {\n        if (worldCoordinateHelper) {\n            const lngLat = worldCoordinateHelper.lngLatFromWorld((p.x + x0) / size, (p.y + y0) / size);\n            return [lngLat.lng, lngLat.lat];\n        }\n        return [\n            (p.x + x0) * 360 / size - 180,\n            360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90\n        ];\n    }\n\n    private projectLine(line: Point[], x0: number, y0: number, size: number, worldCoordinateHelper: WorldCoordinateHelper | undefined) {\n        return line.map(p => this.projectPoint(p, x0, y0, size, worldCoordinateHelper));\n    }\n\n    get geometry(): GeoJSON.Geometry {\n        if (this._geometry) return this._geometry;\n\n        const feature = this._vectorTileFeature;\n        const worldCoordinateHelper = GeoJSONFeature.worldCoordinateHelpers.get(this);\n\n        // Copied from https://github.com/mapbox/vector-tile-js/blob/f1457ee47d0a261e6246d68c959fbd12bf56aeeb/index.js\n        const size = feature.extent * Math.pow(2, this._z);\n        const x0 = feature.extent * this._x;\n        const y0 = feature.extent * this._y;\n        const vtCoords = feature.loadGeometry();\n\n        switch (feature.type) {\n            case 1: {\n                const points = [];\n                for (const line of vtCoords) {\n                    points.push(line[0]);\n                }\n                const coordinates = this.projectLine(points, x0, y0, size, worldCoordinateHelper);\n                this._geometry = points.length === 1 ?\n                    {type: 'Point', coordinates: coordinates[0]} :\n                    {type: 'MultiPoint', coordinates};\n                break;\n            }\n            case 2: {\n                const coordinates = vtCoords.map(coord => this.projectLine(coord, x0, y0, size, worldCoordinateHelper));\n                this._geometry = coordinates.length === 1 ?\n                    {type: 'LineString', coordinates: coordinates[0]} :\n                    {type: 'MultiLineString', coordinates};\n                break;\n            }\n            case 3: {\n                const polygons = classifyRings(vtCoords);\n                const coordinates = [];\n                for (const polygon of polygons) {\n                    coordinates.push(polygon.map(coord => this.projectLine(coord, x0, y0, size, worldCoordinateHelper)));\n                }\n                this._geometry = coordinates.length === 1 ?\n                    {type: 'Polygon', coordinates: coordinates[0]} :\n                    {type: 'MultiPolygon', coordinates};\n                break;\n            }\n            default:\n                throw new Error(`unknown feature type: ${feature.type}`);\n        }\n\n        return this._geometry;\n    }\n\n    set geometry(g: GeoJSON.Geometry) {\n        this._geometry = g;\n    }\n\n    toJSON(): GeoJSON.Feature {\n        const json: any = {\n            geometry: this.geometry\n        };\n        for (const i in this) {\n            if (i === '_geometry' || i === '_vectorTileFeature' || i === '_x' || i === '_y' || i === '_z') continue;\n            json[i] = (this)[i];\n        }\n        return json;\n    }\n}\n", "export default class Vector {\n    constructor(_name, dataBuffer, sizeOrNullabilityBuffer) {\n        this._name = _name;\n        this.dataBuffer = dataBuffer;\n        if (typeof sizeOrNullabilityBuffer === \"number\") {\n            this._size = sizeOrNullabilityBuffer;\n        }\n        else {\n            this.nullabilityBuffer = sizeOrNullabilityBuffer;\n            this._size = sizeOrNullabilityBuffer.size();\n        }\n    }\n    getValue(index) {\n        return this.nullabilityBuffer && !this.nullabilityBuffer.get(index) ? null : this.getValueFromBuffer(index);\n    }\n    has(index) {\n        return this.nullabilityBuffer?.get(index) || !this.nullabilityBuffer;\n    }\n    get name() {\n        return this._name;\n    }\n    get size() {\n        return this._size;\n    }\n}\n//# sourceMappingURL=vector.js.map", "import Vector from \"./vector\";\nexport class FixedSizeVector extends Vector {\n}\n//# sourceMappingURL=fixedSizeVector.js.map", "import { FixedSizeVector } from \"../fixedSizeVector\";\nexport class Int32FlatVector extends FixedSizeVector {\n    getValueFromBuffer(index) {\n        return this.dataBuffer[index];\n    }\n}\n//# sourceMappingURL=int32FlatVector.js.map", "import { FixedSizeVector } from \"../fixedSizeVector\";\nexport class DoubleFlatVector extends FixedSizeVector {\n    getValueFromBuffer(index) {\n        return this.dataBuffer[index];\n    }\n}\n//# sourceMappingURL=doubleFlatVector.js.map", "import Vector from \"../vector\";\nexport class SequenceVector extends Vector {\n    constructor(name, baseValueBuffer, delta, size) {\n        super(name, baseValueBuffer, size);\n        this.delta = delta;\n    }\n}\n//# sourceMappingURL=sequenceVector.js.map", "import { SequenceVector } from \"./sequenceVector\";\nexport class Int32SequenceVector extends SequenceVector {\n    constructor(name, baseValue, delta, size, isSigned) {\n        super(name, isSigned ? Int32Array.of(baseValue) : Uint32Array.of(baseValue), delta, size);\n    }\n    getValueFromBuffer(index) {\n        return this.dataBuffer[0] + index * this.delta;\n    }\n}\n//# sourceMappingURL=int32SequenceVector.js.map", "import Vector from \"../vector\";\nexport class Int32ConstVector extends Vector {\n    constructor(name, value, sizeOrNullabilityBuffer, isSigned) {\n        super(name, isSigned ? Int32Array.of(value) : Uint32Array.of(value), sizeOrNullabilityBuffer);\n    }\n    getValueFromBuffer(_index) {\n        return this.dataBuffer[0];\n    }\n}\n//# sourceMappingURL=int32ConstVector.js.map", "import { Int32FlatVector } from \"./flat/int32FlatVector\";\nimport { DoubleFlatVector } from \"./flat/doubleFlatVector\";\nimport { Int32SequenceVector } from \"./sequence/int32SequenceVector\";\nimport { Int32ConstVector } from \"./constant/int32ConstVector\";\nexport default class FeatureTable {\n    constructor(_name, _geometryVector, _idVector, _propertyVectors, _extent = 4096) {\n        this._name = _name;\n        this._geometryVector = _geometryVector;\n        this._idVector = _idVector;\n        this._propertyVectors = _propertyVectors;\n        this._extent = _extent;\n        if (_name.length === 0) {\n            throw new Error(\"Missing layer name\");\n        }\n    }\n    get name() {\n        return this._name;\n    }\n    get idVector() {\n        return this._idVector;\n    }\n    get geometryVector() {\n        return this._geometryVector;\n    }\n    get propertyVectors() {\n        return this._propertyVectors ?? [];\n    }\n    getPropertyVector(name) {\n        if (!this.propertyVectorsMap) {\n            this.propertyVectorsMap = new Map(this.propertyVectors.map((vector) => [vector.name, vector]));\n        }\n        return this.propertyVectorsMap.get(name);\n    }\n    get numFeatures() {\n        return this.geometryVector.numGeometries;\n    }\n    get extent() {\n        return this._extent;\n    }\n    /**\n     * Returns all features as an array\n     */\n    getFeatures() {\n        const features = [];\n        const geometries = this.geometryVector.getGeometries();\n        for (let i = 0; i < this.numFeatures; i++) {\n            let id;\n            if (this.idVector) {\n                const idValue = this.idVector.getValue(i);\n                if (idValue !== null) {\n                    id = this.containsMaxSafeIntegerValues(this.idVector) ? Number(idValue) : idValue;\n                }\n            }\n            const geometry = {\n                coordinates: geometries[i],\n                type: this.geometryVector.geometryType(i),\n            };\n            const properties = {};\n            for (const propertyColumn of this.propertyVectors) {\n                if (!propertyColumn)\n                    continue;\n                const columnName = propertyColumn.name;\n                const propertyValue = propertyColumn.getValue(i);\n                if (propertyValue !== null) {\n                    properties[columnName] = propertyValue;\n                }\n            }\n            features.push({ id, geometry, properties });\n        }\n        return features;\n    }\n    containsMaxSafeIntegerValues(idVector) {\n        return (idVector instanceof Int32FlatVector ||\n            idVector instanceof Int32ConstVector ||\n            idVector instanceof Int32SequenceVector ||\n            idVector instanceof DoubleFlatVector);\n    }\n}\n//# sourceMappingURL=featureTable.js.map", "// based on ../spec/schema/mlt_tileset_metadata.proto\nexport const ColumnScope = {\n    FEATURE: 0,\n    VERTEX: 1,\n};\nexport const ScalarType = {\n    BOOLEAN: 0,\n    INT_8: 1,\n    UINT_8: 2,\n    INT_32: 3,\n    UINT_32: 4,\n    INT_64: 5,\n    UINT_64: 6,\n    FLOAT: 7,\n    DOUBLE: 8,\n    STRING: 9,\n};\nexport const ComplexType = {\n    GEOMETRY: 0,\n    STRUCT: 1,\n    MAP: 2,\n};\nexport const LogicalScalarType = {\n    ID: 0,\n};\nexport const LogicalComplexType = {\n    BINARY: 0,\n    RANGE_MAP: 1,\n};\n//# sourceMappingURL=tilesetMetadata.js.map", "// Ported from https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/IntWrapper.java\nexport default class IntWrapper {\n    constructor(value) {\n        this.value = value;\n    }\n    get() {\n        return this.value;\n    }\n    set(v) {\n        this.value = v;\n    }\n    increment() {\n        return this.value++;\n    }\n    add(v) {\n        this.value += v;\n    }\n}\n//# sourceMappingURL=intWrapper.js.map", "export var LogicalLevelTechnique;\n(function (LogicalLevelTechnique) {\n    LogicalLevelTechnique[\"NONE\"] = \"NONE\";\n    LogicalLevelTechnique[\"DELTA\"] = \"DELTA\";\n    LogicalLevelTechnique[\"COMPONENTWISE_DELTA\"] = \"COMPONENTWISE_DELTA\";\n    LogicalLevelTechnique[\"RLE\"] = \"RLE\";\n    LogicalLevelTechnique[\"MORTON\"] = \"MORTON\";\n})(LogicalLevelTechnique || (LogicalLevelTechnique = {}));\n//# sourceMappingURL=logicalLevelTechnique.js.map", "export var PhysicalLevelTechnique;\n(function (PhysicalLevelTechnique) {\n    PhysicalLevelTechnique[\"NONE\"] = \"NONE\";\n    /**\n     * Preferred option, tends to produce the best compression ratio and decoding performance.\n     * But currently only limited to 32 bit integer.\n     */\n    PhysicalLevelTechnique[\"FAST_PFOR\"] = \"FAST_PFOR\";\n    /**\n     * Can produce better results in combination with a heavyweight compression scheme like Gzip.\n     * Simple compression scheme where the decoder are easier to implement compared to FastPfor.\n     */\n    PhysicalLevelTechnique[\"VARINT\"] = \"VARINT\";\n})(PhysicalLevelTechnique || (PhysicalLevelTechnique = {}));\n//# sourceMappingURL=physicalLevelTechnique.js.map", "/**\n * Bit masks for each bitwidth 0-32.\n * DO NOT MUTATE - this is a shared constant.\n */\nconst masks = new Uint32Array(33);\nmasks[0] = 0;\nfor (let bitWidth = 1; bitWidth <= 32; bitWidth++) {\n    masks[bitWidth] = bitWidth === 32 ? 0xffffffff : 0xffffffff >>> (32 - bitWidth);\n}\nexport const MASKS = masks;\nexport const DEFAULT_PAGE_SIZE = 65536;\nexport const BLOCK_SIZE = 256;\nexport function greatestMultiple(value, factor) {\n    return value - (value % factor);\n}\nexport function roundUpToMultipleOf32(value) {\n    return greatestMultiple(value + 31, 32);\n}\nexport function normalizePageSize(pageSize) {\n    if (!Number.isFinite(pageSize) || pageSize <= 0)\n        return DEFAULT_PAGE_SIZE;\n    const aligned = greatestMultiple(Math.floor(pageSize), BLOCK_SIZE);\n    return aligned === 0 ? BLOCK_SIZE : aligned;\n}\nexport function bswap32(value) {\n    const x = value >>> 0;\n    return (((x & 0xff) << 24) | ((x & 0xff00) << 8) | ((x >>> 8) & 0xff00) | ((x >>> 24) & 0xff)) >>> 0;\n}\n//# sourceMappingURL=fastPforShared.js.map", "import { MASKS } from \"./fastPforShared\";\nexport function fastUnpack32_1(inValues, inPos, out, outPos) {\n    const in0 = inValues[inPos] >>> 0;\n    for (let i = 0; i < 32; i++) {\n        out[outPos + i] = (in0 >>> i) & 1;\n    }\n}\nexport function fastUnpack32_2(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x3;\n    out[op++] = (in0 >>> 2) & 0x3;\n    out[op++] = (in0 >>> 4) & 0x3;\n    out[op++] = (in0 >>> 6) & 0x3;\n    out[op++] = (in0 >>> 8) & 0x3;\n    out[op++] = (in0 >>> 10) & 0x3;\n    out[op++] = (in0 >>> 12) & 0x3;\n    out[op++] = (in0 >>> 14) & 0x3;\n    out[op++] = (in0 >>> 16) & 0x3;\n    out[op++] = (in0 >>> 18) & 0x3;\n    out[op++] = (in0 >>> 20) & 0x3;\n    out[op++] = (in0 >>> 22) & 0x3;\n    out[op++] = (in0 >>> 24) & 0x3;\n    out[op++] = (in0 >>> 26) & 0x3;\n    out[op++] = (in0 >>> 28) & 0x3;\n    out[op++] = (in0 >>> 30) & 0x3;\n    out[op++] = (in1 >>> 0) & 0x3;\n    out[op++] = (in1 >>> 2) & 0x3;\n    out[op++] = (in1 >>> 4) & 0x3;\n    out[op++] = (in1 >>> 6) & 0x3;\n    out[op++] = (in1 >>> 8) & 0x3;\n    out[op++] = (in1 >>> 10) & 0x3;\n    out[op++] = (in1 >>> 12) & 0x3;\n    out[op++] = (in1 >>> 14) & 0x3;\n    out[op++] = (in1 >>> 16) & 0x3;\n    out[op++] = (in1 >>> 18) & 0x3;\n    out[op++] = (in1 >>> 20) & 0x3;\n    out[op++] = (in1 >>> 22) & 0x3;\n    out[op++] = (in1 >>> 24) & 0x3;\n    out[op++] = (in1 >>> 26) & 0x3;\n    out[op++] = (in1 >>> 28) & 0x3;\n    out[op] = (in1 >>> 30) & 0x3;\n}\nexport function fastUnpack32_3(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x7;\n    out[op++] = (in0 >>> 3) & 0x7;\n    out[op++] = (in0 >>> 6) & 0x7;\n    out[op++] = (in0 >>> 9) & 0x7;\n    out[op++] = (in0 >>> 12) & 0x7;\n    out[op++] = (in0 >>> 15) & 0x7;\n    out[op++] = (in0 >>> 18) & 0x7;\n    out[op++] = (in0 >>> 21) & 0x7;\n    out[op++] = (in0 >>> 24) & 0x7;\n    out[op++] = (in0 >>> 27) & 0x7;\n    out[op++] = ((in0 >>> 30) | ((in1 & 0x1) << 2)) & 0x7;\n    out[op++] = (in1 >>> 1) & 0x7;\n    out[op++] = (in1 >>> 4) & 0x7;\n    out[op++] = (in1 >>> 7) & 0x7;\n    out[op++] = (in1 >>> 10) & 0x7;\n    out[op++] = (in1 >>> 13) & 0x7;\n    out[op++] = (in1 >>> 16) & 0x7;\n    out[op++] = (in1 >>> 19) & 0x7;\n    out[op++] = (in1 >>> 22) & 0x7;\n    out[op++] = (in1 >>> 25) & 0x7;\n    out[op++] = (in1 >>> 28) & 0x7;\n    out[op++] = ((in1 >>> 31) | ((in2 & 0x3) << 1)) & 0x7;\n    out[op++] = (in2 >>> 2) & 0x7;\n    out[op++] = (in2 >>> 5) & 0x7;\n    out[op++] = (in2 >>> 8) & 0x7;\n    out[op++] = (in2 >>> 11) & 0x7;\n    out[op++] = (in2 >>> 14) & 0x7;\n    out[op++] = (in2 >>> 17) & 0x7;\n    out[op++] = (in2 >>> 20) & 0x7;\n    out[op++] = (in2 >>> 23) & 0x7;\n    out[op++] = (in2 >>> 26) & 0x7;\n    out[op] = (in2 >>> 29) & 0x7;\n}\nexport function fastUnpack32_4(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    out[op++] = (in0 >>> 0) & 0xf;\n    out[op++] = (in0 >>> 4) & 0xf;\n    out[op++] = (in0 >>> 8) & 0xf;\n    out[op++] = (in0 >>> 12) & 0xf;\n    out[op++] = (in0 >>> 16) & 0xf;\n    out[op++] = (in0 >>> 20) & 0xf;\n    out[op++] = (in0 >>> 24) & 0xf;\n    out[op++] = (in0 >>> 28) & 0xf;\n    out[op++] = (in1 >>> 0) & 0xf;\n    out[op++] = (in1 >>> 4) & 0xf;\n    out[op++] = (in1 >>> 8) & 0xf;\n    out[op++] = (in1 >>> 12) & 0xf;\n    out[op++] = (in1 >>> 16) & 0xf;\n    out[op++] = (in1 >>> 20) & 0xf;\n    out[op++] = (in1 >>> 24) & 0xf;\n    out[op++] = (in1 >>> 28) & 0xf;\n    out[op++] = (in2 >>> 0) & 0xf;\n    out[op++] = (in2 >>> 4) & 0xf;\n    out[op++] = (in2 >>> 8) & 0xf;\n    out[op++] = (in2 >>> 12) & 0xf;\n    out[op++] = (in2 >>> 16) & 0xf;\n    out[op++] = (in2 >>> 20) & 0xf;\n    out[op++] = (in2 >>> 24) & 0xf;\n    out[op++] = (in2 >>> 28) & 0xf;\n    out[op++] = (in3 >>> 0) & 0xf;\n    out[op++] = (in3 >>> 4) & 0xf;\n    out[op++] = (in3 >>> 8) & 0xf;\n    out[op++] = (in3 >>> 12) & 0xf;\n    out[op++] = (in3 >>> 16) & 0xf;\n    out[op++] = (in3 >>> 20) & 0xf;\n    out[op++] = (in3 >>> 24) & 0xf;\n    out[op] = (in3 >>> 28) & 0xf;\n}\nexport function fastUnpack32_5(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x1f;\n    out[op++] = (in0 >>> 5) & 0x1f;\n    out[op++] = (in0 >>> 10) & 0x1f;\n    out[op++] = (in0 >>> 15) & 0x1f;\n    out[op++] = (in0 >>> 20) & 0x1f;\n    out[op++] = (in0 >>> 25) & 0x1f;\n    out[op++] = ((in0 >>> 30) | ((in1 & 0x7) << 2)) & 0x1f;\n    out[op++] = (in1 >>> 3) & 0x1f;\n    out[op++] = (in1 >>> 8) & 0x1f;\n    out[op++] = (in1 >>> 13) & 0x1f;\n    out[op++] = (in1 >>> 18) & 0x1f;\n    out[op++] = (in1 >>> 23) & 0x1f;\n    out[op++] = ((in1 >>> 28) | ((in2 & 0x1) << 4)) & 0x1f;\n    out[op++] = (in2 >>> 1) & 0x1f;\n    out[op++] = (in2 >>> 6) & 0x1f;\n    out[op++] = (in2 >>> 11) & 0x1f;\n    out[op++] = (in2 >>> 16) & 0x1f;\n    out[op++] = (in2 >>> 21) & 0x1f;\n    out[op++] = (in2 >>> 26) & 0x1f;\n    out[op++] = ((in2 >>> 31) | ((in3 & 0xf) << 1)) & 0x1f;\n    out[op++] = (in3 >>> 4) & 0x1f;\n    out[op++] = (in3 >>> 9) & 0x1f;\n    out[op++] = (in3 >>> 14) & 0x1f;\n    out[op++] = (in3 >>> 19) & 0x1f;\n    out[op++] = (in3 >>> 24) & 0x1f;\n    out[op++] = ((in3 >>> 29) | ((in4 & 0x3) << 3)) & 0x1f;\n    out[op++] = (in4 >>> 2) & 0x1f;\n    out[op++] = (in4 >>> 7) & 0x1f;\n    out[op++] = (in4 >>> 12) & 0x1f;\n    out[op++] = (in4 >>> 17) & 0x1f;\n    out[op++] = (in4 >>> 22) & 0x1f;\n    out[op] = (in4 >>> 27) & 0x1f;\n}\nexport function fastUnpack32_6(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x3f;\n    out[op++] = (in0 >>> 6) & 0x3f;\n    out[op++] = (in0 >>> 12) & 0x3f;\n    out[op++] = (in0 >>> 18) & 0x3f;\n    out[op++] = (in0 >>> 24) & 0x3f;\n    out[op++] = ((in0 >>> 30) | ((in1 & 0xf) << 2)) & 0x3f;\n    out[op++] = (in1 >>> 4) & 0x3f;\n    out[op++] = (in1 >>> 10) & 0x3f;\n    out[op++] = (in1 >>> 16) & 0x3f;\n    out[op++] = (in1 >>> 22) & 0x3f;\n    out[op++] = ((in1 >>> 28) | ((in2 & 0x3) << 4)) & 0x3f;\n    out[op++] = (in2 >>> 2) & 0x3f;\n    out[op++] = (in2 >>> 8) & 0x3f;\n    out[op++] = (in2 >>> 14) & 0x3f;\n    out[op++] = (in2 >>> 20) & 0x3f;\n    out[op++] = (in2 >>> 26) & 0x3f;\n    out[op++] = (in3 >>> 0) & 0x3f;\n    out[op++] = (in3 >>> 6) & 0x3f;\n    out[op++] = (in3 >>> 12) & 0x3f;\n    out[op++] = (in3 >>> 18) & 0x3f;\n    out[op++] = (in3 >>> 24) & 0x3f;\n    out[op++] = ((in3 >>> 30) | ((in4 & 0xf) << 2)) & 0x3f;\n    out[op++] = (in4 >>> 4) & 0x3f;\n    out[op++] = (in4 >>> 10) & 0x3f;\n    out[op++] = (in4 >>> 16) & 0x3f;\n    out[op++] = (in4 >>> 22) & 0x3f;\n    out[op++] = ((in4 >>> 28) | ((in5 & 0x3) << 4)) & 0x3f;\n    out[op++] = (in5 >>> 2) & 0x3f;\n    out[op++] = (in5 >>> 8) & 0x3f;\n    out[op++] = (in5 >>> 14) & 0x3f;\n    out[op++] = (in5 >>> 20) & 0x3f;\n    out[op] = (in5 >>> 26) & 0x3f;\n}\nexport function fastUnpack32_7(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    const in6 = inValues[inPos + 6] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x7f;\n    out[op++] = (in0 >>> 7) & 0x7f;\n    out[op++] = (in0 >>> 14) & 0x7f;\n    out[op++] = (in0 >>> 21) & 0x7f;\n    out[op++] = ((in0 >>> 28) | ((in1 & 0x7) << 4)) & 0x7f;\n    out[op++] = (in1 >>> 3) & 0x7f;\n    out[op++] = (in1 >>> 10) & 0x7f;\n    out[op++] = (in1 >>> 17) & 0x7f;\n    out[op++] = (in1 >>> 24) & 0x7f;\n    out[op++] = ((in1 >>> 31) | ((in2 & 0x3f) << 1)) & 0x7f;\n    out[op++] = (in2 >>> 6) & 0x7f;\n    out[op++] = (in2 >>> 13) & 0x7f;\n    out[op++] = (in2 >>> 20) & 0x7f;\n    out[op++] = ((in2 >>> 27) | ((in3 & 0x3) << 5)) & 0x7f;\n    out[op++] = (in3 >>> 2) & 0x7f;\n    out[op++] = (in3 >>> 9) & 0x7f;\n    out[op++] = (in3 >>> 16) & 0x7f;\n    out[op++] = (in3 >>> 23) & 0x7f;\n    out[op++] = ((in3 >>> 30) | ((in4 & 0x1f) << 2)) & 0x7f;\n    out[op++] = (in4 >>> 5) & 0x7f;\n    out[op++] = (in4 >>> 12) & 0x7f;\n    out[op++] = (in4 >>> 19) & 0x7f;\n    out[op++] = ((in4 >>> 26) | ((in5 & 0x1) << 6)) & 0x7f;\n    out[op++] = (in5 >>> 1) & 0x7f;\n    out[op++] = (in5 >>> 8) & 0x7f;\n    out[op++] = (in5 >>> 15) & 0x7f;\n    out[op++] = (in5 >>> 22) & 0x7f;\n    out[op++] = ((in5 >>> 29) | ((in6 & 0xf) << 3)) & 0x7f;\n    out[op++] = (in6 >>> 4) & 0x7f;\n    out[op++] = (in6 >>> 11) & 0x7f;\n    out[op++] = (in6 >>> 18) & 0x7f;\n    out[op] = (in6 >>> 25) & 0x7f;\n}\nexport function fastUnpack32_8(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    const in6 = inValues[inPos + 6] >>> 0;\n    const in7 = inValues[inPos + 7] >>> 0;\n    out[op++] = (in0 >>> 0) & 0xff;\n    out[op++] = (in0 >>> 8) & 0xff;\n    out[op++] = (in0 >>> 16) & 0xff;\n    out[op++] = (in0 >>> 24) & 0xff;\n    out[op++] = (in1 >>> 0) & 0xff;\n    out[op++] = (in1 >>> 8) & 0xff;\n    out[op++] = (in1 >>> 16) & 0xff;\n    out[op++] = (in1 >>> 24) & 0xff;\n    out[op++] = (in2 >>> 0) & 0xff;\n    out[op++] = (in2 >>> 8) & 0xff;\n    out[op++] = (in2 >>> 16) & 0xff;\n    out[op++] = (in2 >>> 24) & 0xff;\n    out[op++] = (in3 >>> 0) & 0xff;\n    out[op++] = (in3 >>> 8) & 0xff;\n    out[op++] = (in3 >>> 16) & 0xff;\n    out[op++] = (in3 >>> 24) & 0xff;\n    out[op++] = (in4 >>> 0) & 0xff;\n    out[op++] = (in4 >>> 8) & 0xff;\n    out[op++] = (in4 >>> 16) & 0xff;\n    out[op++] = (in4 >>> 24) & 0xff;\n    out[op++] = (in5 >>> 0) & 0xff;\n    out[op++] = (in5 >>> 8) & 0xff;\n    out[op++] = (in5 >>> 16) & 0xff;\n    out[op++] = (in5 >>> 24) & 0xff;\n    out[op++] = (in6 >>> 0) & 0xff;\n    out[op++] = (in6 >>> 8) & 0xff;\n    out[op++] = (in6 >>> 16) & 0xff;\n    out[op++] = (in6 >>> 24) & 0xff;\n    out[op++] = (in7 >>> 0) & 0xff;\n    out[op++] = (in7 >>> 8) & 0xff;\n    out[op++] = (in7 >>> 16) & 0xff;\n    out[op] = (in7 >>> 24) & 0xff;\n}\nexport function fastUnpack32_9(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    const in6 = inValues[inPos + 6] >>> 0;\n    const in7 = inValues[inPos + 7] >>> 0;\n    const in8 = inValues[inPos + 8] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x1ff;\n    out[op++] = (in0 >>> 9) & 0x1ff;\n    out[op++] = (in0 >>> 18) & 0x1ff;\n    out[op++] = ((in0 >>> 27) | ((in1 & 0xf) << 5)) & 0x1ff;\n    out[op++] = (in1 >>> 4) & 0x1ff;\n    out[op++] = (in1 >>> 13) & 0x1ff;\n    out[op++] = (in1 >>> 22) & 0x1ff;\n    out[op++] = ((in1 >>> 31) | ((in2 & 0xff) << 1)) & 0x1ff;\n    out[op++] = (in2 >>> 8) & 0x1ff;\n    out[op++] = (in2 >>> 17) & 0x1ff;\n    out[op++] = ((in2 >>> 26) | ((in3 & 0x7) << 6)) & 0x1ff;\n    out[op++] = (in3 >>> 3) & 0x1ff;\n    out[op++] = (in3 >>> 12) & 0x1ff;\n    out[op++] = (in3 >>> 21) & 0x1ff;\n    out[op++] = ((in3 >>> 30) | ((in4 & 0x7f) << 2)) & 0x1ff;\n    out[op++] = (in4 >>> 7) & 0x1ff;\n    out[op++] = (in4 >>> 16) & 0x1ff;\n    out[op++] = ((in4 >>> 25) | ((in5 & 0x3) << 7)) & 0x1ff;\n    out[op++] = (in5 >>> 2) & 0x1ff;\n    out[op++] = (in5 >>> 11) & 0x1ff;\n    out[op++] = (in5 >>> 20) & 0x1ff;\n    out[op++] = ((in5 >>> 29) | ((in6 & 0x3f) << 3)) & 0x1ff;\n    out[op++] = (in6 >>> 6) & 0x1ff;\n    out[op++] = (in6 >>> 15) & 0x1ff;\n    out[op++] = ((in6 >>> 24) | ((in7 & 0x1) << 8)) & 0x1ff;\n    out[op++] = (in7 >>> 1) & 0x1ff;\n    out[op++] = (in7 >>> 10) & 0x1ff;\n    out[op++] = (in7 >>> 19) & 0x1ff;\n    out[op++] = ((in7 >>> 28) | ((in8 & 0x1f) << 4)) & 0x1ff;\n    out[op++] = (in8 >>> 5) & 0x1ff;\n    out[op++] = (in8 >>> 14) & 0x1ff;\n    out[op] = (in8 >>> 23) & 0x1ff;\n}\nexport function fastUnpack32_10(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    const in6 = inValues[inPos + 6] >>> 0;\n    const in7 = inValues[inPos + 7] >>> 0;\n    const in8 = inValues[inPos + 8] >>> 0;\n    const in9 = inValues[inPos + 9] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x3ff;\n    out[op++] = (in0 >>> 10) & 0x3ff;\n    out[op++] = (in0 >>> 20) & 0x3ff;\n    out[op++] = ((in0 >>> 30) | ((in1 & 0xff) << 2)) & 0x3ff;\n    out[op++] = (in1 >>> 8) & 0x3ff;\n    out[op++] = (in1 >>> 18) & 0x3ff;\n    out[op++] = ((in1 >>> 28) | ((in2 & 0x3f) << 4)) & 0x3ff;\n    out[op++] = (in2 >>> 6) & 0x3ff;\n    out[op++] = (in2 >>> 16) & 0x3ff;\n    out[op++] = ((in2 >>> 26) | ((in3 & 0xf) << 6)) & 0x3ff;\n    out[op++] = (in3 >>> 4) & 0x3ff;\n    out[op++] = (in3 >>> 14) & 0x3ff;\n    out[op++] = ((in3 >>> 24) | ((in4 & 0x3) << 8)) & 0x3ff;\n    out[op++] = (in4 >>> 2) & 0x3ff;\n    out[op++] = (in4 >>> 12) & 0x3ff;\n    out[op++] = (in4 >>> 22) & 0x3ff;\n    out[op++] = (in5 >>> 0) & 0x3ff;\n    out[op++] = (in5 >>> 10) & 0x3ff;\n    out[op++] = (in5 >>> 20) & 0x3ff;\n    out[op++] = ((in5 >>> 30) | ((in6 & 0xff) << 2)) & 0x3ff;\n    out[op++] = (in6 >>> 8) & 0x3ff;\n    out[op++] = (in6 >>> 18) & 0x3ff;\n    out[op++] = ((in6 >>> 28) | ((in7 & 0x3f) << 4)) & 0x3ff;\n    out[op++] = (in7 >>> 6) & 0x3ff;\n    out[op++] = (in7 >>> 16) & 0x3ff;\n    out[op++] = ((in7 >>> 26) | ((in8 & 0xf) << 6)) & 0x3ff;\n    out[op++] = (in8 >>> 4) & 0x3ff;\n    out[op++] = (in8 >>> 14) & 0x3ff;\n    out[op++] = ((in8 >>> 24) | ((in9 & 0x3) << 8)) & 0x3ff;\n    out[op++] = (in9 >>> 2) & 0x3ff;\n    out[op++] = (in9 >>> 12) & 0x3ff;\n    out[op] = (in9 >>> 22) & 0x3ff;\n}\nexport function fastUnpack32_11(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    const in6 = inValues[inPos + 6] >>> 0;\n    const in7 = inValues[inPos + 7] >>> 0;\n    const in8 = inValues[inPos + 8] >>> 0;\n    const in9 = inValues[inPos + 9] >>> 0;\n    const in10 = inValues[inPos + 10] >>> 0;\n    out[op++] = (in0 >>> 0) & 0x7ff;\n    out[op++] = (in0 >>> 11) & 0x7ff;\n    out[op++] = ((in0 >>> 22) | ((in1 & 0x1) << 10)) & 0x7ff;\n    out[op++] = (in1 >>> 1) & 0x7ff;\n    out[op++] = (in1 >>> 12) & 0x7ff;\n    out[op++] = ((in1 >>> 23) | ((in2 & 0x3) << 9)) & 0x7ff;\n    out[op++] = (in2 >>> 2) & 0x7ff;\n    out[op++] = (in2 >>> 13) & 0x7ff;\n    out[op++] = ((in2 >>> 24) | ((in3 & 0x7) << 8)) & 0x7ff;\n    out[op++] = (in3 >>> 3) & 0x7ff;\n    out[op++] = (in3 >>> 14) & 0x7ff;\n    out[op++] = ((in3 >>> 25) | ((in4 & 0xf) << 7)) & 0x7ff;\n    out[op++] = (in4 >>> 4) & 0x7ff;\n    out[op++] = (in4 >>> 15) & 0x7ff;\n    out[op++] = ((in4 >>> 26) | ((in5 & 0x1f) << 6)) & 0x7ff;\n    out[op++] = (in5 >>> 5) & 0x7ff;\n    out[op++] = (in5 >>> 16) & 0x7ff;\n    out[op++] = ((in5 >>> 27) | ((in6 & 0x3f) << 5)) & 0x7ff;\n    out[op++] = (in6 >>> 6) & 0x7ff;\n    out[op++] = (in6 >>> 17) & 0x7ff;\n    out[op++] = ((in6 >>> 28) | ((in7 & 0x7f) << 4)) & 0x7ff;\n    out[op++] = (in7 >>> 7) & 0x7ff;\n    out[op++] = (in7 >>> 18) & 0x7ff;\n    out[op++] = ((in7 >>> 29) | ((in8 & 0xff) << 3)) & 0x7ff;\n    out[op++] = (in8 >>> 8) & 0x7ff;\n    out[op++] = (in8 >>> 19) & 0x7ff;\n    out[op++] = ((in8 >>> 30) | ((in9 & 0x1ff) << 2)) & 0x7ff;\n    out[op++] = (in9 >>> 9) & 0x7ff;\n    out[op++] = (in9 >>> 20) & 0x7ff;\n    out[op++] = ((in9 >>> 31) | ((in10 & 0x3ff) << 1)) & 0x7ff;\n    out[op++] = (in10 >>> 10) & 0x7ff;\n    out[op] = (in10 >>> 21) & 0x7ff;\n}\nexport function fastUnpack32_12(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    const in6 = inValues[inPos + 6] >>> 0;\n    const in7 = inValues[inPos + 7] >>> 0;\n    const in8 = inValues[inPos + 8] >>> 0;\n    const in9 = inValues[inPos + 9] >>> 0;\n    const in10 = inValues[inPos + 10] >>> 0;\n    const in11 = inValues[inPos + 11] >>> 0;\n    out[op++] = (in0 >>> 0) & 0xfff;\n    out[op++] = (in0 >>> 12) & 0xfff;\n    out[op++] = ((in0 >>> 24) | ((in1 & 0xf) << 8)) & 0xfff;\n    out[op++] = (in1 >>> 4) & 0xfff;\n    out[op++] = (in1 >>> 16) & 0xfff;\n    out[op++] = ((in1 >>> 28) | ((in2 & 0xff) << 4)) & 0xfff;\n    out[op++] = (in2 >>> 8) & 0xfff;\n    out[op++] = (in2 >>> 20) & 0xfff;\n    out[op++] = (in3 >>> 0) & 0xfff;\n    out[op++] = (in3 >>> 12) & 0xfff;\n    out[op++] = ((in3 >>> 24) | ((in4 & 0xf) << 8)) & 0xfff;\n    out[op++] = (in4 >>> 4) & 0xfff;\n    out[op++] = (in4 >>> 16) & 0xfff;\n    out[op++] = ((in4 >>> 28) | ((in5 & 0xff) << 4)) & 0xfff;\n    out[op++] = (in5 >>> 8) & 0xfff;\n    out[op++] = (in5 >>> 20) & 0xfff;\n    out[op++] = (in6 >>> 0) & 0xfff;\n    out[op++] = (in6 >>> 12) & 0xfff;\n    out[op++] = ((in6 >>> 24) | ((in7 & 0xf) << 8)) & 0xfff;\n    out[op++] = (in7 >>> 4) & 0xfff;\n    out[op++] = (in7 >>> 16) & 0xfff;\n    out[op++] = ((in7 >>> 28) | ((in8 & 0xff) << 4)) & 0xfff;\n    out[op++] = (in8 >>> 8) & 0xfff;\n    out[op++] = (in8 >>> 20) & 0xfff;\n    out[op++] = (in9 >>> 0) & 0xfff;\n    out[op++] = (in9 >>> 12) & 0xfff;\n    out[op++] = ((in9 >>> 24) | ((in10 & 0xf) << 8)) & 0xfff;\n    out[op++] = (in10 >>> 4) & 0xfff;\n    out[op++] = (in10 >>> 16) & 0xfff;\n    out[op++] = ((in10 >>> 28) | ((in11 & 0xff) << 4)) & 0xfff;\n    out[op++] = (in11 >>> 8) & 0xfff;\n    out[op] = (in11 >>> 20) & 0xfff;\n}\nexport function fastUnpack32_16(inValues, inPos, out, outPos) {\n    let op = outPos;\n    const in0 = inValues[inPos] >>> 0;\n    const in1 = inValues[inPos + 1] >>> 0;\n    const in2 = inValues[inPos + 2] >>> 0;\n    const in3 = inValues[inPos + 3] >>> 0;\n    const in4 = inValues[inPos + 4] >>> 0;\n    const in5 = inValues[inPos + 5] >>> 0;\n    const in6 = inValues[inPos + 6] >>> 0;\n    const in7 = inValues[inPos + 7] >>> 0;\n    const in8 = inValues[inPos + 8] >>> 0;\n    const in9 = inValues[inPos + 9] >>> 0;\n    const in10 = inValues[inPos + 10] >>> 0;\n    const in11 = inValues[inPos + 11] >>> 0;\n    const in12 = inValues[inPos + 12] >>> 0;\n    const in13 = inValues[inPos + 13] >>> 0;\n    const in14 = inValues[inPos + 14] >>> 0;\n    const in15 = inValues[inPos + 15] >>> 0;\n    out[op++] = (in0 >>> 0) & 0xffff;\n    out[op++] = (in0 >>> 16) & 0xffff;\n    out[op++] = (in1 >>> 0) & 0xffff;\n    out[op++] = (in1 >>> 16) & 0xffff;\n    out[op++] = (in2 >>> 0) & 0xffff;\n    out[op++] = (in2 >>> 16) & 0xffff;\n    out[op++] = (in3 >>> 0) & 0xffff;\n    out[op++] = (in3 >>> 16) & 0xffff;\n    out[op++] = (in4 >>> 0) & 0xffff;\n    out[op++] = (in4 >>> 16) & 0xffff;\n    out[op++] = (in5 >>> 0) & 0xffff;\n    out[op++] = (in5 >>> 16) & 0xffff;\n    out[op++] = (in6 >>> 0) & 0xffff;\n    out[op++] = (in6 >>> 16) & 0xffff;\n    out[op++] = (in7 >>> 0) & 0xffff;\n    out[op++] = (in7 >>> 16) & 0xffff;\n    out[op++] = (in8 >>> 0) & 0xffff;\n    out[op++] = (in8 >>> 16) & 0xffff;\n    out[op++] = (in9 >>> 0) & 0xffff;\n    out[op++] = (in9 >>> 16) & 0xffff;\n    out[op++] = (in10 >>> 0) & 0xffff;\n    out[op++] = (in10 >>> 16) & 0xffff;\n    out[op++] = (in11 >>> 0) & 0xffff;\n    out[op++] = (in11 >>> 16) & 0xffff;\n    out[op++] = (in12 >>> 0) & 0xffff;\n    out[op++] = (in12 >>> 16) & 0xffff;\n    out[op++] = (in13 >>> 0) & 0xffff;\n    out[op++] = (in13 >>> 16) & 0xffff;\n    out[op++] = (in14 >>> 0) & 0xffff;\n    out[op++] = (in14 >>> 16) & 0xffff;\n    out[op++] = (in15 >>> 0) & 0xffff;\n    out[op] = (in15 >>> 16) & 0xffff;\n}\nexport function fastUnpack256_1(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0x1;\n        out[op++] = (in0 >>> 1) & 0x1;\n        out[op++] = (in0 >>> 2) & 0x1;\n        out[op++] = (in0 >>> 3) & 0x1;\n        out[op++] = (in0 >>> 4) & 0x1;\n        out[op++] = (in0 >>> 5) & 0x1;\n        out[op++] = (in0 >>> 6) & 0x1;\n        out[op++] = (in0 >>> 7) & 0x1;\n        out[op++] = (in0 >>> 8) & 0x1;\n        out[op++] = (in0 >>> 9) & 0x1;\n        out[op++] = (in0 >>> 10) & 0x1;\n        out[op++] = (in0 >>> 11) & 0x1;\n        out[op++] = (in0 >>> 12) & 0x1;\n        out[op++] = (in0 >>> 13) & 0x1;\n        out[op++] = (in0 >>> 14) & 0x1;\n        out[op++] = (in0 >>> 15) & 0x1;\n        out[op++] = (in0 >>> 16) & 0x1;\n        out[op++] = (in0 >>> 17) & 0x1;\n        out[op++] = (in0 >>> 18) & 0x1;\n        out[op++] = (in0 >>> 19) & 0x1;\n        out[op++] = (in0 >>> 20) & 0x1;\n        out[op++] = (in0 >>> 21) & 0x1;\n        out[op++] = (in0 >>> 22) & 0x1;\n        out[op++] = (in0 >>> 23) & 0x1;\n        out[op++] = (in0 >>> 24) & 0x1;\n        out[op++] = (in0 >>> 25) & 0x1;\n        out[op++] = (in0 >>> 26) & 0x1;\n        out[op++] = (in0 >>> 27) & 0x1;\n        out[op++] = (in0 >>> 28) & 0x1;\n        out[op++] = (in0 >>> 29) & 0x1;\n        out[op++] = (in0 >>> 30) & 0x1;\n        out[op++] = (in0 >>> 31) & 0x1;\n    }\n}\nexport function fastUnpack256_2(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        const in1 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0x3;\n        out[op++] = (in0 >>> 2) & 0x3;\n        out[op++] = (in0 >>> 4) & 0x3;\n        out[op++] = (in0 >>> 6) & 0x3;\n        out[op++] = (in0 >>> 8) & 0x3;\n        out[op++] = (in0 >>> 10) & 0x3;\n        out[op++] = (in0 >>> 12) & 0x3;\n        out[op++] = (in0 >>> 14) & 0x3;\n        out[op++] = (in0 >>> 16) & 0x3;\n        out[op++] = (in0 >>> 18) & 0x3;\n        out[op++] = (in0 >>> 20) & 0x3;\n        out[op++] = (in0 >>> 22) & 0x3;\n        out[op++] = (in0 >>> 24) & 0x3;\n        out[op++] = (in0 >>> 26) & 0x3;\n        out[op++] = (in0 >>> 28) & 0x3;\n        out[op++] = (in0 >>> 30) & 0x3;\n        out[op++] = (in1 >>> 0) & 0x3;\n        out[op++] = (in1 >>> 2) & 0x3;\n        out[op++] = (in1 >>> 4) & 0x3;\n        out[op++] = (in1 >>> 6) & 0x3;\n        out[op++] = (in1 >>> 8) & 0x3;\n        out[op++] = (in1 >>> 10) & 0x3;\n        out[op++] = (in1 >>> 12) & 0x3;\n        out[op++] = (in1 >>> 14) & 0x3;\n        out[op++] = (in1 >>> 16) & 0x3;\n        out[op++] = (in1 >>> 18) & 0x3;\n        out[op++] = (in1 >>> 20) & 0x3;\n        out[op++] = (in1 >>> 22) & 0x3;\n        out[op++] = (in1 >>> 24) & 0x3;\n        out[op++] = (in1 >>> 26) & 0x3;\n        out[op++] = (in1 >>> 28) & 0x3;\n        out[op++] = (in1 >>> 30) & 0x3;\n    }\n}\nexport function fastUnpack256_3(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        const in1 = inValues[ip++] >>> 0;\n        const in2 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0x7;\n        out[op++] = (in0 >>> 3) & 0x7;\n        out[op++] = (in0 >>> 6) & 0x7;\n        out[op++] = (in0 >>> 9) & 0x7;\n        out[op++] = (in0 >>> 12) & 0x7;\n        out[op++] = (in0 >>> 15) & 0x7;\n        out[op++] = (in0 >>> 18) & 0x7;\n        out[op++] = (in0 >>> 21) & 0x7;\n        out[op++] = (in0 >>> 24) & 0x7;\n        out[op++] = (in0 >>> 27) & 0x7;\n        out[op++] = ((in0 >>> 30) | ((in1 & 0x1) << 2)) & 0x7;\n        out[op++] = (in1 >>> 1) & 0x7;\n        out[op++] = (in1 >>> 4) & 0x7;\n        out[op++] = (in1 >>> 7) & 0x7;\n        out[op++] = (in1 >>> 10) & 0x7;\n        out[op++] = (in1 >>> 13) & 0x7;\n        out[op++] = (in1 >>> 16) & 0x7;\n        out[op++] = (in1 >>> 19) & 0x7;\n        out[op++] = (in1 >>> 22) & 0x7;\n        out[op++] = (in1 >>> 25) & 0x7;\n        out[op++] = (in1 >>> 28) & 0x7;\n        out[op++] = ((in1 >>> 31) | ((in2 & 0x3) << 1)) & 0x7;\n        out[op++] = (in2 >>> 2) & 0x7;\n        out[op++] = (in2 >>> 5) & 0x7;\n        out[op++] = (in2 >>> 8) & 0x7;\n        out[op++] = (in2 >>> 11) & 0x7;\n        out[op++] = (in2 >>> 14) & 0x7;\n        out[op++] = (in2 >>> 17) & 0x7;\n        out[op++] = (in2 >>> 20) & 0x7;\n        out[op++] = (in2 >>> 23) & 0x7;\n        out[op++] = (in2 >>> 26) & 0x7;\n        out[op++] = (in2 >>> 29) & 0x7;\n    }\n}\nexport function fastUnpack256_4(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        const in1 = inValues[ip++] >>> 0;\n        const in2 = inValues[ip++] >>> 0;\n        const in3 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0xf;\n        out[op++] = (in0 >>> 4) & 0xf;\n        out[op++] = (in0 >>> 8) & 0xf;\n        out[op++] = (in0 >>> 12) & 0xf;\n        out[op++] = (in0 >>> 16) & 0xf;\n        out[op++] = (in0 >>> 20) & 0xf;\n        out[op++] = (in0 >>> 24) & 0xf;\n        out[op++] = (in0 >>> 28) & 0xf;\n        out[op++] = (in1 >>> 0) & 0xf;\n        out[op++] = (in1 >>> 4) & 0xf;\n        out[op++] = (in1 >>> 8) & 0xf;\n        out[op++] = (in1 >>> 12) & 0xf;\n        out[op++] = (in1 >>> 16) & 0xf;\n        out[op++] = (in1 >>> 20) & 0xf;\n        out[op++] = (in1 >>> 24) & 0xf;\n        out[op++] = (in1 >>> 28) & 0xf;\n        out[op++] = (in2 >>> 0) & 0xf;\n        out[op++] = (in2 >>> 4) & 0xf;\n        out[op++] = (in2 >>> 8) & 0xf;\n        out[op++] = (in2 >>> 12) & 0xf;\n        out[op++] = (in2 >>> 16) & 0xf;\n        out[op++] = (in2 >>> 20) & 0xf;\n        out[op++] = (in2 >>> 24) & 0xf;\n        out[op++] = (in2 >>> 28) & 0xf;\n        out[op++] = (in3 >>> 0) & 0xf;\n        out[op++] = (in3 >>> 4) & 0xf;\n        out[op++] = (in3 >>> 8) & 0xf;\n        out[op++] = (in3 >>> 12) & 0xf;\n        out[op++] = (in3 >>> 16) & 0xf;\n        out[op++] = (in3 >>> 20) & 0xf;\n        out[op++] = (in3 >>> 24) & 0xf;\n        out[op++] = (in3 >>> 28) & 0xf;\n    }\n}\nexport function fastUnpack256_5(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        const in1 = inValues[ip++] >>> 0;\n        const in2 = inValues[ip++] >>> 0;\n        const in3 = inValues[ip++] >>> 0;\n        const in4 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0x1f;\n        out[op++] = (in0 >>> 5) & 0x1f;\n        out[op++] = (in0 >>> 10) & 0x1f;\n        out[op++] = (in0 >>> 15) & 0x1f;\n        out[op++] = (in0 >>> 20) & 0x1f;\n        out[op++] = (in0 >>> 25) & 0x1f;\n        out[op++] = ((in0 >>> 30) | ((in1 & 0x7) << 2)) & 0x1f;\n        out[op++] = (in1 >>> 3) & 0x1f;\n        out[op++] = (in1 >>> 8) & 0x1f;\n        out[op++] = (in1 >>> 13) & 0x1f;\n        out[op++] = (in1 >>> 18) & 0x1f;\n        out[op++] = (in1 >>> 23) & 0x1f;\n        out[op++] = ((in1 >>> 28) | ((in2 & 0x1) << 4)) & 0x1f;\n        out[op++] = (in2 >>> 1) & 0x1f;\n        out[op++] = (in2 >>> 6) & 0x1f;\n        out[op++] = (in2 >>> 11) & 0x1f;\n        out[op++] = (in2 >>> 16) & 0x1f;\n        out[op++] = (in2 >>> 21) & 0x1f;\n        out[op++] = (in2 >>> 26) & 0x1f;\n        out[op++] = ((in2 >>> 31) | ((in3 & 0xf) << 1)) & 0x1f;\n        out[op++] = (in3 >>> 4) & 0x1f;\n        out[op++] = (in3 >>> 9) & 0x1f;\n        out[op++] = (in3 >>> 14) & 0x1f;\n        out[op++] = (in3 >>> 19) & 0x1f;\n        out[op++] = (in3 >>> 24) & 0x1f;\n        out[op++] = ((in3 >>> 29) | ((in4 & 0x3) << 3)) & 0x1f;\n        out[op++] = (in4 >>> 2) & 0x1f;\n        out[op++] = (in4 >>> 7) & 0x1f;\n        out[op++] = (in4 >>> 12) & 0x1f;\n        out[op++] = (in4 >>> 17) & 0x1f;\n        out[op++] = (in4 >>> 22) & 0x1f;\n        out[op++] = (in4 >>> 27) & 0x1f;\n    }\n}\nexport function fastUnpack256_6(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        const in1 = inValues[ip++] >>> 0;\n        const in2 = inValues[ip++] >>> 0;\n        const in3 = inValues[ip++] >>> 0;\n        const in4 = inValues[ip++] >>> 0;\n        const in5 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0x3f;\n        out[op++] = (in0 >>> 6) & 0x3f;\n        out[op++] = (in0 >>> 12) & 0x3f;\n        out[op++] = (in0 >>> 18) & 0x3f;\n        out[op++] = (in0 >>> 24) & 0x3f;\n        out[op++] = ((in0 >>> 30) | ((in1 & 0xf) << 2)) & 0x3f;\n        out[op++] = (in1 >>> 4) & 0x3f;\n        out[op++] = (in1 >>> 10) & 0x3f;\n        out[op++] = (in1 >>> 16) & 0x3f;\n        out[op++] = (in1 >>> 22) & 0x3f;\n        out[op++] = ((in1 >>> 28) | ((in2 & 0x3) << 4)) & 0x3f;\n        out[op++] = (in2 >>> 2) & 0x3f;\n        out[op++] = (in2 >>> 8) & 0x3f;\n        out[op++] = (in2 >>> 14) & 0x3f;\n        out[op++] = (in2 >>> 20) & 0x3f;\n        out[op++] = (in2 >>> 26) & 0x3f;\n        out[op++] = (in3 >>> 0) & 0x3f;\n        out[op++] = (in3 >>> 6) & 0x3f;\n        out[op++] = (in3 >>> 12) & 0x3f;\n        out[op++] = (in3 >>> 18) & 0x3f;\n        out[op++] = (in3 >>> 24) & 0x3f;\n        out[op++] = ((in3 >>> 30) | ((in4 & 0xf) << 2)) & 0x3f;\n        out[op++] = (in4 >>> 4) & 0x3f;\n        out[op++] = (in4 >>> 10) & 0x3f;\n        out[op++] = (in4 >>> 16) & 0x3f;\n        out[op++] = (in4 >>> 22) & 0x3f;\n        out[op++] = ((in4 >>> 28) | ((in5 & 0x3) << 4)) & 0x3f;\n        out[op++] = (in5 >>> 2) & 0x3f;\n        out[op++] = (in5 >>> 8) & 0x3f;\n        out[op++] = (in5 >>> 14) & 0x3f;\n        out[op++] = (in5 >>> 20) & 0x3f;\n        out[op++] = (in5 >>> 26) & 0x3f;\n    }\n}\nexport function fastUnpack256_7(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        const in1 = inValues[ip++] >>> 0;\n        const in2 = inValues[ip++] >>> 0;\n        const in3 = inValues[ip++] >>> 0;\n        const in4 = inValues[ip++] >>> 0;\n        const in5 = inValues[ip++] >>> 0;\n        const in6 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0x7f;\n        out[op++] = (in0 >>> 7) & 0x7f;\n        out[op++] = (in0 >>> 14) & 0x7f;\n        out[op++] = (in0 >>> 21) & 0x7f;\n        out[op++] = ((in0 >>> 28) | ((in1 & 0x7) << 4)) & 0x7f;\n        out[op++] = (in1 >>> 3) & 0x7f;\n        out[op++] = (in1 >>> 10) & 0x7f;\n        out[op++] = (in1 >>> 17) & 0x7f;\n        out[op++] = (in1 >>> 24) & 0x7f;\n        out[op++] = ((in1 >>> 31) | ((in2 & 0x3f) << 1)) & 0x7f;\n        out[op++] = (in2 >>> 6) & 0x7f;\n        out[op++] = (in2 >>> 13) & 0x7f;\n        out[op++] = (in2 >>> 20) & 0x7f;\n        out[op++] = ((in2 >>> 27) | ((in3 & 0x3) << 5)) & 0x7f;\n        out[op++] = (in3 >>> 2) & 0x7f;\n        out[op++] = (in3 >>> 9) & 0x7f;\n        out[op++] = (in3 >>> 16) & 0x7f;\n        out[op++] = (in3 >>> 23) & 0x7f;\n        out[op++] = ((in3 >>> 30) | ((in4 & 0x1f) << 2)) & 0x7f;\n        out[op++] = (in4 >>> 5) & 0x7f;\n        out[op++] = (in4 >>> 12) & 0x7f;\n        out[op++] = (in4 >>> 19) & 0x7f;\n        out[op++] = ((in4 >>> 26) | ((in5 & 0x1) << 6)) & 0x7f;\n        out[op++] = (in5 >>> 1) & 0x7f;\n        out[op++] = (in5 >>> 8) & 0x7f;\n        out[op++] = (in5 >>> 15) & 0x7f;\n        out[op++] = (in5 >>> 22) & 0x7f;\n        out[op++] = ((in5 >>> 29) | ((in6 & 0xf) << 3)) & 0x7f;\n        out[op++] = (in6 >>> 4) & 0x7f;\n        out[op++] = (in6 >>> 11) & 0x7f;\n        out[op++] = (in6 >>> 18) & 0x7f;\n        out[op++] = (in6 >>> 25) & 0x7f;\n    }\n}\nexport function fastUnpack256_8(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let c = 0; c < 8; c++) {\n        const in0 = inValues[ip++] >>> 0;\n        const in1 = inValues[ip++] >>> 0;\n        const in2 = inValues[ip++] >>> 0;\n        const in3 = inValues[ip++] >>> 0;\n        const in4 = inValues[ip++] >>> 0;\n        const in5 = inValues[ip++] >>> 0;\n        const in6 = inValues[ip++] >>> 0;\n        const in7 = inValues[ip++] >>> 0;\n        out[op++] = (in0 >>> 0) & 0xff;\n        out[op++] = (in0 >>> 8) & 0xff;\n        out[op++] = (in0 >>> 16) & 0xff;\n        out[op++] = (in0 >>> 24) & 0xff;\n        out[op++] = (in1 >>> 0) & 0xff;\n        out[op++] = (in1 >>> 8) & 0xff;\n        out[op++] = (in1 >>> 16) & 0xff;\n        out[op++] = (in1 >>> 24) & 0xff;\n        out[op++] = (in2 >>> 0) & 0xff;\n        out[op++] = (in2 >>> 8) & 0xff;\n        out[op++] = (in2 >>> 16) & 0xff;\n        out[op++] = (in2 >>> 24) & 0xff;\n        out[op++] = (in3 >>> 0) & 0xff;\n        out[op++] = (in3 >>> 8) & 0xff;\n        out[op++] = (in3 >>> 16) & 0xff;\n        out[op++] = (in3 >>> 24) & 0xff;\n        out[op++] = (in4 >>> 0) & 0xff;\n        out[op++] = (in4 >>> 8) & 0xff;\n        out[op++] = (in4 >>> 16) & 0xff;\n        out[op++] = (in4 >>> 24) & 0xff;\n        out[op++] = (in5 >>> 0) & 0xff;\n        out[op++] = (in5 >>> 8) & 0xff;\n        out[op++] = (in5 >>> 16) & 0xff;\n        out[op++] = (in5 >>> 24) & 0xff;\n        out[op++] = (in6 >>> 0) & 0xff;\n        out[op++] = (in6 >>> 8) & 0xff;\n        out[op++] = (in6 >>> 16) & 0xff;\n        out[op++] = (in6 >>> 24) & 0xff;\n        out[op++] = (in7 >>> 0) & 0xff;\n        out[op++] = (in7 >>> 8) & 0xff;\n        out[op++] = (in7 >>> 16) & 0xff;\n        out[op++] = (in7 >>> 24) & 0xff;\n    }\n}\nexport function fastUnpack256_16(inValues, inPos, out, outPos) {\n    let op = outPos;\n    let ip = inPos;\n    for (let i = 0; i < 128; i++) {\n        const in0 = inValues[ip++] >>> 0;\n        out[op++] = in0 & 0xffff;\n        out[op++] = (in0 >>> 16) & 0xffff;\n    }\n}\nexport function fastUnpack256_Generic(inValues, inPos, out, outPos, bitWidth) {\n    const mask = MASKS[bitWidth] >>> 0;\n    let inputWordIndex = inPos;\n    let bitOffset = 0;\n    let currentWord = inValues[inputWordIndex] >>> 0;\n    let op = outPos;\n    for (let c = 0; c < 8; c++) {\n        for (let i = 0; i < 32; i++) {\n            if (bitOffset + bitWidth <= 32) {\n                const value = (currentWord >>> bitOffset) & mask;\n                out[op + i] = value | 0;\n                bitOffset += bitWidth;\n                if (bitOffset === 32) {\n                    bitOffset = 0;\n                    inputWordIndex++;\n                    if (i !== 31) {\n                        currentWord = inValues[inputWordIndex] >>> 0;\n                    }\n                }\n            }\n            else {\n                const lowBits = 32 - bitOffset;\n                const low = currentWord >>> bitOffset;\n                inputWordIndex++;\n                currentWord = inValues[inputWordIndex] >>> 0;\n                const highBits = bitWidth - lowBits;\n                const highMask = (-1 >>> (32 - highBits)) >>> 0;\n                const high = currentWord & highMask;\n                const value = (low | (high << lowBits)) & mask;\n                out[op + i] = value | 0;\n                bitOffset = highBits;\n            }\n        }\n        op += 32;\n        bitOffset = 0;\n        if (c < 7) {\n            currentWord = inValues[inputWordIndex] >>> 0;\n        }\n    }\n}\n//# sourceMappingURL=fastPforUnpack.js.map", "import { MASKS, DEFAULT_PAGE_SIZE, BLOCK_SIZE, greatestMultiple, roundUpToMultipleOf32, normalizePageSize, } from \"./fastPforShared\";\nimport { fastUnpack32_2, fastUnpack32_3, fastUnpack32_4, fastUnpack32_5, fastUnpack32_6, fastUnpack32_7, fastUnpack32_8, fastUnpack32_9, fastUnpack32_10, fastUnpack32_11, fastUnpack32_12, fastUnpack32_16, fastUnpack256_1, fastUnpack256_2, fastUnpack256_3, fastUnpack256_4, fastUnpack256_5, fastUnpack256_6, fastUnpack256_7, fastUnpack256_8, fastUnpack256_16, fastUnpack256_Generic, } from \"./fastPforUnpack\";\nconst MAX_BIT_WIDTH = 32;\nconst BIT_WIDTH_SLOTS = MAX_BIT_WIDTH + 1;\nconst PAGE_SIZE = normalizePageSize(DEFAULT_PAGE_SIZE);\nconst BYTE_CONTAINER_SIZE = ((3 * PAGE_SIZE) / BLOCK_SIZE + PAGE_SIZE) | 0;\n/**\n * Creates an isolated workspace for decoding.\n * Reusing a workspace across calls avoids repeated allocations.\n */\nexport function createDecoderWorkspace() {\n    const byteContainer = new Uint8Array(BYTE_CONTAINER_SIZE);\n    return {\n        dataToBePacked: new Array(BIT_WIDTH_SLOTS),\n        dataPointers: new Int32Array(BIT_WIDTH_SLOTS),\n        byteContainer,\n        byteContainerI32: new Int32Array(byteContainer.buffer, byteContainer.byteOffset, byteContainer.byteLength >>> 2),\n        exceptionSizes: new Int32Array(BIT_WIDTH_SLOTS),\n    };\n}\nexport function createFastPforWireDecodeWorkspace(initialEncodedWordCapacity = 16) {\n    if (initialEncodedWordCapacity < 0) {\n        throw new RangeError(`initialEncodedWordCapacity must be >= 0, got ${initialEncodedWordCapacity}`);\n    }\n    const capacity = Math.max(16, initialEncodedWordCapacity | 0);\n    return {\n        encodedWords: new Uint32Array(capacity),\n        decoderWorkspace: createDecoderWorkspace(),\n    };\n}\nexport function ensureFastPforWireEncodedWordsCapacity(workspace, requiredWordCount) {\n    if (requiredWordCount <= workspace.encodedWords.length)\n        return workspace.encodedWords;\n    const next = new Uint32Array(Math.max(16, requiredWordCount * 2));\n    workspace.encodedWords = next;\n    return next;\n}\nfunction materializeByteContainer(inValues, byteContainerStart, byteSize, workspace) {\n    if (workspace.byteContainer.length < byteSize) {\n        workspace.byteContainer = new Uint8Array(byteSize * 2);\n        workspace.byteContainerI32 = undefined;\n    }\n    const byteContainer = workspace.byteContainer;\n    const numFullInts = byteSize >>> 2;\n    if ((byteContainer.byteOffset & 3) === 0) {\n        let intView = workspace.byteContainerI32;\n        if (!intView ||\n            intView.buffer !== byteContainer.buffer ||\n            intView.byteOffset !== byteContainer.byteOffset ||\n            intView.length < numFullInts) {\n            intView = workspace.byteContainerI32 = new Int32Array(byteContainer.buffer, byteContainer.byteOffset, byteContainer.byteLength >>> 2);\n        }\n        intView.set(inValues.subarray(byteContainerStart, byteContainerStart + numFullInts));\n    }\n    else {\n        for (let i = 0; i < numFullInts; i = (i + 1) | 0) {\n            const val = inValues[(byteContainerStart + i) | 0] | 0;\n            const base = i << 2;\n            byteContainer[base] = val & 0xff;\n            byteContainer[(base + 1) | 0] = (val >>> 8) & 0xff;\n            byteContainer[(base + 2) | 0] = (val >>> 16) & 0xff;\n            byteContainer[(base + 3) | 0] = (val >>> 24) & 0xff;\n        }\n    }\n    const remainder = byteSize & 3;\n    if (remainder > 0) {\n        const lastIntIdx = (byteContainerStart + numFullInts) | 0;\n        const lastVal = inValues[lastIntIdx] | 0;\n        const base = numFullInts << 2;\n        for (let r = 0; r < remainder; r = (r + 1) | 0) {\n            byteContainer[(base + r) | 0] = (lastVal >>> (r << 3)) & 0xff;\n        }\n    }\n    return byteContainer;\n}\n/**\n * Unpacks the per-bitWidth \"exception streams\" described by the page's bitmap.\n *\n * @remarks\n * For each bit-width present in the bitmap, a stream header gives the count of outlier values for that\n * bit-width, followed by packed bits representing those values.\n *\n * @param inValues - Packed input (32-bit words).\n * @param inExcept - Offset (32-bit word index) where the exception bitmap starts.\n * @param workspace - Decoder workspace used to store the unpacked exception streams.\n * @returns The new input offset (32-bit word index) after consuming all exception streams.\n */\nfunction unpackExceptionStreams(inValues, inExcept, workspace) {\n    const bitmap = inValues[inExcept++] | 0;\n    const dataToBePacked = workspace.dataToBePacked;\n    for (let bitWidth = 2; bitWidth <= MAX_BIT_WIDTH; bitWidth = (bitWidth + 1) | 0) {\n        if (((bitmap >>> (bitWidth - 1)) & 1) === 0)\n            continue;\n        if (inExcept >= inValues.length) {\n            throw new Error(`FastPFOR decode: truncated exception stream header (bitWidth=${bitWidth}, streamWordIndex=${inExcept}, needWords=1, availableWords=${inValues.length - inExcept}, encodedWords=${inValues.length})`);\n        }\n        const size = inValues[inExcept++] >>> 0;\n        const roundedUp = roundUpToMultipleOf32(size);\n        const wordsNeeded = (size * bitWidth + 31) >>> 5;\n        if (inExcept + wordsNeeded > inValues.length) {\n            throw new Error(`FastPFOR decode: truncated exception stream (bitWidth=${bitWidth}, size=${size}, streamWordIndex=${inExcept}, needWords=${wordsNeeded}, availableWords=${inValues.length - inExcept}, encodedWords=${inValues.length})`);\n        }\n        let exceptionStream = dataToBePacked[bitWidth];\n        if (!exceptionStream || exceptionStream.length < roundedUp) {\n            exceptionStream = dataToBePacked[bitWidth] = new Uint32Array(roundedUp);\n        }\n        let j = 0;\n        for (; j < size; j = (j + 32) | 0) {\n            fastUnpack32(inValues, inExcept, exceptionStream, j, bitWidth);\n            inExcept = (inExcept + bitWidth) | 0;\n        }\n        const overflow = (j - size) | 0;\n        inExcept = (inExcept - ((overflow * bitWidth) >>> 5)) | 0;\n        workspace.exceptionSizes[bitWidth] = size;\n    }\n    return inExcept;\n}\n/**\n * Unpacks one 256-value block from the packed bitstream using a specialized implementation for common widths.\n *\n * @param inValues - Packed input (32-bit words).\n * @param inPos - Input offset (32-bit word index) where the packed block starts.\n * @param out - Output buffer.\n * @param outPos - Output offset where the 256 values will be written.\n * @param bitWidth - Base bit-width used for this block.\n * @returns The new input offset (32-bit word index) right after the packed block data.\n */\nfunction unpackBlock256(inValues, inPos, out, outPos, bitWidth) {\n    switch (bitWidth) {\n        case 1:\n            fastUnpack256_1(inValues, inPos, out, outPos);\n            break;\n        case 2:\n            fastUnpack256_2(inValues, inPos, out, outPos);\n            break;\n        case 3:\n            fastUnpack256_3(inValues, inPos, out, outPos);\n            break;\n        case 4:\n            fastUnpack256_4(inValues, inPos, out, outPos);\n            break;\n        case 5:\n            fastUnpack256_5(inValues, inPos, out, outPos);\n            break;\n        case 6:\n            fastUnpack256_6(inValues, inPos, out, outPos);\n            break;\n        case 7:\n            fastUnpack256_7(inValues, inPos, out, outPos);\n            break;\n        case 8:\n            fastUnpack256_8(inValues, inPos, out, outPos);\n            break;\n        case 16:\n            fastUnpack256_16(inValues, inPos, out, outPos);\n            break;\n        default:\n            fastUnpack256_Generic(inValues, inPos, out, outPos, bitWidth);\n            break;\n    }\n    return (inPos + (bitWidth << 3)) | 0;\n}\n/**\n * Reads and validates the 2-byte block header from the byteContainer.\n *\n * @remarks\n * The header is `[bitWidth, exceptionCount]`, both stored as single bytes.\n *\n * @param byteContainer - Byte metadata buffer for the page.\n * @param byteContainerLen - The valid byte length in `byteContainer` for this page.\n * @param bytePosIn - Current offset in `byteContainer`.\n * @param block - Block index within the page (for error messages).\n * @returns The parsed header and the updated `bytePosIn`.\n */\nfunction readBlockHeader(byteContainer, byteContainerLen, bytePosIn, block) {\n    if (bytePosIn + 2 > byteContainerLen) {\n        throw new Error(`FastPFOR decode: byteContainer underflow at block=${block} (need 2 bytes for [bitWidth, exceptionCount], bytePos=${bytePosIn}, byteSize=${byteContainerLen})`);\n    }\n    const bitWidth = byteContainer[bytePosIn++];\n    const exceptionCount = byteContainer[bytePosIn++];\n    if (bitWidth > MAX_BIT_WIDTH) {\n        throw new Error(`FastPFOR decode: invalid bitWidth=${bitWidth} at block=${block} (expected 0..${MAX_BIT_WIDTH}). This likely indicates corrupted or truncated input.`);\n    }\n    return { bitWidth, exceptionCount, bytePosIn };\n}\n/**\n * Reads and validates the exception header for a block.\n *\n * @remarks\n * The header contains `maxBits` (1 byte), which defines the width of the outlier values as\n * `exceptionBitWidth = maxBits - bitWidth`.\n *\n * @param byteContainer - Byte metadata buffer for the page.\n * @param byteContainerLen - The valid byte length in `byteContainer` for this page.\n * @param bytePosIn - Current offset in `byteContainer`.\n * @param bitWidth - Base bit-width for the block.\n * @param exceptionCount - Number of exceptions/outliers in this block.\n * @param block - Block index within the page (for error messages).\n * @returns Parsed `maxBits`, `exceptionBitWidth`, and the updated `bytePosIn`.\n */\nfunction readBlockExceptionHeader(byteContainer, byteContainerLen, bytePosIn, bitWidth, exceptionCount, block) {\n    if (bytePosIn + 1 > byteContainerLen) {\n        throw new Error(`FastPFOR decode: exception header underflow at block=${block} (need 1 byte for maxBits, bytePos=${bytePosIn}, byteSize=${byteContainerLen})`);\n    }\n    const maxBits = byteContainer[bytePosIn++];\n    if (maxBits < bitWidth || maxBits > MAX_BIT_WIDTH) {\n        throw new Error(`FastPFOR decode: invalid maxBits=${maxBits} at block=${block} (bitWidth=${bitWidth}, expected ${bitWidth}..${MAX_BIT_WIDTH})`);\n    }\n    const exceptionBitWidth = (maxBits - bitWidth) | 0;\n    if (exceptionBitWidth < 1 || exceptionBitWidth > MAX_BIT_WIDTH) {\n        throw new Error(`FastPFOR decode: invalid exceptionBitWidth=${exceptionBitWidth} at block=${block} (bitWidth=${bitWidth}, maxBits=${maxBits})`);\n    }\n    if (bytePosIn + exceptionCount > byteContainerLen) {\n        throw new Error(`FastPFOR decode: exception positions underflow at block=${block} (need=${exceptionCount}, have=${byteContainerLen - bytePosIn})`);\n    }\n    return { maxBits, exceptionBitWidth, bytePosIn };\n}\n/**\n * Applies (block-local) FastPFOR \"exceptions\" (outliers) to an already-unpacked base 256-value block.\n *\n * @param out - Output buffer containing the base unpacked values for the block.\n * @param blockOutPos - Offset in `out` where the 256-value block starts.\n * @param bitWidth - Base bit-width for the block.\n * @param exceptionCount - Number of exceptions/outliers in this block.\n * @param byteContainer - Byte metadata buffer for the page.\n * @param byteContainerLen - The valid byte length in `byteContainer` for this page.\n * @param bytePosIn - Current offset in `byteContainer` (right after `[bitWidth, exceptionCount]`).\n * @param workspace - Decoder workspace holding the unpacked exception streams.\n * @param block - Block index within the page (for error messages).\n * @returns The updated `bytePosIn` after consuming the exception metadata bytes.\n *\n * The exception metadata is stored in `byteContainer`:\n * - `maxBits` (1 byte): the maximum bit-width of any value in the block\n * - `exceptionCount` exception positions (1 byte each, 0..255)\n *\n * The exception values themselves are read from the pre-unpacked exception streams stored in `workspace`.\n * Returns the new position in the byteContainer after consuming the exception metadata bytes.\n */\nfunction applyBlockExceptions(out, blockOutPos, bitWidth, exceptionCount, byteContainer, byteContainerLen, bytePosIn, workspace, block) {\n    const { maxBits, exceptionBitWidth, bytePosIn: afterHeaderPos, } = readBlockExceptionHeader(byteContainer, byteContainerLen, bytePosIn, bitWidth, exceptionCount, block);\n    bytePosIn = afterHeaderPos;\n    if (exceptionBitWidth === 1) {\n        const shift = 1 << bitWidth;\n        for (let k = 0; k < exceptionCount; k = (k + 1) | 0) {\n            const pos = byteContainer[bytePosIn++];\n            out[(pos + blockOutPos) | 0] |= shift;\n        }\n        return bytePosIn;\n    }\n    const exceptionValues = workspace.dataToBePacked[exceptionBitWidth];\n    if (!exceptionValues) {\n        throw new Error(`FastPFOR decode: missing exception stream for exceptionBitWidth=${exceptionBitWidth} (bitWidth=${bitWidth}, maxBits=${maxBits}) at block ${block}`);\n    }\n    const exceptionPointers = workspace.dataPointers;\n    let exPtr = exceptionPointers[exceptionBitWidth] | 0;\n    const exSize = workspace.exceptionSizes[exceptionBitWidth] | 0;\n    if (exPtr + exceptionCount > exSize) {\n        throw new Error(`FastPFOR decode: exception stream overflow for exceptionBitWidth=${exceptionBitWidth} (ptr=${exPtr}, need ${exceptionCount}, size=${exSize}) at block ${block}`);\n    }\n    for (let k = 0; k < exceptionCount; k = (k + 1) | 0) {\n        const pos = byteContainer[bytePosIn++];\n        const val = exceptionValues[exPtr++] | 0;\n        out[(pos + blockOutPos) | 0] |= val << bitWidth;\n    }\n    exceptionPointers[exceptionBitWidth] = exPtr;\n    return bytePosIn;\n}\nfunction decodePageBlocks(inValues, pageStart, inPos, packedEnd, out, outPos, blocks, byteContainer, byteContainerLen, workspace) {\n    let tmpInPos = inPos | 0;\n    let bytePosIn = 0;\n    for (let run = 0; run < blocks; run = (run + 1) | 0) {\n        const header = readBlockHeader(byteContainer, byteContainerLen, bytePosIn, run);\n        bytePosIn = header.bytePosIn;\n        const bitWidth = header.bitWidth;\n        const exceptionCount = header.exceptionCount;\n        const blockOutPos = (outPos + run * BLOCK_SIZE) | 0;\n        switch (bitWidth) {\n            case 0:\n                out.fill(0, blockOutPos, blockOutPos + BLOCK_SIZE);\n                break;\n            case 32:\n                for (let i = 0; i < BLOCK_SIZE; i = (i + 1) | 0) {\n                    out[(blockOutPos + i) | 0] = inValues[(tmpInPos + i) | 0] | 0;\n                }\n                tmpInPos = (tmpInPos + BLOCK_SIZE) | 0;\n                break;\n            default:\n                tmpInPos = unpackBlock256(inValues, tmpInPos, out, blockOutPos, bitWidth);\n                break;\n        }\n        if (exceptionCount > 0) {\n            bytePosIn = applyBlockExceptions(out, blockOutPos, bitWidth, exceptionCount, byteContainer, byteContainerLen, bytePosIn, workspace, run);\n        }\n    }\n    if (tmpInPos !== packedEnd) {\n        throw new Error(`FastPFOR decode: packed region mismatch (pageStart=${pageStart}, packedStart=${inPos}, consumedPackedEnd=${tmpInPos}, expectedPackedEnd=${packedEnd}, packedWords=${packedEnd - inPos}, encoded.length=${inValues.length})`);\n    }\n    return;\n}\n/**\n * Decodes one FastPFOR page (aligned to 256-value blocks).\n */\nfunction decodePage(inValues, out, inPos, outPos, thisSize, workspace) {\n    const pageStart = inPos | 0;\n    const whereMeta = inValues[pageStart] | 0;\n    if (whereMeta <= 0 || pageStart + whereMeta > inValues.length - 1) {\n        throw new Error(`FastPFOR decode: invalid whereMeta=${whereMeta} at pageStart=${pageStart} (expected > 0 and pageStart+whereMeta < encoded.length=${inValues.length})`);\n    }\n    const packedStart = (pageStart + 1) | 0;\n    const packedEnd = (pageStart + whereMeta) | 0;\n    const byteSize = inValues[packedEnd] >>> 0;\n    const metaInts = (byteSize + 3) >>> 2;\n    const byteContainerStart = packedEnd + 1;\n    const bitmapPos = byteContainerStart + metaInts;\n    if (bitmapPos >= inValues.length) {\n        throw new Error(`FastPFOR decode: invalid byteSize=${byteSize} (metaInts=${metaInts}, pageStart=${pageStart}, packedEnd=${packedEnd}, byteContainerStart=${byteContainerStart}) causes bitmapPos=${bitmapPos} out of bounds (encoded.length=${inValues.length})`);\n    }\n    const byteContainer = materializeByteContainer(inValues, byteContainerStart, byteSize, workspace);\n    const byteContainerLen = byteSize;\n    const inExcept = unpackExceptionStreams(inValues, bitmapPos, workspace);\n    const exceptionPointers = workspace.dataPointers;\n    exceptionPointers.fill(0);\n    const startOutPos = outPos | 0;\n    const blocks = (thisSize / BLOCK_SIZE) | 0;\n    decodePageBlocks(inValues, pageStart, packedStart, packedEnd, out, startOutPos, blocks, byteContainer, byteContainerLen, workspace);\n    return inExcept;\n}\nfunction decodeAlignedPages(inValues, out, inPos, outPos, outLength, workspace) {\n    const alignedOutLength = greatestMultiple(outLength, BLOCK_SIZE);\n    const finalOut = outPos + alignedOutLength;\n    let tmpOutPos = outPos;\n    let tmpInPos = inPos;\n    while (tmpOutPos !== finalOut) {\n        const thisSize = Math.min(PAGE_SIZE, finalOut - tmpOutPos);\n        tmpInPos = decodePage(inValues, out, tmpInPos, tmpOutPos, thisSize, workspace);\n        tmpOutPos = (tmpOutPos + thisSize) | 0;\n    }\n    return tmpInPos;\n}\n/**\n * Decodes the VariableByte tail (MSB=1 terminator, opposite of Protobuf Varint).\n */\nfunction decodeVByte(inValues, inPos, inLength, out, outPos, expectedCount) {\n    if (expectedCount === 0)\n        return inPos;\n    let bitOffset = 0;\n    let wordIndex = inPos;\n    const finalWordIndex = inPos + inLength;\n    const outPos0 = outPos;\n    let tmpOutPos = outPos;\n    const targetOut = outPos + expectedCount;\n    let accumulator = 0;\n    let accumulatorShift = 0;\n    while (wordIndex < finalWordIndex && tmpOutPos < targetOut) {\n        const word = inValues[wordIndex];\n        const byte = (word >>> bitOffset) & 0xff;\n        bitOffset += 8;\n        wordIndex += bitOffset >>> 5;\n        bitOffset &= 31;\n        accumulator |= (byte & 0x7f) << accumulatorShift;\n        if ((byte & 0x80) !== 0) {\n            out[tmpOutPos++] = accumulator | 0;\n            accumulator = 0;\n            accumulatorShift = 0;\n        }\n        else {\n            accumulatorShift += 7;\n            if (accumulatorShift > 28) {\n                throw new Error(`FastPFOR VByte: unterminated value (expected MSB=1 terminator within 5 bytes; shift=${accumulatorShift}, partial=${accumulator}, decoded=${tmpOutPos - outPos0}/${expectedCount}, inPos=${wordIndex}, inEnd=${finalWordIndex})`);\n            }\n        }\n    }\n    if (tmpOutPos !== targetOut) {\n        throw new Error(`FastPFOR VByte: truncated stream (decoded=${tmpOutPos - outPos0}, expected=${expectedCount}, consumedWords=${wordIndex - inPos}/${inLength}, vbyteStart=${inPos}, vbyteEnd=${finalWordIndex})`);\n    }\n    return wordIndex;\n}\n/**\n * Decodes a sequence of FastPFOR-encoded integers.\n *\n * @param encoded The input buffer containing FastPFOR encoded data.\n * @param numValues The number of integers expected to be decoded.\n * @param workspace Optional workspace for reuse across calls. If omitted, a new workspace is created per call.\n */\nexport function decodeFastPforInt32(encoded, numValues, workspace) {\n    let inPos = 0;\n    let outPos = 0;\n    const decoded = new Uint32Array(numValues);\n    const decoderWorkspace = workspace ?? createDecoderWorkspace();\n    if (encoded.length > 0) {\n        const alignedLength = encoded[inPos] | 0;\n        inPos = (inPos + 1) | 0;\n        if ((alignedLength & (BLOCK_SIZE - 1)) !== 0) {\n            throw new Error(`FastPFOR decode: invalid alignedLength=${alignedLength} (expected multiple of ${BLOCK_SIZE})`);\n        }\n        if (outPos + alignedLength > decoded.length) {\n            throw new Error(`FastPFOR decode: output buffer too small (outPos=${outPos}, alignedLength=${alignedLength}, out.length=${decoded.length})`);\n        }\n        inPos = decodeAlignedPages(encoded, decoded, inPos, outPos, alignedLength, decoderWorkspace);\n        outPos = (outPos + alignedLength) | 0;\n    }\n    const remainingLength = (encoded.length - inPos) | 0;\n    const expectedTail = (numValues - outPos) | 0;\n    decodeVByte(encoded, inPos, remainingLength, decoded, outPos, expectedTail);\n    return decoded;\n}\nfunction fastUnpack32(inValues, inPos, out, outPos, bitWidth) {\n    switch (bitWidth) {\n        case 2:\n            fastUnpack32_2(inValues, inPos, out, outPos);\n            return;\n        case 3:\n            fastUnpack32_3(inValues, inPos, out, outPos);\n            return;\n        case 4:\n            fastUnpack32_4(inValues, inPos, out, outPos);\n            return;\n        case 5:\n            fastUnpack32_5(inValues, inPos, out, outPos);\n            return;\n        case 6:\n            fastUnpack32_6(inValues, inPos, out, outPos);\n            return;\n        case 7:\n            fastUnpack32_7(inValues, inPos, out, outPos);\n            return;\n        case 8:\n            fastUnpack32_8(inValues, inPos, out, outPos);\n            return;\n        case 9:\n            fastUnpack32_9(inValues, inPos, out, outPos);\n            return;\n        case 10:\n            fastUnpack32_10(inValues, inPos, out, outPos);\n            return;\n        case 11:\n            fastUnpack32_11(inValues, inPos, out, outPos);\n            return;\n        case 12:\n            fastUnpack32_12(inValues, inPos, out, outPos);\n            return;\n        case 16:\n            fastUnpack32_16(inValues, inPos, out, outPos);\n            return;\n        case 32:\n            for (let i = 0; i < 32; i = (i + 1) | 0) {\n                out[(outPos + i) | 0] = inValues[(inPos + i) | 0] | 0;\n            }\n            return;\n        default:\n            break;\n    }\n    const valueMask = MASKS[bitWidth] >>> 0;\n    let inputWordIndex = inPos;\n    let bitOffset = 0;\n    let currentWord = inValues[inputWordIndex] >>> 0;\n    for (let i = 0; i < 32; i++) {\n        if (bitOffset + bitWidth <= 32) {\n            const value = (currentWord >>> bitOffset) & valueMask;\n            out[outPos + i] = value | 0;\n            bitOffset += bitWidth;\n            if (bitOffset === 32) {\n                bitOffset = 0;\n                inputWordIndex++;\n                if (i !== 31)\n                    currentWord = inValues[inputWordIndex] >>> 0;\n            }\n        }\n        else {\n            const lowBits = 32 - bitOffset;\n            const low = currentWord >>> bitOffset;\n            inputWordIndex++;\n            currentWord = inValues[inputWordIndex] >>> 0;\n            const highMask = MASKS[bitWidth - lowBits] >>> 0;\n            const high = currentWord & highMask;\n            const value = (low | (high << lowBits)) & valueMask;\n            out[outPos + i] = value | 0;\n            bitOffset = bitWidth - lowBits;\n        }\n    }\n}\n//# sourceMappingURL=fastPforDecoder.js.map", "import { bswap32 } from \"./fastPforShared\";\n/**\n * Decodes big-endian bytes into `out` without allocating the output buffer.\n *\n * This function does not copy `bytes`; it writes decoded words into the provided `out` array.\n * For aligned inputs it may create a temporary typed-array view (`Uint32Array`) over `bytes.buffer`\n * to speed up decoding.\n *\n * If `byteLength` is not a multiple of 4, the final word is padded with zeros.\n *\n * @returns Number of int32 words written.\n * @throws RangeError If `(offset, byteLength)` is out of bounds, or if `out` is too small.\n */\nexport function decodeBigEndianInt32sInto(bytes, offset, byteLength, out) {\n    if (offset < 0 || byteLength < 0 || offset + byteLength > bytes.length) {\n        throw new RangeError(`decodeBigEndianInt32sInto: out of bounds (offset=${offset}, byteLength=${byteLength}, bytes.length=${bytes.length})`);\n    }\n    const numCompleteInts = Math.floor(byteLength / 4);\n    const hasTrailingBytes = byteLength % 4 !== 0;\n    const numInts = hasTrailingBytes ? numCompleteInts + 1 : numCompleteInts;\n    if (out.length < numInts) {\n        throw new RangeError(`decodeBigEndianInt32sInto: out.length=${out.length} < ${numInts}`);\n    }\n    if (numCompleteInts > 0) {\n        const absoluteOffset = bytes.byteOffset + offset;\n        if ((absoluteOffset & 3) === 0) {\n            const u32 = new Uint32Array(bytes.buffer, absoluteOffset, numCompleteInts);\n            for (let i = 0; i < numCompleteInts; i++) {\n                out[i] = bswap32(u32[i]) | 0;\n            }\n        }\n        else {\n            for (let i = 0; i < numCompleteInts; i++) {\n                const base = offset + i * 4;\n                out[i] = (bytes[base] << 24) | (bytes[base + 1] << 16) | (bytes[base + 2] << 8) | bytes[base + 3] | 0;\n            }\n        }\n    }\n    if (hasTrailingBytes) {\n        const base = offset + numCompleteInts * 4;\n        const remaining = byteLength - numCompleteInts * 4;\n        let v = 0;\n        for (let i = 0; i < remaining; i++) {\n            v |= bytes[base + i] << (24 - i * 8);\n        }\n        out[numCompleteInts] = v | 0;\n    }\n    return numInts;\n}\n//# sourceMappingURL=bigEndianDecode.js.map", "import { createFastPforWireDecodeWorkspace, decodeFastPforInt32, ensureFastPforWireEncodedWordsCapacity, } from \"./fastPforDecoder\";\nimport { decodeBigEndianInt32sInto } from \"./bigEndianDecode\";\nexport { createFastPforWireDecodeWorkspace } from \"./fastPforDecoder\";\n//based on https://github.com/mapbox/pbf/blob/main/index.js\nexport function decodeVarintInt32(buf, bufferOffset, numValues) {\n    const dst = new Uint32Array(numValues);\n    let dstOffset = 0;\n    let offset = bufferOffset.get();\n    for (let i = 0; i < dst.length; i++) {\n        let b = buf[offset++];\n        let val = b & 0x7f;\n        if (b < 0x80) {\n            dst[dstOffset++] = val;\n            continue;\n        }\n        b = buf[offset++];\n        val |= (b & 0x7f) << 7;\n        if (b < 0x80) {\n            dst[dstOffset++] = val;\n            continue;\n        }\n        b = buf[offset++];\n        val |= (b & 0x7f) << 14;\n        if (b < 0x80) {\n            dst[dstOffset++] = val;\n            continue;\n        }\n        b = buf[offset++];\n        val |= (b & 0x7f) << 21;\n        if (b < 0x80) {\n            dst[dstOffset++] = val;\n            continue;\n        }\n        b = buf[offset++];\n        val |= (b & 0x0f) << 28;\n        dst[dstOffset++] = val;\n    }\n    bufferOffset.set(offset);\n    return dst;\n}\nexport function decodeVarintInt64(src, offset, numValues) {\n    const dst = new BigUint64Array(numValues);\n    for (let i = 0; i < dst.length; i++) {\n        dst[i] = decodeVarintInt64Value(src, offset);\n    }\n    return dst;\n}\n// Source: https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/util/VarInt.java\nfunction decodeVarintInt64Value(bytes, pos) {\n    let value = 0n;\n    let shift = 0;\n    let index = pos.get();\n    while (index < bytes.length) {\n        const b = bytes[index++];\n        value |= BigInt(b & 0x7f) << BigInt(shift);\n        if ((b & 0x80) === 0) {\n            break;\n        }\n        shift += 7;\n        if (shift >= 64) {\n            throw new Error(\"Varint too long\");\n        }\n    }\n    pos.set(index);\n    return value;\n}\n/*\n * Since decoding Int64 values to BigInt is more than an order of magnitude slower in the tests then using a Float64,\n * this decoding method limits the max size of a Long value to 53 bits\n */\nexport function decodeVarintFloat64(src, offset, numValues) {\n    const dst = new Float64Array(numValues);\n    for (let i = 0; i < numValues; i++) {\n        dst[i] = decodeVarintFloat64Value(src, offset);\n    }\n    return dst;\n}\n//based on https://github.com/mapbox/pbf/blob/main/index.js\nfunction decodeVarintFloat64Value(buf, offset) {\n    let val;\n    let b;\n    b = buf[offset.get()];\n    offset.increment();\n    val = b & 0x7f;\n    if (b < 0x80)\n        return val;\n    b = buf[offset.get()];\n    offset.increment();\n    val |= (b & 0x7f) << 7;\n    if (b < 0x80)\n        return val;\n    b = buf[offset.get()];\n    offset.increment();\n    val |= (b & 0x7f) << 14;\n    if (b < 0x80)\n        return val;\n    b = buf[offset.get()];\n    offset.increment();\n    val |= (b & 0x7f) << 21;\n    if (b < 0x80)\n        return val;\n    b = buf[offset.get()];\n    val |= (b & 0x0f) << 28;\n    return decodeVarintRemainder(val, buf, offset);\n}\nfunction decodeVarintRemainder(l, buf, offset) {\n    let h;\n    let b;\n    b = buf[offset.get()];\n    offset.increment();\n    h = (b & 0x70) >> 4;\n    if (b < 0x80)\n        return h * 0x100000000 + (l >>> 0);\n    b = buf[offset.get()];\n    offset.increment();\n    h |= (b & 0x7f) << 3;\n    if (b < 0x80)\n        return h * 0x100000000 + (l >>> 0);\n    b = buf[offset.get()];\n    offset.increment();\n    h |= (b & 0x7f) << 10;\n    if (b < 0x80)\n        return h * 0x100000000 + (l >>> 0);\n    b = buf[offset.get()];\n    offset.increment();\n    h |= (b & 0x7f) << 17;\n    if (b < 0x80)\n        return h * 0x100000000 + (l >>> 0);\n    b = buf[offset.get()];\n    offset.increment();\n    h |= (b & 0x7f) << 24;\n    if (b < 0x80)\n        return h * 0x100000000 + (l >>> 0);\n    b = buf[offset.get()];\n    offset.increment();\n    h |= (b & 0x01) << 31;\n    if (b < 0x80)\n        return h * 0x100000000 + (l >>> 0);\n    throw new Error(\"Expected varint not more than 10 bytes\");\n}\nexport function decodeFastPfor(encodedBytes, expectedValueCount, encodedByteLength, offset) {\n    const workspace = createFastPforWireDecodeWorkspace(encodedByteLength >>> 2);\n    return decodeFastPforWithWorkspace(encodedBytes, expectedValueCount, encodedByteLength, offset, workspace);\n}\nexport function decodeFastPforWithWorkspace(encodedBytes, expectedValueCount, encodedByteLength, offset, workspace) {\n    const inputByteOffset = offset.get();\n    if ((encodedByteLength & 3) !== 0) {\n        throw new Error(`FastPFOR: invalid encodedByteLength=${encodedByteLength} at offset=${inputByteOffset} (encodedBytes.length=${encodedBytes.length}; expected a multiple of 4 bytes for an int32 big-endian word stream)`);\n    }\n    const encodedWordCount = encodedByteLength >>> 2;\n    const encodedWordBuffer = ensureFastPforWireEncodedWordsCapacity(workspace, encodedWordCount);\n    decodeBigEndianInt32sInto(encodedBytes, inputByteOffset, encodedByteLength, encodedWordBuffer);\n    const decodedValues = decodeFastPforInt32(encodedWordBuffer.subarray(0, encodedWordCount), expectedValueCount, workspace.decoderWorkspace);\n    offset.add(encodedByteLength);\n    return decodedValues;\n}\nexport function decodeZigZagInt32Value(encoded) {\n    return (encoded >>> 1) ^ -(encoded & 1);\n}\nexport function decodeZigZagInt64Value(encoded) {\n    return (encoded >> 1n) ^ -(encoded & 1n);\n}\nexport function decodeZigZagFloat64Value(encoded) {\n    return encoded % 2 === 1 ? (encoded + 1) / -2 : encoded / 2;\n}\nexport function decodeZigZagInt32(encodedData) {\n    const decodedValues = new Int32Array(encodedData.length);\n    for (let i = 0; i < encodedData.length; i++) {\n        decodedValues[i] = decodeZigZagInt32Value(encodedData[i]);\n    }\n    return decodedValues;\n}\nexport function decodeZigZagInt64(encodedData) {\n    const decodedValues = new BigInt64Array(encodedData.length);\n    for (let i = 0; i < encodedData.length; i++) {\n        decodedValues[i] = decodeZigZagInt64Value(encodedData[i]);\n    }\n    return decodedValues;\n}\nexport function decodeZigZagFloat64(encodedData) {\n    for (let i = 0; i < encodedData.length; i++) {\n        encodedData[i] = decodeZigZagFloat64Value(encodedData[i]);\n    }\n}\nexport function decodeUnsignedRleInt32(encodedData, numRuns, numTotalValues) {\n    // If numTotalValues not provided, calculate from runs (nullable case)\n    if (numTotalValues === undefined) {\n        numTotalValues = 0;\n        for (let i = 0; i < numRuns; i++) {\n            numTotalValues += encodedData[i];\n        }\n    }\n    const decodedValues = new Uint32Array(numTotalValues);\n    let offset = 0;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = encodedData[i];\n        const value = encodedData[i + numRuns];\n        decodedValues.fill(value, offset, offset + runLength);\n        offset += runLength;\n    }\n    return decodedValues;\n}\nexport function decodeUnsignedRleInt64(encodedData, numRuns, numTotalValues) {\n    // If numTotalValues not provided, calculate from runs (nullable case)\n    if (numTotalValues === undefined) {\n        numTotalValues = 0;\n        for (let i = 0; i < numRuns; i++) {\n            numTotalValues += Number(encodedData[i]);\n        }\n    }\n    const decodedValues = new BigUint64Array(numTotalValues);\n    let offset = 0;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = Number(encodedData[i]);\n        const value = encodedData[i + numRuns];\n        decodedValues.fill(value, offset, offset + runLength);\n        offset += runLength;\n    }\n    return decodedValues;\n}\nexport function decodeUnsignedRleFloat64(encodedData, numRuns, numTotalValues) {\n    const decodedValues = new Float64Array(numTotalValues);\n    let offset = 0;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = encodedData[i];\n        const value = encodedData[i + numRuns];\n        decodedValues.fill(value, offset, offset + runLength);\n        offset += runLength;\n    }\n    return decodedValues;\n}\n/*\n * In place decoding of the zigzag encoded delta values.\n * Inspired by https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/differential/Delta.java\n */\nexport function decodeZigZagDeltaInt32(data) {\n    const decodedValues = new Int32Array(data.length);\n    decodedValues[0] = decodeZigZagInt32Value(data[0]);\n    const sz0 = (data.length / 4) * 4;\n    let i = 1;\n    if (sz0 >= 4) {\n        for (; i < sz0 - 4; i += 4) {\n            const data1 = data[i];\n            const data2 = data[i + 1];\n            const data3 = data[i + 2];\n            const data4 = data[i + 3];\n            decodedValues[i] = decodeZigZagInt32Value(data1) + decodedValues[i - 1];\n            decodedValues[i + 1] = decodeZigZagInt32Value(data2) + decodedValues[i];\n            decodedValues[i + 2] = decodeZigZagInt32Value(data3) + decodedValues[i + 1];\n            decodedValues[i + 3] = decodeZigZagInt32Value(data4) + decodedValues[i + 2];\n        }\n    }\n    for (; i !== data.length; ++i) {\n        decodedValues[i] = decodeZigZagInt32Value(data[i]) + decodedValues[i - 1];\n    }\n    return decodedValues;\n}\nexport function decodeZigZagDeltaInt64(data) {\n    const decodedValues = new BigInt64Array(data.length);\n    decodedValues[0] = decodeZigZagInt64Value(data[0]);\n    const sz0 = (data.length / 4) * 4;\n    let i = 1;\n    if (sz0 >= 4) {\n        for (; i < sz0 - 4; i += 4) {\n            const data1 = data[i];\n            const data2 = data[i + 1];\n            const data3 = data[i + 2];\n            const data4 = data[i + 3];\n            decodedValues[i] = decodeZigZagInt64Value(data1) + decodedValues[i - 1];\n            decodedValues[i + 1] = decodeZigZagInt64Value(data2) + decodedValues[i];\n            decodedValues[i + 2] = decodeZigZagInt64Value(data3) + decodedValues[i + 1];\n            decodedValues[i + 3] = decodeZigZagInt64Value(data4) + decodedValues[i + 2];\n        }\n    }\n    for (; i !== decodedValues.length; ++i) {\n        decodedValues[i] = decodeZigZagInt64Value(data[i]) + decodedValues[i - 1];\n    }\n    return decodedValues;\n}\nexport function decodeZigZagDeltaFloat64(data) {\n    data[0] = decodeZigZagFloat64Value(data[0]);\n    const sz0 = (data.length / 4) * 4;\n    let i = 1;\n    if (sz0 >= 4) {\n        for (; i < sz0 - 4; i += 4) {\n            const data1 = data[i];\n            const data2 = data[i + 1];\n            const data3 = data[i + 2];\n            const data4 = data[i + 3];\n            data[i] = decodeZigZagFloat64Value(data1) + data[i - 1];\n            data[i + 1] = decodeZigZagFloat64Value(data2) + data[i];\n            data[i + 2] = decodeZigZagFloat64Value(data3) + data[i + 1];\n            data[i + 3] = decodeZigZagFloat64Value(data4) + data[i + 2];\n        }\n    }\n    for (; i !== data.length; ++i) {\n        data[i] = decodeZigZagFloat64Value(data[i]) + data[i - 1];\n    }\n}\nexport function decodeZigZagRleInt32(data, numRuns, numTotalValues) {\n    // If numTotalValues not provided, calculate from runs (nullable case)\n    if (numTotalValues === undefined) {\n        numTotalValues = 0;\n        for (let i = 0; i < numRuns; i++) {\n            numTotalValues += data[i];\n        }\n    }\n    const decodedValues = new Int32Array(numTotalValues);\n    let offset = 0;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = data[i];\n        let value = data[i + numRuns];\n        value = decodeZigZagInt32Value(value);\n        decodedValues.fill(value, offset, offset + runLength);\n        offset += runLength;\n    }\n    return decodedValues;\n}\nexport function decodeZigZagRleInt64(data, numRuns, numTotalValues) {\n    // If numTotalValues not provided, calculate from runs (nullable case)\n    if (numTotalValues === undefined) {\n        numTotalValues = 0;\n        for (let i = 0; i < numRuns; i++) {\n            numTotalValues += Number(data[i]);\n        }\n    }\n    const decodedValues = new BigInt64Array(numTotalValues);\n    let offset = 0;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = Number(data[i]);\n        let value = data[i + numRuns];\n        value = decodeZigZagInt64Value(value);\n        decodedValues.fill(value, offset, offset + runLength);\n        offset += runLength;\n    }\n    return decodedValues;\n}\nexport function decodeZigZagRleFloat64(data, numRuns, numTotalValues) {\n    const decodedValues = new Float64Array(numTotalValues);\n    let offset = 0;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = data[i];\n        let value = data[i + numRuns];\n        value = decodeZigZagFloat64Value(value);\n        decodedValues.fill(value, offset, offset + runLength);\n        offset += runLength;\n    }\n    return decodedValues;\n}\n/*\n * Inspired by https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/differential/Delta.java\n */\nexport function fastInverseDelta(data) {\n    const sz0 = (data.length / 4) * 4;\n    let i = 1;\n    if (sz0 >= 4) {\n        for (let a = data[0]; i < sz0 - 4; i += 4) {\n            a = data[i] += a;\n            a = data[i + 1] += a;\n            a = data[i + 2] += a;\n            a = data[i + 3] += a;\n        }\n    }\n    while (i !== data.length) {\n        data[i] += data[i - 1];\n        ++i;\n    }\n}\nexport function inverseDelta(data) {\n    let prevValue = 0;\n    for (let i = 0; i < data.length; i++) {\n        data[i] += prevValue;\n        prevValue = data[i];\n    }\n}\n/*\n * In place decoding of the zigzag delta encoded Vec2.\n * Inspired by https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/differential/Delta.java\n */\nexport function decodeComponentwiseDeltaVec2(data) {\n    if (data.length < 2)\n        return new Int32Array(data);\n    const decodedData = new Int32Array(data.length);\n    decodedData[0] = decodeZigZagInt32Value(data[0]);\n    decodedData[1] = decodeZigZagInt32Value(data[1]);\n    const sz0 = (data.length / 4) * 4;\n    let i = 2;\n    if (sz0 >= 4) {\n        for (; i < sz0 - 4; i += 4) {\n            const x1 = data[i];\n            const y1 = data[i + 1];\n            const x2 = data[i + 2];\n            const y2 = data[i + 3];\n            decodedData[i] = decodeZigZagInt32Value(x1) + decodedData[i - 2];\n            decodedData[i + 1] = decodeZigZagInt32Value(y1) + decodedData[i - 1];\n            decodedData[i + 2] = decodeZigZagInt32Value(x2) + decodedData[i];\n            decodedData[i + 3] = decodeZigZagInt32Value(y2) + decodedData[i + 1];\n        }\n    }\n    for (; i !== data.length; i += 2) {\n        decodedData[i] = decodeZigZagInt32Value(data[i]) + decodedData[i - 2];\n        decodedData[i + 1] = decodeZigZagInt32Value(data[i + 1]) + decodedData[i - 1];\n    }\n    return decodedData;\n}\nexport function decodeComponentwiseDeltaVec2Scaled(data, scale, min, max) {\n    if (data.length < 2)\n        return new Int32Array(data);\n    const decodedData = new Int32Array(data.length);\n    let previousVertexX = decodeZigZagInt32Value(data[0]);\n    let previousVertexY = decodeZigZagInt32Value(data[1]);\n    decodedData[0] = clamp(Math.round(previousVertexX * scale), min, max);\n    decodedData[1] = clamp(Math.round(previousVertexY * scale), min, max);\n    const sz0 = data.length / 16;\n    let i = 2;\n    if (sz0 >= 4) {\n        for (; i < sz0 - 4; i += 4) {\n            const x1 = data[i];\n            const y1 = data[i + 1];\n            const currentVertexX = decodeZigZagInt32Value(x1) + previousVertexX;\n            const currentVertexY = decodeZigZagInt32Value(y1) + previousVertexY;\n            decodedData[i] = clamp(Math.round(currentVertexX * scale), min, max);\n            decodedData[i + 1] = clamp(Math.round(currentVertexY * scale), min, max);\n            const x2 = data[i + 2];\n            const y2 = data[i + 3];\n            previousVertexX = decodeZigZagInt32Value(x2) + currentVertexX;\n            previousVertexY = decodeZigZagInt32Value(y2) + currentVertexY;\n            decodedData[i + 2] = clamp(Math.round(previousVertexX * scale), min, max);\n            decodedData[i + 3] = clamp(Math.round(previousVertexY * scale), min, max);\n        }\n    }\n    for (; i !== data.length; i += 2) {\n        previousVertexX += decodeZigZagInt32Value(data[i]);\n        previousVertexY += decodeZigZagInt32Value(data[i + 1]);\n        decodedData[i] = clamp(Math.round(previousVertexX * scale), min, max);\n        decodedData[i + 1] = clamp(Math.round(previousVertexY * scale), min, max);\n    }\n    return decodedData;\n}\nfunction clamp(n, min, max) {\n    return Math.min(max, Math.max(min, n));\n}\n/* Transform data to allow util access ------------------------------------------------------------------------ */\nexport function decodeZigZagDeltaOfDeltaInt32(data) {\n    const decodedData = new Int32Array(data.length + 1);\n    decodedData[0] = 0;\n    decodedData[1] = decodeZigZagInt32Value(data[0]);\n    let deltaSum = decodedData[1];\n    for (let i = 2; i !== decodedData.length; ++i) {\n        const zigZagValue = data[i - 1];\n        const delta = decodeZigZagInt32Value(zigZagValue);\n        deltaSum += delta;\n        decodedData[i] = decodedData[i - 1] + deltaSum;\n    }\n    return new Uint32Array(decodedData);\n}\nexport function decodeZigZagRleDeltaInt32(data, numRuns, numTotalValues) {\n    const decodedValues = new Int32Array(numTotalValues + 1);\n    decodedValues[0] = 0;\n    let offset = 1;\n    let previousValue = decodedValues[0];\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = data[i];\n        let value = data[i + numRuns];\n        value = decodeZigZagInt32Value(value);\n        for (let j = offset; j < offset + runLength; j++) {\n            decodedValues[j] = value + previousValue;\n            previousValue = decodedValues[j];\n        }\n        offset += runLength;\n    }\n    return decodedValues;\n}\nexport function decodeRleDeltaInt32(data, numRuns, numTotalValues) {\n    const decodedValues = new Uint32Array(numTotalValues + 1);\n    decodedValues[0] = 0;\n    let offset = 1;\n    let previousValue = decodedValues[0];\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = data[i];\n        const value = data[i + numRuns];\n        for (let j = offset; j < offset + runLength; j++) {\n            decodedValues[j] = value + previousValue;\n            previousValue = decodedValues[j];\n        }\n        offset += runLength;\n    }\n    return decodedValues;\n}\n/**\n * Decode Delta-RLE with multiple runs by fully reconstructing values.\n *\n * @param data RLE encoded data: [run1, run2, ..., value1, value2, ...]\n * @param numRuns Number of runs in the RLE encoding\n * @param numValues Total number of values to reconstruct\n * @returns Reconstructed values with deltas applied\n */\nexport function decodeDeltaRleInt32(data, numRuns, numValues) {\n    const result = new Int32Array(numValues);\n    let outPos = 0;\n    let previousValue = 0;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = data[i];\n        const zigZagDelta = data[i + numRuns];\n        const delta = decodeZigZagInt32Value(zigZagDelta);\n        for (let j = 0; j < runLength; j++) {\n            previousValue += delta;\n            result[outPos++] = previousValue;\n        }\n    }\n    return result;\n}\n/**\n * Decode Delta-RLE with multiple runs for 64-bit integers.\n */\nexport function decodeDeltaRleInt64(data, numRuns, numValues) {\n    const result = new BigInt64Array(numValues);\n    let outPos = 0;\n    let previousValue = 0n;\n    for (let i = 0; i < numRuns; i++) {\n        const runLength = Number(data[i]);\n        const zigZagDelta = data[i + numRuns];\n        const delta = decodeZigZagInt64Value(zigZagDelta);\n        for (let j = 0; j < runLength; j++) {\n            previousValue += delta;\n            result[outPos++] = previousValue;\n        }\n    }\n    return result;\n}\nexport function decodeUnsignedZigZagDeltaInt32(data) {\n    const decodedValues = new Uint32Array(data.length);\n    decodedValues[0] = decodeZigZagInt32Value(data[0]) >>> 0;\n    for (let i = 1; i < data.length; i++) {\n        decodedValues[i] = (decodedValues[i - 1] + decodeZigZagInt32Value(data[i])) >>> 0;\n    }\n    return decodedValues;\n}\nexport function decodeUnsignedZigZagDeltaInt64(data) {\n    const decodedValues = new BigUint64Array(data.length);\n    decodedValues[0] = BigInt.asUintN(64, decodeZigZagInt64Value(data[0]));\n    for (let i = 1; i < data.length; i++) {\n        decodedValues[i] = BigInt.asUintN(64, decodedValues[i - 1] + decodeZigZagInt64Value(data[i]));\n    }\n    return decodedValues;\n}\nexport function decodeUnsignedComponentwiseDeltaVec2(data) {\n    if (data.length < 2) {\n        return new Uint32Array(data);\n    }\n    const decodedData = new Uint32Array(data.length);\n    decodedData[0] = decodeZigZagInt32Value(data[0]) >>> 0;\n    decodedData[1] = decodeZigZagInt32Value(data[1]) >>> 0;\n    for (let i = 2; i < data.length; i += 2) {\n        decodedData[i] = (decodedData[i - 2] + decodeZigZagInt32Value(data[i])) >>> 0;\n        decodedData[i + 1] = (decodedData[i - 1] + decodeZigZagInt32Value(data[i + 1])) >>> 0;\n    }\n    return decodedData;\n}\nexport function decodeUnsignedComponentwiseDeltaVec2Scaled(data, scale, min, max) {\n    const scaledValues = decodeComponentwiseDeltaVec2Scaled(data, scale, min, max);\n    return new Uint32Array(scaledValues);\n}\nexport function decodeUnsignedConstRleInt32(data) {\n    return data[1];\n}\nexport function decodeZigZagConstRleInt32(data) {\n    return decodeZigZagInt32Value(data[1]);\n}\nexport function decodeZigZagSequenceRleInt32(data) {\n    /* base value and delta value are equal */\n    if (data.length === 2) {\n        const value = decodeZigZagInt32Value(data[1]);\n        return [value, value];\n    }\n    /* base value and delta value are not equal -> 2 runs and 2 values*/\n    const base = decodeZigZagInt32Value(data[2]);\n    const delta = decodeZigZagInt32Value(data[3]);\n    return [base, delta];\n}\nexport function decodeUnsignedConstRleInt64(data) {\n    return data[1];\n}\nexport function decodeZigZagConstRleInt64(data) {\n    return decodeZigZagInt64Value(data[1]);\n}\nexport function decodeZigZagSequenceRleInt64(data) {\n    /* base value and delta value are equal */\n    if (data.length === 2) {\n        const value = decodeZigZagInt64Value(data[1]);\n        return [value, value];\n    }\n    /* base value and delta value are not equal -> 2 runs and 2 values*/\n    const base = decodeZigZagInt64Value(data[2]);\n    const delta = decodeZigZagInt64Value(data[3]);\n    return [base, delta];\n}\n//# sourceMappingURL=integerDecodingUtils.js.map", "export var PhysicalStreamType;\n(function (PhysicalStreamType) {\n    PhysicalStreamType[\"PRESENT\"] = \"PRESENT\";\n    PhysicalStreamType[\"DATA\"] = \"DATA\";\n    PhysicalStreamType[\"OFFSET\"] = \"OFFSET\";\n    PhysicalStreamType[\"LENGTH\"] = \"LENGTH\";\n})(PhysicalStreamType || (PhysicalStreamType = {}));\n//# sourceMappingURL=physicalStreamType.js.map", "export var DictionaryType;\n(function (DictionaryType) {\n    DictionaryType[\"NONE\"] = \"NONE\";\n    DictionaryType[\"SINGLE\"] = \"SINGLE\";\n    DictionaryType[\"SHARED\"] = \"SHARED\";\n    DictionaryType[\"VERTEX\"] = \"VERTEX\";\n    DictionaryType[\"MORTON\"] = \"MORTON\";\n    DictionaryType[\"FSST\"] = \"FSST\";\n})(DictionaryType || (DictionaryType = {}));\n//# sourceMappingURL=dictionaryType.js.map", "export var OffsetType;\n(function (OffsetType) {\n    OffsetType[\"VERTEX\"] = \"VERTEX\";\n    OffsetType[\"INDEX\"] = \"INDEX\";\n    OffsetType[\"STRING\"] = \"STRING\";\n    OffsetType[\"KEY\"] = \"KEY\";\n})(OffsetType || (OffsetType = {}));\n//# sourceMappingURL=offsetType.js.map", "export var LengthType;\n(function (LengthType) {\n    LengthType[\"VAR_BINARY\"] = \"VAR_BINARY\";\n    LengthType[\"GEOMETRIES\"] = \"GEOMETRIES\";\n    LengthType[\"PARTS\"] = \"PARTS\";\n    LengthType[\"RINGS\"] = \"RINGS\";\n    LengthType[\"TRIANGLES\"] = \"TRIANGLES\";\n    LengthType[\"SYMBOL\"] = \"SYMBOL\";\n    LengthType[\"DICTIONARY\"] = \"DICTIONARY\";\n})(LengthType || (LengthType = {}));\n//# sourceMappingURL=lengthType.js.map", "import { LogicalLevelTechnique } from \"./logicalLevelTechnique\";\nimport { PhysicalLevelTechnique } from \"./physicalLevelTechnique\";\nimport { decodeVarintInt32 } from \"../../decoding/integerDecodingUtils\";\nimport { PhysicalStreamType } from \"./physicalStreamType\";\nimport { DictionaryType } from \"./dictionaryType\";\nimport { OffsetType } from \"./offsetType\";\nimport { LengthType } from \"./lengthType\";\nconst PHYSICAL_STREAM_TYPE_BY_ID = [\n    PhysicalStreamType.PRESENT,\n    PhysicalStreamType.DATA,\n    PhysicalStreamType.OFFSET,\n    PhysicalStreamType.LENGTH,\n];\nconst LOGICAL_LEVEL_TECHNIQUE_BY_ID = [\n    LogicalLevelTechnique.NONE,\n    LogicalLevelTechnique.DELTA,\n    LogicalLevelTechnique.COMPONENTWISE_DELTA,\n    LogicalLevelTechnique.RLE,\n    LogicalLevelTechnique.MORTON,\n];\nconst PHYSICAL_LEVEL_TECHNIQUE_BY_ID = [\n    PhysicalLevelTechnique.NONE,\n    PhysicalLevelTechnique.FAST_PFOR,\n    PhysicalLevelTechnique.VARINT,\n];\nconst DICTIONARY_TYPE_BY_ID = [\n    DictionaryType.NONE,\n    DictionaryType.SINGLE,\n    DictionaryType.SHARED,\n    DictionaryType.VERTEX,\n    DictionaryType.MORTON,\n    DictionaryType.FSST,\n];\nconst OFFSET_TYPE_BY_ID = [\n    OffsetType.VERTEX,\n    OffsetType.INDEX,\n    OffsetType.STRING,\n    OffsetType.KEY,\n];\nconst LENGTH_TYPE_BY_ID = [\n    LengthType.VAR_BINARY,\n    LengthType.GEOMETRIES,\n    LengthType.PARTS,\n    LengthType.RINGS,\n    LengthType.TRIANGLES,\n    LengthType.SYMBOL,\n    LengthType.DICTIONARY,\n];\nexport function decodeStreamMetadata(tile, offset) {\n    const streamMetadata = decodeStreamMetadataInternal(tile, offset);\n    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.MORTON) {\n        return decodePartialMortonEncodedStreamMetadata(streamMetadata, tile, offset);\n    }\n    if ((LogicalLevelTechnique.RLE === streamMetadata.logicalLevelTechnique1 ||\n        LogicalLevelTechnique.RLE === streamMetadata.logicalLevelTechnique2) &&\n        PhysicalLevelTechnique.NONE !== streamMetadata.physicalLevelTechnique) {\n        return decodePartialRleEncodedStreamMetadata(streamMetadata, tile, offset);\n    }\n    return streamMetadata;\n}\nfunction decodePartialMortonEncodedStreamMetadata(streamMetadata, tile, offset) {\n    const mortonInfo = decodeVarintInt32(tile, offset, 2);\n    return {\n        physicalStreamType: streamMetadata.physicalStreamType,\n        logicalStreamType: streamMetadata.logicalStreamType,\n        logicalLevelTechnique1: streamMetadata.logicalLevelTechnique1,\n        logicalLevelTechnique2: streamMetadata.logicalLevelTechnique2,\n        physicalLevelTechnique: streamMetadata.physicalLevelTechnique,\n        numValues: streamMetadata.numValues,\n        byteLength: streamMetadata.byteLength,\n        decompressedCount: streamMetadata.decompressedCount,\n        numBits: mortonInfo[0],\n        coordinateShift: mortonInfo[1],\n    };\n}\nfunction decodePartialRleEncodedStreamMetadata(streamMetadata, tile, offset) {\n    const rleInfo = decodeVarintInt32(tile, offset, 2);\n    return {\n        physicalStreamType: streamMetadata.physicalStreamType,\n        logicalStreamType: streamMetadata.logicalStreamType,\n        logicalLevelTechnique1: streamMetadata.logicalLevelTechnique1,\n        logicalLevelTechnique2: streamMetadata.logicalLevelTechnique2,\n        physicalLevelTechnique: streamMetadata.physicalLevelTechnique,\n        numValues: streamMetadata.numValues,\n        byteLength: streamMetadata.byteLength,\n        decompressedCount: rleInfo[1],\n        runs: rleInfo[0],\n        numRleValues: rleInfo[1],\n    };\n}\nfunction decodeStreamMetadataInternal(tile, offset) {\n    const stream_type = tile[offset.get()];\n    const physicalStreamType = PHYSICAL_STREAM_TYPE_BY_ID[stream_type >> 4];\n    let logicalStreamType = {};\n    switch (physicalStreamType) {\n        case PhysicalStreamType.DATA:\n            logicalStreamType = {\n                dictionaryType: DICTIONARY_TYPE_BY_ID[stream_type & 0xf],\n            };\n            break;\n        case PhysicalStreamType.OFFSET:\n            logicalStreamType = {\n                offsetType: OFFSET_TYPE_BY_ID[stream_type & 0xf],\n            };\n            break;\n        case PhysicalStreamType.LENGTH:\n            logicalStreamType = {\n                lengthType: LENGTH_TYPE_BY_ID[stream_type & 0xf],\n            };\n            break;\n    }\n    offset.increment();\n    const encodings_header = tile[offset.get()];\n    const llt1 = LOGICAL_LEVEL_TECHNIQUE_BY_ID[encodings_header >> 5];\n    const llt2 = LOGICAL_LEVEL_TECHNIQUE_BY_ID[(encodings_header >> 2) & 0x7];\n    const plt = PHYSICAL_LEVEL_TECHNIQUE_BY_ID[encodings_header & 0x3];\n    offset.increment();\n    const sizeInfo = decodeVarintInt32(tile, offset, 2);\n    const numValues = sizeInfo[0];\n    const byteLength = sizeInfo[1];\n    return {\n        physicalStreamType,\n        logicalStreamType,\n        logicalLevelTechnique1: llt1,\n        logicalLevelTechnique2: llt2,\n        physicalLevelTechnique: plt,\n        numValues,\n        byteLength,\n        decompressedCount: numValues,\n    };\n}\n//# sourceMappingURL=streamMetadataDecoder.js.map", "export var VectorType;\n(function (VectorType) {\n    VectorType[VectorType[\"FLAT\"] = 0] = \"FLAT\";\n    VectorType[VectorType[\"CONST\"] = 1] = \"CONST\";\n    VectorType[VectorType[\"SEQUENCE\"] = 2] = \"SEQUENCE\";\n    VectorType[VectorType[\"DICTIONARY\"] = 3] = \"DICTIONARY\";\n    VectorType[VectorType[\"FSST_DICTIONARY\"] = 4] = \"FSST_DICTIONARY\";\n})(VectorType || (VectorType = {}));\n//# sourceMappingURL=vectorType.js.map", "export default class BitVector {\n    /**\n     * @param values The byte buffer containing the bit values in least-significant bit (LSB)\n     *     numbering\n     */\n    constructor(values, size) {\n        this.values = values;\n        this._size = size;\n    }\n    get(index) {\n        const byteIndex = Math.floor(index / 8);\n        const bitIndex = index % 8;\n        const b = this.values[byteIndex];\n        return ((b >> bitIndex) & 1) === 1;\n    }\n    set(index, value) {\n        //TODO: refactor -> improve quick and dirty solution\n        const byteIndex = Math.floor(index / 8);\n        const bitIndex = index % 8;\n        this.values[byteIndex] = this.values[byteIndex] | ((value ? 1 : 0) << bitIndex);\n    }\n    getInt(index) {\n        const byteIndex = Math.floor(index / 8);\n        const bitIndex = index % 8;\n        const b = this.values[byteIndex];\n        return (b >> bitIndex) & 1;\n    }\n    size() {\n        return this._size;\n    }\n    getBuffer() {\n        return this.values;\n    }\n}\n//# sourceMappingURL=bitVector.js.map", "import BitVector from \"../vector/flat/bitVector.js\";\n/**\n * Generic unpacking function.\n * Reconstructs the full array by inserting default values at null positions.\n *\n * @param dataStream The compact data stream containing only non-null values\n * @param presentBits BitVector indicating which positions have values (null if non-nullable)\n * @param defaultValue The default value to insert at null positions (0, 0n, etc.)\n * @returns Full array with default values at null positions\n */\nexport function unpackNullable(dataStream, presentBits, defaultValue) {\n    // Non-nullable case: return data stream as-is\n    if (!presentBits) {\n        return dataStream;\n    }\n    const size = presentBits.size();\n    // Create new array of same type with full size\n    const constructor = dataStream.constructor;\n    const result = new constructor(size);\n    let counter = 0;\n    for (let i = 0; i < size; i++) {\n        // If position has a value, take from data stream; otherwise use default\n        result[i] = presentBits.get(i) ? dataStream[counter++] : defaultValue;\n    }\n    return result;\n}\n/**\n * Special case for boolean columns because BitVector is not directly compatible with TypedArray.\n *\n * @param dataStream The compact BitVector data containing only non-null boolean values\n * @param dataStreamSize The number of actual values in dataStream\n * @param presentBits BitVector indicating which positions have values (null if non-nullable)\n * @returns Uint8Array buffer for BitVector with false at null positions\n */\nexport function unpackNullableBoolean(dataStream, dataStreamSize, presentBits) {\n    // Non-nullable case\n    if (!presentBits) {\n        return dataStream;\n    }\n    const numFeatures = presentBits.size();\n    const bitVector = new BitVector(dataStream, dataStreamSize);\n    const result = new BitVector(new Uint8Array(Math.ceil(numFeatures / 8)), numFeatures);\n    let counter = 0;\n    for (let i = 0; i < numFeatures; i++) {\n        // If position has a value, take from data stream; otherwise use false\n        const value = presentBits.get(i) ? bitVector.get(counter++) : false;\n        result.set(i, value);\n    }\n    return result.getBuffer();\n}\n//# sourceMappingURL=unpackNullableUtils.js.map", "import { VectorType } from \"../vector/vectorType\";\nimport { decodeStreamMetadata } from \"../metadata/tile/streamMetadataDecoder\";\nimport { unpackNullableBoolean, unpackNullable } from \"./unpackNullableUtils\";\nexport function skipColumn(numStreams, tile, offset) {\n    //TODO: add size of column in Mlt for fast skipping\n    for (let i = 0; i < numStreams; i++) {\n        const streamMetadata = decodeStreamMetadata(tile, offset);\n        offset.add(streamMetadata.byteLength);\n    }\n}\nexport function decodeBooleanRle(buffer, numBooleans, byteLength, pos, nullabilityBuffer) {\n    const numBytes = Math.ceil(numBooleans / 8.0);\n    const values = decodeByteRle(buffer, numBytes, byteLength, pos);\n    if (nullabilityBuffer) {\n        return unpackNullableBoolean(values, numBooleans, nullabilityBuffer);\n    }\n    return values;\n}\nexport function decodeByteRle(buffer, numBytes, byteLength, pos) {\n    const values = new Uint8Array(numBytes);\n    let valueOffset = 0;\n    const streamEndPos = pos.get() + byteLength;\n    while (valueOffset < numBytes) {\n        if (pos.get() >= streamEndPos) {\n            break;\n        }\n        const header = buffer[pos.increment()];\n        /* Runs */\n        if (header <= 0x7f) {\n            const numRuns = header + 3;\n            const value = buffer[pos.increment()];\n            const endValueOffset = Math.min(valueOffset + numRuns, numBytes);\n            values.fill(value, valueOffset, endValueOffset);\n            valueOffset = endValueOffset;\n        }\n        else {\n            /* Literals */\n            const numLiterals = 256 - header;\n            for (let i = 0; i < numLiterals && valueOffset < numBytes; i++) {\n                values[valueOffset++] = buffer[pos.increment()];\n            }\n        }\n    }\n    pos.set(streamEndPos);\n    return values;\n}\nexport function decodeFloatsLE(encodedValues, pos, numValues, nullabilityBuffer) {\n    const currentPos = pos.get();\n    const newOffset = currentPos + numValues * Float32Array.BYTES_PER_ELEMENT;\n    const newBuf = new Uint8Array(encodedValues.subarray(currentPos, newOffset)).buffer;\n    const fb = new Float32Array(newBuf);\n    pos.set(newOffset);\n    if (nullabilityBuffer) {\n        return unpackNullable(fb, nullabilityBuffer, 0);\n    }\n    return fb;\n}\nexport function decodeDoublesLE(encodedValues, pos, numValues, nullabilityBuffer) {\n    const currentPos = pos.get();\n    const newOffset = currentPos + numValues * Float64Array.BYTES_PER_ELEMENT;\n    const newBuf = new Uint8Array(encodedValues.subarray(currentPos, newOffset)).buffer;\n    const fb = new Float64Array(newBuf);\n    pos.set(newOffset);\n    if (nullabilityBuffer) {\n        return unpackNullable(fb, nullabilityBuffer, 0);\n    }\n    return fb;\n}\nexport function decodeUint32sLE(encodedValues, pos, numValues) {\n    const currentPos = pos.get();\n    const byteLength = numValues * Uint32Array.BYTES_PER_ELEMENT;\n    const view = new DataView(encodedValues.buffer, encodedValues.byteOffset, encodedValues.byteLength);\n    const values = new Uint32Array(numValues);\n    for (let i = 0; i < numValues; i++) {\n        values[i] = view.getUint32(currentPos + i * Uint32Array.BYTES_PER_ELEMENT, true);\n    }\n    pos.add(byteLength);\n    return values;\n}\nexport function decodeUint64sLE(encodedValues, pos, numValues) {\n    const currentPos = pos.get();\n    const byteLength = numValues * BigUint64Array.BYTES_PER_ELEMENT;\n    const view = new DataView(encodedValues.buffer, encodedValues.byteOffset, encodedValues.byteLength);\n    const values = new BigUint64Array(numValues);\n    for (let i = 0; i < numValues; i++) {\n        values[i] = view.getBigUint64(currentPos + i * BigUint64Array.BYTES_PER_ELEMENT, true);\n    }\n    pos.add(byteLength);\n    return values;\n}\nconst TEXT_DECODER_MIN_LENGTH = 12;\nconst utf8TextDecoder = new TextDecoder();\n// Source: https://github.com/mapbox/pbf/issues/106\nexport function decodeString(buf, pos, end) {\n    if (end - pos >= TEXT_DECODER_MIN_LENGTH) {\n        // longer strings are fast with the built-in browser TextDecoder API\n        return utf8TextDecoder.decode(buf.subarray(pos, end));\n    }\n    // short strings are fast with custom implementation\n    return readUtf8(buf, pos, end);\n}\nfunction readUtf8(buf, pos, end) {\n    let str = \"\";\n    let i = pos;\n    while (i < end) {\n        const b0 = buf[i];\n        let c = null; // codepoint\n        let bytesPerSequence = b0 > 0xef ? 4 : b0 > 0xdf ? 3 : b0 > 0xbf ? 2 : 1;\n        if (i + bytesPerSequence > end)\n            break;\n        let b1;\n        let b2;\n        let b3;\n        if (bytesPerSequence === 1) {\n            if (b0 < 0x80) {\n                c = b0;\n            }\n        }\n        else if (bytesPerSequence === 2) {\n            b1 = buf[i + 1];\n            if ((b1 & 0xc0) === 0x80) {\n                c = ((b0 & 0x1f) << 0x6) | (b1 & 0x3f);\n                if (c <= 0x7f) {\n                    c = null;\n                }\n            }\n        }\n        else if (bytesPerSequence === 3) {\n            b1 = buf[i + 1];\n            b2 = buf[i + 2];\n            if ((b1 & 0xc0) === 0x80 && (b2 & 0xc0) === 0x80) {\n                c = ((b0 & 0xf) << 0xc) | ((b1 & 0x3f) << 0x6) | (b2 & 0x3f);\n                if (c <= 0x7ff || (c >= 0xd800 && c <= 0xdfff)) {\n                    c = null;\n                }\n            }\n        }\n        else if (bytesPerSequence === 4) {\n            b1 = buf[i + 1];\n            b2 = buf[i + 2];\n            b3 = buf[i + 3];\n            if ((b1 & 0xc0) === 0x80 && (b2 & 0xc0) === 0x80 && (b3 & 0xc0) === 0x80) {\n                c = ((b0 & 0xf) << 0x12) | ((b1 & 0x3f) << 0xc) | ((b2 & 0x3f) << 0x6) | (b3 & 0x3f);\n                if (c <= 0xffff || c >= 0x110000) {\n                    c = null;\n                }\n            }\n        }\n        if (c === null) {\n            c = 0xfffd;\n            bytesPerSequence = 1;\n        }\n        else if (c > 0xffff) {\n            c -= 0x10000;\n            str += String.fromCharCode(((c >>> 10) & 0x3ff) | 0xd800);\n            c = 0xdc00 | (c & 0x3ff);\n        }\n        str += String.fromCharCode(c);\n        i += bytesPerSequence;\n    }\n    return str;\n}\nexport function getVectorTypeBooleanStream(numFeatures, byteLength, data, offset) {\n    const valuesPerRun = 0x83;\n    // TODO: use VectorType metadata field for to test which VectorType is used\n    return Math.ceil(numFeatures / valuesPerRun) * 2 === byteLength &&\n        /* Test the first value byte if all bits are set to true */\n        (data[offset.get() + 1] & 0xff) === (bitCount(numFeatures) << 2) - 1\n        ? VectorType.CONST\n        : VectorType.FLAT;\n}\nfunction bitCount(number) {\n    //TODO: refactor to get rid of special case handling\n    return number === 0 ? 1 : Math.floor(Math.log2(number) + 1);\n}\n//# sourceMappingURL=decodingUtils.js.map", "import { PhysicalLevelTechnique } from \"../metadata/tile/physicalLevelTechnique\";\nimport IntWrapper from \"./intWrapper\";\nimport { decodeComponentwiseDeltaVec2, decodeComponentwiseDeltaVec2Scaled, decodeDeltaRleInt32, decodeDeltaRleInt64, decodeFastPfor, decodeUnsignedComponentwiseDeltaVec2, decodeUnsignedComponentwiseDeltaVec2Scaled, decodeUnsignedConstRleInt32, decodeUnsignedConstRleInt64, decodeUnsignedRleInt32, decodeUnsignedRleInt64, decodeUnsignedRleFloat64, decodeUnsignedZigZagDeltaInt32, decodeUnsignedZigZagDeltaInt64, decodeVarintInt32, decodeVarintInt64, decodeVarintFloat64, decodeZigZagInt32, decodeZigZagInt64, decodeZigZagFloat64, decodeZigZagConstRleInt32, decodeZigZagConstRleInt64, decodeZigZagDeltaInt32, decodeZigZagDeltaInt64, decodeZigZagDeltaFloat64, decodeZigZagSequenceRleInt32, decodeZigZagSequenceRleInt64, decodeZigZagInt32Value, decodeZigZagInt64Value, fastInverseDelta, inverseDelta, decodeRleDeltaInt32, decodeZigZagDeltaOfDeltaInt32, decodeZigZagRleDeltaInt32, decodeZigZagRleInt32, decodeZigZagRleInt64, decodeZigZagRleFloat64, } from \"./integerDecodingUtils\";\nimport { LogicalLevelTechnique } from \"../metadata/tile/logicalLevelTechnique\";\nimport BitVector from \"../vector/flat/bitVector\";\nimport { VectorType } from \"../vector/vectorType\";\nimport { decodeUint32sLE, decodeUint64sLE } from \"./decodingUtils\";\nimport { unpackNullable } from \"./unpackNullableUtils\";\nexport function decodeSignedInt32Stream(data, offset, streamMetadata, scalingData, nullabilityBuffer) {\n    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);\n    return decodeSignedInt32(values, streamMetadata, scalingData, nullabilityBuffer);\n}\nexport function decodeUnsignedInt32Stream(data, offset, streamMetadata, scalingData, nullabilityBuffer) {\n    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);\n    return decodeUnsignedInt32(values, streamMetadata, scalingData, nullabilityBuffer);\n}\nexport function decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata) {\n    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);\n    return decodeLengthToOffsetBuffer(values, streamMetadata);\n}\nfunction decodePhysicalLevelTechnique(data, offset, streamMetadata) {\n    const physicalLevelTechnique = streamMetadata.physicalLevelTechnique;\n    switch (physicalLevelTechnique) {\n        case PhysicalLevelTechnique.FAST_PFOR:\n            return decodeFastPfor(data, streamMetadata.numValues, streamMetadata.byteLength, offset);\n        case PhysicalLevelTechnique.VARINT:\n            return decodeVarintInt32(data, offset, streamMetadata.numValues);\n        case PhysicalLevelTechnique.NONE:\n            return decodeUint32sLE(data, offset, streamMetadata.numValues);\n        default:\n            throw new Error(`Specified physicalLevelTechnique ${physicalLevelTechnique} is not supported (yet).`);\n    }\n}\nfunction decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata) {\n    const physicalLevelTechnique = streamMetadata.physicalLevelTechnique;\n    switch (physicalLevelTechnique) {\n        case PhysicalLevelTechnique.VARINT:\n            return decodeVarintInt64(data, offset, streamMetadata.numValues);\n        case PhysicalLevelTechnique.NONE:\n            return decodeUint64sLE(data, offset, streamMetadata.numValues);\n        default:\n            throw new Error(`Specified physicalLevelTechnique ${physicalLevelTechnique} is not supported (yet).`);\n    }\n}\nexport function decodeSignedConstInt32Stream(data, offset, streamMetadata) {\n    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);\n    if (values.length === 1) {\n        return decodeZigZagInt32Value(values[0]);\n    }\n    return decodeZigZagConstRleInt32(values);\n}\nexport function decodeUnsignedConstInt32Stream(data, offset, streamMetadata) {\n    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);\n    if (values.length === 1) {\n        if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA) {\n            return decodeZigZagInt32Value(values[0]);\n        }\n        return values[0];\n    }\n    return decodeUnsignedConstRleInt32(values);\n}\nexport function decodeSequenceInt32Stream(data, offset, streamMetadata) {\n    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);\n    return decodeZigZagSequenceRleInt32(values);\n}\nexport function decodeSequenceInt64Stream(data, offset, streamMetadata) {\n    const values = decodeVarintInt64(data, offset, streamMetadata.numValues);\n    return decodeZigZagSequenceRleInt64(values);\n}\nexport function decodeSignedInt64Stream(data, offset, streamMetadata, nullabilityBuffer) {\n    const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata);\n    return decodeSignedInt64(values, streamMetadata, nullabilityBuffer);\n}\nexport function decodeUnsignedInt64Stream(data, offset, streamMetadata, nullabilityBuffer) {\n    const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata);\n    return decodeUnsignedInt64(values, streamMetadata, nullabilityBuffer);\n}\nexport function decodeSignedInt64AsFloat64Stream(data, offset, streamMetadata) {\n    return decodeInt64AsFloat64(data, offset, streamMetadata, true);\n}\nexport function decodeUnsignedInt64AsFloat64Stream(data, offset, streamMetadata, nullabilityBuffer) {\n    const values = decodeInt64AsFloat64(data, offset, streamMetadata, false);\n    return nullabilityBuffer ? unpackNullable(values, nullabilityBuffer, 0) : values;\n}\nfunction decodeInt64AsFloat64(data, offset, streamMetadata, isSigned) {\n    if (streamMetadata.physicalLevelTechnique === PhysicalLevelTechnique.VARINT) {\n        const values = decodeVarintFloat64(data, offset, streamMetadata.numValues);\n        return decodeFloat64Values(values, streamMetadata, isSigned);\n    }\n    const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata);\n    const decodedValues = isSigned\n        ? decodeSignedInt64(values, streamMetadata)\n        : decodeUnsignedInt64(values, streamMetadata);\n    return Float64Array.from(decodedValues, Number);\n}\nexport function decodeSignedConstInt64Stream(data, offset, streamMetadata) {\n    const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata);\n    if (values.length === 1) {\n        return decodeZigZagInt64Value(values[0]);\n    }\n    return decodeZigZagConstRleInt64(values);\n}\nexport function decodeUnsignedConstInt64Stream(data, offset, streamMetadata) {\n    const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata);\n    if (values.length === 1) {\n        if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA) {\n            return decodeZigZagInt64Value(values[0]);\n        }\n        return values[0];\n    }\n    return decodeUnsignedConstRleInt64(values);\n}\n/**\n * This method decodes integer streams.\n * Currently the encoder uses only fixed combinations of encodings.\n * For performance reasons it is also uses a fixed combination of the encodings on the decoding side.\n * The following encodings and combinations are used:\n *   - Morton Delta -> always sorted so not ZigZag encoding needed\n *   - Delta -> currently always in combination with ZigZag encoding\n *   - Rle -> in combination with ZigZag encoding if data type is signed\n *   - Delta Rle\n *   - Componentwise Delta -> always ZigZag encoding is used\n */\nfunction decodeSignedInt32(values, streamMetadata, scalingData, nullabilityBuffer) {\n    let decodedValues;\n    switch (streamMetadata.logicalLevelTechnique1) {\n        case LogicalLevelTechnique.DELTA:\n            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {\n                const rleMetadata = streamMetadata;\n                if (!nullabilityBuffer) {\n                    return decodeDeltaRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues);\n                }\n                values = decodeUnsignedRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues);\n                decodedValues = decodeZigZagDeltaInt32(values);\n            }\n            else {\n                decodedValues = decodeZigZagDeltaInt32(values);\n            }\n            break;\n        case LogicalLevelTechnique.RLE:\n            decodedValues = decodeZigZagRleInt32(values, streamMetadata.runs, streamMetadata.numRleValues);\n            break;\n        case LogicalLevelTechnique.MORTON:\n            fastInverseDelta(values);\n            decodedValues = new Int32Array(values);\n            break;\n        case LogicalLevelTechnique.COMPONENTWISE_DELTA:\n            if (scalingData && !nullabilityBuffer) {\n                return decodeComponentwiseDeltaVec2Scaled(values, scalingData.scale, scalingData.min, scalingData.max);\n            }\n            decodedValues = decodeComponentwiseDeltaVec2(values);\n            break;\n        case LogicalLevelTechnique.NONE:\n            decodedValues = decodeZigZagInt32(values);\n            break;\n        default:\n            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);\n    }\n    if (nullabilityBuffer) {\n        return unpackNullable(decodedValues, nullabilityBuffer, 0);\n    }\n    return decodedValues;\n}\nfunction decodeUnsignedInt32(values, streamMetadata, scalingData, nullabilityBuffer) {\n    let decodedValues;\n    switch (streamMetadata.logicalLevelTechnique1) {\n        case LogicalLevelTechnique.DELTA:\n            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {\n                const rleMetadata = streamMetadata;\n                const deltaValues = decodeUnsignedRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues);\n                decodedValues = decodeUnsignedZigZagDeltaInt32(deltaValues);\n            }\n            else {\n                decodedValues = decodeUnsignedZigZagDeltaInt32(values);\n            }\n            break;\n        case LogicalLevelTechnique.RLE:\n            decodedValues = decodeUnsignedRleInt32(values, streamMetadata.runs, streamMetadata.numRleValues);\n            break;\n        case LogicalLevelTechnique.MORTON:\n            fastInverseDelta(values);\n            decodedValues = values;\n            break;\n        case LogicalLevelTechnique.COMPONENTWISE_DELTA:\n            if (scalingData && !nullabilityBuffer) {\n                decodedValues = decodeUnsignedComponentwiseDeltaVec2Scaled(values, scalingData.scale, scalingData.min, scalingData.max);\n            }\n            else {\n                decodedValues = decodeUnsignedComponentwiseDeltaVec2(values);\n            }\n            break;\n        case LogicalLevelTechnique.NONE:\n            decodedValues = values;\n            break;\n        default:\n            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);\n    }\n    if (nullabilityBuffer) {\n        return unpackNullable(decodedValues, nullabilityBuffer, 0);\n    }\n    return decodedValues;\n}\nfunction decodeSignedInt64(values, streamMetadata, nullabilityBuffer) {\n    let decodedValues;\n    switch (streamMetadata.logicalLevelTechnique1) {\n        case LogicalLevelTechnique.DELTA:\n            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {\n                const rleMetadata = streamMetadata;\n                if (!nullabilityBuffer) {\n                    return decodeDeltaRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues);\n                }\n                values = decodeUnsignedRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues);\n                decodedValues = decodeZigZagDeltaInt64(values);\n            }\n            else {\n                decodedValues = decodeZigZagDeltaInt64(values);\n            }\n            break;\n        case LogicalLevelTechnique.RLE:\n            decodedValues = decodeZigZagRleInt64(values, streamMetadata.runs, streamMetadata.numRleValues);\n            break;\n        case LogicalLevelTechnique.NONE:\n            decodedValues = decodeZigZagInt64(values);\n            break;\n        default:\n            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);\n    }\n    if (nullabilityBuffer) {\n        return unpackNullable(decodedValues, nullabilityBuffer, 0n);\n    }\n    return decodedValues;\n}\nfunction decodeUnsignedInt64(values, streamMetadata, nullabilityBuffer) {\n    let decodedValues;\n    switch (streamMetadata.logicalLevelTechnique1) {\n        case LogicalLevelTechnique.DELTA:\n            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {\n                const rleMetadata = streamMetadata;\n                const deltaValues = decodeUnsignedRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues);\n                decodedValues = decodeUnsignedZigZagDeltaInt64(deltaValues);\n            }\n            else {\n                decodedValues = decodeUnsignedZigZagDeltaInt64(values);\n            }\n            break;\n        case LogicalLevelTechnique.RLE:\n            decodedValues = decodeUnsignedRleInt64(values, streamMetadata.runs, streamMetadata.numRleValues);\n            break;\n        case LogicalLevelTechnique.NONE:\n            decodedValues = values;\n            break;\n        default:\n            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);\n    }\n    if (nullabilityBuffer) {\n        return unpackNullable(decodedValues, nullabilityBuffer, 0n);\n    }\n    return decodedValues;\n}\nfunction decodeFloat64Values(values, streamMetadata, isSigned) {\n    switch (streamMetadata.logicalLevelTechnique1) {\n        case LogicalLevelTechnique.DELTA:\n            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {\n                const rleMetadata = streamMetadata;\n                values = decodeUnsignedRleFloat64(values, rleMetadata.runs, rleMetadata.numRleValues);\n            }\n            decodeZigZagDeltaFloat64(values);\n            return values;\n        case LogicalLevelTechnique.RLE:\n            return decodeRleFloat64(values, streamMetadata, isSigned);\n        case LogicalLevelTechnique.NONE:\n            if (isSigned) {\n                decodeZigZagFloat64(values);\n            }\n            return values;\n        default:\n            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);\n    }\n}\nfunction decodeLengthToOffsetBuffer(values, streamMetadata) {\n    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA &&\n        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) {\n        return decodeZigZagDeltaOfDeltaInt32(values);\n    }\n    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.RLE &&\n        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) {\n        const rleMetadata = streamMetadata;\n        return decodeRleDeltaInt32(values, rleMetadata.runs, rleMetadata.numRleValues);\n    }\n    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.NONE &&\n        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) {\n        //TODO: use fastInverseDelta again and check what are the performance problems in zoom 14\n        //fastInverseDelta(values);\n        inverseDelta(values);\n        const offsets = new Uint32Array(streamMetadata.numValues + 1);\n        offsets[0] = 0;\n        offsets.set(values, 1);\n        return offsets;\n    }\n    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA &&\n        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {\n        const rleMetadata = streamMetadata;\n        const decodedValues = decodeZigZagRleDeltaInt32(values, rleMetadata.runs, rleMetadata.numRleValues);\n        fastInverseDelta(decodedValues);\n        return new Uint32Array(decodedValues);\n    }\n    throw new Error(\"Only delta encoding is supported for transforming length to offset streams yet.\");\n}\nexport function getVectorType(streamMetadata, sizeOrNullabilityBuffer, data, offset, varintWidth = \"int32\") {\n    const logicalLevelTechnique1 = streamMetadata.logicalLevelTechnique1;\n    if (logicalLevelTechnique1 === LogicalLevelTechnique.RLE) {\n        return streamMetadata.runs === 1 ? VectorType.CONST : VectorType.FLAT;\n    }\n    if (logicalLevelTechnique1 !== LogicalLevelTechnique.DELTA ||\n        streamMetadata.logicalLevelTechnique2 !== LogicalLevelTechnique.RLE) {\n        return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;\n    }\n    const numFeatures = sizeOrNullabilityBuffer instanceof BitVector ? sizeOrNullabilityBuffer.size() : sizeOrNullabilityBuffer;\n    const rleMetadata = streamMetadata;\n    if (rleMetadata.numRleValues !== numFeatures) {\n        return VectorType.FLAT;\n    }\n    // Single run is always a sequence\n    if (rleMetadata.runs === 1) {\n        return VectorType.SEQUENCE;\n    }\n    if (rleMetadata.runs !== 2) {\n        return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;\n    }\n    // Two runs can be a sequence if both deltas are equal to 1\n    const savedOffset = offset.get();\n    if (streamMetadata.physicalLevelTechnique === PhysicalLevelTechnique.VARINT) {\n        if (isDeltaRleSequenceVarintWidth(data, offset, varintWidth)) {\n            return VectorType.SEQUENCE;\n        }\n        return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;\n    }\n    const byteOffset = offset.get();\n    const values = new Int32Array(data.buffer, data.byteOffset + byteOffset, 4);\n    offset.set(savedOffset);\n    // Check if both deltas are encoded 1\n    const zigZagOne = 2;\n    if (values[2] === zigZagOne && values[3] === zigZagOne) {\n        return VectorType.SEQUENCE;\n    }\n    return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;\n}\nfunction isDeltaRleSequenceVarintWidth(data, offset, varintWidth) {\n    const peekOffset = new IntWrapper(offset.get());\n    if (varintWidth === \"int64\") {\n        const values = decodeVarintInt64(data, peekOffset, 4);\n        return values[2] === 2n && values[3] === 2n;\n    }\n    const values = decodeVarintInt32(data, peekOffset, 4);\n    return values[2] === 2 && values[3] === 2;\n}\nfunction decodeRleFloat64(data, streamMetadata, isSigned) {\n    return isSigned\n        ? decodeZigZagRleFloat64(data, streamMetadata.runs, streamMetadata.numRleValues)\n        : decodeUnsignedRleFloat64(data, streamMetadata.runs, streamMetadata.numRleValues);\n}\n//# sourceMappingURL=integerStreamDecoder.js.map", "import { FixedSizeVector } from \"../fixedSizeVector\";\nexport class Int64FlatVector extends FixedSizeVector {\n    getValueFromBuffer(index) {\n        return this.dataBuffer[index];\n    }\n}\n//# sourceMappingURL=int64FlatVector.js.map", "import { SequenceVector } from \"./sequenceVector\";\nexport class Int64SequenceVector extends SequenceVector {\n    constructor(name, baseValue, delta, size, isSigned) {\n        super(name, isSigned ? BigInt64Array.of(baseValue) : BigUint64Array.of(baseValue), delta, size);\n    }\n    getValueFromBuffer(index) {\n        return this.dataBuffer[0] + BigInt(index) * this.delta;\n    }\n}\n//# sourceMappingURL=int64SequenceVector.js.map", "export function decodeZOrderCurve(mortonCode, numBits, coordinateShift) {\n    const x = decodeMorton(mortonCode, numBits) - coordinateShift;\n    const y = decodeMorton(mortonCode >> 1, numBits) - coordinateShift;\n    return { x, y };\n}\nfunction decodeMorton(code, numBits) {\n    let coordinate = 0;\n    for (let i = 0; i < numBits; i++) {\n        coordinate |= (code & (1 << (2 * i))) >> i;\n    }\n    return coordinate;\n}\n//# sourceMappingURL=zOrderCurve.js.map", "export var GEOMETRY_TYPE;\n(function (GEOMETRY_TYPE) {\n    GEOMETRY_TYPE[GEOMETRY_TYPE[\"POINT\"] = 0] = \"POINT\";\n    GEOMETRY_TYPE[GEOMETRY_TYPE[\"LINESTRING\"] = 1] = \"LINESTRING\";\n    GEOMETRY_TYPE[GEOMETRY_TYPE[\"POLYGON\"] = 2] = \"POLYGON\";\n    GEOMETRY_TYPE[GEOMETRY_TYPE[\"MULTIPOINT\"] = 3] = \"MULTIPOINT\";\n    GEOMETRY_TYPE[GEOMETRY_TYPE[\"MULTILINESTRING\"] = 4] = \"MULTILINESTRING\";\n    GEOMETRY_TYPE[GEOMETRY_TYPE[\"MULTIPOLYGON\"] = 5] = \"MULTIPOLYGON\";\n})(GEOMETRY_TYPE || (GEOMETRY_TYPE = {}));\nexport var SINGLE_PART_GEOMETRY_TYPE;\n(function (SINGLE_PART_GEOMETRY_TYPE) {\n    SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE[\"POINT\"] = 0] = \"POINT\";\n    SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE[\"LINESTRING\"] = 1] = \"LINESTRING\";\n    SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE[\"POLYGON\"] = 2] = \"POLYGON\";\n})(SINGLE_PART_GEOMETRY_TYPE || (SINGLE_PART_GEOMETRY_TYPE = {}));\n//# sourceMappingURL=geometryType.js.map", "export var VertexBufferType;\n(function (VertexBufferType) {\n    VertexBufferType[VertexBufferType[\"MORTON\"] = 0] = \"MORTON\";\n    VertexBufferType[VertexBufferType[\"VEC_2\"] = 1] = \"VEC_2\";\n    VertexBufferType[VertexBufferType[\"VEC_3\"] = 2] = \"VEC_3\";\n})(VertexBufferType || (VertexBufferType = {}));\n//# sourceMappingURL=vertexBufferType.js.map", "import { decodeZOrderCurve } from \"./zOrderCurve\";\nimport { GEOMETRY_TYPE } from \"./geometryType\";\nimport { VertexBufferType } from \"./vertexBufferType\";\nimport Point from \"@mapbox/point-geometry\";\nexport function convertGeometryVector(geometryVector) {\n    const geometries = new Array(geometryVector.numGeometries);\n    let partOffsetCounter = 1;\n    let ringOffsetsCounter = 1;\n    let geometryOffsetsCounter = 1;\n    let geometryCounter = 0;\n    let vertexBufferOffset = 0;\n    let vertexOffsetsOffset = 0;\n    const mortonSettings = geometryVector.mortonSettings;\n    const topologyVector = geometryVector.topologyVector;\n    const geometryOffsets = topologyVector.geometryOffsets;\n    const partOffsets = topologyVector.partOffsets;\n    const ringOffsets = topologyVector.ringOffsets;\n    const vertexOffsets = geometryVector.vertexOffsets;\n    const nonOffset = !vertexOffsets || vertexOffsets.length === 0;\n    const containsPolygon = geometryVector.containsPolygonGeometry();\n    const vertexBuffer = geometryVector.vertexBuffer;\n    for (let i = 0; i < geometryVector.numGeometries; i++) {\n        const geometryType = geometryVector.geometryType(i);\n        switch (geometryType) {\n            case GEOMETRY_TYPE.POINT:\n                {\n                    let x;\n                    let y;\n                    if (nonOffset) {\n                        x = vertexBuffer[vertexBufferOffset++];\n                        y = vertexBuffer[vertexBufferOffset++];\n                    }\n                    else if (geometryVector.vertexBufferType === VertexBufferType.MORTON) {\n                        const offset = vertexOffsets[vertexOffsetsOffset++];\n                        const mortonCode = vertexBuffer[offset];\n                        const vertex = decodeZOrderCurve(mortonCode, mortonSettings.numBits, mortonSettings.coordinateShift);\n                        x = vertex.x;\n                        y = vertex.y;\n                    }\n                    else {\n                        const offset = vertexOffsets[vertexOffsetsOffset++] * 2;\n                        x = vertexBuffer[offset];\n                        y = vertexBuffer[offset + 1];\n                    }\n                    geometries[geometryCounter++] = [[new Point(x, y)]];\n                    if (geometryOffsets)\n                        geometryOffsetsCounter++;\n                    if (partOffsets)\n                        partOffsetCounter++;\n                    if (ringOffsets)\n                        ringOffsetsCounter++;\n                }\n                break;\n            case GEOMETRY_TYPE.MULTIPOINT:\n                {\n                    const numPoints = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1];\n                    geometryOffsetsCounter++;\n                    let points;\n                    if (nonOffset) {\n                        points = new Array(numPoints);\n                        for (let j = 0; j < numPoints; j++) {\n                            const x = vertexBuffer[vertexBufferOffset++];\n                            const y = vertexBuffer[vertexBufferOffset++];\n                            points[j] = new Point(x, y);\n                        }\n                    }\n                    else {\n                        points = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numPoints, false, mortonSettings);\n                        vertexOffsetsOffset += numPoints;\n                    }\n                    geometries[geometryCounter++] = points.map((point) => [point]);\n                    // MULTIPOINT must increment offset counters like POINT does\n                    partOffsetCounter += numPoints;\n                    ringOffsetsCounter += numPoints;\n                }\n                break;\n            case GEOMETRY_TYPE.LINESTRING:\n                {\n                    let numVertices;\n                    if (containsPolygon) {\n                        numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];\n                        ringOffsetsCounter++;\n                    }\n                    else {\n                        numVertices = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];\n                    }\n                    partOffsetCounter++;\n                    let vertices;\n                    if (nonOffset) {\n                        vertices = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, false);\n                        vertexBufferOffset += numVertices * 2;\n                    }\n                    else {\n                        vertices = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, false, mortonSettings);\n                        vertexOffsetsOffset += numVertices;\n                    }\n                    geometries[geometryCounter++] = [vertices];\n                    if (geometryOffsets)\n                        geometryOffsetsCounter++;\n                }\n                break;\n            case GEOMETRY_TYPE.POLYGON:\n                {\n                    const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];\n                    partOffsetCounter++;\n                    const rings = new Array(numRings - 1);\n                    let shell;\n                    let numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];\n                    ringOffsetsCounter++;\n                    if (nonOffset) {\n                        shell = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true);\n                        vertexBufferOffset += numVertices * 2;\n                        for (let j = 0; j < rings.length; j++) {\n                            numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];\n                            ringOffsetsCounter++;\n                            rings[j] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true);\n                            vertexBufferOffset += numVertices * 2;\n                        }\n                    }\n                    else {\n                        shell = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings);\n                        vertexOffsetsOffset += numVertices;\n                        for (let j = 0; j < rings.length; j++) {\n                            numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];\n                            ringOffsetsCounter++;\n                            rings[j] = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings);\n                            vertexOffsetsOffset += numVertices;\n                        }\n                    }\n                    geometries[geometryCounter++] = [shell].concat(rings);\n                    if (geometryOffsets)\n                        geometryOffsetsCounter++;\n                }\n                break;\n            case GEOMETRY_TYPE.MULTILINESTRING:\n                {\n                    const numLineStrings = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1];\n                    geometryOffsetsCounter++;\n                    const lineStrings = new Array(numLineStrings);\n                    for (let j = 0; j < numLineStrings; j++) {\n                        let numVertices;\n                        if (containsPolygon) {\n                            numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];\n                            ringOffsetsCounter++;\n                        }\n                        else {\n                            numVertices = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];\n                        }\n                        partOffsetCounter++;\n                        if (nonOffset) {\n                            lineStrings[j] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, false);\n                            vertexBufferOffset += numVertices * 2;\n                        }\n                        else {\n                            const vertices = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, false, mortonSettings);\n                            lineStrings[j] = vertices;\n                            vertexOffsetsOffset += numVertices;\n                        }\n                    }\n                    geometries[geometryCounter++] = lineStrings;\n                }\n                break;\n            case GEOMETRY_TYPE.MULTIPOLYGON:\n                {\n                    const numPolygons = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1];\n                    geometryOffsetsCounter++;\n                    const polygons = new Array(numPolygons);\n                    for (let j = 0; j < numPolygons; j++) {\n                        const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];\n                        partOffsetCounter++;\n                        let shell;\n                        const rings = new Array(numRings - 1);\n                        const numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];\n                        ringOffsetsCounter++;\n                        if (nonOffset) {\n                            shell = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true);\n                            vertexBufferOffset += numVertices * 2;\n                        }\n                        else {\n                            shell = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings);\n                            vertexOffsetsOffset += numVertices;\n                        }\n                        for (let k = 0; k < rings.length; k++) {\n                            const numRingVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];\n                            ringOffsetsCounter++;\n                            if (nonOffset) {\n                                rings[k] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numRingVertices, true);\n                                vertexBufferOffset += numRingVertices * 2;\n                            }\n                            else {\n                                rings[k] = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numRingVertices, true, mortonSettings);\n                                vertexOffsetsOffset += numRingVertices;\n                            }\n                        }\n                        polygons[j] = [shell].concat(rings);\n                    }\n                    geometries[geometryCounter++] = polygons.flat();\n                }\n                break;\n            default:\n                throw new Error(`The specified geometry type (${geometryType}) is currently not supported.`);\n        }\n    }\n    return geometries;\n}\nfunction decodeDictionaryEncodedVertices(vertexBufferType, vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing, mortonSettings) {\n    if (vertexBufferType === VertexBufferType.MORTON) {\n        return decodeMortonDictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing, mortonSettings);\n    }\n    else {\n        return decodeVec2DictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing);\n    }\n}\nfunction getLineStringOrRing(vertexBuffer, startIndex, numVertices, isRing) {\n    const vertices = new Array(isRing ? numVertices + 1 : numVertices);\n    for (let i = 0; i < numVertices * 2; i += 2) {\n        const x = vertexBuffer[startIndex + i];\n        const y = vertexBuffer[startIndex + i + 1];\n        vertices[i / 2] = new Point(x, y);\n    }\n    if (isRing) {\n        vertices[vertices.length - 1] = vertices[0];\n    }\n    return vertices;\n}\nfunction decodeVec2DictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing) {\n    const vertices = new Array(isRing ? numVertices + 1 : numVertices);\n    for (let i = 0; i < numVertices * 2; i += 2) {\n        const offset = vertexOffsets[vertexOffset + i / 2] * 2;\n        const x = vertexBuffer[offset];\n        const y = vertexBuffer[offset + 1];\n        vertices[i / 2] = new Point(x, y);\n    }\n    if (isRing) {\n        vertices[vertices.length - 1] = vertices[0];\n    }\n    return vertices;\n}\nfunction decodeMortonDictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing, mortonSettings) {\n    const vertices = new Array(isRing ? numVertices + 1 : numVertices);\n    for (let i = 0; i < numVertices; i++) {\n        const offset = vertexOffsets[vertexOffset + i];\n        const mortonEncodedVertex = vertexBuffer[offset];\n        const vertex = decodeZOrderCurve(mortonEncodedVertex, mortonSettings.numBits, mortonSettings.coordinateShift);\n        vertices[i] = new Point(vertex.x, vertex.y);\n    }\n    if (isRing) {\n        vertices[vertices.length - 1] = vertices[0];\n    }\n    return vertices;\n}\n//# sourceMappingURL=geometryVectorConverter.js.map", "import { convertGeometryVector } from \"./geometryVectorConverter\";\nimport { decodeZOrderCurve } from \"./zOrderCurve\";\nexport class GeometryVector {\n    constructor(_vertexBufferType, _topologyVector, _vertexOffsets, _vertexBuffer, _mortonSettings) {\n        this._vertexBufferType = _vertexBufferType;\n        this._topologyVector = _topologyVector;\n        this._vertexOffsets = _vertexOffsets;\n        this._vertexBuffer = _vertexBuffer;\n        this._mortonSettings = _mortonSettings;\n    }\n    get vertexBufferType() {\n        return this._vertexBufferType;\n    }\n    get topologyVector() {\n        return this._topologyVector;\n    }\n    get vertexOffsets() {\n        return this._vertexOffsets;\n    }\n    get vertexBuffer() {\n        return this._vertexBuffer;\n    }\n    /* Allows faster access to the vertices since morton encoding is currently not used in the POC. Morton encoding\n       will be used after adapting the shader to decode the morton codes on the GPU. */\n    getSimpleEncodedVertex(index) {\n        const offset = this.vertexOffsets ? this.vertexOffsets[index] * 2 : index * 2;\n        const x = this.vertexBuffer[offset];\n        const y = this.vertexBuffer[offset + 1];\n        return [x, y];\n    }\n    //TODO: add scaling information to the constructor\n    getVertex(index) {\n        if (this.vertexOffsets && this.mortonSettings) {\n            //TODO: move decoding of the morton codes on the GPU in the vertex shader\n            const vertexOffset = this.vertexOffsets[index];\n            const mortonEncodedVertex = this.vertexBuffer[vertexOffset];\n            //TODO: improve performance -> inline calculation and move to decoding of VertexBuffer\n            const vertex = decodeZOrderCurve(mortonEncodedVertex, this.mortonSettings.numBits, this.mortonSettings.coordinateShift);\n            return [vertex.x, vertex.y];\n        }\n        const offset = this.vertexOffsets ? this.vertexOffsets[index] * 2 : index * 2;\n        const x = this.vertexBuffer[offset];\n        const y = this.vertexBuffer[offset + 1];\n        return [x, y];\n    }\n    getGeometries() {\n        return convertGeometryVector(this);\n    }\n    get mortonSettings() {\n        return this._mortonSettings;\n    }\n}\n//# sourceMappingURL=geometryVector.js.map", "import { GeometryVector } from \"./geometryVector\";\nimport { GEOMETRY_TYPE } from \"./geometryType\";\nimport { VertexBufferType } from \"./vertexBufferType\";\nexport function createConstGeometryVector(numGeometries, geometryType, topologyVector, vertexOffsets, vertexBuffer) {\n    return new ConstGeometryVector(numGeometries, geometryType, VertexBufferType.VEC_2, topologyVector, vertexOffsets, vertexBuffer);\n}\nexport function createMortonEncodedConstGeometryVector(numGeometries, geometryType, topologyVector, vertexOffsets, vertexBuffer, mortonInfo) {\n    return new ConstGeometryVector(numGeometries, geometryType, VertexBufferType.MORTON, topologyVector, vertexOffsets, vertexBuffer, mortonInfo);\n}\nexport class ConstGeometryVector extends GeometryVector {\n    constructor(_numGeometries, _geometryType, vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings) {\n        super(vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings);\n        this._numGeometries = _numGeometries;\n        this._geometryType = _geometryType;\n    }\n    geometryType(_index) {\n        return this._geometryType;\n    }\n    get numGeometries() {\n        return this._numGeometries;\n    }\n    containsPolygonGeometry() {\n        return this._geometryType === GEOMETRY_TYPE.POLYGON || this._geometryType === GEOMETRY_TYPE.MULTIPOLYGON;\n    }\n    containsSingleGeometryType() {\n        return true;\n    }\n}\n//# sourceMappingURL=constGeometryVector.js.map", "import { GeometryVector } from \"./geometryVector\";\nimport { GEOMETRY_TYPE } from \"./geometryType\";\nimport { VertexBufferType } from \"./vertexBufferType\";\nexport function createFlatGeometryVector(geometryTypes, topologyVector, vertexOffsets, vertexBuffer) {\n    return new FlatGeometryVector(VertexBufferType.VEC_2, geometryTypes, topologyVector, vertexOffsets, vertexBuffer);\n}\nexport function createFlatGeometryVectorMortonEncoded(geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonInfo) {\n    return new FlatGeometryVector(VertexBufferType.MORTON, geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonInfo);\n}\nexport class FlatGeometryVector extends GeometryVector {\n    constructor(vertexBufferType, _geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonSettings) {\n        super(vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings);\n        this._geometryTypes = _geometryTypes;\n    }\n    geometryType(index) {\n        return this._geometryTypes[index];\n    }\n    get numGeometries() {\n        return this._geometryTypes.length;\n    }\n    containsPolygonGeometry() {\n        for (let i = 0; i < this.numGeometries; i++) {\n            if (this.geometryType(i) === GEOMETRY_TYPE.POLYGON || this.geometryType(i) === GEOMETRY_TYPE.MULTIPOLYGON) {\n                return true;\n            }\n        }\n        return false;\n    }\n    containsSingleGeometryType() {\n        return false;\n    }\n}\n//# sourceMappingURL=flatGeometryVector.js.map", "import { createFlatGeometryVector } from \"./flatGeometryVector\";\nexport class GpuVector {\n    constructor(_triangleOffsets, _indexBuffer, _vertexBuffer, _topologyVector) {\n        this._triangleOffsets = _triangleOffsets;\n        this._indexBuffer = _indexBuffer;\n        this._vertexBuffer = _vertexBuffer;\n        this._topologyVector = _topologyVector;\n    }\n    get triangleOffsets() {\n        return this._triangleOffsets;\n    }\n    get indexBuffer() {\n        return this._indexBuffer;\n    }\n    get vertexBuffer() {\n        return this._vertexBuffer;\n    }\n    get topologyVector() {\n        return this._topologyVector;\n    }\n    getGeometries() {\n        if (!this._topologyVector) {\n            throw new Error(\"Cannot convert GpuVector to coordinates without topology information\");\n        }\n        const types = new Uint32Array(this.numGeometries);\n        for (let i = 0; i < this.numGeometries; i++) {\n            types[i] = this.geometryType(i);\n        }\n        return createFlatGeometryVector(types, this._topologyVector, undefined, this._vertexBuffer).getGeometries();\n    }\n    [Symbol.iterator]() {\n        /*for(let i = 1; i < this.triangleOffsets.length; i++) {\n           const numTriangles = this.triangleOffsets[i] - this.triangleOffsets[i-1];\n           const startIndex = this.triangleOffsets[i-1] * 3;\n           const endIndex = this.triangleOffsets[i] * 3;\n       }\n\n        while (index < this.numGeometries) {\n            yield geometries[index++];\n        }*/\n        //throw new Error(\"Iterator on a GpuVector is not implemented yet.\");\n        return null;\n    }\n}\n//# sourceMappingURL=gpuVector.js.map", "import { GpuVector } from \"./gpuVector\";\nexport function createConstGpuVector(numGeometries, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {\n    return new ConstGpuVector(numGeometries, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector);\n}\n//TODO: extend from GeometryVector -> make topology vector optional\nexport class ConstGpuVector extends GpuVector {\n    constructor(_numGeometries, _geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {\n        super(triangleOffsets, indexBuffer, vertexBuffer, topologyVector);\n        this._numGeometries = _numGeometries;\n        this._geometryType = _geometryType;\n    }\n    geometryType(_index) {\n        return this._geometryType;\n    }\n    get numGeometries() {\n        return this._numGeometries;\n    }\n    containsSingleGeometryType() {\n        return true;\n    }\n}\n//# sourceMappingURL=constGpuVector.js.map", "import { GpuVector } from \"./gpuVector\";\nexport function createFlatGpuVector(geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {\n    return new FlatGpuVector(geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector);\n}\n//TODO: extend from GeometryVector -> make topology vector optional\nexport class FlatGpuVector extends GpuVector {\n    constructor(_geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {\n        super(triangleOffsets, indexBuffer, vertexBuffer, topologyVector);\n        this._geometryTypes = _geometryTypes;\n    }\n    geometryType(index) {\n        return this._geometryTypes[index];\n    }\n    get numGeometries() {\n        return this._geometryTypes.length;\n    }\n    containsSingleGeometryType() {\n        return false;\n    }\n}\n//# sourceMappingURL=flatGpuVector.js.map", "import { decodeStreamMetadata } from \"../metadata/tile/streamMetadataDecoder\";\nimport { decodeSignedInt32Stream, decodeLengthStreamToOffsetBuffer, decodeUnsignedConstInt32Stream, decodeUnsignedInt32Stream, getVectorType, } from \"./integerStreamDecoder\";\nimport { VectorType } from \"../vector/vectorType\";\nimport { PhysicalStreamType } from \"../metadata/tile/physicalStreamType\";\nimport { LengthType } from \"../metadata/tile/lengthType\";\nimport { DictionaryType } from \"../metadata/tile/dictionaryType\";\nimport { createConstGeometryVector, createMortonEncodedConstGeometryVector, } from \"../vector/geometry/constGeometryVector\";\nimport { createFlatGeometryVector, createFlatGeometryVectorMortonEncoded } from \"../vector/geometry/flatGeometryVector\";\nimport { OffsetType } from \"../metadata/tile/offsetType\";\nimport { createConstGpuVector } from \"../vector/geometry/constGpuVector\";\nimport { createFlatGpuVector } from \"../vector/geometry/flatGpuVector\";\n// TODO: get rid of numFeatures parameter\nexport function decodeGeometryColumn(tile, numStreams, offset, numFeatures, scalingData) {\n    const geometryTypeMetadata = decodeStreamMetadata(tile, offset);\n    const geometryTypesVectorType = getVectorType(geometryTypeMetadata, numFeatures, tile, offset);\n    let vertexOffsets;\n    let vertexBuffer;\n    let mortonSettings;\n    let indexBuffer;\n    if (geometryTypesVectorType === VectorType.CONST) {\n        /* All geometries in the column have the same geometry type */\n        const geometryType = decodeUnsignedConstInt32Stream(tile, offset, geometryTypeMetadata);\n        // Variables for const geometry path (directly decoded as offsets)\n        let geometryOffsets;\n        let partOffsets;\n        let ringOffsets;\n        //TODO: use geometryOffsets for that? -> but then tessellated polygons can't be used with normal polygons\n        // in one FeatureTable?\n        let triangleOffsets;\n        for (let i = 0; i < numStreams - 1; i++) {\n            const geometryStreamMetadata = decodeStreamMetadata(tile, offset);\n            switch (geometryStreamMetadata.physicalStreamType) {\n                case PhysicalStreamType.LENGTH:\n                    switch (geometryStreamMetadata.logicalStreamType.lengthType) {\n                        case LengthType.GEOMETRIES:\n                            geometryOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);\n                            break;\n                        case LengthType.PARTS:\n                            partOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);\n                            break;\n                        case LengthType.RINGS:\n                            ringOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);\n                            break;\n                        case LengthType.TRIANGLES:\n                            triangleOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);\n                    }\n                    break;\n                case PhysicalStreamType.OFFSET: {\n                    switch (geometryStreamMetadata.logicalStreamType.offsetType) {\n                        case OffsetType.VERTEX:\n                            vertexOffsets = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);\n                            break;\n                        case OffsetType.INDEX:\n                            indexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);\n                            break;\n                    }\n                    break;\n                }\n                case PhysicalStreamType.DATA: {\n                    if (DictionaryType.VERTEX === geometryStreamMetadata.logicalStreamType.dictionaryType) {\n                        vertexBuffer = decodeSignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);\n                    }\n                    else {\n                        const mortonMetadata = geometryStreamMetadata;\n                        mortonSettings = {\n                            numBits: mortonMetadata.numBits,\n                            coordinateShift: mortonMetadata.coordinateShift,\n                        };\n                        vertexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);\n                    }\n                    break;\n                }\n            }\n        }\n        if (indexBuffer) {\n            if (geometryOffsets !== undefined || partOffsets !== undefined) {\n                /* Case when the indices of a Polygon outline are encoded in the tile */\n                const topologyVector = { geometryOffsets, partOffsets, ringOffsets };\n                return createConstGpuVector(numFeatures, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector);\n            }\n            /* Case when the no Polygon outlines are encoded in the tile */\n            return createConstGpuVector(numFeatures, geometryType, triangleOffsets, indexBuffer, vertexBuffer);\n        }\n        return mortonSettings === undefined\n            ? /* Currently only 2D coordinates (Vec2) are implemented in the encoder  */\n                createConstGeometryVector(numFeatures, geometryType, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer)\n            : createMortonEncodedConstGeometryVector(numFeatures, geometryType, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer, mortonSettings);\n    }\n    /* Different geometry types are mixed in the geometry column */\n    const geometryTypeVector = decodeUnsignedInt32Stream(tile, offset, geometryTypeMetadata);\n    // Variables for flat geometry path (decoded as lengths, then converted to offsets)\n    let geometryLengths;\n    let partLengths;\n    let ringLengths;\n    //TODO: use geometryOffsets for that? -> but then tessellated polygons can't be used with normal polygons\n    // in one FeatureTable?\n    let triangleOffsets;\n    for (let i = 0; i < numStreams - 1; i++) {\n        const geometryStreamMetadata = decodeStreamMetadata(tile, offset);\n        switch (geometryStreamMetadata.physicalStreamType) {\n            case PhysicalStreamType.LENGTH:\n                switch (geometryStreamMetadata.logicalStreamType.lengthType) {\n                    case LengthType.GEOMETRIES:\n                        geometryLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);\n                        break;\n                    case LengthType.PARTS:\n                        partLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);\n                        break;\n                    case LengthType.RINGS:\n                        ringLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);\n                        break;\n                    case LengthType.TRIANGLES:\n                        triangleOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);\n                }\n                break;\n            case PhysicalStreamType.OFFSET:\n                switch (geometryStreamMetadata.logicalStreamType.offsetType) {\n                    case OffsetType.VERTEX:\n                        vertexOffsets = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);\n                        break;\n                    case OffsetType.INDEX:\n                        indexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);\n                        break;\n                }\n                break;\n            case PhysicalStreamType.DATA:\n                if (DictionaryType.VERTEX === geometryStreamMetadata.logicalStreamType.dictionaryType) {\n                    vertexBuffer = decodeSignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);\n                }\n                else {\n                    const mortonMetadata = geometryStreamMetadata;\n                    mortonSettings = {\n                        numBits: mortonMetadata.numBits,\n                        coordinateShift: mortonMetadata.coordinateShift,\n                    };\n                    vertexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);\n                }\n                break;\n        }\n    }\n    // TODO: refactor the following instructions -> decode in one pass for performance reasons\n    /* Calculate the offsets from the length buffer for util access */\n    let geometryOffsets;\n    let partOffsets;\n    let ringOffsets;\n    if (geometryLengths) {\n        geometryOffsets = decodeRootLengthStream(geometryTypeVector, geometryLengths, 2);\n        if (partLengths && ringLengths) {\n            partOffsets = decodeLevel1LengthStream(geometryTypeVector, geometryOffsets, partLengths, false);\n            ringOffsets = decodeLevel2LengthStream(geometryTypeVector, geometryOffsets, partOffsets, ringLengths);\n        }\n        else if (partLengths) {\n            partOffsets = decodeLevel1WithoutRingBufferLengthStream(geometryTypeVector, geometryOffsets, partLengths);\n        }\n    }\n    else if (partLengths && ringLengths) {\n        partOffsets = decodeRootLengthStream(geometryTypeVector, partLengths, 1);\n        ringOffsets = decodeLevel1LengthStream(geometryTypeVector, partOffsets, ringLengths, true);\n    }\n    else if (partLengths) {\n        partOffsets = decodeRootLengthStream(geometryTypeVector, partLengths, 0);\n    }\n    if (indexBuffer && !partOffsets) {\n        /* Case when the indices of a Polygon outline are not encoded in the data so no\n         *  topology data are present in the tile */\n        return createFlatGpuVector(geometryTypeVector, triangleOffsets, indexBuffer, vertexBuffer);\n    }\n    if (indexBuffer) {\n        /* Case when the indices of a Polygon outline are encoded in the tile */\n        return createFlatGpuVector(geometryTypeVector, triangleOffsets, indexBuffer, vertexBuffer, {\n            geometryOffsets,\n            partOffsets,\n            ringOffsets,\n        });\n    }\n    return mortonSettings === undefined /* Currently only 2D coordinates (Vec2) are implemented in the encoder  */\n        ? createFlatGeometryVector(geometryTypeVector, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer)\n        : createFlatGeometryVectorMortonEncoded(geometryTypeVector, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer, mortonSettings);\n}\n/*\n * Handle the parsing of the different topology length buffers separate not generic to reduce the\n * branching and improve the performance\n */\nfunction decodeRootLengthStream(geometryTypes, rootLengthStream, bufferId) {\n    const rootBufferOffsets = new Uint32Array(geometryTypes.length + 1);\n    let previousOffset = 0;\n    rootBufferOffsets[0] = previousOffset;\n    let rootLengthCounter = 0;\n    for (let i = 0; i < geometryTypes.length; i++) {\n        /* Test if the geometry has and entry in the root buffer\n         * BufferId: 2 GeometryOffsets -> MultiPolygon, MultiLineString, MultiPoint\n         * BufferId: 1 PartOffsets -> Polygon\n         * BufferId: 0 PartOffsets, RingOffsets -> LineString\n         * */\n        previousOffset = rootBufferOffsets[i + 1] =\n            previousOffset + (geometryTypes[i] > bufferId ? rootLengthStream[rootLengthCounter++] : 1);\n    }\n    return rootBufferOffsets;\n}\nfunction decodeLevel1LengthStream(geometryTypes, rootOffsetBuffer, level1LengthBuffer, isLineStringPresent) {\n    const level1BufferOffsets = new Uint32Array(rootOffsetBuffer[rootOffsetBuffer.length - 1] + 1);\n    let previousOffset = 0;\n    level1BufferOffsets[0] = previousOffset;\n    let level1BufferCounter = 1;\n    let level1LengthBufferCounter = 0;\n    for (let i = 0; i < geometryTypes.length; i++) {\n        const geometryType = geometryTypes[i];\n        const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i];\n        if (geometryType === 5 ||\n            geometryType === 2 ||\n            (isLineStringPresent && (geometryType === 4 || geometryType === 1))) {\n            /* For MultiPolygon, Polygon and in some cases for MultiLineString and LineString\n             * a value in the level1LengthBuffer exists */\n            for (let j = 0; j < numGeometries; j++) {\n                previousOffset = level1BufferOffsets[level1BufferCounter++] =\n                    previousOffset + level1LengthBuffer[level1LengthBufferCounter++];\n            }\n        }\n        else {\n            /* For MultiPoint and Point and in some cases for MultiLineString and LineString no value in the\n             * level1LengthBuffer exists */\n            for (let j = 0; j < numGeometries; j++) {\n                level1BufferOffsets[level1BufferCounter++] = ++previousOffset;\n            }\n        }\n    }\n    return level1BufferOffsets;\n}\n/*\n * Case where no ring buffer exists so no MultiPolygon or Polygon geometry is part of the buffer\n */\nfunction decodeLevel1WithoutRingBufferLengthStream(geometryTypes, rootOffsetBuffer, level1LengthBuffer) {\n    const level1BufferOffsets = new Uint32Array(rootOffsetBuffer[rootOffsetBuffer.length - 1] + 1);\n    let previousOffset = 0;\n    level1BufferOffsets[0] = previousOffset;\n    let level1OffsetBufferCounter = 1;\n    let level1LengthCounter = 0;\n    for (let i = 0; i < geometryTypes.length; i++) {\n        const geometryType = geometryTypes[i];\n        const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i];\n        if (geometryType === 4 || geometryType === 1) {\n            /* For MultiLineString and LineString a value in the level1LengthBuffer exists */\n            for (let j = 0; j < numGeometries; j++) {\n                previousOffset = level1BufferOffsets[level1OffsetBufferCounter++] =\n                    previousOffset + level1LengthBuffer[level1LengthCounter++];\n            }\n        }\n        else {\n            /* For MultiPoint and Point no value in level1LengthBuffer exists */\n            for (let j = 0; j < numGeometries; j++) {\n                level1BufferOffsets[level1OffsetBufferCounter++] = ++previousOffset;\n            }\n        }\n    }\n    return level1BufferOffsets;\n}\nfunction decodeLevel2LengthStream(geometryTypes, rootOffsetBuffer, level1OffsetBuffer, level2LengthBuffer) {\n    const level2BufferOffsets = new Uint32Array(level1OffsetBuffer[level1OffsetBuffer.length - 1] + 1);\n    let previousOffset = 0;\n    level2BufferOffsets[0] = previousOffset;\n    let level1OffsetBufferCounter = 1;\n    let level2OffsetBufferCounter = 1;\n    let level2LengthBufferCounter = 0;\n    for (let i = 0; i < geometryTypes.length; i++) {\n        const geometryType = geometryTypes[i];\n        const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i];\n        if (geometryType !== 0 && geometryType !== 3) {\n            /* For MultiPolygon, MultiLineString, Polygon and LineString a value in level2LengthBuffer\n             * exists */\n            for (let j = 0; j < numGeometries; j++) {\n                const numParts = level1OffsetBuffer[level1OffsetBufferCounter] - level1OffsetBuffer[level1OffsetBufferCounter - 1];\n                level1OffsetBufferCounter++;\n                for (let k = 0; k < numParts; k++) {\n                    previousOffset = level2BufferOffsets[level2OffsetBufferCounter++] =\n                        previousOffset + level2LengthBuffer[level2LengthBufferCounter++];\n                }\n            }\n        }\n        else {\n            /* For MultiPoint and Point no value in level2LengthBuffer exists */\n            for (let j = 0; j < numGeometries; j++) {\n                level2BufferOffsets[level2OffsetBufferCounter++] = ++previousOffset;\n                level1OffsetBufferCounter++;\n            }\n        }\n    }\n    return level2BufferOffsets;\n}\n//# sourceMappingURL=geometryDecoder.js.map", "import Vector from \"../vector\";\nexport class BooleanFlatVector extends Vector {\n    constructor(name, dataVector, sizeOrNullabilityBuffer) {\n        super(name, dataVector.getBuffer(), sizeOrNullabilityBuffer);\n        this.dataVector = dataVector;\n    }\n    getValueFromBuffer(index) {\n        return this.dataVector.get(index);\n    }\n}\n//# sourceMappingURL=booleanFlatVector.js.map", "import { FixedSizeVector } from \"../fixedSizeVector\";\nexport class FloatFlatVector extends FixedSizeVector {\n    getValueFromBuffer(index) {\n        return this.dataBuffer[index];\n    }\n}\n//# sourceMappingURL=floatFlatVector.js.map", "import Vector from \"../vector\";\nexport class Int64ConstVector extends Vector {\n    constructor(name, value, sizeOrNullabilityBuffer, isSigned) {\n        super(name, isSigned ? BigInt64Array.of(value) : BigUint64Array.of(value), sizeOrNullabilityBuffer);\n    }\n    getValueFromBuffer(_index) {\n        return this.dataBuffer[0];\n    }\n}\n//# sourceMappingURL=int64ConstVector.js.map", "import Vector from \"./vector\";\nexport class VariableSizeVector extends Vector {\n    constructor(name, offsetBuffer, dataBuffer, sizeOrNullabilityBuffer) {\n        super(name, dataBuffer, sizeOrNullabilityBuffer);\n        this.offsetBuffer = offsetBuffer;\n    }\n}\n//# sourceMappingURL=variableSizeVector.js.map", "import { VariableSizeVector } from \"../variableSizeVector\";\nimport { decodeString } from \"../../decoding/decodingUtils\";\nexport class StringFlatVector extends VariableSizeVector {\n    constructor(name, offsetBuffer, dataBuffer, nullabilityBuffer) {\n        super(name, offsetBuffer, dataBuffer, nullabilityBuffer ?? offsetBuffer.length - 1);\n    }\n    getValueFromBuffer(index) {\n        const start = this.offsetBuffer[index];\n        const end = this.offsetBuffer[index + 1];\n        return decodeString(this.dataBuffer, start, end);\n    }\n}\n//# sourceMappingURL=stringFlatVector.js.map", "import { VariableSizeVector } from \"../variableSizeVector\";\nimport { decodeString } from \"../../decoding/decodingUtils\";\nexport class StringDictionaryVector extends VariableSizeVector {\n    constructor(name, indexBuffer, offsetBuffer, dictionaryBuffer, nullabilityBuffer) {\n        super(name, offsetBuffer, dictionaryBuffer, nullabilityBuffer ?? indexBuffer.length);\n        this.indexBuffer = indexBuffer;\n        this.indexBuffer = indexBuffer;\n    }\n    getValueFromBuffer(index) {\n        const offset = this.indexBuffer[index];\n        const start = this.offsetBuffer[offset];\n        const end = this.offsetBuffer[offset + 1];\n        return decodeString(this.dataBuffer, start, end);\n    }\n}\n//# sourceMappingURL=stringDictionaryVector.js.map", "/**\n * Calculates the exact output size before decoding. This allows one final\n * `Uint8Array` allocation and avoids growing a JavaScript number array and\n * copying it into a typed array afterward. Traversing the compressed data\n * twice is always worthwhile here because it avoids those larger temporary\n * allocations.\n */\nfunction getDecodedLength(symbolLengths, compressedData) {\n    let decodedLength = 0;\n    for (let i = 0; i < compressedData.length; i++) {\n        const symbolIndex = compressedData[i];\n        if (symbolIndex === 255) {\n            decodedLength++;\n            i++; // Skip the literal byte following the escape marker.\n        }\n        else {\n            decodedLength += symbolLengths[symbolIndex];\n        }\n    }\n    return decodedLength;\n}\n/**\n * Decode FSST compressed data\n *\n * @param symbols           Array of symbols, where each symbol can be between 1 and 8 bytes\n * @param symbolLengths     Array of symbol lengths, length of each symbol in symbols array\n * @param compressedData    FSST Compressed data, where each entry is an index to the symbols array\n * @returns                 Decoded data as Uint8Array\n */\nexport function decodeFsst(symbols, symbolLengths, compressedData) {\n    const symbolOffsets = new Uint32Array(symbolLengths.length);\n    for (let i = 1; i < symbolLengths.length; i++) {\n        symbolOffsets[i] = symbolOffsets[i - 1] + symbolLengths[i - 1];\n    }\n    const decodedData = new Uint8Array(getDecodedLength(symbolLengths, compressedData));\n    let decodedOffset = 0;\n    for (let i = 0; i < compressedData.length; i++) {\n        const symbolIndex = compressedData[i];\n        if (symbolIndex === 255) {\n            i++;\n            decodedData[decodedOffset++] = compressedData[i];\n        }\n        else {\n            let symbolLength = symbolLengths[symbolIndex];\n            let symbolOffset = symbolOffsets[symbolIndex];\n            while (symbolLength-- > 0) {\n                decodedData[decodedOffset++] = symbols[symbolOffset++];\n            }\n        }\n    }\n    return decodedData;\n}\n//# sourceMappingURL=fsstDecoder.js.map", "import { VariableSizeVector } from \"../variableSizeVector\";\nimport { decodeFsst } from \"../../decoding/fsstDecoder\";\nimport { decodeString } from \"../../decoding/decodingUtils\";\nexport class StringFsstDictionaryVector extends VariableSizeVector {\n    constructor(name, indexBuffer, offsetBuffer, dictionaryBuffer, symbolOffsetBuffer, symbolTableBuffer, nullabilityBuffer, \n    /** Cache shared by the FSST child columns of one SharedDict. */\n    sharedDictionaryCache) {\n        super(name, offsetBuffer, dictionaryBuffer, nullabilityBuffer ?? indexBuffer.length);\n        this.indexBuffer = indexBuffer;\n        this.symbolOffsetBuffer = symbolOffsetBuffer;\n        this.symbolTableBuffer = symbolTableBuffer;\n        this.sharedDictionaryCache = sharedDictionaryCache;\n    }\n    getValueFromBuffer(index) {\n        if (this.decodedDictionary == null) {\n            this.decodedDictionary = this.sharedDictionaryCache?.decodedDictionary;\n            if (this.decodedDictionary == null) {\n                this.decodedDictionary = this.decodeDictionary();\n                if (this.sharedDictionaryCache) {\n                    this.sharedDictionaryCache.decodedDictionary = this.decodedDictionary;\n                }\n            }\n        }\n        const offset = this.indexBuffer[index];\n        const start = this.offsetBuffer[offset];\n        const end = this.offsetBuffer[offset + 1];\n        return decodeString(this.decodedDictionary, start, end);\n    }\n    decodeDictionary() {\n        if (this.symbolLengthBuffer == null) {\n            this.symbolLengthBuffer = this.offsetToLengthBuffer(this.symbolOffsetBuffer);\n        }\n        return decodeFsst(this.symbolTableBuffer, this.symbolLengthBuffer, this.dataBuffer);\n    }\n    // TODO: get rid of that conversion\n    offsetToLengthBuffer(offsetBuffer) {\n        const lengthBuffer = new Uint32Array(offsetBuffer.length - 1);\n        let previousOffset = offsetBuffer[0];\n        for (let i = 1; i < offsetBuffer.length; i++) {\n            const offset = offsetBuffer[i];\n            lengthBuffer[i - 1] = offset - previousOffset;\n            previousOffset = offset;\n        }\n        return lengthBuffer;\n    }\n}\n//# sourceMappingURL=stringFsstDictionaryVector.js.map", "import { decodeStreamMetadata } from \"../metadata/tile/streamMetadataDecoder\";\nimport { StringFlatVector } from \"../vector/flat/stringFlatVector\";\nimport { StringDictionaryVector } from \"../vector/dictionary/stringDictionaryVector\";\nimport BitVector from \"../vector/flat/bitVector\";\nimport { PhysicalStreamType } from \"../metadata/tile/physicalStreamType\";\nimport { DictionaryType } from \"../metadata/tile/dictionaryType\";\nimport { LengthType } from \"../metadata/tile/lengthType\";\nimport { decodeUnsignedInt32Stream, decodeLengthStreamToOffsetBuffer } from \"./integerStreamDecoder\";\nimport { ScalarType } from \"../metadata/tileset/tilesetMetadata\";\nimport { decodeVarintInt32 } from \"./integerDecodingUtils\";\nimport { decodeBooleanRle, skipColumn } from \"./decodingUtils\";\nimport { StringFsstDictionaryVector, } from \"../vector/fsst-dictionary/stringFsstDictionaryVector\";\nexport function decodeString(name, data, offset, numStreams, bitVector) {\n    let dictionaryLengthStream;\n    let offsetStream;\n    let dictionaryStream;\n    let symbolLengthStream;\n    let symbolTableStream;\n    let nullabilityBuffer = bitVector;\n    let plainLengthStream;\n    let plainDataStream;\n    for (let i = 0; i < numStreams; i++) {\n        const streamMetadata = decodeStreamMetadata(data, offset);\n        switch (streamMetadata.physicalStreamType) {\n            case PhysicalStreamType.PRESENT: {\n                const presentData = decodeBooleanRle(data, streamMetadata.numValues, streamMetadata.byteLength, offset);\n                const presentStream = new BitVector(presentData, streamMetadata.numValues);\n                nullabilityBuffer = bitVector ?? presentStream;\n                break;\n            }\n            case PhysicalStreamType.OFFSET: {\n                offsetStream = decodeUnsignedInt32Stream(data, offset, streamMetadata, undefined, nullabilityBuffer);\n                break;\n            }\n            case PhysicalStreamType.LENGTH: {\n                const lengthStream = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata);\n                if (LengthType.DICTIONARY === streamMetadata.logicalStreamType.lengthType) {\n                    dictionaryLengthStream = lengthStream;\n                }\n                else if (LengthType.SYMBOL === streamMetadata.logicalStreamType.lengthType) {\n                    symbolLengthStream = lengthStream;\n                }\n                else {\n                    // Plain string encoding uses VAR_BINARY length type\n                    plainLengthStream = lengthStream;\n                }\n                break;\n            }\n            case PhysicalStreamType.DATA: {\n                const dataStream = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength);\n                offset.add(streamMetadata.byteLength);\n                const dictType = streamMetadata.logicalStreamType.dictionaryType;\n                if (DictionaryType.FSST === dictType) {\n                    symbolTableStream = dataStream;\n                }\n                else if (DictionaryType.SINGLE === dictType || DictionaryType.SHARED === dictType) {\n                    dictionaryStream = dataStream;\n                }\n                else if (DictionaryType.NONE === dictType) {\n                    plainDataStream = dataStream;\n                }\n                break;\n            }\n        }\n    }\n    return (decodeFsstDictionaryVector(name, symbolTableStream, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, nullabilityBuffer) ??\n        decodeDictionaryVector(name, dictionaryStream, offsetStream, dictionaryLengthStream, nullabilityBuffer) ??\n        decodePlainStringVector(name, plainLengthStream, plainDataStream, offsetStream, nullabilityBuffer));\n}\nfunction decodeFsstDictionaryVector(name, symbolTableStream, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, nullabilityBuffer) {\n    if (!symbolTableStream) {\n        return undefined;\n    }\n    if (!offsetStream || !dictionaryLengthStream || !dictionaryStream || !symbolLengthStream) {\n        throw new Error(`Incomplete FSST dictionary string column \"${name}\"`);\n    }\n    return new StringFsstDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, symbolTableStream, nullabilityBuffer);\n}\nfunction decodeDictionaryVector(name, dictionaryStream, offsetStream, dictionaryLengthStream, nullabilityBuffer) {\n    if (!dictionaryStream) {\n        return undefined;\n    }\n    if (!offsetStream || !dictionaryLengthStream) {\n        throw new Error(`Incomplete dictionary string column \"${name}\"`);\n    }\n    return nullabilityBuffer\n        ? new StringDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream, nullabilityBuffer)\n        : new StringDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream);\n}\nfunction decodePlainStringVector(name, plainLengthStream, plainDataStream, offsetStream, nullabilityBuffer) {\n    if (!plainLengthStream || !plainDataStream) {\n        return undefined;\n    }\n    if (offsetStream) {\n        return nullabilityBuffer\n            ? new StringDictionaryVector(name, offsetStream, plainLengthStream, plainDataStream, nullabilityBuffer)\n            : new StringDictionaryVector(name, offsetStream, plainLengthStream, plainDataStream);\n    }\n    if (nullabilityBuffer && nullabilityBuffer.size() !== plainLengthStream.length - 1) {\n        const sparseOffsetStream = new Uint32Array(nullabilityBuffer.size());\n        let valueIndex = 0;\n        for (let i = 0; i < nullabilityBuffer.size(); i++) {\n            if (nullabilityBuffer.get(i)) {\n                sparseOffsetStream[i] = valueIndex++;\n            }\n            else {\n                sparseOffsetStream[i] = 0;\n            }\n        }\n        return new StringDictionaryVector(name, sparseOffsetStream, plainLengthStream, plainDataStream, nullabilityBuffer);\n    }\n    return nullabilityBuffer\n        ? new StringFlatVector(name, plainLengthStream, plainDataStream, nullabilityBuffer)\n        : new StringFlatVector(name, plainLengthStream, plainDataStream);\n}\nexport function decodeSharedDictionary(data, offset, column, propertyColumnNames) {\n    let dictionaryOffsetBuffer;\n    let dictionaryBuffer;\n    let symbolOffsetBuffer;\n    let symbolTableBuffer;\n    let dictionaryStreamDecoded = false;\n    while (!dictionaryStreamDecoded) {\n        const streamMetadata = decodeStreamMetadata(data, offset);\n        switch (streamMetadata.physicalStreamType) {\n            case PhysicalStreamType.LENGTH:\n                if (LengthType.DICTIONARY === streamMetadata.logicalStreamType.lengthType) {\n                    dictionaryOffsetBuffer = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata);\n                }\n                else {\n                    symbolOffsetBuffer = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata);\n                }\n                break;\n            case PhysicalStreamType.DATA:\n                if (DictionaryType.SINGLE === streamMetadata.logicalStreamType.dictionaryType ||\n                    DictionaryType.SHARED === streamMetadata.logicalStreamType.dictionaryType) {\n                    dictionaryBuffer = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength);\n                    dictionaryStreamDecoded = true;\n                }\n                else {\n                    symbolTableBuffer = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength);\n                }\n                offset.add(streamMetadata.byteLength);\n                break;\n        }\n    }\n    if (column.type !== \"complexType\") {\n        throw new Error(`Shared dictionary column ${column.name} must be a complex (struct) column.`);\n    }\n    if (!dictionaryOffsetBuffer || !dictionaryBuffer) {\n        throw new Error(`Incomplete shared dictionary for column \"${column.name}\"`);\n    }\n    const childFields = column.complexType.children;\n    const stringDictionaryVectors = [];\n    /** Shared by every FSST child-column vector in this SharedDict and populated on first access. */\n    const sharedDictionaryCache = symbolTableBuffer ? {} : undefined;\n    let i = 0;\n    for (const childField of childFields) {\n        const numStreams = decodeVarintInt32(data, offset, 1)[0];\n        if (numStreams === 0) {\n            /* Column is not present in the tile */\n            continue;\n        }\n        const columnName = childField.name ? `${column.name}${childField.name}` : column.name;\n        if (propertyColumnNames) {\n            if (!propertyColumnNames.has(columnName)) {\n                //TODO: add size of sub column to Mlt for faster skipping\n                skipColumn(numStreams, data, offset);\n                continue;\n            }\n        }\n        if (childField.type !== \"scalarField\" || childField.scalarField.physicalType !== ScalarType.STRING) {\n            throw new Error(\"Currently only scalar string fields are implemented for a struct.\");\n        }\n        if ((numStreams > 1 && !childField.nullable) || (numStreams === 1 && childField.nullable)) {\n            throw new Error(`The number of streams for the child field ${childField.name} does not match its nullability. nullibilty: ${childField.nullable}, numStreams: ${numStreams}`);\n        }\n        let presentStreamBitVector;\n        if (childField.nullable) {\n            const presentStreamMetadata = decodeStreamMetadata(data, offset);\n            const presentStream = decodeBooleanRle(data, presentStreamMetadata.numValues, presentStreamMetadata.byteLength, offset);\n            presentStreamBitVector = new BitVector(presentStream, presentStreamMetadata.numValues);\n        }\n        const offsetStreamMetadata = decodeStreamMetadata(data, offset);\n        const offsetStream = decodeUnsignedInt32Stream(data, offset, offsetStreamMetadata, undefined, presentStreamBitVector);\n        if (symbolTableBuffer) {\n            if (!symbolOffsetBuffer) {\n                throw new Error(`Incomplete shared FSST dictionary for column \"${columnName}\"`);\n            }\n            stringDictionaryVectors[i++] = new StringFsstDictionaryVector(columnName, offsetStream, dictionaryOffsetBuffer, dictionaryBuffer, symbolOffsetBuffer, symbolTableBuffer, presentStreamBitVector, sharedDictionaryCache);\n        }\n        else {\n            stringDictionaryVectors[i++] = new StringDictionaryVector(columnName, offsetStream, dictionaryOffsetBuffer, dictionaryBuffer, presentStreamBitVector);\n        }\n    }\n    return stringDictionaryVectors;\n}\n//# sourceMappingURL=stringDecoder.js.map", "import Vector from \"../vector\";\n/**\n * Holds already-decoded values of arbitrary shape, one per feature.\n *\n * Unlike the other vectors there is no packed buffer to index into: nested property (MAP) columns\n * decode to plain JavaScript maps, arrays and scalars, so the values are kept as-is. Features\n * without a value are marked absent in the nullability buffer, so `has` reports them as missing and\n * `getValue` returns `null`.\n */\nexport class ObjectFlatVector extends Vector {\n    constructor(name, values, nullabilityBuffer) {\n        super(name, new Uint8Array(0), nullabilityBuffer ?? values.length);\n        this.values = values;\n    }\n    getValueFromBuffer(index) {\n        return this.values[index];\n    }\n}\n//# sourceMappingURL=objectFlatVector.js.map", "/**\n * Bitmask written ahead of a nested property (MAP) column, marking which optional streams follow\n * the mandatory length stream. Only one of INT32/INT64 and one of UINT32/UINT64 is ever set: the\n * encoder picks the narrower width that fits every value.\n */\nexport var MapMask;\n(function (MapMask) {\n    MapMask[MapMask[\"STRING\"] = 1] = \"STRING\";\n    MapMask[MapMask[\"INT32\"] = 2] = \"INT32\";\n    MapMask[MapMask[\"UINT32\"] = 4] = \"UINT32\";\n    MapMask[MapMask[\"INT64\"] = 8] = \"INT64\";\n    MapMask[MapMask[\"UINT64\"] = 16] = \"UINT64\";\n    MapMask[MapMask[\"FLOAT\"] = 32] = \"FLOAT\";\n    MapMask[MapMask[\"DOUBLE\"] = 64] = \"DOUBLE\";\n    MapMask[MapMask[\"PRESENCE\"] = 128] = \"PRESENCE\";\n})(MapMask || (MapMask = {}));\n//# sourceMappingURL=mapMask.js.map", "/**\n * Tokens in the data stream of a nested property (MAP) column. Values below `COUNT` describe the\n * structure; anything else is an index into the combined dictionary, offset by `COUNT`. Booleans are\n * encoded directly as tokens rather than being added to a dictionary.\n */\nexport var MapControlValue;\n(function (MapControlValue) {\n    MapControlValue[MapControlValue[\"FALSE\"] = 0] = \"FALSE\";\n    MapControlValue[MapControlValue[\"TRUE\"] = 1] = \"TRUE\";\n    /** A nested map follows: this token, the payload length including these two tokens, the payload. */\n    MapControlValue[MapControlValue[\"START_MAP\"] = 2] = \"START_MAP\";\n    /** A list follows, laid out the same way as START_MAP. */\n    MapControlValue[MapControlValue[\"START_LIST\"] = 3] = \"START_LIST\";\n    /** Number of reserved tokens, i.e. the first dictionary index. */\n    MapControlValue[MapControlValue[\"COUNT\"] = 4] = \"COUNT\";\n})(MapControlValue || (MapControlValue = {}));\n//# sourceMappingURL=mapControlValue.js.map", "import { ObjectFlatVector } from \"../vector/flat/objectFlatVector\";\nimport { decodeStreamMetadata } from \"../metadata/tile/streamMetadataDecoder\";\nimport { PhysicalStreamType } from \"../metadata/tile/physicalStreamType\";\nimport { MapMask } from \"../metadata/tile/mapMask\";\nimport { MapControlValue } from \"../metadata/tile/mapControlValue\";\nimport { decodeBooleanRle, decodeDoublesLE, decodeFloatsLE } from \"./decodingUtils\";\nimport { decodeSignedInt32Stream, decodeSignedInt64Stream, decodeUnsignedInt32Stream, decodeUnsignedInt64Stream, } from \"./integerStreamDecoder\";\nimport { decodeString } from \"./stringDecoder\";\nimport BitVector from \"../vector/flat/bitVector\";\n/**\n * Decodes a nested property (MAP) column into one vector per child column.\n *\n * The column is stored as a length stream (values per feature), a dictionary stream per value type\n * present, an optional presence stream, and a data stream of dictionary indices interleaved with\n * the control tokens that describe the map/list structure.\n *\n * Ported from the Java reference implementation (`MapPropertyDecoder`).\n */\nexport function decodeMapPropertyColumn(data, offset, columnMetadata, numStreams) {\n    const columnNames = getMapColumnNames(columnMetadata);\n    if (numStreams === 0) {\n        return columnNames.map((name) => new ObjectFlatVector(name, []));\n    }\n    const streams = decodeMapStreams(data, offset, numStreams);\n    const totalCounts = streams.presentStream ? streams.presentCount : streams.lengthStream.length;\n    const featureCount = totalCounts / columnNames.length;\n    const vectors = [];\n    let countsCursor = 0;\n    let valuesCursor = 0;\n    for (let childIndex = 0; childIndex < columnNames.length; childIndex++) {\n        const child = decodeChildColumn(streams, childIndex, featureCount, countsCursor, valuesCursor);\n        vectors.push(new ObjectFlatVector(columnNames[childIndex], child.value, child.nullabilityBuffer));\n        countsCursor = child.countsEnd;\n        valuesCursor = child.valuesEnd;\n    }\n    return vectors;\n}\n/**\n * A single map column carries its own name. A shared column carries one child per sibling, whose\n * full name is the parent name followed by the child name.\n */\nfunction getMapColumnNames(columnMetadata) {\n    const children = columnMetadata.type === \"complexType\" ? columnMetadata.complexType.children : undefined;\n    if (!children || children.length === 0) {\n        return [columnMetadata.name];\n    }\n    return children.map((child) => columnMetadata.name + (child.name ?? \"\"));\n}\n/** Reads the stream mask and every stream it announces, in the order the encoder wrote them. */\nfunction decodeMapStreams(data, offset, numStreams) {\n    const dictionaryMask = data[offset.get()];\n    offset.add(1);\n    // The length stream is the only mandatory one.\n    const lengthStream = decodeUnsignedInt32Stream(data, offset, decodeStreamMetadata(data, offset));\n    let remainingStreams = numStreams - 1;\n    const dictionary = [];\n    if (dictionaryMask & MapMask.STRING) {\n        remainingStreams -= decodeStringDictionary(data, offset, dictionary);\n    }\n    remainingStreams -= decodeIntegerDictionaries(data, offset, dictionaryMask, dictionary);\n    remainingStreams -= decodeFloatingPointDictionaries(data, offset, dictionaryMask, dictionary);\n    let presentStream;\n    let presentCount = 0;\n    if (dictionaryMask & MapMask.PRESENCE) {\n        const presence = decodePresenceStream(data, offset);\n        presentStream = presence.value;\n        presentCount = presence.count;\n        remainingStreams--;\n    }\n    let flattenedValues = new Uint32Array(0);\n    if (remainingStreams > 0) {\n        flattenedValues = decodeUnsignedInt32Stream(data, offset, decodeStreamMetadata(data, offset));\n        remainingStreams--;\n    }\n    if (remainingStreams !== 0) {\n        throw new Error(`Unexpected number of remaining streams while decoding map column: ${remainingStreams}`);\n    }\n    return { lengthStream, dictionary, presentStream, presentCount, flattenedValues };\n}\n/** @returns the number of streams consumed, which the string encoding decides for itself. */\nfunction decodeStringDictionary(data, offset, dictionary) {\n    const stringStreamCount = data[offset.get()];\n    offset.add(1);\n    const strings = decodeString(\"\", data, offset, stringStreamCount);\n    if (strings) {\n        for (let i = 0; i < strings.size; i++) {\n            dictionary.push(strings.getValue(i));\n        }\n    }\n    return stringStreamCount;\n}\n/**\n * Signed and unsigned integers each get at most one stream, whose width the encoder chose to fit\n * the widest value.\n *\n * @returns the number of streams consumed.\n */\nfunction decodeIntegerDictionaries(data, offset, dictionaryMask, dictionary) {\n    let consumed = 0;\n    if (dictionaryMask & MapMask.INT32) {\n        pushAll(dictionary, decodeSignedInt32Stream(data, offset, decodeStreamMetadata(data, offset)));\n        consumed++;\n    }\n    else if (dictionaryMask & MapMask.INT64) {\n        pushAll(dictionary, decodeSignedInt64Stream(data, offset, decodeStreamMetadata(data, offset)));\n        consumed++;\n    }\n    if (dictionaryMask & MapMask.UINT32) {\n        pushAll(dictionary, decodeUnsignedInt32Stream(data, offset, decodeStreamMetadata(data, offset)));\n        consumed++;\n    }\n    else if (dictionaryMask & MapMask.UINT64) {\n        pushAll(dictionary, decodeUnsignedInt64Stream(data, offset, decodeStreamMetadata(data, offset)));\n        consumed++;\n    }\n    return consumed;\n}\n/** @returns the number of streams consumed. */\nfunction decodeFloatingPointDictionaries(data, offset, dictionaryMask, dictionary) {\n    let consumed = 0;\n    if (dictionaryMask & MapMask.FLOAT) {\n        const streamMetadata = decodeStreamMetadata(data, offset);\n        pushAll(dictionary, decodeFloatsLE(data, offset, streamMetadata.numValues));\n        consumed++;\n    }\n    if (dictionaryMask & MapMask.DOUBLE) {\n        const streamMetadata = decodeStreamMetadata(data, offset);\n        pushAll(dictionary, decodeDoublesLE(data, offset, streamMetadata.numValues));\n        consumed++;\n    }\n    return consumed;\n}\nfunction decodePresenceStream(data, offset) {\n    const streamMetadata = decodeStreamMetadata(data, offset);\n    if (streamMetadata.physicalStreamType !== PhysicalStreamType.PRESENT) {\n        throw new Error(`Expected PRESENT stream for map column but found: ${streamMetadata.physicalStreamType}`);\n    }\n    const count = streamMetadata.numValues;\n    const streamDataStart = offset.get();\n    const value = new BitVector(decodeBooleanRle(data, count, streamMetadata.byteLength, offset), count);\n    offset.set(streamDataStart + streamMetadata.byteLength);\n    return { value, count };\n}\n/**\n * Decodes one child column's per-feature values.\n *\n * Lengths, presence bits and tokens are all laid out child-major, so each child picks up where the\n * previous one left off.\n */\nfunction decodeChildColumn(streams, childIndex, featureCount, countsCursor, valuesCursor) {\n    const { lengthStream, flattenedValues, presentStream, dictionary } = streams;\n    const presentOffset = childIndex * featureCount;\n    let presentInChild = featureCount;\n    let nullabilityBuffer;\n    if (presentStream) {\n        nullabilityBuffer = new BitVector(new Uint8Array(Math.ceil(featureCount / 8)), featureCount);\n        presentInChild = 0;\n        for (let i = 0; i < featureCount; i++) {\n            if (presentStream.get(presentOffset + i)) {\n                nullabilityBuffer.set(i, true);\n                presentInChild++;\n            }\n        }\n    }\n    const countsEnd = countsCursor + presentInChild;\n    if (countsEnd > lengthStream.length) {\n        throw new Error(\"Merged map counts underflow while decoding child streams\");\n    }\n    const value = new Array(featureCount);\n    let countCursor = countsCursor;\n    let flattenedIndex = valuesCursor;\n    for (let featureIndex = 0; featureIndex < featureCount; featureIndex++) {\n        if (presentStream && !presentStream.get(presentOffset + featureIndex)) {\n            value[featureIndex] = null;\n            continue;\n        }\n        const endIndex = flattenedIndex + lengthStream[countCursor++];\n        if (endIndex > flattenedValues.length) {\n            throw new Error(\"Map value stream underflow while decoding feature payload\");\n        }\n        const decoded = decodeFeatureValue(flattenedValues, flattenedIndex, endIndex, dictionary);\n        value[featureIndex] = decoded.value;\n        flattenedIndex = decoded.nextIndex;\n    }\n    let childValueCount = 0;\n    for (let i = countsCursor; i < countsEnd; i++)\n        childValueCount += lengthStream[i];\n    const valuesEnd = valuesCursor + childValueCount;\n    if (flattenedIndex !== valuesEnd) {\n        throw new Error(\"Unused flattened map values remain after decode\");\n    }\n    return { value, nullabilityBuffer, countsEnd, valuesEnd };\n}\n/**\n * A feature's payload is a bare sequence of map entries, unless it is a single token - a root-level\n * scalar - or opens with a list token. Those two shapes are what distinguish it from map entries.\n */\nfunction decodeFeatureValue(flattenedValues, startIndex, endIndex, dictionary) {\n    if (endIndex - startIndex === 1 || flattenedValues[startIndex] === MapControlValue.START_LIST) {\n        return decodeValue(flattenedValues, startIndex, endIndex, dictionary);\n    }\n    return decodeMapEntries(flattenedValues, startIndex, endIndex, dictionary);\n}\nfunction decodeMapEntries(flattenedValues, startIndex, endIndex, dictionary) {\n    // Keys come off the wire, so the object is created without a prototype: a `__proto__` key would\n    // otherwise reassign the prototype instead of being stored as an entry.\n    const value = Object.create(null);\n    let index = startIndex;\n    while (index < endIndex) {\n        const key = decodeScalarByIndex(flattenedValues[index++], dictionary);\n        if (typeof key !== \"string\") {\n            throw new Error(`Map key dictionary index does not resolve to a string: ${key}`);\n        }\n        const decoded = decodeValue(flattenedValues, index, endIndex, dictionary);\n        value[key] = decoded.value;\n        index = decoded.nextIndex;\n    }\n    return { value, nextIndex: index };\n}\nfunction decodeValue(flattenedValues, startIndex, endIndex, dictionary) {\n    if (startIndex >= endIndex) {\n        throw new Error(\"Unexpected end of map value stream\");\n    }\n    const token = flattenedValues[startIndex];\n    if (token === MapControlValue.FALSE)\n        return { value: false, nextIndex: startIndex + 1 };\n    if (token === MapControlValue.TRUE)\n        return { value: true, nextIndex: startIndex + 1 };\n    if (token === MapControlValue.START_MAP) {\n        const valueEndIndex = decodeNestedPayloadEnd(flattenedValues, startIndex, endIndex);\n        const nested = decodeMapEntries(flattenedValues, startIndex + 2, valueEndIndex, dictionary);\n        return { value: nested.value, nextIndex: valueEndIndex };\n    }\n    if (token === MapControlValue.START_LIST) {\n        const valueEndIndex = decodeNestedPayloadEnd(flattenedValues, startIndex, endIndex);\n        const value = [];\n        let index = startIndex + 2;\n        while (index < valueEndIndex) {\n            const nested = decodeValue(flattenedValues, index, valueEndIndex, dictionary);\n            value.push(nested.value);\n            index = nested.nextIndex;\n        }\n        return { value, nextIndex: valueEndIndex };\n    }\n    return { value: decodeScalarByIndex(token, dictionary), nextIndex: startIndex + 1 };\n}\n/**\n * Reads the length prefix of a nested payload and returns where it ends, the counterpart of\n * `encodeNestedPayloadLength`. The length covers the two header tokens as well.\n */\nfunction decodeNestedPayloadEnd(flattenedValues, startIndex, endIndex) {\n    if (startIndex + 1 >= endIndex) {\n        throw new Error(\"Missing length for nested map/list payload\");\n    }\n    const encodedLength = flattenedValues[startIndex + 1];\n    if (encodedLength < 2) {\n        throw new Error(`Invalid nested payload length: ${encodedLength}`);\n    }\n    const valueEndIndex = startIndex + encodedLength;\n    if (valueEndIndex > endIndex) {\n        throw new Error(\"Nested payload exceeds containing payload bounds\");\n    }\n    return valueEndIndex;\n}\nfunction decodeScalarByIndex(token, dictionary) {\n    const dictionaryIndex = token - MapControlValue.COUNT;\n    if (dictionaryIndex < 0 || dictionaryIndex >= dictionary.length) {\n        throw new Error(`Scalar dictionary index out of range: ${token}`);\n    }\n    return dictionary[dictionaryIndex];\n}\nfunction pushAll(dictionary, values) {\n    for (const value of values)\n        dictionary.push(value);\n}\n//# sourceMappingURL=mapPropertyDecoder.js.map", "import { ComplexType, ScalarType } from \"../metadata/tileset/tilesetMetadata\";\nimport BitVector from \"../vector/flat/bitVector\";\nimport { decodeStreamMetadata } from \"../metadata/tile/streamMetadataDecoder\";\nimport { VectorType } from \"../vector/vectorType\";\nimport { BooleanFlatVector } from \"../vector/flat/booleanFlatVector\";\nimport { DoubleFlatVector } from \"../vector/flat/doubleFlatVector\";\nimport { FloatFlatVector } from \"../vector/flat/floatFlatVector\";\nimport { Int64ConstVector } from \"../vector/constant/int64ConstVector\";\nimport { Int64FlatVector } from \"../vector/flat/int64FlatVector\";\nimport { Int32FlatVector } from \"../vector/flat/int32FlatVector\";\nimport { Int32ConstVector } from \"../vector/constant/int32ConstVector\";\nimport { decodeBooleanRle, decodeDoublesLE, decodeFloatsLE, skipColumn } from \"./decodingUtils\";\nimport { decodeSignedConstInt32Stream, decodeSignedConstInt64Stream, decodeSignedInt32Stream, decodeSignedInt64Stream, decodeUnsignedInt32Stream, decodeUnsignedConstInt32Stream, decodeUnsignedConstInt64Stream, decodeUnsignedInt64Stream, decodeSequenceInt32Stream, decodeSequenceInt64Stream, getVectorType, } from \"./integerStreamDecoder\";\nimport { Int32SequenceVector } from \"../vector/sequence/int32SequenceVector\";\nimport { Int64SequenceVector } from \"../vector/sequence/int64SequenceVector\";\nimport { decodeSharedDictionary, decodeString } from \"./stringDecoder\";\nimport { decodeMapPropertyColumn } from \"./mapPropertyDecoder\";\nexport function decodePropertyColumn(data, offset, columnMetadata, numStreams, numFeatures, propertyColumnNames) {\n    if (columnMetadata.type === \"scalarType\") {\n        if (propertyColumnNames && !propertyColumnNames.has(columnMetadata.name)) {\n            skipColumn(numStreams, data, offset);\n            return null;\n        }\n        return decodeScalarPropertyColumn(numStreams, data, offset, numFeatures, columnMetadata.scalarType, columnMetadata);\n    }\n    if (columnMetadata.complexType?.physicalType === ComplexType.MAP) {\n        return decodeMapPropertyColumn(data, offset, columnMetadata, numStreams);\n    }\n    if (numStreams === 0) {\n        return null;\n    }\n    return decodeSharedDictionary(data, offset, columnMetadata, propertyColumnNames);\n}\nfunction decodeScalarPropertyColumn(numStreams, data, offset, numFeatures, column, columnMetadata) {\n    let nullabilityBuffer;\n    if (numStreams === 0) {\n        return null;\n    }\n    if (columnMetadata.nullable) {\n        const presentStreamMetadata = decodeStreamMetadata(data, offset);\n        const numValues = presentStreamMetadata.numValues;\n        const streamDataStart = offset.get();\n        const presentVector = decodeBooleanRle(data, numValues, presentStreamMetadata.byteLength, offset);\n        offset.set(streamDataStart + presentStreamMetadata.byteLength);\n        nullabilityBuffer = new BitVector(presentVector, presentStreamMetadata.numValues);\n    }\n    const sizeOrNullabilityBuffer = nullabilityBuffer ?? numFeatures;\n    const scalarType = column.physicalType;\n    switch (scalarType) {\n        case ScalarType.UINT_32:\n        case ScalarType.INT_32:\n            return decodeInt32Column(data, offset, columnMetadata, column, sizeOrNullabilityBuffer);\n        case ScalarType.STRING: {\n            // In embedded format: numStreams includes nullability stream if column is nullable\n            const stringDataStreams = columnMetadata.nullable ? numStreams - 1 : numStreams;\n            return decodeString(columnMetadata.name, data, offset, stringDataStreams, nullabilityBuffer) ?? null;\n        }\n        case ScalarType.BOOLEAN:\n            return decodeBooleanColumn(data, offset, columnMetadata, numFeatures, sizeOrNullabilityBuffer);\n        case ScalarType.UINT_64:\n        case ScalarType.INT_64:\n            return decodeInt64Column(data, offset, columnMetadata, sizeOrNullabilityBuffer, column);\n        case ScalarType.FLOAT:\n            return decodeFloatColumn(data, offset, columnMetadata, sizeOrNullabilityBuffer);\n        case ScalarType.DOUBLE:\n            return decodeDoubleColumn(data, offset, columnMetadata, sizeOrNullabilityBuffer);\n        default:\n            throw new Error(`The specified data type for the field is currently not supported: ${column}`);\n    }\n}\nfunction decodeBooleanColumn(data, offset, column, _numFeatures, sizeOrNullabilityBuffer) {\n    const dataStreamMetadata = decodeStreamMetadata(data, offset);\n    const numValues = dataStreamMetadata.numValues;\n    const streamDataStart = offset.get();\n    const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;\n    const dataStream = decodeBooleanRle(data, numValues, dataStreamMetadata.byteLength, offset, nullabilityBuffer);\n    offset.set(streamDataStart + dataStreamMetadata.byteLength);\n    const dataVector = new BitVector(dataStream, numValues);\n    return new BooleanFlatVector(column.name, dataVector, sizeOrNullabilityBuffer);\n}\nfunction decodeFloatColumn(data, offset, column, sizeOrNullabilityBuffer) {\n    const dataStreamMetadata = decodeStreamMetadata(data, offset);\n    const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;\n    const dataStream = decodeFloatsLE(data, offset, dataStreamMetadata.numValues, nullabilityBuffer);\n    return new FloatFlatVector(column.name, dataStream, sizeOrNullabilityBuffer);\n}\nfunction decodeDoubleColumn(data, offset, column, sizeOrNullabilityBuffer) {\n    const dataStreamMetadata = decodeStreamMetadata(data, offset);\n    const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;\n    const dataStream = decodeDoublesLE(data, offset, dataStreamMetadata.numValues, nullabilityBuffer);\n    return new DoubleFlatVector(column.name, dataStream, sizeOrNullabilityBuffer);\n}\nfunction decodeInt64Column(data, offset, column, sizeOrNullabilityBuffer, scalarColumn) {\n    const dataStreamMetadata = decodeStreamMetadata(data, offset);\n    const vectorType = getVectorType(dataStreamMetadata, sizeOrNullabilityBuffer, data, offset, \"int64\");\n    const isSigned = scalarColumn.physicalType === ScalarType.INT_64;\n    if (vectorType === VectorType.FLAT) {\n        const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;\n        const dataStream = isSigned\n            ? decodeSignedInt64Stream(data, offset, dataStreamMetadata, nullabilityBuffer)\n            : decodeUnsignedInt64Stream(data, offset, dataStreamMetadata, nullabilityBuffer);\n        return new Int64FlatVector(column.name, dataStream, sizeOrNullabilityBuffer);\n    }\n    if (vectorType === VectorType.SEQUENCE) {\n        const id = decodeSequenceInt64Stream(data, offset, dataStreamMetadata);\n        return new Int64SequenceVector(column.name, id[0], id[1], dataStreamMetadata.numRleValues, isSigned);\n    }\n    const constValue = isSigned\n        ? decodeSignedConstInt64Stream(data, offset, dataStreamMetadata)\n        : decodeUnsignedConstInt64Stream(data, offset, dataStreamMetadata);\n    return new Int64ConstVector(column.name, constValue, sizeOrNullabilityBuffer, isSigned);\n}\nfunction decodeInt32Column(data, offset, column, scalarColumn, sizeOrNullabilityBuffer) {\n    const dataStreamMetadata = decodeStreamMetadata(data, offset);\n    const vectorType = getVectorType(dataStreamMetadata, sizeOrNullabilityBuffer, data, offset);\n    const isSigned = scalarColumn.physicalType === ScalarType.INT_32;\n    if (vectorType === VectorType.FLAT) {\n        const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;\n        const dataStream = isSigned\n            ? decodeSignedInt32Stream(data, offset, dataStreamMetadata, undefined, nullabilityBuffer)\n            : decodeUnsignedInt32Stream(data, offset, dataStreamMetadata, undefined, nullabilityBuffer);\n        return new Int32FlatVector(column.name, dataStream, sizeOrNullabilityBuffer);\n    }\n    if (vectorType === VectorType.SEQUENCE) {\n        const id = decodeSequenceInt32Stream(data, offset, dataStreamMetadata);\n        return new Int32SequenceVector(column.name, id[0], id[1], dataStreamMetadata.numRleValues, isSigned);\n    }\n    const constValue = isSigned\n        ? decodeSignedConstInt32Stream(data, offset, dataStreamMetadata)\n        : decodeUnsignedConstInt32Stream(data, offset, dataStreamMetadata);\n    return new Int32ConstVector(column.name, constValue, sizeOrNullabilityBuffer, isSigned);\n}\nfunction isNullabilityBuffer(sizeOrNullabilityBuffer) {\n    return sizeOrNullabilityBuffer instanceof BitVector;\n}\n//# sourceMappingURL=propertyDecoder.js.map", "import { ColumnScope, ComplexType, LogicalScalarType, ScalarType, } from \"./tilesetMetadata\";\n/**\n * The single varint32 that introduces every column in the tile metadata, identifying what kind of\n * column follows. Ids occupy a small range of flagged codes, geometry has one code of its own, and\n * scalar properties are laid out from `SCALAR_BASE` upwards, two codes per type.\n */\nexport const ColumnTypeCode = {\n    /** Id columns occupy 0..3. */\n    ID: 0,\n    /** Set on an id column whose values can be null. */\n    ID_NULLABLE: 1,\n    /** Set on an id column holding 64-bit rather than 32-bit ids. */\n    ID_LONG: 2,\n    GEOMETRY: 4,\n    /** Scalar properties are `SCALAR_BASE + scalarType * 2 + (nullable ? 1 : 0)`. */\n    SCALAR_BASE: 10,\n    STRUCT: 30,\n    MAP: 31,\n};\n/**\n * The type code is a single varint32 that encodes:\n * - Physical or logical type\n * - Nullable flag\n * - Whether the column has a name (typeCode >= ColumnTypeCode.SCALAR_BASE)\n * - Whether the column has children (typeCode == 30 for STRUCT)\n * - For ID types: whether it uses long (64-bit) IDs\n */\n/**\n * Decodes a type code into a Column structure.\n *\n * ID type codes (0..3):\n * - Bit 0: nullable\n * - Bit 1: longID (0/1 -> uint32 IDs, 2/3 -> uint64 IDs)\n *\n * ID columns are kept as logical types so they remain distinguishable\n * from feature properties that may also be named \"id\".\n */\nexport function decodeColumnType(typeCode) {\n    switch (typeCode) {\n        case ColumnTypeCode.ID:\n        case ColumnTypeCode.ID | ColumnTypeCode.ID_NULLABLE:\n        case ColumnTypeCode.ID | ColumnTypeCode.ID_LONG:\n        case ColumnTypeCode.ID | ColumnTypeCode.ID_LONG | ColumnTypeCode.ID_NULLABLE:\n            return {\n                nullable: (typeCode & ColumnTypeCode.ID_NULLABLE) !== 0,\n                columnScope: ColumnScope.FEATURE,\n                type: \"scalarType\",\n                scalarType: {\n                    longID: (typeCode & ColumnTypeCode.ID_LONG) !== 0,\n                    type: \"logicalType\",\n                    logicalType: LogicalScalarType.ID,\n                },\n            };\n        case ColumnTypeCode.GEOMETRY:\n            // GEOMETRY (non-nullable, no children)\n            return {\n                nullable: false,\n                columnScope: ColumnScope.FEATURE,\n                type: \"complexType\",\n                complexType: {\n                    type: \"physicalType\",\n                    physicalType: ComplexType.GEOMETRY,\n                    children: [],\n                },\n            };\n        case ColumnTypeCode.STRUCT:\n            // STRUCT (non-nullable with children)\n            return {\n                nullable: false,\n                columnScope: ColumnScope.FEATURE,\n                type: \"complexType\",\n                complexType: {\n                    type: \"physicalType\",\n                    physicalType: ComplexType.STRUCT,\n                    children: [],\n                },\n            };\n        case ColumnTypeCode.MAP:\n            // MAP (nested properties, always nullable, may carry children when the\n            // dictionaries are shared between sibling columns)\n            return {\n                nullable: true,\n                columnScope: ColumnScope.FEATURE,\n                type: \"complexType\",\n                complexType: {\n                    type: \"physicalType\",\n                    physicalType: ComplexType.MAP,\n                    children: [],\n                },\n            };\n        default:\n            return mapScalarType(typeCode);\n    }\n}\n/**\n * Returns true if this type code requires a name to be stored.\n * ID (0-3) and GEOMETRY (4) columns have implicit names.\n * All other types (>= ColumnTypeCode.SCALAR_BASE) require explicit names.\n */\nexport function columnTypeHasName(typeCode) {\n    return typeCode >= ColumnTypeCode.SCALAR_BASE;\n}\n/**\n * Returns true if this type code has child fields.\n * STRUCT (typeCode 30) and MAP (typeCode 31) have children.\n */\nexport function columnTypeHasChildren(typeCode) {\n    return typeCode === ColumnTypeCode.STRUCT || typeCode === ColumnTypeCode.MAP;\n}\n/**\n * Determines if a stream count needs to be read for this column.\n * Mirrors the logic in cpp/include/mlt/metadata/type_map.hpp lines 85-122\n */\nexport function hasStreamCount(column) {\n    if (column.type === \"scalarType\") {\n        const scalarCol = column.scalarType;\n        if (scalarCol.type === \"physicalType\") {\n            const physicalType = scalarCol.physicalType;\n            switch (physicalType) {\n                case ScalarType.BOOLEAN:\n                case ScalarType.INT_8:\n                case ScalarType.UINT_8:\n                case ScalarType.INT_32:\n                case ScalarType.UINT_32:\n                case ScalarType.INT_64:\n                case ScalarType.UINT_64:\n                case ScalarType.FLOAT:\n                case ScalarType.DOUBLE:\n                    return false;\n                case ScalarType.STRING:\n                    return true;\n                default:\n                    return false;\n            }\n        }\n        if (scalarCol.type === \"logicalType\") {\n            return false;\n        }\n    }\n    else if (column.type === \"complexType\") {\n        const complexCol = column.complexType;\n        if (complexCol.type === \"physicalType\") {\n            const physicalType = complexCol.physicalType;\n            switch (physicalType) {\n                case ComplexType.GEOMETRY:\n                case ComplexType.STRUCT:\n                case ComplexType.MAP:\n                    return true;\n                default:\n                    return false;\n            }\n        }\n    }\n    console.warn(\"Unexpected column type in hasStreamCount\", column);\n    return false;\n}\nexport function isLogicalIdColumn(column) {\n    return (column.type === \"scalarType\" &&\n        column.scalarType?.type === \"logicalType\" &&\n        column.scalarType.logicalType === LogicalScalarType.ID);\n}\nexport function isGeometryColumn(column) {\n    return (column.type === \"complexType\" &&\n        column.complexType?.type === \"physicalType\" &&\n        column.complexType.physicalType === ComplexType.GEOMETRY);\n}\n/**\n * Maps a scalar type code to a Column with ScalarType.\n * Type codes 10-29 encode scalar types with nullable flag.\n * Even codes are non-nullable, odd codes are nullable.\n */\nfunction mapScalarType(typeCode) {\n    let physicalType;\n    switch (typeCode) {\n        case 10:\n        case 11:\n            physicalType = ScalarType.BOOLEAN;\n            break;\n        case 12:\n        case 13:\n            physicalType = ScalarType.INT_8;\n            break;\n        case 14:\n        case 15:\n            physicalType = ScalarType.UINT_8;\n            break;\n        case 16:\n        case 17:\n            physicalType = ScalarType.INT_32;\n            break;\n        case 18:\n        case 19:\n            physicalType = ScalarType.UINT_32;\n            break;\n        case 20:\n        case 21:\n            physicalType = ScalarType.INT_64;\n            break;\n        case 22:\n        case 23:\n            physicalType = ScalarType.UINT_64;\n            break;\n        case 24:\n        case 25:\n            physicalType = ScalarType.FLOAT;\n            break;\n        case 26:\n        case 27:\n            physicalType = ScalarType.DOUBLE;\n            break;\n        case 28:\n        case 29:\n            physicalType = ScalarType.STRING;\n            break;\n        default:\n            return null;\n    }\n    return {\n        nullable: (typeCode & 1) !== 0,\n        columnScope: ColumnScope.FEATURE,\n        type: \"scalarType\",\n        scalarType: {\n            longID: false,\n            type: \"physicalType\",\n            physicalType,\n        },\n    };\n}\n//# sourceMappingURL=typeMap.js.map", "import { decodeVarintInt32 } from \"../../decoding/integerDecodingUtils\";\nimport { ColumnTypeCode, columnTypeHasChildren, columnTypeHasName, decodeColumnType } from \"./typeMap\";\nconst textDecoder = new TextDecoder();\nconst SUPPORTED_COLUMN_TYPES = \"0-3(ID), 4(GEOMETRY), 10-29(scalars), 30(STRUCT), 31(MAP)\";\nconst SUPPORTED_FIELD_TYPES = \"10-29(scalars), 30(STRUCT), 31(MAP)\";\n/**\n * Decodes a length-prefixed UTF-8 string.\n * Layout: [len: varint32][bytes: len]\n */\nfunction decodeString(src, offset) {\n    const length = decodeVarintInt32(src, offset, 1)[0];\n    if (length === 0) {\n        return \"\";\n    }\n    const start = offset.get();\n    const end = start + length;\n    const view = src.subarray(start, end);\n    offset.add(length);\n    return textDecoder.decode(view);\n}\n/**\n * Converts a Column to a Field.\n * Used when decoding Field metadata which has the same format as Column.\n */\nfunction columnToField(column) {\n    const name = column.name;\n    const nullable = column.nullable;\n    return column.type === \"scalarType\"\n        ? { type: \"scalarField\", scalarField: column.scalarType, name, nullable }\n        : { type: \"complexField\", complexField: column.complexType, name, nullable };\n}\n/**\n * Decodes a Field used as part of complex types (STRUCT children).\n */\nexport function decodeField(src, offset) {\n    const typeCode = decodeVarintInt32(src, offset, 1)[0] >>> 0;\n    const base = typeCode >= ColumnTypeCode.SCALAR_BASE ? decodeColumnType(typeCode) : null;\n    if (!base) {\n        throw new Error(`Unsupported field type code ${typeCode}. Supported: ${SUPPORTED_FIELD_TYPES}`);\n    }\n    // Field type codes (10-30) always carry an explicit name.\n    const column = { ...base, name: decodeString(src, offset) };\n    if (column.type === \"complexType\" && columnTypeHasChildren(typeCode)) {\n        const complexCol = column.complexType;\n        const childCount = decodeVarintInt32(src, offset, 1)[0] >>> 0;\n        complexCol.children = new Array(childCount);\n        for (let i = 0; i < childCount; i++) {\n            complexCol.children[i] = decodeField(src, offset);\n        }\n    }\n    return columnToField(column);\n}\n/**\n * The typeCode encodes the column type, nullable flag, and whether it has name/children.\n */\nfunction decodeColumn(src, offset) {\n    const typeCode = decodeVarintInt32(src, offset, 1)[0] >>> 0;\n    const base = decodeColumnType(typeCode);\n    if (!base) {\n        throw new Error(`Unsupported column type code ${typeCode}. Supported: ${SUPPORTED_COLUMN_TYPES}`);\n    }\n    let name;\n    if (columnTypeHasName(typeCode)) {\n        name = decodeString(src, offset);\n    }\n    else if (typeCode < ColumnTypeCode.GEOMETRY) {\n        name = \"id\";\n    }\n    else if (typeCode === ColumnTypeCode.GEOMETRY) {\n        name = \"geometry\";\n    }\n    else {\n        throw new Error(`Unsupported column type code ${typeCode}. Supported: ${SUPPORTED_COLUMN_TYPES}`);\n    }\n    const column = { ...base, name };\n    if (column.type === \"complexType\" && columnTypeHasChildren(typeCode)) {\n        const childCount = decodeVarintInt32(src, offset, 1)[0] >>> 0;\n        const complexCol = column.complexType;\n        complexCol.children = new Array(childCount);\n        for (let i = 0; i < childCount; i++) {\n            complexCol.children[i] = decodeField(src, offset);\n        }\n    }\n    return column;\n}\n/**\n * Top-level decoder for embedded tileset metadata.\n * Reads exactly ONE FeatureTableSchema from the stream.\n *\n * @param bytes The byte array containing the metadata\n * @param offset The current offset in the byte array (will be advanced)\n */\nexport function decodeEmbeddedTileSetMetadata(bytes, offset) {\n    const meta = {};\n    meta.featureTables = [];\n    const table = {};\n    table.name = decodeString(bytes, offset);\n    if (table.name.length === 0) {\n        throw new Error(\"Missing layer name\");\n    }\n    const extent = decodeVarintInt32(bytes, offset, 1)[0] >>> 0;\n    const columnCount = decodeVarintInt32(bytes, offset, 1)[0] >>> 0;\n    table.columns = new Array(columnCount);\n    for (let j = 0; j < columnCount; j++) {\n        table.columns[j] = decodeColumn(bytes, offset);\n    }\n    meta.featureTables.push(table);\n    return [meta, extent];\n}\n//# sourceMappingURL=embeddedTilesetMetadataDecoder.js.map", "import FeatureTable from \"./vector/featureTable\";\nimport { ScalarType } from \"./metadata/tileset/tilesetMetadata\";\nimport IntWrapper from \"./decoding/intWrapper\";\nimport { decodeStreamMetadata } from \"./metadata/tile/streamMetadataDecoder\";\nimport { VectorType } from \"./vector/vectorType\";\nimport { Int32FlatVector } from \"./vector/flat/int32FlatVector\";\nimport BitVector from \"./vector/flat/bitVector\";\nimport { decodeUnsignedConstInt32Stream, decodeUnsignedConstInt64Stream, decodeUnsignedInt64AsFloat64Stream, decodeUnsignedInt32Stream, decodeUnsignedInt64Stream, decodeSequenceInt32Stream, decodeSequenceInt64Stream, getVectorType, } from \"./decoding/integerStreamDecoder\";\nimport { Int32SequenceVector } from \"./vector/sequence/int32SequenceVector\";\nimport { Int64FlatVector } from \"./vector/flat/int64FlatVector\";\nimport { Int64SequenceVector } from \"./vector/sequence/int64SequenceVector\";\nimport { decodeVarintInt32 } from \"./decoding/integerDecodingUtils\";\nimport { decodeGeometryColumn } from \"./decoding/geometryDecoder\";\nimport { decodePropertyColumn } from \"./decoding/propertyDecoder\";\nimport { Int32ConstVector } from \"./vector/constant/int32ConstVector\";\nimport { Int64ConstVector } from \"./vector/constant/int64ConstVector\";\nimport { decodeBooleanRle } from \"./decoding/decodingUtils\";\nimport { DoubleFlatVector } from \"./vector/flat/doubleFlatVector\";\nimport { decodeEmbeddedTileSetMetadata } from \"./metadata/tileset/embeddedTilesetMetadataDecoder\";\nimport { hasStreamCount, isGeometryColumn, isLogicalIdColumn } from \"./metadata/tileset/typeMap\";\n/**\n * Decodes a tile with embedded metadata (Tag 0x01 format).\n * This is the primary decoder function for MLT tiles.\n *\n * @param tile The tile data to decode (will be decompressed if gzip-compressed)\n * @param geometryScaling Optional geometry scaling parameters\n * @param idWithinMaxSafeInteger If true, limits ID values to JavaScript safe integer range (53 bits)\n */\nexport default function decodeTile(tile, geometryScaling, idWithinMaxSafeInteger = true) {\n    const offset = new IntWrapper(0);\n    const featureTables = [];\n    while (offset.get() < tile.length) {\n        const blockLength = decodeVarintInt32(tile, offset, 1)[0] >>> 0;\n        const blockStart = offset.get();\n        const blockEnd = blockStart + blockLength;\n        if (blockEnd > tile.length) {\n            throw new Error(`Block overruns tile: ${blockEnd} > ${tile.length}`);\n        }\n        const tag = decodeVarintInt32(tile, offset, 1)[0] >>> 0;\n        if (tag !== 1 && tag !== 2) {\n            // Skip unknown block types\n            offset.set(blockEnd);\n            continue;\n        }\n        const [metadata, extent] = decodeEmbeddedTileSetMetadata(tile, offset);\n        const featureTableMetadata = metadata.featureTables[0];\n        let idVector = null;\n        let geometryVector = null;\n        const propertyVectors = [];\n        let numFeatures = 0;\n        for (const columnMetadata of featureTableMetadata.columns) {\n            const columnName = columnMetadata.name;\n            if (isLogicalIdColumn(columnMetadata)) {\n                let nullabilityBuffer = null;\n                // Check column metadata nullable flag, not numStreams (ID columns don't have stream count)\n                if (columnMetadata.nullable) {\n                    const presentStreamMetadata = decodeStreamMetadata(tile, offset);\n                    const streamDataStart = offset.get();\n                    const values = decodeBooleanRle(tile, presentStreamMetadata.numValues, presentStreamMetadata.byteLength, offset);\n                    offset.set(streamDataStart + presentStreamMetadata.byteLength);\n                    nullabilityBuffer = new BitVector(values, presentStreamMetadata.numValues);\n                }\n                const idDataStreamMetadata = decodeStreamMetadata(tile, offset);\n                // decompressedCount is the count WITHOUT nulls, but we may have nulls\n                numFeatures = nullabilityBuffer ? nullabilityBuffer.size() : idDataStreamMetadata.decompressedCount;\n                idVector = decodeIdColumn(tile, columnMetadata, offset, columnName, idDataStreamMetadata, nullabilityBuffer ?? numFeatures, idWithinMaxSafeInteger);\n            }\n            else if (isGeometryColumn(columnMetadata)) {\n                const numStreams = decodeVarintInt32(tile, offset, 1)[0];\n                // If no ID column, get numFeatures from geometry type stream metadata\n                if (numFeatures === 0) {\n                    const savedOffset = offset.get();\n                    const geometryTypeMetadata = decodeStreamMetadata(tile, offset);\n                    numFeatures = geometryTypeMetadata.decompressedCount;\n                    offset.set(savedOffset); // Reset to re-read in decodeGeometryColumn\n                }\n                if (geometryScaling) {\n                    geometryScaling.scale = geometryScaling.extent / extent;\n                }\n                geometryVector = decodeGeometryColumn(tile, numStreams, offset, numFeatures, geometryScaling);\n            }\n            else {\n                const columnHasStreamCount = hasStreamCount(columnMetadata);\n                const numStreams = columnHasStreamCount ? decodeVarintInt32(tile, offset, 1)[0] : 1;\n                if (numStreams === 0) {\n                    continue;\n                }\n                const propertyVector = decodePropertyColumn(tile, offset, columnMetadata, numStreams, numFeatures, undefined);\n                if (propertyVector) {\n                    if (Array.isArray(propertyVector)) {\n                        for (const property of propertyVector) {\n                            propertyVectors.push(property);\n                        }\n                    }\n                    else {\n                        propertyVectors.push(propertyVector);\n                    }\n                }\n            }\n        }\n        const featureTable = new FeatureTable(featureTableMetadata.name, geometryVector, idVector, propertyVectors, extent);\n        featureTables.push(featureTable);\n        offset.set(blockEnd);\n    }\n    return featureTables;\n}\nfunction decodeIdColumn(tile, columnMetadata, offset, columnName, idDataStreamMetadata, sizeOrNullabilityBuffer, idWithinMaxSafeInteger = false) {\n    const idDataType = columnMetadata.scalarType?.longID ? ScalarType.UINT_64 : ScalarType.UINT_32;\n    const nullabilityBuffer = typeof sizeOrNullabilityBuffer === \"number\" ? undefined : sizeOrNullabilityBuffer;\n    const vectorType = getVectorType(idDataStreamMetadata, sizeOrNullabilityBuffer, tile, offset, idDataType === ScalarType.UINT_64 ? \"int64\" : \"int32\");\n    if (idDataType === ScalarType.UINT_32) {\n        switch (vectorType) {\n            case VectorType.FLAT: {\n                const id = decodeUnsignedInt32Stream(tile, offset, idDataStreamMetadata, undefined, nullabilityBuffer);\n                return new Int32FlatVector(columnName, id, sizeOrNullabilityBuffer);\n            }\n            case VectorType.SEQUENCE: {\n                const id = decodeSequenceInt32Stream(tile, offset, idDataStreamMetadata);\n                return new Int32SequenceVector(columnName, id[0], id[1], idDataStreamMetadata.numRleValues, false);\n            }\n            case VectorType.CONST: {\n                const id = decodeUnsignedConstInt32Stream(tile, offset, idDataStreamMetadata);\n                return new Int32ConstVector(columnName, id, sizeOrNullabilityBuffer, false);\n            }\n        }\n    }\n    switch (vectorType) {\n        case VectorType.FLAT: {\n            if (idWithinMaxSafeInteger) {\n                const id = decodeUnsignedInt64AsFloat64Stream(tile, offset, idDataStreamMetadata, nullabilityBuffer);\n                return new DoubleFlatVector(columnName, id, sizeOrNullabilityBuffer);\n            }\n            const id = decodeUnsignedInt64Stream(tile, offset, idDataStreamMetadata, nullabilityBuffer);\n            return new Int64FlatVector(columnName, id, sizeOrNullabilityBuffer);\n        }\n        case VectorType.SEQUENCE: {\n            const id = decodeSequenceInt64Stream(tile, offset, idDataStreamMetadata);\n            return new Int64SequenceVector(columnName, id[0], id[1], idDataStreamMetadata.numRleValues, false);\n        }\n        case VectorType.CONST: {\n            const id = decodeUnsignedConstInt64Stream(tile, offset, idDataStreamMetadata);\n            return new Int64ConstVector(columnName, id, sizeOrNullabilityBuffer, false);\n        }\n    }\n    throw new Error(\"Vector type not supported for id column.\");\n}\n//# sourceMappingURL=mltDecoder.js.map", "import { MASKS, DEFAULT_PAGE_SIZE, BLOCK_SIZE, greatestMultiple, roundUpToMultipleOf32, normalizePageSize, } from \"../decoding/fastPforShared\";\nconst EXCEPTION_OVERHEAD_BITS = 8;\nconst MAX_BIT_WIDTH = 32;\nconst BIT_WIDTH_SLOTS = MAX_BIT_WIDTH + 1;\nconst PAGE_SIZE = normalizePageSize(DEFAULT_PAGE_SIZE);\nconst INITIAL_PACKED_BUFFER_SIZE_WORDS = (PAGE_SIZE / 32) * 4;\nconst BYTE_CONTAINER_SIZE = ((3 * PAGE_SIZE) / BLOCK_SIZE + PAGE_SIZE) | 0;\nfunction requiredBits(value) {\n    return 32 - Math.clz32(value >>> 0);\n}\nfunction ensureInt32Capacity(buffer, requiredLength) {\n    if (requiredLength <= buffer.length)\n        return buffer;\n    let newLength = buffer.length === 0 ? 1 : buffer.length;\n    while (newLength < requiredLength) {\n        newLength *= 2;\n    }\n    const next = new Uint32Array(newLength);\n    next.set(buffer);\n    return next;\n}\nfunction ensureUint8Capacity(buffer, requiredLength) {\n    if (requiredLength <= buffer.length)\n        return buffer;\n    let newLength = buffer.length === 0 ? 1 : buffer.length;\n    while (newLength < requiredLength) {\n        newLength *= 2;\n    }\n    const next = new Uint8Array(newLength);\n    next.set(buffer);\n    return next;\n}\nexport function fastPack32(inValues, inPos, out, outPos, bitWidth) {\n    if (bitWidth === 0)\n        return;\n    if (bitWidth === 32) {\n        out.set(inValues.subarray(inPos, inPos + 32), outPos);\n        return;\n    }\n    const mask = MASKS[bitWidth] >>> 0;\n    let outputWordIndex = outPos;\n    let bitOffset = 0;\n    let currentWord = 0;\n    for (let i = 0; i < 32; i++) {\n        const value = (inValues[inPos + i] >>> 0) & mask;\n        if (bitOffset + bitWidth <= 32) {\n            currentWord |= value << bitOffset;\n            bitOffset += bitWidth;\n            if (bitOffset === 32) {\n                out[outputWordIndex++] = currentWord | 0;\n                bitOffset = 0;\n                currentWord = 0;\n            }\n        }\n        else {\n            const lowBits = 32 - bitOffset;\n            const lowMask = MASKS[lowBits] >>> 0;\n            currentWord |= (value & lowMask) << bitOffset;\n            out[outputWordIndex++] = currentWord | 0;\n            currentWord = value >>> lowBits;\n            bitOffset = bitWidth - lowBits;\n        }\n    }\n}\nexport function createFastPforEncoderWorkspace() {\n    const dataToBePacked = new Array(BIT_WIDTH_SLOTS);\n    for (let k = 1; k < BIT_WIDTH_SLOTS; k++) {\n        dataToBePacked[k] = new Uint32Array(INITIAL_PACKED_BUFFER_SIZE_WORDS);\n    }\n    return {\n        dataToBePacked,\n        dataPointers: new Int32Array(BIT_WIDTH_SLOTS),\n        byteContainer: new Uint8Array(BYTE_CONTAINER_SIZE),\n        bitWidthFrequencies: new Int32Array(BIT_WIDTH_SLOTS),\n        bestBitWidthPlan: new Int32Array(3),\n    };\n}\nfunction computeBestBitWidthPlan(inValues, pos, workspace) {\n    const bitWidthFrequencies = workspace.bitWidthFrequencies;\n    const bestBitWidthPlan = workspace.bestBitWidthPlan;\n    bitWidthFrequencies.fill(0);\n    for (let k = pos, kEnd = pos + BLOCK_SIZE; k < kEnd; k++) {\n        bitWidthFrequencies[requiredBits(inValues[k])]++;\n    }\n    let maxBitWidth = MAX_BIT_WIDTH;\n    while (bitWidthFrequencies[maxBitWidth] === 0)\n        maxBitWidth--;\n    let bestBitWidth = maxBitWidth;\n    let bestCost = maxBitWidth * BLOCK_SIZE;\n    let exceptionCount = 0;\n    let bestExceptionCount = exceptionCount;\n    for (let candidateBitWidth = maxBitWidth - 1; candidateBitWidth >= 0; candidateBitWidth--) {\n        exceptionCount += bitWidthFrequencies[candidateBitWidth + 1];\n        if (exceptionCount === BLOCK_SIZE)\n            break;\n        let candidateCost = exceptionCount * EXCEPTION_OVERHEAD_BITS +\n            exceptionCount * (maxBitWidth - candidateBitWidth) +\n            candidateBitWidth * BLOCK_SIZE +\n            8;\n        if (maxBitWidth - candidateBitWidth === 1)\n            candidateCost -= exceptionCount;\n        if (candidateCost < bestCost) {\n            bestCost = candidateCost;\n            bestBitWidth = candidateBitWidth;\n            bestExceptionCount = exceptionCount;\n        }\n    }\n    bestBitWidthPlan[0] = bestBitWidth;\n    bestBitWidthPlan[1] = bestExceptionCount;\n    bestBitWidthPlan[2] = maxBitWidth;\n}\nfunction writeByte(workspace, byteContainerPos, byteValue) {\n    if (byteContainerPos >= workspace.byteContainer.length) {\n        workspace.byteContainer = ensureUint8Capacity(workspace.byteContainer, byteContainerPos + 1);\n    }\n    workspace.byteContainer[byteContainerPos] = byteValue & 0xff;\n    return byteContainerPos + 1;\n}\nfunction ensureExceptionValuesCapacity(dataToBePacked, dataPointers, exceptionBitWidth, exceptionCount) {\n    if (exceptionBitWidth === 1)\n        return;\n    const needed = dataPointers[exceptionBitWidth] + exceptionCount;\n    const currentExceptionValues = dataToBePacked[exceptionBitWidth];\n    if (!currentExceptionValues || needed >= currentExceptionValues.length) {\n        let newSize = 2 * needed;\n        newSize = roundUpToMultipleOf32(newSize);\n        const next = new Uint32Array(newSize);\n        if (currentExceptionValues)\n            next.set(currentExceptionValues);\n        dataToBePacked[exceptionBitWidth] = next;\n    }\n}\nfunction writeBlockHeader(workspace, byteContainerPos, bitWidth, exceptionCount, maxBitWidth) {\n    byteContainerPos = writeByte(workspace, byteContainerPos, bitWidth);\n    byteContainerPos = writeByte(workspace, byteContainerPos, exceptionCount);\n    if (exceptionCount > 0) {\n        byteContainerPos = writeByte(workspace, byteContainerPos, maxBitWidth);\n    }\n    return byteContainerPos;\n}\nfunction recordBlockExceptions(workspace, inValues, blockPos, bitWidth, exceptionCount, exceptionBitWidth, byteContainerPos) {\n    if (exceptionCount === 0)\n        return byteContainerPos;\n    const dataToBePacked = workspace.dataToBePacked;\n    const dataPointers = workspace.dataPointers;\n    ensureExceptionValuesCapacity(dataToBePacked, dataPointers, exceptionBitWidth, exceptionCount);\n    for (let k = 0; k < BLOCK_SIZE; k++) {\n        const value = inValues[blockPos + k] >>> 0;\n        if (value >>> bitWidth !== 0) {\n            byteContainerPos = writeByte(workspace, byteContainerPos, k);\n            if (exceptionBitWidth !== 1) {\n                const exceptionValues = dataToBePacked[exceptionBitWidth];\n                exceptionValues[dataPointers[exceptionBitWidth]++] = (value >>> bitWidth) | 0;\n            }\n        }\n    }\n    return byteContainerPos;\n}\nfunction packBlock(inValues, blockPos, bitWidth, state) {\n    for (let k = 0; k < BLOCK_SIZE; k += 32) {\n        state.out = ensureInt32Capacity(state.out, state.outPos + bitWidth);\n        fastPack32(inValues, blockPos + k, state.out, state.outPos, bitWidth);\n        state.outPos += bitWidth;\n    }\n}\nfunction padByteContainerToInt32(workspace, byteContainerPos) {\n    while ((byteContainerPos & 3) !== 0) {\n        byteContainerPos = writeByte(workspace, byteContainerPos, 0);\n    }\n    return byteContainerPos;\n}\nfunction writeByteContainerInts(workspace, state, byteContainerPos) {\n    const howManyInts = byteContainerPos / 4;\n    state.out = ensureInt32Capacity(state.out, state.outPos + howManyInts);\n    const byteContainer = workspace.byteContainer;\n    for (let i = 0; i < howManyInts; i++) {\n        const base = i * 4;\n        const packedWord = byteContainer[base] |\n            (byteContainer[base + 1] << 8) |\n            (byteContainer[base + 2] << 16) |\n            (byteContainer[base + 3] << 24) |\n            0;\n        state.out[state.outPos + i] = packedWord;\n    }\n    state.outPos += howManyInts;\n}\nfunction computeExceptionBitmap(dataPointers) {\n    let bitmap = 0;\n    for (let k = 2; k <= MAX_BIT_WIDTH; k++) {\n        if (dataPointers[k] !== 0) {\n            bitmap |= k === MAX_BIT_WIDTH ? 0x80000000 : 1 << (k - 1);\n        }\n    }\n    return bitmap;\n}\nfunction writeExceptionStreams(workspace, state) {\n    const dataPointers = workspace.dataPointers;\n    const dataToBePacked = workspace.dataToBePacked;\n    const bitmap = computeExceptionBitmap(dataPointers);\n    state.out = ensureInt32Capacity(state.out, state.outPos + 1);\n    state.out[state.outPos++] = bitmap;\n    for (let k = 2; k <= MAX_BIT_WIDTH; k++) {\n        const size = dataPointers[k];\n        if (size !== 0) {\n            state.out = ensureInt32Capacity(state.out, state.outPos + 1);\n            state.out[state.outPos++] = size | 0;\n            let j = 0;\n            for (; j < size; j += 32) {\n                const exceptionValues = dataToBePacked[k];\n                state.out = ensureInt32Capacity(state.out, state.outPos + k);\n                fastPack32(exceptionValues, j, state.out, state.outPos, k);\n                state.outPos += k;\n            }\n            const overflow = j - size;\n            state.outPos -= (overflow * k) >>> 5;\n        }\n    }\n}\nfunction encodePage(inValues, thisSize, state, workspace) {\n    const headerPos = state.outPos;\n    state.out = ensureInt32Capacity(state.out, headerPos + 1);\n    state.outPos = (state.outPos + 1) | 0;\n    const dataPointers = workspace.dataPointers;\n    dataPointers.fill(0);\n    let byteContainerPos = 0;\n    let tmpInPos = state.inPos;\n    const finalInPos = tmpInPos + thisSize - BLOCK_SIZE;\n    for (; tmpInPos <= finalInPos; tmpInPos += BLOCK_SIZE) {\n        computeBestBitWidthPlan(inValues, tmpInPos, workspace);\n        const bestBitWidthPlan = workspace.bestBitWidthPlan;\n        const bitWidth = bestBitWidthPlan[0];\n        const exceptionCount = bestBitWidthPlan[1];\n        const maxBitWidth = bestBitWidthPlan[2];\n        const exceptionBitWidth = exceptionCount > 0 ? maxBitWidth - bitWidth : 0;\n        byteContainerPos = writeBlockHeader(workspace, byteContainerPos, bitWidth, exceptionCount, maxBitWidth);\n        byteContainerPos = recordBlockExceptions(workspace, inValues, tmpInPos, bitWidth, exceptionCount, exceptionBitWidth, byteContainerPos);\n        packBlock(inValues, tmpInPos, bitWidth, state);\n    }\n    const pageEndOutPos = state.outPos;\n    state.inPos = tmpInPos;\n    state.out[headerPos] = (pageEndOutPos - headerPos) | 0;\n    const byteSize = byteContainerPos;\n    byteContainerPos = padByteContainerToInt32(workspace, byteContainerPos);\n    state.out = ensureInt32Capacity(state.out, state.outPos + 1);\n    state.out[state.outPos++] = byteSize | 0;\n    writeByteContainerInts(workspace, state, byteContainerPos);\n    writeExceptionStreams(workspace, state);\n}\nfunction encodeAlignedPages(inValues, inLength, state, workspace) {\n    const alignedLength = greatestMultiple(inLength, BLOCK_SIZE);\n    const finalInPos = state.inPos + alignedLength;\n    while (state.inPos !== finalInPos) {\n        const thisSize = Math.min(PAGE_SIZE, finalInPos - state.inPos);\n        encodePage(inValues, thisSize, state, workspace);\n    }\n}\nfunction encode(inValues, inLength, state, workspace) {\n    const alignedLength = greatestMultiple(inLength, BLOCK_SIZE);\n    state.out = ensureInt32Capacity(state.out, state.outPos + 1);\n    state.out[state.outPos++] = alignedLength;\n    if (alignedLength === 0)\n        return;\n    encodeAlignedPages(inValues, alignedLength, state, workspace);\n}\n/**\n * VByte encoding for FastPFOR tail values (MSB=1 terminator).\n * Note: Inverts standard Protobuf Varint (MSB=0 terminator), so we cannot reuse generic methods.\n */\nfunction encodeVByte(inValues, inLength, state, workspace) {\n    if (inLength === 0)\n        return;\n    const requiredBytes = inLength * 5 + 3;\n    workspace.byteContainer = ensureUint8Capacity(workspace.byteContainer, requiredBytes);\n    const start = state.inPos;\n    let bytePos = 0;\n    for (let k = start; k < start + inLength; k++) {\n        let value = inValues[k] >>> 0;\n        while (value >= 0x80) {\n            workspace.byteContainer[bytePos++] = value & 0x7f;\n            value >>>= 7;\n        }\n        workspace.byteContainer[bytePos++] = (value | 0x80) & 0xff;\n    }\n    while ((bytePos & 3) !== 0)\n        workspace.byteContainer[bytePos++] = 0;\n    const intsToWrite = bytePos / 4;\n    state.out = ensureInt32Capacity(state.out, state.outPos + intsToWrite);\n    let outIdx = state.outPos;\n    for (let i = 0; i < bytePos; i += 4) {\n        const packedWord = workspace.byteContainer[i] |\n            (workspace.byteContainer[i + 1] << 8) |\n            (workspace.byteContainer[i + 2] << 16) |\n            (workspace.byteContainer[i + 3] << 24) |\n            0;\n        state.out[outIdx++] = packedWord;\n    }\n    state.outPos = outIdx;\n    state.inPos = (state.inPos + inLength) | 0;\n}\n/**\n * Encodes an int32 stream using the FastPFOR wire format (pages + VByte tail).\n */\nexport function encodeFastPforInt32WithWorkspace(values, workspace) {\n    const state = { inPos: 0, outPos: 0, out: new Uint32Array(values.length + 1024) };\n    encode(values, values.length, state, workspace);\n    const remaining = values.length - state.inPos;\n    encodeVByte(values, remaining, state, workspace);\n    return state.out.subarray(0, state.outPos);\n}\n//# sourceMappingURL=fastPforEncoder.js.map", "import Point from '@mapbox/point-geometry';\nimport {type FeatureTable, decodeTile, type Feature as MLTFeature, GEOMETRY_TYPE} from '@maplibre/mlt';\n\nimport type {VectorTileFeatureLike, VectorTileLayerLike, VectorTileLike} from '@maplibre/vt-pbf';\n\nclass MLTVectorTileFeature implements VectorTileFeatureLike {\n    _featureData: MLTFeature;\n    properties: {[_: string]: any};\n    type: VectorTileFeatureLike['type'];\n    extent: VectorTileFeatureLike['extent'];\n    id: VectorTileFeatureLike['id'];\n\n    constructor(feature: MLTFeature, extent: number) {\n        this._featureData = feature;\n        this.properties = this._featureData.properties || {};\n        switch (this._featureData.geometry?.type) {\n            case GEOMETRY_TYPE.POINT:\n            case GEOMETRY_TYPE.MULTIPOINT:\n                this.type = 1;\n                break;\n            case GEOMETRY_TYPE.LINESTRING:\n            case GEOMETRY_TYPE.MULTILINESTRING:\n                this.type = 2;\n                break;\n            case GEOMETRY_TYPE.POLYGON:\n            case GEOMETRY_TYPE.MULTIPOLYGON:\n                this.type = 3;\n                break;\n            default:\n                this.type = 0;\n        };\n        this.extent = extent;\n        this.id = Number(this._featureData.id);\n    }\n\n    loadGeometry(): Point[][] {\n        const points: Point[][] = [];\n        for (const ring of this._featureData.geometry.coordinates) {\n            const pointRing: Point[] = [];\n            for (const coord of ring) {\n                pointRing.push(new Point(coord.x, coord.y));\n            }\n            points.push(pointRing);\n        }\n        return points;\n    }\n}\n\nclass MLTVectorTileLayer implements VectorTileLayerLike {\n    featureTable: FeatureTable;\n    name: string;\n    length: number;\n    version: number;\n    extent: number;\n    features: MLTFeature[] = [];\n    \n    constructor(featureTable: FeatureTable) {\n        this.featureTable = featureTable;\n        this.name = featureTable.name;\n        this.extent = featureTable.extent;\n        this.version = 2;\n        this.features = featureTable.getFeatures();\n        this.length = this.features.length;\n    }\n\n    feature(i: number): VectorTileFeatureLike {\n        return new MLTVectorTileFeature(this.features[i], this.extent);\n    }\n}\n\nexport class MLTVectorTile implements VectorTileLike {\n    layers: Record<string, VectorTileLayerLike> = {};\n\n    constructor(buffer: ArrayBuffer) {\n        const features = decodeTile(new Uint8Array(buffer));\n        this.layers = features.reduce((acc, f) => ({...acc, [f.name]: new MLTVectorTileLayer(f)}), {});\n    }\n}\n", "import {type VectorTileFeatureLike, type VectorTileLayerLike, GEOJSON_TILE_LAYER_NAME} from '@maplibre/vt-pbf';\nimport {loadGeometry} from './load_geometry.ts';\nimport {toEvaluationFeature} from './evaluation_feature.ts';\nimport {EXTENT} from './extent.ts';\nimport {featureFilter} from '@maplibre/maplibre-gl-style-spec';\nimport {TransferableGridIndex} from '../util/transferable_grid_index.ts';\nimport {DictionaryCoder} from '../util/dictionary_coder.ts';\nimport {PbfReader} from 'pbf';\nimport {GeoJSONFeature} from '../util/vectortile_to_geojson.ts';\nimport {mapObject, extend} from '../util/util.ts';\nimport {register} from '../util/web_worker_transfer.ts';\nimport {EvaluationParameters} from '../style/evaluation_parameters.ts';\nimport {polygonIntersectsBox} from '../util/intersection_tests.ts';\nimport {PossiblyEvaluated} from '../style/properties.ts';\nimport {FeatureIndexArray} from './array_types.g.ts';\nimport {MLTVectorTile} from '../source/vector_tile_mlt.ts';\nimport {Bounds} from '../geo/bounds.ts';\nimport {VectorTile} from '@mapbox/vector-tile';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\nimport type {SourceFeatureState} from '../source/source_state.ts';\nimport type {PossiblyEvaluatedPropertyValue} from '../style/properties.ts';\nimport type {mat4} from 'gl-matrix';\nimport type {MapGeoJSONFeature} from '../util/vectortile_to_geojson.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {Feature, FeatureFilter, FeatureState, FilterSpecification, PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {IReadonlyTransform, GetElevation, WorldCoordinateHelper} from '../geo/transform_interface.ts';\nimport type {TileEncoding} from '../source/worker_source.ts';\n\nexport {GEOJSON_TILE_LAYER_NAME};\n\ntype QueryParameters = {\n    scale: number;\n    pixelPosMatrix: mat4;\n    transform: IReadonlyTransform;\n    tileSize: number;\n    queryGeometry: Point[];\n    cameraQueryGeometry: Point[];\n    queryPadding: number;\n    getElevation: GetElevation | undefined;\n    params: {\n        filter?: FilterSpecification;\n        layers?: Set<string> | null;\n        availableImages?: string[];\n        globalState?: Record<string, any>;\n    };\n};\n\nexport type QueryResults = {\n    [_: string]: QueryResultsItem[];\n};\n\nexport type QueryResultsItem = {\n    featureIndex: number;\n    feature: GeoJSONFeature;\n    intersectionZ?: boolean | number;\n};\n\n/**\n * An in memory index class to allow fast interaction with features\n */\nexport class FeatureIndex {\n    tileID: OverscaledTileID;\n    x: number;\n    y: number;\n    z: number;\n    grid: TransferableGridIndex;\n    grid3D: TransferableGridIndex;\n    featureIndexArray: FeatureIndexArray;\n    promoteId?: PromoteIdSpecification;\n    encoding: TileEncoding;\n    rawTileData: ArrayBuffer;\n    bucketLayerIDs: string[][];\n\n    vtLayers: {[_: string]: VectorTileLayerLike};\n    sourceLayerCoder: DictionaryCoder;\n\n    constructor(tileID: OverscaledTileID, promoteId?: PromoteIdSpecification | null) {\n        this.tileID = tileID;\n        this.x = tileID.canonical.x;\n        this.y = tileID.canonical.y;\n        this.z = tileID.canonical.z;\n        this.grid = new TransferableGridIndex(EXTENT, 16, 0);\n        this.grid3D = new TransferableGridIndex(EXTENT, 16, 0);\n        this.featureIndexArray = new FeatureIndexArray();\n        this.promoteId = promoteId;\n    }\n\n    insert(feature: VectorTileFeatureLike, geometry: Point[][], featureIndex: number, sourceLayerIndex: number, bucketIndex: number, is3D?: boolean): void {\n        const key = this.featureIndexArray.length;\n        this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex);\n\n        const grid = is3D ? this.grid3D : this.grid;\n\n        for (const ring of geometry) {\n\n            const bbox = [Infinity, Infinity, -Infinity, -Infinity];\n            for (const p of ring) {\n                bbox[0] = Math.min(bbox[0], p.x);\n                bbox[1] = Math.min(bbox[1], p.y);\n                bbox[2] = Math.max(bbox[2], p.x);\n                bbox[3] = Math.max(bbox[3], p.y);\n            }\n\n            if (bbox[0] < EXTENT &&\n                bbox[1] < EXTENT &&\n                bbox[2] >= 0 &&\n                bbox[3] >= 0) {\n                grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);\n            }\n        }\n    }\n\n    loadVTLayers(): {[_: string]: VectorTileLayerLike} {\n        if (!this.vtLayers) {\n            switch (this.encoding) {\n                case 'mlt':\n                    this.vtLayers = new MLTVectorTile(this.rawTileData).layers;\n                    break;\n                case 'mvt':\n                default:\n                    this.vtLayers = new VectorTile(new PbfReader(this.rawTileData)).layers;\n            }\n            this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : [GEOJSON_TILE_LAYER_NAME]);\n        }\n        return this.vtLayers;\n    }\n\n    // Finds non-symbol features in this tile at a particular position.\n    query(\n        args: QueryParameters,\n        styleLayers: {[_: string]: StyleLayer},\n        serializedLayers: {[_: string]: any},\n        sourceFeatureState: SourceFeatureState\n    ): QueryResults {\n        this.loadVTLayers();\n\n        const params = args.params;\n        const pixelsToTileUnits = EXTENT / args.tileSize / args.scale;\n        const filter = featureFilter(params.filter, 'queryRenderedFeatures filter', params.globalState);\n\n        const queryGeometry = args.queryGeometry;\n        const queryPadding = args.queryPadding * pixelsToTileUnits;\n\n        const bounds = Bounds.fromPoints(queryGeometry);\n        const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding);\n\n        const cameraBounds = Bounds.fromPoints(args.cameraQueryGeometry).expandBy(queryPadding);\n        const matching3D = this.grid3D.query(\n            cameraBounds.minX, cameraBounds.minY, cameraBounds.maxX, cameraBounds.maxY,\n            (bx1, by1, bx2, by2) => {\n                return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding);\n            });\n\n        for (const key of matching3D) {\n            matching.push(key);\n        }\n\n        matching.sort(topDownFeatureComparator);\n\n        const result: QueryResults = {};\n        let previousIndex;\n        for (const index of matching) {\n\n            // don't check the same feature more than once\n            if (index === previousIndex) continue;\n            previousIndex = index;\n\n            const match = this.featureIndexArray.get(index);\n            let featureGeometry = null;\n            this.loadMatchingFeature(\n                result,\n                match.bucketIndex,\n                match.sourceLayerIndex,\n                match.featureIndex,\n                filter,\n                params.layers,\n                params.availableImages,\n                styleLayers,\n                serializedLayers,\n                args.transform.worldCoordinateHelper,\n                sourceFeatureState,\n                (feature: VectorTileFeatureLike, styleLayer: StyleLayer, featureState: FeatureState) => {\n                    featureGeometry ||= loadGeometry(feature);\n\n                    return styleLayer.queryIntersectsFeature({\n                        queryGeometry,\n                        feature,\n                        featureState,\n                        geometry: featureGeometry,\n                        zoom: this.z,\n                        transform: args.transform,\n                        pixelsToTileUnits,\n                        pixelPosMatrix: args.pixelPosMatrix,\n                        unwrappedTileID: this.tileID.toUnwrapped(),\n                        getElevation: args.getElevation\n                    });\n                }\n            );\n        }\n\n        return result;\n    }\n\n    loadMatchingFeature(\n        result: QueryResults,\n        bucketIndex: number,\n        sourceLayerIndex: number,\n        featureIndex: number,\n        filter: FeatureFilter,\n        filterLayerIDs: Set<string> | undefined,\n        availableImages: string[],\n        styleLayers: {[_: string]: StyleLayer},\n        serializedLayers: {[_: string]: any},\n        worldCoordinateHelper: WorldCoordinateHelper,\n        sourceFeatureState?: SourceFeatureState,\n        intersectionTest?: (\n            feature: VectorTileFeatureLike,\n            styleLayer: StyleLayer,\n            featureState: any,\n            id: string | number | void\n        ) => boolean | number): void {\n\n        const layerIDs = this.bucketLayerIDs[bucketIndex];\n        if (filterLayerIDs && !layerIDs.some(id => filterLayerIDs.has(id)))\n            return;\n\n        const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);\n        const sourceLayer = this.vtLayers[sourceLayerName];\n        const feature = sourceLayer.feature(featureIndex);\n\n        if (filter.needGeometry) {\n            const evaluationFeature = toEvaluationFeature(feature, true);\n            if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {\n                return;\n            }\n        } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n            return;\n        }\n\n        const id = this.getId(feature, sourceLayerName);\n\n        for (const layerID of layerIDs) {\n\n            if (filterLayerIDs && !filterLayerIDs.has(layerID)) {\n                continue;\n            }\n\n            const styleLayer = styleLayers[layerID];\n\n            if (!styleLayer) continue;\n\n            let featureState = {};\n            if (id && sourceFeatureState) {\n                // `feature-state` expression evaluation requires feature state to be available\n                featureState = sourceFeatureState.getState(styleLayer.sourceLayer || GEOJSON_TILE_LAYER_NAME, id);\n            }\n\n            const serializedLayer = extend({}, serializedLayers[layerID]);\n\n            serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages);\n            serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages);\n\n            const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState);\n            if (!intersectionZ) {\n                // Only applied for non-symbol features\n                continue;\n            }\n\n            const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id, worldCoordinateHelper) as MapGeoJSONFeature;\n            geojsonFeature.layer = serializedLayer;\n            let layerResult = result[layerID];\n            if (layerResult === undefined) {\n                layerResult = result[layerID] = [];\n            }\n            layerResult.push({featureIndex, feature: geojsonFeature, intersectionZ});\n        }\n    }\n\n    // Given a set of symbol indexes that have already been looked up,\n    // return a matching set of GeoJSONFeatures\n    lookupSymbolFeatures(symbolFeatureIndexes: number[],\n        serializedLayers: {[_: string]: StyleLayer},\n        bucketIndex: number,\n        sourceLayerIndex: number,\n        filterParams: {\n            filterSpec: FilterSpecification;\n            globalState: Record<string, any>;\n            worldCoordinateHelper: WorldCoordinateHelper;\n        },\n        filterLayerIDs: Set<string> | null,\n        availableImages: string[],\n        styleLayers: {[_: string]: StyleLayer}): QueryResults {\n        const result: QueryResults = {};\n        this.loadVTLayers();\n\n        const filter = featureFilter(filterParams.filterSpec, 'queryRenderedFeatures symbol filter', filterParams.globalState);\n\n        for (const symbolFeatureIndex of symbolFeatureIndexes) {\n            this.loadMatchingFeature(\n                result,\n                bucketIndex,\n                sourceLayerIndex,\n                symbolFeatureIndex,\n                filter,\n                filterLayerIDs,\n                availableImages,\n                styleLayers,\n                serializedLayers,\n                filterParams.worldCoordinateHelper\n            );\n\n        }\n        return result;\n    }\n\n    hasLayer(id: string): boolean {\n        for (const layerIDs of this.bucketLayerIDs) {\n            for (const layerID of layerIDs) {\n                if (id === layerID) return true;\n            }\n        }\n\n        return false;\n    }\n\n    getId(feature: VectorTileFeatureLike, sourceLayerId: string): string | number {\n        let id: string | number = feature.id;\n        if (this.promoteId) {\n            const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId];\n            id = feature.properties[propName] as string | number;\n            if (typeof id === 'boolean') id = Number(id);\n\n            // When cluster is true, the id is the cluster_id even though promoteId is set\n            if (id === undefined && feature.properties?.cluster && this.promoteId) {\n                id = Number(feature.properties.cluster_id);\n            }\n        }\n        return id;\n    }\n}\n\nregister(\n    'FeatureIndex',\n    FeatureIndex,\n    {omit: ['rawTileData', 'sourceLayerCoder']}\n);\n\n/**\n * Whether a possibly-evaluated property still has to be evaluated against a feature, as a\n * data-driven one does.\n *\n * A data-constant property is already the value it will be drawn with, and that value is often a\n * primitive -- `'map'` for an alignment, a number for an opacity -- which the `in` operator throws\n * on, so it is not reached for until the value is known to be an object.\n */\nfunction needsEvaluating(value: unknown): value is PossiblyEvaluatedPropertyValue<unknown> {\n    return typeof value === 'object' && value !== null && 'evaluate' in value;\n}\n\n/**\n * Evaluates a serialized layer's paint or layout properties against one feature, so that a queried\n * feature reports the values it was actually drawn with.\n *\n * A property the layer does not carry as a possibly-evaluated value, or one that is already a plain\n * value, is passed through as it is.\n */\n\nfunction evaluateProperties<Props, PossiblyEvaluatedProps>(\n    serializedProperties: Record<string, unknown>,\n    styleLayerProperties: PossiblyEvaluated<Props, PossiblyEvaluatedProps> | unknown,\n    feature: Feature,\n    featureState: FeatureState,\n    availableImages: string[]\n): Record<string, unknown> {\n    return mapObject(serializedProperties, (_property, key) => {\n        const value = styleLayerProperties instanceof PossiblyEvaluated ?\n            styleLayerProperties.get(key as keyof PossiblyEvaluatedProps) :\n            null;\n        return needsEvaluating(value) ? value.evaluate(feature, featureState, undefined, availableImages) : value;\n    });\n}\n\nfunction topDownFeatureComparator(a: number, b: number) {\n    return b - a;\n}\n", "/**\n * The possible option of the plugin's status\n *\n * @deprecated Right-to-left text is drawn without a plugin, so this describes only a plugin set\n * through the deprecated {@link setRTLTextPlugin}.\n *\n * `unavailable`: Not loaded.\n *\n * `deferred`: The plugin URL has been specified, but loading has been deferred.\n *\n * `requested`: at least one tile needs RTL to render, but the plugin has not been set\n *\n * `loading`: RTL is in the process of being loaded by worker.\n *\n * `loaded`: The plugin is now loaded\n *\n *  `error`: The plugin failed to load\n */\nexport type RTLPluginStatus =\n                'unavailable' |\n                'deferred' |\n                'requested' |\n                'loading' |\n                'loaded' |\n                'error';\n\n/**\n * The RTL plugin state\n *\n * @deprecated Right-to-left text is drawn without a plugin, so this describes only a plugin set\n * through the deprecated {@link setRTLTextPlugin}.\n */\nexport type PluginState = {\n    pluginStatus: RTLPluginStatus;\n    pluginURL: string;\n};\n\n/**\n * Fired once a plugin set through {@link setRTLTextPlugin} has loaded, so that tiles drawn before it\n * arrived can be drawn again.\n *\n * @deprecated Right-to-left text is drawn without a plugin, so nothing has to be waited for.\n */\nexport const RTLPluginLoadedEventName = 'RTLPluginLoaded';\n\n", "\nimport {browser} from '../util/browser.ts';\nimport {Event, Evented} from '../util/evented.ts';\nimport {warnOnce} from '../util/util.ts';\nimport {type RTLPluginStatus, RTLPluginLoadedEventName, type PluginState} from './rtl_text_plugin_status.ts';\nimport {type GlobalDispatcher, getGlobalDispatcher} from '../util/global_dispatcher.ts';\nimport {MessageType} from '../util/actor_messages.ts';\n\nclass RTLMainThreadPlugin extends Evented {\n    status: RTLPluginStatus = 'unavailable';\n    url: string = null;\n    dispatcher: GlobalDispatcher = getGlobalDispatcher();\n\n    constructor() {\n        super();\n        this.dispatcher.on('workerscreate', () => this._resyncWorkers());\n    }\n\n    /**\n     * Re-syncs the plugin into freshly created workers. A `loading` plugin needs no re-sync: its\n     * in-flight request targets the newest workers, and re-requesting would double-load the\n     * script when the plugin's own broadcast is what created the workers.\n     */\n    async _resyncWorkers(): Promise<void> {\n        try {\n            if (this.status === 'deferred') {\n                await this._syncState('deferred');\n            } else if (this.status === 'loaded') {\n                await this._requestImport();\n            }\n        } catch (error) {\n            warnOnce(`Failed to load the RTL text plugin into the new workers: ${error}`);\n        }\n    }\n\n    /** Sync RTL plugin state by broadcasting a message to the worker */\n    _syncState(statusToSend: RTLPluginStatus): Promise<PluginState[]> {\n        this.status = statusToSend;\n        return this.dispatcher.broadcast(MessageType.syncRTLPluginState, {pluginStatus: statusToSend, pluginURL: this.url})\n            .catch((e: any) => {\n                this.status = 'error';\n                throw e;\n            });\n    }\n\n    /** This one is exposed to outside */\n    getRTLTextPluginStatus(): RTLPluginStatus {\n        return this.status;\n    }\n\n    clearRTLTextPlugin(): void {\n        this.status = 'unavailable';\n        this.url = null;\n    }\n\n    async setRTLTextPlugin(url: string, deferred: boolean = false): Promise<void> {\n        if (this.url) {\n            // error\n            throw new Error('setRTLTextPlugin cannot be called multiple times.');\n        }\n\n        this.url = browser.resolveURL(url);\n        if (!this.url) {\n            throw new Error(`requested url ${url} is invalid`);\n        }\n        if (this.status === 'unavailable') {\n\n            // from initial state:\n            if (deferred) {\n\n                this.status = 'deferred';\n                // fire and forget: in this case it does not need wait for the broadcasting result\n                // it is important to sync the deferred status once because\n                // symbol_bucket will be checking it in worker\n                this._syncState(this.status);\n\n            } else {\n                return this._requestImport();\n            }\n\n        } else if (this.status === 'requested') {\n            return this._requestImport();\n        }\n    }\n\n    /** Send a message to worker which will import the RTL plugin script */\n    async _requestImport() : Promise<void> {\n\n        // all errors/exceptions will be handled by _syncState\n        await this._syncState('loading');\n        this.status = 'loaded';\n        this.fire(new Event(RTLPluginLoadedEventName));\n    }\n\n    /** Start a lazy loading process of RTL plugin */\n    lazyLoad(): void {\n        if (this.status === 'unavailable') {\n            this.status = 'requested';\n        } else if (this.status === 'deferred') {\n            this._requestImport();\n        }\n    }\n}\n\nlet rtlMainThreadPlugin: RTLMainThreadPlugin = null;\n\nexport function rtlMainThreadPluginFactory(): RTLMainThreadPlugin {\n    rtlMainThreadPlugin ||= new RTLMainThreadPlugin();\n    return rtlMainThreadPlugin;\n}\n", "import {uniqueId, parseCacheControl} from '../util/util.ts';\nimport {deserialize as deserializeBucket} from '../data/bucket.ts';\nimport {GEOJSON_TILE_LAYER_NAME, type FeatureIndex, type QueryResults} from '../data/feature_index.ts';\nimport {GeoJSONFeature} from '../util/vectortile_to_geojson.ts';\nimport {featureFilter} from '@maplibre/maplibre-gl-style-spec';\nimport {SymbolBucket} from '../data/bucket/symbol_bucket.ts';\nimport {CollisionBoxArray} from '../data/array_types.g.ts';\nimport {Texture} from '../webgl/texture.ts';\nimport {now} from '../util/time_control.ts';\nimport {toEvaluationFeature} from '../data/evaluation_feature.ts';\nimport {EvaluationParameters} from '../style/evaluation_parameters.ts';\nimport {rtlMainThreadPluginFactory} from '../source/rtl_text_plugin_main_thread.ts';\n\nimport type {SourceFeatureState} from '../source/source_state.ts';\nimport type {Bucket} from '../data/bucket.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {TileEncoding, WorkerTileResult} from '../source/worker_source.ts';\nimport type {Actor} from '../util/actor.ts';\nimport type {DEMData} from '../data/dem_data.ts';\nimport type {AlphaImage} from '../util/image.ts';\nimport type {ImageAtlas} from '../render/image_atlas.ts';\nimport type {ImageManager} from '../render/image_manager.ts';\nimport type {Context} from '../webgl/context.ts';\nimport type {OverscaledTileID} from './tile_id.ts';\nimport type {Framebuffer} from '../webgl/framebuffer.ts';\nimport type {IReadonlyTransform, GetElevation} from '../geo/transform_interface.ts';\nimport type {LayerFeatureStates} from '../source/source_state.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {mat4} from 'gl-matrix';\nimport type {ExpiryData} from '../util/ajax.ts';\nimport type {QueryRenderedFeaturesOptionsStrict, QuerySourceFeatureOptionsStrict} from '../source/query_features.ts';\nimport type {DashEntry} from '../render/line_atlas.ts';\nimport type {VectorTileLayerLike} from '@maplibre/vt-pbf';\nimport type {Painter, RTTObject} from '../render/painter.ts';\nimport type {Style} from '../style/style.ts';\nimport type {RTTFingerprint} from '../webgl/rtt_fingerprint.ts';\n\nconst CLOCK_SKEW_RETRY_TIMEOUT = 30000;\n\n/**\n * The tile's state, can be:\n *\n * - `loading` Tile data is in the process of loading.\n * - `loaded` Tile data has been loaded. Tile can be rendered.\n * - `reloading` Tile data has been loaded and is being updated. Tile can be rendered.\n * - `unloaded` Tile data has been deleted.\n * - `errored` Tile data was not loaded because of an error.\n * - `expired` Tile data was previously loaded, but has expired per its HTTP headers and is in the process of refreshing.\n */\nexport type TileState = 'loading' | 'loaded' | 'reloading' | 'unloaded' | 'errored' | 'expired';\n\n/** @internal */\ntype CrossFadeArgs = {\n    fadingRole: FadingRoles;\n    fadingDirection: FadingDirections;\n    fadingParentID?: OverscaledTileID;\n    fadeEndTime: number;\n};\n\nexport enum FadingRoles {\n    Base, Parent\n}\nexport enum FadingDirections {\n    Departing, Incoming\n}\n\n/**\n * A tile object is the combination of a Coordinate, which defines\n * its place, as well as a unique ID and data tracking for its content\n */\nexport class Tile {\n    tileID: OverscaledTileID;\n    uid: number;\n    uses: number;\n    tileSize: number;\n    buckets: {[_: string]: Bucket};\n    latestFeatureIndex: FeatureIndex | null;\n    latestRawTileData: ArrayBuffer;\n    latestEncoding: TileEncoding;\n    imageAtlas: ImageAtlas;\n    imageAtlasTexture: Texture;\n    dashPositions: {[_: string]: DashEntry};\n    glyphAtlasImage: AlphaImage;\n    glyphAtlasTexture: Texture;\n    etag?: string;\n    expirationTime: any;\n    expiredRequestCount: number;\n    state: TileState;\n    fadingRole: FadingRoles;\n    fadingDirection: FadingDirections;\n    fadingParentID: OverscaledTileID;\n    selfFading: boolean;\n    timeAdded: number = 0;\n    fadeEndTime: number = 0;\n    fadeOpacity: number = 1;\n    collisionBoxArray: CollisionBoxArray;\n    redoWhenDone: boolean;\n    showCollisionBoxes: boolean;\n    placementSource: any;\n    actor: Actor;\n    vtLayers: {[_: string]: VectorTileLayerLike};\n\n    neighboringTiles: Record<string, {backfilled: boolean}>;\n    dem: DEMData;\n    demMatrix: mat4;\n    aborted: boolean;\n    needsHillshadePrepare: boolean;\n    needsTerrainPrepare: boolean;\n    needsColorReliefPrepare: boolean;\n    abortController: AbortController;\n    texture: any;\n    fbo: Framebuffer;\n    demTexture: Texture;\n    refreshedUponExpiration: boolean;\n    reloadPromise: {resolve: () => void; reject: () => void};\n    resourceTiming: PerformanceResourceTiming[];\n    queryPadding: number;\n\n    symbolFadeHoldUntil: number;\n    hasSymbolBuckets: boolean;\n    hasRTLText: boolean;\n    dependencies: any;\n    /**\n     * @internal\n     * Caches the result of rendering this 2D tile into a texture so it can be\n     * draped over 3D terrain. Indexed by stack index, where a stack is a\n     * contiguous run of RTT-eligible layers (fill, line, raster, etc.) split\n     * by non-RTT layers like symbols. So `_rttObjects[0]` holds the texture\n     * for layers below the first symbol break, `_rttObjects[1]` for layers\n     * between the first and second symbol breaks, and so on. Each entry\n     * survives across frames until the tile is unloaded or its source data\n     * changes.\n     */\n    rttObjects: Array<RTTObject | undefined>;\n    rttFingerprint: Record<string, RTTFingerprint>;\n\n    featureStateRevision: number;\n\n    /**\n     * @param tileID - the tile ID\n     * @param size - The tile size\n     */\n    constructor(tileID: OverscaledTileID, size: number) {\n        this.tileID = tileID;\n        this.uid = uniqueId();\n        this.uses = 0;\n        this.tileSize = size;\n        this.buckets = {};\n        this.expirationTime = null;\n        this.queryPadding = 0;\n        this.hasSymbolBuckets = false;\n        this.hasRTLText = false;\n        this.dependencies = {};\n        this.rttObjects = [];\n        this.rttFingerprint = {};\n\n        // Counts the number of times a response was already expired when\n        // received. We're using this to add a delay when making a new request\n        // so we don't have to keep retrying immediately in case of a server\n        // serving expired tiles.\n        this.expiredRequestCount = 0;\n\n        this.state = 'loading';\n        this.featureStateRevision = -1;\n    }\n\n    /**\n     * Incoming and self-fading raster tiles must remain renderable at zero opacity because\n     * drawing advances their opacity. Only transparent departing tiles have finished fading.\n     */\n    isRenderable(symbolLayer: boolean): boolean {\n        return (\n            this.hasData() &&\n            (!this.fadeEndTime || this.fadingDirection !== FadingDirections.Departing || this.fadeOpacity > 0) &&\n            (symbolLayer || !this.holdingForSymbolFade())   // symbol fading\n        );\n    }\n\n    /**\n     * @internal\n     * Many-to-one crossfade between a base tile and parent/ancestor tile (when zooming)\n     */\n    setCrossFadeLogic({fadingRole, fadingDirection, fadingParentID, fadeEndTime}: CrossFadeArgs): void {\n        this.resetFadeLogic();\n\n        this.fadingRole = fadingRole;\n        this.fadingDirection = fadingDirection;\n        this.fadingParentID = fadingParentID;\n        this.fadeEndTime = fadeEndTime;\n    }\n\n    /**\n     * Self fading for edge tiles (when panning map)\n     */\n    setSelfFadeLogic(fadeEndTime: number): void {\n        this.resetFadeLogic();\n        this.selfFading = true;\n        this.fadeEndTime = fadeEndTime;\n    }\n\n    resetFadeLogic(): void {\n        this.fadingRole = null;\n        this.fadingDirection = null;\n        this.fadingParentID = null;\n        this.selfFading = false;\n\n        this.timeAdded = now();\n        this.fadeEndTime = 0;\n        this.fadeOpacity = 1;\n    }\n\n    wasRequested(): boolean {\n        return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading';\n    }\n\n    clearTextures(painter: Painter): void {\n        if (this.demTexture) painter.saveTileTexture(this.demTexture);\n        this.demTexture = null;\n    }\n\n    /**\n     * @internal\n     * Returns the cached RTT object for this stack, or undefined on a cache miss.\n     */\n    getRTT(stack: number): RTTObject | undefined {\n        return this.rttObjects[stack];\n    }\n\n    /**\n     * @internal\n     * Allocates a fresh RTT object from the painter's pool and stores it at the\n     * given stack slot. Callers should check {@link getRTT} first; calling this\n     * over an existing slot leaks the previous object.\n     */\n    acquireRTT(painter: Painter, stack: number, size: number): RTTObject {\n        return this.rttObjects[stack] = painter.acquireRTT(size);\n    }\n\n    /**\n     * @internal\n     * Returns all cached RTT slots to the painter's pool.\n     */\n    releaseRTT(painter: Painter): void {\n        if (this.rttObjects.length === 0) return;\n        for (const obj of this.rttObjects) {\n            // Release RTT only if defined (undefined for holes in sparse array)\n            if (obj) painter.releaseRTT(obj);\n        }\n        this.rttObjects.length = 0;\n    }\n\n    /**\n     * @internal\n     * Returns the cached RTT slot of the stack to the painter's pool.\n     */\n    releaseRTTStack(painter: Painter, stack: number): void {\n        const obj = this.rttObjects[stack];\n        if (!obj) return;\n        painter.releaseRTT(obj);\n        this.rttObjects[stack] = undefined;\n    }\n\n    /**\n     * Given a data object with a 'buffers' property, load it into\n     * this tile's elementGroups and buffers properties and set loaded\n     * to true. If the data is null, like in the case of an empty\n     * GeoJSON tile, no-op but still set loaded to true.\n     * @param data - The data from the worker\n     * @param style - the style the tile's layers belong to\n     * @param justReloaded - `true` to just reload\n     */\n    loadVectorData(data: WorkerTileResult, style: Style, justReloaded?: boolean | null): void {\n        if (data?.etagUnmodified === true) {\n            this.state = 'loaded';\n            return;\n        }\n\n        if (this.hasData()) {\n            this.unloadVectorData();\n        }\n\n        this.state = 'loaded';\n\n        // empty GeoJSON tile\n        if (!data) {\n            this.collisionBoxArray = new CollisionBoxArray();\n            return;\n        }\n\n        if (data.featureIndex) {\n            this.latestFeatureIndex = data.featureIndex;\n            if (data.rawTileData) {\n                // Only vector tiles have rawTileData, and they won't update it for\n                // 'reloadTile'\n                this.latestRawTileData = data.rawTileData;\n                this.latestEncoding = data.encoding;\n                this.latestFeatureIndex.rawTileData = data.rawTileData;\n                this.latestFeatureIndex.encoding = data.encoding;\n            } else if (this.latestRawTileData) {\n                // If rawTileData hasn't updated, hold onto a pointer to the last\n                // one we received\n                this.latestFeatureIndex.rawTileData = this.latestRawTileData;\n                this.latestFeatureIndex.encoding = this.latestEncoding;\n            }\n        }\n        this.collisionBoxArray = data.collisionBoxArray;\n        this.buckets = deserializeBucket(data.buckets, style);\n\n        this.hasSymbolBuckets = false;\n        for (const id in this.buckets) {\n            const bucket = this.buckets[id];\n            if (bucket instanceof SymbolBucket) {\n                this.hasSymbolBuckets = true;\n                if (justReloaded) {\n                    bucket.justReloaded = true;\n                } else {\n                    break;\n                }\n            }\n        }\n\n        this.hasRTLText = false;\n        if (this.hasSymbolBuckets) {\n            for (const id in this.buckets) {\n                const bucket = this.buckets[id];\n                if (bucket instanceof SymbolBucket) {\n                    if (bucket.hasRTLText) {\n                        this.hasRTLText = true;\n                        rtlMainThreadPluginFactory().lazyLoad();\n                        break;\n                    }\n                }\n            }\n        }\n\n        this.queryPadding = 0;\n        for (const id in this.buckets) {\n            const bucket = this.buckets[id];\n            this.queryPadding = Math.max(this.queryPadding, style.getLayer(id).queryRadius(bucket));\n        }\n\n        if (data.imageAtlas) {\n            this.imageAtlas = data.imageAtlas;\n        }\n        if (data.glyphAtlasImage) {\n            this.glyphAtlasImage = data.glyphAtlasImage;\n        }\n        this.dashPositions = data.dashPositions;\n    }\n\n    /**\n     * Release any data or WebGL resources referenced by this tile.\n     */\n    unloadVectorData(): void {\n        for (const id in this.buckets) {\n            this.buckets[id].destroy();\n        }\n        this.buckets = {};\n\n        if (this.imageAtlasTexture) {\n            this.imageAtlasTexture.destroy();\n        }\n\n        if (this.glyphAtlasTexture) {\n            this.glyphAtlasTexture.destroy();\n        }\n\n        this.imageAtlas = null;\n        this.dashPositions = null;\n        this.latestFeatureIndex = null;\n        this.state = 'unloaded';\n    }\n\n    getBucket(layer: StyleLayer): Bucket {\n        return this.buckets[layer.id];\n    }\n\n    upload(context: Context): void {\n        for (const id in this.buckets) {\n            const bucket = this.buckets[id];\n            if (bucket.uploadPending()) {\n                bucket.upload(context);\n            }\n        }\n\n        const gl = context.gl;\n        if (this.imageAtlas && !this.imageAtlas.uploaded) {\n            this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA);\n            this.imageAtlas.uploaded = true;\n        }\n\n        if (this.glyphAtlasImage) {\n            this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA);\n            this.glyphAtlasImage = null;\n        }\n    }\n\n    prepare(imageManager: ImageManager): void {\n        if (this.imageAtlas) {\n            this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);\n        }\n    }\n\n    // Queries non-symbol features rendered for this tile.\n    // Symbol features are queried globally\n    queryRenderedFeatures(\n        layers: {[_: string]: StyleLayer},\n        serializedLayers: {[_: string]: any},\n        sourceFeatureState: SourceFeatureState,\n        queryGeometry: Point[],\n        cameraQueryGeometry: Point[],\n        scale: number,\n        params: Pick<QueryRenderedFeaturesOptionsStrict, 'filter' | 'layers' | 'availableImages'> | undefined,\n        transform: IReadonlyTransform,\n        maxPitchScaleFactor: number,\n        pixelPosMatrix: mat4,\n        getElevation: GetElevation | undefined\n    ): QueryResults {\n        if (!this.latestFeatureIndex?.rawTileData)\n            return {};\n\n        return this.latestFeatureIndex.query({\n            queryGeometry,\n            cameraQueryGeometry,\n            scale,\n            tileSize: this.tileSize,\n            pixelPosMatrix,\n            transform,\n            params,\n            queryPadding: this.queryPadding * maxPitchScaleFactor,\n            getElevation\n        }, layers, serializedLayers, sourceFeatureState);\n    }\n\n    querySourceFeatures(result: GeoJSONFeature[], params: QuerySourceFeatureOptionsStrict): void {\n        const featureIndex = this.latestFeatureIndex;\n        if (!featureIndex?.rawTileData) return;\n\n        const vtLayers = featureIndex.loadVTLayers();\n\n        const sourceLayer = params.sourceLayer ? params.sourceLayer : '';\n        const layer = vtLayers[GEOJSON_TILE_LAYER_NAME] || vtLayers[sourceLayer];\n\n        if (!layer) return;\n\n        const filter = featureFilter(params.filter, `querySourceFeatures[${sourceLayer}].filter`, params.globalState);\n        const {z, x, y} = this.tileID.canonical;\n        const coord = {z, x, y};\n\n        for (let i = 0; i < layer.length; i++) {\n            const feature = layer.feature(i);\n            if (filter.needGeometry) {\n                const evaluationFeature = toEvaluationFeature(feature, true);\n                if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue;\n            } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n                continue;\n            }\n            const id = featureIndex.getId(feature, sourceLayer);\n            const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id, params.worldCoordinateHelper);\n            (geojsonFeature as any).tile = coord;\n            result.push(geojsonFeature);\n        }\n    }\n\n    hasData(): boolean {\n        return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired';\n    }\n\n    patternsLoaded(): boolean {\n        return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;\n    }\n\n    setExpiryData(data: ExpiryData): void {\n        const prior = this.expirationTime;\n\n        if (data.cacheControl) {\n            const parsedCC = parseCacheControl(data.cacheControl);\n            if (parsedCC['max-age']) this.expirationTime = Date.now() + parsedCC['max-age'] * 1000;\n        } else if (data.expires) {\n            this.expirationTime = new Date(data.expires).getTime();\n        }\n\n        if (this.expirationTime) {\n            const now = Date.now();\n            let isExpired = false;\n\n            if (this.expirationTime > now) {\n                isExpired = false;\n            } else if (!prior) {\n                isExpired = true;\n            } else if (this.expirationTime < prior) {\n                // Expiring date is going backwards:\n                // fall back to exponential backoff\n                isExpired = true;\n\n            } else {\n                const delta = this.expirationTime - prior;\n\n                if (!delta) {\n                    // Server is serving the same expired resource over and over: fall\n                    // back to exponential backoff.\n                    isExpired = true;\n\n                } else {\n                    // Assume that either the client or the server clock is wrong and\n                    // try to interpolate a valid expiration date (from the client POV)\n                    // observing a minimum timeout.\n                    this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);\n\n                }\n            }\n\n            if (isExpired) {\n                this.expiredRequestCount++;\n                this.state = 'expired';\n            } else {\n                this.expiredRequestCount = 0;\n            }\n        }\n    }\n\n    getExpiryTimeout(): number {\n        if (this.expirationTime) {\n            if (this.expiredRequestCount) {\n                return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31));\n            } else {\n                // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly\n                return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1);\n            }\n        }\n    }\n\n    setFeatureState(states: LayerFeatureStates, style: Style, revision: number): void {\n        if (!this.latestFeatureIndex?.rawTileData ||\n            Object.keys(states).length === 0) {\n            return;\n        }\n\n        // Skip bucket updates if we already processed this revision\n        if (this.featureStateRevision === revision) {\n            return;\n        }\n        this.featureStateRevision = revision;\n\n        const vtLayers = this.latestFeatureIndex.loadVTLayers();\n\n        for (const id in this.buckets) {\n            if (!style.hasLayer(id)) continue;\n\n            const bucket = this.buckets[id];\n            // Buckets are grouped by common source-layer\n            const sourceLayerId = bucket.layers[0]['sourceLayer'] || GEOJSON_TILE_LAYER_NAME;\n            const sourceLayer = vtLayers[sourceLayerId];\n            const sourceLayerStates = states[sourceLayerId];\n            if (!sourceLayer || !sourceLayerStates || sourceLayerStates.length === 0) continue;\n\n            bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas?.patternPositions || {}, this.dashPositions || {});\n            const layer = style.getLayer(id);\n            if (layer) {\n                this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));\n            }\n        }\n    }\n\n    holdingForSymbolFade(): boolean {\n        return this.symbolFadeHoldUntil !== undefined;\n    }\n\n    symbolFadeFinished(): boolean {\n        return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < now();\n    }\n\n    clearSymbolFadeHold(): void {\n        this.symbolFadeHoldUntil = undefined;\n    }\n\n    setSymbolHoldDuration(duration: number): void {\n        this.symbolFadeHoldUntil = now() + duration;\n    }\n\n    setDependencies(namespace: string, dependencies: string[]): void {\n        const index = {};\n        for (const dep of dependencies) {\n            index[dep] = true;\n        }\n        this.dependencies[namespace] = index;\n    }\n\n    hasDependency(namespaces: string[], keys: string[]): boolean {\n        for (const namespace of namespaces) {\n            const dependencies = this.dependencies[namespace];\n            if (dependencies) {\n                for (const key of keys) {\n                    if (dependencies[key]) {\n                        return true;\n                    }\n                }\n            }\n        }\n        return false;\n    }\n}\n", "import type {OverscaledTileID} from './tile_id.ts';\nimport type {Tile} from './tile.ts';\n\n/**\n * @internal\n * A [least-recently-used cache](https://en.wikipedia.org/wiki/Cache_algorithms)\n * with hash lookup made possible by keeping a list of keys in parallel to\n * an array of dictionary of values\n *\n * TileManager offloads currently unused tiles to this cache, and when a tile gets used again,\n * it is also removed from this cache. Thus addition is the only operation that counts as \"usage\"\n * for the purposes of LRU behaviour.\n */\nexport class TileCache {\n    max: number;\n    data: {\n        [key: string]: Array<{\n            value: Tile;\n            timeout: ReturnType<typeof setTimeout>;\n        }>;\n    };\n    order: string[];\n    onRemove: (element: Tile) => void;\n    /**\n     * @param max - number of permitted values\n     * @param onRemove - callback called with items when they expire\n     */\n    constructor(max: number, onRemove: (element: Tile) => void) {\n        this.max = max;\n        this.onRemove = onRemove;\n        this.reset();\n    }\n\n    /**\n     * Clear the cache\n     *\n     * @returns this cache\n     */\n    reset(): this {\n        for (const key in this.data) {\n            for (const removedData of this.data[key]) {\n                if (removedData.timeout) clearTimeout(removedData.timeout);\n                this.onRemove(removedData.value);\n            }\n        }\n\n        this.data = {};\n        this.order = [];\n\n        return this;\n    }\n\n    /**\n     * Add a key, value combination to the cache, trimming its size if this pushes\n     * it over max length.\n     *\n     * @param tileID - lookup key for the item\n     * @param data - tile data\n     *\n     * @returns this cache\n     */\n    add(tileID: OverscaledTileID, data: Tile, expiryTimeout: number | void): this {\n        const key = tileID.wrapped().key;\n        if (this.data[key] === undefined) {\n            this.data[key] = [];\n        }\n\n        const dataWrapper = {\n            value: data,\n            timeout: undefined\n        };\n\n        if (expiryTimeout !== undefined) {\n            dataWrapper.timeout = setTimeout(() => {\n                this.remove(tileID, dataWrapper);\n            }, expiryTimeout as number);\n        }\n\n        this.data[key].push(dataWrapper);\n        this.order.push(key);\n\n        if (this.order.length > this.max) {\n            const removedData = this._getAndRemoveByKey(this.order[0]);\n            if (removedData) this.onRemove(removedData);\n        }\n\n        return this;\n    }\n\n    /**\n     * Determine whether the value attached to `key` is present\n     *\n     * @param tileID - the key to be looked-up\n     * @returns whether the cache has this value\n     */\n    has(tileID: OverscaledTileID): boolean {\n        return tileID.wrapped().key in this.data;\n    }\n\n    /**\n     * Get the value attached to a specific key and remove data from cache.\n     * If the key is not found, returns `null`\n     *\n     * @param tileID - the key to look up\n     * @returns the tile data, or null if it isn't found\n     */\n    getAndRemove(tileID: OverscaledTileID): Tile {\n        if (!this.has(tileID)) { return null; }\n        return this._getAndRemoveByKey(tileID.wrapped().key);\n    }\n\n    /*\n     * Get and remove the value with the specified key.\n     */\n    _getAndRemoveByKey(key: string): Tile {\n        const data = this.data[key].shift();\n        if (data.timeout) clearTimeout(data.timeout);\n\n        if (this.data[key].length === 0) {\n            delete this.data[key];\n        }\n        this.order.splice(this.order.indexOf(key), 1);\n\n        return data.value;\n    }\n\n    /*\n     * Get the value with the specified (wrapped tile) key.\n     */\n    getByKey(key: string): Tile {\n        const data = this.data[key];\n        return data ? data[0].value : null;\n    }\n\n    /**\n     * Get the value attached to a specific key without removing data\n     * from the cache. If the key is not found, returns `null`\n     *\n     * @param tileID - the key to look up\n     * @returns the tile data, or null if it isn't found\n     */\n    get(tileID: OverscaledTileID): Tile {\n        if (!this.has(tileID)) { return null; }\n\n        const data = this.data[tileID.wrapped().key][0];\n        return data.value;\n    }\n\n    /**\n     * Remove a key/value combination from the cache.\n     *\n     * @param tileID - the key for the pair to delete\n     * @param value - If a value is provided, remove that exact version of the value.\n     * @returns this cache\n     */\n    remove(tileID: OverscaledTileID, value?: {\n        value: Tile;\n        timeout: ReturnType<typeof setTimeout>;\n    }): this {\n        if (!this.has(tileID)) { return this; }\n        const key = tileID.wrapped().key;\n\n        const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value);\n        const data = this.data[key][dataIndex];\n        this.data[key].splice(dataIndex, 1);\n        if (data.timeout) clearTimeout(data.timeout);\n        if (this.data[key].length === 0) {\n            delete this.data[key];\n        }\n        this.onRemove(data.value);\n        this.order.splice(this.order.indexOf(key), 1);\n\n        return this;\n    }\n\n    /**\n     * Change the max size of the cache.\n     *\n     * @param max - the max size of the cache\n     * @returns this cache\n     */\n    setMaxSize(max: number): this {\n        this.max = max;\n\n        while (this.order.length > this.max) {\n            const removedData = this._getAndRemoveByKey(this.order[0]);\n            if (removedData) this.onRemove(removedData);\n        }\n\n        return this;\n    }\n\n    /**\n     * Remove entries that do not pass a filter function. Used for removing\n     * stale tiles from the cache.\n     *\n     * @param filterFn - Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out.\n     */\n    filter(filterFn: (tile: Tile) => boolean): void {\n        const removed = [];\n        for (const key in this.data) {\n            for (const entry of this.data[key]) {\n                if (!filterFn(entry.value)) {\n                    removed.push(entry);\n                }\n            }\n        }\n        for (const r of removed) {\n            this.remove(r.value.tileID, r);\n        }\n    }\n}\n\nexport class BoundedLRUCache<K, V> {\n    private maxEntries: number;\n    private map: Map<K, V>;\n\n    constructor(maxEntries: number) {\n        this.maxEntries = maxEntries;\n        this.map = new Map();\n    }\n\n    get(key: K): V | undefined {\n        const value = this.map.get(key);\n        if (value !== undefined) {\n            // Move key to end (most recently used)\n            this.map.delete(key);\n            this.map.set(key, value);\n        }\n        return value;\n    }\n\n    set(key: K, value: V): void {\n        if (this.map.has(key)) {\n            this.map.delete(key);\n        } else if (this.map.size >= this.maxEntries) {\n            // Delete oldest\n            const oldestKey = this.map.keys().next().value;\n            this.map.delete(oldestKey);\n        }\n        this.map.set(key, value);\n    }\n\n    clear(): void {\n        this.map.clear();\n    }\n}\n", "import {extend} from '../util/util.ts';\n\nimport type {Tile} from '../tile/tile.ts';\nimport type {FeatureState} from '@maplibre/maplibre-gl-style-spec';\nimport type {InViewTiles} from '../tile/tile_manager_in_view_tiles.ts';\nimport type {Style} from '../style/style.ts';\n\nexport type FeatureStateEntry = {id: string; state: FeatureState};\nexport type FeatureStates = FeatureStateEntry[];\nexport type LayerFeatureStates = Record<string, FeatureStates>;\n\ntype FeatureStatesMap = Record<string, FeatureState>;\ntype LayerFeatureStatesMap = Record<string, FeatureStatesMap>;\n\nfunction featureStatesMapToArray(map: FeatureStatesMap): FeatureStates {\n    const result: FeatureStates = [];\n    for (const id in map) {\n        result.push({id, state: map[id]});\n    }\n    return result;\n}\n\n/**\n * @internal\n * SourceFeatureState manages the state and pending changes\n * to features in a source, separated by source layer.\n * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively)\n * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's\n * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations.\n * In deletedStates, all null's denote complete removal of state at that scope\n*/\nexport class SourceFeatureState {\n    state: LayerFeatureStatesMap;\n    stateChanges: LayerFeatureStatesMap;\n    deletedStates: {};\n    revision: number;\n\n    constructor() {\n        this.state = {};\n        this.stateChanges = {};\n        this.deletedStates = {};\n        this.revision = 0;\n    }\n\n    updateState(sourceLayer: string, featureId: number | string, newState: any): void {\n        const feature = String(featureId);\n        this.stateChanges[sourceLayer] ||= {};\n        this.stateChanges[sourceLayer][feature] ||= {};\n        extend(this.stateChanges[sourceLayer][feature], newState);\n\n        if (this.deletedStates[sourceLayer] === null) {\n            this.deletedStates[sourceLayer] = {};\n            for (const ft in this.state[sourceLayer]) {\n                if (ft === feature){\n                    this.deletedStates[sourceLayer][feature] = {};\n                    for (const prop in this.state[sourceLayer][ft]){\n                        if (newState[prop] === undefined) this.deletedStates[sourceLayer][feature][prop] = null;\n                    }\n                } else {\n                    this.deletedStates[sourceLayer][ft] = null;\n                }\n            }\n        } else {\n            const featureDeletionQueued = this.deletedStates[sourceLayer]?.[feature] === null;\n            if (featureDeletionQueued) {\n                this.deletedStates[sourceLayer][feature] = {};\n                for (const prop in this.state[sourceLayer][feature]) {\n                    if (newState[prop] === undefined) this.deletedStates[sourceLayer][feature][prop] = null;\n                }\n            } else {\n                for (const key in newState) {\n                    const deletionInQueue = this.deletedStates[sourceLayer]?.[feature]?.[key] === null;\n                    if (deletionInQueue) delete this.deletedStates[sourceLayer][feature][key];\n                }\n            }\n        }\n    }\n\n    removeFeatureState(sourceLayer: string, featureId?: number | string, key?: string): void {\n        const sourceLayerDeleted = this.deletedStates[sourceLayer] === null;\n        if (sourceLayerDeleted) return;\n\n        const feature = String(featureId);\n\n        this.deletedStates[sourceLayer] ||= {};\n\n        if (key && featureId !== undefined) {\n            if (this.deletedStates[sourceLayer][feature] !== null) {\n                this.deletedStates[sourceLayer][feature] ||= {};\n                this.deletedStates[sourceLayer][feature][key] = null;\n            }\n        } else if (featureId !== undefined) {\n            const updateInQueue = this.stateChanges[sourceLayer]?.[feature];\n            if (updateInQueue) {\n                this.deletedStates[sourceLayer][feature] = {};\n                for (key in this.stateChanges[sourceLayer][feature]) this.deletedStates[sourceLayer][feature][key] = null;\n\n            } else {\n                this.deletedStates[sourceLayer][feature] = null;\n            }\n        } else {\n            this.deletedStates[sourceLayer] = null;\n        }\n\n    }\n\n    getState(sourceLayer: string, featureId: number | string): FeatureState {\n        const feature = String(featureId);\n        const base = this.state[sourceLayer] || {};\n        const changes = this.stateChanges[sourceLayer] || {};\n\n        const reconciledState = extend({}, base[feature], changes[feature]);\n\n        //return empty object if the whole source layer is awaiting deletion\n        if (this.deletedStates[sourceLayer] === null) return {};\n        else if (this.deletedStates[sourceLayer]) {\n            const featureDeletions = this.deletedStates[sourceLayer][featureId];\n            if (featureDeletions === null) return {};\n            for (const prop in featureDeletions) delete reconciledState[prop];\n        }\n        return reconciledState;\n    }\n\n    initializeTileState(tile: Tile, style: Style): void {\n        const layerStates: LayerFeatureStates = {};\n        for (const sourceLayer in this.state) {\n            layerStates[sourceLayer] = featureStatesMapToArray(this.state[sourceLayer]);\n        }\n        tile.setFeatureState(layerStates, style, this.revision);\n    }\n\n    coalesceChanges(inViewTiles: InViewTiles, style: Style): void {\n        //track changes with full state objects, but only for features that got modified\n        //use an intermediate object keyed by feature id to naturally deduplicate entries\n        const featuresChangedMap: LayerFeatureStatesMap = {};\n\n        for (const sourceLayer in this.stateChanges) {\n            this.state[sourceLayer] ||= {};\n            featuresChangedMap[sourceLayer] ||= {};\n            for (const feature in this.stateChanges[sourceLayer]) {\n                this.state[sourceLayer][feature] ||= {};\n                extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);\n                featuresChangedMap[sourceLayer][feature] = this.state[sourceLayer][feature];\n            }\n        }\n\n        for (const sourceLayer in this.deletedStates) {\n            this.state[sourceLayer] ||= {};\n            featuresChangedMap[sourceLayer] ||= {};\n\n            if (this.deletedStates[sourceLayer] === null) {\n                for (const ft in this.state[sourceLayer]) {\n                    this.state[sourceLayer][ft] = {};\n                    featuresChangedMap[sourceLayer][ft] = {};\n                }\n            } else {\n                for (const feature in this.deletedStates[sourceLayer]) {\n                    const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null;\n                    if (deleteWholeFeatureState) this.state[sourceLayer][feature] = {};\n                    else if (this.state[sourceLayer][feature]) {\n                        for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) {\n                            delete this.state[sourceLayer][feature][key];\n                        }\n                    } else continue;\n                    featuresChangedMap[sourceLayer][feature] = this.state[sourceLayer][feature];\n                }\n            }\n        }\n\n        this.stateChanges = {};\n        this.deletedStates = {};\n\n        if (Object.keys(featuresChangedMap).length === 0) return;\n\n        this.revision++;\n\n        const featuresChanged: LayerFeatureStates = {};\n        for (const sourceLayer in featuresChangedMap) {\n            featuresChanged[sourceLayer] = featureStatesMapToArray(featuresChangedMap[sourceLayer]);\n        }\n\n        inViewTiles.setFeatureState(featuresChanged, style, this.revision);\n    }\n}\n", "import {vec3, type vec4} from 'gl-matrix';\nimport {IntersectionResult, type IBoundingVolume} from './bounding_volume.ts';\n\nimport type {Frustum} from './frustum.ts';\n\nexport class Aabb implements IBoundingVolume {\n    min: vec3;\n    max: vec3;\n    center: vec3;\n\n    constructor(min_: vec3, max_: vec3) {\n        this.min = min_;\n        this.max = max_;\n        this.center = vec3.scale([], vec3.add([], this.min, this.max), 0.5);\n    }\n\n    quadrant(index: number): Aabb {\n        const split = [(index % 2) === 0, index < 2];\n        const qMin = vec3.clone(this.min);\n        const qMax = vec3.clone(this.max);\n        for (let axis = 0; axis < split.length; axis++) {\n            qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];\n            qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];\n        }\n        // Elevation is always constant, hence quadrant.max.z = this.max.z\n        qMax[2] = this.max[2];\n        return new Aabb(qMin, qMax);\n    }\n\n    distanceX(point: number[]): number {\n        const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]);\n        return pointOnAabb - point[0];\n    }\n\n    distanceY(point: number[]): number {\n        const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]);\n        return pointOnAabb - point[1];\n    }\n\n    /**\n     * Performs a frustum-aabb intersection test.\n     */\n    intersectsFrustum(frustum: Frustum): IntersectionResult {\n        // Execute separating axis test between two convex objects to find intersections\n        // Each frustum plane together with 3 major axes define the separating axes\n        let fullyInside = true;\n\n        for (const plane of frustum.planes) {\n            const planeIntersection = this.intersectsPlane(plane);\n\n            if (planeIntersection === IntersectionResult.None) {\n                return IntersectionResult.None;\n            }\n            if (planeIntersection === IntersectionResult.Partial) {\n                fullyInside = false;\n            }\n        }\n\n        if (fullyInside) {\n            return IntersectionResult.Full;\n        }\n\n        if (frustum.aabb.min[0] > this.max[0] || frustum.aabb.min[1] > this.max[1] || frustum.aabb.min[2] > this.max[2] ||\n            frustum.aabb.max[0] < this.min[0] || frustum.aabb.max[1] < this.min[1] || frustum.aabb.max[2] < this.min[2]) {\n            return IntersectionResult.None;\n        }\n\n        return IntersectionResult.Partial;\n    }\n\n    /**\n     * Performs a halfspace-aabb intersection test.\n     */\n    intersectsPlane(plane: vec4): IntersectionResult {\n        let distMin = plane[3];\n        let distMax = plane[3];\n        for (let i = 0; i < 3; i++) {\n            if (plane[i] > 0) {\n                distMin += plane[i] * this.min[i];\n                distMax += plane[i] * this.max[i];\n            } else {\n                distMax += plane[i] * this.min[i];\n                distMin += plane[i] * this.max[i];\n            }\n        }\n\n        if (distMin >= 0) {\n            return IntersectionResult.Full;\n        }\n        if (distMax < 0) {\n            return IntersectionResult.None;\n        }\n        return IntersectionResult.Partial;\n    }\n}\n", "import {type mat4, vec3, vec4} from 'gl-matrix';\nimport {Aabb} from './aabb.ts';\nimport {pointPlaneSignedDistance, rayPlaneIntersection} from '../util.ts';\n\nexport class Frustum {\n\n    constructor(public points: vec4[], public planes: vec4[], public aabb: Aabb) { }\n\n    public static fromInvProjectionMatrix(invProj: mat4, worldSize: number = 1, zoom: number = 0, horizonPlane?: vec4, flippedNearFar?: boolean): Frustum {\n        const clipSpaceCorners = [\n            [-1, 1, -1, 1],\n            [1, 1, -1, 1],\n            [1, -1, -1, 1],\n            [-1, -1, -1, 1],\n            [-1, 1, 1, 1],\n            [1, 1, 1, 1],\n            [1, -1, 1, 1],\n            [-1, -1, 1, 1]\n        ];\n\n        // Globe and mercator projection matrices have different Y directions, hence we need different sets of indices.\n        // This should be fixed in the future.\n        const frustumPlanePointIndices = flippedNearFar ? [\n            [6, 5, 4],  // near\n            [0, 1, 2],  // far\n            [0, 3, 7],  // left\n            [2, 1, 5],  // right\n            [3, 2, 6],  // bottom\n            [0, 4, 5]   // top\n        ] : [\n            [0, 1, 2],  // near\n            [6, 5, 4],  // far\n            [0, 3, 7],  // left\n            [2, 1, 5],  // right\n            [3, 2, 6],  // bottom\n            [0, 4, 5]   // top\n        ];\n\n        const scale = Math.pow(2, zoom);\n\n        // Transform frustum corner points from clip space to tile space, Z to meters\n        const frustumCoords = clipSpaceCorners.map(v => unprojectClipSpacePoint(v, invProj, worldSize, scale));\n\n        if (horizonPlane) {\n            // A horizon clipping plane was supplied.\n            adjustFarPlaneByHorizonPlane(frustumCoords, frustumPlanePointIndices[0], horizonPlane, flippedNearFar);\n        }\n\n        const frustumPlanes = frustumPlanePointIndices.map((p: number[]) => {\n            const a = vec3.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);\n            const b = vec3.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);\n            const n = vec3.normalize([], vec3.cross([], a, b)) as any;\n            const d = -vec3.dot(n, frustumCoords[p[1]]);\n            return n.concat(d);\n        });\n\n        const min: vec3 = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];\n        const max: vec3 = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];\n\n        for (const p of frustumCoords) {\n            for (let i = 0; i < 3; i++) {\n                min[i] = Math.min(min[i], p[i]);\n                max[i] = Math.max(max[i], p[i]);\n            }\n        }\n\n        return new Frustum(frustumCoords, frustumPlanes, new Aabb(min, max));\n    }\n}\n\nfunction unprojectClipSpacePoint(point: vec4 | number[], invProj: mat4, worldSize: number, scale: number): vec4 {\n    const v = vec4.transformMat4([], point, invProj) as any;\n    const s = 1.0 / v[3] / worldSize * scale;\n    return vec4.mul(v, v, [s, s, 1.0 / v[3], s] as vec4);\n}\n\n/**\n * Modifies points in the supplied `frustumCoords` array so that the frustum's far plane only lies as far as the horizon,\n * which improves frustum culling effectiveness.\n * @param frustumCoords - Points of the frustum.\n * @param nearPlanePointsIndices - Which indices in the `frustumCoords` form the near plane.\n * @param horizonPlane - The horizon plane.\n */\nfunction adjustFarPlaneByHorizonPlane(frustumCoords: vec4[], nearPlanePointsIndices: number[], horizonPlane: vec4, flippedNearFar: boolean): void {\n    // For each of the 4 edges from near to far plane,\n    // we find at which distance these edges intersect the given clipping plane,\n    // select the maximal value from these distances and then we move\n    // the frustum's far plane so that it is at most as far away from the near plane\n    // as this maximal distance.\n\n    const nearPlanePointsOffset = flippedNearFar ? 4 : 0;\n    const farPlanePointsOffset = flippedNearFar ? 0 : 4;\n\n    let maxDist = 0;\n    const cornerRayLengths: number[] = [];\n    const cornerRayNormalizedDirections: vec3[] = [];\n    for (let i = 0; i < 4; i++) {\n        const dir = vec3.sub([], frustumCoords[i + farPlanePointsOffset], frustumCoords[i + nearPlanePointsOffset]);\n        const len = vec3.length(dir);\n        vec3.scale(dir, dir, 1.0 / len); // normalize\n        cornerRayLengths.push(len);\n        cornerRayNormalizedDirections.push(dir);\n    }\n\n    for (let i = 0; i < 4; i++) {\n        const dist = rayPlaneIntersection(frustumCoords[i + nearPlanePointsOffset], cornerRayNormalizedDirections[i], horizonPlane);\n        if (dist !== null && dist >= 0) {\n            maxDist = Math.max(maxDist, dist);\n        } else {\n            // Use the original ray length for rays parallel to the horizon plane, or for rays pointing away from it.\n            maxDist = Math.max(maxDist, cornerRayLengths[i]);\n        }\n    }\n\n    // Compute the near plane.\n    // We use its normal as the \"view vector\" - direction in which the camera is looking.\n    const nearPlaneNormalized = getNormalizedNearPlane(frustumCoords, nearPlanePointsIndices);\n\n    // We also try to adjust the far plane position so that it exactly intersects the point on the horizon\n    // that is most distant from the near plane.\n    const idealFarPlaneDistanceFromNearPlane = getIdealNearFarPlaneDistance(horizonPlane, nearPlaneNormalized);\n    if (idealFarPlaneDistanceFromNearPlane !== null) {\n        const idealCornerRayLength = idealFarPlaneDistanceFromNearPlane / vec3.dot(cornerRayNormalizedDirections[0], nearPlaneNormalized); // dot(near plane, ray dir) is the same for all 4 corners\n        maxDist = Math.min(maxDist, idealCornerRayLength);\n    }\n\n    for (let i = 0; i < 4; i++) {\n        const targetLength = Math.min(maxDist, cornerRayLengths[i]);\n        frustumCoords[i + farPlanePointsOffset] = [\n            frustumCoords[i + nearPlanePointsOffset][0] + cornerRayNormalizedDirections[i][0] * targetLength,\n            frustumCoords[i + nearPlanePointsOffset][1] + cornerRayNormalizedDirections[i][1] * targetLength,\n            frustumCoords[i + nearPlanePointsOffset][2] + cornerRayNormalizedDirections[i][2] * targetLength,\n            1,\n        ] as vec4;\n    }\n}\n\n/**\n * Returns the near plane equation with unit length direction.\n * @param frustumCoords - Points of the frustum.\n * @param nearPlanePointsIndices - Which indices in the `frustumCoords` form the near plane.\n */\nfunction getNormalizedNearPlane(frustumCoords: vec4[], nearPlanePointsIndices: number[]): vec4 {\n    const nearPlaneA = vec3.sub([], frustumCoords[nearPlanePointsIndices[0]], frustumCoords[nearPlanePointsIndices[1]]);\n    const nearPlaneB = vec3.sub([], frustumCoords[nearPlanePointsIndices[2]], frustumCoords[nearPlanePointsIndices[1]]);\n    const nearPlaneNormalized = [0, 0, 0, 0] as vec4;\n    vec3.normalize(nearPlaneNormalized, vec3.cross([], nearPlaneA, nearPlaneB)) as any;\n    nearPlaneNormalized[3] = -vec3.dot(nearPlaneNormalized, frustumCoords[nearPlanePointsIndices[0]]);\n    return nearPlaneNormalized;\n}\n\n/**\n * Returns the ideal distance between the frustum's near and far plane so that the far plane only lies as far as the horizon.\n */\nfunction getIdealNearFarPlaneDistance(horizonPlane: vec4, nearPlaneNormalized: vec4): number | null {\n    // Normalize the horizon plane to unit direction\n    const horizonPlaneLen = vec3.len(horizonPlane);\n    const normalizedHorizonPlane = vec4.scale([], horizonPlane, 1 / horizonPlaneLen);\n\n    // Project the view vector onto the horizon plane\n    const projectedViewDirection = vec3.sub([], nearPlaneNormalized, vec3.scale([], normalizedHorizonPlane, vec3.dot(nearPlaneNormalized, normalizedHorizonPlane)));\n    const projectedViewLength = vec3.len(projectedViewDirection);\n\n    // projectedViewLength will be 0 if the camera is looking straight down\n    if (projectedViewLength > 0) {\n        // Find the radius and center of the horizon circle (the horizon circle is the intersection of the planet's sphere and the horizon plane).\n        const horizonCircleRadius = Math.sqrt(1 - normalizedHorizonPlane[3] * normalizedHorizonPlane[3]);\n        const horizonCircleCenter = vec3.scale([], normalizedHorizonPlane, -normalizedHorizonPlane[3]); // The horizon plane normal always points towards the camera.\n        // Find the furthest point on the horizon circle from the near plane.\n        const pointFurthestOnHorizonCircle = vec3.add([], horizonCircleCenter, vec3.scale([], projectedViewDirection, horizonCircleRadius / projectedViewLength));\n        // Compute this point's distance from the near plane.\n        return pointPlaneSignedDistance(nearPlaneNormalized, pointFurthestOnHorizonCircle);\n    } else {\n        return null;\n    }\n}\n", "import {OverscaledTileID} from '../../tile/tile_id.ts';\nimport {vec2, type vec3, type vec4} from 'gl-matrix';\nimport {Frustum} from '../../util/primitives/frustum.ts';\nimport {Aabb} from '../../util/primitives/aabb.ts';\nimport {clamp, degreesToRadians, scaleZoom} from '../../util/util.ts';\nimport {cameraMercatorCoordinate, maxMercatorHorizonAngle} from './mercator_utils.ts';\nimport {earthRadius} from '../lng_lat.ts';\nimport {type IBoundingVolume, IntersectionResult} from '../../util/primitives/bounding_volume.ts';\n\nimport type {Terrain} from '../../render/terrain.ts';\nimport type {IReadonlyTransform} from '../transform_interface.ts';\n\ntype CoveringTilesResult = {\n    tileID: OverscaledTileID;\n    distanceSq: number;\n    tileDistanceToCamera: number;\n};\n\ntype CoveringTilesStackEntry = {\n    zoom: number;\n    x: number;\n    y: number;\n    wrap: number;\n    fullyVisible: boolean;\n};\n\nexport type CoveringTilesOptions = {\n    /**\n     * Smallest allowed tile zoom.\n     */\n    minzoom?: number;\n    /**\n     * Largest allowed tile zoom.\n     */\n    maxzoom?: number;\n    /**\n     * Whether to round or floor the target zoom level. If true, the value will be rounded to the closest integer. Otherwise the value will be floored.\n     */\n    roundZoom?: boolean;\n    /**\n     * Tile size, expressed in screen pixels.\n     */\n    tileSize: number;\n};\n\nexport type CoveringTilesOptionsInternal = CoveringTilesOptions & {\n    /**\n     * `true` if tiles should be sent back to the worker for each overzoomed zoom level, `false` if not.\n     * Fill this option when computing covering tiles for a source.\n     * When true, any tile at `maxzoom` level that should be overscaled to a greater zoom will have\n     * its zoom set to the overscaled greater zoom. When false, such tiles will have zoom set to `maxzoom`.\n     */\n    reparseOverscaled?: boolean;\n    /**\n     * When terrain is present, tile visibility will be computed in regards to the min and max elevations for each tile.\n     */\n    terrain?: Terrain;\n    /**\n     * Optional function to redefine how tiles are loaded at high pitch angles.\n     */\n    calculateTileZoom?: CalculateTileZoomFunction;\n    /**\n     * The highest elevation, in meters, that this source's content may reach above the ground,\n     * e.g. the largest `symbol-height-offset` in use. `maxContentElevation` can raise the\n     * culling height above `ASSUMED_MAX_FEATURE_HEIGHT_METERS`, so tiles under highly elevated\n     * content are not dropped while that content is still visible.\n     */\n    maxContentElevation?: number;\n};\n\n/**\n * Function to define how tiles are loaded at high pitch angles\n * @param requestedCenterZoom - the requested zoom level, valid at the center point.\n * @param distanceToTile2D - 2D distance from the camera to the candidate tile, in mercator units.\n * @param distanceToTileZ - vertical distance from the camera to the candidate tile, in mercator units.\n * @param distanceToCenter3D - distance from camera to center point, in mercator units\n * @param cameraVerticalFOV - camera vertical field of view, in degrees\n * @return the desired zoom level for this tile. May not be an integer.\n */\nexport type CalculateTileZoomFunction = (requestedCenterZoom: number,\n    distanceToTile2D: number,\n    distanceToTileZ: number,\n    distanceToCenter3D: number,\n    cameraVerticalFOV: number) => number;\n\n/**\n * A simple/heuristic function that returns whether the tile is visible under the current transform.\n * @returns an {@link IntersectionResult}.\n */\nexport function isTileVisible(frustum: Frustum, tileBoundingVolume: IBoundingVolume, plane?: vec4): IntersectionResult {\n    const frustumTest = tileBoundingVolume.intersectsFrustum(frustum);\n    if (!plane || frustumTest === IntersectionResult.None) {\n        return frustumTest;\n    }\n    const planeTest = tileBoundingVolume.intersectsPlane(plane);\n\n    if (planeTest === IntersectionResult.None) {\n        return IntersectionResult.None;\n    }\n\n    if (frustumTest === IntersectionResult.Full && planeTest === IntersectionResult.Full) {\n        return IntersectionResult.Full;\n    }\n\n    return IntersectionResult.Partial;\n}\n\n/**\n * Definite integral of cos(x)^p. The analytical solution is described in `developer-guides/covering-tiles.md`,\n * but here the integral is evaluated numerically.\n * @param p - the power to raise cos(x) to inside the integral\n * @param x1 - the starting point of the integral.\n * @param x2 - the ending point of the integral.\n * @return the integral of cos(x)^p from x=x1 to x=x2\n */\nfunction integralOfCosXByP(p: number, x1: number, x2: number): number {\n    const numPoints = 10;\n    let sum = 0;\n    const dx = (x2 - x1 ) / numPoints;\n    // Midpoint integration\n    for( let i = 0; i < numPoints; i++)\n    {\n        const x = x1 + (i + 0.5)/numPoints * (x2 - x1);\n        sum += dx * Math.pow(Math.cos(x), p);\n    }\n    return sum;\n}\n\nexport function createCalculateTileZoomFunction(maxZoomLevelsOnScreen: number, tileCountMaxMinRatio: number): CalculateTileZoomFunction {\n    return function (requestedCenterZoom: number,\n        distanceToTile2D: number,\n        distanceToTileZ: number,\n        distanceToCenter3D: number,\n        cameraVerticalFOV: number): number {\n        /**\n        * Controls how tiles are loaded at high pitch angles. Higher numbers cause fewer, lower resolution\n        * tiles to be loaded. Calculate the value that will result in the selected number of zoom levels in\n        * the worst-case condition (when the horizon is at the top of the screen). For more information, see\n        * `developer-guides/covering-tiles.md`\n        */\n        const pitchTileLoadingBehavior = 2 * ((maxZoomLevelsOnScreen - 1) /\n            scaleZoom(Math.cos(degreesToRadians(maxMercatorHorizonAngle - cameraVerticalFOV)) /\n                Math.cos(degreesToRadians(maxMercatorHorizonAngle))) - 1);\n\n        const centerPitch = Math.acos(distanceToTileZ / distanceToCenter3D);\n        const tileCountPitch0 = 2 * integralOfCosXByP(pitchTileLoadingBehavior - 1, 0, degreesToRadians(cameraVerticalFOV / 2));\n        const highestPitch = Math.min(degreesToRadians(maxMercatorHorizonAngle), centerPitch + degreesToRadians(cameraVerticalFOV / 2));\n        const lowestPitch = Math.min(highestPitch, centerPitch - degreesToRadians(cameraVerticalFOV / 2));\n        const tileCount = integralOfCosXByP(pitchTileLoadingBehavior - 1, lowestPitch, highestPitch);\n        const thisTilePitch = Math.atan(distanceToTile2D / distanceToTileZ);\n        const distanceToTile3D = Math.hypot(distanceToTile2D, distanceToTileZ);\n\n        let thisTileDesiredZ = requestedCenterZoom;\n        // if distance to candidate tile is a tiny bit farther than distance to center,\n        // use the same zoom as the center. This is achieved by the scaling distance ratio by cos(fov/2)\n        thisTileDesiredZ = thisTileDesiredZ + scaleZoom(distanceToCenter3D / distanceToTile3D / Math.max(0.5, Math.cos(degreesToRadians(cameraVerticalFOV / 2))));\n        thisTileDesiredZ += pitchTileLoadingBehavior * scaleZoom(Math.cos(thisTilePitch)) / 2;\n        thisTileDesiredZ -= scaleZoom(Math.max(1, tileCount / tileCountPitch0 / tileCountMaxMinRatio)) / 2;\n        return thisTileDesiredZ;\n    };\n}\nconst defaultMaxZoomLevelsOnScreen = 9.314;\nconst defaultTileCountMaxMinRatio = 3.0;\nconst defaultCalculateTileZoom = createCalculateTileZoomFunction(defaultMaxZoomLevelsOnScreen, defaultTileCountMaxMinRatio);\n\n/**\n * Return what zoom level of a tile source would most closely cover the tiles displayed by this transform.\n * @param options - The options, most importantly the source's tile size.\n * @returns An integer zoom level at which all tiles will be visible.\n */\nexport function coveringZoomLevel(transform: IReadonlyTransform, options: CoveringTilesOptions): number {\n    const z = (options.roundZoom ? Math.round : Math.floor)(\n        transform.zoom + scaleZoom(transform.tileSize / options.tileSize)\n    );\n    // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist.\n    return Math.max(0, z);\n}\n\n/**\n * Without terrain, `getTileBoundingVolume` has no knowledge of extruded features\n * (eg. 3D buildings): every tile's bounding box is flat at the camera's `elevation`.\n * That's a fine approximation of what's visible for most views, but it breaks down\n * as the frustum's bottom edge approaches horizontal (which depends on both `pitch`\n * and `fov`, not pitch alone) - a tall building can still be poking up into view\n * long after its tile's ground point has dropped out of the frustum.\n *\n * This is an assumed upper bound on real-world feature height (in metres), used to\n * grow the elevation used for tile culling as that bottom edge nears horizontal, so\n * such tiles are not dropped too early. It has no effect away from that edge case.\n */\nconst ASSUMED_MAX_FEATURE_HEIGHT_METERS = 500;\n\n/**\n * Angle between the frustum's bottom edge and the mercator horizon below which\n * the culling elevation starts to grow.\n */\nconst TILE_CULLING_HORIZON_ONSET_DEGREES = 15;\n\n/**\n * Returns the elevation to use when computing tile bounding volumes for culling:\n * `transform.elevation`, growing by up to the greater of\n * `ASSUMED_MAX_FEATURE_HEIGHT_METERS` and `maxContentElevation` (when provided)\n * as the frustum's bottom edge approaches the horizon, where a ground-level\n * bounding box would cull tiles whose extruded features are still visible.\n */\nfunction getElevationForTileCulling(transform: IReadonlyTransform, maxContentElevation?: number): number {\n    const bottomEdgeDegreesAboveHorizontal = maxMercatorHorizonAngle - transform.pitch - transform.fov / 2;\n    const proximityToHorizon = clamp(\n        (TILE_CULLING_HORIZON_ONSET_DEGREES - bottomEdgeDegreesAboveHorizontal) / TILE_CULLING_HORIZON_ONSET_DEGREES,\n        0, 1);\n    const maxFeatureHeight = Math.max(ASSUMED_MAX_FEATURE_HEIGHT_METERS, maxContentElevation ?? 0);\n    return transform.elevation + proximityToHorizon * maxFeatureHeight;\n}\n\n/**\n * Returns a copy of the frustum with its far plane moved away from the camera by `distance`.\n * Each far corner travels along its own camera ray until it reaches the pushed plane, so the\n * result stays a pyramid and the corners stay consistent with the side planes. The globe\n * frustum's far plane is fitted to the surface horizon, so elevated content beyond it would\n * otherwise be culled while still visible.\n */\nfunction pushFrustumFarPlane(frustum: Frustum, distance: number, cameraPos: vec3): Frustum {\n    const far = frustum.planes[1];\n    const points = frustum.points.map((p) => {\n        const distanceToFar = far[0] * p[0] + far[1] * p[1] + far[2] * p[2] + far[3];\n        if (Math.abs(distanceToFar) > 1e-6) {\n            return p;\n        }\n        const ray = [p[0] - cameraPos[0], p[1] - cameraPos[1], p[2] - cameraPos[2]];\n        const rayDotNormal = far[0] * ray[0] + far[1] * ray[1] + far[2] * ray[2];\n        if (rayDotNormal >= -1e-9) {\n            return p;\n        }\n        const scale = distance / -rayDotNormal;\n        return [p[0] + ray[0] * scale, p[1] + ray[1] * scale, p[2] + ray[2] * scale, p[3]] as vec4;\n    });\n    const planes = frustum.planes.map((p, i) => i === 1 ? [p[0], p[1], p[2], p[3] + distance] as vec4 : p);\n    const min: vec3 = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];\n    const max: vec3 = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];\n    for (const p of points) {\n        for (let i = 0; i < 3; i++) {\n            min[i] = Math.min(min[i], p[i]);\n            max[i] = Math.max(max[i], p[i]);\n        }\n    }\n    return new Frustum(points, planes, new Aabb(min, max));\n}\n\n/**\n * The horizon culling plane and the frustum's far plane both assume content sits on the\n * surface. Content elevated to radius r (in planet radii) stays visible up to acos(1/r)\n * beyond the surface horizon and up to sqrt(r^2-1) farther away, so both are pushed back\n * accordingly; without this, tiles under highly elevated symbols would be dropped while\n * the symbols are still in view.\n * @param frustum - The covering frustum, fitted to the surface horizon.\n * @param plane - The horizon culling plane used by globe transform.\n * @param cameraPos - The camera position, in the frustum's space.\n * @param maxContentElevation - The highest elevation the content may reach, in meters.\n */\nexport function expandCullingToContentElevation(frustum: Frustum, plane: vec4, cameraPos: vec3, maxContentElevation: number): {frustum: Frustum; plane: vec4} {\n    const len = Math.hypot(plane[0], plane[1], plane[2]);\n    if (len === 0) {\n        return {frustum, plane};\n    }\n    const shellRadius = 1.0 + maxContentElevation / earthRadius;\n    const horizonCos = clamp(-plane[3] / len, -1, 1);\n    const shellCos = Math.cos(Math.acos(horizonCos) + Math.acos(1.0 / shellRadius));\n    return {\n        frustum: pushFrustumFarPlane(frustum, Math.sqrt(shellRadius * shellRadius - 1.0), cameraPos),\n        plane: [plane[0], plane[1], plane[2], -shellCos * len] as vec4,\n    };\n}\n\n/**\n * Returns a list of tiles that optimally covers the screen. Adapted for globe projection.\n * Correctly handles LOD when moving over the antimeridian.\n * @param transform - The transform instance.\n * @param frustum - The covering frustum.\n * @param plane - The clipping plane used by globe transform, or null.\n * @param cameraCoord - The x, y, z position of the camera in MercatorCoordinates.\n * @param centerCoord - The x, y, z position of the center point in MercatorCoordinates.\n * @param options - Additional coveringTiles options.\n * @param details - Interface to define required helper functions.\n * @returns A list of tile coordinates, ordered by ascending distance from camera.\n */\nexport function coveringTiles(transform: IReadonlyTransform, options: CoveringTilesOptionsInternal): OverscaledTileID[] {\n    let frustum = transform.getCameraFrustum();\n    let plane = transform.getClippingPlane();\n    if (plane && options.maxContentElevation > 0) {\n        ({frustum, plane} = expandCullingToContentElevation(frustum, plane, transform.cameraPosition, options.maxContentElevation));\n    }\n    const detailsProvider = transform.getCoveringTilesDetailsProvider();\n    const center = detailsProvider.getCenter(transform);\n    const cameraCoord = cameraMercatorCoordinate(transform, center);\n    const centerCoord = transform.worldCoordinateHelper.worldFromLngLat(center.lng, center.lat, transform.elevation);\n    const elevationForTileCulling = getElevationForTileCulling(transform, options.maxContentElevation);\n    const allowVariableZoom = detailsProvider.allowVariableZoom(transform, options);\n    \n    const desiredZ = coveringZoomLevel(transform, options);\n    const minZoom = options.minzoom || 0;\n    const maxZoom = options.maxzoom !== undefined ? options.maxzoom : transform.maxZoom;\n    const nominalZ = Math.min(Math.max(0, desiredZ), maxZoom);\n\n    const numTiles = Math.pow(2, nominalZ);\n    const cameraPoint = [numTiles * cameraCoord.x, numTiles * cameraCoord.y, 0];\n    const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0];\n    const distanceToCenter2d = Math.hypot(centerCoord.x - cameraCoord.x, centerCoord.y - cameraCoord.y);\n    const distanceZ = Math.abs(centerCoord.z - cameraCoord.z);\n    const distanceToCenter3d = Math.hypot(distanceToCenter2d, distanceZ);\n\n    const newRootTile = (wrap: number): CoveringTilesStackEntry => {\n        return {\n            zoom: 0,\n            x: 0,\n            y: 0,\n            wrap,\n            fullyVisible: false\n        };\n    };\n\n    // Do a depth-first traversal to find visible tiles and proper levels of detail\n    const stack: CoveringTilesStackEntry[] = [];\n    const result: CoveringTilesResult[] = [];\n\n    if (transform.renderWorldCopies && transform.worldCoordinateHelper.wraps && detailsProvider.allowWorldCopies()) {\n        // Render copy of the globe thrice on both sides\n        for (let i = 1; i <= 3; i++) {\n            stack.push(newRootTile(-i));\n            stack.push(newRootTile(i));\n        }\n    }\n\n    stack.push(newRootTile(0));\n\n    while (stack.length > 0) {\n        const it = stack.pop();\n        const x = it.x;\n        const y = it.y;\n        let fullyVisible = it.fullyVisible;\n        const tileID = {x, y, z: it.zoom};\n        const boundingVolume = detailsProvider.getTileBoundingVolume(tileID, it.wrap, elevationForTileCulling, options);\n\n        // Visibility of a tile is not required if any of its ancestor is fully visible\n        if (!fullyVisible) {\n            const intersectResult = isTileVisible(frustum, boundingVolume, plane);\n\n            if (intersectResult === IntersectionResult.None)\n                continue;\n\n            fullyVisible = intersectResult === IntersectionResult.Full;\n        }\n\n        const distToTile2d = detailsProvider.distanceToTile2d(cameraCoord.x, cameraCoord.y, tileID, boundingVolume);\n\n        let thisTileDesiredZ = desiredZ;\n        if (allowVariableZoom) {\n            const tileZoomFunc = options.calculateTileZoom || defaultCalculateTileZoom;\n            thisTileDesiredZ = tileZoomFunc(transform.zoom + scaleZoom(transform.tileSize / options.tileSize),\n                distToTile2d,\n                distanceZ,\n                distanceToCenter3d,\n                transform.fov);\n        }\n        thisTileDesiredZ = (options.roundZoom ? Math.round : Math.floor)(thisTileDesiredZ);\n        thisTileDesiredZ = Math.max(0, thisTileDesiredZ);\n        const z = Math.min(thisTileDesiredZ, maxZoom);\n\n        // We need to compute a valid wrap value for the tile to keep globe compatibility with mercator\n        it.wrap = detailsProvider.getWrap(centerCoord, tileID, it.wrap);\n\n        // Have we reached the target depth?\n        if (it.zoom >= z) {\n            if (it.zoom < minZoom) {\n                continue;\n            }\n            const dz = nominalZ - it.zoom;\n            const dx = cameraPoint[0] - 0.5 - (x << dz);\n            const dy = cameraPoint[1] - 0.5 - (y << dz);\n            const overscaledZ = options.reparseOverscaled ? Math.max(it.zoom, thisTileDesiredZ) : it.zoom;\n            result.push({\n                tileID: new OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y),\n                distanceSq: vec2.sqrLen([centerPoint[0] - 0.5 - x, centerPoint[1] - 0.5 - y]),\n                // this variable is currently not used, but may be important to reduce the amount of loaded tiles\n                tileDistanceToCamera: Math.sqrt(dx * dx + dy * dy)\n            });\n            continue;\n        }\n\n        for (let i = 0; i < 4; i++) {\n            const childX = (x << 1) + (i % 2);\n            const childY = (y << 1) + (i >> 1);\n            const childZ = it.zoom + 1;\n            stack.push({zoom: childZ, x: childX, y: childY, wrap: it.wrap, fullyVisible});\n        }\n    }\n\n    return result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID);\n}\n", "import {now} from '../util/time_control.ts';\nimport {getEdgeTiles} from '../util/util.ts';\nimport {FadingDirections, FadingRoles, type Tile} from './tile.ts';\n\nimport type {OverscaledTileID} from './tile_id.ts';\nimport type {InViewTiles} from './tile_manager_in_view_tiles.ts';\n\nexport function isRasterType(type: string): boolean {\n    return type === 'raster' || type === 'image' || type === 'video';\n}\n\n/**\n * Designate fading bases and parents using a many-to-one relationship where the lower children fade in/out\n * with their parents. Raster shaders are not currently designed for a one-to-many fade relationship.\n *\n * Tiles that are candidates for fading out must be loaded and rendered tiles, as loading a tile to then\n * fade it out would not appear smoothly. The first source of truth for tile fading always starts at the\n * ideal tile, which continually changes on map adjustment. The state of the previously rendered ideal\n * tile plane indicates which direction to fade each part of the newer ideal plane (with varying z).\n *\n * For a pitched map, the back of the map can have decreasing zooms while the front can have increasing zooms.\n * Fade logic must therefore adapt dynamically based on the previously rendered ideal tile set.\n */\nexport function updateFadingTiles(\n    inViewTiles: InViewTiles,\n    idealTileIDs: OverscaledTileID[], \n    retain: Record<string, OverscaledTileID>,\n    maxFadingAncestorLevels: number,\n    sourceMinZoom: number,\n    sourceMaxZoom: number,\n    rasterFadeDuration: number): void {\n    const currentTime: number = now();\n    const edgeTileIDs: Set<OverscaledTileID> = getEdgeTiles(idealTileIDs);\n\n    for (const idealID of idealTileIDs) {\n        const idealTile = inViewTiles.getTileById(idealID.key);\n\n        // reset any previously departing(ed) tiles that are now ideal tiles\n        if (idealTile.fadingDirection === FadingDirections.Departing || idealTile.fadeOpacity === 0) {\n            idealTile.resetFadeLogic();\n        }\n\n        const parentIsFader = updateFadingAncestor(inViewTiles, idealTile, retain, currentTime, maxFadingAncestorLevels, sourceMinZoom, rasterFadeDuration);\n        if (parentIsFader) continue;\n\n        const childIsFader = updateFadingDescendents(inViewTiles, idealTile, retain, currentTime, sourceMaxZoom, rasterFadeDuration);\n        if (childIsFader) continue;\n\n        const edgeIsFader = updateFadingEdge(idealTile, edgeTileIDs, currentTime, rasterFadeDuration);\n        if (edgeIsFader) continue;\n\n        // for all remaining non-fading ideal tiles reset the fade logic\n        idealTile.resetFadeLogic();\n    }\n}\n\n/**\n * Many-to-one cross-fade. Set 4 ideal tiles as the fading base for a rendered parent tile\n * as the fading parent. Here the parent is fading out and the ideal tile is fading in.\n *\n * Parent tile - fading out                                ■                                -- Fading Parent\n *                                   ┌──────────────┬──────┴───────┬──────────────┐\n * Ideal tiles - fading in           ■              ■              ■              ■         -- Base Role = Incoming\n *                             ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐\n *                             ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■\n */\nfunction updateFadingAncestor(\n    inViewTiles: InViewTiles,\n    idealTile: Tile, \n    retain: Record<string, OverscaledTileID>, \n    now: number,\n    maxFadingAncestorLevels: number,\n    sourceMinZoom: number,\n    rasterFadeDuration: number): boolean {\n    if (!idealTile.hasData()) return false;\n\n    const {tileID: idealID, fadingRole, fadingDirection, fadingParentID} = idealTile;\n    // ideal tile already has fading parent - retain and return\n    if (fadingRole === FadingRoles.Base && fadingDirection === FadingDirections.Incoming && fadingParentID) {\n        retain[fadingParentID.key] = fadingParentID;\n        return true;\n    }\n\n    // find a loaded parent tile to fade with the ideal tile\n    const minAncestorZ = Math.max(idealID.overscaledZ - maxFadingAncestorLevels, sourceMinZoom);\n    for (let ancestorZ = idealID.overscaledZ - 1; ancestorZ >= minAncestorZ; ancestorZ--) {\n        const ancestorID = idealID.scaledTo(ancestorZ);\n        const ancestorTile = inViewTiles.getLoadedTile(ancestorID);\n        if (!ancestorTile) continue;\n\n        // ideal tile (base) is fading in\n        idealTile.setCrossFadeLogic({\n            fadingRole: FadingRoles.Base,\n            fadingDirection: FadingDirections.Incoming,\n            fadingParentID: ancestorTile.tileID,  // fading out\n            fadeEndTime: now + rasterFadeDuration\n        });\n        // ancestor tile (parent) is fading out\n        ancestorTile.setCrossFadeLogic({\n            fadingRole: FadingRoles.Parent,\n            fadingDirection: FadingDirections.Departing,\n            fadeEndTime: now + rasterFadeDuration\n        });\n\n        retain[ancestorID.key] = ancestorID;\n        return true;\n    }\n    return false;\n}\n\n/**\n * Many-to-one cross-fade. Search descendents of ideal tiles as the fading base with the ideal tile\n * as the fading parent. Here the children are fading out and the ideal tile is fading in.\n *\n *                                                         ■\n *                                   ┌──────────────┬──────┴───────┬──────────────┐\n * Ideal tiles - fading in           ■              ■              ■              ■          -- Fading Parent\n *                             ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐\n * Child tiles - fading out    ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■    -- Base Role = Departing\n *\n * Try direct children first. If none found, try grandchildren. Stops at the first generation that provides a fader.\n */\nfunction updateFadingDescendents(inViewTiles: InViewTiles, idealTile: Tile, retain: Record<string, OverscaledTileID>, now: number, sourceMaxZoom: number, rasterFadeDuration: number): boolean {\n    if (!idealTile.hasData()) return false;\n\n    // search first level of descendents (4 tiles)\n    const idealChildren = idealTile.tileID.children(sourceMaxZoom);\n    let hasFader = updateFadingChildren(inViewTiles, idealTile, idealChildren, retain, now, sourceMaxZoom, rasterFadeDuration);\n    if (hasFader) return true;\n\n    // search second level of descendents (16 tiles)\n    for (const childID of idealChildren) {\n        const grandChildIDs = childID.children(sourceMaxZoom);\n        if (updateFadingChildren(inViewTiles, idealTile, grandChildIDs, retain, now, sourceMaxZoom, rasterFadeDuration)) {\n            hasFader = true;\n        }\n    }\n\n    return hasFader;\n}\n\nfunction updateFadingChildren(\n    inViewTiles: InViewTiles,\n    idealTile: Tile, \n    childIDs: OverscaledTileID[], \n    retain: Record<string, OverscaledTileID>, \n    now: number, \n    sourceMaxZoom: number,\n    rasterFadeDuration: number): boolean {\n    if (childIDs[0].overscaledZ > sourceMaxZoom) return false;\n    let foundFader = false;\n\n    // find loaded child tiles to fade with the ideal tile\n    for (const childID of childIDs) {\n        const childTile = inViewTiles.getLoadedTile(childID);\n        if (!childTile) continue;\n\n        const {fadingRole, fadingDirection, fadingParentID} = childTile;\n        if (fadingRole !== FadingRoles.Base || fadingDirection !== FadingDirections.Departing || !fadingParentID) {\n            // child tile (base) is fading out\n            childTile.setCrossFadeLogic({\n                fadingRole: FadingRoles.Base,\n                fadingDirection: FadingDirections.Departing,\n                fadingParentID: idealTile.tileID,\n                fadeEndTime: now + rasterFadeDuration\n            });\n            // ideal tile (parent) is fading in\n            idealTile.setCrossFadeLogic({\n                fadingRole: FadingRoles.Parent,\n                fadingDirection: FadingDirections.Incoming,\n                fadeEndTime: now + rasterFadeDuration\n            });\n        }\n\n        retain[childID.key] = childID;\n        foundFader = true;\n    }\n\n    return foundFader;\n}\n\n/**\n * One-to-one self fading for unloaded edge tiles (for panning sideways on map). for loading tiles over gaps it feels\n * more natural for them to fade in, however if they are already loaded/cached then there is no need to fade as map will\n * look cohesive with no gaps. Note that draw_raster determines fade priority, as many-to-one fade supersedes edge fading.\n */\nfunction updateFadingEdge(idealTile: Tile, edgeTileIDs: Set<OverscaledTileID>, now: number, rasterFadeDuration: number): boolean {\n    const idealID: OverscaledTileID = idealTile.tileID;\n\n    // tile is already self fading\n    if (idealTile.selfFading) {\n        return true;\n    }\n\n    // fading not needed for tiles that are already loaded\n    if (idealTile.hasData()) {\n        return false;\n    }\n\n    // enable fading for loading edges with no data\n    if (edgeTileIDs.has(idealID)) {\n        const fadeEndTime = now + rasterFadeDuration;\n        idealTile.setSelfFadeLogic(fadeEndTime);\n        return true;\n    }\n\n    return false;\n}\n\nexport function hasRasterTransition(inViewTiles: InViewTiles, rasterFadeDuration: number): boolean {\n    if (rasterFadeDuration <= 0) {\n        return false;\n    }\n    const currentTime = now();\n    for (const tile of inViewTiles.getAllTiles()) {\n        if (tile.fadeEndTime >= currentTime) {\n            return true;\n        }\n    }\n    return false;\n}", "import type {Tile} from './tile.ts';\nimport type {InViewTiles} from './tile_manager_in_view_tiles.ts';\n\n/**\n * For raster terrain source, backfill DEM to eliminate visible tile boundaries\n */\nexport function backfillDEM(tile: Tile, inViewTiles: InViewTiles): void {\n    const renderables = inViewTiles.getRenderableIds();\n    for (const borderId of renderables) {\n        if (!tile.neighboringTiles?.[borderId]) {\n            continue;\n        }\n        const borderTile = inViewTiles.getTileById(borderId);\n        if (!tile.neighboringTiles[borderId].backfilled) {\n            fillBorder(tile, borderTile);\n        }\n        if (borderTile.neighboringTiles?.[tile.tileID.key]?.backfilled) {\n            continue;\n        }\n        fillBorder(borderTile, tile);\n    }\n}\n\nfunction fillBorder(tile: Tile, borderTile: Tile) {\n    tile.needsHillshadePrepare = true;\n    tile.needsTerrainPrepare = true;\n    tile.needsColorReliefPrepare = true;\n    let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;\n    const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;\n    const dim = Math.pow(2, tile.tileID.canonical.z);\n    const borderId = borderTile.tileID.key;\n    if (dx === 0 && dy === 0) return;\n\n    if (Math.abs(dy) > 1) {\n        return;\n    }\n    if (Math.abs(dx) > 1) {\n        // Adjust the delta coordinate for world wraparound.\n        if (Math.abs(dx + dim) === 1) {\n            dx += dim;\n        } else if (Math.abs(dx - dim) === 1) {\n            dx -= dim;\n        }\n    }\n    if (!borderTile.dem || !tile.dem) return;\n    tile.dem.backfillBorder(borderTile.dem, dx, dy);\n    if (tile.neighboringTiles?.[borderId]) {\n        tile.neighboringTiles[borderId].backfilled = true;\n    }\n}\n\n", "import Point from '@mapbox/point-geometry';\nimport {compareTileId, type OverscaledTileID} from './tile_id.ts';\n\nimport type {LayerFeatureStates} from '../source/source_state.ts';\nimport type {Tile} from './tile.ts';\nimport type {Style} from '../style/style.ts';\n\nexport class InViewTiles {\n    private _tiles: Record<string, Tile> = {};\n\n    public handleWrapJump(wrapDelta: number): void {\n        const tiles: Record<string, Tile> = {};\n        for (const id in this._tiles) {\n            const tile = this._tiles[id];\n            tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);\n            tiles[tile.tileID.key] = tile;\n        }\n        this._tiles = tiles;\n    }\n\n    public setFeatureState(featuresChanged: LayerFeatureStates, style: Style, revision: number): void {\n        for (const id in this._tiles) {\n            const tile = this._tiles[id];\n            tile.setFeatureState(featuresChanged, style, revision);\n        }\n    }\n\n    public getAllTiles(): Tile[] {\n        return Object.values(this._tiles);\n    }\n\n    public getAllIds(sorted = false): string[] {\n        if (sorted) {\n            return Object.values(this._tiles).map(tile => tile.tileID).sort(compareTileId).map(id => id.key);\n        }\n        return Object.keys(this._tiles);\n    }\n\n    public getTileById(key: string): Tile | undefined {\n        return this._tiles[key];\n    }\n\n    public setTile(key: string, tile: Tile): void {\n        this._tiles[key] = tile;\n    }\n\n    public deleteTileById(key: string): void {\n        delete this._tiles[key];\n    }\n\n    /**\n     * Get a currently loaded tile.\n     * - a cached tile is not a loaded tile\n     * @returns the tile if it's in view and had data, null otherwise.\n     */\n    public getLoadedTile(tileID: OverscaledTileID): Tile | null {\n        const tile = this.getTileById(tileID.key);\n        if (tile?.hasData()) {\n            return tile;\n        }\n        return null;\n    }\n\n    public isIdRenderable(id: string, symbolLayer: boolean = false): boolean {\n        return this.getTileById(id)?.isRenderable(symbolLayer);\n    }\n\n    public getRenderableIds(bearingInRadians: number = 0, symbolLayer?: boolean): string[] {\n        const renderables: Tile[] = [];\n        for (const id of this.getAllIds()) {\n            if (this.isIdRenderable(id, symbolLayer)) {\n                renderables.push(this.getTileById(id));\n            }\n        }\n        if (symbolLayer) {\n            return renderables.sort((a_: Tile, b_: Tile) => {\n                const a = a_.tileID;\n                const b = b_.tileID;\n                const rotatedA = (new Point(a.canonical.x, a.canonical.y))._rotate(-bearingInRadians);\n                const rotatedB = (new Point(b.canonical.x, b.canonical.y))._rotate(-bearingInRadians);\n                return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;\n            }).map(tile => tile.tileID.key);\n        }\n        return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key);\n    }\n}", "import {create as createSource} from '../source/source.ts';\nimport {Tile} from './tile.ts';\nimport {ErrorEvent, Evented} from '../util/evented.ts';\nimport {ensureError} from '../util/util.ts';\nimport {TileCache} from './tile_cache.ts';\nimport {MercatorCoordinate} from '../geo/mercator_coordinate.ts';\nimport {EXTENT} from '../data/extent.ts';\nimport {now} from '../util/time_control.ts';\nimport {OverscaledTileID} from './tile_id.ts';\nimport {SourceFeatureState} from '../source/source_state.ts';\nimport {config} from '../util/config.ts';\nimport {coveringTiles, coveringZoomLevel} from '../geo/projection/covering_tiles.ts';\nimport {Bounds} from '../geo/bounds.ts';\nimport {EXTENT_BOUNDS} from '../data/extent_bounds.ts';\nimport {GEOJSON_TILE_LAYER_NAME} from '../data/feature_index.ts';\nimport {hasRasterTransition, isRasterType, updateFadingTiles} from './tile_manager_raster.ts';\nimport {backfillDEM} from './tile_manager_raster_dem.ts';\nimport {InViewTiles} from './tile_manager_in_view_tiles.ts';\nimport {MapSourceDataEvent, type SourceEventType} from '../ui/events.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Context} from '../webgl/context.ts';\nimport type {Source} from '../source/source.ts';\nimport type {Map} from '../ui/map.ts';\nimport type {Style} from '../style/style.ts';\nimport type {Dispatcher} from '../util/dispatcher.ts';\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\nimport type {TileState} from './tile.ts';\nimport type {FeatureState, ICanonicalTileID, SourceSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Terrain} from '../render/terrain.ts';\nimport type {CanvasSourceSpecification} from '../source/canvas_source.ts';\nimport type {LoadTileResult} from '../source/vector_tile_source.ts';\nimport type {SymbolStyleLayer} from '../style/style_layer/symbol_style_layer.ts';\nimport type {SymbolBucket} from '../data/bucket/symbol_bucket.ts';\n\ntype TileResult = {\n    tile: Tile;\n    tileID: OverscaledTileID;\n    queryGeometry: Point[];\n    cameraQueryGeometry: Point[];\n    scale: number;\n};\n\n/**\n * @internal\n * `TileManager` is responsible for\n *\n *  - creating an instance of `Source`\n *  - caching tiles loaded from an instance of `Source`\n *  - handling incoming source data events events from `Map` and coordinating updates\n *  - providing the current renderable tile coordinates to the `Painter`\n *  - loading the tiles needed to render a given viewport\n *  - retaining the tiles needed as substitutes for pending loading tiles\n *  - retaining the tiles needed for fading between parents and children (for raster sources)\n *  - reloading tiles when source data or dependencies change\n *  - handling tile expiration and refresh timers\n *  - unloading cached tiles not needed to render a given viewport\n *  - managing tile state and feature state\n */\nexport class TileManager extends Evented<SourceEventType> {\n    id: string;\n    dispatcher: Dispatcher;\n    map: Map;\n    style: Style;\n\n    _source: Source;\n\n    /**\n     * @internal\n     * signifies that the TileJSON is loaded if applicable.\n     * if the source type does not come with a TileJSON, the flag signifies the\n     * source data has loaded (i.e geojson has been tiled on the worker and is ready)\n     */\n    _sourceLoaded: boolean;\n    _maxContentElevationSeen: number = 0;\n\n    /**\n     * @internal\n     * signifies that the source itself failed to load and had no pending loads, so `loaded()` stops waiting for it\n     * until it starts loading again. A tile that fails does not set it, since `loaded()` already counts a failed tile as done.\n     */\n    _sourceErrored: boolean;\n    _inViewTiles: InViewTiles;\n    _prevLng: number;\n    _outOfViewCache: TileCache;\n    _timers: Record<string, ReturnType<typeof setTimeout>>;\n    _maxTileCacheSize: number;\n    _maxTileCacheZoomLevels: number;\n    _paused: boolean;\n    _shouldReloadOnResume: boolean;\n    transform: IReadonlyTransform;\n    terrain: Terrain;\n    used: boolean;\n    usedForTerrain: boolean;\n    tileSize: number;\n    _state: SourceFeatureState;\n    _didEmitContent: boolean;\n    _updated: boolean;\n    _rasterFadeDuration: number;\n    _maxFadingAncestorLevels: number;\n\n    static maxUnderzooming: number = 10;\n    static maxOverzooming: number = 3;\n\n    constructor(id: string, options: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher) {\n        super();\n        this.id = id;\n        this.dispatcher = dispatcher;\n\n        this.on('data', (e: MapSourceDataEvent) => { this._dataHandler(e); });\n\n        this.on('dataloading', () => {\n            this._sourceErrored = false;\n        });\n\n        this.on('error', (e: ErrorEvent & {tile?: Tile}) => {\n            if (!e.tile) this._sourceErrored = this._source.loaded();\n        });\n\n        this._source = createSource(id, options, dispatcher, this);\n\n        this._inViewTiles = new InViewTiles();\n        this._outOfViewCache = new TileCache(0, (tile) => this._unloadTile(tile));\n        this._timers = {};\n        this._maxTileCacheSize = null;\n        this._maxTileCacheZoomLevels = null;\n        this._rasterFadeDuration = 0;\n        this._maxFadingAncestorLevels = 5;\n\n        this._state = new SourceFeatureState();\n        this._didEmitContent = false;\n        this._updated = false;\n    }\n\n    onAdd(map: Map): void {\n        this.map = map;\n        this._maxTileCacheSize = map ? map._maxTileCacheSize : null;\n        this._maxTileCacheZoomLevels = map ? map._maxTileCacheZoomLevels : null;\n        if (this._source?.onAdd) {\n            this._source.onAdd(map);\n        }\n    }\n\n    onRemove(map: Map): void {\n        for (const tile of this._inViewTiles.getAllTiles()) {\n            tile.unloadVectorData();\n        }\n        this.clearTiles();\n        if (this._source?.onRemove) {\n            this._source.onRemove(map);\n        }\n        this._inViewTiles = new InViewTiles();\n    }\n\n    /**\n     * Return true if no tile data is pending, tiles will not change unless\n     * an additional API call is received.\n     */\n    loaded(): boolean {\n        if (this._sourceErrored) { return true; }\n        if (!this._sourceLoaded) { return false; }\n        if (!this._source.loaded()) { return false; }\n        if ((this.used !== undefined || this.usedForTerrain !== undefined) && !this.used && !this.usedForTerrain) { return true; }\n        // do not consider as loaded if the update hasn't been called yet (we do not know if we will have any tiles to fetch)\n        if (!this._updated) { return false; }\n\n        for (const tile of this._inViewTiles.getAllTiles()) {\n            if (tile.state !== 'loaded' && tile.state !== 'errored')\n                return false;\n        }\n        return true;\n    }\n\n    getSource(): Source {\n        return this._source;\n    }\n\n    getState(): SourceFeatureState {\n        return this._state;\n    }\n\n    pause(): void {\n        this._paused = true;\n    }\n\n    resume(): void {\n        if (!this._paused) return;\n        const shouldReload = this._shouldReloadOnResume;\n        this._paused = false;\n        this._shouldReloadOnResume = false;\n        if (shouldReload) this.reload();\n        if (this.transform) this.update(this.transform, this.terrain);\n    }\n\n    async _loadTile(tile: Tile, id: string, state: TileState, hadData: boolean): Promise<void> {\n        try {\n            const result = await this._source.loadTile(tile) as LoadTileResult;\n            this._tileLoaded(tile, id, state, hadData, result);\n        } catch (err) {\n            tile.state = 'errored';\n\n            if (err.status !== 404) {\n                this._source.fire(new ErrorEvent(ensureError(err), {tile}));\n            } else {\n                // continue to try loading parent/children tiles if a tile doesn't exist (404)\n                this.update(this.transform, this.terrain);\n            }\n        }\n    }\n\n    _unloadTile(tile: Tile): void {\n        if (this._source.unloadTile)\n            this._source.unloadTile(tile);\n    }\n\n    _abortTile(tile: Tile): void {\n        if (this._source.abortTile)\n            this._source.abortTile(tile);\n\n        this._source.fire(new MapSourceDataEvent('dataabort', {tile, coord: tile.tileID}));\n    }\n\n    serialize(): any {\n        return this._source.serialize();\n    }\n\n    prepare(context: Context): void {\n        if  (this._source.prepare) {\n            this._source.prepare();\n        }\n\n        this._state.coalesceChanges(this._inViewTiles, this.style);\n        for (const tile of this._inViewTiles.getAllTiles()) {\n            tile.upload(context);\n            tile.prepare(this.map.style.imageManager);\n        }\n    }\n\n    /**\n     * Return all tile ids ordered with z-order, and cast to numbers\n     */\n    getIds(): string[] {\n        return this._inViewTiles.getAllIds(true);\n    }\n\n    getRenderableIds(symbolLayer?: boolean): string[] {\n        return this._inViewTiles.getRenderableIds(this.transform?.bearingInRadians, symbolLayer);\n    }\n\n    hasRenderableParent(tileID: OverscaledTileID): boolean {\n        const parentZ = tileID.overscaledZ - 1;\n        if (parentZ >= this._source.minzoom) {\n            const parentTile = this.getLoadedTile(tileID.scaledTo(parentZ));\n            if (parentTile) {\n                return this._inViewTiles.isIdRenderable(parentTile.tileID.key);\n            }\n        }\n        return false;\n    }\n\n    /**\n     * Reload tiles based on the current state of the source.\n     * @param sourceDataChanged - If `true`, reload all tiles using a state of 'expired' (errored tiles use 'loading' since they have nothing to show yet), otherwise reload only non-errored tiles using state of 'reloading'.\n     * @param shouldReloadTileOptions - Set of options associated with a `MapSourceDataChangedEvent` that can be passed back to the associated `Source` determine whether a tile should be reloaded.\n     */\n    reload(\n        sourceDataChanged?: boolean,\n        shouldReloadTileOptions: any = undefined\n    ): void {\n        if (this._paused) {\n            this._shouldReloadOnResume = true;\n            return;\n        }\n\n        this._outOfViewCache.reset();\n\n        for (const id of this._inViewTiles.getAllIds()) {\n            const tile = this._inViewTiles.getTileById(id);\n            if (shouldReloadTileOptions && !this._source.shouldReloadTile(tile, shouldReloadTileOptions)) {\n                continue;\n            } else if (sourceDataChanged) {\n                this._reloadTile(id, tile.state === 'errored' ? 'loading' : 'expired');\n            } else if (tile.state !== 'errored') {\n                this._reloadTile(id, 'reloading');\n            }\n        }\n    }\n\n    async _reloadTile(id: string, state: TileState): Promise<void> {\n        const tile = this._inViewTiles.getTileById(id);\n\n        // this potentially does not address all underlying\n        // issues https://github.com/mapbox/mapbox-gl-js/issues/4252\n        // - hard to tell without repro steps\n        if (!tile) return;\n\n        const hadData = tile.hasData();\n\n        // The difference between \"loading\" tiles and \"reloading\" or \"expired\"\n        // tiles is that \"reloading\"/\"expired\" tiles are \"renderable\".\n        // Therefore, a \"loading\" tile cannot become a \"reloading\" tile without\n        // first becoming a \"loaded\" tile.\n        if (tile.state !== 'loading') {\n            tile.state = state;\n        }\n        await this._loadTile(tile, id, state, hadData);\n    }\n\n    _tileLoaded(tile: Tile, id: string, previousState: TileState, hadData: boolean, result: LoadTileResult): void {\n        // If the tile was already showing do not restart its fade-in animation\n        if (!hadData) {\n            tile.timeAdded = now();\n            // Since self-fading applies to unloaded tiles, fadeEndTime must be updated upon load\n            if (tile.selfFading) {\n                tile.fadeEndTime = tile.timeAdded + this._rasterFadeDuration;\n            }\n        }\n\n        if (previousState === 'expired') tile.refreshedUponExpiration = true;\n        this._setTileReloadTimer(id, tile);\n\n        if (result?.unmodified) return;\n\n        if (this.getSource().type === 'raster-dem' && tile.dem) {\n            backfillDEM(tile, this._inViewTiles);\n        }\n        // Reset feature state revision so initializeTileState re-applies\n        // feature state to the tile's new bucket data after a reload.\n        tile.featureStateRevision = -1;\n        this._state.initializeTileState(tile, this.style);\n\n        if (!tile.aborted) {\n            this._source.fire(new MapSourceDataEvent('data', {tile, coord: tile.tileID}));\n        }\n    }\n    /**\n     * Get a specific tile by TileID\n     */\n    getTile(tileID: OverscaledTileID): Tile {\n        return this.getTileByID(tileID.key);\n    }\n\n    /**\n     * Get a specific tile by id\n     */\n    getTileByID(id: string): Tile | undefined {\n        return this._inViewTiles.getTileById(id);\n    }\n\n    /**\n     * Retain the uppermost loaded children of each provided target tile, within a variable covering zoom range.\n     *\n     * On pitched maps, different parts of the screen show different zoom levels simultaneously.\n     * Ideal tiles are generated using coveringTiles() above, which returns the ideal tile set for\n     * the current pitched plane, which can carry tiles of varying zooms (overscaledZ).\n     * See: https://maplibre.org/maplibre-gl-js/docs/examples/level-of-detail-control/\n     *\n     * A fixed `maxCoveringZoom` on a pitched map would incorrectly intersect with some\n     * ideal tiles and cause distant high-pitch tiles to skip their uppermost children.\n     *\n     * To solve this, we calculate the max covering zoom for each ideal tile separately using its\n     * `overscaledZ`. This effectively makes the \"max covering zoom plane\" parallel to the\n     * \"ideal tile plane,\" ensuring that we correctly capture the uppermost children\n     * of each ideal tile across the pitched view.\n     *\n     * Analogy: imagine two sheets of paper in 3D space:\n     *   - one sheet = ideal tiles at varying overscaledZ\n     *   - the second sheet = maxCoveringZoom\n     *\n     * @param retainTileMap - this parameters will be updated with the child tiles to keep\n     * @param idealTilesWithoutData - which of the ideal tiles currently does not have loaded data\n     * @return a set of tiles that need to be loaded\n     */\n    _retainLoadedChildren(retainTileMap: Record<string, OverscaledTileID>, idealTilesWithoutData: Set<OverscaledTileID>): Set<OverscaledTileID> {\n        const loadedDescendents: Record<string, Tile[]> = this._getLoadedDescendents(idealTilesWithoutData);\n        const incomplete = new Set<OverscaledTileID>();\n\n        // retain the uppermost descendents of target tiles\n        for (const targetID of idealTilesWithoutData) {\n            const descendents = loadedDescendents[targetID.key];\n            if (!descendents?.length) {\n                incomplete.add(targetID);\n                continue;\n            }\n\n            // find descendents within the max covering zoom range\n            const maxCoveringZoom = targetID.overscaledZ + TileManager.maxOverzooming;\n            const candidates = descendents.filter(t => t.tileID.overscaledZ <= maxCoveringZoom);\n            if (!candidates.length) {\n                incomplete.add(targetID);\n                continue;\n            }\n\n            // retain the uppermost descendents in the topmost zoom below the target tile\n            const topZoom = Math.min(...candidates.map(t => t.tileID.overscaledZ));\n            const topIDs = candidates.filter(t => t.tileID.overscaledZ === topZoom).map(t => t.tileID);\n            for (const tileID of topIDs) {\n                retainTileMap[tileID.key] = tileID;\n            }\n\n            //determine if the retained generation is fully covered\n            if (!this._areDescendentsComplete(topIDs, topZoom, targetID.overscaledZ)) {\n                incomplete.add(targetID);\n            }\n        }\n\n        return incomplete;\n    }\n\n    /**\n     * Return dictionary of qualified loaded descendents for each provided target tile id\n     */\n    _getLoadedDescendents(targetTileIDs: Set<OverscaledTileID>): Record<string, Tile[]> {\n        const loadedDescendents: Record<string, Tile[]> = {};\n\n        // enumerate current tiles and find the loaded descendents of each target tile\n        for (const tile of this._inViewTiles.getAllTiles().filter(tile => tile.hasData())) {\n            // determine if the loaded tile (hasData) is a qualified descendent of any target tile\n            for (const targetID of targetTileIDs) {\n                if (tile.tileID.isChildOf(targetID)) {\n                    loadedDescendents[targetID.key] ||= [];\n                    loadedDescendents[targetID.key].push(tile);\n                }\n            }\n        }\n\n        return loadedDescendents;\n    }\n\n    /**\n     * Determine if tile ids fully cover the current generation.\n     * - 1st generation: need 4 children or 1 overscaled child\n     * - 2nd generation: need 16 children or 1 overscaled child\n     */\n    _areDescendentsComplete(generationIDs: OverscaledTileID[], generationZ: number, ancestorZ: number): boolean {\n        //if overscaled, seeking 1 tile at generationZ, otherwise seeking a power of 4 for each descending Z\n        if (generationIDs.length === 1 && generationIDs[0].isOverscaled()) {\n            return generationIDs[0].overscaledZ === generationZ;\n        } else {\n            const expectedTiles = Math.pow(4, generationZ - ancestorZ);  //4, 16, 64 (for first 3 gens)\n            return expectedTiles === generationIDs.length;\n        }\n    }\n\n    /**\n     * Get a currently loaded tile.\n     * - a cached tile is not a loaded tile\n     * @returns the tile if it's in view and had data, null otherwise.\n     */\n    getLoadedTile(tileID: OverscaledTileID): Tile | null {\n        return this._inViewTiles.getLoadedTile(tileID);\n    }\n\n    /**\n     * Resizes the tile cache based on the current viewport's size\n     * or the maxTileCacheSize option passed during map creation\n     *\n     * Larger viewports use more tiles and need larger caches. Larger viewports\n     * are more likely to be found on devices with more memory and on pages where\n     * the map is more important.\n     */\n    updateCacheSize(transform: IReadonlyTransform): void {\n        const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1;\n        const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1;\n        const approxTilesInView = widthInTiles * heightInTiles;\n        const commonZoomRange = this._maxTileCacheZoomLevels === null ?\n            config.MAX_TILE_CACHE_ZOOM_LEVELS : this._maxTileCacheZoomLevels;\n        const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);\n        const maxSize = typeof this._maxTileCacheSize === 'number' ?\n            Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;\n\n        this._outOfViewCache.setMaxSize(maxSize);\n    }\n\n    handleWrapJump(lng: number): void {\n        // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify\n        // which copy of the world the tile belongs to. For example, at `lng: 10` you\n        // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1.\n        //\n        // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect\n        // to see the same thing on the screen (370 degrees and 10 degrees is the same\n        // place in the world) but all the TileIDs will have different wrap values.\n        //\n        // In order to make this transition seamless, we calculate the rounded difference of\n        // \"worlds\" between the last frame and the current frame. If the map panned by\n        // a world, then we can assign all the tiles new TileIDs with updated wrap values.\n        // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered\n        // in a different position.\n        //\n        // This enables us to reuse the tiles at more ideal locations and prevent flickering.\n        const prevLng = this._prevLng === undefined ? lng : this._prevLng;\n        const lngDifference = lng - prevLng;\n        const worldDifference = lngDifference / 360;\n        const wrapDelta = Math.round(worldDifference);\n        this._prevLng = lng;\n\n        if (wrapDelta) {\n            this._inViewTiles.handleWrapJump(wrapDelta);\n            this._resetTileReloadTimers();\n        }\n    }\n\n    /**\n     * The highest elevation this source's symbols may reach, in meters: `symbol-height-offset`\n     * constants read from the visible symbol layers, data-driven maxima tracked by the loaded\n     * buckets at layout time. Only data-driven layers scan the loaded tiles, so styles without\n     * them pay nothing beyond the layer loop. The value is a high-water mark: a maximum seen once is kept even\n     * after its tile unloads, otherwise dropping the tile would also drop the reason to keep it,\n     * and the tile could not come back while its content is still visible. The mark resets with\n     * the tiles in `clearTiles`.\n     */\n    _updateMaxContentElevation(): number {\n        let maxElevation = this._maxContentElevationSeen;\n        const layers = this.map?.style?._layers;\n        if (!layers) return maxElevation;\n        const tiles = this._inViewTiles.getAllTiles();\n        for (const layerId in layers) {\n            const layer = layers[layerId];\n            if (layer.type !== 'symbol' || layer.source !== this.id || layer.isHidden(this.transform.zoom)) continue;\n            const symbolLayer = layer as SymbolStyleLayer;\n            if (!symbolLayer.layout) continue;\n            const heightOffset = symbolLayer.layout.get('symbol-height-offset');\n            maxElevation = Math.max(maxElevation, heightOffset.constantOr(0));\n            if (heightOffset.isConstant()) continue;\n            for (const tile of tiles) {\n                const bucket = tile.getBucket(layer) as SymbolBucket;\n                if (bucket && bucket.maxHeightOffset > maxElevation) {\n                    maxElevation = bucket.maxHeightOffset;\n                }\n            }\n        }\n        this._maxContentElevationSeen = maxElevation;\n        return maxElevation;\n    }\n\n    /**\n     * Removes tiles that are outside the viewport and adds new tiles that\n     * are inside the viewport.\n     */\n    update(transform: IReadonlyTransform, terrain?: Terrain): void {\n        if (!this._sourceLoaded || this._paused) {\n            return;\n        }\n        this.transform = transform;\n        this.terrain = terrain;\n\n        this.updateCacheSize(transform);\n        if (this.transform.worldCoordinateHelper.wraps) {\n            this.handleWrapJump(this.transform.center.lng);\n        }\n\n        let idealTileIDs: OverscaledTileID[];\n\n        if (!this.used && !this.usedForTerrain) {\n            idealTileIDs = [];\n        } else if (this._source.tileID) { // image source\n            idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID)\n                .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));\n        } else {\n            idealTileIDs = coveringTiles(transform, {\n                tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize,\n                minzoom: this._source.minzoom,\n                maxzoom: this._source.type === 'vector' && this.map._zoomLevelsToOverscale !== undefined\n                    ? Math.max(this._source.maxzoom, transform.maxZoom - this.map._zoomLevelsToOverscale)\n                    : this._source.maxzoom,\n                roundZoom: this.usedForTerrain ? false : this._source.roundZoom,\n                reparseOverscaled: this._source.reparseOverscaled,\n                terrain,\n                calculateTileZoom: this._source.calculateTileZoom,\n                maxContentElevation: this._updateMaxContentElevation(),\n            });\n\n            if (this._source.hasTile) { // tile should be in bounds\n                idealTileIDs = idealTileIDs.filter((coord) => this._source.hasTile(coord));\n            }\n        }\n\n        // When tilemanager is used for terrain also load parent tiles for complete rendering of 3d terrain levels\n        if (this.usedForTerrain) {\n            idealTileIDs = this._addTerrainIdealTiles(idealTileIDs);\n        }\n\n        const noPendingDataEmissions = idealTileIDs.length === 0 && !this._updated && this._didEmitContent;\n        this._updated = true;\n        // if we won't have any tiles to fetch and content is already emitted\n        // there will be no more data emissions, so we need to emit the event with isSourceLoaded = true\n        if (noPendingDataEmissions) {\n            this.fire(new MapSourceDataEvent('data', {sourceDataType: 'idle', sourceId: this.id}));\n        }\n\n        // Retain is a list of tiles that we shouldn't delete, even if they are not\n        // the most ideal tile for the current viewport. This may include tiles like\n        // parent or child tiles that are *already* loaded.\n        const zoom: number = coveringZoomLevel(transform, this._source);\n        const retain: Record<string, OverscaledTileID> = this._updateRetainedTiles(idealTileIDs, zoom);\n\n        // enable fading for raster source except when using terrain which doesn't currently support fading\n        const isRaster = isRasterType(this._source.type);\n        if (isRaster && this._rasterFadeDuration > 0 && !terrain) {\n            updateFadingTiles(this._inViewTiles, idealTileIDs, retain, this._maxFadingAncestorLevels, this._source.minzoom, this._source.maxzoom, this._rasterFadeDuration);\n        }\n\n        // clean up non-retained tiles that are no longer needed\n        if (isRaster) {\n            this._cleanUpRasterTiles(retain);\n        } else {\n            this._cleanUpVectorTiles(retain);\n        }\n    }\n\n    /**\n     * Remove raster tiles that are no longer retained\n     */\n    _cleanUpRasterTiles(retain: Record<string, OverscaledTileID>): void {\n        for (const id of this._inViewTiles.getAllIds()) {\n            if (!retain[id]) {\n                this._removeTile(id);\n            }\n        }\n    }\n\n    /**\n     * Remove vector tiles that are no longer retained and also not needed for symbol fading\n     */\n    _cleanUpVectorTiles(retain: Record<string, OverscaledTileID>): void {\n        for (const id of this._inViewTiles.getAllIds()) {\n            const tile = this._inViewTiles.getTileById(id);\n\n            // retained - clear fade hold so if it's removed again fade timer starts fresh.\n            if (retain[id]) {\n                tile.clearSymbolFadeHold();\n                continue;\n            }\n\n            // remove non-retained tiles without symbols\n            if (!tile.hasSymbolBuckets) {\n                this._removeTile(id);\n                continue;\n            }\n\n            // for tile with symbols - hold for fade - then remove\n            if (!tile.holdingForSymbolFade()) {\n                tile.setSymbolHoldDuration(this.map._fadeDuration);\n            } else if (tile.symbolFadeFinished()) {\n                this._removeTile(id);\n            }\n        }\n    }\n\n    /**\n     * Add ideal tiles needed for 3D terrain rendering\n     */\n    _addTerrainIdealTiles(idealTileIDs: OverscaledTileID[]): OverscaledTileID[] {\n        const ancestors = [];\n\n        for (const tileID of idealTileIDs) {\n            if (tileID.canonical.z > this._source.minzoom) {\n                const parent = tileID.scaledTo(tileID.canonical.z - 1);\n                ancestors.push(parent);\n                // load very low zoom to calculate tile visibility in transform.coveringTiles and high zoom levels correct\n                const parent2 = tileID.scaledTo(Math.max(this._source.minzoom, Math.min(tileID.canonical.z, 5)));\n                ancestors.push(parent2);\n            }\n        }\n\n        return idealTileIDs.concat(ancestors);\n    }\n\n    releaseSymbolFadeTiles(): void {\n        for (const id of this._inViewTiles.getAllIds()) {\n            if (this._inViewTiles.getTileById(id).holdingForSymbolFade()) {\n                this._removeTile(id);\n            }\n        }\n    }\n\n    /**\n     * Set tiles to be retained on update of the source. For ideal tiles that do not have data, retain their loaded\n     * children so they can be displayed as substitutes pending load of each ideal tile (to reduce flickering).\n     * If no loaded children are available, fallback to seeking loaded parents as an alternative substitute.\n     */\n    _updateRetainedTiles(idealTileIDs: OverscaledTileID[], zoom: number): Record<string, OverscaledTileID> {\n        const idealTilesWithoutData = new Set<OverscaledTileID>();\n        for (const idealID of idealTileIDs) {\n            const idealTile = this._addTile(idealID);\n\n            if (!idealTile.hasData()) {\n                idealTilesWithoutData.add(idealID);\n            }\n        }\n\n        // retain the tile even if it's not loaded because it's an ideal tile.\n        const retainTileMap: Record<string, OverscaledTileID> = idealTileIDs.reduce((acc, t) => { acc[t.key] = t; return acc;}, {});\n        const tileIdsWithoutData = this._retainLoadedChildren(retainTileMap, idealTilesWithoutData);\n\n        // for remaining missing tiles with incomplete child coverage, seek a loaded parent tile\n        const checked: Record<string, boolean> = {};\n        const minCoveringZoom = Math.max(zoom - TileManager.maxUnderzooming, this._source.minzoom);\n        for (const tileID of tileIdsWithoutData) {\n            let tile = this._inViewTiles.getTileById(tileID.key);\n\n            // As we ascend up the tile pyramid of the ideal tile, we check whether the parent\n            // tile has been previously requested (and errored because we only loop over tiles with no data)\n            // in order to determine if we need to request its parent.\n            let parentWasRequested = tile?.wasRequested();\n\n            for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {\n                const parentId = tileID.scaledTo(overscaledZ);\n\n                // Break parent tile ascent if this route has been previously checked by another child.\n                if (checked[parentId.key]) break;\n                checked[parentId.key] = true;\n\n                tile = this.getTile(parentId);\n                if (!tile && parentWasRequested) {\n                    tile = this._addTile(parentId);\n                }\n                if (tile) {\n                    const hasData = tile.hasData();\n                    if (hasData || !this.map?.cancelPendingTileRequestsWhileZooming || parentWasRequested) {\n                        retainTileMap[parentId.key] = parentId;\n                    }\n                    // Save the current values, since they're the parent of the next iteration\n                    // of the parent tile ascent loop.\n                    parentWasRequested = tile.wasRequested();\n                    if (hasData) break;\n                }\n            }\n        }\n\n        return retainTileMap;\n    }\n\n    /**\n     * Add a tile, given its coordinate, to the pyramid.\n     */\n    _addTile(tileID: OverscaledTileID): Tile {\n        let tile = this._inViewTiles.getTileById(tileID.key);\n        if (tile)\n            return tile;\n\n        tile = this._outOfViewCache.getAndRemove(tileID);\n        if (tile) {\n            //reset fading logic to remove stale fading data from cache\n            tile.resetFadeLogic();\n\n            // set timer for the reloading of the tile upon expiration\n            this._setTileReloadTimer(tileID.key, tile);\n\n            // set the tileID because the cached tile could have had a different wrap value\n            tile.tileID = tileID;\n            this._state.initializeTileState(tile, this.style);\n        }\n\n        const cached = tile;\n\n        if (!tile) {\n            tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor());\n            this._loadTile(tile, tileID.key, tile.state, false);\n        }\n\n        tile.uses++;\n        this._inViewTiles.setTile(tileID.key, tile);\n        if (!cached) {\n            this._source.fire(new MapSourceDataEvent('dataloading', {tile, coord: tile.tileID}));\n        }\n\n        return tile;\n    }\n\n    /**\n     * Set a timeout to reload the tile after it expires\n     */\n    _setTileReloadTimer(id: string, tile: Tile): void {\n        this._clearTileReloadTimer(id);\n\n        const expiryTimeout = tile.getExpiryTimeout();\n        if (expiryTimeout) {\n            const reload = () => {\n                this._reloadTile(id, 'expired');\n                delete this._timers[id];\n            };\n            this._timers[id] = setTimeout(reload, expiryTimeout);\n        }\n    }\n\n    _clearTileReloadTimer(id: string): void {\n        const timeout = this._timers[id];\n        if (timeout) {\n            clearTimeout(timeout);\n            delete this._timers[id];\n        }\n    }\n\n    _resetTileReloadTimers(): void {\n        for (const id in this._timers) {\n            clearTimeout(this._timers[id]);\n            delete this._timers[id];\n        }\n        for (const id of this._inViewTiles.getAllIds()) {\n            const tile = this._inViewTiles.getTileById(id);\n            this._setTileReloadTimer(id, tile);\n        }\n    }\n\n    /**\n     * Reload any currently renderable tiles that are match one of the incoming `tileId` x/y/z\n     */\n    refreshTiles(tileIds: ICanonicalTileID[]): void {\n        for (const id of this._inViewTiles.getAllIds()) {\n            const tile = this._inViewTiles.getTileById(id);\n            if (!this._inViewTiles.isIdRenderable(id) && tile.state != 'errored') {\n                continue;\n            }\n            if (tileIds.some(tid => tid.equals(tile.tileID.canonical))) {\n                this._reloadTile(id, 'expired');\n            }\n        }\n    }\n\n    /**\n     * Remove a tile, given its id, from the pyramid\n     */\n    _removeTile(id: string): void {\n        const tile = this._inViewTiles.getTileById(id);\n        if (!tile)\n            return;\n\n        tile.uses--;\n        this._inViewTiles.deleteTileById(id);\n        this._clearTileReloadTimer(id);\n\n        if (tile.uses > 0)\n            return;\n\n        if (tile.hasData() && tile.state !== 'reloading') {\n            this._outOfViewCache.add(tile.tileID, tile, tile.getExpiryTimeout());\n        } else {\n            tile.aborted = true;\n            this._abortTile(tile);\n            this._unloadTile(tile);\n        }\n    }\n\n    /** @internal\n     * Handles incoming source data messages (i.e. after the source has been updated via a worker that has fired\n     * to map.ts data event). For sources with mutable data, the 'content' event fires when the underlying data\n     * to a source has changed. (i.e. GeoJSONSource.setData and ImageSource.setCoordinates)\n     */\n    private _dataHandler(e: MapSourceDataEvent): void {\n        if (e.dataType !== 'source') return;\n\n        if (e.sourceDataType === 'metadata') {\n            this._sourceLoaded = true;\n            return;\n        }\n\n        if (e.sourceDataType !== 'content' || !this._sourceLoaded || this._paused) {\n            return;\n        }\n\n        this.reload(e.sourceDataChanged, e.shouldReloadTileOptions);\n        if (this.transform) {\n            this.update(this.transform, this.terrain);\n        }\n        this._didEmitContent = true;\n    }\n\n    /**\n     * Forgets the recorded maximum content elevation, so the next update recomputes it from the\n     * current layers and loaded tiles. Called when a symbol layer is removed, since the removed\n     * layer's heights would otherwise keep expanding tile coverage.\n     */\n    resetMaxContentElevation(): void {\n        this._maxContentElevationSeen = 0;\n    }\n\n    /**\n     * Remove all tiles from this pyramid\n     */\n    clearTiles(): void {\n        this._shouldReloadOnResume = false;\n        this._paused = false;\n        this.resetMaxContentElevation();\n\n        for (const id of this._inViewTiles.getAllIds()) {\n            this._removeTile(id);\n        }\n\n        this._outOfViewCache.reset();\n    }\n\n    /**\n     * Search through our current tiles and attempt to find the tiles that\n     * cover the given bounds.\n     * @param pointQueryGeometry - coordinates of the corners of bounding rectangle\n     * @returns 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.\n     */\n    tilesIn(pointQueryGeometry: Point[], maxPitchScaleFactor: number, has3DLayer: boolean): TileResult[] {\n        const tileResults: TileResult[] = [];\n\n        const transform = this.transform;\n        if (!transform) return tileResults;\n        const allowWorldCopies = transform.getCoveringTilesDetailsProvider().allowWorldCopies();\n\n        const cameraPointQueryGeometry = has3DLayer ?\n            transform.getCameraQueryGeometry(pointQueryGeometry) :\n            pointQueryGeometry;\n\n        const project = (point: Point) => transform.screenPointToMercatorCoordinate(point, this.terrain);\n        const queryGeometry = this.transformBbox(pointQueryGeometry, project, !allowWorldCopies);\n        const cameraQueryGeometry = this.transformBbox(cameraPointQueryGeometry, project, !allowWorldCopies);\n\n        const ids = this.getIds();\n\n        const cameraBounds = Bounds.fromPoints(cameraQueryGeometry);\n\n        for (const id of ids) {\n            const tile = this._inViewTiles.getTileById(id);\n            if (tile.holdingForSymbolFade()) {\n                // Tiles held for fading are covered by tiles that are closer to ideal\n                continue;\n            }\n            // if the projection does not render world copies then we need to explicitly check for the bounding box crossing the antimeridian\n            const tileIDs = allowWorldCopies ? [tile.tileID] : [tile.tileID.unwrapTo(-1), tile.tileID.unwrapTo(0)];\n            const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);\n            const queryPadding = maxPitchScaleFactor * tile.queryPadding * EXTENT / tile.tileSize / scale;\n\n            for (const tileID of tileIDs) {\n\n                const tileSpaceBounds = cameraBounds.map(point => tileID.getTilePoint(new MercatorCoordinate(point.x, point.y)));\n                tileSpaceBounds.expandBy(queryPadding);\n\n                if (tileSpaceBounds.intersects(EXTENT_BOUNDS)) {\n\n                    const tileSpaceQueryGeometry: Point[] = queryGeometry.map((c) => tileID.getTilePoint(c));\n                    const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c));\n\n                    tileResults.push({\n                        tile,\n                        tileID: allowWorldCopies ? tileID : tileID.unwrapTo(0),\n                        queryGeometry: tileSpaceQueryGeometry,\n                        cameraQueryGeometry: tileSpaceCameraQueryGeometry,\n                        scale\n                    });\n                }\n            }\n        }\n\n        return tileResults;\n    }\n\n    private transformBbox(geom: Point[], project: (point: Point) => MercatorCoordinate, checkWrap: boolean): MercatorCoordinate[] {\n        let transformed = geom.map(project);\n        if (checkWrap) {\n            // If the projection does not allow world copies, then a bounding box may span the antimeridian and\n            // instead of a bounding box going from 179°E to 179°W, it goes from 179°W to 179°E and covers the entire\n            // planet except for what should be inside it.\n            const bounds = Bounds.fromPoints(geom);\n            bounds.shrinkBy(Math.min(bounds.width(), bounds.height()) * 0.001);\n            const projected = bounds.map(project);\n\n            const newBounds = Bounds.fromPoints(transformed);\n\n            if (!newBounds.covers(projected)) {\n                transformed = transformed.map((coord) => coord.x > 0.5 ?\n                    new MercatorCoordinate(coord.x - 1, coord.y, coord.z) :\n                    coord\n                );\n            }\n        }\n        return transformed;\n    }\n\n    getVisibleCoordinates(symbolLayer?: boolean): OverscaledTileID[] {\n        return this.getRenderableIds(symbolLayer).map((id) => this._inViewTiles.getTileById(id).tileID);\n    }\n\n    hasTransition(): boolean {\n        if (this._source.hasTransition()) {\n            return true;\n        }\n\n        return isRasterType(this._source.type) && hasRasterTransition(this._inViewTiles, this._rasterFadeDuration);\n    }\n\n    setRasterFadeDuration(fadeDuration: number): void {\n        this._rasterFadeDuration = fadeDuration;\n    }\n\n    /**\n     * Set the value of a particular state for a feature\n     */\n    setFeatureState(sourceLayer: string, featureId: number | string, state: any): void {\n        sourceLayer ||= GEOJSON_TILE_LAYER_NAME;\n        this._state.updateState(sourceLayer, featureId, state);\n    }\n\n    /**\n     * Resets the value of a particular state key for a feature\n     */\n    removeFeatureState(sourceLayer?: string, featureId?: number | string, key?: string): void {\n        sourceLayer ||= GEOJSON_TILE_LAYER_NAME;\n        this._state.removeFeatureState(sourceLayer, featureId, key);\n    }\n\n    /**\n     * Get the entire state object for a feature\n     */\n    getFeatureState(sourceLayer: string, featureId: number | string): FeatureState {\n        sourceLayer ||= GEOJSON_TILE_LAYER_NAME;\n        return this._state.getState(sourceLayer, featureId);\n    }\n\n    /**\n     * Sets the set of keys that the tile depends on. This allows tiles to\n     * be reloaded when their dependencies change.\n     */\n    setDependencies(tileKey: string, namespace: string, dependencies: string[]): void {\n        const tile = this._inViewTiles.getTileById(tileKey);\n        if (tile) {\n            tile.setDependencies(namespace, dependencies);\n        }\n    }\n\n    /**\n     * Reloads all tiles that depend on the given keys.\n     */\n    reloadTilesForDependencies(namespaces: string[], keys: string[]): void {\n        for (const id of this._inViewTiles.getAllIds()) {\n            const tile = this._inViewTiles.getTileById(id);\n            if (tile.hasDependency(namespaces, keys)) {\n                this._reloadTile(id, 'reloading');\n            }\n        }\n        this._outOfViewCache.filter(tile => !tile.hasDependency(namespaces, keys));\n    }\n\n    areTilesLoaded(): boolean {\n        for (const tile of this._inViewTiles.getAllTiles()) {\n            if (!(tile.state === 'loaded' || tile.state === 'errored')) {\n                return false;\n            }\n        }\n        return true;\n    }\n}\n", "import {clamp} from '../util/util.ts';\n\nimport type Point from '@mapbox/point-geometry';\n\nexport class PathInterpolator {\n    points: Point[];\n    length: number;\n    paddedLength: number;\n    padding: number;\n    _distances: number[];\n\n    constructor(points_?: Point[] | null, padding_?: number | null) {\n        this.reset(points_, padding_);\n    }\n\n    reset(points_?: Point[] | null, padding_?: number | null): void {\n        this.points = points_ || [];\n\n        // Compute cumulative distance from first point to every other point in the segment.\n        // Last entry in the array is total length of the path\n        this._distances = [0.0];\n\n        for (let i = 1; i < this.points.length; i++) {\n            this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]);\n        }\n\n        this.length = this._distances[this._distances.length - 1];\n        this.padding = Math.min(padding_ || 0, this.length * 0.5);\n        this.paddedLength = this.length - this.padding * 2.0;\n    }\n\n    lerp(t: number): Point {\n        if (this.points.length === 1) {\n            return this.points[0];\n        }\n\n        t = clamp(t, 0, 1);\n\n        // Find the correct segment [p0, p1] where p0 <= x < p1\n        let currentIndex = 1;\n        let distOfCurrentIdx = this._distances[currentIndex];\n        const distToTarget = t * this.paddedLength + this.padding;\n\n        while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) {\n            distOfCurrentIdx = this._distances[++currentIndex];\n        }\n\n        // Interpolate between the two points of the segment\n        const idxOfPrevPoint = currentIndex - 1;\n        const distOfPrevIdx = this._distances[idxOfPrevPoint];\n        const segmentLength = distOfCurrentIdx - distOfPrevIdx;\n        const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0;\n\n        return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT));\n    }\n}\n", "import type {GetElevation} from '../geo/transform_interface.ts';\n\n/**\n * Resolves the elevation of a symbol at a tile coordinate, combining the terrain elevation with the\n * symbol's `symbol-height-offset`. `symbol-height-anchor` selects the datum the offset is measured\n * from: the terrain surface below the symbol (`ground`) or the zero elevation datum (`absolute`),\n * in which case the terrain below the symbol is ignored.\n *\n * Call this where the elevation is needed, so that `getElevation` keeps returning the plain terrain\n * elevation and never has to be substituted with a wrapper.\n *\n * @param getElevation - the terrain elevation function, absent when the map has no terrain\n * @param x - the tile x coordinate to evaluate the elevation at\n * @param y - the tile y coordinate to evaluate the elevation at\n * @param heightOffset - the evaluated `symbol-height-offset` of the symbol, in meters\n * @param heightAnchorGround - whether `symbol-height-anchor` is `ground`\n * @returns the elevation in meters, or undefined when the symbol sits at the zero elevation datum,\n * which lets the projection take its fast path that ignores the z coordinate\n */\nexport function getSymbolElevation(getElevation: GetElevation | undefined, x: number, y: number, heightOffset: number, heightAnchorGround: boolean): number | undefined {\n    if (!heightAnchorGround) {\n        return heightOffset;\n    }\n    if (!getElevation) {\n        return heightOffset !== 0 ? heightOffset : undefined;\n    }\n    return getElevation(x, y) + heightOffset;\n}\n", "import type {OverlapMode} from '../style/style_layer/overlap_mode.ts';\n\ntype QueryArgs = {\n    hitTest: boolean;\n    overlapMode?: OverlapMode;\n    circle?: {\n        x: number;\n        y: number;\n        radius: number;\n    };\n    seenUids: {\n        box: {\n            [_: number]: boolean;\n        };\n        circle: {\n            [_: number]: boolean;\n        };\n    };\n};\n\ntype QueryResult<T> = {\n    key: T;\n    x1: number;\n    y1: number;\n    x2: number;\n    y2: number;\n};\n\n/**\n * A key for the grid\n */\nexport type GridKey = {\n    overlapMode?: OverlapMode;\n};\n\nfunction overlapAllowed(overlapA: OverlapMode, overlapB: OverlapMode): boolean {\n    let allowed = true;\n\n    if (overlapA === 'always') {\n        // symbol A using 'always' overlap - allowed to overlap anything.\n    } else if (overlapA === 'never' || overlapB === 'never') {\n        // symbol A using 'never' overlap - can't overlap anything\n        // symbol A using 'cooperative' overlap - can overlap 'always' or 'cooperative' symbol; can't overlap 'never'\n        allowed = false;\n    }\n\n    return allowed;\n}\n\n/**\n * @internal\n * GridIndex is a data structure for testing the intersection of\n * circles and rectangles in a 2d plane.\n * It is optimized for rapid insertion and querying.\n * GridIndex splits the plane into a set of \"cells\" and keeps track\n * of which geometries intersect with each cell. At query time,\n * full geometry comparisons are only done for items that share\n * at least one cell. As long as the geometries are relatively\n * uniformly distributed across the plane, this greatly reduces\n * the number of comparisons necessary.\n */\nexport class GridIndex<T extends GridKey> {\n    circleKeys: T[];\n    boxKeys: T[];\n    boxCells: number[][];\n    circleCells: number[][];\n    bboxes: number[];\n    circles: number[];\n    xCellCount: number;\n    yCellCount: number;\n    width: number;\n    height: number;\n    xScale: number;\n    yScale: number;\n    boxUid: number;\n    circleUid: number;\n\n    constructor (width: number, height: number, cellSize: number) {\n        const boxCells = this.boxCells = [];\n        const circleCells = this.circleCells = [];\n\n        // More cells -> fewer geometries to check per cell, but items tend\n        // to be split across more cells.\n        // Sweet spot allows most small items to fit in one cell\n        this.xCellCount = Math.ceil(width / cellSize);\n        this.yCellCount = Math.ceil(height / cellSize);\n\n        for (let i = 0; i < this.xCellCount * this.yCellCount; i++) {\n            boxCells.push([]);\n            circleCells.push([]);\n        }\n        this.circleKeys = [];\n        this.boxKeys = [];\n        this.bboxes = [];\n        this.circles = [];\n\n        this.width = width;\n        this.height = height;\n        this.xScale = this.xCellCount / width;\n        this.yScale = this.yCellCount / height;\n        this.boxUid = 0;\n        this.circleUid = 0;\n    }\n\n    keysLength(): number {\n        return this.boxKeys.length + this.circleKeys.length;\n    }\n\n    insert(key: T, x1: number, y1: number, x2: number, y2: number): void {\n        this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++);\n        this.boxKeys.push(key);\n        this.bboxes.push(x1);\n        this.bboxes.push(y1);\n        this.bboxes.push(x2);\n        this.bboxes.push(y2);\n    }\n\n    insertCircle(key: T, x: number, y: number, radius: number): void {\n        // Insert circle into grid for all cells in the circumscribing square\n        // It's more than necessary (by a factor of 4/PI), but fast to insert\n        this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++);\n        this.circleKeys.push(key);\n        this.circles.push(x);\n        this.circles.push(y);\n        this.circles.push(radius);\n    }\n\n    private _insertBoxCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n        this.boxCells[cellIndex].push(uid);\n    }\n\n    private _insertCircleCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number)  {\n        this.circleCells[cellIndex].push(uid);\n    }\n\n    private _query(x1: number, y1: number, x2: number, y2: number, hitTest: boolean, overlapMode: OverlapMode, predicate?: (key: T) => boolean): Array<QueryResult<T>> {\n        if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {\n            return [];\n        }\n        const result: Array<QueryResult<T>> = [];\n        if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {\n            if (hitTest) {\n                // Covers the entire grid, so collides with everything\n                return [{\n                    key: null,\n                    x1,\n                    y1,\n                    x2,\n                    y2\n                }];\n            }\n            for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) {\n                result.push({\n                    key: this.boxKeys[boxUid],\n                    x1: this.bboxes[boxUid * 4],\n                    y1: this.bboxes[boxUid * 4 + 1],\n                    x2: this.bboxes[boxUid * 4 + 2],\n                    y2: this.bboxes[boxUid * 4 + 3]\n                });\n            }\n            for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) {\n                const x = this.circles[circleUid * 3];\n                const y = this.circles[circleUid * 3 + 1];\n                const radius = this.circles[circleUid * 3 + 2];\n                result.push({\n                    key: this.circleKeys[circleUid],\n                    x1: x - radius,\n                    y1: y - radius,\n                    x2: x + radius,\n                    y2: y + radius\n                });\n            }\n        } else {\n            const queryArgs: QueryArgs = {\n                hitTest,\n                overlapMode,\n                seenUids: {box: {}, circle: {}}\n            };\n            this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);\n        }\n\n        return result;\n    }\n\n    query(x1: number, y1: number, x2: number, y2: number): Array<QueryResult<T>> {\n        return this._query(x1, y1, x2, y2, false, null);\n    }\n\n    hitTest(x1: number, y1: number, x2: number, y2: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean {\n        return this._query(x1, y1, x2, y2, true, overlapMode, predicate).length > 0;\n    }\n\n    hitTestCircle(x: number, y: number, radius: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean {\n        // Insert circle into grid for all cells in the circumscribing square\n        // It's more than necessary (by a factor of 4/PI), but fast to insert\n        const x1 = x - radius;\n        const x2 = x + radius;\n        const y1 = y - radius;\n        const y2 = y + radius;\n        if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {\n            return false;\n        }\n\n        // Box query early exits if the bounding box is larger than the grid, but we don't do\n        // the equivalent calculation for circle queries because early exit is less likely\n        // and the calculation is more expensive\n        const result: boolean[] = [];\n        const queryArgs: QueryArgs = {\n            hitTest: true,\n            overlapMode,\n            circle: {x, y, radius},\n            seenUids: {box: {}, circle: {}}\n        };\n        this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);\n        return result.length > 0;\n    }\n\n    private _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: Array<QueryResult<T>>, queryArgs: QueryArgs, predicate?: (key: T) => boolean): boolean {\n        const {seenUids, hitTest, overlapMode} = queryArgs;\n        const boxCell = this.boxCells[cellIndex];\n\n        // Use a small epsilon to account for floating-point imprecision\n        // when collision box boundaries are computed via different\n        // projection paths (different tiles/sources) but should\n        // mathematically produce the same boundary value.\n        const epsilon = 1e-6;\n\n        if (boxCell !== null) {\n            const bboxes = this.bboxes;\n            for (const boxUid of boxCell) {\n                if (!seenUids.box[boxUid]) {\n                    seenUids.box[boxUid] = true;\n                    const offset = boxUid * 4;\n                    const key = this.boxKeys[boxUid];\n\n                    if ((x1 <= bboxes[offset + 2] + epsilon) &&\n                        (y1 <= bboxes[offset + 3] + epsilon) &&\n                        (x2 >= bboxes[offset + 0] - epsilon) &&\n                        (y2 >= bboxes[offset + 1] - epsilon) &&\n                        (!predicate || predicate(key))) {\n                        if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {\n                            result.push({\n                                key,\n                                x1: bboxes[offset],\n                                y1: bboxes[offset + 1],\n                                x2: bboxes[offset + 2],\n                                y2: bboxes[offset + 3]\n                            });\n                            if (hitTest) {\n                                // true return value stops the query after first match\n                                return true;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        const circleCell = this.circleCells[cellIndex];\n        if (circleCell !== null) {\n            const circles = this.circles;\n            for (const circleUid of circleCell) {\n                if (!seenUids.circle[circleUid]) {\n                    seenUids.circle[circleUid] = true;\n                    const offset = circleUid * 3;\n                    const key = this.circleKeys[circleUid];\n\n                    if (this._circleAndRectCollide(\n                        circles[offset],\n                        circles[offset + 1],\n                        circles[offset + 2],\n                        x1,\n                        y1,\n                        x2,\n                        y2) &&\n                        (!predicate || predicate(key))) {\n                        if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {\n                            const x = circles[offset];\n                            const y = circles[offset + 1];\n                            const radius = circles[offset + 2];\n                            result.push({\n                                key,\n                                x1: x - radius,\n                                y1: y - radius,\n                                x2: x + radius,\n                                y2: y + radius\n                            });\n                            if (hitTest) {\n                                // true return value stops the query after first match\n                                return true;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // false return to continue query\n        return false;\n    }\n\n    private _queryCellCircle(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: boolean[], queryArgs: QueryArgs, predicate?: (key: T) => boolean): boolean {\n        const {circle, seenUids, overlapMode} = queryArgs;\n        const boxCell = this.boxCells[cellIndex];\n\n        if (boxCell !== null) {\n            const bboxes = this.bboxes;\n            for (const boxUid of boxCell) {\n                if (!seenUids.box[boxUid]) {\n                    seenUids.box[boxUid] = true;\n                    const offset = boxUid * 4;\n                    const key = this.boxKeys[boxUid];\n                    if (this._circleAndRectCollide(\n                        circle.x,\n                        circle.y,\n                        circle.radius,\n                        bboxes[offset + 0],\n                        bboxes[offset + 1],\n                        bboxes[offset + 2],\n                        bboxes[offset + 3]) &&\n                        (!predicate || predicate(key)) &&\n                        !overlapAllowed(overlapMode, key.overlapMode)) {\n                        result.push(true);\n                        return true;\n                    }\n                }\n            }\n        }\n\n        const circleCell = this.circleCells[cellIndex];\n        if (circleCell !== null) {\n            const circles = this.circles;\n            for (const circleUid of circleCell) {\n                if (!seenUids.circle[circleUid]) {\n                    seenUids.circle[circleUid] = true;\n                    const offset = circleUid * 3;\n                    const key = this.circleKeys[circleUid];\n                    if (this._circlesCollide(\n                        circles[offset],\n                        circles[offset + 1],\n                        circles[offset + 2],\n                        circle.x,\n                        circle.y,\n                        circle.radius) &&\n                        (!predicate || predicate(key)) &&\n                        !overlapAllowed(overlapMode, key.overlapMode)) {\n                        result.push(true);\n                        return true;\n                    }\n                }\n            }\n        }\n    }\n\n    private _forEachCell<TArg>(\n        x1: number,\n        y1: number,\n        x2: number,\n        y2: number,\n        fn: (x1: number, y1: number, x2: number, y2: number, cellIndex: number, arg1: TArg, arg2?: QueryArgs, predicate?: (key: T) => boolean) => boolean | void,\n        arg1: TArg,\n        arg2?: QueryArgs,\n        predicate?: (key: T) => boolean) {\n        const cx1 = this._convertToXCellCoord(x1);\n        const cy1 = this._convertToYCellCoord(y1);\n        const cx2 = this._convertToXCellCoord(x2);\n        const cy2 = this._convertToYCellCoord(y2);\n\n        for (let x = cx1; x <= cx2; x++) {\n            for (let y = cy1; y <= cy2; y++) {\n                const cellIndex = this.xCellCount * y + x;\n                if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) return;\n            }\n        }\n    }\n\n    private _convertToXCellCoord(x: number) {\n        return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));\n    }\n\n    private _convertToYCellCoord(y: number) {\n        return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));\n    }\n\n    private _circlesCollide(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number): boolean {\n        const dx = x2 - x1;\n        const dy = y2 - y1;\n        const bothRadii = r1 + r2;\n        return (bothRadii * bothRadii) > (dx * dx + dy * dy);\n    }\n\n    private _circleAndRectCollide(\n        circleX: number,\n        circleY: number,\n        radius: number,\n        x1: number,\n        y1: number,\n        x2: number,\n        y2: number\n    ): boolean {\n        const halfRectWidth = (x2 - x1) / 2;\n        const distX = Math.abs(circleX - (x1 + halfRectWidth));\n        if (distX > (halfRectWidth + radius)) {\n            return false;\n        }\n\n        const halfRectHeight = (y2 - y1) / 2;\n        const distY = Math.abs(circleY - (y1 + halfRectHeight));\n        if (distY > (halfRectHeight + radius)) {\n            return false;\n        }\n\n        if (distX <= halfRectWidth || distY <= halfRectHeight) {\n            return true;\n        }\n\n        const dx = distX - halfRectWidth;\n        const dy = distY - halfRectHeight;\n        return (dx * dx + dy * dy <= (radius * radius));\n    }\n}\n", "/*\nThis class implements fast mathematical operations to optimize or complement gl-matrix\n*/\nimport type {mat4} from 'gl-matrix';\n\n/*\nInvert a transform matrix\ndst and src are in column-major flat format\n*/\nexport function fastInvertTransformMat4(dst: mat4, src: mat4): mat4{\n    // extract scale. hyp: scale X = scale Y:\n    const sXYSqInv = 1.0 / (src[0] * src[0] + src[1] * src[1] + src[2] * src[2]);\n    const sZSqInv = 1.0 / (src[8] * src[8] + src[9] * src[9] + src[10] * src[10]);\n\n    // inv rotation and scaling part:\n    const s0 = src[0] * sXYSqInv;\n    const s4 = src[4] * sXYSqInv;\n    const s8 = src[8] * sZSqInv;\n    const s1 = src[1] * sXYSqInv;\n    const s5 = src[5] * sXYSqInv;\n    const s9 = src[9] * sZSqInv;\n    const s2 = src[2] * sXYSqInv;\n    const s6 = src[6] * sXYSqInv;\n    const s10 = src[10] * sZSqInv;\n\n    // rotation part:\n    dst[0] = s0;\n    dst[1] = s4;\n    dst[2] = s8;\n    dst[4] = s1;\n    dst[5] = s5;\n    dst[6] = s9;\n    dst[8] = s2;\n    dst[9] = s6;\n    dst[10] = s10;\n\n    // translation part:\n    const t0 = src[12];\n    const t1 = src[13];\n    const t2 = src[14];\n    dst[12] = -s0 * t0 - s1 * t1 - s2 * t2;\n    dst[13] = -s4 * t0 - s5 * t1 - s6 * t2;\n    dst[14] = -s8 * t0 - s9 * t1 - s10 * t2;\n\n    // constant part:\n    dst[3] = 0;\n    dst[7] = 0;\n    dst[11] = 0;\n    dst[15] = 1;\n\n    return dst;\n}\n\n/*\nInvert a perspective projection matrix\ndst and src are in column-major flat format\n*/\nexport function fastInvertProjMat4(dst: mat4, src: mat4): mat4{\n    dst[0] = 1 / src[0];\n    dst[1] = 0;\n    dst[2] = 0;\n    dst[3] = 0;\n\n    dst[4] = 0;\n    dst[5] = 1 / src[5];\n    dst[6] = 0;\n    dst[7] = 0;\n\n    dst[8] = 0;\n    dst[9] = 0;\n    dst[10] = 0;\n    dst[11] = 1 / src[14];\n\n    dst[12] = 0;\n    dst[13] = 0;\n    dst[14] = -1;\n    dst[15] = src[10] / src[14];\n\n    return dst;\n}\n\n/*\nInvert a skew matrix\nwith diag coefficients > 0 and XY counterdiag\ndst and src are in column-major flat format\n*/\n\nexport function fastInvertSkewMat4(dst: mat4, src: mat4): mat4{\n    const invDetXY = 1.0 / (src[0]*src[5] - src[1]*src[4]);\n    dst[0] = src[5] * invDetXY;\n    dst[1] = -src[1] * invDetXY;\n    dst[2] = 0;\n    dst[3] = 0;\n\n    dst[4] = -src[4] * invDetXY;\n    dst[5] = src[0] * invDetXY;\n    dst[6] = 0;\n    dst[7] = 0;\n\n    dst[8] = 0;\n    dst[9] = 0;\n    dst[10] = 1 / src[10];\n    dst[11] = 0;\n\n    dst[12] = 0;\n    dst[13] = 0;\n    dst[14] = 0;\n    dst[15] = 1 / src[15];\n\n    return dst;\n}\n", "import Point from '@mapbox/point-geometry';\nimport {mat2, mat4, vec2, vec4} from 'gl-matrix';\nimport {getSymbolElevation} from './symbol_elevation.ts';\nimport * as symbolSize from './symbol_size.ts';\nimport {addDynamicAttributes} from '../data/bucket/symbol_bucket.ts';\nimport {fastInvertSkewMat4} from '../util/fast_maths.ts';\nimport {WritingMode} from '../symbol/shaping.ts';\nimport {findLineIntersection} from '../util/util.ts';\n\nimport type {Painter} from '../render/painter.ts';\nimport type {IReadonlyTransform, GetElevation} from '../geo/transform_interface.ts';\nimport type {SymbolBucket} from '../data/bucket/symbol_bucket.ts';\nimport type {\n    GlyphOffsetArray,\n    SymbolLineVertexArray,\n    SymbolDynamicLayoutArray,\n    PlacedSymbol,\n} from '../data/array_types.g.ts';\nimport type {UnwrappedTileID} from '../tile/tile_id.ts';\nimport type {StructArray} from '../util/struct_array.ts';\n\n/**\n * Pre-allocate objects to avoid online allocation\n */\nconst tmpMat4 = mat4.create();\n\n/**\n * The result of projecting a point to the screen, with some additional information about the projection.\n */\nexport type PointProjection = {\n    /**\n     * The projected point.\n     */\n    point: Point;\n    /**\n     * The original W component of the projection.\n     */\n    signedDistanceFromCamera: number;\n    /**\n     * For complex projections (such as globe), true if the point is occluded by the projection, such as by being on the backfacing side of the globe.\n     * If the point is simply beyond the edge of the screen, this should NOT be set to false.\n     */\n    isOccluded: boolean;\n};\n\n/*\n * # Overview of coordinate spaces\n *\n * ## Tile coordinate spaces\n * Each label has an anchor. Some labels have corresponding line geometries.\n * The points for both anchors and lines are stored in tile units. Each tile has it's own\n * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right.\n *\n * ## Clip space (GL coordinate space)\n * At the end of everything, the vertex shader needs to produce a position in clip space,\n * which is (-1, 1) at the top left and (1, -1) in the bottom right.\n * In the depth buffer, values are between 0 (near plane) to 1 (far plane).\n *\n * ## Map pixel coordinate spaces\n * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is\n * whatever counts as 1 pixel at the current zoom.\n * This space is used for pitch-alignment=map, rotation-alignment=map\n *\n * ## Rotated map pixel coordinate spaces\n * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile.\n * This space is used for pitch-alignment=map, rotation-alignment=viewport\n *\n * ## Viewport pixel coordinate space\n * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner\n * of the canvas. This space is used for pitch-alignment=viewport\n *\n *\n * # Vertex projection\n * It goes roughly like this:\n * 1. project the anchor and line from tile units into the correct label coordinate space\n *      - map pixel space           pitch-alignment=map         rotation-alignment=map\n *      - rotated map pixel space   pitch-alignment=map         rotation-alignment=viewport\n *      - viewport pixel space      pitch-alignment=viewport    rotation-alignment=*\n * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor.\n * 3. add the glyph's corner offset to the point from step 3\n * 4. convert from the label coordinate space to clip space\n *\n * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work).\n *      This is what `u_label_plane_matrix` is used for.\n * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry.\n *      This is what `updateLineLabels(...)` does.\n *      Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix.\n *\n * Steps 3 and 4 are done in the shaders for all labels.\n *\n *\n * # Custom projection handling\n * Note that since MapLibre now supports more than one projection, the transformation\n * to viewport pixel space and GL clip space now *must* go through the projection's (`transform`'s)\n * `projectTileCoordinates` function, since it might do nontrivial transformations.\n *\n * Hence projecting anything to a symbol's label plane can no longer be handled by a simple matrix,\n * since, if the symbol's label plane is viewport pixel space, `projectTileCoordinates` must be used.\n * This is applies both here and in the symbol vertex shaders.\n */\n\nexport function getPitchedLabelPlaneMatrix(\n    rotateWithMap: boolean,\n    transform: IReadonlyTransform,\n    pixelsToTileUnits: number): mat4 {\n    const m = mat4.create();\n    if (!rotateWithMap) {\n        const {vecSouth, vecEast} = getTileSkewVectors(transform);\n        const skew = mat2.create();\n        skew[0] = vecEast[0];\n        skew[1] = vecEast[1];\n        skew[2] = vecSouth[0];\n        skew[3] = vecSouth[1];\n        mat2.invert(skew, skew);\n        m[0] = skew[0];\n        m[1] = skew[1];\n        m[4] = skew[2];\n        m[5] = skew[3];\n    }\n    mat4.scale(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]);\n    return m;\n}\n\n/*\n * Returns a matrix for either converting from pitched label space to tile space,\n * or for converting from screenspace pixels to clip space.\n */\nexport function getGlCoordMatrix(\n    pitchWithMap: boolean,\n    rotateWithMap: boolean,\n    transform: IReadonlyTransform,\n    pixelsToTileUnits: number): mat4 {\n    if (pitchWithMap) {\n        const m = mat4.create();\n        if (!rotateWithMap) {\n            const {vecSouth, vecEast} = getTileSkewVectors(transform);\n            m[0] = vecEast[0];\n            m[1] = vecEast[1];\n            m[4] = vecSouth[0];\n            m[5] = vecSouth[1];\n        }\n        mat4.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]);\n        return m;\n    } else {\n        return transform.pixelsToClipSpaceMatrix;\n    }\n}\n\nexport function getTileSkewVectors(transform: IReadonlyTransform): {vecEast: vec2; vecSouth: vec2} {\n    const cosRoll = Math.cos(transform.rollInRadians);\n    const sinRoll = Math.sin(transform.rollInRadians);\n    const cosPitch = Math.cos(transform.pitchInRadians);\n    const cosBearing = Math.cos(transform.bearingInRadians);\n    const sinBearing = Math.sin(transform.bearingInRadians);\n    const vecSouth = vec2.create();\n    vecSouth[0] = -cosBearing * cosPitch * sinRoll - sinBearing * cosRoll;\n    vecSouth[1] = -sinBearing * cosPitch * sinRoll + cosBearing * cosRoll;\n    const vecSouthLen = vec2.length(vecSouth);\n    if (vecSouthLen < 1.0e-9) {\n        vec2.zero(vecSouth);\n    } else {\n        vec2.scale(vecSouth, vecSouth, 1 / vecSouthLen);\n    }\n    const vecEast = vec2.create();\n    vecEast[0] = cosBearing * cosPitch * cosRoll - sinBearing * sinRoll;\n    vecEast[1] = sinBearing * cosPitch * cosRoll + cosBearing * sinRoll;\n    const vecEastLen = vec2.length(vecEast);\n    if (vecEastLen < 1.0e-9) {\n        vec2.zero(vecEast);\n    } else {\n        vec2.scale(vecEast, vecEast, 1 / vecEastLen);\n    }\n\n    return {vecEast, vecSouth};\n}\n\n/**\n * Resolves the elevation of the symbol described by `projectionContext` at a tile coordinate.\n */\nexport function elevationAt(projectionContext: SymbolProjectionContext, x: number, y: number): number | undefined {\n    return getSymbolElevation(projectionContext.getElevation, x, y, projectionContext.heightOffset ?? 0, projectionContext.heightAnchorGround ?? true);\n}\n\n/**\n * Projects a point using a specified matrix, including the perspective divide.\n * Uses a fast path if `elevation` is undefined.\n */\nexport function projectWithMatrix(x: number, y: number, matrix: mat4, elevation?: number): PointProjection {\n    let pos;\n    if (elevation != null) { // slow because of handle z-index\n        pos = [x, y, elevation, 1] as vec4;\n        vec4.transformMat4(pos, pos, matrix);\n    } else { // fast because of ignore z-index\n        pos = [x, y, 0, 1] as vec4;\n        xyTransformMat4(pos, pos, matrix);\n    }\n    const w = pos[3];\n    return {\n        point: new Point(pos[0] / w, pos[1] / w),\n        signedDistanceFromCamera: w,\n        isOccluded: false\n    };\n}\n\nexport function getPerspectiveRatio(cameraToCenterDistance: number, signedDistanceFromCamera: number): number {\n    return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera);\n}\n\nfunction isVisible(p: Point,\n    clippingBuffer: [number, number]) {\n    const inPaddedViewport = (\n        p.x >= -clippingBuffer[0] &&\n        p.x <= clippingBuffer[0] &&\n        p.y >= -clippingBuffer[1] &&\n        p.y <= clippingBuffer[1]);\n    return inPaddedViewport;\n}\n\n/*\n *  Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view.\n *  This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader.\n */\nexport function updateLineLabels(bucket: SymbolBucket,\n    painter: Painter,\n    transform: IReadonlyTransform,\n    isText: boolean,\n    pitchedLabelPlaneMatrix: mat4,\n    pitchedLabelPlaneMatrixInverse: mat4,\n    pitchWithMap: boolean,\n    keepUpright: boolean,\n    rotateToLine: boolean,\n    unwrappedTileID: UnwrappedTileID,\n    translation: [number, number],\n    getElevation: GetElevation | undefined): void {\n\n    const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;\n    const partiallyEvaluatedSize = symbolSize.evaluateSizeForZoom(sizeData, transform.zoom);\n\n    const clippingBuffer: [number, number] = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1];\n\n    const dynamicLayoutVertexArray = isText ?\n        bucket.text.dynamicLayoutVertexArray :\n        bucket.icon.dynamicLayoutVertexArray;\n    dynamicLayoutVertexArray.clear();\n\n    const lineVertexArray = bucket.lineVertexArray;\n    const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray;\n\n    const aspectRatio = transform.width / transform.height;\n\n    let useVertical = false;\n\n    for (let s = 0; s < placedSymbols.length; s++) {\n        const symbol = placedSymbols.get(s);\n\n        // Don't do calculations for vertical glyphs unless the previous symbol was horizontal\n        // and we determined that vertical glyphs were necessary.\n        // Also don't do calculations for symbols that are collided and fully faded out\n        if (symbol.hidden || symbol.writingMode === WritingMode.vertical && !useVertical) {\n            hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n            continue;\n        }\n        // Awkward... but we're counting on the paired \"vertical\" symbol coming immediately after its horizontal counterpart\n        useVertical = false;\n\n        const tileAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n        const projectionCache: ProjectionCache = {projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false};\n\n        const projectionContext: SymbolProjectionContext = {\n            getElevation,\n            pitchedLabelPlaneMatrix,\n            lineVertexArray,\n            pitchWithMap,\n            projectionCache,\n            transform,\n            tileAnchorPoint,\n            unwrappedTileID,\n            width: transform.width,\n            height: transform.height,\n            translation\n        };\n\n        const anchorPos = projectTileCoordinatesToClipSpace(symbol.anchorX, symbol.anchorY, projectionContext);\n\n        // Don't bother calculating the correct point for invisible labels.\n        if (!isVisible(anchorPos.point, clippingBuffer)) {\n            hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n            continue;\n        }\n\n        const cameraToAnchorDistance = anchorPos.signedDistanceFromCamera;\n        const perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, cameraToAnchorDistance);\n\n        const fontSize = symbolSize.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);\n        const pitchScaledFontSize = pitchWithMap ? (fontSize * transform.getPitchedTextCorrection(symbol.anchorX, symbol.anchorY, unwrappedTileID) / perspectiveRatio) : fontSize * perspectiveRatio;\n\n        const placeUnflipped = placeGlyphsAlongLine({\n            projectionContext,\n            pitchedLabelPlaneMatrixInverse,\n            symbol,\n            fontSize: pitchScaledFontSize,\n            flip: false,\n            keepUpright,\n            glyphOffsetArray: bucket.glyphOffsetArray,\n            dynamicLayoutVertexArray,\n            aspectRatio,\n            rotateToLine,\n        });\n\n        useVertical = placeUnflipped.useVertical;\n\n        if (placeUnflipped.notEnoughRoom || useVertical ||\n            (placeUnflipped.needsFlipping &&\n                placeGlyphsAlongLine({\n                    projectionContext,\n                    pitchedLabelPlaneMatrixInverse,\n                    symbol,\n                    fontSize: pitchScaledFontSize,\n                    flip: true, // flipped\n                    keepUpright,\n                    glyphOffsetArray: bucket.glyphOffsetArray,\n                    dynamicLayoutVertexArray,\n                    aspectRatio,\n                    rotateToLine,\n                }).notEnoughRoom)) {\n            hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n        }\n    }\n\n    if (isText) {\n        bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n    } else {\n        bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n    }\n}\n\ntype FirstAndLastGlyphPlacement = {\n    first: PlacedGlyph;\n    last: PlacedGlyph;\n} | null;\n\n/*\n * Place the first and last glyph of a line label, projected to the label plane.\n * This function is called both during collision detection (to determine the label's size)\n * and during line label rendering (to make sure the label fits on the line geometry with\n * the current camera position, which may differ from the position used during collision detection).\n *\n * Calling this function has the effect of populating the \"projectionCache\" with all projected\n * vertex locations the label will need, making future calls to placeGlyphAlongLine (for all the\n * intermediate glyphs) much cheaper.\n *\n * Returns null if the label can't fit on the geometry\n */\nexport function placeFirstAndLastGlyph(\n    fontScale: number,\n    glyphOffsetArray: GlyphOffsetArray,\n    lineOffsetX: number,\n    lineOffsetY: number,\n    flip: boolean,\n    symbol: PlacedSymbol,\n    rotateToLine: boolean,\n    projectionContext: SymbolProjectionContext): FirstAndLastGlyphPlacement {\n    const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;\n    const lineStartIndex = symbol.lineStartIndex;\n    const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;\n\n    const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex);\n    const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1);\n\n    const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment,\n        lineStartIndex, lineEndIndex, projectionContext, rotateToLine);\n    if (!firstPlacedGlyph)\n        return null;\n\n    const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment,\n        lineStartIndex, lineEndIndex, projectionContext, rotateToLine);\n    if (!lastPlacedGlyph)\n        return null;\n\n    if (projectionContext.projectionCache.anyProjectionOccluded) {\n        return null;\n    }\n\n    return {first: firstPlacedGlyph, last: lastPlacedGlyph};\n}\n\ntype OrientationChangeType = {\n    useVertical?: boolean;\n    needsFlipping?: boolean;\n};\n\nfunction requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio): OrientationChangeType {\n    if (writingMode === WritingMode.horizontal) {\n        // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate\n        // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal\n        // and vertical versions can have slightly different projections which could lead to angles where both or\n        // neither showed.\n        const rise = Math.abs(lastPoint.y - firstPoint.y);\n        const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio;\n        if (rise > run) {\n            return {useVertical: true};\n        }\n    }\n\n    if (writingMode === WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) {\n        // Includes \"horizontalOnly\" case for labels without vertical glyphs\n        return {needsFlipping: true};\n    }\n\n    return null;\n}\n\ntype GlyphLinePlacementResult = OrientationChangeType & {\n    notEnoughRoom?: boolean;\n};\n\ntype GlyphLinePlacementArgs = {\n    projectionContext: SymbolProjectionContext;\n    pitchedLabelPlaneMatrixInverse: mat4;\n    symbol: PlacedSymbol;\n    fontSize: number;\n    flip: boolean;\n    keepUpright: boolean;\n    glyphOffsetArray: GlyphOffsetArray;\n    dynamicLayoutVertexArray: StructArray;\n    aspectRatio: number;\n    rotateToLine: boolean;\n};\n\n/*\n* Place first and last glyph along the line projected to label plane, and if they fit\n* iterate through all the intermediate glyphs, calculating their label plane positions\n* from the projected line.\n*\n* Finally, add resulting glyph position calculations to dynamicLayoutVertexArray for\n* upload to the GPU\n*/\nfunction placeGlyphsAlongLine(args: GlyphLinePlacementArgs): GlyphLinePlacementResult {\n    const {\n        projectionContext,\n        pitchedLabelPlaneMatrixInverse,\n        symbol,\n        fontSize,\n        flip,\n        keepUpright,\n        glyphOffsetArray,\n        dynamicLayoutVertexArray,\n        aspectRatio,\n        rotateToLine\n    } = args;\n\n    const fontScale = fontSize / 24;\n    const lineOffsetX = symbol.lineOffsetX * fontScale;\n    const lineOffsetY = symbol.lineOffsetY * fontScale;\n\n    let placedGlyphs;\n    if (symbol.numGlyphs > 1) {\n        const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;\n        const lineStartIndex = symbol.lineStartIndex;\n        const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;\n\n        // Place the first and the last glyph in the label first, so we can figure out\n        // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode\n        // Note: these glyphs are placed onto the label plane\n        const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext);\n        if (!firstAndLastGlyph) {\n            return {notEnoughRoom: true};\n        }\n        const firstPoint = projectFromLabelPlaneToClipSpace(firstAndLastGlyph.first.point.x, firstAndLastGlyph.first.point.y, projectionContext, pitchedLabelPlaneMatrixInverse);\n        const lastPoint = projectFromLabelPlaneToClipSpace(firstAndLastGlyph.last.point.x, firstAndLastGlyph.last.point.y, projectionContext, pitchedLabelPlaneMatrixInverse);\n\n        if (keepUpright && !flip) {\n            const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio);\n            if (orientationChange) {\n                return orientationChange;\n            }\n        }\n\n        placedGlyphs = [firstAndLastGlyph.first];\n        for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) {\n            // Since first and last glyph fit on the line, try placing the rest of the glyphs.\n            const placedGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, symbol.segment,\n                lineStartIndex, lineEndIndex, projectionContext, rotateToLine);\n            if (!placedGlyph) {\n                return {notEnoughRoom: true};\n            }\n            placedGlyphs.push(placedGlyph);\n        }\n        placedGlyphs.push(firstAndLastGlyph.last);\n    } else {\n        // Only a single glyph to place\n        // So, determine whether to flip based on projected angle of the line segment it's on\n        if (keepUpright && !flip) {\n            const a = projectTileCoordinatesToLabelPlane(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point;\n            const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1);\n            const tileSegmentEnd = new Point(projectionContext.lineVertexArray.getx(tileVertexIndex), projectionContext.lineVertexArray.gety(tileVertexIndex));\n            const projectedVertex = projectTileCoordinatesToLabelPlane(tileSegmentEnd.x, tileSegmentEnd.y, projectionContext);\n            // We know the anchor will be in the viewport, but the end of the line segment may be\n            // behind the plane of the camera, in which case we can use a point at any arbitrary (closer)\n            // point on the segment.\n            const b = (projectedVertex.signedDistanceFromCamera > 0) ?\n                projectedVertex.point :\n                projectTruncatedLineSegmentToLabelPlane(projectionContext.tileAnchorPoint, tileSegmentEnd, a, 1, projectionContext);\n\n            const clipSpaceA = projectFromLabelPlaneToClipSpace(a.x, a.y, projectionContext, pitchedLabelPlaneMatrixInverse);\n            const clipSpaceB = projectFromLabelPlaneToClipSpace(b.x, b.y, projectionContext, pitchedLabelPlaneMatrixInverse);\n\n            const orientationChange = requiresOrientationChange(symbol.writingMode, clipSpaceA, clipSpaceB, aspectRatio);\n            if (orientationChange) {\n                return orientationChange;\n            }\n        }\n        const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, symbol.segment,\n            symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, projectionContext, rotateToLine);\n        if (!singleGlyph || projectionContext.projectionCache.anyProjectionOccluded)\n            return {notEnoughRoom: true};\n\n        placedGlyphs = [singleGlyph];\n    }\n\n    for (const glyph of placedGlyphs) {\n        addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle);\n    }\n    return {};\n}\n\n/**\n * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, projects it to the correct label plane,\n * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`.\n * Projects a \"virtual\" vertex along a line segment.\n * @param previousTilePoint - Line start point, in tile coordinates.\n * @param currentTilePoint - Line end point, in tile coordinates.\n * @param previousProjectedPoint - Projection of `previousTilePoint` into label plane\n * @param minimumLength - Distance in the projected space along the line for the returned point.\n * @param projectionContext - Projection context, used to get terrain's `getElevation`, and to project the points to screen pixels.\n */\nfunction projectTruncatedLineSegmentToLabelPlane(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionContext: SymbolProjectionContext) {\n    // We are assuming \"previousTilePoint\" won't project to a point within one unit of the camera plane\n    // If it did, that would mean our label extended all the way out from within the viewport to a (very distant)\n    // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the\n    // plane of the camera.\n    const unitVertexToBeProjected = previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit());\n    const projectedUnitVertex = projectTileCoordinatesToLabelPlane(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionContext).point;\n    const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex);\n    return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag()));\n}\n\ntype IndexToPointCache = { [lineIndex: number]: Point };\n\n/**\n * @internal\n * We calculate label-plane projected points for line vertices as we place glyphs along the line\n * Since we will use the same vertices for potentially many glyphs, cache the results for this bucket\n * over the course of the render. Each vertex location also potentially has one offset equivalent\n * for us to hold onto. The vertex indices are per-symbol-bucket.\n */\ntype ProjectionCache = {\n    /**\n     * tile-unit vertices projected into label-plane units\n     */\n    projections: IndexToPointCache;\n    /**\n     * label-plane vertices which have been shifted to follow an offset line\n     */\n    offsets: IndexToPointCache;\n    /**\n     * Cached projected anchor point.\n     */\n    cachedAnchorPoint: Point | undefined;\n    /**\n     * Was any projected point occluded by the map itself (eg. occluded by the planet when using globe projection).\n     *\n     * Viewport-pitched line-following texts where *any* of the line points is hidden behind the planet curve becomes entirely hidden.\n     * This is perhaps not the most ideal behavior, but it works, it is simple and planetary-scale texts such as this seem to be a rare edge case.\n     */\n    anyProjectionOccluded: boolean;\n};\n\n/**\n * @internal\n * Arguments necessary to project a vertex to the label plane\n */\nexport type SymbolProjectionContext = {\n    /**\n     * Used to cache results, save cost if projecting the same vertex multiple times\n     */\n    projectionCache: ProjectionCache;\n    /**\n     * The array of tile-unit vertices transferred from worker\n     */\n    lineVertexArray: SymbolLineVertexArray;\n    /**\n     * Matrix for transforming from pixels (symbol shaping) to potentially rotated tile units (pitched map label plane).\n     */\n    pitchedLabelPlaneMatrix: mat4;\n    /**\n     * Function to get elevation at a point, absent when the map has no terrain\n     * @param x - the x coordinate\n     * @param y - the y coordinate\n    */\n    getElevation: GetElevation | undefined;\n    /**\n     * The evaluated `symbol-height-offset` of the symbol being projected, in meters. Defaults to 0.\n     */\n    heightOffset?: number;\n    /**\n     * Whether `symbol-height-anchor` is `ground`, so that `heightOffset` is measured from the\n     * terrain surface rather than from the zero elevation datum. Defaults to true.\n     */\n    heightAnchorGround?: boolean;\n    /**\n     * Only for creating synthetic vertices if vertex would otherwise project behind plane of camera,\n     * but still convenient to pass it inside this type.\n     */\n    tileAnchorPoint: Point;\n    /**\n     * True when line glyphs are projected onto the map, instead of onto the viewport.\n     */\n    pitchWithMap: boolean;\n    transform: IReadonlyTransform;\n    unwrappedTileID: UnwrappedTileID;\n    /**\n     * Viewport width.\n     */\n    width: number;\n    /**\n     * Viewport height.\n     */\n    height: number;\n    /**\n     * Translation in tile units, computed using text-translate and text-translate-anchor paint style properties.\n     */\n    translation: [number, number];\n};\n\n/**\n * Only for creating synthetic vertices if vertex would otherwise project behind plane of camera\n */\nexport type ProjectionSyntheticVertexArgs = {\n    distanceFromAnchor: number;\n    previousVertex: Point;\n    direction: number;\n    absOffsetX: number;\n};\n\n/**\n * Transform a vertex from tile coordinates to label plane coordinates\n * @param index - index of vertex to project\n * @param projectionContext - necessary data to project a vertex\n * @returns the vertex projected to the label plane\n */\nexport function projectLineVertexToLabelPlane(index: number, projectionContext: SymbolProjectionContext, syntheticVertexArgs: ProjectionSyntheticVertexArgs): Point {\n    const cache = projectionContext.projectionCache;\n\n    if (cache.projections[index]) {\n        return cache.projections[index];\n    }\n    const currentVertex = new Point(\n        projectionContext.lineVertexArray.getx(index),\n        projectionContext.lineVertexArray.gety(index));\n\n    const projection = projectTileCoordinatesToLabelPlane(currentVertex.x, currentVertex.y, projectionContext);\n\n    if (projection.signedDistanceFromCamera > 0) {\n        cache.projections[index] = projection.point;\n        cache.anyProjectionOccluded ||= projection.isOccluded;\n        return projection.point;\n    }\n\n    // The vertex is behind the plane of the camera, so we can't project it\n    // Instead, we'll create a vertex along the line that's far enough to include the glyph\n    const previousLineVertexIndex = index - syntheticVertexArgs.direction;\n    const previousTilePoint = syntheticVertexArgs.distanceFromAnchor === 0 ?\n        projectionContext.tileAnchorPoint :\n        new Point(projectionContext.lineVertexArray.getx(previousLineVertexIndex), projectionContext.lineVertexArray.gety(previousLineVertexIndex));\n\n    // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment\n    const minimumLength = syntheticVertexArgs.absOffsetX - syntheticVertexArgs.distanceFromAnchor + 1;\n    return projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentVertex, syntheticVertexArgs.previousVertex, minimumLength, projectionContext);\n}\n\n/**\n * Projects the given point in tile coordinates to the correct label plane.\n * If pitchWithMap is true, the (rotated) map plane in pixels is used,\n * otherwise screen pixels are used.\n */\nexport function projectTileCoordinatesToLabelPlane(x: number, y: number, projectionContext: SymbolProjectionContext): PointProjection {\n    const translatedX = x + projectionContext.translation[0];\n    const translatedY = y + projectionContext.translation[1];\n    let projection;\n    if (projectionContext.pitchWithMap) {\n        projection = projectWithMatrix(translatedX, translatedY, projectionContext.pitchedLabelPlaneMatrix, elevationAt(projectionContext, translatedX, translatedY));\n        projection.isOccluded = false;\n    } else {\n        projection = projectionContext.transform.projectTileCoordinates(translatedX, translatedY, projectionContext.unwrappedTileID, elevationAt(projectionContext, translatedX, translatedY));\n        projection.point.x = (projection.point.x * 0.5 + 0.5) * projectionContext.width;\n        projection.point.y = (-projection.point.y * 0.5 + 0.5) * projectionContext.height;\n    }\n    return projection;\n}\n\nfunction projectFromLabelPlaneToClipSpace(x: number, y: number, projectionContext: SymbolProjectionContext, pitchedLabelPlaneMatrixInverse: mat4): {x: number; y: number} {\n    if (projectionContext.pitchWithMap) {\n        const pos = [x, y, 0, 1] as vec4;\n        vec4.transformMat4(pos, pos, pitchedLabelPlaneMatrixInverse);\n        const tileX = pos[0] / pos[3];\n        const tileY = pos[1] / pos[3];\n        return projectionContext.transform.projectTileCoordinates(tileX, tileY, projectionContext.unwrappedTileID, elevationAt(projectionContext, tileX, tileY)).point;\n    } else {\n        return {\n            x: (x / projectionContext.width) * 2.0 - 1.0,\n            y: 1.0 - (y / projectionContext.height) * 2.0\n        };\n    }\n}\n\n/**\n * Projects the given point in tile coordinates to the GL clip space (-1..1).\n */\nexport function projectTileCoordinatesToClipSpace(x: number, y: number, projectionContext: SymbolProjectionContext): PointProjection {\n    const projection = projectionContext.transform.projectTileCoordinates(x, y, projectionContext.unwrappedTileID, elevationAt(projectionContext, x, y));\n    return projection;\n}\n\n/**\n * Calculate the normal vector for a line segment\n * @param segmentVector - will be mutated as a tiny optimization\n * @param offset - magnitude of resulting vector\n * @param direction - direction of line traversal\n * @returns a normal vector from the segment, with magnitude equal to offset amount\n */\nexport function transformToOffsetNormal(segmentVector: Point, offset: number, direction: number): Point {\n    return segmentVector._unit()._perp()._mult(offset * direction);\n}\n\n/**\n * Construct offset line segments for the current segment and the next segment, then extend/shrink\n * the segments until they intersect. If the segments are parallel, then they will touch with no modification.\n *\n * Where the line doubles back on itself, the two offset segments are parallel but for rounding error, so their\n * intersection lands arbitrarily far away, possibly behind the start of the current segment, which would lay the\n * glyphs out backwards; they are joined at the offset current vertex instead. Features with the same label are merged\n * end to end, so two features running in opposite directions form such a line.\n *\n * @param index - Index of the current vertex\n * @param prevToCurrentOffsetNormal - Normal vector of the line segment from the previous vertex to the current vertex\n * @param currentVertex - Current (non-offset) vertex projected to the label plane\n * @param lineStartIndex - Beginning index for the line this label is on\n * @param lineEndIndex - End index for the line this label is on\n * @param offsetPreviousVertex - The previous vertex projected to the label plane, and then offset along the previous segments normal\n * @param lineOffsetY - Magnitude of the offset\n * @param projectionContext - Necessary data for tile-to-label-plane projection\n * @returns The point at which the current and next line segments intersect, once offset and extended/shrunk to their meeting point\n */\nexport function findOffsetIntersectionPoint(\n    index: number,\n    prevToCurrentOffsetNormal: Point,\n    currentVertex: Point,\n    lineStartIndex: number,\n    lineEndIndex: number,\n    offsetPreviousVertex: Point,\n    lineOffsetY: number,\n    projectionContext: SymbolProjectionContext,\n    syntheticVertexArgs: ProjectionSyntheticVertexArgs): Point {\n    if (projectionContext.projectionCache.offsets[index]) {\n        return projectionContext.projectionCache.offsets[index];\n    }\n\n    const offsetCurrentVertex = currentVertex.add(prevToCurrentOffsetNormal);\n\n    if (index + syntheticVertexArgs.direction < lineStartIndex || index + syntheticVertexArgs.direction >= lineEndIndex) {\n        // This is the end of the line, no intersection to calculate\n        projectionContext.projectionCache.offsets[index] = offsetCurrentVertex;\n        return offsetCurrentVertex;\n    }\n    // Offset the vertices for the next segment\n    const nextVertex = projectLineVertexToLabelPlane(index + syntheticVertexArgs.direction, projectionContext, syntheticVertexArgs);\n    const currentToNextOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, syntheticVertexArgs.direction);\n    const offsetNextSegmentBegin = currentVertex.add(currentToNextOffsetNormal);\n    const offsetNextSegmentEnd = nextVertex.add(currentToNextOffsetNormal);\n\n    // find the intersection of these two lines\n    // if the lines are parallel, offsetCurrent/offsetNextBegin will touch\n    const doublesBack = isLineDoublingBack(index, syntheticVertexArgs.direction, lineStartIndex, lineEndIndex, projectionContext.lineVertexArray);\n    projectionContext.projectionCache.offsets[index] = doublesBack ? offsetCurrentVertex :\n        findLineIntersection(offsetPreviousVertex, offsetCurrentVertex, offsetNextSegmentBegin, offsetNextSegmentEnd) || offsetCurrentVertex;\n\n    return projectionContext.projectionCache.offsets[index];\n}\n\n/**\n * Whether the line turns straight back on itself at the vertex `index`, reached by walking it in `direction`: the\n * segment after the vertex runs along the segment before it, the other way. Tile coordinates are integers, so the test\n * is exact.\n *\n * A vertex without a neighbour on both sides within `[lineStartIndex, lineEndIndex)` is not a turn at all, so a line\n * end, or a line of a single point, never doubles back. A zero-length segment from a repeated vertex has no direction\n * and does not count either.\n */\nfunction isLineDoublingBack(index: number, direction: number, lineStartIndex: number, lineEndIndex: number, lineVertexArray: SymbolLineVertexArray): boolean {\n    const previous = index - direction;\n    const next = index + direction;\n    if (Math.min(previous, next) < lineStartIndex || Math.max(previous, next) >= lineEndIndex) return false;\n\n    const inX = lineVertexArray.getx(index) - lineVertexArray.getx(previous);\n    const inY = lineVertexArray.gety(index) - lineVertexArray.gety(previous);\n    const outX = lineVertexArray.getx(next) - lineVertexArray.getx(index);\n    const outY = lineVertexArray.gety(next) - lineVertexArray.gety(index);\n    return inX * outY - inY * outX === 0 && inX * outX + inY * outY < 0;\n}\n\n/**\n * Placed Glyph type\n */\ntype PlacedGlyph = {\n    /**\n     * The point at which the glyph should be placed, in label plane coordinates\n     */\n    point: Point;\n    /**\n     * The angle at which the glyph should be placed\n     */\n    angle: number;\n    /**\n     * The label-plane path used to reach this glyph: used only for collision detection\n     */\n    path: Point[];\n};\n\n/*\n * Place a single glyph along its line, projected into the label plane, by iterating outward\n * from the anchor point until the distance traversed in the label plane equals the glyph's\n * offsetX. Returns null if the glyph can't fit on the line geometry.\n */\nexport function placeGlyphAlongLine(\n    offsetX: number,\n    lineOffsetX: number,\n    lineOffsetY: number,\n    flip: boolean,\n    anchorSegment: number,\n    lineStartIndex: number,\n    lineEndIndex: number,\n    projectionContext: SymbolProjectionContext,\n    rotateToLine: boolean): PlacedGlyph | null {\n\n    const combinedOffsetX = flip ?\n        offsetX - lineOffsetX :\n        offsetX + lineOffsetX;\n\n    let direction = combinedOffsetX > 0 ? 1 : -1;\n\n    let angle = 0;\n    if (flip) {\n        // The label needs to be flipped to keep text upright.\n        // Iterate in the reverse direction.\n        direction *= -1;\n        angle = Math.PI;\n    }\n\n    if (direction < 0) angle += Math.PI;\n\n    let currentIndex = direction > 0 ?\n        lineStartIndex + anchorSegment :\n        lineStartIndex + anchorSegment + 1;\n\n    // Project anchor point to viewport and cache it\n    let anchorPoint: Point;\n\n    if (projectionContext.projectionCache.cachedAnchorPoint) {\n        anchorPoint = projectionContext.projectionCache.cachedAnchorPoint;\n    } else {\n        anchorPoint = projectTileCoordinatesToLabelPlane(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point;\n        projectionContext.projectionCache.cachedAnchorPoint = anchorPoint;\n    }\n\n    let currentVertex = anchorPoint;\n    let previousVertex = anchorPoint;\n\n    // offsetPrev and intersectionPoint are analogous to previousVertex and currentVertex\n    // but if there's a line offset they are calculated in parallel as projection happens\n    let offsetIntersectionPoint: Point;\n    let offsetPreviousVertex: Point;\n\n    let distanceFromAnchor = 0;\n    let currentSegmentDistance = 0;\n    const absOffsetX = Math.abs(combinedOffsetX);\n    const pathVertices: Point[] = [];\n\n    let currentLineSegment: Point;\n    while (distanceFromAnchor + currentSegmentDistance <= absOffsetX) {\n        currentIndex += direction;\n\n        // offset does not fit on the projected line\n        if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex)\n            return null;\n\n        // accumulate values from last iteration\n        distanceFromAnchor += currentSegmentDistance;\n        previousVertex = currentVertex;\n        offsetPreviousVertex = offsetIntersectionPoint;\n\n        const syntheticVertexArgs: ProjectionSyntheticVertexArgs = {\n            absOffsetX,\n            direction,\n            distanceFromAnchor,\n            previousVertex\n        };\n\n        // find next vertex in viewport space\n        currentVertex = projectLineVertexToLabelPlane(currentIndex, projectionContext, syntheticVertexArgs);\n        if (lineOffsetY === 0) {\n            // Store vertices for collision detection and update current segment geometry\n            pathVertices.push(previousVertex);\n            currentLineSegment = currentVertex.sub(previousVertex);\n        } else {\n            // Calculate the offset for this section\n            let prevToCurrentOffsetNormal;\n            const prevToCurrent = currentVertex.sub(previousVertex);\n            if (prevToCurrent.mag() === 0) {\n                // We are starting with our anchor point directly on the vertex, so look one vertex ahead\n                // to calculate a normal\n                const nextVertex = projectLineVertexToLabelPlane(currentIndex + direction, projectionContext, syntheticVertexArgs);\n                prevToCurrentOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, direction);\n            } else {\n                prevToCurrentOffsetNormal = transformToOffsetNormal(prevToCurrent, lineOffsetY, direction);\n            }\n            // Initialize offsetPrev on our first iteration, after that it will be pre-calculated\n            offsetPreviousVertex ||= previousVertex.add(prevToCurrentOffsetNormal);\n\n            offsetIntersectionPoint = findOffsetIntersectionPoint(currentIndex, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs);\n\n            pathVertices.push(offsetPreviousVertex);\n            currentLineSegment = offsetIntersectionPoint.sub(offsetPreviousVertex);\n        }\n        currentSegmentDistance = currentLineSegment.mag();\n    }\n\n    // The point is on the current segment. Interpolate to find it.\n    const segmentInterpolationT = (absOffsetX - distanceFromAnchor) / currentSegmentDistance;\n    const p = currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex || previousVertex);\n\n    const segmentAngle = angle + Math.atan2(currentVertex.y - previousVertex.y, currentVertex.x - previousVertex.x);\n\n    pathVertices.push(p);\n\n    return {\n        point: p,\n        angle: rotateToLine ? segmentAngle : 0.0,\n        path: pathVertices\n    };\n}\n\nconst hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]);\n\n// Hide them by moving them offscreen. We still need to add them to the buffer\n// because the dynamic buffer is paired with a static buffer that doesn't get updated.\nexport function hideGlyphs(num: number, dynamicLayoutVertexArray: SymbolDynamicLayoutArray): void {\n    for (let i = 0; i < num; i++) {\n        const offset = dynamicLayoutVertexArray.length;\n        dynamicLayoutVertexArray.resize(offset + 4);\n        // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set\n        // for each set of four vertices, instead of calling addDynamicAttributes for each vertex.\n        dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3);\n    }\n}\n\n// For line label layout, we're not using z output and our w input is always 1\n// This custom matrix transformation ignores those components to make projection faster\nexport function xyTransformMat4(out: vec4, a: vec4, m: mat4): vec4 {\n    const x = a[0], y = a[1];\n    out[0] = m[0] * x + m[4] * y + m[12];\n    out[1] = m[1] * x + m[5] * y + m[13];\n    out[3] = m[3] * x + m[7] * y + m[15];\n    return out;\n}\n\n/**\n * Takes a path of points that was previously projected using the `pitchedLabelPlaneMatrix`\n * and projects it using the map projection's (mercator/globe...) `projectTileCoordinates` function.\n * Returns a new array of the projected points.\n * Does not modify the input array.\n */\nexport function projectPathSpecialProjection(projectedPath: Point[], projectionContext: SymbolProjectionContext): PointProjection[] {\n    const inverseLabelPlaneMatrix = tmpMat4;\n    fastInvertSkewMat4(inverseLabelPlaneMatrix, projectionContext.pitchedLabelPlaneMatrix);\n    return projectedPath.map(p => {\n        const backProjected = projectWithMatrix(p.x, p.y, inverseLabelPlaneMatrix, elevationAt(projectionContext, p.x, p.y));\n        const projected = projectionContext.transform.projectTileCoordinates(\n            backProjected.point.x,\n            backProjected.point.y,\n            projectionContext.unwrappedTileID,\n            elevationAt(projectionContext, backProjected.point.x, backProjected.point.y)\n        );\n        projected.point.x = (projected.point.x * 0.5 + 0.5) * projectionContext.width;\n        projected.point.y = (-projected.point.y * 0.5 + 0.5) * projectionContext.height;\n        return projected;\n    });\n}\n\n/**\n * Takes a path of points projected to screenspace, finds the longest continuous unoccluded segment of that path\n * and returns it.\n * Does not modify the input array.\n */\nexport function pathSlicedToLongestUnoccluded(path: PointProjection[]): PointProjection[] {\n    let longestUnoccludedStart = 0;\n    let longestUnoccludedLength = 0;\n    let currentUnoccludedStart = 0;\n    let currentUnoccludedLength = 0;\n    for (let i = 0; i < path.length; i++) {\n        if (path[i].isOccluded) {\n            currentUnoccludedStart = i + 1;\n            currentUnoccludedLength = 0;\n        } else {\n            currentUnoccludedLength++;\n            if (currentUnoccludedLength > longestUnoccludedLength) {\n                longestUnoccludedLength = currentUnoccludedLength;\n                longestUnoccludedStart = currentUnoccludedStart;\n            }\n        }\n    }\n    return path.slice(longestUnoccludedStart, longestUnoccludedStart + longestUnoccludedLength);\n}\n", "import Point from '@mapbox/point-geometry';\nimport {clipLine} from './clip_line.ts';\nimport {PathInterpolator} from './path_interpolator.ts';\nimport {getSymbolElevation} from './symbol_elevation.ts';\nimport * as intersectionTests from '../util/intersection_tests.ts';\nimport {GridIndex} from './grid_index.ts';\nimport {mat4, vec4} from 'gl-matrix';\nimport {clamp, getAABB} from '../util/util.ts';\nimport {Bounds} from '../geo/bounds.ts';\nimport {type PointProjection, type SymbolProjectionContext, getTileSkewVectors, pathSlicedToLongestUnoccluded, placeFirstAndLastGlyph, projectPathSpecialProjection, xyTransformMat4} from '../symbol/projection.ts';\nimport ONE_EM from '../symbol/one_em.ts';\n\nimport type {IReadonlyTransform, GetElevation} from '../geo/transform_interface.ts';\nimport type {SingleCollisionBox} from '../data/bucket/symbol_bucket.ts';\nimport type {\n    GlyphOffsetArray,\n    PlacedSymbol,\n    SymbolLineVertexArray\n} from '../data/array_types.g.ts';\nimport type {OverlapMode} from '../style/style_layer/overlap_mode.ts';\nimport type {OverscaledTileID, UnwrappedTileID} from '../tile/tile_id.ts';\n\n// When a symbol crosses the edge that causes it to be included in\n// collision detection, it will cause changes in the symbols around\n// it. This constant specifies how many pixels to pad the edge of\n// the viewport for collision detection so that the bulk of the changes\n// occur offscreen. Making this constant greater increases label\n// stability, but it's expensive.\nexport const viewportPadding = 100;\n\nexport type PlacedCircles = {\n    circles: number[];\n    offscreen: boolean;\n    collisionDetected: boolean;\n};\n\nexport type PlacedBox = {\n    box: number[];\n    placeable: boolean;\n    offscreen: boolean;\n    occluded: boolean;\n};\n\nexport type FeatureKey = {\n    bucketInstanceId: number;\n    featureIndex: number;\n    collisionGroupID: number;\n    overlapMode: OverlapMode;\n};\n\ntype ProjectedBox = {\n    /**\n     * The AABB in the format [minX, minY, maxX, maxY].\n     */\n    box: [number, number, number, number];\n    allPointsOccluded: boolean;\n};\n\n/**\n * @internal\n * A collision index used to prevent symbols from overlapping. It keep tracks of\n * where previous symbols have been placed and is used to check if a new\n * symbol overlaps with any previously added symbols.\n *\n * There are two steps to insertion: first placeCollisionBox/Circles checks if\n * there's room for a symbol, then insertCollisionBox/Circles actually puts the\n * symbol in the index. The two step process allows paired symbols to be inserted\n * together even if they overlap.\n */\nexport class CollisionIndex {\n    grid: GridIndex<FeatureKey>;\n    ignoredGrid: GridIndex<FeatureKey>;\n    transform: IReadonlyTransform;\n    pitchFactor: number;\n    screenRightBoundary: number;\n    screenBottomBoundary: number;\n    gridRightBoundary: number;\n    gridBottomBoundary: number;\n\n    // With perspectiveRatio the fontsize is calculated for tilted maps (near = bigger, far = smaller).\n    // The cutoff defines a threshold to no longer render labels near the horizon.\n    perspectiveRatioCutoff: number;\n\n    constructor(\n        transform: IReadonlyTransform,\n        grid: GridIndex<FeatureKey> = new GridIndex<FeatureKey>(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25),\n        ignoredGrid: GridIndex<FeatureKey> = new GridIndex<FeatureKey>(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)\n    ) {\n        this.transform = transform;\n\n        this.grid = grid;\n        this.ignoredGrid = ignoredGrid;\n        this.pitchFactor = Math.cos(transform.pitch * Math.PI / 180.0) * transform.cameraToCenterDistance;\n\n        this.screenRightBoundary = transform.width + viewportPadding;\n        this.screenBottomBoundary = transform.height + viewportPadding;\n        this.gridRightBoundary = transform.width + 2 * viewportPadding;\n        this.gridBottomBoundary = transform.height + 2 * viewportPadding;\n\n        this.perspectiveRatioCutoff = 0.6;\n    }\n\n    placeCollisionBox(\n        collisionBox: SingleCollisionBox,\n        overlapMode: OverlapMode,\n        textPixelRatio: number,\n        tileID: OverscaledTileID,\n        unwrappedTileID: UnwrappedTileID,\n        pitchWithMap: boolean,\n        rotateWithMap: boolean,\n        translation: [number, number],\n        collisionGroupPredicate?: (key: FeatureKey) => boolean,\n        getElevation?: GetElevation,\n        shift?: Point,\n        simpleProjectionMatrix?: mat4,\n        heightOffset: number = 0,\n        heightAnchorGround: boolean = true,\n    ): PlacedBox {\n        const x = collisionBox.anchorPointX + translation[0];\n        const y = collisionBox.anchorPointY + translation[1];\n        const projectedPoint = this.projectAndGetPerspectiveRatio(\n            x,\n            y,\n            unwrappedTileID,\n            getSymbolElevation(getElevation, x, y, heightOffset, heightAnchorGround),\n            simpleProjectionMatrix\n        );\n\n        const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;\n        let projectedBox: ProjectedBox;\n\n        if (!pitchWithMap && !rotateWithMap) {\n            // Fast path for common symbols\n            const pointX = projectedPoint.x + (shift ? shift.x * tileToViewport : 0);\n            const pointY = projectedPoint.y + (shift ? shift.y * tileToViewport : 0);\n            projectedBox = {\n                allPointsOccluded: false,\n                box: [\n                    pointX + collisionBox.x1 * tileToViewport,\n                    pointY + collisionBox.y1 * tileToViewport,\n                    pointX + collisionBox.x2 * tileToViewport,\n                    pointY + collisionBox.y2 * tileToViewport,\n                ]\n            };\n        } else {\n            projectedBox = this._projectCollisionBox(\n                collisionBox,\n                tileToViewport,\n                tileID,\n                unwrappedTileID,\n                pitchWithMap,\n                rotateWithMap,\n                translation,\n                projectedPoint,\n                getElevation,\n                shift,\n                simpleProjectionMatrix,\n                heightOffset,\n                heightAnchorGround,\n            );\n        }\n\n        const [tlX, tlY, brX, brY] = projectedBox.box;\n\n        // Conditions are ordered from the fastest to evaluate to the slowest.\n        const occluded = pitchWithMap ? projectedBox.allPointsOccluded : projectedPoint.isOccluded;\n\n        let unplaceable = occluded;\n        unplaceable ||= projectedPoint.perspectiveRatio < this.perspectiveRatioCutoff;\n        unplaceable ||= !this.isInsideGrid(tlX, tlY, brX, brY);\n\n        if (unplaceable ||\n            (overlapMode !== 'always' && this.grid.hitTest(tlX, tlY, brX, brY, overlapMode, collisionGroupPredicate))) {\n            return {\n                box: [tlX, tlY, brX, brY],\n                placeable: false,\n                offscreen: false,\n                occluded\n            };\n        }\n\n        return {\n            box: [tlX, tlY, brX, brY],\n            placeable: true,\n            offscreen: this.isOffscreen(tlX, tlY, brX, brY),\n            occluded\n        };\n    }\n\n    placeCollisionCircles(\n        overlapMode: OverlapMode,\n        symbol: PlacedSymbol,\n        lineVertexArray: SymbolLineVertexArray,\n        glyphOffsetArray: GlyphOffsetArray,\n        fontSize: number,\n        unwrappedTileID: UnwrappedTileID,\n        pitchedLabelPlaneMatrix: mat4,\n        showCollisionCircles: boolean,\n        pitchWithMap: boolean,\n        collisionGroupPredicate: (key: FeatureKey) => boolean,\n        circlePixelDiameter: number,\n        textPixelPadding: number,\n        translation: [number, number],\n        getElevation: GetElevation | undefined\n    ): PlacedCircles {\n        const placedCollisionCircles = [];\n\n        const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n        const perspectiveRatio = this.getPerspectiveRatio(tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, unwrappedTileID, getElevation?.(tileUnitAnchorPoint.x, tileUnitAnchorPoint.y));\n\n        const labelPlaneFontSize = pitchWithMap ? (fontSize * this.transform.getPitchedTextCorrection(symbol.anchorX, symbol.anchorY, unwrappedTileID) / perspectiveRatio) : fontSize * perspectiveRatio;\n        const labelPlaneFontScale = labelPlaneFontSize / ONE_EM;\n\n        const projectionCache = {projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false};\n        const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;\n        const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;\n\n        const projectionContext: SymbolProjectionContext = {\n            getElevation,\n            pitchedLabelPlaneMatrix,\n            lineVertexArray,\n            pitchWithMap,\n            projectionCache,\n            transform: this.transform,\n            tileAnchorPoint: tileUnitAnchorPoint,\n            unwrappedTileID,\n            width: this.transform.width,\n            height: this.transform.height,\n            translation\n        };\n\n        const firstAndLastGlyph = placeFirstAndLastGlyph(\n            labelPlaneFontScale,\n            glyphOffsetArray,\n            lineOffsetX,\n            lineOffsetY,\n            /*flip*/ false,\n            symbol,\n            false,\n            projectionContext);\n\n        let collisionDetected = false;\n        let inGrid = false;\n        let entirelyOffscreen = true;\n\n        if (firstAndLastGlyph) {\n            const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding;\n            const screenPlaneMin = new Point(-viewportPadding, -viewportPadding);\n            const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary);\n            const interpolator = new PathInterpolator();\n\n            // Construct a projected path from projected line vertices. Anchor points are ignored and removed\n            const first = firstAndLastGlyph.first;\n            const last = firstAndLastGlyph.last;\n\n            let projectedPath: Point[] = [];\n            for (let i = first.path.length - 1; i >= 1; i--) {\n                projectedPath.push(first.path[i]);\n            }\n            for (let i = 1; i < last.path.length; i++) {\n                projectedPath.push(last.path[i]);\n            }\n\n            // Tolerate a slightly longer distance than one diameter between two adjacent circles\n            const circleDist = radius * 2.5;\n\n            // The path might need to be converted into screen space if a pitched map is used as the label space\n            if (pitchWithMap) {\n                const screenSpacePath = this.projectPathToScreenSpace(projectedPath, projectionContext);\n                // Do not try to place collision circles if even one of the points is behind the camera.\n                // This is a plausible scenario with big camera pitch angles\n                if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) {\n                    projectedPath = [];\n                } else {\n                    projectedPath = screenSpacePath.map(p => p.point);\n                }\n            }\n\n            let segments = [];\n\n            if (projectedPath.length > 0) {\n                // Quickly check if the path is fully inside or outside of the padded collision region.\n                // For overlapping paths we'll only create collision circles for the visible segments\n                const minPoint = projectedPath[0].clone();\n                const maxPoint = projectedPath[0].clone();\n\n                for (let i = 1; i < projectedPath.length; i++) {\n                    minPoint.x = Math.min(minPoint.x, projectedPath[i].x);\n                    minPoint.y = Math.min(minPoint.y, projectedPath[i].y);\n                    maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x);\n                    maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y);\n                }\n\n                if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x &&\n                    minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) {\n                    // Quad fully visible\n                    segments = [projectedPath];\n                } else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x ||\n                    maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) {\n                    // Not visible\n                    segments = [];\n                } else {\n                    segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);\n                }\n            }\n\n            for (const seg of segments) {\n                // interpolate positions for collision circles. Add a small padding to both ends of the segment\n                interpolator.reset(seg, radius * 0.25);\n\n                let numCircles = 0;\n\n                if (interpolator.length <= 0.5 * radius) {\n                    numCircles = 1;\n                } else {\n                    numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;\n                }\n\n                for (let i = 0; i < numCircles; i++) {\n                    const t = i / Math.max(numCircles - 1, 1);\n                    const circlePosition = interpolator.lerp(t);\n\n                    // add viewport padding to the position and perform initial collision check\n                    const centerX = circlePosition.x + viewportPadding;\n                    const centerY = circlePosition.y + viewportPadding;\n\n                    placedCollisionCircles.push(centerX, centerY, radius, 0);\n\n                    const x1 = centerX - radius;\n                    const y1 = centerY - radius;\n                    const x2 = centerX + radius;\n                    const y2 = centerY + radius;\n\n                    entirelyOffscreen &&= this.isOffscreen(x1, y1, x2, y2);\n                    inGrid ||= this.isInsideGrid(x1, y1, x2, y2);\n\n                    if (overlapMode !== 'always' && this.grid.hitTestCircle(centerX, centerY, radius, overlapMode, collisionGroupPredicate)) {\n                        // Don't early exit if we're showing the debug circles because we still want to calculate\n                        // which circles are in use\n                        collisionDetected = true;\n                        if (!showCollisionCircles) {\n                            return {\n                                circles: [],\n                                offscreen: false,\n                                collisionDetected\n                            };\n                        }\n                    }\n                }\n            }\n        }\n\n        return {\n            circles: ((!showCollisionCircles && collisionDetected) || !inGrid || perspectiveRatio < this.perspectiveRatioCutoff) ? [] : placedCollisionCircles,\n            offscreen: entirelyOffscreen,\n            collisionDetected\n        };\n    }\n\n    projectPathToScreenSpace(projectedPath: Point[], projectionContext: SymbolProjectionContext): PointProjection[] {\n        const screenSpacePath = projectPathSpecialProjection(projectedPath, projectionContext);\n        // We don't want to generate screenspace collision circles for parts of the line that\n        // are occluded by the planet itself. Find the longest segment of the path that is\n        // not occluded, and remove everything else.\n        return pathSlicedToLongestUnoccluded(screenSpacePath);\n    }\n\n    /**\n     * Because the geometries in the CollisionIndex are an approximation of the shape of\n     * symbols on the map, we use the CollisionIndex to look up the symbol part of\n     * `queryRenderedFeatures`.\n     */\n    queryRenderedSymbols(viewportQueryGeometry: Point[]): Record<number, number[]> {\n        if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) {\n            return {};\n        }\n\n        const query = [];\n        const bounds = new Bounds();\n        for (const point of viewportQueryGeometry) {\n            const gridPoint = new Point(point.x + viewportPadding, point.y + viewportPadding);\n            bounds.extend(gridPoint);\n            query.push(gridPoint);\n        }\n\n        const {minX, minY, maxX, maxY} = bounds;\n        const features = this.grid.query(minX, minY, maxX, maxY)\n            .concat(this.ignoredGrid.query(minX, minY, maxX, maxY));\n\n        const seenFeatures = {};\n        const result = {};\n\n        for (const feature of features) {\n            const featureKey = feature.key;\n            // Skip already seen features.\n            if (seenFeatures[featureKey.bucketInstanceId] === undefined) {\n                seenFeatures[featureKey.bucketInstanceId] = {};\n            }\n            if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {\n                continue;\n            }\n\n            // Check if query intersects with the feature box\n            // \"Collision Circles\" for line labels are treated as boxes here\n            // Since there's no actual collision taking place, the circle vs. square\n            // distinction doesn't matter as much, and box geometry is easier\n            // to work with.\n            const bbox = [\n                new Point(feature.x1, feature.y1),\n                new Point(feature.x2, feature.y1),\n                new Point(feature.x2, feature.y2),\n                new Point(feature.x1, feature.y2)\n            ];\n            if (!intersectionTests.polygonIntersectsPolygon(query, bbox)) {\n                continue;\n            }\n\n            seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;\n            if (result[featureKey.bucketInstanceId] === undefined) {\n                result[featureKey.bucketInstanceId] = [];\n            }\n            result[featureKey.bucketInstanceId].push(featureKey.featureIndex);\n        }\n\n        return result;\n    }\n\n    insertCollisionBox(collisionBox: number[], overlapMode: OverlapMode, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number): void {\n        const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n        const key = {bucketInstanceId, featureIndex, collisionGroupID, overlapMode};\n        grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);\n    }\n\n    insertCollisionCircles(collisionCircles: number[], overlapMode: OverlapMode, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number): void {\n        const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n        const key = {bucketInstanceId, featureIndex, collisionGroupID, overlapMode};\n        for (let k = 0; k < collisionCircles.length; k += 4) {\n            grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);\n        }\n    }\n\n    projectAndGetPerspectiveRatio(x: number, y: number, unwrappedTileID: UnwrappedTileID, elevation?: number, simpleProjectionMatrix?: mat4): {\n        x: number;\n        y: number;\n        perspectiveRatio: number;\n        isOccluded: boolean;\n        signedDistanceFromCamera: number;\n    } {\n        if (simpleProjectionMatrix) {\n            // This branch is a fast-path for mercator transform.\n            // The code here is a copy of MercatorTransform.projectTileCoordinates, slightly modified for extra performance.\n            // This has a huge impact for some reason.\n            let pos;\n            if (elevation != null) { // slow because of handle z-index\n                pos = [x, y, elevation, 1] as vec4;\n                vec4.transformMat4(pos, pos, simpleProjectionMatrix);\n            } else { // fast because of ignore z-index\n                pos = [x, y, 0, 1] as vec4;\n                xyTransformMat4(pos, pos, simpleProjectionMatrix);\n            }\n            const w = pos[3];\n            return {\n                x: (((pos[0] / w + 1) / 2) * this.transform.width) + viewportPadding,\n                y: (((-pos[1] / w + 1) / 2) * this.transform.height) + viewportPadding,\n                perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / w),\n                isOccluded: false,\n                signedDistanceFromCamera: w\n            };\n        } else {\n            const projected = this.transform.projectTileCoordinates(x, y, unwrappedTileID, elevation);\n            return {\n                x: (((projected.point.x + 1) / 2) * this.transform.width) + viewportPadding,\n                y: (((-projected.point.y + 1) / 2) * this.transform.height) + viewportPadding,\n                // See perspective ratio comment in symbol_sdf.vertex\n                // We're doing collision detection in viewport space so we need\n                // to scale down boxes in the distance\n                perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera),\n                isOccluded: projected.isOccluded,\n                signedDistanceFromCamera: projected.signedDistanceFromCamera\n            };\n        }\n    }\n\n    getPerspectiveRatio(x: number, y: number, unwrappedTileID: UnwrappedTileID, elevation?: number): number {\n        // We don't care about the actual projected point, just its W component.\n        const projected = this.transform.projectTileCoordinates(x, y, unwrappedTileID, elevation);\n        return 0.5 + 0.5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera);\n    }\n\n    isOffscreen(x1: number, y1: number, x2: number, y2: number): boolean {\n        return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary;\n    }\n\n    isInsideGrid(x1: number, y1: number, x2: number, y2: number): boolean {\n        return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;\n    }\n\n    /*\n    * Returns a matrix for transforming collision shapes to viewport coordinate space.\n    * Use this function to render e.g. collision circles on the screen.\n    *   example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos\n    */\n    getViewportMatrix(): mat4 {\n        const m = mat4.identity([]);\n        mat4.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]);\n        return m;\n    }\n\n    /**\n     * Applies all layout+paint properties of the given box in order to find as good approximation of its screen-space bounding box as possible.\n     */\n    private _projectCollisionBox(\n        collisionBox: SingleCollisionBox,\n        tileToViewport: number,\n        tileID: OverscaledTileID,\n        unwrappedTileID: UnwrappedTileID,\n        pitchWithMap: boolean,\n        rotateWithMap: boolean,\n        translation: [number, number],\n        projectedPoint: {x: number; y: number; perspectiveRatio: number; signedDistanceFromCamera: number},\n        getElevation?: GetElevation,\n        shift?: Point,\n        simpleProjectionMatrix?: mat4,\n        heightOffset: number = 0,\n        heightAnchorGround: boolean = true,\n    ): ProjectedBox {\n        // These vectors are valid both for screen space viewport-rotation-aligned texts and for pitch-align: map texts that are map-rotation-aligned.\n        let vecEastX = 1;\n        let vecEastY = 0;\n        let vecSouthX = 0;\n        let vecSouthY = 1;\n\n        const translatedAnchorX = collisionBox.anchorPointX + translation[0];\n        const translatedAnchorY = collisionBox.anchorPointY + translation[1];\n\n        if (rotateWithMap && !pitchWithMap) {\n            // Handles screen space texts that are always aligned east-west.\n            const projectedEast = this.projectAndGetPerspectiveRatio(\n                translatedAnchorX + 1,\n                translatedAnchorY,\n                unwrappedTileID,\n                getSymbolElevation(getElevation, translatedAnchorX + 1, translatedAnchorY, heightOffset, heightAnchorGround),\n                simpleProjectionMatrix,\n            );\n            const toEastX = projectedEast.x - projectedPoint.x;\n            const toEastY = projectedEast.y - projectedPoint.y;\n            const angle = Math.atan(toEastY / toEastX) + (toEastX < 0 ? Math.PI : 0);\n            const sin = Math.sin(angle);\n            const cos = Math.cos(angle);\n            vecEastX = cos;\n            vecEastY = sin;\n            vecSouthX = -sin;\n            vecSouthY = cos;\n        } else if (!rotateWithMap && pitchWithMap) {\n            // Handles pitch-align: map texts that are always aligned with the viewport's X axis.\n            const skew = getTileSkewVectors(this.transform);\n            vecEastX = skew.vecEast[0];\n            vecEastY = skew.vecEast[1];\n            vecSouthX = skew.vecSouth[0];\n            vecSouthY = skew.vecSouth[1];\n        }\n\n        // Configuration for screen space offsets\n        let basePointX = projectedPoint.x;\n        let basePointY = projectedPoint.y;\n        let distanceMultiplier = tileToViewport;\n\n        if (pitchWithMap) {\n            // Configuration for tile space (map-pitch-aligned) offsets\n            basePointX = translatedAnchorX;\n            basePointY = translatedAnchorY;\n\n            const zoomFraction = this.transform.zoom - tileID.overscaledZ;\n            distanceMultiplier = Math.pow(2, -zoomFraction);\n            distanceMultiplier *= this.transform.getPitchedTextCorrection(translatedAnchorX, translatedAnchorY, unwrappedTileID);\n\n            // This next correction can't be applied when variable anchors are in use.\n            if (!shift) {\n                // Shader applies a perspective size correction, we need to apply the same correction.\n                // For non-pitchWithMap texts, this is handled above by multiplying `textPixelRatio` with `projectedPoint.perspectiveRatio`,\n                // which is equivalent to the non-pitchWithMap branch of the GLSL code.\n                // Here, we compute and apply the pitchWithMap branch.\n                // See the computation of `perspective_ratio` in the symbol vertex shaders for the GLSL code.\n                const distanceRatio = projectedPoint.signedDistanceFromCamera / this.transform.cameraToCenterDistance;\n                const perspectiveRatio = clamp(0.5 + 0.5 * distanceRatio, 0.0, 4.0); // Same clamp as what is used in the shader.\n                distanceMultiplier *= perspectiveRatio;\n            }\n        }\n\n        if (shift) {\n            // Variable anchors are in use\n            basePointX += vecEastX * shift.x * distanceMultiplier + vecSouthX * shift.y * distanceMultiplier;\n            basePointY += vecEastY * shift.x * distanceMultiplier + vecSouthY * shift.y * distanceMultiplier;\n        }\n\n        const offsetXmin = collisionBox.x1 * distanceMultiplier;\n        const offsetXmax = collisionBox.x2 * distanceMultiplier;\n        const offsetXhalf = (offsetXmin + offsetXmax) / 2;\n        const offsetYmin = collisionBox.y1 * distanceMultiplier;\n        const offsetYmax = collisionBox.y2 * distanceMultiplier;\n        const offsetYhalf = (offsetYmin + offsetYmax) / 2;\n\n        // 0--1--2\n        // |     |\n        // 7     3\n        // |     |\n        // 6--5--4\n        const offsetsArray: Array<{offsetX: number; offsetY: number}> = [\n            {offsetX: offsetXmin,  offsetY: offsetYmin},\n            {offsetX: offsetXhalf, offsetY: offsetYmin},\n            {offsetX: offsetXmax,  offsetY: offsetYmin},\n            {offsetX: offsetXmax,  offsetY: offsetYhalf},\n            {offsetX: offsetXmax,  offsetY: offsetYmax},\n            {offsetX: offsetXhalf, offsetY: offsetYmax},\n            {offsetX: offsetXmin,  offsetY: offsetYmax},\n            {offsetX: offsetXmin,  offsetY: offsetYhalf}\n        ];\n\n        let points: Point[] = [];\n\n        for (const {offsetX, offsetY} of offsetsArray) {\n            points.push(new Point(\n                basePointX + vecEastX * offsetX + vecSouthX * offsetY,\n                basePointY + vecEastY * offsetX + vecSouthY * offsetY\n            ));\n        }\n\n        // Is any point of the collision shape visible on the globe (on beyond horizon)?\n        let anyPointVisible = false;\n\n        if (pitchWithMap) {\n            const projected = points.map(p => this.projectAndGetPerspectiveRatio(p.x, p.y, unwrappedTileID, getSymbolElevation(getElevation, p.x, p.y, heightOffset, heightAnchorGround), simpleProjectionMatrix));\n\n            // Is at least one of the projected points NOT behind the horizon?\n            anyPointVisible = projected.some(p => !p.isOccluded);\n\n            points = projected.map(p => new Point(p.x, p.y));\n        } else {\n            // Labels that are not pitchWithMap cannot ever hide behind the horizon.\n            anyPointVisible = true;\n        }\n\n        return {\n            box: getAABB(points),\n            allPointsOccluded: !anyPointVisible\n        };\n    }\n}\n", "import {CollisionIndex, viewportPadding} from './collision_index.ts';\nimport {EXTENT} from '../data/extent.ts';\nimport * as symbolSize from './symbol_size.ts';\nimport * as projection from './projection.ts';\nimport {getAnchorJustification} from './symbol_layout.ts';\nimport {getAnchorAlignment, WritingMode} from './shaping.ts';\nimport {pixelsToTileUnits} from '../source/pixels_to_tile_units.ts';\nimport Point from '@mapbox/point-geometry';\nimport {getOverlapMode, type OverlapMode} from '../style/style_layer/overlap_mode.ts';\nimport {TextAnchorEnum, type TextAnchor} from '../style/style_layer/variable_text_anchor.ts';\nimport {translatePosition, warnOnce} from '../util/util.ts';\nimport {symbolInstance as symbolInstanceLayout} from '../data/bucket/symbol_attributes.ts';\n\nimport type {mat4} from 'gl-matrix';\nimport type {FeatureKey, PlacedBox, PlacedCircles} from './collision_index.ts';\nimport type {IReadonlyTransform, GetElevation} from '../geo/transform_interface.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {PossiblyEvaluated} from '../style/properties.ts';\nimport type {SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated} from '../style/style_layer/symbol_style_layer_properties.g.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {SymbolBucket, CollisionArrays, SingleCollisionBox, SymbolBuffers} from '../data/bucket/symbol_bucket.ts';\nimport type {CollisionBoxArray, CollisionVertexArray, SymbolInstance, TextAnchorOffset} from '../data/array_types.g.ts';\nimport type {FeatureIndex} from '../data/feature_index.ts';\nimport type {OverscaledTileID, UnwrappedTileID} from '../tile/tile_id.ts';\nimport type {Terrain} from '../render/terrain.ts';\n\nclass OpacityState {\n    opacity: number;\n    placed: boolean;\n    constructor(prevState: OpacityState, increment: number, placed: boolean, skipFade?: boolean | null) {\n        if (prevState) {\n            this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment)));\n        } else {\n            this.opacity = (skipFade && placed) ? 1 : 0;\n        }\n        this.placed = placed;\n    }\n    isHidden(): boolean {\n        return this.opacity === 0 && !this.placed;\n    }\n}\n\nclass JointOpacityState {\n    text: OpacityState;\n    icon: OpacityState;\n    constructor(prevState: JointOpacityState, increment: number, placedText: boolean, placedIcon: boolean, skipFade?: boolean | null) {\n        this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade);\n        this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade);\n    }\n    isHidden(): boolean {\n        return this.text.isHidden() && this.icon.isHidden();\n    }\n}\n\nclass JointPlacement {\n    text: boolean;\n    icon: boolean;\n    // skipFade = outside viewport, but within CollisionIndex::viewportPadding px of the edge\n    // Because these symbols aren't onscreen yet, we can skip the \"fade in\" animation,\n    // and if a subsequent viewport change brings them into view, they'll be fully\n    // visible right away.\n    skipFade: boolean;\n    constructor(text: boolean, icon: boolean, skipFade: boolean) {\n        this.text = text;\n        this.icon = icon;\n        this.skipFade = skipFade;\n    }\n}\n\nexport class RetainedQueryData {\n    bucketInstanceId: number;\n    featureIndex: FeatureIndex;\n    sourceLayerIndex: number;\n    bucketIndex: number;\n    tileID: OverscaledTileID;\n    featureSortOrder: number[];\n    constructor(bucketInstanceId: number,\n        featureIndex: FeatureIndex,\n        sourceLayerIndex: number,\n        bucketIndex: number,\n        tileID: OverscaledTileID) {\n        this.bucketInstanceId = bucketInstanceId;\n        this.featureIndex = featureIndex;\n        this.sourceLayerIndex = sourceLayerIndex;\n        this.bucketIndex = bucketIndex;\n        this.tileID = tileID;\n    }\n}\n\ntype CollisionGroup = {\n    ID: number;\n    predicate?: (key: FeatureKey) => boolean;\n};\n\nclass CollisionGroups {\n    collisionGroups: {[groupName: string]: CollisionGroup};\n    maxGroupID: number;\n    crossSourceCollisions: boolean;\n\n    constructor(crossSourceCollisions: boolean) {\n        this.crossSourceCollisions = crossSourceCollisions;\n        this.maxGroupID = 0;\n        this.collisionGroups = {};\n    }\n\n    get(sourceID: string): CollisionGroup {\n        // The predicate/groupID mechanism allows for arbitrary grouping,\n        // but the current interface defines one source == one group when\n        // crossSourceCollisions == true.\n        if (!this.crossSourceCollisions) {\n            if (!this.collisionGroups[sourceID]) {\n                const nextGroupID = ++this.maxGroupID;\n                this.collisionGroups[sourceID] = {\n                    ID: nextGroupID,\n                    predicate: (key) => {\n                        return key.collisionGroupID === nextGroupID;\n                    }\n                };\n            }\n            return this.collisionGroups[sourceID];\n        } else {\n            return {ID: 0, predicate: null};\n        }\n    }\n}\n\nfunction calculateVariableLayoutShift(\n    anchor: TextAnchor,\n    width: number,\n    height: number,\n    textOffset: [number, number],\n    textBoxScale: number\n): Point {\n    const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n    const shiftX = -(horizontalAlign - 0.5) * width;\n    const shiftY = -(verticalAlign - 0.5) * height;\n    return new Point(\n        shiftX + textOffset[0] * textBoxScale,\n        shiftY + textOffset[1] * textBoxScale\n    );\n}\n\nexport type VariableOffset = {\n    textOffset: [number, number];\n    width: number;\n    height: number;\n    anchor: TextAnchor;\n    textBoxScale: number;\n    prevAnchor?: TextAnchor;\n};\n\ntype TileLayerParameters = {\n    bucket: SymbolBucket;\n    layout: PossiblyEvaluated<SymbolLayoutProps, SymbolLayoutPropsPossiblyEvaluated>;\n    translationText: [number, number];\n    translationIcon: [number, number];\n    unwrappedTileID: UnwrappedTileID;\n    pitchedLabelPlaneMatrix: mat4;\n    scale: number;\n    textPixelRatio: number;\n    holdingForFade: boolean;\n    collisionBoxArray: CollisionBoxArray;\n    partiallyEvaluatedTextSize: {\n        uSize: number;\n        uSizeT: number;\n    };\n    collisionGroup: CollisionGroup;\n};\n\nexport type BucketPart = {\n    sortKey?: number | void;\n    symbolInstanceStart: number;\n    symbolInstanceEnd: number;\n    parameters: TileLayerParameters;\n};\n\nexport type CrossTileID = string | number;\n\n/** Where `crossTileID` sits within one `SymbolInstanceArray` element, counted in uint32s. */\nconst CROSS_TILE_ID_UINT32_OFFSET: number =\n    symbolInstanceLayout.members.find(member => member.name === 'crossTileID').offset / 4;\n\n/** What the last rewrite of a bucket's opacity buffers read, one entry per symbol. */\ntype OpacityInputs = {\n    crossTileIDs: number[];\n    /** True for every symbol whose label another bucket is drawing. */\n    duplicates: boolean[];\n};\n\nexport class Placement {\n    transform: IReadonlyTransform;\n    terrain: Terrain;\n    collisionIndex: CollisionIndex;\n    placements: {\n        [_ in CrossTileID]: JointPlacement;\n    };\n    opacities: {\n        [_ in CrossTileID]: JointOpacityState;\n    };\n    variableOffsets: {\n        [_ in CrossTileID]: VariableOffset;\n    };\n    placedOrientations: {\n        [_ in CrossTileID]: number;\n    };\n    commitTime: number;\n    prevZoomAdjustment: number;\n    lastPlacementChangeTime: number;\n    stale: boolean;\n    fadeDuration: number;\n    retainedQueryData: {\n        [_: number]: RetainedQueryData;\n    };\n    collisionGroups: CollisionGroups;\n    prevPlacement: Placement;\n    zoomAtLastRecencyCheck: number;\n    collisionCircleArrays: {\n        [k in any]: number[];\n    };\n    collisionBoxArrays: Map<number, Map<number, {\n        text: number[];\n        icon: number[];\n    }>>;\n    lastOpacityInputs: WeakMap<SymbolBucket, OpacityInputs>;\n\n    constructor(transform: IReadonlyTransform, terrain: Terrain, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement) {\n        this.transform = transform.clone();\n        this.terrain = terrain;\n        this.collisionIndex = new CollisionIndex(this.transform);\n        this.placements = {};\n        this.opacities = {};\n        this.variableOffsets = {};\n        this.stale = false;\n        this.commitTime = 0;\n        this.fadeDuration = fadeDuration;\n        this.retainedQueryData = {};\n        this.collisionGroups = new CollisionGroups(crossSourceCollisions);\n        this.collisionCircleArrays = {};\n        this.collisionBoxArrays = new Map<number, Map<number, {\n            text: number[];\n            icon: number[];\n        }>>();\n        this.lastOpacityInputs = new WeakMap();\n\n        this.prevPlacement = prevPlacement;\n        if (prevPlacement) {\n            prevPlacement.prevPlacement = undefined; // Only hold on to one placement back\n        }\n\n        this.placedOrientations = {};\n    }\n\n    private _getTerrainElevationFunc(tileID: OverscaledTileID): GetElevation | undefined {\n        const terrain = this.terrain;\n        if (!terrain) return undefined;\n        return (x: number, y: number) => terrain.getElevation(tileID, x, y);\n    }\n\n    getBucketParts(results: BucketPart[], styleLayer: StyleLayer, tile: Tile, sortAcrossTiles: boolean): void {\n        const symbolBucket = (tile.getBucket(styleLayer) as SymbolBucket);\n        const bucketFeatureIndex = tile.latestFeatureIndex;\n        if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0])\n            return;\n\n        const collisionBoxArray = tile.collisionBoxArray;\n\n        const layout = symbolBucket.layers[0].layout;\n        const paint = symbolBucket.layers[0].paint;\n\n        const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);\n        const textPixelRatio = tile.tileSize / EXTENT;\n\n        const unwrappedTileID = tile.tileID.toUnwrapped();\n\n        const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n        const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom);\n\n        const translationText = translatePosition(\n            this.collisionIndex.transform,\n            tile,\n            paint.get('text-translate'),\n            paint.get('text-translate-anchor'),);\n\n        const translationIcon = translatePosition(\n            this.collisionIndex.transform,\n            tile,\n            paint.get('icon-translate'),\n            paint.get('icon-translate-anchor'),);\n\n        const pitchedLabelPlaneMatrix = projection.getPitchedLabelPlaneMatrix(rotateWithMap, this.transform, pixelsToTiles);\n\n        // As long as this placement lives, we have to hold onto this bucket's\n        // matching FeatureIndex/data for querying purposes\n        this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(\n            symbolBucket.bucketInstanceId,\n            bucketFeatureIndex,\n            symbolBucket.sourceLayerIndex,\n            symbolBucket.index,\n            tile.tileID\n        );\n\n        const parameters: TileLayerParameters = {\n            bucket: symbolBucket,\n            layout,\n            translationText,\n            translationIcon,\n            unwrappedTileID,\n            pitchedLabelPlaneMatrix,\n            scale,\n            textPixelRatio,\n            holdingForFade: tile.holdingForSymbolFade(),\n            collisionBoxArray,\n            partiallyEvaluatedTextSize: symbolSize.evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom),\n            collisionGroup: this.collisionGroups.get(symbolBucket.sourceID)\n        };\n\n        if (sortAcrossTiles) {\n            for (const range of symbolBucket.sortKeyRanges) {\n                const {sortKey, symbolInstanceStart, symbolInstanceEnd} = range;\n                results.push({sortKey, symbolInstanceStart, symbolInstanceEnd, parameters});\n            }\n        } else {\n            results.push({\n                symbolInstanceStart: 0,\n                symbolInstanceEnd: symbolBucket.symbolInstances.length,\n                parameters\n            });\n        }\n    }\n\n    attemptAnchorPlacement(\n        textAnchorOffset: TextAnchorOffset,\n        textBox: SingleCollisionBox,\n        width: number,\n        height: number,\n        textBoxScale: number,\n        rotateWithMap: boolean,\n        pitchWithMap: boolean,\n        textPixelRatio: number,\n        tileID: OverscaledTileID,\n        unwrappedTileID: UnwrappedTileID,\n        collisionGroup: CollisionGroup,\n        textOverlapMode: OverlapMode,\n        symbolInstance: SymbolInstance,\n        bucket: SymbolBucket,\n        orientation: number,\n        translationText: [number, number],\n        translationIcon: [number, number],\n        iconBox?: SingleCollisionBox | null,\n        getElevation?: GetElevation,\n        simpleProjectionMatrix?: mat4,\n        heightOffset?: number,\n        heightAnchorGround?: boolean,\n    ): {\n        shift: Point;\n        placedGlyphBoxes: PlacedBox;\n    } {\n\n        const anchor = TextAnchorEnum[textAnchorOffset.textAnchor] as TextAnchor;\n        const textOffset = [textAnchorOffset.textOffset0, textAnchorOffset.textOffset1] as [number, number];\n        const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale);\n\n        const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(\n            textBox,\n            textOverlapMode,\n            textPixelRatio,\n            tileID,\n            unwrappedTileID,\n            pitchWithMap,\n            rotateWithMap,\n            translationText,\n            collisionGroup.predicate,\n            getElevation,\n            shift,\n            simpleProjectionMatrix,\n            heightOffset,\n            heightAnchorGround,\n        );\n\n        if (iconBox) {\n            const placedIconBoxes = this.collisionIndex.placeCollisionBox(\n                iconBox,\n                textOverlapMode,\n                textPixelRatio,\n                tileID,\n                unwrappedTileID,\n                pitchWithMap,\n                rotateWithMap,\n                translationIcon,\n                collisionGroup.predicate,\n                getElevation,\n                shift,\n                simpleProjectionMatrix,\n                heightOffset,\n                heightAnchorGround,\n            );\n            if (!placedIconBoxes.placeable) return;\n        }\n\n        if (placedGlyphBoxes.placeable) {\n            let prevAnchor;\n            // If this label was placed in the previous placement, record the anchor position\n            // to allow us to animate the transition\n            if (this.prevPlacement?.variableOffsets[symbolInstance.crossTileID] &&\n                this.prevPlacement?.placements[symbolInstance.crossTileID]?.text) {\n                prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor;\n            }\n            if (symbolInstance.crossTileID === 0) throw new Error('symbolInstance.crossTileID can\\'t be 0');\n            this.variableOffsets[symbolInstance.crossTileID] = {\n                textOffset,\n                width,\n                height,\n                anchor,\n                textBoxScale,\n                prevAnchor\n            };\n            this.markUsedJustification(bucket, anchor, symbolInstance, orientation);\n\n            if (bucket.allowVerticalPlacement) {\n                this.markUsedOrientation(bucket, orientation, symbolInstance);\n                this.placedOrientations[symbolInstance.crossTileID] = orientation;\n            }\n\n            return {shift, placedGlyphBoxes};\n        }\n    }\n\n    placeLayerBucketPart(bucketPart: BucketPart, seenCrossTileIDs: {\n        [k in string | number]: boolean;\n    }, showCollisionBoxes: boolean): void {\n\n        const {\n            bucket,\n            layout,\n            translationText,\n            translationIcon,\n            unwrappedTileID,\n            pitchedLabelPlaneMatrix,\n            textPixelRatio,\n            holdingForFade,\n            collisionBoxArray,\n            partiallyEvaluatedTextSize,\n            collisionGroup\n        } = bucketPart.parameters;\n\n        const textOptional = layout.get('text-optional');\n        const iconOptional = layout.get('icon-optional');\n        const textOverlapMode = getOverlapMode(layout, 'text-overlap', 'text-allow-overlap');\n        const textAlwaysOverlap = textOverlapMode === 'always';\n        const iconOverlapMode = getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap');\n        const iconAlwaysOverlap = iconOverlapMode === 'always';\n        const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n        const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n        const hasIconTextFit = layout.get('icon-text-fit') !== 'none';\n        const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y';\n        const heightAnchorGround = layout.get('symbol-height-anchor') === 'ground';\n\n        // This logic is similar to the \"defaultOpacityState\" logic below in updateBucketOpacities\n        // If we know a symbol is always supposed to show, force it to be marked visible even if\n        // it wasn't placed into the collision index (because some or all of it was outside the range\n        // of the collision grid).\n        // There is a subtle edge case here we're accepting:\n        //  Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false\n        //  A's icon is outside the grid, so doesn't get placed\n        //  A's text would be inside grid, but doesn't get placed because of icon-optional: false\n        //  We still show A because of the allow-overlap settings.\n        //  Symbol B has allow-overlap: false, and gets placed where A's text would be\n        //  On panning in, there is a short period when Symbol B and Symbol A will overlap\n        //  This is the reverse of our normal policy of \"fade in on pan\", but should look like any other\n        //  collision and hopefully not be too noticeable.\n        // See https://github.com/mapbox/mapbox-gl-js/issues/7172\n        const alwaysShowText = textAlwaysOverlap && (iconAlwaysOverlap || !bucket.hasIconData() || iconOptional);\n        const alwaysShowIcon = iconAlwaysOverlap && (textAlwaysOverlap || !bucket.hasTextData() || textOptional);\n\n        if (!bucket.collisionArrays && collisionBoxArray) {\n            bucket.deserializeCollisionBoxes(collisionBoxArray);\n        }\n\n        const tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID;\n        const getElevation = this._getTerrainElevationFunc(tileID);\n        const simpleProjectionMatrix = this.transform.getFastPathSimpleProjectionMatrix(tileID);\n\n        const placeSymbol = (symbolInstance: SymbolInstance, collisionArrays: CollisionArrays, symbolIndex: number) => {\n            if (seenCrossTileIDs[symbolInstance.crossTileID]) return;\n            if (holdingForFade) {\n                // Mark all symbols from this tile as \"not placed\", but don't add to seenCrossTileIDs, because we don't\n                // know yet if we have a duplicate in a parent tile that _should_ be placed.\n                this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false);\n                return;\n            }\n\n            const symbolHeightOffset = symbolInstance.heightOffset;\n\n            let placeText = false;\n            let placeIcon = false;\n            let offscreen = true;\n            let shift = null;\n\n            let placed: PlacedBox = {box: null, placeable: false, offscreen: null, occluded: false};\n            let placedVerticalText = {box: null, placeable: false, offscreen: null};\n\n            let placedGlyphBoxes: PlacedBox = null;\n            let placedGlyphCircles: PlacedCircles = null;\n            let placedIconBoxes: PlacedBox = null;\n            let textFeatureIndex = 0;\n            let verticalTextFeatureIndex = 0;\n            let iconFeatureIndex = 0;\n\n            if (collisionArrays.textFeatureIndex) {\n                textFeatureIndex = collisionArrays.textFeatureIndex;\n            } else if (symbolInstance.useRuntimeCollisionCircles) {\n                textFeatureIndex = symbolInstance.featureIndex;\n            }\n            if (collisionArrays.verticalTextFeatureIndex) {\n                verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex;\n            }\n\n            const textBox = collisionArrays.textBox;\n            if (textBox) {\n\n                const updatePreviousOrientationIfNotPlaced = (isPlaced) => {\n                    let previousOrientation = WritingMode.horizontal;\n                    if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) {\n                        const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID];\n                        if (prevPlacedOrientation) {\n                            this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation;\n                            previousOrientation = prevPlacedOrientation;\n                            this.markUsedOrientation(bucket, previousOrientation, symbolInstance);\n                        }\n                    }\n                    return previousOrientation;\n                };\n\n                const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => {\n                    if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) {\n                        for (const placementMode of bucket.writingModes) {\n                            if (placementMode === WritingMode.vertical) {\n                                placed = placeVerticalFn();\n                                placedVerticalText = placed;\n                            } else {\n                                placed = placeHorizontalFn();\n                            }\n                            if (placed?.placeable) break;\n                        }\n                    } else {\n                        placed = placeHorizontalFn();\n                    }\n                };\n\n                const textAnchorOffsetStart = symbolInstance.textAnchorOffsetStartIndex;\n                const textAnchorOffsetEnd = symbolInstance.textAnchorOffsetEndIndex;\n\n                // If start+end indices match, text-variable-anchor is not in play.\n                if (textAnchorOffsetEnd === textAnchorOffsetStart) {\n                    const placeBox = (collisionTextBox, orientation) => {\n                        const placedFeature = this.collisionIndex.placeCollisionBox(\n                            collisionTextBox,\n                            textOverlapMode,\n                            textPixelRatio,\n                            tileID,\n                            unwrappedTileID,\n                            pitchWithMap,\n                            rotateWithMap,\n                            translationText,\n                            collisionGroup.predicate,\n                            getElevation,\n                            undefined,\n                            simpleProjectionMatrix,\n                            symbolHeightOffset,\n                            heightAnchorGround,\n                        );\n                        if (placedFeature?.placeable) {\n                            this.markUsedOrientation(bucket, orientation, symbolInstance);\n                            this.placedOrientations[symbolInstance.crossTileID] = orientation;\n                        }\n                        return placedFeature;\n                    };\n\n                    const placeHorizontal = () => {\n                        return placeBox(textBox, WritingMode.horizontal);\n                    };\n\n                    const placeVertical = () => {\n                        const verticalTextBox = collisionArrays.verticalTextBox;\n                        if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {\n                            return placeBox(verticalTextBox, WritingMode.vertical);\n                        }\n                        return {box: null, offscreen: null};\n                    };\n\n                    placeTextForPlacementModes(placeHorizontal, placeVertical);\n                    updatePreviousOrientationIfNotPlaced(placed?.placeable);\n\n                } else {\n                    // If this symbol was in the last placement, prefer placement using same anchor, if it's still available\n                    let prevAnchor = TextAnchorEnum[this.prevPlacement?.variableOffsets[symbolInstance.crossTileID]?.anchor];\n\n                    const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => {\n                        const width = collisionTextBox.x2 - collisionTextBox.x1;\n                        const height = collisionTextBox.y2 - collisionTextBox.y1;\n                        const textBoxScale = symbolInstance.textBoxScale;\n                        const variableIconBox = hasIconTextFit && (iconOverlapMode === 'never') ? collisionIconBox : null;\n\n                        let placedBox: PlacedBox = null;\n                        let placementPasses = (textOverlapMode === 'never') ? 1 : 2;\n                        let overlapMode: OverlapMode = 'never';\n\n                        if (prevAnchor) {\n                            placementPasses++;\n                        }\n\n                        for (let pass = 0; pass < placementPasses; pass++) {\n                            for (let i = textAnchorOffsetStart; i < textAnchorOffsetEnd; i++) {\n                                const textAnchorOffset = bucket.textAnchorOffsets.get(i);\n\n                                if (prevAnchor && textAnchorOffset.textAnchor !== prevAnchor) {\n                                    continue;\n                                }\n\n                                const result = this.attemptAnchorPlacement(\n                                    textAnchorOffset, collisionTextBox, width, height,\n                                    textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, tileID, unwrappedTileID,\n                                    collisionGroup, overlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, variableIconBox, getElevation, simpleProjectionMatrix, symbolHeightOffset, heightAnchorGround);\n\n                                if (result) {\n                                    placedBox = result.placedGlyphBoxes;\n                                    if (placedBox?.placeable) {\n                                        placeText = true;\n                                        shift = result.shift;\n                                        return placedBox;\n                                    }\n                                }\n                            }\n\n                            if (prevAnchor) {\n                                prevAnchor = null;\n                            } else {\n                                overlapMode = textOverlapMode;\n                            }\n                        }\n\n                        if (showCollisionBoxes && !placedBox) {\n                            // No box was successfully placed\n                            // Generate bounds for a fake centered box, so that we can at least display something for collision debug.\n                            const placedFakeGlyphBox = this.collisionIndex.placeCollisionBox(\n                                textBox,\n                                'always', // Skips expensive collision check with already placed boxes\n                                textPixelRatio,\n                                tileID,\n                                unwrappedTileID,\n                                pitchWithMap,\n                                rotateWithMap,\n                                translationText,\n                                collisionGroup.predicate,\n                                getElevation,\n                                undefined,\n                                simpleProjectionMatrix,\n                                symbolHeightOffset,\n                                heightAnchorGround,\n                            );\n                            placedBox = {\n                                box: placedFakeGlyphBox.box,\n                                offscreen: false,\n                                placeable: false,\n                                occluded: false,\n                            };\n                        }\n\n                        return placedBox;\n                    };\n\n                    const placeHorizontal = () => {\n                        return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, WritingMode.horizontal);\n                    };\n\n                    const placeVertical = () => {\n                        const verticalTextBox = collisionArrays.verticalTextBox;\n                        const wasPlaced = placed?.placeable;\n                        if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {\n                            return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, WritingMode.vertical);\n                        }\n                        return {box: null, occluded: true, offscreen: null};\n                    };\n\n                    placeTextForPlacementModes(placeHorizontal, placeVertical);\n\n                    if (placed) {\n                        placeText = placed.placeable;\n                        offscreen = placed.offscreen;\n                    }\n\n                    const prevOrientation = updatePreviousOrientationIfNotPlaced(placed?.placeable);\n\n                    // If we didn't get placed, we still need to copy our position from the last placement for\n                    // fade animations\n                    if (!placeText && this.prevPlacement) {\n                        const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID];\n                        if (prevOffset) {\n                            this.variableOffsets[symbolInstance.crossTileID] = prevOffset;\n                            this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation);\n                        }\n                    }\n\n                }\n            }\n\n            placedGlyphBoxes = placed;\n            placeText = placedGlyphBoxes?.placeable;\n            offscreen = placedGlyphBoxes?.offscreen;\n\n            if (symbolInstance.useRuntimeCollisionCircles && symbolInstance.centerJustifiedTextSymbolIndex >= 0) {\n                const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);\n                const fontSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);\n\n                const textPixelPadding = layout.get('text-padding');\n                const circlePixelDiameter = symbolInstance.collisionCircleDiameter;\n\n                placedGlyphCircles = this.collisionIndex.placeCollisionCircles(\n                    textOverlapMode,\n                    placedSymbol,\n                    bucket.lineVertexArray,\n                    bucket.glyphOffsetArray,\n                    fontSize,\n                    unwrappedTileID,\n                    pitchedLabelPlaneMatrix,\n                    showCollisionBoxes,\n                    pitchWithMap,\n                    collisionGroup.predicate,\n                    circlePixelDiameter,\n                    textPixelPadding,\n                    translationText,\n                    getElevation\n                );\n\n                if (placedGlyphCircles.circles.length && placedGlyphCircles.collisionDetected && !showCollisionBoxes) {\n                    warnOnce('Collisions detected, but collision boxes are not shown');\n                }\n\n                // If text-overlap is set to 'always', force \"placedCircles\" to true\n                // In theory there should always be at least one circle placed\n                // in this case, but for now quirks in text-anchor\n                // and text-offset may prevent that from being true.\n                placeText = textAlwaysOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected);\n                offscreen &&= placedGlyphCircles.offscreen;\n            }\n\n            if (collisionArrays.iconFeatureIndex) {\n                iconFeatureIndex = collisionArrays.iconFeatureIndex;\n            }\n\n            if (collisionArrays.iconBox) {\n                const placeIconFeature = iconBox => {\n                    return this.collisionIndex.placeCollisionBox(\n                        iconBox,\n                        iconOverlapMode,\n                        textPixelRatio,\n                        tileID,\n                        unwrappedTileID,\n                        pitchWithMap,\n                        rotateWithMap,\n                        translationIcon,\n                        collisionGroup.predicate,\n                        getElevation,\n                        (hasIconTextFit && shift) ? shift : undefined,\n                        simpleProjectionMatrix,\n                        symbolHeightOffset,\n                        heightAnchorGround,\n                    );\n                };\n\n                if (placedVerticalText && placedVerticalText.placeable && collisionArrays.verticalIconBox) {\n                    placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox);\n                    placeIcon = placedIconBoxes.placeable;\n                } else {\n                    placedIconBoxes = placeIconFeature(collisionArrays.iconBox);\n                    placeIcon = placedIconBoxes.placeable;\n                }\n                offscreen &&= placedIconBoxes.offscreen;\n            }\n\n            const iconWithoutText = textOptional ||\n                (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0);\n            const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0;\n\n            // Combine the scales for icons and text.\n            if (!iconWithoutText && !textWithoutIcon) {\n                placeIcon = placeText = placeIcon && placeText;\n            } else if (!textWithoutIcon) {\n                placeText = placeIcon && placeText;\n            } else if (!iconWithoutText) {\n                placeIcon &&= placeText;\n            }\n\n            const hasTextBox = placeText && placedGlyphBoxes.placeable;\n            const hasIconBox = placeIcon && placedIconBoxes.placeable;\n\n            if (hasTextBox) {\n                if (placedVerticalText && placedVerticalText.placeable && verticalTextFeatureIndex) {\n                    this.collisionIndex.insertCollisionBox(\n                        placedGlyphBoxes.box,\n                        textOverlapMode,\n                        layout.get('text-ignore-placement'),\n                        bucket.bucketInstanceId,\n                        verticalTextFeatureIndex,\n                        collisionGroup.ID);\n                } else {\n                    this.collisionIndex.insertCollisionBox(\n                        placedGlyphBoxes.box,\n                        textOverlapMode,\n                        layout.get('text-ignore-placement'),\n                        bucket.bucketInstanceId,\n                        textFeatureIndex,\n                        collisionGroup.ID);\n                }\n\n            }\n            if (hasIconBox) {\n                this.collisionIndex.insertCollisionBox(\n                    placedIconBoxes.box,\n                    iconOverlapMode,\n                    layout.get('icon-ignore-placement'),\n                    bucket.bucketInstanceId,\n                    iconFeatureIndex,\n                    collisionGroup.ID);\n            }\n            if (placedGlyphCircles) {\n                if (placeText) {\n                    this.collisionIndex.insertCollisionCircles(\n                        placedGlyphCircles.circles,\n                        textOverlapMode,\n                        layout.get('text-ignore-placement'),\n                        bucket.bucketInstanceId,\n                        textFeatureIndex,\n                        collisionGroup.ID);\n                }\n            }\n\n            if (showCollisionBoxes) {\n                this.storeCollisionData(bucket.bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles);\n            }\n\n            if (symbolInstance.crossTileID === 0) throw new Error('symbolInstance.crossTileID can\\'t be 0');\n            if (bucket.bucketInstanceId === 0) throw new Error('bucket.bucketInstanceId can\\'t be 0');\n\n            // Do not show text or icons that are occluded by the globe, even if overlap mode is 'always'!\n            const textVisible: boolean = (placeText || alwaysShowText) && !(placedGlyphBoxes?.occluded);\n            const iconVisible = (placeIcon || alwaysShowIcon) && !(placedIconBoxes?.occluded);\n            this.placements[symbolInstance.crossTileID] = new JointPlacement(textVisible, iconVisible, offscreen || bucket.justReloaded);\n            seenCrossTileIDs[symbolInstance.crossTileID] = true;\n        };\n\n        if (zOrderByViewportY) {\n            if (bucketPart.symbolInstanceStart !== 0) throw new Error('bucket.bucketInstanceId should be 0');\n            const symbolIndexes = bucket.getSortedSymbolIndexes(-this.transform.bearingInRadians);\n            for (let i = symbolIndexes.length - 1; i >= 0; --i) {\n                const symbolIndex = symbolIndexes[i];\n                placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex], symbolIndex);\n            }\n        } else {\n            for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) {\n                placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i], i);\n            }\n        }\n\n        bucket.justReloaded = false;\n    }\n\n    storeCollisionData(bucketInstanceId: number, symbolIndex: number, collisionArrays: CollisionArrays, placedGlyphBoxes: PlacedBox, placedIconBoxes: PlacedBox, placedGlyphCircles: PlacedCircles): void {\n        if (collisionArrays.textBox || collisionArrays.iconBox) {\n            // Store the actually used collision box for debug draw\n            let boxArray: Map<number, {\n                text: number[];\n                icon: number[];\n            }>;\n\n            if (this.collisionBoxArrays.has(bucketInstanceId)) {\n                boxArray = this.collisionBoxArrays.get(bucketInstanceId);\n            } else {\n                boxArray = new Map<number, {\n                    text: number[];\n                    icon: number[];\n                }>();\n                this.collisionBoxArrays.set(bucketInstanceId, boxArray);\n            }\n            let realCollisionBox: {\n                text: number[];\n                icon: number[];\n            };\n\n            if (boxArray.has(symbolIndex)) {\n                realCollisionBox = boxArray.get(symbolIndex);\n            } else {\n                realCollisionBox = {\n                    text: null,\n                    icon: null\n                };\n                boxArray.set(symbolIndex, realCollisionBox);\n            }\n\n            if (collisionArrays.textBox) {\n                realCollisionBox.text = placedGlyphBoxes.box;\n            }\n            if (collisionArrays.iconBox) {\n                realCollisionBox.icon = placedIconBoxes.box;\n            }\n        }\n\n        if (placedGlyphCircles) {\n            let circleArray = this.collisionCircleArrays[bucketInstanceId];\n\n            // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement\n            // for a bucket is not guaranteed to be complete before the commit-function has been called\n            if (circleArray === undefined)\n                circleArray = this.collisionCircleArrays[bucketInstanceId] = [];\n\n            for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) {\n                circleArray.push(placedGlyphCircles.circles[i + 0] - viewportPadding); // x\n                circleArray.push(placedGlyphCircles.circles[i + 1] - viewportPadding); // y\n                circleArray.push(placedGlyphCircles.circles[i + 2]);                   // radius\n                circleArray.push(placedGlyphCircles.collisionDetected ? 1 : 0);        // collisionDetected-flag\n            }\n        }\n    }\n\n    markUsedJustification(bucket: SymbolBucket, placedAnchor: TextAnchor, symbolInstance: SymbolInstance, orientation: number): void {\n        const justifications = {\n            'left': symbolInstance.leftJustifiedTextSymbolIndex,\n            'center': symbolInstance.centerJustifiedTextSymbolIndex,\n            'right': symbolInstance.rightJustifiedTextSymbolIndex\n        };\n\n        let autoIndex;\n        if (orientation === WritingMode.vertical) {\n            autoIndex = symbolInstance.verticalPlacedTextSymbolIndex;\n        } else {\n            autoIndex = justifications[getAnchorJustification(placedAnchor)];\n        }\n\n        const indexes = [\n            symbolInstance.leftJustifiedTextSymbolIndex,\n            symbolInstance.centerJustifiedTextSymbolIndex,\n            symbolInstance.rightJustifiedTextSymbolIndex,\n            symbolInstance.verticalPlacedTextSymbolIndex\n        ];\n\n        for (const index of indexes) {\n            if (index >= 0) {\n                if (autoIndex >= 0 && index !== autoIndex) {\n                    // There are multiple justifications and this one isn't it: shift offscreen\n                    bucket.text.placedSymbolArray.get(index).crossTileID = 0;\n                } else {\n                    // Either this is the chosen justification or the justification is hardwired: use this one\n                    bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID;\n                }\n            }\n        }\n    }\n\n    markUsedOrientation(bucket: SymbolBucket, orientation: number, symbolInstance: SymbolInstance): void {\n        const horizontal = (orientation === WritingMode.horizontal || orientation === WritingMode.horizontalOnly) ? orientation : 0;\n        const vertical = orientation === WritingMode.vertical ? orientation : 0;\n\n        const horizontalIndexes = [\n            symbolInstance.leftJustifiedTextSymbolIndex,\n            symbolInstance.centerJustifiedTextSymbolIndex,\n            symbolInstance.rightJustifiedTextSymbolIndex\n        ];\n\n        for (const index of horizontalIndexes) {\n            bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal;\n        }\n\n        if (symbolInstance.verticalPlacedTextSymbolIndex) {\n            bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical;\n        }\n    }\n\n    commit(now: number): void {\n        this.commitTime = now;\n        this.zoomAtLastRecencyCheck = this.transform.zoom;\n\n        const prevPlacement = this.prevPlacement;\n        let placementChanged = false;\n\n        this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0;\n        const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1;\n\n        const prevOpacities = prevPlacement ? prevPlacement.opacities : {};\n        const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {};\n        const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {};\n\n        // add the opacities from the current placement, and copy their current values from the previous placement\n        for (const crossTileID in this.placements) {\n            const jointPlacement = this.placements[crossTileID];\n            const prevOpacity = prevOpacities[crossTileID];\n            if (prevOpacity) {\n                this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon);\n                placementChanged ||= jointPlacement.text !== prevOpacity.text.placed;\n                placementChanged ||= jointPlacement.icon !== prevOpacity.icon.placed;\n            } else {\n                this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade);\n                placementChanged ||= jointPlacement.text || jointPlacement.icon;\n            }\n        }\n\n        // copy and update values from the previous placement that aren't in the current placement but haven't finished fading\n        for (const crossTileID in prevOpacities) {\n            const prevOpacity = prevOpacities[crossTileID];\n            if (!this.opacities[crossTileID]) {\n                const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false);\n                if (!jointOpacity.isHidden()) {\n                    this.opacities[crossTileID] = jointOpacity;\n                    placementChanged ||= prevOpacity.text.placed;\n                    placementChanged ||= prevOpacity.icon.placed;\n                }\n            }\n        }\n        for (const crossTileID in prevOffsets) {\n            if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {\n                this.variableOffsets[crossTileID] = prevOffsets[crossTileID];\n            }\n        }\n\n        for (const crossTileID in prevOrientations) {\n            if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {\n                this.placedOrientations[crossTileID] = prevOrientations[crossTileID];\n            }\n        }\n\n        // this.lastPlacementChangeTime is the time of the last commit() that\n        // resulted in a placement change -- in other words, the start time of\n        // the last symbol fade animation\n        if (prevPlacement && prevPlacement.lastPlacementChangeTime === undefined) {\n            throw new Error('Last placement time for previous placement is not defined');\n        }\n        if (placementChanged) {\n            this.lastPlacementChangeTime = now;\n        } else if (typeof this.lastPlacementChangeTime !== 'number') {\n            this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now;\n        }\n    }\n\n    /** Writes the opacity buffers of `styleLayer`, skipping buckets a rewrite would leave as they are. */\n    updateLayerOpacities(styleLayer: StyleLayer, tiles: Tile[]): void {\n        const seenCrossTileIDs = {};\n        for (const tile of tiles) {\n            const symbolBucket = tile.getBucket(styleLayer) as SymbolBucket;\n            if (!symbolBucket || !tile.latestFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) continue;\n\n            const {duplicates, changed} = this._markDuplicates(symbolBucket, seenCrossTileIDs);\n            // Debug geometry and pending collision circles reach the bucket only through a rewrite.\n            const hasDebugOutput = Boolean(symbolBucket.hasDebugData()) || symbolBucket.bucketInstanceId in this.collisionCircleArrays;\n            if (changed || hasDebugOutput) {\n                this.updateBucketOpacities(symbolBucket, tile.tileID, duplicates, tile.collisionBoxArray);\n            }\n\n            symbolBucket.sortFeatures(-this.transform.bearingInRadians);\n            if (this.retainedQueryData[symbolBucket.bucketInstanceId]) {\n                this.retainedQueryData[symbolBucket.bucketInstanceId].featureSortOrder = symbolBucket.featureSortOrder;\n            }\n        }\n    }\n\n    /**\n     * Marks the bucket's symbols whose label an earlier bucket already draws, and claims the rest in `seenCrossTileIDs`.\n     * `changed` is false when the marks match the last call, which means the buffers are already up to date.\n     */\n    _markDuplicates(bucket: SymbolBucket, seenCrossTileIDs: {[k in string | number]: boolean}): {duplicates: boolean[]; changed: boolean} {\n        const length = bucket.symbolInstances.length;\n        let inputs = this.lastOpacityInputs.get(bucket);\n        let changed = false;\n        if (!inputs) {\n            inputs = {crossTileIDs: new Array<number>(length).fill(0), duplicates: new Array<boolean>(length).fill(false)};\n            this.lastOpacityInputs.set(bucket, inputs);\n            changed = true;\n        }\n\n        const {crossTileIDs, duplicates} = inputs;\n        // Straight out of the buffer: `get` builds a struct per symbol.\n        const uint32 = bucket.symbolInstances.uint32;\n        const stride = bucket.symbolInstances.bytesPerElement / 4;\n        for (let s = 0; s < length; s++) {\n            const crossTileID = uint32[s * stride + CROSS_TILE_ID_UINT32_OFFSET];\n            const duplicate = Boolean(seenCrossTileIDs[crossTileID]);\n            seenCrossTileIDs[crossTileID] = true;\n            if (crossTileIDs[s] !== crossTileID || duplicates[s] !== duplicate) {\n                crossTileIDs[s] = crossTileID;\n                duplicates[s] = duplicate;\n                changed = true;\n            }\n        }\n        return {duplicates, changed};\n    }\n\n    updateBucketOpacities(bucket: SymbolBucket, tileID: OverscaledTileID, duplicates: boolean[], collisionBoxArray?: CollisionBoxArray | null): void {\n        if (bucket.hasTextData()) {\n            bucket.text.opacityVertexArray.clear();\n            bucket.text.hasVisibleVertices = false;\n        }\n        if (bucket.hasIconData()) {\n            bucket.icon.opacityVertexArray.clear();\n            bucket.icon.hasVisibleVertices = false;\n        }\n        if (bucket.hasIconCollisionBoxData()) bucket.iconCollisionBox.collisionVertexArray.clear();\n        if (bucket.hasTextCollisionBoxData()) bucket.textCollisionBox.collisionVertexArray.clear();\n\n        const layer = bucket.layers[0];\n        const layout = layer.layout;\n        const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true);\n        const textAllowOverlap = layout.get('text-allow-overlap');\n        const iconAllowOverlap = layout.get('icon-allow-overlap');\n        const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset');\n        const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n        const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n        const hasIconTextFit = layout.get('icon-text-fit') !== 'none';\n        // If allow-overlap is true, we can show symbols before placement runs on them\n        // But we have to wait for placement if we potentially depend on a paired icon/text\n        // with allow-overlap: false.\n        // See https://github.com/mapbox/mapbox-gl-js/issues/7032\n        const defaultOpacityState = new JointOpacityState(null, 0,\n            textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')),\n            iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')),\n            true);\n\n        if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) {\n            bucket.deserializeCollisionBoxes(collisionBoxArray);\n        }\n\n        const addOpacities = (iconOrText: SymbolBuffers, numVertices: number, opacity: number) => {\n            for (let i = 0; i < numVertices / 4; i++) {\n                iconOrText.opacityVertexArray.emplaceBack(opacity);\n            }\n            iconOrText.hasVisibleVertices ||= (opacity !== PACKED_HIDDEN_OPACITY);\n        };\n\n        const boxArrays = this.collisionBoxArrays.get(bucket.bucketInstanceId);\n\n        for (let s = 0; s < bucket.symbolInstances.length; s++) {\n            const symbolInstance = bucket.symbolInstances.get(s);\n            const {\n                numHorizontalGlyphVertices,\n                numVerticalGlyphVertices,\n                crossTileID\n            } = symbolInstance;\n\n            const isDuplicate = duplicates[s];\n\n            let opacityState = this.opacities[crossTileID];\n            if (isDuplicate) {\n                opacityState = duplicateOpacityState;\n            } else if (!opacityState) {\n                opacityState = defaultOpacityState;\n                // store the state so that future placements use it as a starting point\n                this.opacities[crossTileID] = opacityState;\n            }\n\n            const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0;\n            const hasIcon = symbolInstance.numIconVertices > 0;\n\n            const placedOrientation = this.placedOrientations[symbolInstance.crossTileID];\n            const horizontalHidden = placedOrientation === WritingMode.vertical;\n            const verticalHidden = placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly;\n\n            if (hasText) {\n                const packedOpacity = packOpacity(opacityState.text);\n                // Vertical text fades in/out on collision the same way as corresponding\n                // horizontal text. Switch between vertical/horizontal should be instantaneous\n                const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;\n                addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity);\n                const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;\n                addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity);\n\n                // If this label is completely faded, mark it so that we don't have to calculate\n                // its position at render time. If this layer has variable placement, shift the various\n                // symbol instances appropriately so that symbols from buckets that have yet to be placed\n                // offset appropriately.\n                const symbolHidden = opacityState.text.isHidden();\n                const textSymbolIndexes = [\n                    symbolInstance.rightJustifiedTextSymbolIndex,\n                    symbolInstance.centerJustifiedTextSymbolIndex,\n                    symbolInstance.leftJustifiedTextSymbolIndex\n                ];\n                for (const index of textSymbolIndexes) {\n                    if (index >= 0) {\n                        bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0;\n                    }\n                }\n\n                if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n                    bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0;\n                }\n\n                const prevOffset = this.variableOffsets[symbolInstance.crossTileID];\n                if (prevOffset) {\n                    this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation);\n                }\n\n                const prevOrientation = this.placedOrientations[symbolInstance.crossTileID];\n                if (prevOrientation) {\n                    this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation);\n                    this.markUsedOrientation(bucket, prevOrientation, symbolInstance);\n                }\n            }\n\n            if (hasIcon) {\n                const packedOpacity = packOpacity(opacityState.icon);\n\n                const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden);\n\n                if (symbolInstance.placedIconSymbolIndex >= 0) {\n                    const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;\n                    addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity);\n                    bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden =\n                        (opacityState.icon.isHidden() as any);\n                }\n\n                if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {\n                    const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;\n                    addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity);\n                    bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden =\n                        (opacityState.icon.isHidden() as any);\n                }\n            }\n\n            const realBoxes = (boxArrays?.has(s)) ? boxArrays.get(s) : {\n                text: null,\n                icon: null\n            };\n\n            if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) {\n                const collisionArrays = bucket.collisionArrays[s];\n                if (collisionArrays) {\n                    let shift = new Point(0, 0);\n                    if (collisionArrays.textBox || collisionArrays.verticalTextBox) {\n                        let used = true;\n                        if (hasVariablePlacement) {\n                            const variableOffset = this.variableOffsets[crossTileID];\n                            if (variableOffset) {\n                                // This will show either the currently placed position or the last\n                                // successfully placed position (so you can visualize what collision\n                                // just made the symbol disappear, and the most likely place for the\n                                // symbol to come back)\n                                shift = calculateVariableLayoutShift(variableOffset.anchor,\n                                    variableOffset.width,\n                                    variableOffset.height,\n                                    variableOffset.textOffset,\n                                    variableOffset.textBoxScale);\n                                if (rotateWithMap) {\n                                    shift._rotate(pitchWithMap ? -this.transform.bearingInRadians : this.transform.bearingInRadians);\n                                }\n                            } else {\n                                // No offset -> this symbol hasn't been placed since coming on-screen\n                                // No single box is particularly meaningful and all of them would be too noisy\n                                // Use the center box just to show something's there, but mark it \"not used\"\n                                used = false;\n                            }\n                        }\n\n                        if (collisionArrays.textBox || collisionArrays.verticalTextBox) {\n                            let hidden: boolean;\n                            if (collisionArrays.textBox) {\n                                hidden = horizontalHidden;\n                            }\n                            if (collisionArrays.verticalTextBox) {\n                                hidden = verticalHidden;\n                            }\n                            updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || hidden, realBoxes.text, shift.x, shift.y);\n                        }\n                    }\n\n                    if (collisionArrays.iconBox || collisionArrays.verticalIconBox) {\n                        const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox);\n                        let hidden: boolean;\n                        if (collisionArrays.iconBox) {\n                            hidden = verticalIconUsed;\n                        }\n                        if (collisionArrays.verticalIconBox) {\n                            hidden = !verticalIconUsed;\n                        }\n                        updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, hidden, realBoxes.icon,\n                            hasIconTextFit ? shift.x : 0,\n                            hasIconTextFit ? shift.y : 0);\n                    }\n                }\n            }\n        }\n\n        if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) {\n            bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray);\n        }\n        if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) {\n            bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray);\n        }\n        if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) {\n            bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray);\n        }\n        if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) {\n            bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray);\n        }\n\n        if (bucket.text.opacityVertexArray.length !== bucket.text.layoutVertexArray.length / 4) throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`);\n        if (bucket.icon.opacityVertexArray.length !== bucket.icon.layoutVertexArray.length / 4) throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`);\n\n        // Push generated collision circles to the bucket for debug rendering\n        if (bucket.bucketInstanceId in this.collisionCircleArrays) {\n            bucket.collisionCircleArray = this.collisionCircleArrays[bucket.bucketInstanceId];\n            delete this.collisionCircleArrays[bucket.bucketInstanceId];\n        }\n    }\n\n    symbolFadeChange(now: number): number {\n        return this.fadeDuration === 0 ?\n            1 :\n            ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment);\n    }\n\n    zoomAdjustment(zoom: number): number {\n        // When zooming out quickly, labels can overlap each other. This\n        // adjustment is used to reduce the interval between placement calculations\n        // and to reduce the fade duration when zooming out quickly. Discovering the\n        // collisions more quickly and fading them more quickly reduces the unwanted effect.\n        return Math.max(0, (this.transform.zoom - zoom) / 1.5);\n    }\n\n    hasTransitions(now: number): boolean {\n        return this.stale ||\n            now - this.lastPlacementChangeTime < this.fadeDuration;\n    }\n\n    stillRecent(now: number, zoom: number): boolean {\n        // The adjustment makes placement more frequent when zooming.\n        // This condition applies the adjustment only after the map has\n        // stopped zooming. This avoids adding extra jank while zooming.\n        const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ?\n            (1 - this.zoomAdjustment(zoom)) :\n            1;\n        this.zoomAtLastRecencyCheck = zoom;\n\n        return this.commitTime + this.fadeDuration * durationAdjustment > now;\n    }\n\n    setStale(): void {\n        this.stale = true;\n    }\n}\n\nfunction updateCollisionVertices(collisionVertexArray: CollisionVertexArray, placed: boolean, notUsed: boolean | number, realBox: number[], shiftX?: number, shiftY?: number) {\n    if (!realBox || realBox.length === 0) {\n        realBox = [0, 0, 0, 0];\n    }\n\n    const tlX = realBox[0] - viewportPadding;\n    const tlY = realBox[1] - viewportPadding;\n    const brX = realBox[2] - viewportPadding;\n    const brY = realBox[3] - viewportPadding;\n\n    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, tlY);\n    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, tlY);\n    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, brY);\n    collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, brY);\n}\n\n// All four vertices for a glyph will have the same opacity state\n// So we pack the opacity into a uint8, and then repeat it four times\n// to make a single uint32 that we can upload for each glyph in the\n// label.\nconst shift25 = Math.pow(2, 25);\nconst shift24 = Math.pow(2, 24);\nconst shift17 = Math.pow(2, 17);\nconst shift16 = Math.pow(2, 16);\nconst shift9 = Math.pow(2, 9);\nconst shift8 = Math.pow(2, 8);\nconst shift1 = Math.pow(2, 1);\nfunction packOpacity(opacityState: OpacityState): number {\n    if (opacityState.opacity === 0 && !opacityState.placed) {\n        return PACKED_HIDDEN_OPACITY;\n    } else if (opacityState.opacity === 1 && opacityState.placed) {\n        return PACKED_VISIBLE_OPACITY;\n    }\n    const targetBit = opacityState.placed ? 1 : 0;\n    const opacityBits = Math.floor(opacityState.opacity * 127);\n    return opacityBits * shift25 + targetBit * shift24 +\n        opacityBits * shift17 + targetBit * shift16 +\n        opacityBits * shift9 + targetBit * shift8 +\n        opacityBits * shift1 + targetBit;\n}\n\nexport const PACKED_HIDDEN_OPACITY = 0;\nexport const PACKED_VISIBLE_OPACITY = 4294967295;\n", "import {now} from '../util/time_control.ts';\nimport {Placement} from '../symbol/placement.ts';\nimport {isSymbolStyleLayer, type SymbolStyleLayer} from './style_layer/symbol_style_layer.ts';\n\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\nimport type {StyleLayer} from './style_layer.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {BucketPart} from '../symbol/placement.ts';\nimport type {Terrain} from '../render/terrain.ts';\n\nclass LayerPlacement {\n    _sortAcrossTiles: boolean;\n    _currentTileIndex: number;\n    _currentPartIndex: number;\n    _seenCrossTileIDs: {\n        [k in string | number]: boolean;\n    };\n    _bucketParts: BucketPart[];\n\n    constructor(styleLayer: SymbolStyleLayer) {\n        this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' &&\n            !styleLayer.layout.get('symbol-sort-key').isConstant();\n\n        this._currentTileIndex = 0;\n        this._currentPartIndex = 0;\n        this._seenCrossTileIDs = {};\n        this._bucketParts = [];\n    }\n\n    continuePlacement(tiles: Tile[], placement: Placement, showCollisionBoxes: boolean, styleLayer: StyleLayer, shouldPausePlacement: () => boolean): boolean {\n\n        const bucketParts = this._bucketParts;\n\n        while (this._currentTileIndex < tiles.length) {\n            const tile = tiles[this._currentTileIndex];\n            placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles);\n\n            this._currentTileIndex++;\n            if (shouldPausePlacement()) {\n                return true;\n            }\n        }\n\n        if (this._sortAcrossTiles) {\n            this._sortAcrossTiles = false;\n            bucketParts.sort((a, b) => (a.sortKey as any as number) - (b.sortKey as any as number));\n        }\n\n        while (this._currentPartIndex < bucketParts.length) {\n            const bucketPart = bucketParts[this._currentPartIndex];\n            placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes);\n\n            this._currentPartIndex++;\n            if (shouldPausePlacement()) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n\nexport class PauseablePlacement {\n    placement: Placement;\n    _done: boolean;\n    _currentPlacementIndex: number;\n    _forceFullPlacement: boolean;\n    _showCollisionBoxes: boolean;\n    _inProgressLayer: LayerPlacement;\n\n    constructor(\n        transform: IReadonlyTransform,\n        terrain: Terrain,\n        order: string[],\n        forceFullPlacement: boolean,\n        showCollisionBoxes: boolean,\n        fadeDuration: number,\n        crossSourceCollisions: boolean,\n        prevPlacement?: Placement\n    ) {\n        this.placement = new Placement(transform, terrain, fadeDuration, crossSourceCollisions, prevPlacement);\n        this._currentPlacementIndex = order.length - 1;\n        this._forceFullPlacement = forceFullPlacement;\n        this._showCollisionBoxes = showCollisionBoxes;\n        this._done = false;\n    }\n\n    isDone(): boolean {\n        return this._done;\n    }\n\n    continuePlacement(\n        order: string[],\n        layers: {[_: string]: StyleLayer},\n        layerTiles: {[_: string]: Tile[]}\n    ): void {\n        const startTime = now();\n\n        const shouldPausePlacement = () => {\n            return this._forceFullPlacement ? false : (now() - startTime) > 2;\n        };\n\n        while (this._currentPlacementIndex >= 0) {\n            const layerId = order[this._currentPlacementIndex];\n            const layer = layers[layerId];\n            const placementZoom = this.placement.collisionIndex.transform.zoom;\n            if (isSymbolStyleLayer(layer) &&\n                layer.layout &&\n                (!layer.minzoom || layer.minzoom <= placementZoom) &&\n                (!layer.maxzoom || layer.maxzoom > placementZoom)) {\n\n                this._inProgressLayer ||= new LayerPlacement(layer);\n\n                const pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement);\n\n                if (pausePlacement) {\n                    // We didn't finish placing all layers within 2ms,\n                    // but we can keep rendering with a partial placement\n                    // We'll resume here on the next frame\n                    return;\n                }\n\n                delete this._inProgressLayer;\n            }\n\n            this._currentPlacementIndex--;\n        }\n\n        this._done = true;\n    }\n\n    commit(now: number): Placement {\n        this.placement.commit(now);\n        return this.placement;\n    }\n}\n", "\nconst ARRAY_TYPES = [\n    Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,\n    Int32Array, Uint32Array, Float32Array, Float64Array\n];\n\n/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */\n/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */\n\nconst VERSION = 1; // serialized format version\nconst HEADER_SIZE = 8;\n\n// Shared scratch stack for iterative DFS in range/within. Sized for the worst case:\n// 3 ints per frame * (treeHeight + 1), with treeHeight ≤ ceil(log2(2^32 / 3)) ≈ 31.\nconst STACK = new Uint32Array(96);\n\nexport default class KDBush {\n\n    /**\n     * Creates an index from raw `ArrayBuffer` data.\n     * @param {ArrayBufferLike} data\n     */\n    static from(data) {\n        // @ts-expect-error duck typing array buffers\n        if (!data || data.byteLength === undefined || data.buffer) {\n            throw new Error('Data must be an instance of ArrayBuffer or SharedArrayBuffer.');\n        }\n        const [magic, versionAndType] = new Uint8Array(data, 0, 2);\n        if (magic !== 0xdb) {\n            throw new Error('Data does not appear to be in a KDBush format.');\n        }\n        const version = versionAndType >> 4;\n        if (version !== VERSION) {\n            throw new Error(`Got v${version} data when expected v${VERSION}.`);\n        }\n        const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];\n        if (!ArrayType) {\n            throw new Error('Unrecognized array type.');\n        }\n        const [nodeSize] = new Uint16Array(data, 2, 1);\n        const [numItems] = new Uint32Array(data, 4, 1);\n\n        return new KDBush(numItems, nodeSize, ArrayType, undefined, data);\n    }\n\n    /**\n     * Creates an index that will hold a given number of items.\n     * @param {number} numItems\n     * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).\n     * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).\n     * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).\n     * @param {ArrayBufferLike} [data] (For internal use only)\n     */\n    constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {\n        if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);\n\n        this.numItems = +numItems;\n        this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);\n        this.ArrayType = ArrayType;\n        this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;\n\n        const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);\n        const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;\n        const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;\n        const padCoords = (8 - idsByteSize % 8) % 8;\n\n        if (arrayTypeIndex < 0) {\n            throw new Error(`Unexpected typed array class: ${ArrayType}.`);\n        }\n\n        if (data) { // reconstruct an index from a buffer\n            this.data = data;\n            // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n            this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n            // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n            this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n            this._pos = numItems * 2;\n            this._finished = true;\n\n        } else { // initialize a new index\n            const data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);\n            // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n            this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n            // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n            this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n            this._pos = 0;\n            this._finished = false;\n\n            // set header\n            new Uint8Array(data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);\n            new Uint16Array(data, 2, 1)[0] = nodeSize;\n            new Uint32Array(data, 4, 1)[0] = numItems;\n        }\n    }\n\n    /**\n     * Add a point to the index.\n     * @param {number} x\n     * @param {number} y\n     * @returns {number} An incremental index associated with the added item (starting from `0`).\n     */\n    add(x, y) {\n        const index = this._pos >> 1;\n        this.ids[index] = index;\n        this.coords[this._pos++] = x;\n        this.coords[this._pos++] = y;\n        return index;\n    }\n\n    /**\n     * Perform indexing of the added points.\n     */\n    finish() {\n        const numAdded = this._pos >> 1;\n        if (numAdded !== this.numItems) {\n            throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);\n        }\n        // kd-sort both arrays for efficient search\n        sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);\n\n        this._finished = true;\n        return this;\n    }\n\n    /**\n     * Search the index for items within a given bounding box.\n     * @param {number} minX\n     * @param {number} minY\n     * @param {number} maxX\n     * @param {number} maxY\n     * @returns {number[]} An array of indices correponding to the found items.\n     */\n    range(minX, minY, maxX, maxY) {\n        if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n        const {ids, coords, nodeSize} = this;\n        STACK[0] = 0;\n        STACK[1] = ids.length - 1;\n        STACK[2] = 0;\n        let sp = 3;\n        const result = [];\n\n        // recursively search for items in range in the kd-sorted arrays\n        while (sp > 0) {\n            const axis = STACK[--sp];\n            const right = STACK[--sp];\n            const left = STACK[--sp];\n\n            // if we reached \"tree node\", search linearly\n            if (right - left <= nodeSize) {\n                for (let i = left; i <= right; i++) {\n                    const x = coords[2 * i];\n                    const y = coords[2 * i + 1];\n                    if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);\n                }\n                continue;\n            }\n\n            // otherwise find the middle index\n            const m = (left + right) >> 1;\n\n            // include the middle item if it's in range\n            const x = coords[2 * m];\n            const y = coords[2 * m + 1];\n            if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n            // queue search in halves that intersect the query\n            if (axis === 0 ? minX <= x : minY <= y) {\n                STACK[sp++] = left;\n                STACK[sp++] = m - 1;\n                STACK[sp++] = 1 - axis;\n            }\n            if (axis === 0 ? maxX >= x : maxY >= y) {\n                STACK[sp++] = m + 1;\n                STACK[sp++] = right;\n                STACK[sp++] = 1 - axis;\n            }\n        }\n\n        return result;\n    }\n\n    /**\n     * Search the index for items within a given radius.\n     * @param {number} qx\n     * @param {number} qy\n     * @param {number} r Query radius.\n     * @returns {number[]} An array of indices correponding to the found items.\n     */\n    within(qx, qy, r) {\n        const result = /** @type {number[]} */ ([]);\n        this.withinInto(qx, qy, r, result);\n        return result;\n    }\n\n    /**\n     * Search the index for items within a given radius, writing matching ids into `out`\n     * via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —\n     * a typed array sized to the expected upper bound (allocation-free, fast) or a plain\n     * `Array` (which will grow as needed). Returns the number of matches written.\n     * @param {number} qx\n     * @param {number} qy\n     * @param {number} r Query radius.\n     * @param {number[] | TypedArray} out Container to write matching ids into.\n     * @returns {number} The number of matches written to `out`.\n     */\n    withinInto(qx, qy, r, out) {\n        if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n        const {ids, coords, nodeSize} = this;\n        STACK[0] = 0;\n        STACK[1] = ids.length - 1;\n        STACK[2] = 0;\n        let sp = 3;\n        let count = 0;\n        const r2 = r * r;\n\n        // recursively search for items within radius in the kd-sorted arrays\n        while (sp > 0) {\n            const axis = STACK[--sp];\n            const right = STACK[--sp];\n            const left = STACK[--sp];\n\n            // if we reached \"tree node\", search linearly\n            if (right - left <= nodeSize) {\n                for (let i = left; i <= right; i++) {\n                    if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];\n                }\n                continue;\n            }\n\n            // otherwise find the middle index\n            const m = (left + right) >> 1;\n\n            // include the middle item if it's in range\n            const x = coords[2 * m];\n            const y = coords[2 * m + 1];\n            if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];\n\n            // queue search in halves that intersect the query\n            if (axis === 0 ? qx - r <= x : qy - r <= y) {\n                STACK[sp++] = left;\n                STACK[sp++] = m - 1;\n                STACK[sp++] = 1 - axis;\n            }\n            if (axis === 0 ? qx + r >= x : qy + r >= y) {\n                STACK[sp++] = m + 1;\n                STACK[sp++] = right;\n                STACK[sp++] = 1 - axis;\n            }\n        }\n\n        return count;\n    }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} nodeSize\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction sort(ids, coords, nodeSize, left, right, axis) {\n    if (right - left <= nodeSize) return;\n\n    const m = (left + right) >> 1; // middle index\n\n    // sort ids and coords around the middle index so that the halves lie\n    // either left/right or top/bottom correspondingly (taking turns)\n    select(ids, coords, m, left, right, axis);\n\n    // recursively kd-sort first half and second half on the opposite axis\n    sort(ids, coords, nodeSize, left, m - 1, 1 - axis);\n    sort(ids, coords, nodeSize, m + 1, right, 1 - axis);\n}\n\n/**\n * Custom Floyd-Rivest selection algorithm: sort ids and coords so that\n * [left..k-1] items are smaller than k-th item (on either x or y axis)\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} k\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction select(ids, coords, k, left, right, axis) {\n\n    while (right > left) {\n        if (right - left > 600) {\n            const n = right - left + 1;\n            const m = k - left + 1;\n            const z = Math.log(n);\n            const s = 0.5 * Math.exp(2 * z / 3);\n            const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n            const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n            const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n            select(ids, coords, k, newLeft, newRight, axis);\n        }\n\n        const t = coords[2 * k + axis];\n        let i = left;\n        let j = right;\n\n        swapItem(ids, coords, left, k);\n        if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);\n\n        while (i < j) {\n            swapItem(ids, coords, i, j);\n            i++;\n            j--;\n            while (coords[2 * i + axis] < t) i++;\n            while (coords[2 * j + axis] > t) j--;\n        }\n\n        if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);\n        else {\n            j++;\n            swapItem(ids, coords, j, right);\n        }\n\n        if (j <= k) left = j + 1;\n        if (k <= j) right = j - 1;\n    }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} i\n * @param {number} j\n */\nfunction swapItem(ids, coords, i, j) {\n    swap(ids, i, j);\n    swap(coords, 2 * i, 2 * j);\n    swap(coords, 2 * i + 1, 2 * j + 1);\n}\n\n/**\n * @param {TypedArray} arr\n * @param {number} i\n * @param {number} j\n */\nfunction swap(arr, i, j) {\n    const tmp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = tmp;\n}\n\n/**\n * @param {number} ax\n * @param {number} ay\n * @param {number} bx\n * @param {number} by\n */\nfunction sqDist(ax, ay, bx, by) {\n    const dx = ax - bx;\n    const dy = ay - by;\n    return dx * dx + dy * dy;\n}\n", "import KDBush from 'kdbush';\nimport {EXTENT} from '../data/extent.ts';\n\nimport type {SymbolInstanceArray} from '../data/array_types.g.ts';\nimport type {SymbolInstance} from '../data/array_types.g.ts';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\nimport type {SymbolBucket} from '../data/bucket/symbol_bucket.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {Tile} from '../tile/tile.ts';\n\n/*\n    The CrossTileSymbolIndex generally works on the assumption that\n    a conceptual \"unique symbol\" can be identified by the text of\n    the label combined with the anchor point (and, for sources with\n    `promoteId`, the feature id, see `symbol_layout.ts`). The goal is to assign\n    these conceptual \"unique symbols\" a shared crossTileID that can be\n    used by Placement to keep fading opacity states consistent and to\n    deduplicate labels.\n\n    The CrossTileSymbolIndex indexes all the current symbol instances and\n    their crossTileIDs. When a symbol bucket gets added or updated, the\n    index assigns a crossTileID to each of it's symbol instances by either\n    matching it with an existing id or assigning a new one.\n*/\n\n// Round anchor positions to roughly 4 pixel grid\nconst roundingFactor = 512 / EXTENT / 2;\n\nexport const KDBUSH_THRESHHOLD = 128;\n\ntype SymbolsByKeyEntry = {\n    index?: KDBush;\n    positions?: Array<{x: number; y: number}>;\n    crossTileIDs: number[];\n};\n\nclass TileLayerIndex {\n    _symbolsByKey: Record<number, SymbolsByKeyEntry> = {};\n\n    constructor(public tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, public bucketInstanceId: number) {\n        // group the symbolInstances by key\n        const symbolInstancesByKey = new Map<number, SymbolInstance[]>();\n        for (let i = 0; i < symbolInstances.length; i++) {\n            const symbolInstance = symbolInstances.get(i);\n            const key = symbolInstance.key;\n            const instances = symbolInstancesByKey.get(key);\n            if (instances) {\n                // This tile may have multiple symbol instances with the same key\n                // Store each one along with its coordinates\n                instances.push(symbolInstance);\n            } else {\n                symbolInstancesByKey.set(key, [symbolInstance]);\n            }\n        }\n\n        // index the SymbolInstances in this each bucket\n        for (const [key, symbols] of symbolInstancesByKey) {\n            const positions = symbols.map(symbolInstance => ({x: Math.floor(symbolInstance.anchorX * roundingFactor), y: Math.floor(symbolInstance.anchorY * roundingFactor)}));\n            const crossTileIDs = symbols.map(v => v.crossTileID);\n            const entry: SymbolsByKeyEntry = {positions, crossTileIDs};\n\n            // once we get too many symbols for a given key, it becomes much faster to index it before queries\n            if (entry.positions.length > KDBUSH_THRESHHOLD) {\n\n                const index = new KDBush(entry.positions.length, 16, Uint16Array);\n                for (const {x, y} of entry.positions) index.add(x, y);\n                index.finish();\n\n                // clear all references to the original positions data\n                delete entry.positions;\n                entry.index = index;\n            }\n\n            this._symbolsByKey[key] = entry;\n        }\n    }\n\n    // Converts the coordinates of the input symbol instance into coordinates that be can compared\n    // against other symbols in this index. Coordinates are:\n    // (1) local-tile-based (so after correction we get x,y values relative to our local anchorX/Y)\n    // (2) converted to the z-scale of this TileLayerIndex\n    // (3) down-sampled by \"roundingFactor\" from tile coordinate precision in order to be\n    //     more tolerant of small differences between tiles.\n    getScaledCoordinates(symbolInstance: SymbolInstance, childTileID: OverscaledTileID): {x: number; y: number} {\n        const {x: localX, y: localY, z: localZ} = this.tileID.canonical;\n        const {x, y, z} = childTileID.canonical;\n\n        const zDifference = z - localZ;\n        const scale = roundingFactor / Math.pow(2, zDifference);\n        const xWorld = (x * EXTENT + symbolInstance.anchorX) * scale;\n        const yWorld = (y * EXTENT + symbolInstance.anchorY) * scale;\n        const xOffset = localX * EXTENT * roundingFactor;\n        const yOffset = localY * EXTENT * roundingFactor;\n        return {\n            x: Math.floor(xWorld - xOffset),\n            y: Math.floor(yWorld - yOffset)\n        };\n    }\n\n    findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: {\n        [crossTileID: number]: boolean;\n    }): void {\n        const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z);\n\n        for (let i = 0; i < symbolInstances.length; i++) {\n            const symbolInstance = symbolInstances.get(i);\n            if (symbolInstance.crossTileID) {\n                // already has a match, skip\n                continue;\n            }\n\n            const entry = this._symbolsByKey[symbolInstance.key];\n            if (!entry) {\n                // No symbol with this key in this bucket\n                continue;\n            }\n\n            const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID);\n\n            if (entry.index) {\n                this.findMatchesForIndexedEntry(entry, symbolInstance, scaledSymbolCoord, tolerance, zoomCrossTileIDs);\n            } else if (entry.positions) {\n                this.findMatchesForNonIndexedEntry(entry, symbolInstance, scaledSymbolCoord, tolerance, zoomCrossTileIDs);\n            }\n        }\n    }\n\n    /**\n     * Matches a symbol instance against an entry backed by a KDBush spatial index\n     * (used for keys with more than {@link KDBUSH_THRESHHOLD} symbols).\n     *\n     * Matches any symbol with the same key whose coordinates are within one grid\n     * unit (with a 4px grid, this covers a 12px by 12px area). The lowest-index\n     * unclaimed candidate is claimed in a single pass rather than sorting the\n     * whole result set on every query: `range()` can return many candidates where\n     * symbols are coincident (e.g. stacked point markers), so a per-query sort\n     * would dominate placement cost on dense layers.\n     *\n     * Once a symbol is marked duplicate against a parent symbol, no other symbol\n     * at the same zoom level may duplicate against the same parent (see issue #5993).\n     */\n    private findMatchesForIndexedEntry(entry: SymbolsByKeyEntry, symbolInstance: SymbolInstance, scaledSymbolCoord: {x: number; y: number}, tolerance: number, zoomCrossTileIDs: {\n        [crossTileID: number]: boolean;\n    }): void {\n        const indexes = entry.index.range(\n            scaledSymbolCoord.x - tolerance,\n            scaledSymbolCoord.y - tolerance,\n            scaledSymbolCoord.x + tolerance,\n            scaledSymbolCoord.y + tolerance);\n\n        let bestIndex = Infinity;\n        for (const candidate of indexes) {\n            if (candidate < bestIndex && !zoomCrossTileIDs[entry.crossTileIDs[candidate]]) {\n                bestIndex = candidate;\n            }\n        }\n        if (bestIndex !== Infinity) {\n            const crossTileID = entry.crossTileIDs[bestIndex];\n            zoomCrossTileIDs[crossTileID] = true;\n            symbolInstance.crossTileID = crossTileID;\n        }\n    }\n\n    /**\n     * Matches a symbol instance against an entry that stores its positions as a\n     * plain array (used for keys with at most {@link KDBUSH_THRESHHOLD} symbols).\n     *\n     * Matches any symbol with the same key whose coordinates are within one grid\n     * unit (with a 4px grid, this covers a 12px by 12px area). Positions are\n     * stored in symbol-instance order, so the first unclaimed match is also the\n     * lowest-index one.\n     *\n     * Once a symbol is marked duplicate against a parent symbol, no other symbol\n     * at the same zoom level may duplicate against the same parent (see issue #5993).\n     */\n    private findMatchesForNonIndexedEntry(entry: SymbolsByKeyEntry, symbolInstance: SymbolInstance, scaledSymbolCoord: {x: number; y: number}, tolerance: number, zoomCrossTileIDs: {\n        [crossTileID: number]: boolean;\n    }): void {\n        for (let i = 0; i < entry.positions.length; i++) {\n            const thisTileSymbol = entry.positions[i];\n            const crossTileID = entry.crossTileIDs[i];\n\n            if (Math.abs(thisTileSymbol.x - scaledSymbolCoord.x) <= tolerance &&\n                Math.abs(thisTileSymbol.y - scaledSymbolCoord.y) <= tolerance &&\n                !zoomCrossTileIDs[crossTileID]) {\n                zoomCrossTileIDs[crossTileID] = true;\n                symbolInstance.crossTileID = crossTileID;\n                break;\n            }\n        }\n    }\n\n    getCrossTileIDsLists(): number[][] {\n        return Object.values(this._symbolsByKey).map(({crossTileIDs}) => crossTileIDs);\n    }\n}\n\nclass CrossTileIDs {\n    maxCrossTileID: number;\n    constructor() {\n        this.maxCrossTileID = 0;\n    }\n    generate(): number {\n        return ++this.maxCrossTileID;\n    }\n}\n\nclass CrossTileSymbolLayerIndex {\n    indexes: {\n        [zoom in string | number]: {\n            [tileId in string | number]: TileLayerIndex;\n        };\n    };\n    usedCrossTileIDs: {\n        [zoom in string | number]: {\n            [crossTileID: number]: boolean;\n        };\n    };\n    lng: number;\n\n    constructor() {\n        this.indexes = {};\n        this.usedCrossTileIDs = {};\n        this.lng = 0;\n    }\n\n    /*\n     * Sometimes when a user pans across the antimeridian the longitude value gets wrapped.\n     * To prevent labels from flashing out and in we adjust the tileID values in the indexes\n     * so that they match the new wrapped version of the map.\n     */\n    handleWrapJump(lng: number): void {\n        const wrapDelta = Math.round((lng - this.lng) / 360);\n        if (wrapDelta !== 0) {\n            for (const zoom in this.indexes) {\n                const zoomIndexes = this.indexes[zoom];\n                const newZoomIndex = {};\n                for (const key in zoomIndexes) {\n                    // change the tileID's wrap and add it to a new index\n                    const index = zoomIndexes[key];\n                    index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta);\n                    newZoomIndex[index.tileID.key] = index;\n                }\n                this.indexes[zoom] = newZoomIndex;\n            }\n        }\n        this.lng = lng;\n    }\n\n    addBucket(tileID: OverscaledTileID, bucket: SymbolBucket, crossTileIDs: CrossTileIDs): boolean {\n        if (this.indexes[tileID.overscaledZ]?.[tileID.key]) {\n            if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId ===\n                bucket.bucketInstanceId) {\n                return false;\n            } else {\n                // We're replacing this bucket with an updated version\n                // Remove the old bucket's \"used crossTileIDs\" now so that\n                // the new bucket can claim them.\n                // The old index entries themselves stick around until\n                // 'removeStaleBuckets' is called.\n                this.removeBucketCrossTileIDs(tileID.overscaledZ,\n                    this.indexes[tileID.overscaledZ][tileID.key]);\n            }\n        }\n\n        for (let i = 0; i < bucket.symbolInstances.length; i++) {\n            const symbolInstance = bucket.symbolInstances.get(i);\n            symbolInstance.crossTileID = 0;\n        }\n\n        this.usedCrossTileIDs[tileID.overscaledZ] ||= {};\n        const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ];\n\n        for (const zoom in this.indexes) {\n            const zoomIndexes = this.indexes[zoom];\n            if (Number(zoom) > tileID.overscaledZ) {\n                for (const id in zoomIndexes) {\n                    const childIndex = zoomIndexes[id];\n                    if (childIndex.tileID.isChildOf(tileID)) {\n                        childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);\n                    }\n                }\n            } else {\n                const parentCoord = tileID.scaledTo(Number(zoom));\n                const parentIndex = zoomIndexes[parentCoord.key];\n                if (parentIndex) {\n                    parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);\n                }\n            }\n        }\n\n        for (let i = 0; i < bucket.symbolInstances.length; i++) {\n            const symbolInstance = bucket.symbolInstances.get(i);\n            if (!symbolInstance.crossTileID) {\n                // symbol did not match any known symbol, assign a new id\n                symbolInstance.crossTileID = crossTileIDs.generate();\n                zoomCrossTileIDs[symbolInstance.crossTileID] = true;\n            }\n        }\n\n        if (this.indexes[tileID.overscaledZ] === undefined) {\n            this.indexes[tileID.overscaledZ] = {};\n        }\n        this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId);\n\n        return true;\n    }\n\n    removeBucketCrossTileIDs(zoom: string | number, removedBucket: TileLayerIndex): void {\n        for (const crossTileIDs of removedBucket.getCrossTileIDsLists()) {\n            for (const crossTileID of crossTileIDs) {\n                delete this.usedCrossTileIDs[zoom][crossTileID];\n            }\n        }\n    }\n\n    removeStaleBuckets(currentIDs: {\n        [k in string | number]: boolean;\n    }): boolean {\n        let tilesChanged = false;\n        for (const z in this.indexes) {\n            const zoomIndexes = this.indexes[z];\n            for (const tileKey in zoomIndexes) {\n                if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) {\n                    this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]);\n                    delete zoomIndexes[tileKey];\n                    tilesChanged = true;\n                }\n            }\n        }\n        return tilesChanged;\n    }\n}\n\nexport class CrossTileSymbolIndex {\n    layerIndexes: {[layerId: string]: CrossTileSymbolLayerIndex};\n    crossTileIDs: CrossTileIDs;\n    maxBucketInstanceId: number;\n    bucketsInCurrentPlacement: {[_: number]: boolean};\n\n    constructor() {\n        this.layerIndexes = {};\n        this.crossTileIDs = new CrossTileIDs();\n        this.maxBucketInstanceId = 0;\n        this.bucketsInCurrentPlacement = {};\n    }\n\n    addLayer(styleLayer: StyleLayer, tiles: Tile[], lng: number): boolean {\n        let layerIndex = this.layerIndexes[styleLayer.id];\n        if (layerIndex === undefined) {\n            layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex();\n        }\n\n        let symbolBucketsChanged = false;\n        const currentBucketIDs = {};\n\n        layerIndex.handleWrapJump(lng);\n\n        for (const tile of tiles) {\n            const symbolBucket = (tile.getBucket(styleLayer) as any as SymbolBucket);\n            if (styleLayer.id !== symbolBucket?.layerIds[0])\n                continue;\n\n            if (!symbolBucket.bucketInstanceId) {\n                this.maxBucketInstanceId += 1;\n                symbolBucket.bucketInstanceId = this.maxBucketInstanceId;\n            }\n\n            if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) {\n                symbolBucketsChanged = true;\n            }\n            currentBucketIDs[symbolBucket.bucketInstanceId] = true;\n        }\n\n        if (layerIndex.removeStaleBuckets(currentBucketIDs)) {\n            symbolBucketsChanged = true;\n        }\n\n        return symbolBucketsChanged;\n    }\n\n    pruneUnusedLayers(usedLayers: string[]): void {\n        const usedLayerMap = {};\n        for (const usedLayer of usedLayers) {\n            usedLayerMap[usedLayer] = true;\n        }\n        for (const layerId in this.layerIndexes) {\n            if (!usedLayerMap[layerId]) {\n                delete this.layerIndexes[layerId];\n            }\n        }\n    }\n}\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision mediump float;\\n#else\\n#if !defined(lowp)\\n#define lowp\\n#endif\\n#if !defined(mediump)\\n#define mediump\\n#endif\\n#if !defined(highp)\\n#define highp\\n#endif\\n#endif\\nout highp vec4 fragColor;layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#else\\n#if !defined(lowp)\\n#define lowp\\n#endif\\n#if !defined(mediump)\\n#define mediump\\n#endif\\n#if !defined(highp)\\n#define highp\\n#endif\\n#endif\\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const uint packedOpacity) {return vec2(float(packedOpacity >> 1u)/127.0,float(packedOpacity & 1u));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+      c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+    c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+    c\\n);}\\n#ifdef TERRAIN3D\\nuniform sampler2D u_terrain;uniform highp sampler2D u_depth;layout(std140) uniform TerrainUBO {highp mat4 u_terrain_matrix;highp vec4 u_terrain_unpack;highp float u_terrain_dim;highp float u_terrain_exaggeration;};\\n#endif\\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\\n#ifdef TERRAIN3D\\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\\n#else\\nreturn 1.0;\\n#endif\\n}float calculate_visibility(vec4 pos) {\\n#ifdef TERRAIN3D\\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\\n#else\\nreturn 1.0;\\n#endif\\n}float ele(ivec2 pos) {\\n#ifdef TERRAIN3D\\nvec4 rgb=(texelFetch(u_terrain,pos,0)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\\n#else\\nreturn 0.0;\\n#endif\\n}float get_elevation(vec2 pos) {\\n#ifdef TERRAIN3D\\n#ifdef GLOBE\\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\\n#endif\\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.5;vec2 f=fract(coord);ivec2 c=ivec2(floor(coord));ivec2 hi=textureSize(u_terrain,0)-1;float tl=ele(clamp(c,ivec2(0),hi));float tr=ele(clamp(c+ivec2(1,0),ivec2(0),hi));float bl=ele(clamp(c+ivec2(0,1),ivec2(0),hi));float br=ele(clamp(c+ivec2(1,1),ivec2(0),hi));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\\n#else\\nreturn 0.0;\\n#endif\\n}const float PI=3.141592653589793;\\n#define PROJECTION_UBO\\nlayout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in vec3 v_data;in float v_visibility;\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define mediump float radius\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define highp vec4 stroke_color\\n#pragma maplibre: define mediump float stroke_width\\n#pragma maplibre: define lowp float stroke_opacity\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize mediump float radius\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize highp vec4 stroke_color\\n#pragma maplibre: initialize mediump float stroke_width\\n#pragma maplibre: initialize lowp float stroke_opacity\\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform vec2 u_translate;layout(location=0) in ivec2 a_pos;out vec3 v_data;out float v_visibility;\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define mediump float radius\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define highp vec4 stroke_color\\n#pragma maplibre: define mediump float stroke_width\\n#pragma maplibre: define lowp float stroke_opacity\\nvoid main(void) {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize mediump float radius\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize highp vec4 stroke_color\\n#pragma maplibre: initialize mediump float stroke_width\\n#pragma maplibre: initialize lowp float stroke_opacity\\nivec2 pos_raw=a_pos+32768;vec2 extrude=vec2(pos_raw & 7)/7.0*2.0-1.0;vec2 circle_center=vec2(pos_raw >> 3)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\\n#ifdef GLOBE\\nvec3 center_vector=projectToSphere(circle_center);\\n#endif\\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\\n#ifdef GLOBE\\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\\n#else\\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\\n#endif\\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\\n#ifdef GLOBE\\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\\n#else\\ngl_Position=projectTileWithElevation(corner_position,ele);\\n#endif\\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'void main() {fragColor=vec4(1.0);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform highp float u_intensity;in vec2 v_extrude;\\n#pragma maplibre: define highp float weight\\n#define GAUSS_COEF 0.3989422804014327\\nvoid main() {\\n#pragma maplibre: initialize highp float weight\\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;layout(location=0) in ivec2 a_pos;out vec2 v_extrude;\\n#pragma maplibre: define highp float weight\\n#pragma maplibre: define mediump float radius\\nconst highp float ZERO=1.0/255.0/16.0;\\n#define GAUSS_COEF 0.3989422804014327\\nvoid main(void) {\\n#pragma maplibre: initialize highp float weight\\n#pragma maplibre: initialize mediump float radius\\nivec2 pos_raw=a_pos+32768;vec2 unscaled_extrude=vec2(pos_raw & 7)/7.0*2.0-1.0;float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=vec2(pos_raw >> 3);\\n#ifdef GLOBE\\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\\n#else\\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(0.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world_size,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_anchor_pos;layout(location=1) in vec2 a_placed;layout(location=2) in vec2 a_box_real;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;layout(location=1) in float a_radius;layout(location=2) in vec2 a_flags;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {vec4 data=texelFetch(u_elevation_stops,ivec2(stop,0),0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=2.0/u_dimension;float scale=(u_dimension.x-4.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;void main() {\\n#ifdef GLOBE\\ngl_Position=projectTileFor3D(a_pos,0.0);\\n#else\\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize lowp float opacity\\nfragColor=color*opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize lowp float opacity\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in vec2 v_pos;\\n#ifdef GLOBE\\nin float v_depth;\\n#endif\\n#pragma maplibre: define highp vec4 outline_color\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 outline_color\\n#pragma maplibre: initialize lowp float opacity\\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\\n#ifdef GLOBE\\nif (v_depth > 1.0) {discard;}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;out vec2 v_pos;\\n#ifdef GLOBE\\nout float v_depth;\\n#endif\\n#pragma maplibre: define highp vec4 outline_color\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 outline_color\\n#pragma maplibre: initialize lowp float opacity\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world_size;\\n#ifdef GLOBE\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;uniform bool u_sdf_pattern;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\\n#ifdef GLOBE\\nin float v_depth;\\n#endif\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);if (u_sdf_pattern) {highp float sdf_edge=(256.0-64.0)/256.0;highp float sdf_gamma_a=max(fwidth(color1.a)*0.5,1.0/255.0/16.0);highp float sdf_gamma_b=max(fwidth(color2.a)*0.5,1.0/255.0/16.0);float sdf_alpha_a=smoothstep(sdf_edge-sdf_gamma_a,sdf_edge+sdf_gamma_a,color1.a);float sdf_alpha_b=smoothstep(sdf_edge-sdf_gamma_b,sdf_edge+sdf_gamma_b,color2.a);fragColor=mix(color*sdf_alpha_a,color*sdf_alpha_b,u_fade)*alpha*opacity;} else {fragColor=mix(color1,color2,u_fade)*alpha*opacity;}\\n#ifdef GLOBE\\nif (v_depth > 1.0) {discard;}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\\n#ifdef GLOBE\\nout float v_depth;\\n#endif\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\n#pragma maplibre: define lowp float pixel_ratio_from\\n#pragma maplibre: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\n#pragma maplibre: initialize lowp float pixel_ratio_from\\n#pragma maplibre: initialize lowp float pixel_ratio_to\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world_size;\\n#ifdef GLOBE\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nuniform vec2 u_texsize;uniform float u_fade;uniform bool u_sdf_pattern;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);if (u_sdf_pattern) {highp float sdf_edge=(256.0-64.0)/256.0;highp float sdf_gamma_a=max(fwidth(color1.a)*0.5,1.0/255.0/16.0);highp float sdf_gamma_b=max(fwidth(color2.a)*0.5,1.0/255.0/16.0);float sdf_alpha_a=smoothstep(sdf_edge-sdf_gamma_a,sdf_edge+sdf_gamma_a,color1.a);float sdf_alpha_b=smoothstep(sdf_edge-sdf_gamma_b,sdf_edge+sdf_gamma_b,color2.a);fragColor=mix(color*sdf_alpha_a,color*sdf_alpha_b,u_fade)*opacity;} else {fragColor=mix(color1,color2,u_fade)*opacity;}\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\n#pragma maplibre: define lowp float pixel_ratio_from\\n#pragma maplibre: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\n#pragma maplibre: initialize lowp float pixel_ratio_from\\n#pragma maplibre: initialize lowp float pixel_ratio_to\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in vec4 v_color;void main() {fragColor=v_color;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;\\n#ifdef TERRAIN3D\\nlayout(location=2) in vec2 a_centroid;\\n#endif\\nout vec4 v_color;\\n#pragma maplibre: define highp float base\\n#pragma maplibre: define highp float height\\n#pragma maplibre: define highp vec4 color\\nvoid main() {\\n#pragma maplibre: initialize highp float base\\n#pragma maplibre: initialize highp float height\\n#pragma maplibre: initialize highp vec4 color\\nvec3 normal=vec3(a_normal_ed.xyz);float gradient_base=max(0.0,base);float gradient_height=max(0.0,height);\\n#ifdef TERRAIN3D\\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\\n#else\\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\\n#endif\\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=float(a_normal_ed.x & 1);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\\n#ifdef GLOBE\\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\\n#else\\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\\n#endif\\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\\n#ifdef GLOBE\\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\\n#endif\\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\\n#pragma maplibre: define lowp float base\\n#pragma maplibre: define lowp float height\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\n#pragma maplibre: define lowp float pixel_ratio_from\\n#pragma maplibre: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float base\\n#pragma maplibre: initialize lowp float height\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\n#pragma maplibre: initialize lowp float pixel_ratio_from\\n#pragma maplibre: initialize lowp float pixel_ratio_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;\\n#ifdef TERRAIN3D\\nlayout(location=2) in vec2 a_centroid;\\n#endif\\n#ifdef GLOBE\\nout vec3 v_sphere_pos;\\n#endif\\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\\n#pragma maplibre: define lowp float base\\n#pragma maplibre: define lowp float height\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\n#pragma maplibre: define lowp float pixel_ratio_from\\n#pragma maplibre: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float base\\n#pragma maplibre: initialize lowp float height\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\n#pragma maplibre: initialize lowp float pixel_ratio_from\\n#pragma maplibre: initialize lowp float pixel_ratio_to\\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=vec3(a_normal_ed.xyz);float edgedistance=float(a_normal_ed.w);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;float gradient_base=max(0.0,base);float gradient_height=max(0.0,height);\\n#ifdef TERRAIN3D\\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\\n#else\\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\\n#endif\\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=float(a_normal_ed.x & 1);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\\n#ifdef GLOBE\\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\\n#else\\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\\n#endif\\nvec2 pos=a_normal_ed.x==1 && a_normal_ed.y==0 && a_normal_ed.z==16384\\n? a_pos\\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;uniform float u_log2_world_width;float getElevation(ivec2 texel) {vec4 data=texelFetch(u_image,texel,0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {ivec2 pos=ivec2(gl_FragCoord.xy)+ivec2(1);float tileSize=u_dimension.x-4.0;float a=getElevation(pos+ivec2(-1,-1));float b=getElevation(pos+ivec2(0,-1));float c=getElevation(pos+ivec2(1,-1));float d=getElevation(pos+ivec2(-1,0));float e=getElevation(pos);float f=getElevation(pos+ivec2(1,0));float g=getElevation(pos+ivec2(-1,1));float h=getElevation(pos+ivec2(0,1));float i=getElevation(pos+ivec2(1,1));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(3.0+u_log2_world_width-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+128.0/255.0,deriv.y/8.0+128.0/255.0,1.0,1.0),0.0,1.0);\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;layout(location=1) in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_image;in highp vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\\n#define PI 3.141592653589793\\n#define STANDARD 0\\n#define COMBINED 1\\n#define IGOR 2\\n#define MULTIDIRECTIONAL 3\\n#define BASIC 4\\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {highp vec2 size=vec2(textureSize(u_image,0));highp vec2 texturePos=(v_pos*(size-2.0)+1.0)/size;vec4 pixel=texture(u_image,texturePos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=(pixel.rg-128.0/255.0)*8.0/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\\n#ifdef GLOBE\\nin float v_depth;\\n#endif\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\\n#ifdef GLOBE\\nif (v_depth > 1.0) {discard;}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;uniform vec2 u_translation;uniform mediump float u_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\\n#ifdef GLOBE\\nout float v_depth;\\n#endif\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define mediump float gapwidth\\n#pragma maplibre: define lowp float offset\\n#pragma maplibre: define mediump float width\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize mediump float gapwidth\\n#pragma maplibre: initialize lowp float offset\\n#pragma maplibre: initialize mediump float width\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);v_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*2.0;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\\n#ifdef GLOBE\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\\n#endif\\nv_width2=vec2(outset,inset);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\\n#ifdef GLOBE\\nin float v_depth;\\n#endif\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\\n#ifdef GLOBE\\nif (v_depth > 1.0) {discard;}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;layout(location=3) in float a_uv_x;layout(location=4) in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\\n#ifdef GLOBE\\nout float v_depth;\\n#endif\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define mediump float gapwidth\\n#pragma maplibre: define lowp float offset\\n#pragma maplibre: define mediump float width\\nvoid main() {\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize mediump float gapwidth\\n#pragma maplibre: initialize lowp float offset\\n#pragma maplibre: initialize mediump float width\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\\n#ifdef GLOBE\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\\n#endif\\nv_width2=vec2(outset,inset);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nuniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\\n#ifdef GLOBE\\nin float v_depth;\\n#endif\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\n#pragma maplibre: define lowp float pixel_ratio_from\\n#pragma maplibre: define lowp float pixel_ratio_to\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\n#pragma maplibre: initialize lowp float pixel_ratio_from\\n#pragma maplibre: initialize lowp float pixel_ratio_to\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\nclipAntimeridian();vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\\n#ifdef GLOBE\\nif (v_depth > 1.0) {discard;}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\n#define LINE_DISTANCE_SCALE 2.0\\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;uniform vec2 u_translation;uniform mediump float u_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\\n#ifdef GLOBE\\nout float v_depth;\\n#endif\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define lowp float offset\\n#pragma maplibre: define mediump float gapwidth\\n#pragma maplibre: define mediump float width\\n#pragma maplibre: define lowp float floorwidth\\n#pragma maplibre: define lowp vec4 pattern_from\\n#pragma maplibre: define lowp vec4 pattern_to\\n#pragma maplibre: define lowp float pixel_ratio_from\\n#pragma maplibre: define lowp float pixel_ratio_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize lowp float offset\\n#pragma maplibre: initialize mediump float gapwidth\\n#pragma maplibre: initialize mediump float width\\n#pragma maplibre: initialize lowp float floorwidth\\n#pragma maplibre: initialize mediump vec4 pattern_from\\n#pragma maplibre: initialize mediump vec4 pattern_to\\n#pragma maplibre: initialize lowp float pixel_ratio_from\\n#pragma maplibre: initialize lowp float pixel_ratio_to\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\\n#ifdef GLOBE\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\\n#endif\\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform lowp float u_lineatlas_width;uniform sampler2D u_image;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\\n#ifdef GLOBE\\nin float v_depth;\\n#endif\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define mediump float width\\n#pragma maplibre: define lowp float floorwidth\\n#pragma maplibre: define mediump vec4 dasharray_from\\n#pragma maplibre: define mediump vec4 dasharray_to\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize mediump float width\\n#pragma maplibre: initialize lowp float floorwidth\\n#pragma maplibre: initialize mediump vec4 dasharray_from\\n#pragma maplibre: initialize mediump vec4 dasharray_to\\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);float sdfgamma=(u_lineatlas_width/256.0/u_device_pixel_ratio)/min(dasharray_from.w,dasharray_to.w);alpha*=smoothstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\\n#ifdef GLOBE\\nif (v_depth > 1.0) {discard;}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\n#define LINE_DISTANCE_SCALE 2.0\\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;uniform vec2 u_translation;uniform mediump float u_ratio;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\\n#ifdef GLOBE\\nout float v_depth;\\n#endif\\n#pragma maplibre: define highp vec4 color\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define mediump float gapwidth\\n#pragma maplibre: define lowp float offset\\n#pragma maplibre: define mediump float width\\n#pragma maplibre: define lowp float floorwidth\\n#pragma maplibre: define mediump vec4 dasharray_from\\n#pragma maplibre: define mediump vec4 dasharray_to\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 color\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize mediump float gapwidth\\n#pragma maplibre: initialize lowp float offset\\n#pragma maplibre: initialize mediump float width\\n#pragma maplibre: initialize lowp float floorwidth\\n#pragma maplibre: initialize mediump vec4 dasharray_from\\n#pragma maplibre: initialize mediump vec4 dasharray_to\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\\n#ifdef GLOBE\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\\n#endif\\nfloat u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_image;uniform sampler2D u_image_dash;uniform float u_mix;uniform lowp float u_lineatlas_width;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;in highp vec2 v_uv;\\n#ifdef GLOBE\\nin float v_depth;\\n#endif\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define mediump float width\\n#pragma maplibre: define lowp float floorwidth\\n#pragma maplibre: define mediump vec4 dasharray_from\\n#pragma maplibre: define mediump vec4 dasharray_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize mediump float width\\n#pragma maplibre: initialize lowp float floorwidth\\n#pragma maplibre: initialize mediump vec4 dasharray_from\\n#pragma maplibre: initialize mediump vec4 dasharray_to\\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);float sdfdist_a=texture(u_image_dash,v_tex_a).a;float sdfdist_b=texture(u_image_dash,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);float sdfgamma=(u_lineatlas_width/256.0)/min(dasharray_from.w,dasharray_to.w);float dash_alpha=smoothstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*dash_alpha*opacity);\\n#ifdef GLOBE\\nif (v_depth > 1.0) {discard;}\\n#endif\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\n#define scale 0.015873016\\n#define LINE_DISTANCE_SCALE 2.0\\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;layout(location=3) in float a_uv_x;layout(location=4) in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform float u_image_height;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;out vec2 v_tex_a;out vec2 v_tex_b;\\n#ifdef GLOBE\\nout float v_depth;\\n#endif\\n#pragma maplibre: define lowp float blur\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define mediump float gapwidth\\n#pragma maplibre: define lowp float offset\\n#pragma maplibre: define mediump float width\\n#pragma maplibre: define lowp float floorwidth\\n#pragma maplibre: define mediump vec4 dasharray_from\\n#pragma maplibre: define mediump vec4 dasharray_to\\nvoid main() {\\n#pragma maplibre: initialize lowp float blur\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize mediump float gapwidth\\n#pragma maplibre: initialize lowp float offset\\n#pragma maplibre: initialize mediump float width\\n#pragma maplibre: initialize lowp float floorwidth\\n#pragma maplibre: initialize mediump vec4 dasharray_from\\n#pragma maplibre: initialize mediump vec4 dasharray_to\\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;float texel_height=1.0/u_image_height;float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\\n#ifdef GLOBE\\nv_depth=gl_Position.z/gl_Position.w;\\n#endif\\n#ifdef TERRAIN3D\\nv_gamma_scale=1.0;\\n#else\\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\\n#endif\\nfloat u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_image;uniform float u_opacity;in vec2 v_pos;void main() {fragColor=texture(u_image,v_pos)*u_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(0.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos.x*2.0-1.0,1.0-a_pos.y*2.0,0.0,1.0);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec3 v_pos0;in vec3 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0.xy/v_pos0.z);vec4 color1=texture(u_image1,v_pos1.xy/v_pos1.z);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec3 u_image_warp;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;layout(location=0) in vec2 a_pos;out vec3 v_pos0;out vec3 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 topLeft=u_coords_top.xy;vec2 topRight=u_coords_top.zw;vec2 bottomLeft=u_coords_bottom.xy;vec2 bottomRight=u_coords_bottom.zw;vec2 bilinearPos=mix(mix(topLeft,topRight,fractionalPos.x),mix(bottomLeft,bottomRight,fractionalPos.x),fractionalPos.y);float denominator=dot(u_image_warp.xy,fractionalPos)+1.0;vec2 acrossTop=topRight-topLeft+u_image_warp.x*topRight;vec2 downLeft=bottomLeft-topLeft+u_image_warp.y*bottomLeft;vec2 projectivePos=(acrossTop*fractionalPos.x+downLeft*fractionalPos.y+topLeft)/denominator;vec2 position=mix(projectivePos,bilinearPos,u_image_warp.z);gl_Position=projectTile(position,position);vec2 texturePos=((fractionalPos-0.5)/u_buffer_scale)+0.5;\\n#ifdef GLOBE\\nif (a_pos.y <-32767.5) {texturePos.y=0.0;}if (a_pos.y > 32766.5) {texturePos.y=1.0;}\\n#endif\\nfloat perspectiveRatio=mix(1.0/denominator,1.0,u_image_warp.z);v_pos0=vec3(texturePos*perspectiveRatio,perspectiveRatio);vec2 parentPos=(texturePos*u_scale_parent)+u_tl_parent;v_pos1=vec3(parentPos*perspectiveRatio,perspectiveRatio);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_texture;in vec2 v_tex;in float v_total_opacity;void main() {fragColor=texture(u_texture,v_tex)*v_total_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec4 a_pos_offset;layout(location=1) in uvec4 a_data;layout(location=2) in vec4 a_pixeloffset;layout(location=3) in vec3 a_projected_pos;layout(location=4) in uint a_fade_opacity;layout(location=5) in float a_height_offset;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform bool u_rotate_symbol;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;uniform bool u_is_offset;uniform bool u_height_anchor_ground;out vec2 v_tex;out float v_total_opacity;\\n#pragma maplibre: define lowp float opacity\\nvoid main() {\\n#pragma maplibre: initialize lowp float opacity\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=vec2(a_data.xy);vec2 a_size=vec2(a_data.zw);float a_size_min=float(a_data.z >> 1u);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=a_height_offset+(u_height_anchor_ground ? get_elevation(a_pos) : 0.0);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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=mix(-u_symbol_fade_change,u_symbol_fade_change,fade_opacity[1]);float visibility=calculate_visibility(projectedPoint);v_total_opacity=opacity*max(0.0,min(visibility,fade_opacity[0]+fade_change));if (v_total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\\ncamera_to_anchor_distance/u_camera_to_center_distance :\\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);if (!u_is_offset) {size*=perspective_ratio;}float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\\n#ifdef GLOBE\\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\\n#endif\\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#define SDF_PX 8.0\\nuniform bool u_is_halo;uniform bool u_is_plain;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\\n#pragma maplibre: define highp vec4 fill_color\\n#pragma maplibre: define highp vec4 halo_color\\n#pragma maplibre: define lowp float halo_width\\n#pragma maplibre: define lowp float halo_blur\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 fill_color\\n#pragma maplibre: initialize highp vec4 halo_color\\n#pragma maplibre: initialize lowp float halo_width\\n#pragma maplibre: initialize lowp float halo_blur\\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float total_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;lowp float dist=texture(u_texture,tex).a;lowp vec4 color_alpha_out_text,color_alpha_out_halo;if (u_is_plain){highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);color_alpha_out_text=total_opacity*alpha*fill_color;}if (u_is_halo) {float gamma_halo=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);float inner_edge_halo=inner_edge+gamma_halo*gamma_scale;highp float gamma_scaled_halo=gamma_halo*gamma_scale;highp float alpha_halo=smoothstep(inner_edge_halo-gamma_scaled_halo,inner_edge_halo+gamma_scaled_halo,dist);highp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha_halo= min(smoothstep(halo_edge-gamma_scaled_halo,halo_edge+gamma_scaled_halo,dist),1.0-alpha_halo);color_alpha_out_halo=total_opacity*alpha_halo*halo_color;}if (u_is_plain && u_is_halo) {fragColor=color_alpha_out_text+(1.-color_alpha_out_text.a)*color_alpha_out_halo;} else if (u_is_halo){fragColor=color_alpha_out_halo;} else {fragColor=color_alpha_out_text;}\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec4 a_pos_offset;layout(location=1) in uvec4 a_data;layout(location=2) in vec4 a_pixeloffset;layout(location=3) in vec3 a_projected_pos;layout(location=4) in uint a_fade_opacity;layout(location=5) in float a_height_offset;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform bool u_rotate_symbol;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;uniform bool u_is_offset;uniform bool u_height_anchor_ground;out vec2 v_data0;out vec3 v_data1;\\n#pragma maplibre: define highp vec4 fill_color\\n#pragma maplibre: define highp vec4 halo_color\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define lowp float halo_width\\n#pragma maplibre: define lowp float halo_blur\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 fill_color\\n#pragma maplibre: initialize highp vec4 halo_color\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize lowp float halo_width\\n#pragma maplibre: initialize lowp float halo_blur\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=vec2(a_data.xy);vec2 a_size=vec2(a_data.zw);float a_size_min=float(a_data.z >> 1u);vec2 a_pxoffset=a_pixeloffset.xy/16.0;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=a_height_offset+(u_height_anchor_ground ? get_elevation(a_pos) : 0.0);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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=mix(-u_symbol_fade_change,u_symbol_fade_change,fade_opacity[1]);float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));float total_opacity=opacity*interpolated_fade_opacity;if (total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\\ncamera_to_anchor_distance/u_camera_to_center_distance :\\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);if (!u_is_offset) {size*=perspective_ratio;}float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\\n#ifdef GLOBE\\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\\n#endif\\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,total_opacity);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#define SDF_PX 8.0\\n#define SDF 1.0\\n#define ICON 0.0\\nuniform bool u_is_halo;uniform bool u_is_text;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;in vec4 v_data0;in vec3 v_data1;in float v_is_sdf;\\n#pragma maplibre: define highp vec4 fill_color\\n#pragma maplibre: define highp vec4 halo_color\\n#pragma maplibre: define lowp float halo_width\\n#pragma maplibre: define lowp float halo_blur\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 fill_color\\n#pragma maplibre: initialize highp vec4 halo_color\\n#pragma maplibre: initialize lowp float halo_width\\n#pragma maplibre: initialize lowp float halo_blur\\nfloat total_opacity=v_data1[2];if (v_is_sdf==ICON) {vec2 tex_icon=v_data0.zw;fragColor=texture(u_texture_icon,tex_icon)*total_opacity;\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;lowp float dist=texture(u_texture,tex).a;lowp vec4 color_alpha_out,color_alpha_out_halo;if (u_is_text) {highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);color_alpha_out=fill_color*(alpha*total_opacity);}if (u_is_halo) {highp float gamma_halo=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);lowp float buff_halo=(6.0-halo_width/fontScale)/SDF_PX;highp float gamma_scaled_halo=gamma_halo*gamma_scale;highp float alpha_halo=smoothstep(buff_halo-gamma_scaled_halo,buff_halo+gamma_scaled_halo,dist);color_alpha_out_halo=halo_color*(alpha_halo*total_opacity);}if (u_is_text && u_is_halo) {fragColor=color_alpha_out+(1.-color_alpha_out.a)*color_alpha_out_halo;} else if (u_is_halo) {fragColor=color_alpha_out_halo;} else {fragColor=color_alpha_out;}\\n#ifdef OVERDRAW_INSPECTOR\\nfragColor=vec4(1.0);\\n#endif\\n}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec4 a_pos_offset;layout(location=1) in uvec4 a_data;layout(location=2) in vec3 a_projected_pos;layout(location=3) in uint a_fade_opacity;layout(location=4) in float a_height_offset;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;uniform bool u_is_offset;uniform bool u_height_anchor_ground;out vec4 v_data0;out vec3 v_data1;out float v_is_sdf;\\n#pragma maplibre: define highp vec4 fill_color\\n#pragma maplibre: define highp vec4 halo_color\\n#pragma maplibre: define lowp float opacity\\n#pragma maplibre: define lowp float halo_width\\n#pragma maplibre: define lowp float halo_blur\\nvoid main() {\\n#pragma maplibre: initialize highp vec4 fill_color\\n#pragma maplibre: initialize highp vec4 halo_color\\n#pragma maplibre: initialize lowp float opacity\\n#pragma maplibre: initialize lowp float halo_width\\n#pragma maplibre: initialize lowp float halo_blur\\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=vec2(a_data.xy);vec2 a_size=vec2(a_data.zw);float a_size_min=float(a_data.z >> 1u);float is_sdf=float(a_data.z & 1u);float ele=a_height_offset+(u_height_anchor_ground ? get_elevation(a_pos) : 0.0);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;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=mix(-u_symbol_fade_change,u_symbol_fade_change,fade_opacity[1]);float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));float total_opacity=opacity*interpolated_fade_opacity;if (total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\\ncamera_to_anchor_distance/u_camera_to_center_distance :\\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);if (!u_is_offset) {size*=perspective_ratio;}float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);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;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\\n#ifdef GLOBE\\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\\n#endif\\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec3(gamma_scale,size,total_opacity);v_is_sdf=is_sdf;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && u_fog_ground_blend_opacity > 0.0 && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in highp float v_elevation;void main() {fragColor=vec4(v_elevation,0.0,0.0,1.0);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec3 a_pos3d;uniform vec4 u_tile_bounds;out highp float v_elevation;void main() {v_elevation=get_elevation(a_pos3d.xy);vec2 position=u_tile_bounds.xy+a_pos3d.xy/8192.0*u_tile_bounds.zw;gl_Position=vec4(position.x*2.0-1.0,1.0-position.y*2.0,0.0,1.0);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '\\nvoid clipAntimeridian() {}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#define GLOBE_RADIUS 6371008.8\\n#ifndef PROJECTION_UBO\\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;\\n#endif\\nout highp float v_projection_tile_x;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float t=exp(PI-(mercator_pos_y*PI*2.0));return (2.0*t)/(t*t+1.0);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY);if (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;float spherical_x=mercator_pos.x*PI*2.0+PI;float t=exp(PI-(mercator_pos.y*PI*2.0));float t2=t*t;float denom=t2+1.0;float sin_sy=(t2-1.0)/denom;float cos_sy=(2.0*t)/denom;vec3 pos=vec3(sin(spherical_x)*cos_sy,sin_sy,cos(spherical_x)*cos_sy\\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'in highp float v_projection_tile_x;void clipAntimeridian() {if (u_projection_clip_antimeridian !=0 && (v_projection_tile_x < 0.0 || v_projection_tile_x >=8192.0)) {discard;}}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default '#ifdef GL_ES\\nprecision highp float;\\n#endif\\nin vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;in vec3 v_view_direction;const float ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS=100000.0/6371000.0;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;float opacity=1.0;if (u_sky_blend > 0.0) {vec3 ray=normalize(v_view_direction);float globe_distance=length(u_globe_position);float angle_to_globe_center=acos(clamp(dot(ray,u_globe_position)/globe_distance,-1.0,1.0));float horizon_angle=asin(min(u_globe_radius/globe_distance,1.0));blend=mix(blend,((angle_to_globe_center-horizon_angle)*u_camera_to_center_distance+1.0)*u_device_pixel_ratio,u_sky_blend);float closest_approach=max(dot(ray,u_globe_position),0.0);float lowest_altitude=sqrt(max(globe_distance*globe_distance-closest_approach*closest_approach,0.0))-u_globe_radius;float atmosphere_height=u_globe_radius*ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS;float inside_atmosphere=1.0-smoothstep(atmosphere_height,10.0*atmosphere_height,globe_distance-u_globe_radius);float through_atmosphere=1.0-smoothstep(0.0,atmosphere_height,lowest_altitude);opacity=inside_atmosphere*through_atmosphere*(1.0-u_atmosphere_blend);}if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor*=mix(1.0,opacity,u_sky_blend);}';\n", "// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.\nexport default 'layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 v_view_direction;void main() {v_view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,1.0,1.0);}';\n", "// Disable Flow annotations here because Flow doesn't support importing GLSL files\n\nimport preludeFrag from './glsl/_prelude.fragment.glsl.g.ts';\nimport preludeVert from './glsl/_prelude.vertex.glsl.g.ts';\nimport backgroundFrag from './glsl/background.fragment.glsl.g.ts';\nimport backgroundVert from './glsl/background.vertex.glsl.g.ts';\nimport backgroundPatternFrag from './glsl/background_pattern.fragment.glsl.g.ts';\nimport backgroundPatternVert from './glsl/background_pattern.vertex.glsl.g.ts';\nimport circleFrag from './glsl/circle.fragment.glsl.g.ts';\nimport circleVert from './glsl/circle.vertex.glsl.g.ts';\nimport clippingMaskFrag from './glsl/clipping_mask.fragment.glsl.g.ts';\nimport clippingMaskVert from './glsl/clipping_mask.vertex.glsl.g.ts';\nimport heatmapFrag from './glsl/heatmap.fragment.glsl.g.ts';\nimport heatmapVert from './glsl/heatmap.vertex.glsl.g.ts';\nimport heatmapTextureFrag from './glsl/heatmap_texture.fragment.glsl.g.ts';\nimport heatmapTextureVert from './glsl/heatmap_texture.vertex.glsl.g.ts';\nimport collisionBoxFrag from './glsl/collision_box.fragment.glsl.g.ts';\nimport collisionBoxVert from './glsl/collision_box.vertex.glsl.g.ts';\nimport collisionCircleFrag from './glsl/collision_circle.fragment.glsl.g.ts';\nimport collisionCircleVert from './glsl/collision_circle.vertex.glsl.g.ts';\nimport colorReliefFrag from './glsl/color_relief.fragment.glsl.g.ts';\nimport colorReliefVert from './glsl/color_relief.vertex.glsl.g.ts';\nimport debugFrag from './glsl/debug.fragment.glsl.g.ts';\nimport debugVert from './glsl/debug.vertex.glsl.g.ts';\nimport depthVert from './glsl/depth.vertex.glsl.g.ts';\nimport fillFrag from './glsl/fill.fragment.glsl.g.ts';\nimport fillVert from './glsl/fill.vertex.glsl.g.ts';\nimport fillOutlineFrag from './glsl/fill_outline.fragment.glsl.g.ts';\nimport fillOutlineVert from './glsl/fill_outline.vertex.glsl.g.ts';\nimport fillOutlinePatternFrag from './glsl/fill_outline_pattern.fragment.glsl.g.ts';\nimport fillOutlinePatternVert from './glsl/fill_outline_pattern.vertex.glsl.g.ts';\nimport fillPatternFrag from './glsl/fill_pattern.fragment.glsl.g.ts';\nimport fillPatternVert from './glsl/fill_pattern.vertex.glsl.g.ts';\nimport fillExtrusionFrag from './glsl/fill_extrusion.fragment.glsl.g.ts';\nimport fillExtrusionVert from './glsl/fill_extrusion.vertex.glsl.g.ts';\nimport fillExtrusionPatternFrag from './glsl/fill_extrusion_pattern.fragment.glsl.g.ts';\nimport fillExtrusionPatternVert from './glsl/fill_extrusion_pattern.vertex.glsl.g.ts';\nimport hillshadePrepareFrag from './glsl/hillshade_prepare.fragment.glsl.g.ts';\nimport hillshadePrepareVert from './glsl/hillshade_prepare.vertex.glsl.g.ts';\nimport hillshadeFrag from './glsl/hillshade.fragment.glsl.g.ts';\nimport hillshadeVert from './glsl/hillshade.vertex.glsl.g.ts';\nimport lineFrag from './glsl/line.fragment.glsl.g.ts';\nimport lineVert from './glsl/line.vertex.glsl.g.ts';\nimport lineGradientFrag from './glsl/line_gradient.fragment.glsl.g.ts';\nimport lineGradientVert from './glsl/line_gradient.vertex.glsl.g.ts';\nimport linePatternFrag from './glsl/line_pattern.fragment.glsl.g.ts';\nimport linePatternVert from './glsl/line_pattern.vertex.glsl.g.ts';\nimport lineSDFFrag from './glsl/line_sdf.fragment.glsl.g.ts';\nimport lineSDFVert from './glsl/line_sdf.vertex.glsl.g.ts';\nimport lineGradientSDFFrag from './glsl/line_gradient_sdf.fragment.glsl.g.ts';\nimport lineGradientSDFVert from './glsl/line_gradient_sdf.vertex.glsl.g.ts';\nimport layerOpacityFrag from './glsl/layer_opacity.fragment.glsl.g.ts';\nimport layerOpacityVert from './glsl/layer_opacity.vertex.glsl.g.ts';\nimport rasterFrag from './glsl/raster.fragment.glsl.g.ts';\nimport rasterVert from './glsl/raster.vertex.glsl.g.ts';\nimport symbolIconFrag from './glsl/symbol_icon.fragment.glsl.g.ts';\nimport symbolIconVert from './glsl/symbol_icon.vertex.glsl.g.ts';\nimport symbolSDFFrag from './glsl/symbol_sdf.fragment.glsl.g.ts';\nimport symbolSDFVert from './glsl/symbol_sdf.vertex.glsl.g.ts';\nimport symbolTextAndIconFrag from './glsl/symbol_text_and_icon.fragment.glsl.g.ts';\nimport symbolTextAndIconVert from './glsl/symbol_text_and_icon.vertex.glsl.g.ts';\nimport terrainDepthFrag from './glsl/terrain_depth.fragment.glsl.g.ts';\nimport terrainFrag from './glsl/terrain.fragment.glsl.g.ts';\nimport terrainVert from './glsl/terrain.vertex.glsl.g.ts';\nimport terrainVertDepth from './glsl/terrain_depth.vertex.glsl.g.ts';\nimport terrainHeightFrag from './glsl/terrain_height.fragment.glsl.g.ts';\nimport terrainHeightVert from './glsl/terrain_height.vertex.glsl.g.ts';\nimport projectionMercatorVert from './glsl/_projection_mercator.vertex.glsl.g.ts';\nimport projectionMercatorFrag from './glsl/_projection_mercator.fragment.glsl.g.ts';\nimport projectionGlobeVert from './glsl/_projection_globe.vertex.glsl.g.ts';\nimport projectionGlobeFrag from './glsl/_projection_globe.fragment.glsl.g.ts';\nimport atmosphereFrag from './glsl/atmosphere.fragment.glsl.g.ts';\nimport atmosphereVert from './glsl/atmosphere.vertex.glsl.g.ts';\nimport skyFrag from './glsl/sky.fragment.glsl.g.ts';\nimport skyVert from './glsl/sky.vertex.glsl.g.ts';\n\nexport type PreparedShader = {\n    fragmentSource: string;\n    vertexSource: string;\n    staticAttributes: string[];\n    staticUniforms: string[];\n};\n\nexport const shaders: {\n    prelude: PreparedShader;\n    projectionMercator: PreparedShader;\n    projectionGlobe: PreparedShader;\n    background: PreparedShader;\n    backgroundPattern: PreparedShader;\n    circle: PreparedShader;\n    clippingMask: PreparedShader;\n    heatmap: PreparedShader;\n    heatmapTexture: PreparedShader;\n    collisionBox: PreparedShader;\n    collisionCircle: PreparedShader;\n    colorRelief: PreparedShader;\n    debug: PreparedShader;\n    depth: PreparedShader;\n    fill: PreparedShader;\n    fillOutline: PreparedShader;\n    fillOutlinePattern: PreparedShader;\n    fillPattern: PreparedShader;\n    fillExtrusion: PreparedShader;\n    fillExtrusionPattern: PreparedShader;\n    hillshadePrepare: PreparedShader;\n    hillshade: PreparedShader;\n    line: PreparedShader;\n    lineGradient: PreparedShader;\n    linePattern: PreparedShader;\n    lineSDF: PreparedShader;\n    lineGradientSDF: PreparedShader;\n    layerOpacity: PreparedShader;\n    raster: PreparedShader;\n    symbolIcon: PreparedShader;\n    symbolSDF: PreparedShader;\n    symbolTextAndIcon: PreparedShader;\n    terrain: PreparedShader;\n    terrainDepth: PreparedShader;\n    terrainHeight: PreparedShader;\n    atmosphere: PreparedShader;\n    sky: PreparedShader;\n} = {\n    prelude: prepare(preludeFrag, preludeVert),\n    projectionMercator: prepare(projectionMercatorFrag, projectionMercatorVert),\n    projectionGlobe: prepare(projectionGlobeFrag, projectionGlobeVert),\n    background: prepare(backgroundFrag, backgroundVert),\n    backgroundPattern: prepare(backgroundPatternFrag, backgroundPatternVert),\n    circle: prepare(circleFrag, circleVert),\n    clippingMask: prepare(clippingMaskFrag, clippingMaskVert),\n    heatmap: prepare(heatmapFrag, heatmapVert),\n    heatmapTexture: prepare(heatmapTextureFrag, heatmapTextureVert),\n    collisionBox: prepare(collisionBoxFrag, collisionBoxVert),\n    collisionCircle: prepare(collisionCircleFrag, collisionCircleVert),\n    colorRelief: prepare(colorReliefFrag, colorReliefVert),\n    debug: prepare(debugFrag, debugVert),\n    depth: prepare(clippingMaskFrag, depthVert),\n    fill: prepare(fillFrag, fillVert),\n    fillOutline: prepare(fillOutlineFrag, fillOutlineVert),\n    fillOutlinePattern: prepare(fillOutlinePatternFrag, fillOutlinePatternVert),\n    fillPattern: prepare(fillPatternFrag, fillPatternVert),\n    fillExtrusion: prepare(fillExtrusionFrag, fillExtrusionVert),\n    fillExtrusionPattern: prepare(fillExtrusionPatternFrag, fillExtrusionPatternVert),\n    hillshadePrepare: prepare(hillshadePrepareFrag, hillshadePrepareVert),\n    hillshade: prepare(hillshadeFrag, hillshadeVert),\n    line: prepare(lineFrag, lineVert),\n    lineGradient: prepare(lineGradientFrag, lineGradientVert),\n    linePattern: prepare(linePatternFrag, linePatternVert),\n    lineSDF: prepare(lineSDFFrag, lineSDFVert),\n    lineGradientSDF: prepare(lineGradientSDFFrag, lineGradientSDFVert),\n    layerOpacity: prepare(layerOpacityFrag, layerOpacityVert),\n    raster: prepare(rasterFrag, rasterVert),\n    symbolIcon: prepare(symbolIconFrag, symbolIconVert),\n    symbolSDF: prepare(symbolSDFFrag, symbolSDFVert),\n    symbolTextAndIcon: prepare(symbolTextAndIconFrag, symbolTextAndIconVert),\n    terrain: prepare(terrainFrag, terrainVert),\n    terrainDepth: prepare(terrainDepthFrag, terrainVertDepth),\n    terrainHeight: prepare(terrainHeightFrag, terrainHeightVert),\n    atmosphere: prepare(atmosphereFrag, atmosphereVert),\n    sky: prepare(skyFrag, skyVert),\n};\n\n/** Expand #pragmas to #ifdefs, extract attributes and uniforms */\nfunction prepare(fragmentSource: string, vertexSource: string): PreparedShader {\n    const re = /#pragma maplibre: ([\\w]+) ([\\w]+) ([\\w]+) ([\\w]+)/g;\n\n    const vertexAttributes = vertexSource.match(/in ([\\w]+) ([\\w]+)/g);\n    const fragmentUniforms = fragmentSource.match(/uniform ([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n    const vertexUniforms = vertexSource.match(/uniform ([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n    const shaderUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms;\n\n    const staticLayoutCount = vertexAttributes ? vertexAttributes.length : 0;\n    let locationCounter = staticLayoutCount;\n\n    const fragmentPragmas = {};\n\n    fragmentSource = fragmentSource.replace(re, (match, operation, precision, type, name) => {\n        fragmentPragmas[name] = true;\n        if (operation === 'define') {\n            return `\n#ifndef HAS_UNIFORM_u_${name}\nin ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n        } else /* if (operation === 'initialize') */ {\n            return `\n#ifdef HAS_UNIFORM_u_${name}\n    ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n        }\n    });\n\n    vertexSource = vertexSource.replace(re, (match, operation, precision, type, name) => {\n        const attrType = type === 'float' ? 'vec2' : 'vec4';\n        const unpackType = name.match(/color/) ? 'color' : attrType;\n\n        if (fragmentPragmas[name]) {\n            if (operation === 'define') {\n                const loc = locationCounter++;\n                return `\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nlayout(location = ${loc}) in ${precision} ${attrType} a_${name};\nout ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n            } else /* if (operation === 'initialize') */ {\n                if (unpackType === 'vec4') {\n                    // vec4 attributes are only used for cross-faded properties, and are not packed\n                    return `\n#ifndef HAS_UNIFORM_u_${name}\n    ${name} = a_${name};\n#else\n    ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n                } else {\n                    return `\n#ifndef HAS_UNIFORM_u_${name}\n    ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n    ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n                }\n            }\n        } else {\n            if (operation === 'define') {\n                const loc = locationCounter++;\n                return `\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nlayout(location = ${loc}) in ${precision} ${attrType} a_${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n            } else /* if (operation === 'initialize') */ {\n                if (unpackType === 'vec4') {\n                    // vec4 attributes are only used for cross-faded properties, and are not packed\n                    return `\n#ifndef HAS_UNIFORM_u_${name}\n    ${precision} ${type} ${name} = a_${name};\n#else\n    ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n                } else /* */ {\n                    return `\n#ifndef HAS_UNIFORM_u_${name}\n    ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n    ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n                }\n            }\n        }\n    });\n\n    return {fragmentSource, vertexSource, staticAttributes: vertexAttributes, staticUniforms: shaderUniforms};\n}\n\n", "import {EXTENT} from '../../data/extent.ts';\nimport {type PreparedShader, shaders} from '../../shaders/shaders.ts';\nimport {Mesh} from '../../render/mesh.ts';\nimport {PosArray, TriangleIndexArray} from '../../data/array_types.g.ts';\nimport {SegmentVector} from '../../data/segment.ts';\nimport posAttributes from '../../data/pos_attributes.ts';\nimport {SubdivisionGranularitySetting} from '../../render/subdivision_granularity_settings.ts';\nimport {mercatorWorldCoordinateHelper} from '../mercator_coordinate.ts';\n\nimport type {ProjectionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Context} from '../../webgl/context.ts';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {Projection, TileMeshUsage} from './projection.ts';\nimport type {WorldCoordinateHelper} from '../transform_interface.ts';\n\nexport const MercatorShaderDefine = '#define PROJECTION_MERCATOR';\nexport const MercatorShaderVariantKey = 'mercator';\n\n/**\n * The flat projection. Mercator by default; the factory also builds one for a CRS registered with `addProjection`,\n * since such tiles already sit in their own quad grid and render exactly like mercator tiles do. The projection\n * takes its name from the lng/lat mapping of that grid, which the transform built alongside it runs on too.\n * Every planar projection shares one shader variant.\n */\nexport class MercatorProjection implements Projection {\n    private _cachedMesh: Mesh = null;\n    private readonly _worldCoordinateHelper: WorldCoordinateHelper;\n\n    /**\n     * @param worldCoordinateHelper - the lng/lat mapping of the grid this projection draws; mercator's when omitted\n     */\n    constructor(worldCoordinateHelper: WorldCoordinateHelper = mercatorWorldCoordinateHelper) {\n        this._worldCoordinateHelper = worldCoordinateHelper;\n    }\n\n    get name(): ProjectionSpecification['type'] {\n        return this._worldCoordinateHelper.name;\n    }\n\n    get worldCoordinateHelper(): WorldCoordinateHelper {\n        return this._worldCoordinateHelper;\n    }\n\n    get useSubdivision(): boolean {\n        // Mercator never uses subdivision.\n        return false;\n    }\n\n    get shaderVariantName(): string {\n        return MercatorShaderVariantKey;\n    }\n\n    get shaderDefine(): string {\n        return MercatorShaderDefine;\n    }\n\n    get shaderPreludeCode(): PreparedShader {\n        return shaders.projectionMercator;\n    }\n\n    get vertexShaderPreludeCode(): string {\n        return shaders.projectionMercator.vertexSource;\n    }\n\n    get subdivisionGranularity(): SubdivisionGranularitySetting {\n        return SubdivisionGranularitySetting.noSubdivision;\n    }\n\n    get useGlobeControls(): boolean {\n        return false;\n    }\n\n    get transitionState(): number {\n        return 0;\n    }\n\n    public destroy(): void {\n        // Do nothing.\n    }\n\n    public getMeshFromTileID(context: Context, _tileID: CanonicalTileID, _hasBorder: boolean, _allowPoles: boolean, _usage: TileMeshUsage): Mesh {\n        if (this._cachedMesh) {\n            return this._cachedMesh;\n        }\n\n        // The parameters tileID, hasBorder and allowPoles are all ignored on purpose for mercator meshes.\n\n        const tileExtentArray = new PosArray();\n        tileExtentArray.emplaceBack(0, 0);\n        tileExtentArray.emplaceBack(EXTENT, 0);\n        tileExtentArray.emplaceBack(0, EXTENT);\n        tileExtentArray.emplaceBack(EXTENT, EXTENT);\n        const tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);\n        const tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n        const quadTriangleIndices = new TriangleIndexArray();\n        quadTriangleIndices.emplaceBack(1, 0, 2);\n        quadTriangleIndices.emplaceBack(1, 2, 3);\n        const quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);\n\n        this._cachedMesh = new Mesh(tileExtentBuffer, quadTriangleIndexBuffer, tileExtentSegments);\n        return this._cachedMesh;\n    }\n\n    public recalculate(): void {\n        // Do nothing.\n    }\n\n    public hasTransition(): boolean {\n        return false;\n    }\n}\n", "import {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport Point from '@mapbox/point-geometry';\nimport {clamp, type Complete, type RequireAtLeastOne} from '../util/util.ts';\n\n/**\n * An `EdgeInset` object represents screen space padding applied to the edges of the viewport.\n * This shifts the apparent center or the vanishing point of the map. This is useful for adding floating UI elements\n * on top of the map and having the vanishing point shift as UI elements resize.\n *\n * @group Geography and Geometry\n */\nexport class EdgeInsets {\n    /**\n     * @defaultValue 0\n     */\n    top: number;\n    /**\n     * @defaultValue 0\n     */\n    bottom: number;\n    /**\n     * @defaultValue 0\n     */\n    left: number;\n    /**\n     * @defaultValue 0\n     */\n    right: number;\n\n    constructor(top: number = 0, bottom: number = 0, left: number = 0, right: number = 0) {\n        if (isNaN(top) || top < 0 ||\n            isNaN(bottom) || bottom < 0 ||\n            isNaN(left) || left < 0 ||\n            isNaN(right) || right < 0\n        ) {\n            throw new Error('Invalid value for edge-insets, top, bottom, left and right must all be numbers');\n        }\n\n        this.top = top;\n        this.bottom = bottom;\n        this.left = left;\n        this.right = right;\n    }\n\n    /**\n     * Interpolates the inset in-place.\n     * This maintains the current inset value for any inset not present in `target`.\n     * @param start - interpolation start\n     * @param target - interpolation target\n     * @param t - interpolation step/weight\n     * @returns the insets\n     */\n    interpolate(start: PaddingOptions | EdgeInsets, target: PaddingOptions, t: number): this {\n        if (target.top != null && start.top != null) this.top = interpolates.number(start.top, target.top, t);\n        if (target.bottom != null && start.bottom != null) this.bottom = interpolates.number(start.bottom, target.bottom, t);\n        if (target.left != null && start.left != null) this.left = interpolates.number(start.left, target.left, t);\n        if (target.right != null && start.right != null) this.right = interpolates.number(start.right, target.right, t);\n\n        return this;\n    }\n\n    /**\n     * Utility method that computes the new apparent center or vanishing point after applying insets.\n     * This is in pixels and with the top left being (0.0) and +y being downwards.\n     *\n     * @param width - the width\n     * @param height - the height\n     * @returns the point\n     */\n    getCenter(width: number, height: number): Point {\n        // Clamp insets so they never overflow width/height and always calculate a valid center\n        const x = clamp((this.left + width - this.right) / 2, 0, width);\n        const y = clamp((this.top + height - this.bottom) / 2, 0, height);\n\n        return new Point(x, y);\n    }\n\n    equals(other: PaddingOptions): boolean {\n        return this.top === other.top &&\n            this.bottom === other.bottom &&\n            this.left === other.left &&\n            this.right === other.right;\n    }\n\n    clone(): EdgeInsets {\n        return new EdgeInsets(this.top, this.bottom, this.left, this.right);\n    }\n\n    /**\n     * Returns the current state as json, useful when you want to have a\n     * read-only representation of the inset.\n     *\n     * @returns state as json\n     */\n    toJSON(): Complete<PaddingOptions> {\n        return {\n            top: this.top,\n            bottom: this.bottom,\n            left: this.left,\n            right: this.right\n        };\n    }\n}\n\n/**\n * 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\n * non-negative integers.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n *   padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * ```\n *\n * @example\n * ```ts\n * let bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n *   padding: 20\n * });\n * ```\n * @see [Fit to the bounds of a LineString](https://maplibre.org/maplibre-gl-js/docs/examples/zoomto-linestring/)\n * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/)\n */\nexport type PaddingOptions = RequireAtLeastOne<{\n    /**\n     * Padding in pixels from the top of the map canvas.\n     */\n    top: number;\n    /**\n     * Padding in pixels from the bottom of the map canvas.\n     */\n    bottom: number;\n    /**\n     * Padding in pixels from the left of the map canvas.\n     */\n    right: number;\n    /**\n     * Padding in pixels from the right of the map canvas.\n     */\n    left: number;\n}>;\n", "import Point from '@mapbox/point-geometry';\nimport {LngLat} from './lng_lat.ts';\nimport {EdgeInsets} from './edge_insets.ts';\nimport {MAX_VALID_LATITUDE, radiansToDegrees} from '../util/util.ts';\n\nimport type {mat2, mat4} from 'gl-matrix';\nimport type {TransformOptions} from './transform_helper.ts';\nimport type {NearFarZ} from './transform_interface.ts';\n\n/**\n * @internal\n * The camera of a transform, which is its position, its size and limits, and the values that follow from them\n * in every projection. It is plain data. {@link TransformHelper} is the only one to change it, and the projection\n * classes read it.\n */\nexport type CameraState = {\n    readonly tileSize: number;\n    width: number;\n    height: number;\n    center: LngLat;\n    /**\n     * Elevation at the center, in meters above sea level.\n     */\n    elevation: number;\n    zoom: number;\n    bearingInRadians: number;\n    pitchInRadians: number;\n    rollInRadians: number;\n    /**\n     * Vertical field of view in radians.\n     */\n    fovInRadians: number;\n    edgeInsets: EdgeInsets;\n    minZoom: number;\n    maxZoom: number;\n    minPitch: number;\n    maxPitch: number;\n    lngRange: [number, number];\n    latRange: [number, number];\n    renderWorldCopies: boolean;\n    minElevationForCurrentTile: number;\n    /**\n     * The depth range to use instead of the one each projection computes, or null.\n     */\n    nearFarZOverride: NearFarZ | null;\n\n    // Derived the same way in every projection\n    /**\n     * The integer zoom level for tiles.\n     */\n    tileZoom: number;\n    /**\n     * Computed based on zoom.\n     */\n    scale: number;\n    pixelsPerMeter: number;\n    cameraToCenterDistance: number;\n    rotationMatrix: mat2;\n    pixelsToGLUnits: [number, number];\n    pixelsToClipSpaceMatrix: mat4;\n    clipSpaceToPixelsMatrix: mat4;\n};\n\n/**\n * @internal\n * The camera state of a new transform, which has no size yet and no bounds. The matrices and the values computed\n * with them start out `undefined` until the transform computes them.\n */\nexport function createCameraState(options?: TransformOptions): CameraState {\n    return {\n        tileSize: 512,\n        width: 0,\n        height: 0,\n        center: new LngLat(0, 0),\n        elevation: 0,\n        zoom: 0,\n        bearingInRadians: 0,\n        pitchInRadians: 0,\n        rollInRadians: 0,\n        fovInRadians: 0.6435011087932844,\n        edgeInsets: new EdgeInsets(),\n        minZoom: options?.minZoom || 0,\n        maxZoom: options?.maxZoom || 22,\n        minPitch: (options?.minPitch === undefined || options?.minPitch === null) ? 0 : options?.minPitch,\n        maxPitch: (options?.maxPitch === undefined || options?.maxPitch === null) ? 60 : options?.maxPitch,\n        lngRange: null,\n        latRange: [-MAX_VALID_LATITUDE, MAX_VALID_LATITUDE],\n        renderWorldCopies: options?.renderWorldCopies === undefined ? true : !!options?.renderWorldCopies,\n        minElevationForCurrentTile: 0,\n        nearFarZOverride: null,\n        tileZoom: 0,\n        scale: 1,\n        pixelsPerMeter: undefined,\n        cameraToCenterDistance: undefined,\n        rotationMatrix: undefined,\n        pixelsToGLUnits: undefined,\n        pixelsToClipSpaceMatrix: undefined,\n        clipSpaceToPixelsMatrix: undefined,\n    };\n}\n\n/**\n * @internal\n * The center of the screen in pixels with the top-left corner being (0,0) and +y axis pointing downwards.\n * This accounts for padding.\n */\nexport function getCenterPoint(cameraState: Readonly<CameraState>): Point {\n    return cameraState.edgeInsets.getCenter(cameraState.width, cameraState.height);\n}\n\n/**\n * @internal\n * How far the padding moves the center point away from the middle of the screen, in pixels.\n */\nexport function getCenterOffset(cameraState: Readonly<CameraState>): Point {\n    return getCenterPoint(cameraState)._sub(new Point(cameraState.width, cameraState.height)._div(2));\n}\n\n/**\n * @internal\n * The size of the world in pixels at the zoom.\n */\nexport function getWorldSize(cameraState: Readonly<CameraState>): number {\n    return cameraState.tileSize * cameraState.scale;\n}\n\n/**\n * @internal\n * The bearing in degrees.\n */\nexport function getBearing(cameraState: Readonly<CameraState>): number {\n    return cameraState.bearingInRadians / Math.PI * 180;\n}\n\n/**\n * @internal\n * The pitch in degrees.\n */\nexport function getPitch(cameraState: Readonly<CameraState>): number {\n    return cameraState.pitchInRadians / Math.PI * 180;\n}\n\n/**\n * @internal\n * The roll in degrees.\n */\nexport function getRoll(cameraState: Readonly<CameraState>): number {\n    return cameraState.rollInRadians / Math.PI * 180;\n}\n\n/**\n * @internal\n * The vertical field of view in degrees.\n */\nexport function getFov(cameraState: Readonly<CameraState>): number {\n    return radiansToDegrees(cameraState.fovInRadians);\n}\n", "import {LngLat, type LngLatLike} from './lng_lat.ts';\nimport {LngLatBounds} from './lng_lat_bounds.ts';\nimport Point from '@mapbox/point-geometry';\nimport {wrap, clamp, degreesToRadians, zoomScale, MAX_VALID_LATITUDE, scaleZoom, warnOnce} from '../util/util.ts';\nimport {mat4, mat2} from 'gl-matrix';\nimport {EdgeInsets} from './edge_insets.ts';\nimport {MercatorCoordinate, mercatorWorldCoordinateHelper} from './mercator_coordinate.ts';\nimport {cameraDirectionFromPitchBearing, maxMercatorHorizonAngle} from './projection/mercator_utils.ts';\nimport {Bounds} from './bounds.ts';\nimport {createCameraState, getBearing, getCenterPoint, getFov, getPitch, getRoll, getWorldSize, type CameraState} from './camera_state.ts';\n\nimport type {WorldCoordinateHelper} from './transform_interface.ts';\nimport type {PaddingOptions} from './edge_insets.ts';\nimport type {IReadonlyTransform, ITransformGetters, NearFarZ, TransformConstrainFunction} from './transform_interface.ts';\n/**\n * If a path crossing the antimeridian would be shorter, extend the final coordinate so that\n * interpolating between the two endpoints will cross it. A world that does not wrap has no antimeridian to cross.\n * @param center - The LngLat object of the desired center. This object will be mutated.\n */\nexport function normalizeCenter(tr: IReadonlyTransform, center: LngLat): void {\n    if (!tr.renderWorldCopies || !tr.worldCoordinateHelper.wraps || tr.lngRange) return;\n    const delta = center.lng - tr.center.lng;\n    center.lng +=\n        delta > 180 ? -360 :\n            delta < -180 ? 360 : 0;\n}\n\nexport type UnwrappedTileIDType = {\n    /**\n     * Tile wrap: 0 for the \"main\" world,\n     * negative values for worlds left of the main,\n     * positive values for worlds right of the main.\n     */\n    wrap?: number;\n    canonical: {\n        /**\n         * Tile X coordinate, in range 0..(z^2)-1\n         */\n        x: number;\n        /**\n         * Tile Y coordinate, in range 0..(z^2)-1\n         */\n        y: number;\n        /**\n         * Tile zoom level.\n         */\n        z: number;\n    };\n};\n\nexport type TransformHelperCallbacks = {\n    /**\n     * The transform's default getter of center lngLat and zoom to ensure that\n     * 1) everything beyond the bounds is excluded\n     * 2) a given lngLat is as near the center as possible\n     * Bounds are those set by maxBounds or North & South \"Poles\" and, if only 1 globe is displayed, antimeridian.\n     */\n    defaultConstrain: TransformConstrainFunction;\n\n    /**\n     * Updates the underlying transform's internal matrices.\n     */\n    calcMatrices: () => void;\n};\n\nexport type TransformOptions = {\n    /**\n     * The minimum zoom level of the map. Users cannot zoom out beyond this level. (0–24)\n     * @defaultValue 0\n     */\n    minZoom?: number;\n    /**\n     * The maximum zoom level of the map. Users cannot zoom in beyond this level. (0–24)\n     * @defaultValue 22\n     */\n    maxZoom?: number;\n    /**\n     * The minimum pitch of the map.\n     */\n    minPitch?: number;\n    /**\n     * The maximum pitch of the map.\n     */\n    maxPitch?: number;\n    /**\n     * Whether to render multiple copies of the world side by side in the map.\n     */\n    renderWorldCopies?: boolean;\n    /**\n     * An override of the transform's default constraining function for respecting its longitude and latitude bounds.\n     */\n    constrainOverride?: TransformConstrainFunction | null;\n    /**\n     * The camera's lng/lat to world coordinate mapping, fixed for the transform's lifetime. Defaults to mercator.\n     */\n    worldCoordinateHelper?: WorldCoordinateHelper;\n};\n\nfunction getTileZoom(zoom: number): number {\n    return Math.max(0, Math.floor(zoom));\n}\n\n/** The most passes {@link TransformHelper._centerAlongView} takes to agree on the mercator scale at the center it finds. */\nconst MAX_CENTER_PASSES = 10;\n\n/**\n * @internal\n * This class stores all values that define a transform's state,\n * such as center, zoom, minZoom, etc.\n * This can be used as a helper for implementing the ITransform interface.\n */\nexport class TransformHelper implements ITransformGetters {\n    private _callbacks: TransformHelperCallbacks;\n\n    private readonly _cameraState: CameraState;\n    /**\n     * Whether the camera was never deliberately positioned, in which case a loading style may apply its own camera.\n     * Cleared by the setters that move the camera, but not by ones that only snap it into a valid range.\n     */\n    _unmodified: boolean;\n\n    _constraining: boolean;\n\n    _constrainOverride: TransformConstrainFunction;\n\n    private readonly _worldCoordinateHelper: WorldCoordinateHelper;\n\n    constructor(callbacks: TransformHelperCallbacks, options?: TransformOptions) {\n        this._callbacks = callbacks;\n        this._cameraState = createCameraState(options);\n        this._worldCoordinateHelper = options?.worldCoordinateHelper ?? mercatorWorldCoordinateHelper;\n\n        this._constrainOverride = options?.constrainOverride ?? null;\n\n        this._unmodified = true;\n    }\n\n    public apply(thatI: ITransformGetters, constrain: boolean): void {\n        this._constrainOverride = thatI.constrainOverride;\n        this._cameraState.latRange = thatI.latRange;\n        this._cameraState.lngRange = thatI.lngRange;\n        this._cameraState.width = thatI.width;\n        this._cameraState.height = thatI.height;\n        this._cameraState.center = thatI.center;\n        this._cameraState.elevation = thatI.elevation;\n        this._cameraState.minElevationForCurrentTile = thatI.minElevationForCurrentTile;\n        this._cameraState.zoom = thatI.zoom;\n        this._cameraState.tileZoom = getTileZoom(this._cameraState.zoom);\n        this._cameraState.scale = zoomScale(this._cameraState.zoom);\n        this._cameraState.bearingInRadians = thatI.bearingInRadians;\n        this._cameraState.fovInRadians = thatI.fovInRadians;\n        this._cameraState.pitchInRadians = thatI.pitchInRadians;\n        this._cameraState.rollInRadians = thatI.rollInRadians;\n        this._unmodified = thatI.unmodified;\n        this._cameraState.edgeInsets = new EdgeInsets(thatI.padding.top, thatI.padding.bottom, thatI.padding.left, thatI.padding.right);\n        this._cameraState.minZoom = thatI.minZoom;\n        this._cameraState.maxZoom = thatI.maxZoom;\n        this._cameraState.minPitch = thatI.minPitch;\n        this._cameraState.maxPitch = thatI.maxPitch;\n        this._cameraState.renderWorldCopies = thatI.renderWorldCopies;\n        this._cameraState.cameraToCenterDistance = thatI.cameraToCenterDistance;\n        this._cameraState.nearFarZOverride = thatI.nearFarZOverride;\n        if (constrain) {\n            this.constrainInternal();\n        }\n        this._calcMatrices();\n    }\n\n    get pixelsToClipSpaceMatrix(): mat4 { return this._cameraState.pixelsToClipSpaceMatrix; }\n    get clipSpaceToPixelsMatrix(): mat4 { return this._cameraState.clipSpaceToPixelsMatrix; }\n\n    get minElevationForCurrentTile(): number { return this._cameraState.minElevationForCurrentTile; }\n    setMinElevationForCurrentTile(ele: number): void {\n        if (ele === this._cameraState.minElevationForCurrentTile) return;\n        this._cameraState.minElevationForCurrentTile = ele;\n        this._calcMatrices();\n    }\n\n    get tileSize(): number { return this._cameraState.tileSize; }\n    get tileZoom(): number { return this._cameraState.tileZoom; }\n    get scale(): number { return this._cameraState.scale; }\n\n    /**\n     * Gets the transform's width in pixels. Use {@link resize} to set the transform's size.\n     */\n    get width(): number { return this._cameraState.width; }\n\n    /**\n     * Gets the transform's height in pixels. Use {@link resize} to set the transform's size.\n     */\n    get height(): number { return this._cameraState.height; }\n\n    /**\n     * Gets the transform's bearing in radians.\n     */\n    get bearingInRadians(): number { return this._cameraState.bearingInRadians; }\n\n    get lngRange(): [number, number] { return this._cameraState.lngRange; }\n    get latRange(): [number, number] { return this._cameraState.latRange; }\n    get worldCoordinateHelper(): WorldCoordinateHelper { return this._worldCoordinateHelper; }\n\n    get pixelsToGLUnits(): [number, number] { return this._cameraState.pixelsToGLUnits; }\n\n    get minZoom(): number { return this._cameraState.minZoom; }\n    setMinZoom(zoom: number): void {\n        if (this._cameraState.minZoom === zoom) return;\n        this._cameraState.minZoom = zoom;\n        const unmodified = this._unmodified;\n        this.setZoom(this.applyConstrain(this._cameraState.center, this.zoom).zoom);\n        this._unmodified = unmodified;\n    }\n\n    get maxZoom(): number { return this._cameraState.maxZoom; }\n    setMaxZoom(zoom: number): void {\n        if (this._cameraState.maxZoom === zoom) return;\n        this._cameraState.maxZoom = zoom;\n        const unmodified = this._unmodified;\n        this.setZoom(this.applyConstrain(this._cameraState.center, this.zoom).zoom);\n        this._unmodified = unmodified;\n    }\n\n    get minPitch(): number { return this._cameraState.minPitch; }\n    setMinPitch(pitch: number): void {\n        if (this._cameraState.minPitch === pitch) return;\n        this._cameraState.minPitch = pitch;\n        const unmodified = this._unmodified;\n        this.setPitch(Math.max(this.pitch, pitch));\n        this._unmodified = unmodified;\n    }\n\n    get maxPitch(): number { return this._cameraState.maxPitch; }\n    setMaxPitch(pitch: number): void {\n        if (this._cameraState.maxPitch === pitch) return;\n        this._cameraState.maxPitch = pitch;\n        const unmodified = this._unmodified;\n        this.setPitch(Math.min(this.pitch, pitch));\n        this._unmodified = unmodified;\n    }\n\n    get renderWorldCopies(): boolean { return this._cameraState.renderWorldCopies; }\n    setRenderWorldCopies(renderWorldCopies: boolean): void {\n        if (renderWorldCopies === undefined) {\n            renderWorldCopies = true;\n        } else if (renderWorldCopies === null) {\n            renderWorldCopies = false;\n        }\n\n        if (renderWorldCopies && !this._worldCoordinateHelper.wraps) {\n            warnOnce('renderWorldCopies has no effect in a projection whose world does not wrap.');\n        }\n        this._cameraState.renderWorldCopies = renderWorldCopies;\n    }\n\n    get constrainOverride(): TransformConstrainFunction { return this._constrainOverride; }\n    setConstrainOverride(constrain?: TransformConstrainFunction | null): void {\n        if (constrain === undefined) constrain = null;\n        if (this._constrainOverride === constrain) return;\n        this._constrainOverride = constrain;\n        this.constrainInternal();\n        this._calcMatrices();\n    }\n\n    get worldSize(): number {\n        return getWorldSize(this._cameraState);\n    }\n\n    /**\n     * Gets the transform's dimensions packed into a Point object.\n     */\n    get size(): Point {\n        return new Point(this._cameraState.width, this._cameraState.height);\n    }\n\n    get bearing(): number {\n        return getBearing(this._cameraState);\n    }\n    setBearing(bearing: number): void {\n        const b = wrap(bearing, -180, 180) * Math.PI / 180;\n        if (this._cameraState.bearingInRadians === b) return;\n        this._unmodified = false;\n        this._cameraState.bearingInRadians = b;\n        this._calcMatrices();\n\n        // 2x2 matrix for rotating points\n        this._cameraState.rotationMatrix = mat2.create();\n        mat2.rotate(this._cameraState.rotationMatrix, this._cameraState.rotationMatrix, -this._cameraState.bearingInRadians);\n    }\n\n    get rotationMatrix(): mat2 { return this._cameraState.rotationMatrix; }\n\n    get pitchInRadians(): number {\n        return this._cameraState.pitchInRadians;\n    }\n    get pitch(): number {\n        return getPitch(this._cameraState);\n    }\n    setPitch(pitch: number): void {\n        const p = clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI;\n        if (this._cameraState.pitchInRadians === p) return;\n        this._unmodified = false;\n        this._cameraState.pitchInRadians = p;\n        this._calcMatrices();\n    }\n\n    get rollInRadians(): number {\n        return this._cameraState.rollInRadians;\n    }\n    get roll(): number {\n        return getRoll(this._cameraState);\n    }\n    setRoll(roll: number): void {\n        const r = roll / 180 * Math.PI;\n        if (this._cameraState.rollInRadians === r) return;\n        this._unmodified = false;\n        this._cameraState.rollInRadians = r;\n        this._calcMatrices();\n    }\n\n    get fovInRadians(): number {\n        return this._cameraState.fovInRadians;\n    }\n    get fov(): number {\n        return getFov(this._cameraState);\n    }\n    setFov(fov: number): void {\n        fov = clamp(fov, 0.1, 150);\n        if (this.fov === fov) return;\n        this._unmodified = false;\n        this._cameraState.fovInRadians = degreesToRadians(fov);\n        this._calcMatrices();\n    }\n\n    get zoom(): number { return this._cameraState.zoom; }\n    setZoom(zoom: number): void {\n        const constrainedZoom = this.applyConstrain(this._cameraState.center, zoom).zoom;\n        if (this._cameraState.zoom === constrainedZoom) return;\n        this._unmodified = false;\n        this._cameraState.zoom = constrainedZoom;\n        this._cameraState.tileZoom = Math.max(0, Math.floor(constrainedZoom));\n        this._cameraState.scale = zoomScale(constrainedZoom);\n        this.constrainInternal();\n        this._calcMatrices();\n    }\n\n    get center(): LngLat { return this._cameraState.center; }\n    setCenter(center: LngLat): void {\n        if (center.lat === this._cameraState.center.lat && center.lng === this._cameraState.center.lng) return;\n        this._unmodified = false;\n        this._cameraState.center = center;\n        this.constrainInternal();\n        this._calcMatrices();\n    }\n\n    /**\n     * Moves the center and the zoom in one write, to a camera that is already constrained.\n     */\n    setCenterAndZoom(center: LngLat, zoom: number): void {\n        const state = this._cameraState;\n        this._unmodified = false;\n        state.center = center;\n        state.zoom = zoom;\n        state.tileZoom = Math.max(0, Math.floor(zoom));\n        state.scale = zoomScale(zoom);\n        this._calcMatrices();\n    }\n\n    /**\n     * Elevation at current center point, meters above sea level\n     */\n    get elevation(): number { return this._cameraState.elevation; }\n    setElevation(elevation: number): void {\n        if (elevation === this._cameraState.elevation) return;\n        this._cameraState.elevation = elevation;\n        this.constrainInternal();\n        this._calcMatrices();\n    }\n\n    get padding(): PaddingOptions { return this._cameraState.edgeInsets.toJSON(); }\n    setPadding(padding: PaddingOptions): void {\n        if (this._cameraState.edgeInsets.equals(padding)) return;\n        this._unmodified = false;\n        // Update edge-insets in-place\n        this._cameraState.edgeInsets.interpolate(this._cameraState.edgeInsets, padding, 1);\n        this.constrainInternal();\n        this._calcMatrices();\n    }\n\n    /**\n     * The center of the screen in pixels with the top-left corner being (0,0)\n     * and +y axis pointing downwards. This accounts for padding.\n     */\n    get centerPoint(): Point {\n        return getCenterPoint(this._cameraState);\n    }\n\n    /**\n     * @internal\n     */\n    get pixelsPerMeter(): number { return this._cameraState.pixelsPerMeter; }\n\n    get unmodified(): boolean { return this._unmodified; }\n\n    /**\n     * The camera state, which only the helper changes and the projection classes read their camera values from.\n     */\n    get cameraState(): Readonly<CameraState> { return this._cameraState; }\n\n    get cameraToCenterDistance(): number { return this._cameraState.cameraToCenterDistance; }\n\n    get nearFarZOverride(): NearFarZ | null { return this._cameraState.nearFarZOverride; }\n    get autoCalculateNearFarZ(): boolean { return this._cameraState.nearFarZOverride === null; }\n    overrideNearFarZ(nearZ: number, farZ: number): void {\n        this._cameraState.nearFarZOverride = {nearZ, farZ};\n        this._calcMatrices();\n    }\n    clearNearFarZOverride(): void {\n        this._cameraState.nearFarZOverride = null;\n        this._calcMatrices();\n    }\n\n    /**\n     * Returns if the padding params match\n     *\n     * @param padding - the padding to check against\n     * @returns true if they are equal, false otherwise\n     */\n    isPaddingEqual(padding: PaddingOptions): boolean {\n        return this._cameraState.edgeInsets.equals(padding);\n    }\n\n    /**\n     * Helper method to update edge-insets in place\n     *\n     * @param start - the starting padding\n     * @param target - the target padding\n     * @param t - the step/weight\n     */\n    interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number): void {\n        this._unmodified = false;\n        this._cameraState.edgeInsets.interpolate(start, target, t);\n        this.constrainInternal();\n        this._calcMatrices();\n    }\n\n    resize(width: number, height: number, constrain: boolean = true): void {\n        this._cameraState.width = width;\n        this._cameraState.height = height;\n        if (constrain) this.constrainInternal();\n        this._calcMatrices();\n    }\n\n    /**\n     * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.\n     * @returns max bounds\n     */\n    getMaxBounds(): LngLatBounds | null {\n        if (!this._cameraState.lngRange &&\n            this._cameraState.latRange[0] === -MAX_VALID_LATITUDE &&\n            this._cameraState.latRange[1] === MAX_VALID_LATITUDE) return null;\n\n        return new LngLatBounds([\n            this._cameraState.lngRange?.[0] ?? -Infinity,\n            this._cameraState.latRange[0],\n            this._cameraState.lngRange?.[1] ?? Infinity,\n            this._cameraState.latRange[1]\n        ]);\n    }\n\n    /**\n     * Sets or clears the map's geographical constraints.\n     * @param bounds - A {@link LngLatBounds} object describing the new geographic boundaries of the map.\n     */\n    setMaxBounds(bounds?: LngLatBounds | null): void {\n        if (!bounds) {\n            this._cameraState.lngRange = null;\n            this._cameraState.latRange = [-MAX_VALID_LATITUDE, MAX_VALID_LATITUDE];\n            return;\n        }\n\n        const west = bounds.getWest();\n        const east = bounds.getEast();\n        const south = bounds.getSouth();\n        const north = bounds.getNorth();\n\n        const longitudeUnconstrained = west === -Infinity && east === Infinity;\n        if ((!Number.isFinite(west) || !Number.isFinite(east)) && !longitudeUnconstrained) {\n            throw new Error('Longitude maxBounds values must either be finite or span from -Infinity to Infinity');\n        }\n\n        this._cameraState.lngRange = longitudeUnconstrained ? null : [west, east];\n        this._cameraState.latRange = [\n            clamp(south, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE),\n            clamp(north, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE)\n        ];\n        this.constrainInternal();\n    }\n\n    /**\n     * When the map is pitched, some of the 3D features that intersect a query will not intersect\n     * the query at the surface of the earth. Instead the feature may be closer and only intersect\n     * the query because it extrudes into the air.\n     * @param queryGeometry - For point queries, the line from the query point to the \"camera point\",\n     * for other geometries, the envelope of the query geometry and the \"camera point\"\n     * @returns a geometry that includes all of the original query as well as all possible ares of the\n     * screen where the *base* of a visible extrusion could be.\n     *\n     */\n    getCameraQueryGeometry(queryGeometry: Point[]): Point[] {\n        const cameraPoint = this.getCameraPoint();\n        if (queryGeometry.length === 1) {\n            return [queryGeometry[0], cameraPoint];\n        } else {\n            const {minX, minY, maxX, maxY} = Bounds.fromPoints(queryGeometry).extend(cameraPoint);\n            return [\n                new Point(minX, minY),\n                new Point(maxX, minY),\n                new Point(maxX, maxY),\n                new Point(minX, maxY),\n                new Point(minX, minY)\n            ];\n        }\n    }\n\n    applyConstrain: TransformConstrainFunction = (lngLat, zoom) => {\n        if (this._constrainOverride !== null) {\n            return this._constrainOverride(lngLat, zoom);\n        } else {\n            return this._callbacks.defaultConstrain(lngLat, zoom);\n        }\n    };\n\n    /**\n     * Where the constrain puts a camera moved to `center` and `zoom`. A transform without a size is not constrained,\n     * so it keeps the two as they are.\n     */\n    getConstrainedCamera(center: LngLat, zoom: number): {center: LngLat; zoom: number} {\n        if (!this._cameraState.width || !this._cameraState.height) return {center, zoom};\n        const constrained = this.applyConstrain(center, zoom);\n        return {center: constrained.center, zoom: this.applyConstrain(constrained.center, constrained.zoom).zoom};\n    }\n\n    /**\n     * @internal\n     * Snaps the transform's center, zoom, etc. into the valid range.\n     */\n    private constrainInternal(): void {\n        if (!this.center || !this._cameraState.width || !this._cameraState.height || this._constraining) return;\n        this._constraining = true;\n        const unmodified = this._unmodified;\n        const {center, zoom} = this.applyConstrain(this.center, this.zoom);\n        this.setCenter(center);\n        this.setZoom(zoom);\n        this._unmodified = unmodified;\n        this._constraining = false;\n    }\n\n    /**\n     * This function is called every time one of the transform's defining properties (center, pitch, etc.) changes.\n     * This function should update the transform's internal data, such as matrices.\n     * Any derived `_calcMatrices` function should also call the base function first. The base function only depends on the `_width` and `_height` fields.\n     * While either dimension is zero there is no view to build, so the derived function is not called at all.\n     */\n    private _calcMatrices(): void {\n        this._cameraState.pixelsPerMeter = this.worldCoordinateHelper.worldZFromAltitude(1, this.center) * this.worldSize;\n        if (!this._cameraState.width || !this._cameraState.height) {\n            return;\n        }\n        this._cameraState.pixelsToGLUnits = [2 / this._cameraState.width, -2 / this._cameraState.height];\n\n        let m = mat4.identity(new Float64Array(16));\n        mat4.scale(m, m, [this._cameraState.width / 2, -this._cameraState.height / 2, 1]);\n        mat4.translate(m, m, [1, -1, 0]);\n        this._cameraState.clipSpaceToPixelsMatrix = m;\n\n        m = mat4.identity(new Float64Array(16));\n        mat4.scale(m, m, [1, -1, 1]);\n        mat4.translate(m, m, [-1, -1, 0]);\n        mat4.scale(m, m, [2 / this._cameraState.width, 2 / this._cameraState.height, 1]);\n        this._cameraState.pixelsToClipSpaceMatrix = m;\n        const halfFov = this.fovInRadians / 2;\n        this._cameraState.cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this._cameraState.height;\n        this._callbacks.calcMatrices();\n    }\n\n    calculateCenterFromCameraLngLatAlt(lnglat: LngLatLike, alt: number, bearing?: number, pitch?: number): {center: LngLat; elevation: number; zoom: number} {\n        const cameraBearing = bearing !== undefined ? bearing : this.bearing;\n        const cameraPitch = pitch = pitch !== undefined ? pitch : this.pitch;\n\n        const {distanceToCenter, clampedElevation} = this._distanceToCenterFromAltElevationPitch(alt, this.elevation, cameraPitch);\n        const {x, y} = cameraDirectionFromPitchBearing(cameraPitch, cameraBearing);\n        \n        const worldCoordinateHelper = this.worldCoordinateHelper;\n        const cameraLngLat = LngLat.convert(lnglat);\n        const camMercator = worldCoordinateHelper.worldFromLngLat(cameraLngLat.lng, cameraLngLat.lat, alt);\n        const {centerMercator, dMercator} = this._centerAlongView(camMercator, x, y, distanceToCenter, worldCoordinateHelper.metersPerWorldUnit(camMercator.x, camMercator.y));\n        const center = worldCoordinateHelper.lngLatFromWorld(centerMercator.x, centerMercator.y);\n        const zoom = scaleZoom(this.height / 2 / Math.tan(this.fovInRadians / 2) / dMercator / this.tileSize);\n        return {center, elevation: clampedElevation, zoom};\n    }\n\n    /**\n     * Moves the center along the view to the given elevation with the camera where it is, and sets the zoom to match.\n     * The center is found along the view from the camera's position, which is kept, by {@link _centerAlongView},\n     * starting from the old center's mercator scale. The matrices are recomputed even where `setZoom` leaves the zoom\n     * as it was, as at a zoom bound, since the center and its elevation have moved.\n     * @param elevation - the elevation in meters for the center\n     */\n    recalculateZoomAndCenter(elevation: number): void {\n        if (this.elevation - elevation === 0) return;\n\n        const cameraPitch = this.pitch;\n        const cameraBearing = this.bearing;\n        const {x, y, z} = cameraDirectionFromPitchBearing(cameraPitch, cameraBearing);\n        const worldCoordinateHelper = this.worldCoordinateHelper;\n        const originalCenterMercator = worldCoordinateHelper.worldFromLngLat(this.center.lng, this.center.lat, this.elevation);\n        const originalMetersPerMercUnit = 1 / worldCoordinateHelper.worldZFromAltitude(1, this.center);\n        const dCamMercator = this.cameraToCenterDistance / this.worldSize;\n        const camMercator = new MercatorCoordinate(originalCenterMercator.x - x * dCamMercator, originalCenterMercator.y - y * dCamMercator, originalCenterMercator.z + z * dCamMercator);\n\n        const {distanceToCenter, clampedElevation} = this._distanceToCenterFromAltElevationPitch(camMercator.z * originalMetersPerMercUnit, elevation, cameraPitch);\n        const {centerMercator, dMercator} = this._centerAlongView(camMercator, x, y, distanceToCenter, originalMetersPerMercUnit);\n        const center = worldCoordinateHelper.lngLatFromWorld(centerMercator.x, centerMercator.y);\n        const zoom = scaleZoom(this.cameraToCenterDistance / dMercator / this.tileSize);\n\n        // Update matrices\n        this._cameraState.elevation = clampedElevation;\n        this._cameraState.center = center;\n        const previousZoom = this._cameraState.zoom;\n        this.setZoom(zoom);\n        if (this._cameraState.zoom === previousZoom) {\n            this._unmodified = false;\n            this.constrainInternal();\n            this._calcMatrices();\n        }\n    }\n\n    /**\n     * The center `distanceToCenter` meters from the camera along the view, in world units, and that distance in\n     * world units. The mercator scale changes with latitude and the center's latitude is unknown until the center\n     * is: each pass places the center with the scale at the center the last pass found, from `metersPerMercUnit`,\n     * and stops once two passes agree. Zoomed far out at a high latitude the scale changes faster along the view than\n     * a pass follows; a pass that would move the center further than the last one did ends the search at the last\n     * stable center instead of oscillating (#6775).\n     * @param cameraMercator - the camera's position\n     * @param x - the view direction's x component, see {@link cameraDirectionFromPitchBearing}\n     * @param y - the view direction's y component\n     * @param distanceToCenter - the camera's distance to the center in meters\n     * @param metersPerMercUnit - the mercator scale to start from\n     */\n    private _centerAlongView(cameraMercator: MercatorCoordinate, x: number, y: number, distanceToCenter: number, metersPerMercUnit: number): {centerMercator: MercatorCoordinate; dMercator: number} {\n        let dMercator = distanceToCenter / metersPerMercUnit;\n        let centerMercator = new MercatorCoordinate(cameraMercator.x + x * dMercator, cameraMercator.y + y * dMercator);\n        let step = Infinity;\n        for (let pass = 1; pass < MAX_CENTER_PASSES; pass++) {\n            const centerMetersPerMercUnit = this.worldCoordinateHelper.metersPerWorldUnit(centerMercator.x, centerMercator.y);\n            const nextStep = Math.abs(centerMetersPerMercUnit - metersPerMercUnit);\n            if (nextStep <= 1e-12 * metersPerMercUnit || nextStep >= step) break;\n            step = nextStep;\n            metersPerMercUnit = centerMetersPerMercUnit;\n            dMercator = distanceToCenter / metersPerMercUnit;\n            centerMercator = new MercatorCoordinate(cameraMercator.x + x * dMercator, cameraMercator.y + y * dMercator);\n        }\n        return {centerMercator, dMercator};\n    }\n\n    _distanceToCenterFromAltElevationPitch(alt: number, elevation: number, pitch: number): {distanceToCenter: number; clampedElevation: number} {\n        const dzNormalized = -Math.cos(degreesToRadians(pitch));\n        const altitudeAGL = alt - elevation;\n        let distanceToCenter: number;\n        let clampedElevation = elevation;\n        if (dzNormalized * altitudeAGL >= 0.0 || Math.abs(dzNormalized) < Math.cos(degreesToRadians(maxMercatorHorizonAngle))) {\n            distanceToCenter = 10000;\n            clampedElevation = alt + distanceToCenter * dzNormalized;\n        } else {\n            distanceToCenter = -altitudeAGL / dzNormalized;\n        }\n        return {distanceToCenter, clampedElevation};\n    }\n\n    getCameraPoint(): Point {\n        const pitch = this.pitchInRadians;\n        const offset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);\n        return this.centerPoint.add(new Point(offset * Math.sin(this.rollInRadians), offset * Math.cos(this.rollInRadians)));\n    }\n}\n", "import {OverscaledTileID} from '../../tile/tile_id.ts';\nimport {Aabb} from '../../util/primitives/aabb.ts';\nimport {clamp} from '../../util/util.ts';\n\nimport type {LngLat} from '../lng_lat.ts';\nimport type {MercatorCoordinate} from '../mercator_coordinate.ts';\nimport type {IReadonlyTransform} from '../transform_interface.ts';\nimport type {CoveringTilesOptionsInternal} from './covering_tiles.ts';\nimport type {CoveringTilesDetailsProvider} from './covering_tiles_details_provider.ts';\nimport type {IBoundingVolume} from '../../util/primitives/bounding_volume.ts';\n\nexport class MercatorCoveringTilesDetailsProvider implements CoveringTilesDetailsProvider {\n\n    getCenter(transform: IReadonlyTransform): LngLat {\n        return transform.center;\n    }\n\n    distanceToTile2d(pointX: number, pointY: number, _tileID: {x: number; y: number; z: number}, boundingVolume: IBoundingVolume): number {\n        const aabb = boundingVolume as Aabb;\n        const distanceX = aabb.distanceX([pointX, pointY]);\n        const distanceY = aabb.distanceY([pointX, pointY]);\n        return Math.hypot(distanceX, distanceY);\n    }\n\n    /**\n     * Returns the wrap value for a given tile, computed so that tiles will remain loaded when crossing the antimeridian.\n     */\n    getWrap(centerCoord: MercatorCoordinate, tileID: {x:number; y: number; z: number}, parentWrap: number): number {\n        return parentWrap;\n    }\n\n    /**\n     * Returns the AABB of the specified tile.\n     * @param tileID - Tile x, y and z for zoom.\n     */\n    getTileBoundingVolume(tileID: {x: number; y: number; z: number}, wrap: number, elevation: number, options: CoveringTilesOptionsInternal): Aabb {\n        let minElevation = Math.min(0, elevation);\n        let maxElevation = Math.max(0, elevation);\n        if (options?.terrain) {\n            const overscaledTileID = new OverscaledTileID(tileID.z, wrap, tileID.z, tileID.x, tileID.y);\n            const minMax = options.terrain.getMinMaxElevation(overscaledTileID);\n            minElevation = minMax.minElevation ?? minElevation;\n            maxElevation = minMax.maxElevation ?? maxElevation;\n        }\n        const numTiles = 1 << tileID.z;\n        return new Aabb([wrap + tileID.x / numTiles, tileID.y / numTiles, minElevation],\n            [wrap + (tileID.x + 1) / numTiles, (tileID.y + 1) / numTiles, maxElevation]);\n    }\n    \n    allowVariableZoom(transform: IReadonlyTransform, options: CoveringTilesOptionsInternal): boolean {\n        const zfov = transform.fov * (Math.abs(Math.cos(transform.rollInRadians)) * transform.height + Math.abs(Math.sin(transform.rollInRadians)) * transform.width) / transform.height;\n        const maxConstantZoomPitch = clamp(78.5 - zfov / 2, 0.0, 60.0);\n        return (!!options.terrain || transform.pitch > maxConstantZoomPitch);\n    }\n\n    allowWorldCopies(): boolean {\n        return true;\n    }\n\n    prepareNextFrame(): void { \n        // Do nothing\n    }\n}", "import {EXTENT} from '../data/extent.ts';\nimport {mercatorWorldCoordinateHelper} from '../geo/mercator_coordinate.ts';\n\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\nimport type {LngLat} from '../geo/lng_lat.ts';\nimport type {TerrainTileManager} from '../tile/terrain_tile_manager.ts';\nimport type {WorldCoordinateHelper} from '../geo/transform_interface.ts';\n\nexport type TerrainElevationSampler = (x: number, y: number, extent: number) => number;\n\nconst MAX_BISECTIONS = 40;\nconst HIT_EPSILON_M = 1e-6;\n/**\n * @internal\n * The last fraction of the camera-to-location distance within which a terrain hit does not count for\n * {@link ITransform.isLocationOccluded}, so the terrain the location sits on never hides it.\n */\nexport const TERRAIN_OCCLUSION_MARGIN = 0.01;\n/** Keeps the elevation bracket non-degenerate when the terrain is entirely flat, such as unloaded DEMs. */\nconst BRACKET_PADDING_M = 10;\n/** Tile coordinates run from 0 up to but not including `EXTENT`; a point on the far edge is clamped back into the tile. */\nconst MAX_TILE_COORD = EXTENT * (1 - 1e-12);\n\n/**\n * Offset, in DEM pixels, from a tile coordinate scaled by `dim` to the pixel index `DEMData.sampleBilinear` expects.\n * DEM pixel `i` describes the cell centred at tile coordinate `(i + 0.5) / dim`, the same placement hillshade and\n * color-relief use, so a sample between two cell centres interpolates the pixels on either side of it.\n */\nconst DEM_CELL_CENTER_OFFSET = -0.5;\n\nexport type TerrainSample = {\n    covered: boolean;\n    /** Whether the elevation comes from loaded DEM data rather than the flat surface rendered while it loads. */\n    demLoaded: boolean;\n    elevation: number;\n};\n\nexport type TerrainCoverageIndex = {\n    zooms: number[];\n    samplerPerTile: Map<string, TerrainElevationSampler | null>;\n    minElevation: number;\n    maxElevation: number;\n};\n\nconst NOT_COVERED: TerrainSample = {covered: false, demLoaded: false, elevation: 0};\n\n/**\n * The drawn terrain tiles' DEM data as sampled on the CPU: an index of their elevation samplers, built on first use\n * and kept until {@link reset} (the renderable tile set changed, or the terrain source), in two views: every drawn\n * tile's DEM data, a loaded parent's where the tile's own has not loaded, or only the tiles' own.\n * @param tileManager - the terrain source's tiles, drawn and loaded\n * @param exaggeration - the terrain's exaggeration, which every sampled elevation includes\n * @param getWorldCoordinateHelper - the lng/lat to world mapping of the map's projection, mercator by default\n */\nexport class TerrainCoverage {\n    private _samplerCache = new Map<string, TerrainElevationSampler>();\n    /** undefined means not built yet; null that no terrain tile is renderable. */\n    private _index: TerrainCoverageIndex | null | undefined;\n    private _ownDemIndex: TerrainCoverageIndex | null | undefined;\n\n    constructor(\n        private readonly tileManager: TerrainTileManager,\n        private readonly exaggeration: number,\n        private readonly getWorldCoordinateHelper: () => WorldCoordinateHelper = () => mercatorWorldCoordinateHelper\n    ) {}\n\n    /** Drops the samplers and both indexes. Missing DEM data is never cached, so a later sample can retry. */\n    reset(): void {\n        this._samplerCache.clear();\n        this._index = undefined;\n        this._ownDemIndex = undefined;\n    }\n\n    /**\n     * @param ownDemOnly - whether a tile whose own DEM data has not loaded has none, though a loaded parent's is drawn\n     * in its place\n     * @returns the index, or null when no terrain tile is renderable\n     */\n    getIndex(ownDemOnly: boolean = false): TerrainCoverageIndex | null {\n        if (ownDemOnly) {\n            if (this._ownDemIndex === undefined) this._ownDemIndex = this._build(true);\n            return this._ownDemIndex;\n        }\n        if (this._index === undefined) this._index = this._build(false);\n        return this._index;\n    }\n\n    /**\n     * The elevation the drawn tiles' DEM data gives at a location, in respect of exaggeration, or undefined where no\n     * drawn tile has that data.\n     */\n    sample(lnglat: LngLat, ownDemOnly: boolean = false): number | undefined {\n        const index = this.getIndex(ownDemOnly);\n        if (!index) return undefined;\n        const worldCoordinateHelper = this.getWorldCoordinateHelper();\n        const {x, y} = worldCoordinateHelper.worldFromLngLat(lnglat.lng, lnglat.lat);\n        const sample = sampleAt(index, this.exaggeration, x, y, worldCoordinateHelper.wraps);\n        return sample.demLoaded ? sample.elevation : undefined;\n    }\n\n    /** The cached sampler of a tile's raw DEM elevation, or null when its DEM data is not loaded. */\n    getSampler(tileID: OverscaledTileID): TerrainElevationSampler | null {\n        const key = tileID.key;\n        const cachedSampler = this._samplerCache.get(key);\n        if (cachedSampler) return cachedSampler;\n        const sampler = this._createElevationSampler(tileID);\n        if (sampler) this._samplerCache.set(key, sampler);\n        return sampler;\n    }\n\n    /**\n     * A function that samples a tile's raw DEM elevation, without exaggeration, or null when the tile's DEM data is\n     * not loaded. The DEM tile is the tile's own or a loaded parent's, so the tile's coordinates are scaled and offset\n     * into it, as {@link Terrain._getDEMTileMatrix} does for the renderer; the sampler places DEM pixels at cell\n     * centres, matching `get_elevation` in the vertex shader prelude.\n     */\n    private _createElevationSampler(tileID: OverscaledTileID): TerrainElevationSampler | null {\n        const sourceTile = this.tileManager.getSourceTile(tileID, true);\n        const dem = sourceTile?.dem;\n        if (!sourceTile || !dem) return null;\n\n        const dz = tileID.canonical.z - sourceTile.tileID.canonical.z;\n        const tilesPerDemTile = 1 << dz;\n        // Store the vector-tile to DEM-pixel transform once for the hot sampling loop.\n        const demPixelScale = dem.dim / (EXTENT * tilesPerDemTile);\n        const demPixelOffsetX = (tileID.canonical.x - (tileID.canonical.x >> dz << dz)) / tilesPerDemTile * dem.dim + DEM_CELL_CENTER_OFFSET;\n        const demPixelOffsetY = (tileID.canonical.y - (tileID.canonical.y >> dz << dz)) / tilesPerDemTile * dem.dim + DEM_CELL_CENTER_OFFSET;\n        return (x: number, y: number, extent: number): number => {\n            const extentScale = extent === EXTENT ? 1 : EXTENT / extent;\n            return dem.sampleBilinear(\n                x * extentScale * demPixelScale + demPixelOffsetX,\n                y * extentScale * demPixelScale + demPixelOffsetY\n            );\n        };\n    }\n\n    private _build(ownDemOnly: boolean): TerrainCoverageIndex | null {\n        const {tileManager} = this;\n        const zooms: number[] = [];\n        const samplerPerTile = new Map<string, TerrainElevationSampler | null>();\n        let minElevation = 0;\n        let maxElevation = 0;\n\n        for (const tile of tileManager.getRenderableTiles()) {\n            if (!tile) continue;\n            const {canonical, wrap} = tile.tileID;\n            if (!zooms.includes(canonical.z)) zooms.push(canonical.z);\n            const sampler = ownDemOnly && !tileManager.getSourceTile(tile.tileID)?.dem ? null : this.getSampler(tile.tileID);\n            samplerPerTile.set(`${wrap}/${canonical.z}/${canonical.x}/${canonical.y}`, sampler);\n            const dem = tileManager.getSourceTile(tile.tileID, true)?.dem;\n            minElevation = Math.min(minElevation, (dem?.min ?? 0) * this.exaggeration);\n            maxElevation = Math.max(maxElevation, (dem?.max ?? 0) * this.exaggeration);\n        }\n\n        if (samplerPerTile.size === 0) return null;\n        zooms.sort((a, b) => b - a);\n        return {zooms, samplerPerTile, minElevation: minElevation - BRACKET_PADDING_M, maxElevation: maxElevation + BRACKET_PADDING_M};\n    }\n}\n\n/**\n * Elevation of the rendered terrain surface at a world position, and whether it is covered at all.\n * A covered tile whose DEM has not loaded yet is flat at zero, which is what the terrain mesh renders.\n * @param wraps - whether x wraps into world copies (mercator); a planar CRS has no terrain outside its world square\n */\nexport function sampleAt(index: TerrainCoverageIndex, exaggeration: number, worldX: number, worldY: number, wraps: boolean): TerrainSample {\n    if (worldY < 0 || worldY >= 1) return NOT_COVERED;\n    if (!wraps && (worldX < 0 || worldX >= 1)) return NOT_COVERED;\n    const wrap = wraps ? Math.floor(worldX) : 0;\n    const wrappedX = worldX - wrap;\n\n    for (const z of index.zooms) {\n        const scale = 1 << z;\n        const scaledX = wrappedX * scale;\n        const scaledY = worldY * scale;\n        const tileX = Math.floor(scaledX);\n        const tileY = Math.floor(scaledY);\n        const key = `${wrap}/${z}/${tileX}/${tileY}`;\n        if (!index.samplerPerTile.has(key)) continue;\n        const sampler = index.samplerPerTile.get(key);\n        if (!sampler) return {covered: true, demLoaded: false, elevation: 0};\n        const x = Math.min((scaledX - tileX) * EXTENT, MAX_TILE_COORD);\n        const y = Math.min((scaledY - tileY) * EXTENT, MAX_TILE_COORD);\n        return {covered: true, demLoaded: true, elevation: sampler(x, y, EXTENT) * exaggeration};\n    }\n    return NOT_COVERED;\n}\n\n/**\n * Whether a height in meters is at or below the sampled terrain surface.\n * The epsilon absorbs rounding when a bracket endpoint lands exactly on the surface.\n */\nexport function isBelowTerrainSample(sample: TerrainSample, height: number): boolean {\n    return sample.covered && height <= sample.elevation + HIT_EPSILON_M;\n}\n\n/**\n * Narrows the bracket `[lo, hi]` around the surface crossing until it is shorter than `tolerance` in ray parameter units.\n */\nexport function bisect<Ray>(ray: Ray, isBelowTerrain: (ray: Ray, t: number) => boolean, lo: number, hi: number, tolerance: number): {lo: number; hi: number} {\n    for (let j = 0; j < MAX_BISECTIONS && hi - lo > tolerance; j++) {\n        const mid = (lo + hi) / 2;\n        if (isBelowTerrain(ray, mid)) hi = mid;\n        else lo = mid;\n    }\n    return {lo, hi};\n}\n", "import {LngLat, type LngLatLike} from '../lng_lat.ts';\nimport {MercatorCoordinate, mercatorXfromLng, mercatorYfromLat} from '../mercator_coordinate.ts';\nimport Point from '@mapbox/point-geometry';\nimport {wrap, clamp, createMat4f64, degreesToRadians, radiansToDegrees, createIdentityMat4f32, zoomScale, scaleZoom, type Mat4f32, type Mat4f64} from '../../util/util.ts';\nimport {type mat2, mat4, vec3, vec4} from 'gl-matrix';\nimport {UnwrappedTileID, OverscaledTileID, type CanonicalTileID, calculateTileKey} from '../../tile/tile_id.ts';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {type PointProjection, xyTransformMat4} from '../../symbol/projection.ts';\nimport {LngLatBounds} from '../lng_lat_bounds.ts';\nimport {getMercatorHorizon, getMercatorTileCoordinates, projectToWorldCoordinates, unprojectFromWorldCoordinates, calculateTileMatrix, maxMercatorHorizonAngle, cameraMercatorCoordinateFromCenterAndRotation, lngLatBoxToWorldBox} from './mercator_utils.ts';\nimport {EXTENT} from '../../data/extent.ts';\nimport {TransformHelper} from '../transform_helper.ts';\nimport {MercatorCoveringTilesDetailsProvider} from './mercator_covering_tiles_details_provider.ts';\nimport {Frustum} from '../../util/primitives/frustum.ts';\nimport {fastInvertProjMat4} from '../../util/fast_maths.ts';\nimport {bisect, sampleAt, isBelowTerrainSample, TERRAIN_OCCLUSION_MARGIN, type TerrainCoverageIndex, type TerrainSample} from '../../render/terrain_coverage.ts';\nimport {getBearing, getCenterOffset, getCenterPoint, getFov, getPitch, getRoll, getWorldSize} from '../camera_state.ts';\n\nimport type {CameraState} from '../camera_state.ts';\nimport type {CameraOptionsFromTo, IReadonlyTransform, ITransform, NearFarZ, TransformConstrainFunction, WorldCoordinateHelper} from '../transform_interface.ts';\nimport type {Terrain} from '../../render/terrain.ts';\nimport type {TransformOptions} from '../transform_helper.ts';\nimport type {PaddingOptions} from '../edge_insets.ts';\nimport type {CustomLayerProjectionData, ProjectionDataParams, RendererProjectionData} from './projection_data.ts';\nimport type {CoveringTilesDetailsProvider} from './covering_tiles_details_provider.ts';\n\n/**\n * @internal\n * The portion of a ray through a screen pixel that lies inside the view frustum.\n * Both endpoints use world pixels for x and y, and meters above sea level for z.\n */\ntype RaySegment = {\n    near: vec3;\n    far: vec3;\n};\n\nconst TARGET_WORLD_STEP_PX = 4;\nconst MAX_SAMPLES = 512;\nconst MERCATOR_BISECT_EPSILON_WORLD_PX = 1e-3;\n/**\n * How many times {@link MercatorTransform.recalculateZoomAndCenter} picks the terrain under the center and moves the\n * center onto it, and how far above or below the terrain a center may stay. Each pass keeps the camera where it is,\n * so the center's latitude changes the mercator scale the next pass sees and the terrain pick moves with it; the\n * remainder shrinks by the scale difference each pass, from meters to under a millimeter on the second.\n */\nconst CENTER_ON_TERRAIN_PASSES = 3;\nconst CENTER_ON_TERRAIN_TOLERANCE_M = 0.0001;\n/**\n * The clip-space depth of the near clipping plane, where the ray segment through a screen pixel starts for a terrain\n * pick so that it holds all the view shows; see `getRaySegmentFromPixel`.\n */\nconst NEAR_PLANE_CLIP_Z = -1;\n\n/**\n * @internal\n * A ray to intersect with the terrain surface, in world pixels:\n * `near` is the segment start, `dx`/`dy`/`dz` span to the segment end, and z values are meters above sea level.\n */\ntype MercatorRay = {\n    index: TerrainCoverageIndex;\n    exaggeration: number;\n    near: vec3;\n    dx: number;\n    dy: number;\n    dz: number;\n    worldSize: number;\n    wraps: boolean;\n};\n\nexport class MercatorTransform implements ITransform {\n    private _helper: TransformHelper;\n\n    //\n    // Implementation of transform getters and setters\n    //\n\n    get pixelsToClipSpaceMatrix(): mat4 {\n        return this._helper.pixelsToClipSpaceMatrix;\n    }\n    get clipSpaceToPixelsMatrix(): mat4 {\n        return this._helper.clipSpaceToPixelsMatrix;\n    }\n    get pixelsToGLUnits(): [number, number] {\n        return this._helper.pixelsToGLUnits;\n    }\n    get size(): Point {\n        return this._helper.size;\n    }\n    get rotationMatrix(): mat2 {\n        return this._helper.rotationMatrix;\n    }\n    get centerPoint(): Point {\n        return this._helper.centerPoint;\n    }\n    get pixelsPerMeter(): number {\n        return this._helper.pixelsPerMeter;\n    }\n    setMinZoom(zoom: number): void {\n        this._helper.setMinZoom(zoom);\n    }\n    setMaxZoom(zoom: number): void {\n        this._helper.setMaxZoom(zoom);\n    }\n    setMinPitch(pitch: number): void {\n        this._helper.setMinPitch(pitch);\n    }\n    setMaxPitch(pitch: number): void {\n        this._helper.setMaxPitch(pitch);\n    }\n    setRenderWorldCopies(renderWorldCopies: boolean): void {\n        this._helper.setRenderWorldCopies(renderWorldCopies);\n    }\n    setBearing(bearing: number): void {\n        this._helper.setBearing(bearing);\n    }\n    setPitch(pitch: number): void {\n        this._helper.setPitch(pitch);\n    }\n    setRoll(roll: number): void {\n        this._helper.setRoll(roll);\n    }\n    setFov(fov: number): void {\n        this._helper.setFov(fov);\n    }\n    setZoom(zoom: number): void {\n        this._helper.setZoom(zoom);\n    }\n    setCenter(center: LngLat): void {\n        this._helper.setCenter(center);\n    }\n    setElevation(elevation: number): void {\n        this._helper.setElevation(elevation);\n    }\n    setMinElevationForCurrentTile(elevation: number): void {\n        this._helper.setMinElevationForCurrentTile(elevation);\n    }\n    setPadding(padding: PaddingOptions): void {\n        this._helper.setPadding(padding);\n    }\n    interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number): void {\n        this._helper.interpolatePadding(start, target, t);\n    }\n    isPaddingEqual(padding: PaddingOptions): boolean {\n        return this._helper.isPaddingEqual(padding);\n    }\n    resize(width: number, height: number, constrain: boolean = true): void {\n        this._helper.resize(width, height, constrain);\n    }\n    getMaxBounds(): LngLatBounds {\n        return this._helper.getMaxBounds();\n    }\n    setMaxBounds(bounds?: LngLatBounds): void {\n        this._helper.setMaxBounds(bounds);\n    }\n    setConstrainOverride(constrain?: TransformConstrainFunction | null): void {\n        this._helper.setConstrainOverride(constrain);\n    }\n    overrideNearFarZ(nearZ: number, farZ: number): void {\n        this._helper.overrideNearFarZ(nearZ, farZ);\n    }\n    clearNearFarZOverride(): void {\n        this._helper.clearNearFarZOverride();\n    }\n    getCameraQueryGeometry(queryGeometry: Point[]): Point[] {\n        return this._helper.getCameraQueryGeometry(queryGeometry);\n    }\n\n    get tileSize(): number {\n        return this._helper.tileSize;\n    }\n    get tileZoom(): number {\n        return this._helper.tileZoom;\n    }\n    get scale(): number {\n        return this._helper.scale;\n    }\n    get worldSize(): number {\n        return this._helper.worldSize;\n    }\n    get width(): number {\n        return this._helper.width;\n    }\n    get height(): number {\n        return this._helper.height;\n    }\n    get lngRange(): [number, number] {\n        return this._helper.lngRange;\n    }\n    get latRange(): [number, number] {\n        return this._helper.latRange;\n    }\n    get minZoom(): number {\n        return this._helper.minZoom;\n    }\n    get maxZoom(): number {\n        return this._helper.maxZoom;\n    }\n    get zoom(): number {\n        return this._helper.zoom;\n    }\n    get center(): LngLat {\n        return this._helper.center;\n    }\n    get minPitch(): number {\n        return this._helper.minPitch;\n    }\n    get maxPitch(): number {\n        return this._helper.maxPitch;\n    }\n    get pitch(): number {\n        return this._helper.pitch;\n    }\n    get pitchInRadians(): number {\n        return this._helper.pitchInRadians;\n    }\n    get roll(): number {\n        return this._helper.roll;\n    }\n    get rollInRadians(): number {\n        return this._helper.rollInRadians;\n    }\n    get bearing(): number {\n        return this._helper.bearing;\n    }\n    get bearingInRadians(): number {\n        return this._helper.bearingInRadians;\n    }\n    get fov(): number {\n        return this._helper.fov;\n    }\n    get fovInRadians(): number {\n        return this._helper.fovInRadians;\n    }\n    get elevation(): number {\n        return this._helper.elevation;\n    }\n    get minElevationForCurrentTile(): number {\n        return this._helper.minElevationForCurrentTile;\n    }\n    get padding(): PaddingOptions {\n        return this._helper.padding;\n    }\n    get unmodified(): boolean {\n        return this._helper.unmodified;\n    }\n    get renderWorldCopies(): boolean {\n        return this._helper.renderWorldCopies;\n    }\n    get cameraToCenterDistance(): number {\n        return this._helper.cameraToCenterDistance;\n    }\n    get constrainOverride(): TransformConstrainFunction {\n        return this._helper.constrainOverride;\n    }\n    public get nearZ(): number {\n        return this._nearZ;\n    }\n    public get farZ(): number {\n        return this._farZ;\n    }\n    public get nearFarZOverride(): NearFarZ | null {\n        return this._helper.nearFarZOverride;\n    }\n    public get autoCalculateNearFarZ(): boolean {\n        return this._helper.autoCalculateNearFarZ;\n    }\n    setTransitionState(_value: number): void {\n        // Do nothing\n    }\n    //\n    // Implementation of mercator transform\n    //\n\n    private _cameraPosition: vec3;\n    private _nearZ: number;\n    private _farZ: number;\n\n    private _mercatorMatrix: mat4;\n    private _projectionMatrix: mat4;\n    private _viewProjMatrix: mat4;\n    private _invViewProjMatrix: mat4;\n    private _invProjMatrix: mat4;\n    private _alignedProjMatrix: mat4;\n    private _pixelMatrix: mat4;\n    private _pixelMatrix3D: mat4;\n    private _pixelMatrixInverse: mat4;\n    private _fogMatrix: mat4;\n\n    private _posMatrixCache: Map<string, {f64: Mat4f64; f32: Mat4f32}> = new Map();\n    private _alignedPosMatrixCache: Map<string, {f64: Mat4f64; f32: Mat4f32}> = new Map();\n    private _fogMatrixCacheF32: Map<string, mat4> = new Map();\n\n    private _coveringTilesDetailsProvider;\n    /** The last `maxBounds` projected into the world square, and the ranges it was projected from. */\n    private _maxBoundsWorldBox: {lngRange: [number, number]; latRange: [number, number]; box: {minX: number; minY: number; maxX: number; maxY: number}} | null = null;\n\n    /**\n     * @param options - Initial state. Ignored when `sharedHelper` is given, which already carries it.\n     * @param sharedHelper - Camera to use instead of owning one, so that a composing transform such as\n     * {@link GlobeTransform} keeps a single copy of the state rather than one per child. Its owner then drives\n     * {@link _calcMatrices}, because a helper has only one `calcMatrices` callback.\n     */\n    constructor(options?: TransformOptions, sharedHelper?: TransformHelper) {\n        this._helper = sharedHelper ?? new TransformHelper({\n            calcMatrices: () => this._calcMatrices(),\n            defaultConstrain: (center, zoom) => { return this.defaultConstrain(center, zoom); }\n        }, options);\n        this._coveringTilesDetailsProvider = new MercatorCoveringTilesDetailsProvider();\n    }\n\n    private get _cameraState(): Readonly<CameraState> {\n        return this._helper.cameraState;\n    }\n\n    /** The {@link getMercatorHorizon} of this camera. */\n    private _getHorizon(): number {\n        return getMercatorHorizon({pitch: getPitch(this._cameraState), cameraToCenterDistance: this._cameraState.cameraToCenterDistance});\n    }\n\n    public clone(): ITransform {\n        const clone = new MercatorTransform({worldCoordinateHelper: this.worldCoordinateHelper});\n        clone.apply(this, false);\n        return clone;\n    }\n\n    get worldCoordinateHelper(): WorldCoordinateHelper {\n        return this._helper.worldCoordinateHelper;\n    }\n\n    public apply(that: IReadonlyTransform, constrain: boolean): void {\n        this._helper.apply(that, constrain);\n    }\n\n    public get cameraPosition(): vec3 { return this._cameraPosition; }\n    public get projectionMatrix(): mat4 { return this._projectionMatrix; }\n    public get modelViewProjectionMatrix(): mat4 { return this._viewProjMatrix; }\n    public get inverseProjectionMatrix(): mat4 { return this._invProjMatrix; }\n    public get mercatorMatrix(): mat4 { return this._mercatorMatrix; } // Not part of ITransform interface\n\n    getVisibleUnwrappedCoordinates(tileID: CanonicalTileID): UnwrappedTileID[] {\n        const result = [new UnwrappedTileID(0, tileID)];\n        if (this._cameraState.renderWorldCopies && this.worldCoordinateHelper.wraps) {\n            const utl = this.screenPointToMercatorCoordinate(new Point(0, 0));\n            const utr = this.screenPointToMercatorCoordinate(new Point(this._cameraState.width, 0));\n            const ubl = this.screenPointToMercatorCoordinate(new Point(this._cameraState.width, this._cameraState.height));\n            const ubr = this.screenPointToMercatorCoordinate(new Point(0, this._cameraState.height));\n            const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x));\n            const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x));\n\n            // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources.\n            // Both sources draw outside the tile boundaries of the tile that \"contains them\" so we need\n            // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones.\n            const extraWorldCopy = 1;\n\n            for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {\n                if (w === 0) continue;\n                result.push(new UnwrappedTileID(w, tileID));\n            }\n        }\n        return result;\n    }\n\n    getCameraFrustum(): Frustum {\n        return Frustum.fromInvProjectionMatrix(this._invViewProjMatrix, getWorldSize(this._cameraState));\n    }\n    getClippingPlane(): vec4 | null {\n        return null;\n    }\n    getCoveringTilesDetailsProvider(): CoveringTilesDetailsProvider {\n        return this._coveringTilesDetailsProvider;\n    }\n\n    recalculateZoomAndCenter(terrain?: Terrain): void {\n        for (let pass = 0; pass < CENTER_ON_TERRAIN_PASSES; pass++) {\n            const elevation = this.getGroundElevationAtCenter(terrain);\n            if (elevation === null) return;\n            this._helper.recalculateZoomAndCenter(elevation);\n            if (!terrain || Math.abs(terrain.getElevationForLngLat(this._cameraState.center, this._cameraState.tileZoom) - this._cameraState.elevation) <= CENTER_ON_TERRAIN_TOLERANCE_M) return;\n        }\n    }\n\n    /**\n     * The elevation of the ground the camera looks at, which {@link recalculateZoomAndCenter} moves the center to,\n     * or null where the camera would end up below that ground.\n     */\n    getGroundElevationAtCenter(terrain?: Terrain): number | null {\n        const center = (terrain && this._terrainPointPastMaxZoom(terrain)) || this.screenPointToLocation(getCenterPoint(this._cameraState), terrain);\n        const elevation = terrain ? terrain.getElevationForLngLat(center, this._cameraState.tileZoom) : 0;\n        if (getPitch(this._cameraState) < 90 && elevation >= this.getCameraAltitude()) return null;\n        return elevation;\n    }\n\n    setLocationAtPoint(lnglat: LngLat, point: Point, elevation?: number): void {\n        const camera = this.getCameraForLocationAtPoint(lnglat, point, elevation);\n        if (camera) this._helper.setCenterAndZoom(camera.center, camera.zoom);\n    }\n\n    /**\n     * The center and zoom that {@link setLocationAtPoint} moves the camera to, so that `lnglat`, on the ground at\n     * `elevation` meters, renders at the screen `point`, or null where the camera stays where it is. Both rays are\n     * cast through the same inverse pixel matrix so its inversion error cancels out of their difference; the\n     * current-center ray must be intersected at the center's own elevation (z=0), since intersecting it with the\n     * elevated plane would land `(elevation - centerElevation)·tan(pitch)` away from the center and make repeated\n     * calls drift. In a world that wraps, a center outside the main world is then wrapped into it and constrained\n     * again.\n     */\n    getCameraForLocationAtPoint(lnglat: LngLat, point: Point, elevation: number = this._cameraState.elevation): {center: LngLat; zoom: number} | null {\n        const z = elevation - this._cameraState.elevation;\n        const a = this.screenPointToMercatorCoordinateAtZ(point, z);\n        const b = this.screenPointToMercatorCoordinateAtZ(getCenterPoint(this._cameraState), 0);\n        const worldCoordinateHelper = this.worldCoordinateHelper;\n        const loc = worldCoordinateHelper.worldFromLngLat(lnglat.lng, lnglat.lat);\n        const center = worldCoordinateHelper.lngLatFromWorld(\n            loc.x - (a.x - b.x),\n            loc.y - (a.y - b.y));\n        const moved = center.lng !== this._cameraState.center.lng || center.lat !== this._cameraState.center.lat;\n        let camera = moved ? this._helper.getConstrainedCamera(center, this._cameraState.zoom) : null;\n        if (this._cameraState.renderWorldCopies && worldCoordinateHelper.wraps) {\n            const unwrapped = camera ?? {center: this._cameraState.center, zoom: this._cameraState.zoom};\n            const wrapped = unwrapped.center.wrap();\n            if (wrapped.lng !== unwrapped.center.lng) camera = this._helper.getConstrainedCamera(wrapped, unwrapped.zoom);\n        }\n        return camera;\n    }\n\n    locationToScreenPoint(lnglat: LngLat, terrain?: Terrain): Point {\n        const coord = this.worldCoordinateHelper.worldFromLngLat(lnglat.lng, lnglat.lat);\n        return terrain ?\n            this.coordinatePoint(coord, terrain.getElevationForLngLat(lnglat, this._cameraState.tileZoom), this._pixelMatrix3D) :\n            this.coordinatePoint(coord);\n    }\n\n    screenPointToLocation(p: Point, terrain?: Terrain): LngLat {\n        return this._worldToLngLat(this.screenPointToMercatorCoordinate(p, terrain));\n    }\n\n    screenPointToLocationAtElevation(p: Point, elevation: number): LngLat {\n        return this._worldToLngLat(this.screenPointToMercatorCoordinateAtZ(p, elevation - this._cameraState.elevation));\n    }\n\n    /**\n     * Maps a world position back to lng/lat through the projection, or `undefined` when the point missed\n     * the world (a screen point above the horizon or off the terrain).\n     */\n    private _worldToLngLat(coord: MercatorCoordinate | null | undefined): LngLat | undefined {\n        return coord ? this.worldCoordinateHelper.lngLatFromWorld(coord.x, coord.y) : undefined;\n    }\n\n    screenPointToMercatorCoordinate(p: Point, terrain?: Terrain): MercatorCoordinate {\n        if (terrain) {\n            const coordinate = this.screenTerrainPointToMercatorCoordinate(p, terrain);\n            if (coordinate != null) {\n                return coordinate;\n            }\n        }\n        return this.screenPointToMercatorCoordinateAtZ(p);\n    }\n\n    /**\n     * Where the center ray meets the terrain beyond the distance at which the center sits from the camera at maxZoom,\n     * if the ray is above the terrain there; null otherwise. A center on nearer terrain needs a zoom past maxZoom, which\n     * `setZoom` clamps by moving the camera back, so once the ray has cleared a bump nearer than that, the center goes\n     * to the terrain behind it. Where maxZoom lets the camera nearer than the near clipping plane, the ray is followed\n     * from that plane, like every terrain pick.\n     */\n    private _terrainPointPastMaxZoom(terrain: Terrain): LngLat | null {\n        const index = terrain.getCoverageIndex();\n        if (!index) return null;\n        const {near, far} = this.getRaySegmentFromPixel(getCenterPoint(this._cameraState), NEAR_PLANE_CLIP_Z);\n        const distanceAtMaxZoom = this._cameraState.cameraToCenterDistance * zoomScale(this._cameraState.zoom - this._cameraState.maxZoom);\n        const start = vec3.lerp([], near, far, Math.max(0, (distanceAtMaxZoom - this.nearZ) / (this.farZ - this.nearZ)));\n        if (isBelowTerrainSample(sampleAt(index, terrain.exaggeration, start[0] / getWorldSize(this._cameraState), start[1] / getWorldSize(this._cameraState), this.worldCoordinateHelper.wraps), start[2])) return null;\n        return this._worldToLngLat(this._raycastTerrain(start, far, terrain)) ?? null;\n    }\n\n    /** {@inheritDoc ITransform.screenTerrainPointToMercatorCoordinate} */\n    screenTerrainPointToMercatorCoordinate(p: Point, terrain: Terrain): MercatorCoordinate | null {\n        const {near, far} = this.getRaySegmentFromPixel(p, NEAR_PLANE_CLIP_Z);\n        return this._raycastTerrain(near, far, terrain);\n    }\n\n    /** The first point where the segment from `near` to `far` enters the terrain from above, or null. */\n    private _raycastTerrain(near: vec3, far: vec3, terrain: Terrain): MercatorCoordinate | null {\n        const index = terrain.getCoverageIndex();\n        if (!index) return null;\n\n        const worldSize = getWorldSize(this._cameraState);\n        const dx = far[0] - near[0];\n        const dy = far[1] - near[1];\n        const dz = far[2] - near[2];\n        const ray: MercatorRay = {index, exaggeration: terrain.exaggeration, near, dx, dy, dz, worldSize, wraps: this.worldCoordinateHelper.wraps};\n\n        let tStart = 0;\n        let tEnd = 1;\n        if (dz === 0) {\n            if (near[2] > index.maxElevation || near[2] < index.minElevation) return null;\n        } else {\n            const tHigh = (index.maxElevation - near[2]) / dz;\n            const tLow = (index.minElevation - near[2]) / dz;\n            tStart = Math.max(tStart, Math.min(tHigh, tLow));\n            tEnd = Math.min(tEnd, Math.max(tHigh, tLow));\n            if (tStart > tEnd) return null;\n        }\n\n        const horizontalLength = Math.hypot(dx, dy);\n        const samples = clamp(Math.ceil(horizontalLength * (tEnd - tStart) / TARGET_WORLD_STEP_PX), 1, MAX_SAMPLES);\n\n        let previousT = 0;\n        let aboveTerrain = !mercatorIsBelowTerrain(ray, 0);\n\n        for (let i = 0; i <= samples; i++) {\n            const t = tStart + (tEnd - tStart) * i / samples;\n\n            if (!aboveTerrain) {\n                aboveTerrain = !mercatorIsBelowTerrain(ray, t);\n            } else if (mercatorIsBelowTerrain(ray, t)) {\n                const {lo, hi} = bisect(ray, mercatorIsBelowTerrain, previousT, t, MERCATOR_BISECT_EPSILON_WORLD_PX / horizontalLength);\n                const sampleLo = mercatorSampleAt(ray, lo);\n                const sampleHi = mercatorSampleAt(ray, hi);\n                const fLo = near[2] + lo * dz - sampleLo.elevation;\n                const fHi = near[2] + hi * dz - sampleHi.elevation;\n                const hit = sampleLo.covered && fLo > fHi ? clamp(lo + fLo * (hi - lo) / (fLo - fHi), lo, hi) : hi;\n                return new MercatorCoordinate(\n                    (near[0] + hit * dx) / worldSize,\n                    (near[1] + hit * dy) / worldSize,\n                    mercatorSampleAt(ray, hit).elevation);\n            }\n\n            previousT = t;\n        }\n\n        return null;\n    }\n\n    /**\n     * Returns the segment of the ray through the given screen pixel from its point at depth `clipZ` in clip space to the\n     * far clipping plane. The default of 0 lies at about twice the near clipping plane's distance from the camera, which\n     * is all a plane intersection needs; `NEAR_PLANE_CLIP_Z` starts the segment at the near clipping plane, so it holds\n     * all the view shows, as terrain picks need.\n     */\n    private getRaySegmentFromPixel(p: Point, clipZ: number = 0): RaySegment {\n        const coord0 = [p.x, p.y, clipZ, 1] as vec4;\n        const coord1 = [p.x, p.y, 1, 1] as vec4;\n\n        vec4.transformMat4(coord0, coord0, this._pixelMatrixInverse);\n        vec4.transformMat4(coord1, coord1, this._pixelMatrixInverse);\n\n        const w0 = coord0[3];\n        const w1 = coord1[3];\n        // The pixel matrix is built before the elevation translate, so unprojected z is relative to the center's elevation.\n        const elevation = this._cameraState.elevation;\n\n        return {\n            near: [coord0[0] / w0, coord0[1] / w0, coord0[2] / w0 + elevation],\n            far: [coord1[0] / w1, coord1[1] / w1, coord1[2] / w1 + elevation]\n        };\n    }\n\n    /**\n     * Intersects the ray through a screen point with the horizontal plane at `z`,\n     * given in meters relative to the plane at the center's elevation (not mercator units).\n     */\n    screenPointToMercatorCoordinateAtZ(p: Point, z?: number): MercatorCoordinate {\n        const targetZ = z ? z : 0;\n        const {near, far} = this.getRaySegmentFromPixel(p);\n\n        const t = near[2] === far[2] ? 0 : (targetZ + this._cameraState.elevation - near[2]) / (far[2] - near[2]);\n\n        return new MercatorCoordinate(\n            interpolates.number(near[0], far[0], t) / getWorldSize(this._cameraState),\n            interpolates.number(near[1], far[1], t) / getWorldSize(this._cameraState),\n            targetZ);\n    }\n\n    /**\n     * Given a coordinate, return the screen point that corresponds to it\n     * @param coord - the coordinates\n     * @param elevation - the elevation\n     * @param pixelMatrix - the pixel matrix\n     * @returns screen point. Point will be outside the viewport if the coordinate is behind the camera.\n     */\n    coordinatePoint(coord: MercatorCoordinate, elevation: number = 0, pixelMatrix: mat4 = this._pixelMatrix): Point {\n        const p = this._coordinateClipPoint(coord, elevation, pixelMatrix);\n        const w = p[3];\n        if (w > 0) {\n            return new Point(p[0] / w, p[1] / w);\n        }\n        return this._offScreenPointBehindCamera(p[0], p[1], w);\n    }\n\n    /**\n     * The coordinate in the clip space of `pixelMatrix`: pixel x and y and NDC depth, each times `w`, which is positive\n     * in front of the camera.\n     */\n    private _coordinateClipPoint(coord: MercatorCoordinate, elevation: number, pixelMatrix: mat4): vec4 {\n        const p = [coord.x * getWorldSize(this._cameraState), coord.y * getWorldSize(this._cameraState), elevation, 1] as vec4;\n        return vec4.transformMat4(p, p, pixelMatrix);\n    }\n\n    /**\n     * Returns a screen point outside the viewport for a coordinate that is behind the camera.\n     * The point lies on the boundary of the viewport enlarged by one viewport size on each side,\n     * on whichever edge the ray from the screen centre in the coordinate's direction reaches first.\n     * A coordinate exactly behind the camera has no direction to leave through, so it is placed straight down.\n     * @param x - the x component of the clip space position, before the division by w\n     * @param y - the y component of the clip space position, before the division by w\n     * @param w - the w component of the clip space position, zero or negative\n     * @returns screen point outside the viewport\n     */\n    private _offScreenPointBehindCamera(x: number, y: number, w: number): Point {\n        const cx = this._cameraState.width / 2;\n        const cy = this._cameraState.height / 2;\n        const dx = x - cx * w;\n        let dy = y - cy * w;\n        if (dx === 0 && dy === 0) {\n            dy = 1;\n        }\n        const halfExtentX = cx + this._cameraState.width;\n        const halfExtentY = cy + this._cameraState.height;\n        const scale = Math.min(\n            dx !== 0 ? halfExtentX / Math.abs(dx) : Infinity,\n            dy !== 0 ? halfExtentY / Math.abs(dy) : Infinity);\n        return new Point(cx + dx * scale, cy + dy * scale);\n    }\n\n    getBounds(): LngLatBounds {\n        const top = Math.max(0, this._cameraState.height / 2 - this._getHorizon());\n        return new LngLatBounds()\n            .extend(this.screenPointToLocation(new Point(0, top)))\n            .extend(this.screenPointToLocation(new Point(this._cameraState.width, top)))\n            .extend(this.screenPointToLocation(new Point(this._cameraState.width, this._cameraState.height)))\n            .extend(this.screenPointToLocation(new Point(0, this._cameraState.height)));\n    }\n\n    isPointOnMapSurface(p: Point, terrain?: Terrain): boolean {\n        if (terrain) {\n            return this.screenTerrainPointToMercatorCoordinate(p, terrain) != null;\n        }\n        const belowHorizon = p.y > getCenterPoint(this._cameraState).y - this._getHorizon();\n        if (!belowHorizon || this.worldCoordinateHelper.wraps) {\n            return belowHorizon;\n        }\n        const coordinate = this.screenPointToMercatorCoordinate(p);\n        return this.worldCoordinateHelper.hasLngLat(coordinate.x, coordinate.y);\n    }\n\n    /**\n     * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map.\n     * This function is specific to the mercator projection.\n     * @param tileID - the tile ID\n     * @param aligned - whether to use a pixel-aligned matrix variant, intended for rendering raster tiles\n     * @param useFloat32 - when true, returns a float32 matrix instead of float64. Use float32 for matrices that are passed to shaders, use float64 for everything else.\n     */\n    calculatePosMatrix(tileID: UnwrappedTileID | OverscaledTileID, aligned: boolean | undefined, useFloat32: true): Mat4f32;\n    calculatePosMatrix(tileID: UnwrappedTileID | OverscaledTileID, aligned?: boolean, useFloat32?: false): Mat4f64;\n    calculatePosMatrix(tileID: UnwrappedTileID | OverscaledTileID, aligned: boolean = false, useFloat32: boolean = false): Mat4f32 | Mat4f64 {\n        const posMatrixKey = tileID.key ?? calculateTileKey(tileID.wrap, tileID.canonical.z, tileID.canonical.z, tileID.canonical.x, tileID.canonical.y);\n        const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache;\n        if (cache.has(posMatrixKey)) {\n            const matrices = cache.get(posMatrixKey);\n            return useFloat32 ? matrices.f32 : matrices.f64;\n        }\n\n        const tileMatrix = calculateTileMatrix(tileID, getWorldSize(this._cameraState));\n        mat4.multiply(tileMatrix, aligned ? this._alignedProjMatrix : this._viewProjMatrix, tileMatrix);\n        const matrices: {f64: Mat4f64; f32: Mat4f32} = {\n            f64: tileMatrix,\n            f32: new Float32Array(tileMatrix), // Must have a 32 bit float version for WebGL, otherwise WebGL calls in Chrome get very slow.\n        };\n        cache.set(posMatrixKey, matrices);\n        // Make sure to return the correct precision\n        return useFloat32 ? matrices.f32 : matrices.f64;\n    }\n\n    calculateFogMatrix(unwrappedTileID: UnwrappedTileID): mat4 {\n        const posMatrixKey = unwrappedTileID.key;\n        const cache = this._fogMatrixCacheF32;\n        if (cache.has(posMatrixKey)) {\n            return cache.get(posMatrixKey);\n        }\n\n        const fogMatrix = calculateTileMatrix(unwrappedTileID, getWorldSize(this._cameraState));\n        mat4.multiply(fogMatrix, this._fogMatrix, fogMatrix);\n\n        cache.set(posMatrixKey, new Float32Array(fogMatrix)); // Must be 32 bit floats, otherwise WebGL calls in Chrome get very slow.\n        return cache.get(posMatrixKey);\n    }\n\n    /**\n     * This mercator implementation returns center lngLat and zoom to ensure that:\n     *\n     * 1) everything beyond the bounds is excluded\n     * 2) a given lngLat is as near the center as possible\n     *\n     * Bounds are those set by maxBounds or North & South \"Poles\" and, if only 1 globe is displayed, antimeridian.\n     * A non-wrapping world (a registered planar CRS) keeps its center inside its world square instead, see\n     * {@link MercatorTransform._constrainToWorldSquare}.\n     */\n    defaultConstrain: TransformConstrainFunction = (lngLat, zoom) => {\n        zoom = clamp(+zoom, this._cameraState.minZoom, this._cameraState.maxZoom);\n        if (!this.worldCoordinateHelper.wraps) return this._constrainToWorldSquare(lngLat, zoom);\n        const result = {\n            center: new LngLat(lngLat.lng, lngLat.lat),\n            zoom\n        };\n\n        let lngRange = this._cameraState.lngRange;\n\n        if (!this._cameraState.renderWorldCopies && lngRange === null) {\n            const almost180 = 180 - 1e-10;\n            lngRange = [-almost180, almost180];\n        }\n\n        const worldSize = this._cameraState.tileSize * zoomScale(result.zoom); // A world size for the requested zoom level, not the current world size\n        let minY = 0;\n        let maxY = worldSize;\n        let minX = 0;\n        let maxX = worldSize;\n        let scaleY = 0;\n        let scaleX = 0;\n        const {top = 0, bottom = 0, left = 0, right = 0} = this._cameraState.edgeInsets;\n        const screenWidth = this._cameraState.width - left - right;\n        const screenHeight = this._cameraState.height - top - bottom;\n\n        if (this._cameraState.latRange) {\n            const latRange = this._cameraState.latRange;\n            minY = mercatorYfromLat(latRange[1]) * worldSize;\n            maxY = mercatorYfromLat(latRange[0]) * worldSize;\n            const shouldZoomIn = maxY - minY < screenHeight;\n            if (shouldZoomIn) scaleY = screenHeight / (maxY - minY);\n        }\n\n        if (lngRange) {\n            minX = wrap(\n                mercatorXfromLng(lngRange[0]) * worldSize,\n                0,\n                worldSize\n            );\n            maxX = wrap(\n                mercatorXfromLng(lngRange[1]) * worldSize,\n                0,\n                worldSize\n            );\n\n            if (maxX < minX) maxX += worldSize;\n\n            const shouldZoomIn = maxX - minX < screenWidth;\n            if (shouldZoomIn) scaleX = screenWidth / (maxX - minX);\n        }\n\n        const {x: originalX, y: originalY} = projectToWorldCoordinates(worldSize, lngLat, this.worldCoordinateHelper);\n        let modifiedX, modifiedY;\n\n        const scale = Math.max(scaleX || 0, scaleY || 0);\n\n        if (scale) {\n            // zoom in to exclude all beyond the given lng/lat ranges\n            const newPoint = new Point(\n                scaleX ? (maxX + minX) / 2 : originalX,\n                scaleY ? (maxY + minY) / 2 : originalY);\n            result.center = unprojectFromWorldCoordinates(worldSize, newPoint, this.worldCoordinateHelper).wrap();\n            result.zoom += scaleZoom(scale);\n            return result;\n        }\n\n        if (this._cameraState.latRange) {\n            const h2 = screenHeight / 2;\n            if (originalY - h2 < minY) modifiedY = minY + h2;\n            if (originalY + h2 > maxY) modifiedY = maxY - h2;\n        }\n\n        if (lngRange) {\n            const centerX = (minX + maxX) / 2;\n            let wrappedX = originalX;\n            if (this._cameraState.renderWorldCopies) {\n                wrappedX = wrap(originalX, centerX - worldSize / 2, centerX + worldSize / 2);\n            }\n            const w2 = screenWidth / 2;\n\n            if (wrappedX - w2 < minX) modifiedX = minX + w2;\n            if (wrappedX + w2 > maxX) modifiedX = maxX - w2;\n        }\n\n        // pan the map if the screen goes off the range\n        if (modifiedX !== undefined || modifiedY !== undefined) {\n            const newPoint = new Point(modifiedX ?? originalX, modifiedY ?? originalY);\n            result.center = unprojectFromWorldCoordinates(worldSize, newPoint, this.worldCoordinateHelper).wrap();\n        }\n\n        return result;\n    };\n\n    /**\n     * The constrain for a projection whose world does not wrap. Without max bounds only the center stays inside the\n     * 0..1 world square and the zoom is left to `minZoom`: the square is the grid the tile matrix set picked, which\n     * can be much larger than the area of interest or narrower than the window. With max bounds, projected as a box\n     * since both world axes may depend on lng and lat, the view may not leave them and the map zooms in until they\n     * fill the screen.\n     */\n    private _constrainToWorldSquare(lngLat: LngLat, zoom: number): {center: LngLat; zoom: number} {\n        const worldCoordinateHelper = this.worldCoordinateHelper;\n        const lngRange = this._cameraState.lngRange;\n        const worldSize = this._cameraState.tileSize * zoomScale(zoom);\n        if (!lngRange) {\n            const {x, y} = projectToWorldCoordinates(worldSize, lngLat, worldCoordinateHelper);\n            const clampedX = clamp(x, 0, worldSize);\n            const clampedY = clamp(y, 0, worldSize);\n            if (clampedX !== x || clampedY !== y) {\n                return {center: unprojectFromWorldCoordinates(worldSize, new Point(clampedX, clampedY), worldCoordinateHelper), zoom};\n            }\n            return {center: new LngLat(lngLat.lng, lngLat.lat), zoom};\n        }\n        const box = this._projectMaxBounds(lngRange, this._cameraState.latRange);\n        const minX = Math.max(box.minX, 0) * worldSize;\n        const maxX = Math.min(box.maxX, 1) * worldSize;\n        const minY = Math.max(box.minY, 0) * worldSize;\n        const maxY = Math.min(box.maxY, 1) * worldSize;\n        const {width: screenWidth, height: screenHeight} = this._cameraState;\n        const scaleX = maxX - minX < screenWidth ? screenWidth / (maxX - minX) : 0;\n        const scaleY = maxY - minY < screenHeight ? screenHeight / (maxY - minY) : 0;\n        const {x, y} = projectToWorldCoordinates(worldSize, lngLat, worldCoordinateHelper);\n\n        const scale = Math.max(scaleX, scaleY);\n        if (scale) {\n            const newPoint = new Point(scaleX ? (maxX + minX) / 2 : x, scaleY ? (maxY + minY) / 2 : y);\n            return {center: unprojectFromWorldCoordinates(worldSize, newPoint, worldCoordinateHelper), zoom: zoom + scaleZoom(scale)};\n        }\n\n        const constrainedX = clamp(x, minX + screenWidth / 2, maxX - screenWidth / 2);\n        const constrainedY = clamp(y, minY + screenHeight / 2, maxY - screenHeight / 2);\n        if (constrainedX !== x || constrainedY !== y) {\n            return {center: unprojectFromWorldCoordinates(worldSize, new Point(constrainedX, constrainedY), worldCoordinateHelper), zoom};\n        }\n        return {center: new LngLat(lngLat.lng, lngLat.lat), zoom};\n    }\n\n    /**\n     * `maxBounds` in the world square. Projecting a box samples it on a grid and every constrain reads it,\n     * so the result is kept until the bounds change.\n     */\n    private _projectMaxBounds(lngRange: [number, number], latRange: [number, number]): {minX: number; minY: number; maxX: number; maxY: number} {\n        const cached = this._maxBoundsWorldBox;\n        if (cached?.lngRange === lngRange && cached.latRange === latRange) return cached.box;\n        const box = lngLatBoxToWorldBox(this.worldCoordinateHelper, lngRange[0], latRange[0], lngRange[1], latRange[1]);\n        this._maxBoundsWorldBox = {lngRange, latRange, box};\n        return box;\n    }\n\n    applyConstrain: TransformConstrainFunction = (lngLat, zoom) => {\n        return this._helper.applyConstrain(lngLat, zoom);\n    };\n\n    calculateCenterFromCameraLngLatAlt(lnglat: LngLatLike, alt: number, bearing?: number, pitch?: number): {center: LngLat; elevation: number; zoom: number} {\n        return this._helper.calculateCenterFromCameraLngLatAlt(lnglat, alt, bearing, pitch);\n    }\n\n    calculateCameraOptionsFromTo(from: LngLatLike, altitudeFrom: number, to: LngLatLike, altitudeTo: number): CameraOptionsFromTo {\n        const worldCoordinateHelper = this.worldCoordinateHelper;\n        const fromLngLat = LngLat.convert(from);\n        const toLngLat = LngLat.convert(to);\n        const fromWorld = worldCoordinateHelper.worldFromLngLat(fromLngLat.lng, fromLngLat.lat, altitudeFrom);\n        const toWorld = worldCoordinateHelper.worldFromLngLat(toLngLat.lng, toLngLat.lat, altitudeTo);\n        const dx = toWorld.x - fromWorld.x;\n        const dy = toWorld.y - fromWorld.y;\n        const dz = toWorld.z - fromWorld.z;\n\n        const distance3D = Math.hypot(dx, dy, dz);\n        if (distance3D === 0) throw new Error('Can\\'t calculate camera options with same From and To');\n\n        const groundDistance = Math.hypot(dx, dy);\n\n        const zoom = scaleZoom(this._cameraState.cameraToCenterDistance / distance3D / this._cameraState.tileSize);\n        const bearing = radiansToDegrees(Math.atan2(dx, -dy));\n        let pitch = radiansToDegrees(Math.acos(groundDistance / distance3D));\n        pitch = dz < 0 ? 90 - pitch : 90 + pitch;\n\n        return {center: worldCoordinateHelper.lngLatFromWorld(toWorld.x, toWorld.y), elevation: altitudeTo, zoom, pitch, bearing};\n    }\n\n    _calculateNearFarZ(cameraToSeaLevelDistance: number, limitedPitchRadians: number, offset: Point): NearFarZ {\n        // In case of negative minimum elevation (e.g. the dead see, under the sea maps) use a lower plane for calculation\n        const minRenderDistanceBelowCameraInMeters = 100;\n        const minElevation = Math.min(this._cameraState.elevation, this._cameraState.minElevationForCurrentTile, this.getCameraAltitude() - minRenderDistanceBelowCameraInMeters);\n        const cameraToLowestPointDistance = cameraToSeaLevelDistance - minElevation * this._cameraState.pixelsPerMeter / Math.cos(limitedPitchRadians);\n        const lowestPlane = minElevation < 0 ? cameraToLowestPointDistance : cameraToSeaLevelDistance;\n\n        // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the\n        // center top point [width/2 + offset.x, 0] in Z units, using the law of sines.\n        // 1 Z unit is equivalent to 1 horizontal px at the center of the map\n        // (the distance between[width/2, height/2] and [width/2 + 1, height/2])\n        const groundAngle = Math.PI / 2 + this._cameraState.pitchInRadians;\n        const zfov = degreesToRadians(getFov(this._cameraState)) * (Math.abs(Math.cos(degreesToRadians(getRoll(this._cameraState)))) * this._cameraState.height + Math.abs(Math.sin(degreesToRadians(getRoll(this._cameraState)))) * this._cameraState.width) / this._cameraState.height;\n        const fovAboveCenter = zfov * (0.5 + offset.y / this._cameraState.height);\n        const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * lowestPlane / Math.sin(clamp(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01));\n\n        // Find the distance from the center point to the horizon\n        const horizon = this._getHorizon();\n        const horizonAngle = Math.atan(horizon / this._cameraState.cameraToCenterDistance);\n        const minFovCenterToHorizonRadians = degreesToRadians(90 - maxMercatorHorizonAngle);\n        const fovCenterToHorizon = horizonAngle > minFovCenterToHorizonRadians ? 2 * horizonAngle * (0.5 + offset.y / (horizon * 2)) : minFovCenterToHorizonRadians;\n        const topHalfSurfaceDistanceHorizon = Math.sin(fovCenterToHorizon) * lowestPlane / Math.sin(clamp(Math.PI - groundAngle - fovCenterToHorizon, 0.01, Math.PI - 0.01));\n\n        // Calculate z distance of the farthest fragment that should be rendered.\n        // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`\n        const topHalfMinDistance = Math.min(topHalfSurfaceDistance, topHalfSurfaceDistanceHorizon);\n\n        const farZ = (Math.cos(Math.PI / 2 - limitedPitchRadians) * topHalfMinDistance + lowestPlane) * 1.01;\n\n        // The larger the value of nearZ is\n        // - the more depth precision is available for features (good)\n        // - clipping starts appearing sooner when the camera is close to 3d features (bad)\n        //\n        // Other values work for mapbox-gl-js but deck.gl was encountering precision issues\n        // when rendering custom layers. This value was experimentally chosen and\n        // seems to solve z-fighting issues in deck.gl while not clipping buildings too close to the camera.\n        const nearZ = this._cameraState.height / 50;\n        return {nearZ, farZ};\n    }\n\n    /**\n     * @param nearFarZ - The depth range to use instead of computing one, by default the camera state's override.\n     * {@link GlobeTransform} passes the range of its vertical perspective child, so both children share one range.\n     */\n    _calcMatrices(nearFarZ: NearFarZ | null = this._cameraState.nearFarZOverride): void {\n        const offset = getCenterOffset(this._cameraState);\n        const worldCoordinateHelper = this.worldCoordinateHelper;\n        const point = projectToWorldCoordinates(getWorldSize(this._cameraState), this._cameraState.center, worldCoordinateHelper);\n        const x = point.x, y = point.y;\n\n        // Calculate the camera to sea-level distance in pixel in respect of terrain\n        const limitedPitchRadians = degreesToRadians(Math.min(getPitch(this._cameraState), maxMercatorHorizonAngle));\n        const cameraToSeaLevelDistance = Math.max(this._cameraState.cameraToCenterDistance / 2, this._cameraState.cameraToCenterDistance + this._cameraState.elevation * this._cameraState.pixelsPerMeter / Math.cos(limitedPitchRadians));\n\n        const {nearZ, farZ} = nearFarZ ?? this._calculateNearFarZ(cameraToSeaLevelDistance, limitedPitchRadians, offset);\n        this._nearZ = nearZ;\n        this._farZ = farZ;\n\n        // matrix for conversion from location to clip space(-1 .. 1)\n        let m: mat4;\n        m = new Float64Array(16);\n        mat4.perspective(m, this._cameraState.fovInRadians, this._cameraState.width / this._cameraState.height, this._nearZ, this._farZ);\n        this._invProjMatrix = new Float64Array(16);\n        fastInvertProjMat4(this._invProjMatrix, m);\n\n        // Apply center of perspective offset\n        m[8] = -offset.x * 2 / this._cameraState.width;\n        m[9] = offset.y * 2 / this._cameraState.height;\n        this._projectionMatrix = mat4.clone(m);\n\n        mat4.scale(m, m, [1, -1, 1]);\n        mat4.translate(m, m, [0, 0, -this._cameraState.cameraToCenterDistance]);\n        mat4.rotateZ(m, m, -this._cameraState.rollInRadians);\n        mat4.rotateX(m, m, this._cameraState.pitchInRadians);\n        mat4.rotateZ(m, m, -this._cameraState.bearingInRadians);\n        mat4.translate(m, m, [-x, -y, 0]);\n\n        // The mercatorMatrix can be used to transform points from mercator coordinates\n        // ([0, 0] nw, [1, 1] se) to clip space.\n        this._mercatorMatrix = mat4.scale([], m, [getWorldSize(this._cameraState), getWorldSize(this._cameraState), getWorldSize(this._cameraState)]);\n\n        // scale vertically to meters per pixel (inverse of ground resolution):\n        mat4.scale(m, m, [1, 1, this._cameraState.pixelsPerMeter]);\n\n        // matrix for conversion from world space to screen coordinates in 2D\n        this._pixelMatrix = mat4.multiply(new Float64Array(16), this._cameraState.clipSpaceToPixelsMatrix, m);\n\n        // matrix for conversion from world space to clip space (-1 .. 1)\n        mat4.translate(m, m, [0, 0, -this._cameraState.elevation]); // elevate camera over terrain\n        this._viewProjMatrix = m;\n        this._invViewProjMatrix = mat4.invert([], m);\n\n        const cameraPos: vec4 = [0, 0, -1, 1];\n        vec4.transformMat4(cameraPos, cameraPos, this._invViewProjMatrix);\n        this._cameraPosition = [\n            cameraPos[0] / cameraPos[3],\n            cameraPos[1] / cameraPos[3],\n            cameraPos[2] / cameraPos[3]\n        ];\n\n        // create a fog matrix, same es proj-matrix but with near clipping-plane in mapcenter\n        // needed to calculate a correct z-value for fog calculation, because projMatrix z value is not\n        this._fogMatrix = new Float64Array(16);\n        mat4.perspective(this._fogMatrix, this._cameraState.fovInRadians, this._cameraState.width / this._cameraState.height, cameraToSeaLevelDistance, this._farZ);\n        this._fogMatrix[8] = -offset.x * 2 / this._cameraState.width;\n        this._fogMatrix[9] = offset.y * 2 / this._cameraState.height;\n        mat4.scale(this._fogMatrix, this._fogMatrix, [1, -1, 1]);\n        mat4.translate(this._fogMatrix, this._fogMatrix, [0, 0, -this._cameraState.cameraToCenterDistance]);\n        mat4.rotateZ(this._fogMatrix, this._fogMatrix, -this._cameraState.rollInRadians);\n        mat4.rotateX(this._fogMatrix, this._fogMatrix, this._cameraState.pitchInRadians);\n        mat4.rotateZ(this._fogMatrix, this._fogMatrix, -this._cameraState.bearingInRadians);\n        mat4.translate(this._fogMatrix, this._fogMatrix, [-x, -y, 0]);\n        mat4.scale(this._fogMatrix, this._fogMatrix, [1, 1, this._cameraState.pixelsPerMeter]);\n        mat4.translate(this._fogMatrix, this._fogMatrix, [0, 0, -this._cameraState.elevation]); // elevate camera over terrain\n\n        // matrix for conversion from world space to screen coordinates in 3D\n        this._pixelMatrix3D = mat4.multiply(new Float64Array(16), this._cameraState.clipSpaceToPixelsMatrix, m);\n\n        // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles.\n        // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional\n        // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension\n        // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle\n        // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that\n        // it is always <= 0.5 pixels.\n        const xShift = (this._cameraState.width % 2) / 2, yShift = (this._cameraState.height % 2) / 2,\n            angleCos = Math.cos(this._cameraState.bearingInRadians), angleSin = Math.sin(-this._cameraState.bearingInRadians),\n            dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift,\n            dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;\n        const alignedM = new Float64Array(m) as any as mat4;\n        mat4.translate(alignedM, alignedM, [dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0]);\n        this._alignedProjMatrix = alignedM;\n\n        // inverse matrix for conversion from screen coordinates to location\n        m = mat4.invert(new Float64Array(16), this._pixelMatrix);\n        if (!m) throw new Error('failed to invert matrix');\n        this._pixelMatrixInverse = m;\n\n        this._clearMatrixCaches();\n    }\n\n    private _clearMatrixCaches(): void {\n        this._posMatrixCache.clear();\n        this._alignedPosMatrixCache.clear();\n        this._fogMatrixCacheF32.clear();\n    }\n\n    maxPitchScaleFactor(): number {\n        // calcMatrices hasn't run yet\n        if (!this._pixelMatrixInverse) return 1;\n\n        const coord = this.screenPointToMercatorCoordinate(new Point(0, 0));\n        const p = [coord.x * getWorldSize(this._cameraState), coord.y * getWorldSize(this._cameraState), 0, 1] as vec4;\n        const topPoint = vec4.transformMat4(p, p, this._pixelMatrix);\n        return topPoint[3] / this._cameraState.cameraToCenterDistance;\n    }\n\n    getCameraPoint(): Point {\n        return this._helper.getCameraPoint();\n    }\n\n    getCameraAltitude(): number {\n        return Math.cos(this._cameraState.pitchInRadians) * this._cameraState.cameraToCenterDistance / this._cameraState.pixelsPerMeter + this._cameraState.elevation;\n    }\n\n    getCameraLngLat(): LngLat {\n        const worldCoordinateHelper = this.worldCoordinateHelper;\n        const center = this._cameraState.center;\n        const mercUnitsPerMeter = worldCoordinateHelper.worldZFromAltitude(1, center);\n        const pixelPerMeter = mercUnitsPerMeter * getWorldSize(this._cameraState);\n        const cameraToCenterDistanceMeters = this._cameraState.cameraToCenterDistance / pixelPerMeter;\n        const centerMercator = worldCoordinateHelper.worldFromLngLat(center.lng, center.lat, this._cameraState.elevation);\n        const camMercator = cameraMercatorCoordinateFromCenterAndRotation(centerMercator, getPitch(this._cameraState), getBearing(this._cameraState), cameraToCenterDistanceMeters * mercUnitsPerMeter);\n        return worldCoordinateHelper.lngLatFromWorld(camMercator.x, camMercator.y);\n    }\n\n    getProjectionData(params: ProjectionDataParams): RendererProjectionData {\n        const {overscaledTileID, aligned, applyTerrainMatrix} = params;\n        const mercatorTileCoordinates = getMercatorTileCoordinates(overscaledTileID);\n        const tilePosMatrix = overscaledTileID ? this.calculatePosMatrix(overscaledTileID, aligned, true) : null;\n\n        let mainMatrix: Mat4f32;\n        if (overscaledTileID?.terrainRttPosMatrix32f && applyTerrainMatrix) {\n            mainMatrix = overscaledTileID.terrainRttPosMatrix32f;\n        } else if (tilePosMatrix) {\n            mainMatrix = tilePosMatrix; // This matrix should be float32\n        } else {\n            mainMatrix = createIdentityMat4f32();\n        }\n        return {\n            mainMatrix, // Might be set to a custom matrix by different projections.\n            tileMercatorCoords: mercatorTileCoordinates,\n            clippingPlane: [0, 0, 0, 0],\n            projectionTransition: 0.0, // Range 0..1, where 0 is mercator, 1 is another projection, mostly globe.\n            fallbackMatrix: mainMatrix,\n            clipAntimeridian: false,\n        };\n    }\n\n    /** {@inheritDoc ITransform.isLocationOccluded} */\n    isLocationOccluded(lngLat: LngLat, terrain?: Terrain, elevation?: number): boolean {\n        if (!terrain?.getCoverageIndex()) return false;\n\n        const location = this.worldCoordinateHelper.worldFromLngLat(lngLat.lng, lngLat.lat);\n        elevation ??= terrain.getElevationForLngLat(lngLat, this._cameraState.tileZoom);\n        const clip = this._coordinateClipPoint(location, elevation, this._pixelMatrix3D);\n        const w = clip[3];\n        if (w <= 0 || clip[2] > w) return true;\n        const p = new Point(clip[0] / w, clip[1] / w);\n\n        const hit = this.screenTerrainPointToMercatorCoordinate(p, terrain);\n        if (hit == null) return false;\n        const segment = this.getRaySegmentFromPixel(p, NEAR_PLANE_CLIP_Z);\n        const tLocation = raySegmentParameter(segment, location.x * getWorldSize(this._cameraState), location.y * getWorldSize(this._cameraState), elevation);\n        return raySegmentParameter(segment, hit.x * getWorldSize(this._cameraState), hit.y * getWorldSize(this._cameraState), hit.z) < tLocation * (1 - TERRAIN_OCCLUSION_MARGIN);\n    }\n\n    getPixelScale(): number {\n        return 1.0;\n    }\n\n    getCircleRadiusCorrection(): number {\n        return 1.0;\n    }\n\n    getPitchedTextCorrection(_textAnchorX: number, _textAnchorY: number, _tileID: UnwrappedTileID): number {\n        return 1.0;\n    }\n\n    transformLightDirection(dir: vec3): vec3 {\n        return vec3.clone(dir);\n    }\n\n    getRayDirectionFromPixel(_p: Point): vec3 {\n        throw new Error('Not implemented.'); // No need for this in mercator transform\n    }\n\n    projectTileCoordinates(x: number, y: number, unwrappedTileID: UnwrappedTileID, elevation?: number): PointProjection {\n        const matrix = this.calculatePosMatrix(unwrappedTileID);\n        let pos;\n        if (elevation != null) { // slow because of handle z-index\n            pos = [x, y, elevation, 1] as vec4;\n            vec4.transformMat4(pos, pos, matrix);\n        } else { // fast because of ignore z-index\n            pos = [x, y, 0, 1] as vec4;\n            xyTransformMat4(pos, pos, matrix);\n        }\n        const w = pos[3];\n        return {\n            point: new Point(pos[0] / w, pos[1] / w),\n            signedDistanceFromCamera: w,\n            isOccluded: false\n        };\n    }\n\n    getProjectionDataForCustomLayer(applyGlobeMatrix: boolean = true): CustomLayerProjectionData {\n        const tileID = new OverscaledTileID(0, 0, 0, 0, 0);\n        const rendererProjectionData = this.getProjectionData({overscaledTileID: tileID, applyGlobeMatrix});\n        const tileMatrix = calculateTileMatrix(tileID, getWorldSize(this._cameraState));\n        mat4.multiply(tileMatrix, this._viewProjMatrix, tileMatrix);\n\n        // Even though we requested projection data for the mercator base tile which covers the entire mercator range,\n        // the shader projection machinery still expects inputs to be in tile units range [0..EXTENT].\n        // Since custom layers are expected to supply mercator coordinates [0..1], we need to rescale\n        // both matrices by EXTENT. We also need to rescale Z.\n\n        const scale: vec3 = [EXTENT, EXTENT, getWorldSize(this._cameraState) / this._cameraState.pixelsPerMeter];\n\n        // We pass full-precision 64bit float matrices to custom layers to prevent precision loss in case the user wants to do further transformations.\n        // Otherwise we get very visible precision-artifacts and twitching for objects that are bulding-scale.\n        const projectionMatrixScaled = createMat4f64();\n        mat4.scale(projectionMatrixScaled, tileMatrix, scale);\n\n        return {\n            ...rendererProjectionData,\n            tileMercatorCoords: [0, 0, 1, 1],\n            fallbackMatrix: projectionMatrixScaled,\n            mainMatrix: projectionMatrixScaled,\n        };\n    }\n\n    getFastPathSimpleProjectionMatrix(tileID: OverscaledTileID): mat4 {\n        return this.calculatePosMatrix(tileID);\n    }\n}\n\n/**\n * Creates a transform for the mercator projection.\n */\nexport function createMercatorTransform(options?: TransformOptions): MercatorTransform {\n    return new MercatorTransform(options);\n}\n\nfunction mercatorSampleAt(ray: MercatorRay, t: number): TerrainSample {\n    return sampleAt(ray.index, ray.exaggeration, (ray.near[0] + t * ray.dx) / ray.worldSize, (ray.near[1] + t * ray.dy) / ray.worldSize, ray.wraps);\n}\n\nfunction mercatorIsBelowTerrain(ray: MercatorRay, t: number): boolean {\n    return isBelowTerrainSample(mercatorSampleAt(ray, t), ray.near[2] + t * ray.dz);\n}\n\n/**\n * Where the point of `segment` closest to the given world pixel position and elevation lies along it,\n * as the fraction from `near` (0) to `far` (1).\n */\nfunction raySegmentParameter({near, far}: RaySegment, worldX: number, worldY: number, elevation: number): number {\n    const dx = far[0] - near[0];\n    const dy = far[1] - near[1];\n    const dz = far[2] - near[2];\n    return ((worldX - near[0]) * dx + (worldY - near[1]) * dy + (elevation - near[2]) * dz) / (dx * dx + dy * dy + dz * dz);\n}\n", "import Point from '@mapbox/point-geometry';\nimport {clamp, degreesToRadians, getRollPitchBearing, MAX_VALID_LATITUDE, type RollPitchBearing, rollPitchBearingToQuat, scaleZoom, warnOnce, zoomScale} from '../../util/util.ts';\nimport {quat} from 'gl-matrix';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {lngLatBoxToWorldSamples, projectToWorldCoordinates, unprojectFromWorldCoordinates} from './mercator_utils.ts';\n\nimport type {IReadonlyTransform, ITransform} from '../transform_interface.ts';\nimport type {LngLat, LngLatLike} from '../lng_lat.ts';\nimport type {CameraForBoundsOptions, PointLike} from '../../ui/camera.ts';\nimport type {PaddingOptions} from '../edge_insets.ts';\nimport type {LngLatBounds} from '../lng_lat_bounds.ts';\n\nexport type MapControlsDeltas = {\n    panDelta: Point;\n    zoomDelta: number;\n    bearingDelta: number;\n    pitchDelta: number;\n    rollDelta: number;\n    around: Point;\n    /**\n     * Elevation in meters of the terrain under `around` at gesture start; when set,\n     * pan and zoom keep the terrain at this elevation under `around`.\n     */\n    aroundElevation?: number;\n};\n\nexport type CameraForBoxAndBearingHandlerResult = {\n    center: LngLat;\n    zoom: number;\n    bearing: number;\n};\n\nexport type EaseToHandlerOptions = {\n    bearing: number;\n    pitch: number;\n    roll: number;\n    padding: PaddingOptions;\n    offsetAsPoint: Point;\n    around?: LngLat;\n    aroundPoint?: Point;\n    center?: LngLatLike;\n    zoom?: number;\n    offset?: PointLike;\n};\n\nexport type EaseToHandlerResult = {\n    easeFunc: (k: number) => void;\n    /**\n     * The map center when the animation ends.\n     */\n    elevationCenter: LngLat;\n    isZooming: boolean;\n};\n\nexport type FlyToHandlerOptions = {\n    bearing: number;\n    pitch: number;\n    roll: number;\n    padding: PaddingOptions;\n    offsetAsPoint: Point;\n    center?: LngLatLike;\n    locationAtOffset: LngLat;\n    zoom?: number;\n    minZoom?: number;\n};\n\nexport type FlyToHandlerResult = {\n    easeFunc: (k: number, scale: number, centerFactor: number, pointAtOffset: Point) => void;\n    scaleOfZoom: number;\n    scaleOfMinZoom: number;\n    /**\n     * The map center when the animation ends.\n     */\n    targetCenter: LngLat;\n    pixelPathLength: number;\n};\n\nexport type UpdateRotationArgs = {\n    /**\n     * The starting Euler angles.\n     */\n    startEulerAngles: RollPitchBearing;\n\n    /**\n     * The end Euler angles.\n     */\n    endEulerAngles: RollPitchBearing;\n\n    /**\n     * The transform to be updated\n     */\n    tr: ITransform;\n\n    /**\n     * The interpolation fraction, between 0 and 1.\n     */\n    k: number;\n\n    /**\n     * If true, use spherical linear interpolation. If false, use linear interpolation of Euler angles.\n     */\n    useSlerp: boolean;\n};\n\n/**\n * @internal\n */\nexport function cameraBoundsWarning(): void {\n    warnOnce(\n        'Map cannot fit within canvas with the given bounds, padding, and/or offset.'\n    );\n}\n\n/**\n * @internal\n * Contains projection-specific functions related to camera controls, easeTo, flyTo, inertia, etc.\n */\nexport interface ICameraHelper {\n    get useGlobeControls(): boolean;\n\n    handlePanInertia(pan: Point, transform: IReadonlyTransform): {\n        easingCenter: LngLat;\n        easingOffset: Point;\n    };\n\n    handleMapControlsRollPitchBearingZoom(deltas: MapControlsDeltas, tr: ITransform): void;\n\n    handleMapControlsPan(deltas: MapControlsDeltas, tr: ITransform, preZoomAroundLoc: LngLat): void;\n\n    /**\n     * @param fitPadding - The `padding` option of `cameraForBounds`: the space wanted around the bounds.\n     * @param mapPadding - The map's own padding, as in `map.getPadding()`, which the bounds must also stay clear of.\n     */\n    cameraForBoxAndBearing(options: CameraForBoundsOptions, fitPadding: PaddingOptions, mapPadding: PaddingOptions, bounds: LngLatBounds, bearing: number, tr: IReadonlyTransform): CameraForBoxAndBearingHandlerResult;\n\n    handleJumpToCenterZoom(tr: ITransform, options: { zoom?: number; center?: LngLatLike }): void;\n\n    handleEaseTo(tr: ITransform, options: EaseToHandlerOptions): EaseToHandlerResult;\n\n    handleFlyTo(tr: ITransform, options: FlyToHandlerOptions): FlyToHandlerResult;\n}\n\n/**\n * @internal\n * Set a transform's rotation to a value interpolated between startEulerAngles and endEulerAngles\n */\nexport function updateRotation(args: UpdateRotationArgs): void {\n    if (args.useSlerp) {\n        // At pitch ==0, the Euler angle representation is ambiguous. In this case, set the Euler angles\n        // to the representation requested by the caller\n        if (args.k < 1) {\n            const startRotation = rollPitchBearingToQuat(args.startEulerAngles.roll, args.startEulerAngles.pitch, args.startEulerAngles.bearing);\n            const endRotation = rollPitchBearingToQuat(args.endEulerAngles.roll, args.endEulerAngles.pitch, args.endEulerAngles.bearing);\n            const rotation: quat = new Float64Array(4);\n            quat.slerp(rotation, startRotation, endRotation, args.k);\n            const eulerAngles = getRollPitchBearing(rotation);\n            args.tr.setRoll(eulerAngles.roll);\n            args.tr.setPitch(eulerAngles.pitch);\n            args.tr.setBearing(eulerAngles.bearing);\n        } else {\n            args.tr.setRoll(args.endEulerAngles.roll);\n            args.tr.setPitch(args.endEulerAngles.pitch);\n            args.tr.setBearing(args.endEulerAngles.bearing);\n        }\n    } else {\n        args.tr.setRoll(interpolates.number(args.startEulerAngles.roll, args.endEulerAngles.roll, args.k));\n        args.tr.setPitch(interpolates.number(args.startEulerAngles.pitch, args.endEulerAngles.pitch, args.k));\n        args.tr.setBearing(interpolates.number(args.startEulerAngles.bearing, args.endEulerAngles.bearing, args.k));\n    }\n}\n\nexport function cameraForBoxAndBearing(options: CameraForBoundsOptions, fitPadding: PaddingOptions, mapPadding: PaddingOptions, bounds: LngLatBounds, bearing: number, tr: IReadonlyTransform): CameraForBoxAndBearingHandlerResult {\n    // Fit the whole box, not only its corners: rotate the points sampled over it by the bearing and take\n    // the rectangle around them in the rotated frame, grown by how far the edges bulge past the points.\n\n    const worldCoordinateHelper = tr.worldCoordinateHelper;\n    const nwWorld = projectToWorldCoordinates(tr.worldSize, bounds.getNorthWest(), worldCoordinateHelper);\n    const neWorld = projectToWorldCoordinates(tr.worldSize, bounds.getNorthEast(), worldCoordinateHelper);\n    const seWorld = projectToWorldCoordinates(tr.worldSize, bounds.getSouthEast(), worldCoordinateHelper);\n    const swWorld = projectToWorldCoordinates(tr.worldSize, bounds.getSouthWest(), worldCoordinateHelper);\n    const [south, north] = worldCoordinateHelper.wraps ?\n        [clamp(bounds.getSouth(), -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE), clamp(bounds.getNorth(), -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE)] :\n        [bounds.getSouth(), bounds.getNorth()];\n    const {points, bulge} = lngLatBoxToWorldSamples(worldCoordinateHelper, bounds.getWest(), south, bounds.getEast(), north);\n\n    const bearingRadians = degreesToRadians(-bearing);\n\n    let minX = Infinity;\n    let minY = Infinity;\n    let maxX = -Infinity;\n    let maxY = -Infinity;\n    for (const point of points) {\n        const {x, y} = point.mult(tr.worldSize).rotate(bearingRadians);\n        if (x < minX) minX = x;\n        if (y < minY) minY = y;\n        if (x > maxX) maxX = x;\n        if (y > maxY) maxY = y;\n    }\n    const worldBulge = bulge * tr.worldSize;\n    const upperRight = new Point(maxX + worldBulge, maxY + worldBulge);\n    const lowerLeft = new Point(minX - worldBulge, minY - worldBulge);\n\n    // Calculate zoom: consider the original bbox and both paddings.\n    const size = upperRight.sub(lowerLeft);\n\n    const availableWidth = (tr.width - (mapPadding.left + mapPadding.right + fitPadding.left + fitPadding.right));\n    const availableHeight = (tr.height - (mapPadding.top + mapPadding.bottom + fitPadding.top + fitPadding.bottom));\n    const scaleX = availableWidth / size.x;\n    const scaleY = availableHeight / size.y;\n\n    // A box reaching a point the projection sends to infinity has no finite size to fit.\n    if (scaleY < 0 || scaleX < 0 || !Number.isFinite(size.x) || !Number.isFinite(size.y)) {\n        cameraBoundsWarning();\n        return undefined;\n    }\n\n    const zoom = Math.min(scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);\n\n    // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of the fit padding.\n    const offset = Point.convert(options.offset);\n    const paddingOffsetX = (fitPadding.left - fitPadding.right) / 2;\n    const paddingOffsetY = (fitPadding.top - fitPadding.bottom) / 2;\n    const paddingOffset = new Point(paddingOffsetX, paddingOffsetY);\n    const rotatedPaddingOffset = paddingOffset.rotate(degreesToRadians(bearing));\n    const offsetAtInitialZoom = offset.add(rotatedPaddingOffset);\n    const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / zoomScale(zoom));\n\n    // The middle of the fitted rectangle, rotated back. For a box that projects to a parallelogram, as every box\n    // does in mercator, that is the midpoint of its diagonal, taken directly to keep rotation rounding out of it.\n    const projectsToParallelogram = bulge === 0 && nwWorld.add(seWorld).equals(neWorld.add(swWorld));\n    const middle = projectsToParallelogram ? nwWorld.add(seWorld).div(2) : upperRight.add(lowerLeft).div(2).rotate(-bearingRadians);\n    const center = unprojectFromWorldCoordinates(\n        tr.worldSize,\n        middle.sub(offsetAtFinalZoom),\n        worldCoordinateHelper\n    );\n\n    return {\n        center,\n        zoom,\n        bearing\n    };\n}\n", "import {LngLat, type LngLatLike} from '../lng_lat.ts';\nimport {cameraForBoxAndBearing, type CameraForBoxAndBearingHandlerResult, type EaseToHandlerResult, type EaseToHandlerOptions, type FlyToHandlerResult, type FlyToHandlerOptions, type ICameraHelper, type MapControlsDeltas, updateRotation} from './camera_helper.ts';\nimport {normalizeCenter} from '../transform_helper.ts';\nimport {rollPitchBearingEqual, scaleZoom, zoomScale} from '../../util/util.ts';\nimport {getMercatorHorizon, projectToWorldCoordinates, unprojectFromWorldCoordinates} from './mercator_utils.ts';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {IReadonlyTransform, ITransform} from '../transform_interface.ts';\nimport type {CameraForBoundsOptions} from '../../ui/camera.ts';\nimport type {PaddingOptions} from '../edge_insets.ts';\nimport type {LngLatBounds} from '../lng_lat_bounds.ts';\n\n/**\n * @internal\n */\nexport class MercatorCameraHelper implements ICameraHelper {\n    get useGlobeControls(): boolean { return false; }\n\n    handlePanInertia(pan: Point, transform: IReadonlyTransform): {\n        easingCenter: LngLat;\n        easingOffset: Point;\n    } {\n        // Reduce the offset so that it never goes past the horizon. If it goes past\n        // the horizon, the pan direction is opposite of the intended direction.\n        const offsetLength = pan.mag();\n        const pixelsToHorizon = Math.abs(getMercatorHorizon(transform));\n        const horizonFactor = 0.75; // Must be < 1 to prevent the offset from crossing the horizon\n        const offsetAsPoint = pan.mult(Math.min(pixelsToHorizon * horizonFactor / offsetLength, 1.0));\n        return {\n            easingOffset: offsetAsPoint,\n            easingCenter: transform.center,\n        };\n    }\n\n    handleMapControlsRollPitchBearingZoom(deltas: MapControlsDeltas, tr: ITransform): void {\n        if (deltas.bearingDelta) tr.setBearing(tr.bearing + deltas.bearingDelta);\n        if (deltas.pitchDelta) tr.setPitch(tr.pitch + deltas.pitchDelta);\n        if (deltas.rollDelta) tr.setRoll(tr.roll + deltas.rollDelta);\n        if (deltas.zoomDelta) tr.setZoom(tr.zoom + deltas.zoomDelta);\n    }\n\n    handleMapControlsPan(deltas: MapControlsDeltas, tr: ITransform, preZoomAroundLoc: LngLat): void {\n        // If we are rotating about the center point, there is no need to update the transform center. Doing so causes\n        // a small amount of drift of the center point, especially when pitch is close to 90 degrees.\n        // In this case, return early.\n        if (deltas.around.distSqr(tr.centerPoint) < 1.0e-2) {\n            return;\n        }\n        tr.setLocationAtPoint(preZoomAroundLoc, deltas.around, deltas.aroundElevation);\n    }\n\n    cameraForBoxAndBearing(options: CameraForBoundsOptions, fitPadding: PaddingOptions, mapPadding: PaddingOptions, bounds: LngLatBounds, bearing: number, tr: IReadonlyTransform): CameraForBoxAndBearingHandlerResult {\n        return cameraForBoxAndBearing(options, fitPadding, mapPadding, bounds, bearing, tr);\n    }\n\n    handleJumpToCenterZoom(tr: ITransform, options: { zoom?: number; center?: LngLatLike }): void {\n        // Mercator zoom & center handling.\n        const optionsZoom = typeof options.zoom !== 'undefined';\n\n        const zoom = optionsZoom ? +options.zoom : tr.zoom;\n        if (tr.zoom !== zoom) {\n            tr.setZoom(+options.zoom);\n        }\n\n        if (options.center !== undefined) {\n            tr.setCenter(LngLat.convert(options.center));\n        }\n    }\n\n    handleEaseTo(tr: ITransform, options: EaseToHandlerOptions): EaseToHandlerResult {\n        const startZoom = tr.zoom;\n        const startPadding = tr.padding;\n        const startEulerAngles = {roll: tr.roll, pitch: tr.pitch, bearing: tr.bearing};\n        const endRoll = options.roll === undefined ? tr.roll : options.roll;\n        const endPitch = options.pitch === undefined ? tr.pitch : options.pitch;\n        const endBearing = options.bearing === undefined ? tr.bearing : options.bearing;\n        const endEulerAngles = {roll: endRoll, pitch: endPitch, bearing: endBearing};\n\n        const optionsZoom = typeof options.zoom !== 'undefined';\n\n        const doPadding = !tr.isPaddingEqual(options.padding);\n\n        let isZooming = false;\n\n        const zoom = optionsZoom ? +options.zoom : tr.zoom;\n\n        let pointAtOffset = tr.centerPoint.add(options.offsetAsPoint);\n        const locationAtOffset = tr.screenPointToLocation(pointAtOffset);\n        const {center, zoom: endZoom} = tr.applyConstrain(\n            LngLat.convert(options.center || locationAtOffset),\n            zoom ?? startZoom\n        );\n        normalizeCenter(tr, center);\n\n        const worldCoordinateHelper = tr.worldCoordinateHelper;\n        const from = projectToWorldCoordinates(tr.worldSize, locationAtOffset, worldCoordinateHelper);\n        const delta = projectToWorldCoordinates(tr.worldSize, center, worldCoordinateHelper).sub(from);\n\n        const finalScale = zoomScale(endZoom - startZoom);\n        isZooming = (endZoom !== startZoom);\n\n        const easeFunc = (k: number) => {\n            if (isZooming) {\n                tr.setZoom(interpolates.number(startZoom, endZoom, k));\n            }\n            if (!rollPitchBearingEqual(startEulerAngles, endEulerAngles)) {\n                updateRotation({\n                    startEulerAngles,\n                    endEulerAngles,\n                    tr,\n                    k,\n                    useSlerp: startEulerAngles.roll != endEulerAngles.roll});\n            }\n            if (doPadding) {\n                tr.interpolatePadding(startPadding, options.padding, k);\n                // When padding is being applied, Transform.centerPoint is changing continuously,\n                // thus we need to recalculate offsetPoint every frame\n                pointAtOffset = tr.centerPoint.add(options.offsetAsPoint);\n            }\n\n            if (options.around) {\n                tr.setLocationAtPoint(options.around, options.aroundPoint);\n            } else {\n                const scale = zoomScale(tr.zoom - startZoom);\n                const base = endZoom > startZoom ?\n                    Math.min(2, finalScale) :\n                    Math.max(0.5, finalScale);\n                const speedup = Math.pow(base, 1 - k);\n                const newCenterWorld = from.add(delta.mult(k * speedup)).mult(scale);\n                const newCenter = unprojectFromWorldCoordinates(tr.worldSize, newCenterWorld, worldCoordinateHelper);\n                tr.setLocationAtPoint(tr.renderWorldCopies && worldCoordinateHelper.wraps ? newCenter.wrap() : newCenter, pointAtOffset);\n            }\n        };\n\n        const endTransform = this._transformAtAnimationEnd(tr, endZoom, endEulerAngles, options.padding);\n        if (options.around) {\n            endTransform.setLocationAtPoint(options.around, options.aroundPoint);\n        } else {\n            endTransform.setLocationAtPoint(center, endTransform.centerPoint.add(options.offsetAsPoint));\n        }\n\n        return {\n            easeFunc,\n            isZooming,\n            elevationCenter: endTransform.center,\n        };\n    }\n\n    handleFlyTo(tr: ITransform, options: FlyToHandlerOptions): FlyToHandlerResult {\n        const optionsZoom = typeof options.zoom !== 'undefined';\n\n        const startZoom = tr.zoom;\n\n        // Obtain target center and zoom\n        const constrained = tr.applyConstrain(\n            LngLat.convert(options.center || options.locationAtOffset),\n            optionsZoom ? +options.zoom : startZoom\n        );\n        const constrainedCenter = constrained.center;\n        const targetZoom = constrained.zoom;\n\n        normalizeCenter(tr, constrainedCenter);\n\n        const worldCoordinateHelper = tr.worldCoordinateHelper;\n        const startWorldSize = tr.worldSize;\n        const from = projectToWorldCoordinates(startWorldSize, options.locationAtOffset, worldCoordinateHelper);\n        const delta = projectToWorldCoordinates(startWorldSize, constrainedCenter, worldCoordinateHelper).sub(from);\n\n        const pixelPathLength = delta.mag();\n\n        const scaleOfZoom = zoomScale(targetZoom - startZoom);\n\n        const requestedMinZoom = typeof options.minZoom !== 'undefined' ? +options.minZoom : tr.minZoom;\n        const effectiveMinZoom = Math.max(requestedMinZoom, tr.minZoom);\n        const minZoomPreConstrain = Math.min(effectiveMinZoom, startZoom, targetZoom);\n        const minZoom = tr.applyConstrain(constrainedCenter, minZoomPreConstrain).zoom;\n        const scaleOfMinZoom = zoomScale(minZoom - startZoom);\n\n        const easeFunc = (k: number, scale: number, centerFactor: number, pointAtOffset: Point) => {\n            tr.setZoom(k === 1 ? targetZoom : startZoom + scaleZoom(scale));\n            const newCenter = k === 1\n                ? constrainedCenter\n                : unprojectFromWorldCoordinates(startWorldSize, from.add(delta.mult(centerFactor)), worldCoordinateHelper);\n            tr.setLocationAtPoint(tr.renderWorldCopies && worldCoordinateHelper.wraps ? newCenter.wrap() : newCenter, pointAtOffset);\n        };\n\n        const endTransform = this._transformAtAnimationEnd(tr, targetZoom, {roll: options.roll, pitch: options.pitch, bearing: options.bearing}, options.padding);\n        endTransform.setLocationAtPoint(constrainedCenter, endTransform.centerPoint.add(options.offsetAsPoint));\n\n        return {\n            easeFunc,\n            scaleOfZoom,\n            targetCenter: endTransform.center,\n            scaleOfMinZoom,\n            pixelPathLength,\n        };\n    }\n\n    /**\n     * A copy of the transform at the animation's end zoom, angles and padding, for reading where the map center\n     * ends up once a location is placed at its screen point.\n     */\n    private _transformAtAnimationEnd(tr: ITransform, zoom: number, angles: {roll: number; pitch: number; bearing: number}, padding: PaddingOptions): ITransform {\n        const endTransform = tr.clone();\n        endTransform.setZoom(zoom);\n        endTransform.setRoll(angles.roll);\n        endTransform.setPitch(angles.pitch);\n        endTransform.setBearing(angles.bearing);\n        endTransform.setPadding(padding);\n        return endTransform;\n    }\n}\n", "// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.\n/* eslint-disable */\n\nimport {latest as styleSpec} from '@maplibre/maplibre-gl-style-spec';\n\nimport {\n    Properties,\n    DataConstantProperty,\n    DataDrivenProperty,\n    CrossFadedDataDrivenProperty,\n    CrossFadedProperty,\n    ColorRampProperty,\n    PossiblyEvaluatedPropertyValue,\n    CrossFaded\n} from './properties.ts';\n\nimport type {Color, Formatted, Padding, NumberArray, ColorArray, ResolvedImage, VariableAnchorOffsetCollection, ProjectionDefinitionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {StylePropertySpecification} from '@maplibre/maplibre-gl-style-spec';\n\n\nexport type ProjectionProps = {\n    \"type\": DataConstantProperty<ProjectionDefinitionSpecification>,\n};\n\nexport type ProjectionPropsPossiblyEvaluated = {\n    \"type\": ProjectionDefinitionSpecification,\n};\n\nlet properties: Properties<ProjectionProps>;\nexport const getProperties = (): Properties<ProjectionProps> => properties = properties || new Properties({\n    \"type\": new DataConstantProperty(styleSpec[\"projection\"][\"type\"] as any as StylePropertySpecification, \"type\"),\n});", "import {SubdivisionGranularityExpression, SubdivisionGranularitySetting} from '../../render/subdivision_granularity_settings.ts';\nimport {type PreparedShader, shaders} from '../../shaders/shaders.ts';\nimport {createTileMeshWithBuffers, type CreateTileMeshOptions} from '../../util/create_tile_mesh.ts';\nimport {mercatorWorldCoordinateHelper} from '../mercator_coordinate.ts';\n\nimport type {EvaluationParameters} from '../../style/evaluation_parameters.ts';\nimport type {Mesh} from '../../render/mesh.ts';\nimport type {Projection, TileMeshUsage} from './projection.ts';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {WorldCoordinateHelper} from '../transform_interface.ts';\n\nexport const VerticalPerspectiveShaderDefine = '#define GLOBE';\nexport const VerticalPerspectiveShaderVariantKey = 'globe';\n\nconst granularitySettingsGlobe: SubdivisionGranularitySetting = new SubdivisionGranularitySetting({\n    fill: new SubdivisionGranularityExpression(128, 2),\n    line: new SubdivisionGranularityExpression(512, 0),\n    // Always keep at least some subdivision on raster tiles, etc,\n    // otherwise they will be visibly warped at high zooms (before mercator transition).\n    // This si not needed on fill, because fill geometry tends to already be\n    // highly tessellated and granular at high zooms.\n    tile: new SubdivisionGranularityExpression(128, 32),\n    // Stencil granularity must never be higher than fill granularity,\n    // otherwise we would get seams in the oceans at zoom levels where\n    // stencil has higher granularity than fill.\n    stencil: new SubdivisionGranularityExpression(128, 1),\n    circle: 3\n});\n\nexport class VerticalPerspectiveProjection implements Projection {\n    private _tileMeshCache: {[_: string]: Mesh} = {};\n\n    get name(): 'vertical-perspective' {\n        return 'vertical-perspective';\n    }\n\n    /**\n     * The globe draws mercator tiles on a sphere, so the plane its tiles sit in is mercator's. A CRS registered\n     * with `addProjection` is flat only; the factory never builds this projection over one.\n     */\n    get worldCoordinateHelper(): WorldCoordinateHelper {\n        return mercatorWorldCoordinateHelper;\n    }\n\n    get transitionState(): number {\n        return 1;\n    }\n\n    get useSubdivision(): boolean {\n        return true;\n    }\n\n    get shaderVariantName(): string {\n        return VerticalPerspectiveShaderVariantKey;\n    }\n\n    get shaderDefine(): string {\n        return VerticalPerspectiveShaderDefine;\n    }\n\n    get shaderPreludeCode(): PreparedShader {\n        return shaders.projectionGlobe;\n    }\n\n    get vertexShaderPreludeCode(): string {\n        return shaders.projectionMercator.vertexSource;\n    }\n\n    get subdivisionGranularity(): SubdivisionGranularitySetting {\n        return granularitySettingsGlobe;\n    }\n\n    get useGlobeControls(): boolean {\n        return true;\n    }\n\n    public destroy(): void {\n        // Do nothing.\n    }\n\n    private _getMeshKey(options: CreateTileMeshOptions): string {\n        return `${options.granularity.toString(36)}_${options.generateBorders ? 'b' : ''}${options.extendToNorthPole ? 'n' : ''}${options.extendToSouthPole ? 's' : ''}`;\n    }\n\n    public getMeshFromTileID(context: Context, canonical: CanonicalTileID, hasBorder: boolean, allowPoles: boolean, usage: TileMeshUsage): Mesh {\n        // Stencil granularity must match fill granularity\n        const granularityConfig = usage === 'stencil' ? granularitySettingsGlobe.stencil : granularitySettingsGlobe.tile;\n        const granularity = granularityConfig.getGranularityForZoomLevel(canonical.z);\n        const north = (canonical.y === 0) && allowPoles;\n        const south = (canonical.y === (1 << canonical.z) - 1) && allowPoles;\n        return this._getMesh(context, {\n            granularity,\n            generateBorders: hasBorder,\n            extendToNorthPole: north,\n            extendToSouthPole: south,\n        });\n    }\n\n    private _getMesh(context: Context, options: CreateTileMeshOptions): Mesh {\n        const key = this._getMeshKey(options);\n\n        if (key in this._tileMeshCache) {\n            return this._tileMeshCache[key];\n        }\n\n        const mesh = createTileMeshWithBuffers(context, options);\n        this._tileMeshCache[key] = mesh;\n        return mesh;\n    }\n\n    recalculate(_params: EvaluationParameters): void {\n        // Do nothing.\n    }\n\n    hasTransition(): boolean {\n        return false;\n    }\n}", "import {ProjectionDefinition, type ProjectionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {type PossiblyEvaluated, Transitionable, type Transitioning, type TransitionParameters} from '../../style/properties.ts';\nimport {getProperties, type ProjectionProps, type ProjectionPropsPossiblyEvaluated} from '../../style/projection_properties.g.ts';\nimport {Evented} from '../../util/evented.ts';\nimport {EvaluationParameters} from '../../style/evaluation_parameters.ts';\nimport {MercatorProjection} from './mercator_projection.ts';\nimport {VerticalPerspectiveProjection} from './vertical_perspective_projection.ts';\n\nimport type {Projection, TileMeshUsage} from './projection.ts';\nimport type {PreparedShader} from '../../shaders/shaders.ts';\nimport type {SubdivisionGranularitySetting} from '../../render/subdivision_granularity_settings.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {CanonicalTileID} from '../../tile/tile_id.ts';\nimport type {Mesh} from '../../render/mesh.ts';\nimport type {WorldCoordinateHelper} from '../transform_interface.ts';\n\nexport class GlobeProjection extends Evented implements Projection {\n    properties: PossiblyEvaluated<ProjectionProps, ProjectionPropsPossiblyEvaluated>;\n\n    _transitionable: Transitionable<ProjectionProps>;\n    _transitioning: Transitioning<ProjectionProps>;\n    _mercatorProjection: MercatorProjection;\n    _verticalPerspectiveProjection: VerticalPerspectiveProjection;\n\n    constructor(projection: ProjectionSpecification | undefined, globalState: Record<string, any>) {\n        super();\n        this._transitionable = new Transitionable(getProperties(), 'projection', globalState);\n        this.setProjection(projection);\n        this._transitioning = this._transitionable.untransitioned();\n        this.recalculate(new EvaluationParameters(0));\n        this._mercatorProjection = new MercatorProjection();\n        this._verticalPerspectiveProjection = new VerticalPerspectiveProjection();\n    }\n\n    public get transitionState(): number {\n        const currentProjectionSpecValue = this.properties.get('type');\n        if (typeof currentProjectionSpecValue === 'string' && currentProjectionSpecValue === 'mercator') {\n            return 0;\n        }\n        if (typeof currentProjectionSpecValue === 'string' && currentProjectionSpecValue === 'vertical-perspective') {\n            return 1;\n        }\n        if (currentProjectionSpecValue instanceof ProjectionDefinition) {\n            if (currentProjectionSpecValue.from === currentProjectionSpecValue.to) {\n                return currentProjectionSpecValue.from === 'mercator' ? 0 : 1;\n            }\n            if (currentProjectionSpecValue.from === 'vertical-perspective' && currentProjectionSpecValue.to === 'mercator') {\n                return 1 - currentProjectionSpecValue.transition;\n            }\n            if (currentProjectionSpecValue.from === 'mercator' && currentProjectionSpecValue.to === 'vertical-perspective') {\n                return currentProjectionSpecValue.transition;\n            }\n        };\n        return 1;\n    }\n\n    get useGlobeRendering(): boolean {\n        return this.transitionState > 0;\n    }\n\n    private get currentProjection(): Projection {\n        return this.useGlobeRendering ? this._verticalPerspectiveProjection : this._mercatorProjection;\n    }\n\n    get name(): ProjectionSpecification['type'] {\n        return 'globe';\n    }\n\n    get worldCoordinateHelper(): WorldCoordinateHelper {\n        return this.currentProjection.worldCoordinateHelper;\n    }\n\n    get useSubdivision(): boolean {\n        return this.currentProjection.useSubdivision;\n    }\n\n    get shaderVariantName(): string {\n        return this.currentProjection.shaderVariantName;\n    }\n\n    get shaderDefine(): string {\n        return this.currentProjection.shaderDefine;\n    }\n\n    get shaderPreludeCode(): PreparedShader {\n        return this.currentProjection.shaderPreludeCode;\n    }\n\n    get vertexShaderPreludeCode(): string {\n        return this.currentProjection.vertexShaderPreludeCode;\n    }\n\n    get subdivisionGranularity(): SubdivisionGranularitySetting {\n        return this.currentProjection.subdivisionGranularity;\n    }\n\n    get useGlobeControls(): boolean {\n        return this.transitionState > 0;\n    }\n\n    public destroy(): void {\n        this._mercatorProjection.destroy();\n        this._verticalPerspectiveProjection.destroy();\n    }\n\n    public getMeshFromTileID(context: Context, _tileID: CanonicalTileID, _hasBorder: boolean, _allowPoles: boolean, _usage: TileMeshUsage): Mesh {\n        return this.currentProjection.getMeshFromTileID(context, _tileID, _hasBorder, _allowPoles, _usage);\n    }\n\n    setProjection(projection?: ProjectionSpecification): void {\n        this._transitionable.setValue('type', projection?.type || 'mercator');\n    }\n\n    updateTransitions(parameters: TransitionParameters): void {\n        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);\n    }\n\n    hasTransition(): boolean {\n        return this._transitioning.hasTransition() || this.currentProjection.hasTransition();\n    }\n\n    recalculate(parameters: EvaluationParameters): void {\n        this.properties = this._transitioning.possiblyEvaluate(parameters);\n    }\n}\n", "import {type mat4, quat, type ReadonlyVec4, vec3, vec4} from 'gl-matrix';\nimport {clamp, createVec3f64, createVec4f64, differenceOfAnglesDegrees, lerp, MAX_VALID_LATITUDE, mod, remapSaturate, scaleZoom, wrap} from '../../util/util.ts';\nimport {LngLat} from '../lng_lat.ts';\nimport {EXTENT} from '../../data/extent.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {ITransform} from '../transform_interface.ts';\n\nexport function getGlobeCircumferencePixels(transform: {worldSize: number; center: {lat: number}}): number {\n    const radius = getGlobeRadiusPixels(transform.worldSize, transform.center.lat);\n    return 2.0 * Math.PI * radius;\n}\n\nexport function globeDistanceOfLocationsPixels(transform: {worldSize: number; center: {lat: number}}, a: LngLat, b: LngLat): number {\n    const vecA = angularCoordinatesToSurfaceVector(a);\n    const vecB = angularCoordinatesToSurfaceVector(b);\n    const dot = clamp(vec3.dot(vecA, vecB), -1, 1);\n    const radians = Math.acos(dot);\n    const circumference = getGlobeCircumferencePixels(transform);\n    return radians / (2.0 * Math.PI) * circumference;\n}\n\n/**\n * For given mercator coordinates in range 0..1, returns the angular coordinates on the sphere's surface, in radians.\n */\nexport function mercatorCoordinatesToAngularCoordinatesRadians(mercatorX: number, mercatorY: number): [number, number] {\n    const sphericalX = mod(mercatorX * Math.PI * 2.0 + Math.PI, Math.PI * 2);\n    const sphericalY = 2.0 * Math.atan(Math.exp(Math.PI - (mercatorY * Math.PI * 2.0))) - Math.PI * 0.5;\n    return [sphericalX, sphericalY];\n}\n\n/**\n * For a given longitude and latitude (note: in radians) returns the normalized vector from the planet center to the specified place on the surface.\n * @param lngRadians - Longitude in radians.\n * @param latRadians - Latitude in radians.\n */\nexport function angularCoordinatesRadiansToVector(lngRadians: number, latRadians: number): vec3 {\n    const len = Math.cos(latRadians);\n    const vec = new Float64Array(3) as any;\n    vec[0] = Math.sin(lngRadians) * len;\n    vec[1] = Math.sin(latRadians);\n    vec[2] = Math.cos(lngRadians) * len;\n    return vec;\n}\n\n/**\n * Projects a point within a tile to the surface of the unit sphere globe.\n * @param inTileX - X coordinate inside the tile in range [0 .. 8192].\n * @param inTileY - Y coordinate inside the tile in range [0 .. 8192].\n * @param tileIdX - Tile's X coordinate in range [0 .. 2^zoom - 1].\n * @param tileIdY - Tile's Y coordinate in range [0 .. 2^zoom - 1].\n * @param tileIdZ - Tile's zoom.\n * @returns A 3D vector - coordinates of the projected point on a unit sphere.\n */\nexport function projectTileCoordinatesToSphere(inTileX: number, inTileY: number, tileIdX: number, tileIdY: number, tileIdZ: number): vec3 {\n    // This code could be assembled from 3 functions, but this is a hot path for symbol placement,\n    // so for optimization purposes everything is inlined by hand.\n    //\n    // Non-inlined variant of this function would be this:\n    //     const mercator = tileCoordinatesToMercatorCoordinates(inTileX, inTileY, tileID);\n    //     const angular = mercatorCoordinatesToAngularCoordinatesRadians(mercator.x, mercator.y);\n    //     const sphere = angularCoordinatesRadiansToVector(angular[0], angular[1]);\n    //     return sphere;\n    const scale = 1.0 / (1 << tileIdZ);\n    const mercatorX = inTileX / EXTENT * scale + tileIdX * scale;\n    const mercatorY = inTileY / EXTENT * scale + tileIdY * scale;\n    const sphericalX = mod(mercatorX * Math.PI * 2.0 + Math.PI, Math.PI * 2);\n    const sphericalY = 2.0 * Math.atan(Math.exp(Math.PI - (mercatorY * Math.PI * 2.0))) - Math.PI * 0.5;\n    const len = Math.cos(sphericalY);\n    const vec = new Float64Array(3) as any;\n    vec[0] = Math.sin(sphericalX) * len;\n    vec[1] = Math.sin(sphericalY);\n    vec[2] = Math.cos(sphericalX) * len;\n    return vec;\n}\n\n/**\n * For a given longitude and latitude (note: in degrees) returns the normalized vector from the planet center to the specified place on the surface.\n */\nexport function angularCoordinatesToSurfaceVector(lngLat: LngLat): vec3 {\n    return angularCoordinatesRadiansToVector(lngLat.lng * Math.PI / 180, lngLat.lat * Math.PI / 180);\n}\n\nexport function getGlobeRadiusPixels(worldSize: number, latitudeDegrees: number): number {\n    // We want zoom levels to be consistent between globe and flat views.\n    // This means that the pixel size of features at the map center point\n    // should be the same for both globe and flat view.\n    // For this reason we scale the globe up when map center is nearer to the poles.\n    return worldSize / (2.0 * Math.PI) / planetScaleAtLatitude(latitudeDegrees);\n}\n\n/**\n * Returns the globe center in view space, in pixels: the camera is at the origin and looks down the negative Z axis.\n */\nexport function getGlobeCenterInViewSpace(transform: {modelViewProjectionMatrix: mat4; inverseProjectionMatrix: mat4}): vec3 {\n    const position = vec4.transformMat4(createVec4f64(), [0, 0, 0, 1], transform.modelViewProjectionMatrix);\n    vec4.transformMat4(position, position, transform.inverseProjectionMatrix);\n    return [position[0] / position[3], position[1] / position[3], position[2] / position[3]];\n}\n\n/**\n * Given a 3D point on the surface of a unit sphere, returns its angular coordinates in degrees.\n * The input vector must be normalized.\n */\nexport function sphereSurfacePointToCoordinates(surface: vec3): LngLat {\n    const latRadians = Math.asin(surface[1]);\n    const latDegrees = latRadians / Math.PI * 180.0;\n    const lengthXZ = Math.sqrt(surface[0] * surface[0] + surface[2] * surface[2]);\n    if (lengthXZ > 1e-6) {\n        const projX = surface[0] / lengthXZ;\n        const projZ = surface[2] / lengthXZ;\n        const acosZ = Math.acos(projZ);\n        const lngRadians = (projX > 0) ? acosZ : -acosZ;\n        const lngDegrees = lngRadians / Math.PI * 180.0;\n        return new LngLat(wrap(lngDegrees, -180, 180), latDegrees);\n    } else {\n        return new LngLat(0.0, latDegrees);\n    }\n}\n\n/**\n * Returns the globe orientation quaternion for the given map center and bearing.\n * The inverse of {@link lngLatBearingFromOrientation}.\n */\nexport function orientationFromLngLatBearing(lngLat: LngLat, bearing: number): quat {\n    return quat.fromEuler(createVec4f64(), -lngLat.lng, -lngLat.lat, bearing);\n}\n\n/**\n * Given a globe orientation quaternion, returns the corresponding map center and bearing.\n * The inverse of {@link orientationFromLngLatBearing}.\n */\nexport function lngLatBearingFromOrientation(q: quat): { lng: number; lat: number; bearing: number } {\n    const x = q[0], y = q[1], z = q[2], w = q[3];\n    const lng = -Math.atan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y)) * 180 / Math.PI;\n    const lat = -Math.asin(clamp(2 * (w * y - z * x), -1, 1)) * 180 / Math.PI;\n    const bearing = Math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)) * 180 / Math.PI;\n    return {lng, lat, bearing};\n}\n\n/**\n * How much of the angle between the view axis and the horizon is given over to easing off, measured\n * inward from the horizon. Only the outermost sliver of the globe is affected, where a pixel is\n * already worth degrees of arc.\n *\n * This is the one number here open to taste, and it sets two things at once: narrowing it keeps the\n * drag exact over more of the globe, and, since the exact curve steepens towards tangency, hands\n * over at a higher rate too. Bell has no such freedom, as a hyperbola of the fixed form `k/d` meets\n * a sphere in both value and slope at exactly one radius.\n */\nconst PAN_FALLOFF_BAND = 0.1;\n\n/**\n * Radius around the pole's screen position, in pixels, within which the cursor's sweep around it\n * stops being trusted at face value: the angle a given drag subtends grows without bound as the\n * cursor closes on the pole, and at the pole itself there is no angle at all.\n */\nconst DIAL_MIN_RADIUS_PIXELS = 20;\n\n/** Kept just below a half turn so the center cannot land exactly on the far side of the globe. */\nconst PAN_MAX_ANGLE = Math.PI * 0.98;\n\n/**\n * Returns the point on the globe that a drag towards `point` should aim at.\n *\n * Exact tracking breaks down at the silhouette: the ray meets the globe at `asin(D sin a) - a`,\n * whose slope runs away to infinity as the ray goes tangent, and past it there is no intersection\n * at all. So the exact curve is left {@link PAN_FALLOFF_BAND} early and continued with a hyperbola\n * matching it in value and slope, easing off and saturating short of the far side. Bell's virtual\n * trackball takes the same idea of easing a sphere into a hyperbola before the rim, though it fits\n * the curve differently: SGI's `trackball.c`, described in Henriksen, Sporring and Hornbæk,\n * \"Virtual Trackballs Revisited\", IEEE TVCG 10(2):206-216, 2004.\n *\n * The angle comes from atan2, so a ray pointing away from the globe is a wide angle the falloff\n * saturates rather than a case to reject.\n * @param tr - The transform being dragged.\n * @param point - The cursor position.\n */\nfunction panSurfaceLocation(tr: ITransform, point: Point): LngLat {\n    const origin = tr.cameraPosition;\n    const distance = vec3.length(origin);\n    if (distance <= 1) {\n        return tr.screenPointToLocation(point);\n    }\n\n    const u = createVec3f64();\n    vec3.normalize(u, origin);\n    const direction = tr.getRayDirectionFromPixel(point);\n    const c = -vec3.dot(direction, u);\n    const lateral = createVec3f64();\n    vec3.scaleAndAdd(lateral, direction, u, c);\n    const s = vec3.length(lateral);\n    if (s < 1e-9) {\n        return tr.screenPointToLocation(point);\n    }\n\n    const angle = Math.atan2(s, c);\n    const horizonAngle = Math.asin(1 / distance);\n    const handoverAngle = horizonAngle * (1 - PAN_FALLOFF_BAND);\n    if (angle < handoverAngle) {\n        return tr.screenPointToLocation(point);\n    }\n\n    const sinHandover = distance * Math.sin(handoverAngle);\n    const targetAtHandover = Math.asin(clamp(sinHandover, -1, 1)) - handoverAngle;\n    const slopeAtHandover = distance * Math.cos(handoverAngle) / Math.sqrt(Math.max(1 - sinHandover * sinHandover, 1e-12)) - 1;\n    const room = PAN_MAX_ANGLE - targetAtHandover;\n    const excess = angle - handoverAngle;\n    const target = targetAtHandover + room * (slopeAtHandover * excess) / (room + slopeAtHandover * excess);\n\n    const e = createVec3f64();\n    vec3.scale(e, lateral, 1 / s);\n    const surface = createVec3f64();\n    vec3.scale(surface, u, Math.cos(clamp(target, 0, PAN_MAX_ANGLE)));\n    vec3.scaleAndAdd(surface, surface, e, Math.sin(clamp(target, 0, PAN_MAX_ANGLE)));\n    vec3.normalize(surface, surface);\n    return sphereSurfacePointToCoordinates(surface);\n}\n\n/**\n * Rotates the globe so that the given location appears at the given screen point, by composing\n * versors, the unit quaternions that represent rotations. Unlike the bearing-preserving\n * {@link ITransform.setLocationAtPoint}, this stays smooth near and across the poles, and keeps\n * panning once the cursor leaves the globe.\n *\n * Note: the delta rotation's axis is in the surface-vector frame of\n * {@link angularCoordinatesToSurfaceVector}, while the orientation quaternion uses the Euler frame\n * of {@link orientationFromLngLatBearing}, hence the component swizzle where they combine. Zoom is\n * adjusted to keep the planet the same size, as `setLocationAtPoint` does.\n * @param tr - The transform to rotate.\n * @param lnglat - The location to bring under `point`.\n * @param point - The screen point that `lnglat` should appear at.\n * @param panDelta - The drag's pixel delta. Used to re-derive the previous cursor location through\n * {@link panSurfaceLocation}, since both ends of the rotation must come from the same mapping.\n * @param fixedBearing - Applies the swing only, keeping the bearing fixed, which is what dragging\n * the globe does. Pass `false` to apply the twist about the view axis as well, so that the grabbed\n * location tracks the cursor exactly and the bearing drifts with it.\n */\nexport function versorSetLocationAtPoint(tr: ITransform, lnglat: LngLat, point: Point, panDelta?: Point, fixedBearing = true): void {\n    const pointLngLat = panSurfaceLocation(tr, point);\n    let sourceLngLat = lnglat;\n    if (panDelta) {\n        sourceLngLat = panSurfaceLocation(tr, point.sub(panDelta));\n    } else if (!tr.isPointOnMapSurface(point)) {\n        return;\n    }\n\n    const vecToPixelCurrent = angularCoordinatesToSurfaceVector(pointLngLat);\n    const vecToTarget = angularCoordinatesToSurfaceVector(sourceLngLat);\n    const centerQuat = orientationFromLngLatBearing(tr.center, tr.bearing);\n    const w = vec3.cross(createVec3f64(), vecToTarget, vecToPixelCurrent);\n    const l = Math.sqrt(vec3.dot(w, w));\n    const t = Math.acos(clamp(vec3.dot(vecToTarget, vecToPixelCurrent), -1, 1)) / 2;\n    const s = Math.sin(t);\n    const delta = l ? quat.set(createVec4f64(), (w[1] / l) * s, (-w[0] / l) * s, (w[2] / l) * s, Math.cos(t)) : quat.identity(createVec4f64());\n    const newCenterQuat = quat.multiply(createVec4f64(), centerQuat, delta);\n    const {lng: newCenterLng, lat: newCenterLat, bearing: newBearing} = lngLatBearingFromOrientation(newCenterQuat);\n\n    const oldLat = tr.center.lat;\n    const oldZoom = tr.zoom;\n    const finalLat = fixedBearing ? fixedBearingLatitude(tr, newCenterLat, newBearing) : newCenterLat;\n    const finalLng = fixedBearing ? fixedBearingLongitude(tr, point, panDelta, newCenterLng) : newCenterLng;\n\n    tr.setCenter(new LngLat(wrap(finalLng, -180, 180), finalLat));\n    if (!fixedBearing) {\n        tr.setBearing(newBearing);\n    }\n    tr.setZoom(oldZoom + getZoomAdjustment(oldLat, tr.center.lat));\n}\n\n/**\n * Returns the center latitude for a bearing-preserving drag. A swing over a pole turns the bearing around,\n * so with the bearing held the center stops on that pole.\n */\nfunction fixedBearingLatitude(tr: ITransform, newCenterLat: number, newBearing: number): number {\n    if (Math.abs(differenceOfAnglesDegrees(tr.bearing, newBearing)) <= 90) {\n        return newCenterLat;\n    }\n    return newCenterLat > 0 ? 90 : -90;\n}\n\n/**\n * Returns the center longitude for a bearing-preserving drag.\n *\n * The swing longitude becomes ill-conditioned near the pole and the grabbed location slips away\n * from the cursor, so within the last ~12 degrees of latitude the cursor is treated as turning a\n * dial around the pole, blended in with a smoothstep anchored on {@link MAX_VALID_LATITUDE} and in\n * full from there to the pole. The sweep comes from the raw pixel delta rather than a\n * round-tripped previous cursor position, which would lose its sign to cancellation at the pole,\n * and is damped within {@link DIAL_MIN_RADIUS_PIXELS} so it eases to nothing there instead of\n * being dropped, which would leave a spot where the drag could not move at all.\n * @param tr - The transform being dragged.\n * @param point - The cursor position.\n * @param panDelta - The drag's pixel delta, or undefined to use the swing longitude only.\n * @param newCenterLng - The swing target longitude.\n * @returns the center longitude to apply.\n */\nfunction fixedBearingLongitude(tr: ITransform, point: Point, panDelta: Point | undefined, newCenterLng: number): number {\n    const oldLng = tr.center.lng;\n    const oldLat = tr.center.lat;\n    const poleLat = oldLat >= 0 ? 90 : -90;\n    const polePoint = tr.locationToScreenPoint(new LngLat(0, poleLat));\n    const rx = point.x - polePoint.x, ry = point.y - polePoint.y;\n    const r2 = rx * rx + ry * ry;\n\n    const tRamp = clamp(1 - (MAX_VALID_LATITUDE - Math.abs(oldLat)) / 12, 0, 1);\n    const dial = tRamp * tRamp * (3 - 2 * tRamp);\n    const dLngSwing = mod(newCenterLng - oldLng + 180, 360) - 180;\n\n    let dLngDial = 0;\n    if (dial > 0 && panDelta) {\n        const dTheta = (rx * panDelta.y - ry * panDelta.x) / Math.max(r2, DIAL_MIN_RADIUS_PIXELS * DIAL_MIN_RADIUS_PIXELS);\n        dLngDial = (poleLat > 0 ? 1 : -1) * dTheta * 180 / Math.PI;\n    }\n\n    return oldLng + (1 - dial) * dLngSwing + dial * dLngDial;\n}\n\n/**\n * Given a normalized horizon plane in Ax+By+Cz+D=0 format, compute the center and radius of\n * the circle in that plain that contains the entire visible portion of the unit sphere from horizon\n * to horizon.\n * @param horizonPlane - The plane that passes through visible horizon in Ax + By + Cz + D = 0 format where mag(A,B,C)=1\n * @returns the center point and radius of the disc that passes through the entire visible horizon\n */\nexport function horizonPlaneToCenterAndRadius(horizonPlane: ReadonlyVec4): { center: vec3; radius: number } {\n    const center = createVec3f64();\n    center[0] = horizonPlane[0] * -horizonPlane[3];\n    center[1] = horizonPlane[1] * -horizonPlane[3];\n    center[2] = horizonPlane[2] * -horizonPlane[3];\n    /*\n                     .*******\n                 ****|\\\n               **    | \\\n             **      |  1\n            * radius |   \\\n           *         |    \\\n           *  center +--D--+(0,0,0)\n     */\n    const radius = Math.sqrt(1 - horizonPlane[3] * horizonPlane[3]);\n    return {center, radius};\n}\n\n/**\n * Computes the closest point on a sphere to `point`.\n * @param center - Center of the sphere\n * @param radius - Radius of the sphere\n * @param point - Point inside or outside the sphere\n * @returns A 3d vector of the point on the sphere closest to `point`\n */\nexport function clampToSphere(center: vec3, radius: number, point: vec3): vec3 {\n    const relativeToCenter = createVec3f64();\n    vec3.sub(relativeToCenter, point, center);\n    const clamped = createVec3f64();\n    vec3.scaleAndAdd(clamped, center, relativeToCenter, radius / vec3.len(relativeToCenter));\n    return clamped;\n}\n\n/**\n * Returns the cosine of the given center latitude, which the globe radius is divided by so that zoom levels match\n * mercator at the map center. Mercator ends at {@link MAX_VALID_LATITUDE}, so past it the globe keeps its size there.\n */\nexport function planetScaleAtLatitude(latitudeDegrees: number): number {\n    return Math.cos(Math.min(Math.abs(latitudeDegrees), MAX_VALID_LATITUDE) * Math.PI / 180);\n}\n\n/**\n * Computes how much to modify zoom to keep the globe size constant when changing latitude.\n * @param transform - An instance of any transform. Does not have any relation on the computed values.\n * @param oldLat - Latitude before change, in degrees.\n * @param newLat - Latitude after change, in degrees.\n * @returns A value to add to zoom level used for old latitude to keep same planet radius at new latitude.\n */\nexport function getZoomAdjustment(oldLat: number, newLat: number): number {\n    const oldCircumference = planetScaleAtLatitude(oldLat);\n    const newCircumference = planetScaleAtLatitude(newLat);\n    return scaleZoom(newCircumference / oldCircumference);\n}\n\nexport function getDegreesPerPixel(worldSize: number, lat: number): number {\n    return 360.0 / getGlobeCircumferencePixels({worldSize, center: {lat}});\n}\n\n/**\n * Returns transform's new center rotation after applying panning.\n * @param panDelta - Panning delta, in same units as what is supplied to {@link HandlerManager}.\n * @param tr - Current transform. This object is not modified by the function.\n * @returns New center location to set to the map's transform to apply the specified panning.\n */\nexport function computeGlobePanCenter(panDelta: Point, tr: {\n    readonly bearingInRadians: number;\n    readonly worldSize: number;\n    readonly center: LngLat;\n    readonly zoom: number;\n}): LngLat {\n    // Apply map bearing to the panning vector\n    const rotatedPanDelta = panDelta.rotate(tr.bearingInRadians);\n    // Compute what the current zoom would be if the transform center would be moved to latitude 0.\n    const normalizedGlobeZoom = tr.zoom + getZoomAdjustment(tr.center.lat, 0);\n    // Note: we divide longitude speed by planet width at the given latitude. But we diminish this effect when the globe is zoomed out a lot.\n    const lngSpeed = lerp(\n        1.0 / planetScaleAtLatitude(tr.center.lat), // speed adjusted by latitude\n        1.0 / planetScaleAtLatitude(Math.min(Math.abs(tr.center.lat), 60)), // also adjusted, but latitude is clamped to 60° to avoid too large speeds near poles\n        remapSaturate(normalizedGlobeZoom, 7, 3, 0, 1.0) // Values chosen so that globe interactions feel good. Not scientific by any means.\n    );\n    const panningDegreesPerPixel = getDegreesPerPixel(tr.worldSize, tr.center.lat);\n    return new LngLat(\n        tr.center.lng - rotatedPanDelta.x * panningDegreesPerPixel * lngSpeed,\n        clamp(tr.center.lat + rotatedPanDelta.y * panningDegreesPerPixel, -90, 90)\n    );\n}\n\n/**\n * Integration of `1 / cos(x)`.\n */\nfunction integrateSecX(x: number): number {\n    const xHalf = 0.5 * x;\n    const sin = Math.sin(xHalf);\n    const cos = Math.cos(xHalf);\n    return Math.log(sin + cos) - Math.log(cos - sin);\n}\n\n/**\n * Interpolates globe center between two locations while preserving apparent rotation speed during interpolation.\n * The speed grows without bound towards the poles, so past {@link MAX_VALID_LATITUDE} it stays at its value there.\n * @param start - The starting location of the interpolation.\n * @param deltaLng - Longitude delta to the end of the interpolation.\n * @param deltaLat - Latitude delta to the end of the interpolation.\n * @param t - The interpolation point in [0..1], where 0 is starting location, 1 is end location and other values are in between.\n * @returns The interpolated location.\n */\nexport function interpolateLngLatForGlobe(start: LngLat, deltaLng: number, deltaLat: number, t: number): LngLat {\n    // Rate of change of longitude when moving the globe should be roughly 1/cos(latitude)\n    // We want to use this rate of change, even for interpolation during easing.\n    // Thus we know the derivative of our interpolation function: 1/cos(x)\n    // To get our interpolation function, we need to integrate that.\n\n    const interpolatedLat = clamp(start.lat + deltaLat * t, -90, 90);\n    const startLat = clamp(start.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE);\n    const endLat = clamp(start.lat + deltaLat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE);\n\n    if (Math.abs(endLat - startLat) > 1) {\n        const onDifferentHemispheres = Math.sign(endLat) !== Math.sign(startLat);\n        // Where do we sample the integrated speed curve?\n        const samplePointStart = (onDifferentHemispheres ? -Math.abs(startLat) : Math.abs(startLat)) * Math.PI / 180;\n        const samplePointEnd = Math.abs(endLat) * Math.PI / 180;\n        // Read the integrated speed curve at those points, and at the interpolation value \"t\".\n        const valueT = integrateSecX(samplePointStart + t * (samplePointEnd - samplePointStart));\n        const valueStart = integrateSecX(samplePointStart);\n        const valueEnd = integrateSecX(samplePointEnd);\n        // Compute new interpolation factor based on the speed curve\n        const newT = (valueT - valueStart) / (valueEnd - valueStart);\n        // Interpolate using that factor\n        const interpolatedLng = start.lng + deltaLng * newT;\n        return new LngLat(\n            interpolatedLng,\n            interpolatedLat\n        );\n    } else {\n        // Fall back to simple interpolation when latitude doesn't change much.\n        const interpolatedLng = start.lng + deltaLng * t;\n        return new LngLat(\n            interpolatedLng,\n            interpolatedLat\n        );\n    }\n}\n\n/**\n * Describes the intersection of ray and sphere.\n * When null, no intersection occurred.\n * When both \"t\" values are the same, the ray just touched the sphere's surface.\n * When both value are different, a full intersection occurred.\n */\nexport type RaySphereIntersection = {\n    /**\n     * The ray parameter for intersection that is \"less\" along the ray direction.\n     * Note that this value can be negative, meaning that this intersection occurred before the ray's origin.\n     * The intersection point can be computed as `origin + direction * tMin`.\n     */\n    tMin: number;\n    /**\n     * The ray parameter for intersection that is \"more\" along the ray direction.\n     * The intersection point can be computed as `origin + direction * tMax`.\n     */\n    tMax: number;\n} | null;\n\n/**\n * Returns the two intersection points of the ray and a sphere centered at the origin,\n * or null if no intersection occurs.\n * The intersections are encoded as the parameter for parametric ray equation,\n * with `tMin` being the first intersection and `tMax` being the second.\n * The quadratic is solved as suggested in Ray Tracing Gems, chapter 7, since the\n * schoolbook approach leads to floating point precision issues:\n * https://www.realtimerendering.com/raytracinggems/rtg/index.html\n * @param origin - The ray origin.\n * @param direction - The normalized ray direction.\n * @param radius - The sphere radius, defaults to the unit sphere of the planet.\n */\nexport function raySphereIntersection(origin: vec3, direction: vec3, radius: number = 1.0): RaySphereIntersection {\n    const originDotDirection = vec3.dot(origin, direction);\n    const radiusSquared = radius * radius;\n\n    const inner = createVec3f64();\n    const scaledDir = createVec3f64();\n    vec3.scale(scaledDir, direction, originDotDirection);\n    vec3.sub(inner, origin, scaledDir);\n    const discriminant = radiusSquared - vec3.dot(inner, inner);\n\n    if (discriminant < 0) {\n        return null;\n    }\n\n    const c = vec3.dot(origin, origin) - radiusSquared;\n    const q = -originDotDirection + (originDotDirection < 0 ? 1 : -1) * Math.sqrt(discriminant);\n    const t0 = c / q;\n    const t1 = q;\n    const tMax = Math.max(t0, t1);\n    if (tMax < 0) {\n        return null;\n    }\n    return {\n        tMin: Math.min(t0, t1),\n        tMax\n    };\n}\n\n/** Height of the atmosphere relative to the globe radius, 100 km for Earth. */\nconst ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS = 100000 / 6371000;\n\n/**\n * Returns how much of the atmosphere to draw for a camera at the given altitude above the globe.\n * It is 0 inside the atmosphere and reaches 1 at ten times the atmosphere height. The sky shader\n * fades out along the same curve.\n */\nexport function getAtmosphereAltitudeBlend(altitude: number, globeRadius: number): number {\n    const atmosphereHeight = globeRadius * ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS;\n    const x = clamp((altitude - atmosphereHeight) / (9 * atmosphereHeight), 0, 1);\n    return x * x * (3 - 2 * x);\n}\n", "import type {CoveringTilesOptionsInternal} from '../../geo/projection/covering_tiles.ts';\nimport type {IBoundingVolume} from './bounding_volume.ts';\n\ntype BoundingVolumeFactory<T extends IBoundingVolume> = (tileID: {x: number; y: number; z: number}, wrap: number, elevation: number, options: CoveringTilesOptionsInternal) => T;\n\nexport class BoundingVolumeCache<T extends IBoundingVolume> {\n    private _cachePrevious: Map<string, T> = new Map();\n    private _cache: Map<string, T> = new Map();\n    private _hadAnyChanges = false;\n    private _boundingVolumeFactory: BoundingVolumeFactory<T>;\n\n    constructor(boundingVolumeFactory: BoundingVolumeFactory<T>) {\n        this._boundingVolumeFactory = boundingVolumeFactory;\n    }\n\n    /**\n     * Prepares bounding volume cache for next frame. Call at the beginning of a frame.\n     * Bounding volume of any tile accesses in the last frame is kept in the cache, other (unaccessed) bounding volumes are deleted.\n     */\n    swapBuffers(): void {\n        if (!this._hadAnyChanges) {\n            // If no new bounding volumes were added this frame, no need to conserve memory, do not clear caches.\n            return;\n        }\n        const oldCache = this._cachePrevious;\n        this._cachePrevious = this._cache;\n        this._cache = oldCache;\n        this._cache.clear();\n        this._hadAnyChanges = false;\n    }\n\n    /**\n     * Returns the bounding volume of the specified tile, fetching it from cache or creating it using the factory function if needed.\n     * @param tileID - Tile x, y and z for zoom.\n     */\n    getTileBoundingVolume(tileID: {x: number; y: number; z: number}, wrap: number, elevation: number, options: CoveringTilesOptionsInternal): T {\n        // Elevation affects the computed volume (see getElevationForTileCulling);\n        // rounding keeps sub-meter changes from defeating the cache.\n        const key = `${tileID.z}_${tileID.x}_${tileID.y}_${options?.terrain ? 't' : ''}_${Math.round(elevation)}`;\n        const cached = this._cache.get(key);\n        if (cached) {\n            return cached;\n        }\n        const cachedPrevious = this._cachePrevious.get(key);\n        if (cachedPrevious) {\n            this._cache.set(key, cachedPrevious);\n            return cachedPrevious;\n        }\n        const boundingVolume = this._boundingVolumeFactory(tileID, wrap, elevation, options);\n        this._cache.set(key, boundingVolume);\n        this._hadAnyChanges = true;\n        return boundingVolume;\n    }\n}\n", "import {quat, vec3, type vec4} from 'gl-matrix';\nimport {IntersectionResult, type IBoundingVolume} from './bounding_volume.ts';\n\nimport type {Frustum} from './frustum.ts';\n\n/**\n * A general convex bounding volume, defined by a set of points.\n */\nexport class ConvexVolume implements IBoundingVolume {\n    // Precomputed AABB for rejecting frustum intersection.\n    min: vec3;\n    max: vec3;\n\n    points: vec3[];\n    planes: vec4[];\n\n    /**\n     * Creates an instance of a general convex bounding volume.\n     * Note that the provided points array is used *as is*, its contents are not copied!\n     *\n     * Additionally, an AABB must be provided for rejecting frustum intersections.\n     * This AABB does not need to bound this convex volume (it may be smaller),\n     * but it *must* accurately bound the actual shape this volume is approximating.\n     * @param points - Points forming the convex shape. Note that this array reference is used *as is*, its contents are not copied!\n     * @param min - The bounding AABB's min point.\n     * @param max - The bounding AABB's min point.\n     */\n    constructor(points: vec3[], planes: vec4[], min: vec3, max: vec3) {\n        this.min = min;\n        this.max = max;\n        this.points = points;\n        this.planes = planes;\n    }\n\n    /**\n     * Creates a convex BV equivalent to the specified AABB.\n     * @param min - The AABB's min point.\n     * @param max - The AABB's max point.\n     */\n    public static fromAabb(min: vec3, max: vec3): ConvexVolume {\n        const points = [];\n        for (let i = 0; i < 8; i++) {\n            points.push([\n                ((i >> 0) & 1) === 1 ? max[0] : min[0],\n                ((i >> 1) & 1) === 1 ? max[1] : min[1],\n                ((i >> 2) & 1) === 1 ? max[2] : min[2]\n            ]);\n        }\n        return new ConvexVolume(points, [\n            [-1, 0, 0, max[0]],\n            [1, 0, 0, -min[0]],\n            [0, -1, 0, max[1]],\n            [0, 1, 0, -min[1]],\n            [0, 0, -1, max[2]],\n            [0, 0, 1, -min[2]]\n        ], min, max);\n    }\n\n    /**\n     * Creates a convex bounding volume that is actually an oriented bounding box created from the specified center, half-size and rotation angles.\n     * @param center - Center of the OBB.\n     * @param halfSize - The half-size of the OBB in each axis. The box will extend by this value in each direction for the given axis.\n     * @param angles - The rotation of the box. Euler angles, in degrees.\n     */\n    public static fromCenterSizeAngles(center: vec3, halfSize: vec3, angles: vec3): ConvexVolume {\n        const q = quat.fromEuler([], angles[0], angles[1], angles[2]);\n        const axisX = vec3.transformQuat([], [halfSize[0], 0, 0], q);\n        const axisY = vec3.transformQuat([], [0, halfSize[1], 0], q);\n        const axisZ = vec3.transformQuat([], [0, 0, halfSize[2]], q);\n        // Find the AABB min/max\n        const min = [...center] as vec3;\n        const max = [...center] as vec3;\n        for (let i = 0; i < 8; i++) {\n            for (let axis = 0; axis < 3; axis++) {\n                const point = center[axis]\n                    + axisX[axis] * ((((i >> 0) & 1) === 1) ? 1 : -1)\n                    + axisY[axis] * ((((i >> 1) & 1) === 1) ? 1 : -1)\n                    + axisZ[axis] * ((((i >> 2) & 1) === 1) ? 1 : -1);\n                min[axis] = Math.min(min[axis], point);\n                max[axis] = Math.max(max[axis], point);\n            }\n        }\n        const points = [];\n        for (let i = 0; i < 8; i++) {\n            const p = [...center] as vec3;\n            vec3.add(p, p, vec3.scale([], axisX, ((i >> 0) & 1) === 1 ? 1 : -1));\n            vec3.add(p, p, vec3.scale([], axisY, ((i >> 1) & 1) === 1 ? 1 : -1));\n            vec3.add(p, p, vec3.scale([], axisZ, ((i >> 2) & 1) === 1 ? 1 : -1));\n            points.push(p);\n        }\n        return new ConvexVolume(points, [\n            [...axisX, -vec3.dot(axisX, points[0])] as vec4,\n            [...axisY, -vec3.dot(axisY, points[0])] as vec4,\n            [...axisZ, -vec3.dot(axisZ, points[0])] as vec4,\n            [-axisX[0], -axisX[1], -axisX[2], -vec3.dot(axisX, points[7])] as vec4,\n            [-axisY[0], -axisY[1], -axisY[2], -vec3.dot(axisY, points[7])] as vec4,\n            [-axisZ[0], -axisZ[1], -axisZ[2], -vec3.dot(axisZ, points[7])] as vec4,\n        ], min, max);\n    }\n\n    /**\n     * Performs an approximate frustum-obb intersection test.\n     */\n    intersectsFrustum(frustum: Frustum): IntersectionResult {\n        // Performance-critical\n        let fullyInside = true;\n\n        const boxPointCount = this.points.length;\n        const boxPlaneCount = this.planes.length;\n        const frustumPlaneCount = frustum.planes.length;\n        const frustumPointCount = frustum.points.length;\n\n        // Test whether this volume's points are inside the frustum\n        for (let i = 0; i < frustumPlaneCount; i++) {\n            const plane = frustum.planes[i];\n            let boxPointsPassed = 0;\n            for(let j = 0; j < boxPointCount; j++) {\n                const point = this.points[j];\n                // Get point-plane distance sign\n                if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) {\n                    boxPointsPassed++;\n                }\n            }\n\n            if (boxPointsPassed === 0) {\n                return IntersectionResult.None;\n            }\n            if (boxPointsPassed < boxPointCount) {\n                fullyInside = false;\n            }\n        }\n\n        if (fullyInside) {\n            return IntersectionResult.Full;\n        }\n\n        // Test whether the frustum's points are inside this volume.\n        for (let i = 0; i < boxPlaneCount; i++) {\n            const plane = this.planes[i];\n            let frustumPointsPassed = 0;\n            for (let j = 0; j < frustumPointCount; j++) {\n                const point = frustum.points[j];\n                if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) {\n                    frustumPointsPassed++;\n                }\n            }\n            if (frustumPointsPassed === 0) {\n                return IntersectionResult.None;\n            }\n        }\n\n        return IntersectionResult.Partial;\n    }\n\n    /**\n     * Performs an intersection test with a halfspace.\n     */\n    intersectsPlane(plane: vec4): IntersectionResult {\n        const pointCount = this.points.length;\n        let positivePoints = 0;\n        for (let i = 0; i < pointCount; i++) {\n            const point = this.points[i];\n            if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) {\n                positivePoints++;\n            }\n        }\n\n        if (positivePoints === pointCount) {\n            return IntersectionResult.Full;\n        }\n        if (positivePoints === 0) {\n            return IntersectionResult.None;\n        }\n        return IntersectionResult.Partial;\n    }\n}\n", "import {EXTENT} from '../../data/extent.ts';\nimport {projectTileCoordinatesToSphere} from './globe_utils.ts';\nimport {BoundingVolumeCache} from '../../util/primitives/bounding_volume_cache.ts';\nimport {coveringZoomLevel, type CoveringTilesOptionsInternal} from './covering_tiles.ts';\nimport {vec3, type vec4} from 'gl-matrix';\nimport {OverscaledTileID} from '../../tile/tile_id.ts';\nimport {earthRadius, LngLat} from '../lng_lat.ts';\nimport {ConvexVolume} from '../../util/primitives/convex_volume.ts';\nimport {clamp, MAX_VALID_LATITUDE, threePlaneIntersection} from '../../util/util.ts';\n\nimport type {IReadonlyTransform} from '../transform_interface.ts';\nimport type {MercatorCoordinate} from '../mercator_coordinate.ts';\nimport type {CoveringTilesDetailsProvider} from './covering_tiles_details_provider.ts';\nimport type {IBoundingVolume} from '../../util/primitives/bounding_volume.ts';\n\n/**\n * Computes distance of a point to a tile in an arbitrary axis.\n * World is assumed to have size 1, distance returned is to the nearer tile edge.\n * @param point - Point position.\n * @param tile - Tile position.\n * @param tileSize - Tile size.\n */\nfunction distanceToTileSimple(point: number, tile: number, tileSize: number): number {\n    const delta = point - tile;\n    return (delta < 0) ? -delta : Math.max(0, delta - tileSize);\n}\n\nfunction distanceToTileWrapX(pointX: number, pointY: number, tileCornerX: number, tileCornerY: number, tileSize: number): number {\n    const tileCornerToPointX = pointX - tileCornerX;\n\n    let distanceX: number;\n    if (tileCornerToPointX < 0) {\n        // Point is left of tile\n        distanceX = Math.min(-tileCornerToPointX, 1.0 + tileCornerToPointX - tileSize);\n    } else if (tileCornerToPointX > tileSize) {\n        // Point is right of tile\n        distanceX = Math.min(Math.max(tileCornerToPointX - tileSize, 0), 1.0 - tileCornerToPointX);\n    } else {\n        // Point is inside tile in the X axis.\n        distanceX = 0;\n    }\n\n    return Math.max(distanceX, distanceToTileSimple(pointY, tileCornerY, tileSize));\n}\n\nexport class GlobeCoveringTilesDetailsProvider implements CoveringTilesDetailsProvider {\n    private _boundingVolumeCache: BoundingVolumeCache<ConvexVolume> = new BoundingVolumeCache(this._computeTileBoundingVolume);\n\n    /**\n     * The tiles end at the mercator edge, so a center past it selects the tiles from that edge.\n     */\n    getCenter(transform: IReadonlyTransform): LngLat {\n        return new LngLat(transform.center.lng, clamp(transform.center.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE));\n    }\n\n    /**\n     * Prepares the internal bounding volume cache for the next frame.\n     */\n    prepareNextFrame(): void {\n        this._boundingVolumeCache.swapBuffers();\n    }\n\n    /**\n     * Returns the distance of a point to a square tile. If the point is inside the tile, returns 0.\n     * Assumes the world to be of size 1.\n     * Handles distances on a sphere correctly: X is wrapped when crossing the antimeridian,\n     * when crossing the poles Y is mirrored and X is shifted by half world size.\n     */\n    distanceToTile2d(pointX: number, pointY: number, tileID: {x: number; y: number; z: number}, _bv: IBoundingVolume): number {\n        const scale = 1 << tileID.z;\n        const tileMercatorSize = 1.0 / scale;\n        const tileCornerX = tileID.x / scale; // In range 0..1\n        const tileCornerY = tileID.y / scale; // In range 0..1\n\n        const worldSize = 1.0;\n        const halfWorld = 0.5 * worldSize;\n        let smallestDistance = 2.0 * worldSize;\n        // Original tile\n        smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX, tileCornerY, tileMercatorSize));\n        // Up\n        smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX + halfWorld, -tileCornerY - tileMercatorSize, tileMercatorSize));\n        // Down\n        smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX + halfWorld, worldSize + worldSize - tileCornerY - tileMercatorSize, tileMercatorSize));\n\n        return smallestDistance;\n    }\n\n    /**\n     * Returns the wrap value for a given tile, computed so that tiles will remain loaded when crossing the antimeridian.\n     */\n    getWrap(centerCoord: MercatorCoordinate, tileID: {x: number; y: number; z: number}, _parentWrap: number): number {\n        const scale = 1 << tileID.z;\n        const tileMercatorSize = 1.0 / scale;\n        const tileX = tileID.x / scale; // In range 0..1\n        const distanceCurrent = distanceToTileSimple(centerCoord.x, tileX, tileMercatorSize);\n        const distanceLeft = distanceToTileSimple(centerCoord.x, tileX - 1.0, tileMercatorSize);\n        const distanceRight = distanceToTileSimple(centerCoord.x, tileX + 1.0, tileMercatorSize);\n        const distanceSmallest = Math.min(distanceCurrent, distanceLeft, distanceRight);\n        if (distanceSmallest === distanceRight) {\n            return 1;\n        }\n        if (distanceSmallest === distanceLeft) {\n            return -1;\n        }\n        return 0;\n    }\n    \n    allowVariableZoom(transform: IReadonlyTransform, options: CoveringTilesOptionsInternal): boolean {\n        return coveringZoomLevel(transform, options) > 4;\n    }\n\n    allowWorldCopies(): boolean {\n        return false;\n    }\n\n    getTileBoundingVolume(tileID: { x: number; y: number; z: number }, wrap: number, elevation: number, options: CoveringTilesOptionsInternal): ConvexVolume {\n        return this._boundingVolumeCache.getTileBoundingVolume(tileID, wrap, elevation, options);\n    }\n\n    /**\n     * Computes the bounding volume of a tile for culling. The volume reaches up to `elevation`,\n     * which carries the content elevation allowance (e.g. elevated symbols); terrain elevations\n     * widen the volume but never shrink that allowance.\n     */\n    private _computeTileBoundingVolume(tileID: {x: number; y: number; z: number}, wrap: number, elevation: number, options: CoveringTilesOptionsInternal): ConvexVolume {\n        let minElevation = Math.min(0, elevation);\n        let maxElevation = Math.max(0, elevation);\n        if (options?.terrain) {\n            const overscaledTileID = new OverscaledTileID(tileID.z, wrap, tileID.z, tileID.x, tileID.y);\n            const minMax = options.terrain.getMinMaxElevation(overscaledTileID);\n            minElevation = minMax.minElevation ?? minElevation;\n            maxElevation = Math.max(minMax.maxElevation ?? maxElevation, maxElevation);\n        }\n        // Convert elevation to distances from center of a unit sphere planet (so that 1 is surface)\n        minElevation /= earthRadius;\n        maxElevation /= earthRadius;\n        minElevation += 1;\n        maxElevation += 1;\n\n        if (tileID.z <= 0) {\n            // Tile covers the entire sphere.\n            return ConvexVolume.fromAabb( // We return an AABB in this case.\n                [-maxElevation, -maxElevation, -maxElevation],\n                [maxElevation, maxElevation, maxElevation]\n            );\n        } else if (tileID.z === 1) {\n            // Tile covers a quarter of the sphere.\n            // X is 1 at lng=E90°\n            // Y is 1 at **north** pole\n            // Z is 1 at null island\n            return ConvexVolume.fromAabb( // We also just use AABBs for this zoom level.\n                [tileID.x === 0 ? -maxElevation : 0, tileID.y === 0 ? 0 : -maxElevation, -maxElevation],\n                [tileID.x === 0 ? 0 : maxElevation, tileID.y === 0 ? maxElevation : 0, maxElevation]\n            );\n        } else {\n            const corners = [\n                projectTileCoordinatesToSphere(0, 0, tileID.x, tileID.y, tileID.z),\n                projectTileCoordinatesToSphere(EXTENT, 0, tileID.x, tileID.y, tileID.z),\n                projectTileCoordinatesToSphere(EXTENT, EXTENT, tileID.x, tileID.y, tileID.z),\n                projectTileCoordinatesToSphere(0, EXTENT, tileID.x, tileID.y, tileID.z),\n            ];\n\n            const extremesPoints = [];\n\n            for (const c of corners) {\n                extremesPoints.push(vec3.scale([], c, maxElevation));\n            }\n\n            if (maxElevation !== minElevation) {\n                // Only add additional points if terrain is enabled and is not flat.\n                for (const c of corners) {\n                    extremesPoints.push(vec3.scale([], c, minElevation));\n                }\n            }\n\n            // Special handling of poles - we need to extend the tile AABB\n            // to include the pole for tiles that border mercator north/south edge.\n            if (tileID.y === 0) {\n                extremesPoints.push([0, 1, 0]); // North pole\n            }\n            if (tileID.y === (1 << tileID.z) - 1) {\n                extremesPoints.push([0, -1, 0]); // South pole\n            }\n\n            // Compute a best-fit AABB for the frustum rejection test\n            const aabbMin: vec3 = [1, 1, 1];\n            const aabbMax: vec3 = [-1, -1, -1];\n\n            for (const c of extremesPoints) {\n                for (let i = 0; i < 3; i++) {\n                    aabbMin[i] = Math.min(aabbMin[i], c[i]);\n                    aabbMax[i] = Math.max(aabbMax[i], c[i]);\n                }\n            }\n\n            // Now we compute the actual bounding volume.\n            // The up/down plane will be normal to the tile's center.\n            // The north/south plane will be used for the tile's north and south edge and will be orthogonal to the up/down plane.\n            // The left and right planes will be determined by the tile's east/west edges and will differ slightly - we are not creating a box!\n            // We will find the min and max extents for the up/down and north/south planes using the set of points\n            // where the extremes are likely to lie.\n\n            // Vector \"center\" (from planet center to tile center) will be our up/down axis.\n            const center = projectTileCoordinatesToSphere(EXTENT / 2, EXTENT / 2, tileID.x, tileID.y, tileID.z);\n            // Vector to the east of \"center\".\n            const centerEast = vec3.cross([], [0, 1, 0], center);\n            vec3.normalize(centerEast, centerEast);\n            // Vector to the north of \"center\" will be our north/south axis.\n            const north = vec3.cross([], center, centerEast);\n            vec3.normalize(north, north);\n\n            // Axes for the east and west edge of our bounding volume.\n            // These axes are NOT opposites of each other, they differ!\n            // They are also not orthogonal to the up/down and north/south axes.\n            const axisEast = vec3.cross([], corners[2], corners[1]);\n            vec3.normalize(axisEast, axisEast);\n            const axisWest = vec3.cross([], corners[0], corners[3]);\n            vec3.normalize(axisWest, axisWest);\n\n            // Now we will expand the extremes point set for bounding volume creation.\n            // We will also include the tile center point, since it will always be an extreme for the \"center\" axis.\n            extremesPoints.push(vec3.scale([], center, maxElevation));\n            // No need to include a minElevation-scaled center, since we already have minElevation corners in the set and these will always lie lower than the center.\n\n            // The extremes might also lie on the midpoint of the north or south edge.\n            // For tiles in the north hemisphere, only the south edge can contain an extreme,\n            // since when we imagine the tile's actual shape projected onto the plane normal to \"center\" vector,\n            // the tile's north edge will curve towards the tile center, thus its extremes are accounted for by the\n            // corners, however the south edge will curve away from the center point, extending beyond the tile's edges,\n            // thus it must be included.\n            // The poles are an exception - they must always be included in the extremes, if the tile touches the north/south mercator range edge.\n            //\n            // A tile's exaggerated shape on the northern hemisphere, projected onto the normal plane of \"center\".\n            // The \"c\" is the tile's center point. The \"m\" is the edge mid point we are looking for.\n            //\n            //      /--       --\\\n            //     /   -------   \\\n            //    /               \\\n            //   /        c        \\\n            //  /                   \\\n            // /--                 --\\\n            //    -----       -----\n            //         ---m---\n            \n            if (tileID.y >= (1 << tileID.z) / 2) {\n                // South hemisphere - include the tile's north edge midpoint\n                extremesPoints.push(vec3.scale([], projectTileCoordinatesToSphere(EXTENT / 2, 0, tileID.x, tileID.y, tileID.z), maxElevation));\n                // No need to include minElevation variant of this point, for the same reason why we don't include minElevation center.\n            }\n            if (tileID.y < (1 << tileID.z) / 2) {\n                // North hemisphere - include the tile's south edge midpoint\n                extremesPoints.push(vec3.scale([], projectTileCoordinatesToSphere(EXTENT / 2, EXTENT, tileID.x, tileID.y, tileID.z), maxElevation));\n                // No need to include minElevation variant of this point, for the same reason why we don't include minElevation center.\n            }\n\n            // Find the min and max extends and the midpoints along each axis,\n            // using the set of extreme points.\n            const upDownMinMax = findAxisMinMax(center, extremesPoints);\n            const northSouthMinMax = findAxisMinMax(north, extremesPoints);\n\n            const planeUp = [-center[0], -center[1], -center[2], upDownMinMax.max] as vec4;\n            const planeDown = [center[0], center[1], center[2], -upDownMinMax.min] as vec4;\n            const planeNorth = [-north[0], -north[1], -north[2], northSouthMinMax.max] as vec4;\n            const planeSouth = [north[0], north[1], north[2], -northSouthMinMax.min] as vec4;\n            const planeEast = [...axisEast, 0] as vec4;\n            const planeWest = [...axisWest, 0] as vec4;\n\n            const points: vec3[] = [];\n\n            // North points\n            if (tileID.y === 0) {\n                // If the tile borders a pole, then \n                points.push(\n                    threePlaneIntersection(planeWest, planeEast, planeUp),\n                    threePlaneIntersection(planeWest, planeEast, planeDown),\n                );\n            } else {\n                points.push(\n                    threePlaneIntersection(planeNorth, planeEast, planeUp),\n                    threePlaneIntersection(planeNorth, planeEast, planeDown),\n                    threePlaneIntersection(planeNorth, planeWest, planeUp),\n                    threePlaneIntersection(planeNorth, planeWest, planeDown)\n                );\n            }\n\n            // South points\n            if (tileID.y === (1 << tileID.z) - 1) {\n                points.push(\n                    threePlaneIntersection(planeWest, planeEast, planeUp),\n                    threePlaneIntersection(planeWest, planeEast, planeDown),\n                );\n            } else {\n                points.push(\n                    threePlaneIntersection(planeSouth, planeEast, planeUp),\n                    threePlaneIntersection(planeSouth, planeEast, planeDown),\n                    threePlaneIntersection(planeSouth, planeWest, planeUp),\n                    threePlaneIntersection(planeSouth, planeWest, planeDown)\n                );\n            }\n\n            return new ConvexVolume(points, [\n                planeUp,\n                planeDown,\n                planeNorth,\n                planeSouth,\n                planeEast,\n                planeWest\n            ], aabbMin, aabbMax);\n        }\n    }\n}\n\nfunction findAxisMinMax(axis: vec3, points: vec3[]) {\n    let min = +Infinity;\n    let max = -Infinity;\n    for (const c of points) {\n        const dot = vec3.dot(axis, c);\n        min = Math.min(min, dot);\n        max = Math.max(max, dot);\n    }\n    return {\n        min,\n        max\n    };\n}", "import {type mat2, mat4, vec3, vec4} from 'gl-matrix';\nimport {TransformHelper} from '../transform_helper.ts';\nimport {LngLat, type LngLatLike, earthRadius} from '../lng_lat.ts';\nimport {angleToRotateBetweenVectors2D, clamp, createIdentityMat4f32, degreesToRadians, radiansToDegrees, scaleZoom, createIdentityMat4f64, createMat4f64, createVec3f64, createVec4f64, differenceOfAnglesDegrees, distanceOfAnglesRadians, MAX_VALID_LATITUDE, pointPlaneSignedDistance, remapSaturate, warnOnce, zoomScale, type Mat4f32} from '../../util/util.ts';\nimport {OverscaledTileID, UnwrappedTileID, type CanonicalTileID} from '../../tile/tile_id.ts';\nimport Point from '@mapbox/point-geometry';\nimport {MercatorCoordinate} from '../mercator_coordinate.ts';\nimport {LngLatBounds} from '../lng_lat_bounds.ts';\nimport {getMercatorTileCoordinates, tileCoordinatesToMercatorCoordinates} from './mercator_utils.ts';\nimport {angularCoordinatesToSurfaceVector, clampToSphere, getGlobeRadiusPixels, getZoomAdjustment, horizonPlaneToCenterAndRadius, mercatorCoordinatesToAngularCoordinatesRadians, planetScaleAtLatitude, projectTileCoordinatesToSphere, raySphereIntersection, sphereSurfacePointToCoordinates} from './globe_utils.ts';\nimport {GlobeCoveringTilesDetailsProvider} from './globe_covering_tiles_details_provider.ts';\nimport {Frustum} from '../../util/primitives/frustum.ts';\nimport {bisect, sampleAt, isBelowTerrainSample, TERRAIN_OCCLUSION_MARGIN, type TerrainCoverageIndex, type TerrainSample} from '../../render/terrain_coverage.ts';\nimport {getBearing, getCenterOffset, getWorldSize} from '../camera_state.ts';\n\nimport type {CameraState} from '../camera_state.ts';\nimport type {PointProjection} from '../../symbol/projection.ts';\nimport type {Terrain} from '../../render/terrain.ts';\nimport type {CameraOptionsFromTo, IReadonlyTransform, ITransform, NearFarZ, TransformConstrainFunction, WorldCoordinateHelper} from '../transform_interface.ts';\nimport type {TransformOptions} from '../transform_helper.ts';\nimport type {PaddingOptions} from '../edge_insets.ts';\nimport type {CustomLayerProjectionData, ProjectionDataParams, RendererProjectionData} from './projection_data.ts';\nimport type {CoveringTilesDetailsProvider} from './covering_tiles_details_provider.ts';\n\nconst GLOBE_SAMPLES = 256;\nconst GLOBE_BISECT_EPSILON_T = 1e-12;\n/** Latitudes outside the mercator range project past the world edge; the globe mesh still covers them. */\nconst MAX_MERCATOR_Y = 1 - 1e-9;\n/** Two points on the unit globe closer than this, a micrometre, are the same point. */\nconst SAME_POINT_DISTANCE = 1e-12;\n/** A camera whose horizontal offset is this small relative to its distance is straight above the center. */\nconst STRAIGHT_ABOVE_RATIO = 1e-9;\n/**\n * How many times larger than the viewport the area past the mercator edge has grown when the center is back on that edge.\n * While the area fits in the viewport the center can be on the pole.\n */\nconst POLE_AREA_FADE_SCALE = 4;\n\n/**\n * @internal\n * A ray to intersect with the terrain surface, in globe coordinates:\n * `origin` and the unit-length `direction` are on the unit sphere, and terrain elevations are in meters above sea level.\n */\ntype GlobeRay = {\n    index: TerrainCoverageIndex;\n    exaggeration: number;\n    origin: vec3;\n    direction: vec3;\n};\n\nexport class VerticalPerspectiveTransform implements ITransform {\n    private _helper: TransformHelper;\n\n    //\n    // Implementation of transform getters and setters\n    //\n\n    get pixelsToClipSpaceMatrix(): mat4 {\n        return this._helper.pixelsToClipSpaceMatrix;\n    }\n    get clipSpaceToPixelsMatrix(): mat4 {\n        return this._helper.clipSpaceToPixelsMatrix;\n    }\n    get pixelsToGLUnits(): [number, number] {\n        return this._helper.pixelsToGLUnits;\n    }\n    get size(): Point {\n        return this._helper.size;\n    }\n    get rotationMatrix(): mat2 {\n        return this._helper.rotationMatrix;\n    }\n    get centerPoint(): Point {\n        return this._helper.centerPoint;\n    }\n    get pixelsPerMeter(): number {\n        return this._helper.pixelsPerMeter;\n    }\n    setMinZoom(zoom: number): void {\n        this._helper.setMinZoom(zoom);\n    }\n    setMaxZoom(zoom: number): void {\n        this._helper.setMaxZoom(zoom);\n    }\n    setMinPitch(pitch: number): void {\n        this._helper.setMinPitch(pitch);\n    }\n    setMaxPitch(pitch: number): void {\n        this._helper.setMaxPitch(pitch);\n    }\n    setRenderWorldCopies(renderWorldCopies: boolean): void {\n        this._helper.setRenderWorldCopies(renderWorldCopies);\n    }\n    setBearing(bearing: number): void {\n        this._helper.setBearing(bearing);\n    }\n    setPitch(pitch: number): void {\n        this._helper.setPitch(pitch);\n    }\n    setRoll(roll: number): void {\n        this._helper.setRoll(roll);\n    }\n    setFov(fov: number): void {\n        this._helper.setFov(fov);\n    }\n    setZoom(zoom: number): void {\n        this._helper.setZoom(zoom);\n    }\n    setCenter(center: LngLat): void {\n        this._helper.setCenter(center);\n    }\n    setElevation(elevation: number): void {\n        this._helper.setElevation(elevation);\n    }\n    setMinElevationForCurrentTile(elevation: number): void {\n        this._helper.setMinElevationForCurrentTile(elevation);\n    }\n    setPadding(padding: PaddingOptions): void {\n        this._helper.setPadding(padding);\n    }\n    interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number): void {\n        this._helper.interpolatePadding(start, target, t);\n    }\n    isPaddingEqual(padding: PaddingOptions): boolean {\n        return this._helper.isPaddingEqual(padding);\n    }\n    resize(width: number, height: number, constrain: boolean = true): void {\n        this._helper.resize(width, height, constrain);\n    }\n    getMaxBounds(): LngLatBounds {\n        return this._helper.getMaxBounds();\n    }\n    setMaxBounds(bounds?: LngLatBounds): void {\n        this._helper.setMaxBounds(bounds);\n    }\n    setConstrainOverride(constrain?: TransformConstrainFunction | null): void {\n        this._helper.setConstrainOverride(constrain);\n    }\n    overrideNearFarZ(nearZ: number, farZ: number): void {\n        this._helper.overrideNearFarZ(nearZ, farZ);\n    }\n    clearNearFarZOverride(): void {\n        this._helper.clearNearFarZOverride();\n    }\n    getCameraQueryGeometry(queryGeometry: Point[]): Point[] {\n        return this._helper.getCameraQueryGeometry(queryGeometry);\n    }\n\n    get tileSize(): number {\n        return this._helper.tileSize;\n    }\n    get tileZoom(): number {\n        return this._helper.tileZoom;\n    }\n    get scale(): number {\n        return this._helper.scale;\n    }\n    get worldSize(): number {\n        return this._helper.worldSize;\n    }\n    get width(): number {\n        return this._helper.width;\n    }\n    get height(): number {\n        return this._helper.height;\n    }\n    get lngRange(): [number, number] {\n        return this._helper.lngRange;\n    }\n    get latRange(): [number, number] {\n        return this._helper.latRange;\n    }\n    get minZoom(): number {\n        return this._helper.minZoom;\n    }\n    get maxZoom(): number {\n        return this._helper.maxZoom;\n    }\n    get zoom(): number {\n        return this._helper.zoom;\n    }\n    get center(): LngLat {\n        return this._helper.center;\n    }\n    get minPitch(): number {\n        return this._helper.minPitch;\n    }\n    get maxPitch(): number {\n        return this._helper.maxPitch;\n    }\n    get pitch(): number {\n        return this._helper.pitch;\n    }\n    get pitchInRadians(): number {\n        return this._helper.pitchInRadians;\n    }\n    get roll(): number {\n        return this._helper.roll;\n    }\n    get rollInRadians(): number {\n        return this._helper.rollInRadians;\n    }\n    get bearing(): number {\n        return this._helper.bearing;\n    }\n    get bearingInRadians(): number {\n        return this._helper.bearingInRadians;\n    }\n    get fov(): number {\n        return this._helper.fov;\n    }\n    get fovInRadians(): number {\n        return this._helper.fovInRadians;\n    }\n    get elevation(): number {\n        return this._helper.elevation;\n    }\n    get minElevationForCurrentTile(): number {\n        return this._helper.minElevationForCurrentTile;\n    }\n    get padding(): PaddingOptions {\n        return this._helper.padding;\n    }\n    get unmodified(): boolean {\n        return this._helper.unmodified;\n    }\n    get renderWorldCopies(): boolean {\n        return this._helper.renderWorldCopies;\n    }\n    get constrainOverride(): TransformConstrainFunction {\n        return this._helper.constrainOverride;\n    }\n    public get nearZ(): number {\n        return this._nearZ;\n    }\n    public get farZ(): number {\n        return this._farZ;\n    }\n    public get nearFarZOverride(): NearFarZ | null {\n        return this._helper.nearFarZOverride;\n    }\n    public get autoCalculateNearFarZ(): boolean {\n        return this._helper.autoCalculateNearFarZ;\n    }\n    setTransitionState(_value: number): void {\n        // Do nothing\n    }\n    //\n    // Implementation of globe transform\n    //\n\n    private _cachedClippingPlane: vec4 = createVec4f64();\n    private _cachedFrustum: Frustum;\n    private _projectionMatrix: mat4 = createIdentityMat4f64();\n    private _globeViewProjMatrix32f: Mat4f32 = createIdentityMat4f32(); // Must be 32 bit floats, otherwise WebGL calls in Chrome get very slow.\n    private _globeViewProjMatrixF64: mat4 = createIdentityMat4f64();\n    private _globeViewProjMatrixF64Inverted: mat4 = createIdentityMat4f64();\n    private _globeProjMatrixInverted: mat4 = createIdentityMat4f64();\n\n    private _cameraPosition: vec3 = createVec3f64();\n    private _nearZ: number;\n    private _farZ: number;\n    /**\n     * Globe projection can smoothly interpolate between globe view and mercator. This variable controls this interpolation.\n     * Value 0 is mercator, value 1 is globe, anything between is an interpolation between the two projections.\n     */\n\n    private _coveringTilesDetailsProvider: GlobeCoveringTilesDetailsProvider;\n\n    /**\n     * @param options - Initial state. Ignored when `sharedHelper` is given, which already carries it.\n     * @param sharedHelper - Camera to use instead of owning one, so that a composing transform such as\n     * {@link GlobeTransform} keeps a single copy of the state rather than one per child. Its owner then drives\n     * {@link _calcMatrices}, because a helper has only one `calcMatrices` callback.\n     */\n    public constructor(options?: TransformOptions, sharedHelper?: TransformHelper) {\n        this._helper = sharedHelper ?? new TransformHelper({\n            calcMatrices: () => this._calcMatrices(),\n            defaultConstrain: (center, zoom) => { return this.defaultConstrain(center, zoom); }\n        }, options);\n        this._coveringTilesDetailsProvider = new GlobeCoveringTilesDetailsProvider();\n    }\n\n    private get _cameraState(): Readonly<CameraState> {\n        return this._helper.cameraState;\n    }\n\n    clone(): ITransform {\n        const clone = new VerticalPerspectiveTransform();\n        clone.apply(this, false);\n        return clone;\n    }\n\n    public apply(that: IReadonlyTransform, constrain: boolean): void {\n        this._helper.apply(that, constrain);\n    }\n\n    public get projectionMatrix(): mat4 { return this._projectionMatrix; }\n\n    public get modelViewProjectionMatrix(): mat4 { return this._globeViewProjMatrixF64; }\n\n    public get inverseProjectionMatrix(): mat4 { return this._globeProjMatrixInverted; }\n\n    public get cameraPosition(): vec3 {\n        // Return a copy - don't let outside code mutate our precomputed camera position.\n        const copy = createVec3f64(); // Ensure the resulting vector is float64s\n        copy[0] = this._cameraPosition[0];\n        copy[1] = this._cameraPosition[1];\n        copy[2] = this._cameraPosition[2];\n        return copy;\n    }\n\n    get cameraToCenterDistance(): number {\n        // Globe uses the same cameraToCenterDistance as mercator.\n        return this._helper.cameraToCenterDistance;\n    }\n\n    getProjectionData(params: ProjectionDataParams): RendererProjectionData {\n        const {overscaledTileID, applyGlobeMatrix} = params;\n        const mercatorTileCoordinates = getMercatorTileCoordinates(overscaledTileID);\n        return {\n            mainMatrix: this._globeViewProjMatrix32f,\n            tileMercatorCoords: mercatorTileCoordinates,\n            clippingPlane: this._cachedClippingPlane as [number, number, number, number],\n            projectionTransition: applyGlobeMatrix ? 1 : 0,\n            fallbackMatrix: this._globeViewProjMatrix32f,\n            clipAntimeridian: overscaledTileID?.canonical.z === 0,\n        };\n    }\n\n    private _computeClippingPlane(globeRadiusPixels: number): vec4 {\n        // We want to compute a plane equation that, when applied to the unit sphere generated\n        // in the vertex shader, places all visible parts of the sphere into the positive half-space\n        // and all the non-visible parts in the negative half-space.\n        // We can then use that to accurately clip all non-visible geometry.\n\n        // cam....------------A\n        //        ....        |\n        //            ....    |\n        //                ....B\n        //                ggggggggg\n        //          gggggg    |   .gggggg\n        //       ggg          |       ...ggg    ^\n        //     gg             |                 |\n        //    g               |                 y\n        //    g               |                 |\n        //   g                C                 #---x--->\n        //\n        // Notes:\n        // - note the coordinate axes\n        // - \"g\" marks the globe edge\n        // - the dotted line is the camera center \"ray\" - we are looking in this direction\n        // - \"cam\" is camera origin\n        // - \"C\" is globe center\n        // - \"B\" is the point on \"top\" of the globe - camera is looking at B - \"B\" is the intersection between the camera center ray and the globe\n        // - this._pitchInRadians is the angle at B between points cam,B,A\n        // - this.cameraToCenterDistance is the distance from camera to \"B\"\n        // - globe radius is (0.5 * this.worldSize)\n        // - \"T\" is any point where a tangent line from \"cam\" touches the globe surface\n        // - elevation is assumed to be zero - globe rendering must be separate from terrain rendering anyway\n\n        const pitch = this._cameraState.pitchInRadians;\n        // scale things so that the globe radius is 1\n        const distanceCameraToB = this._cameraState.cameraToCenterDistance / globeRadiusPixels;\n        const radius = 1;\n\n        // Distance from camera to \"A\" - the point at the same elevation as camera, right above center point on globe\n        const distanceCameraToA = Math.sin(pitch) * distanceCameraToB;\n        // Distance from \"A\" to \"C\"\n        const distanceAtoC = (Math.cos(pitch) * distanceCameraToB + radius);\n        // Distance from camera to \"C\" - the globe center\n        const distanceCameraToC = Math.sqrt(distanceCameraToA * distanceCameraToA + distanceAtoC * distanceAtoC);\n        // cam - C - T angle cosine (at C)\n        const camCTcosine = radius / distanceCameraToC;\n        // Distance from globe center to the plane defined by all possible \"T\" points\n        const tangentPlaneDistanceToC = camCTcosine * radius;\n\n        let vectorCtoCamX = -distanceCameraToA;\n        let vectorCtoCamY = distanceAtoC;\n        // Normalize the vector\n        const vectorCtoCamLength = Math.sqrt(vectorCtoCamX * vectorCtoCamX + vectorCtoCamY * vectorCtoCamY);\n        vectorCtoCamX /= vectorCtoCamLength;\n        vectorCtoCamY /= vectorCtoCamLength;\n\n        // Note the swizzled components\n        const planeVector: vec3 = [0, vectorCtoCamX, vectorCtoCamY];\n        // Apply transforms - lat, lng and angle (NOT pitch - already accounted for, as it affects the tangent plane)\n        vec3.rotateZ(planeVector, planeVector, [0, 0, 0], -this._cameraState.bearingInRadians);\n        vec3.rotateX(planeVector, planeVector, [0, 0, 0], -1 * this._cameraState.center.lat * Math.PI / 180.0);\n        vec3.rotateY(planeVector, planeVector, [0, 0, 0], this._cameraState.center.lng * Math.PI / 180.0);\n        // Normalize the plane vector\n        const scale = 1 / vec3.length(planeVector);\n        vec3.scale(planeVector, planeVector, scale);\n        return [...planeVector, -tangentPlaneDistanceToC * scale];\n    }\n\n    /** {@inheritDoc ITransform.isLocationOccluded} */\n    public isLocationOccluded(lngLat: LngLat, terrain?: Terrain, elevation?: number): boolean {\n        const coverage = terrain?.getCoverageIndex();\n        elevation ??= coverage ? terrain.getElevationForLngLat(lngLat, this._cameraState.tileZoom) : 0;\n        const location = raisedSurfaceVector(lngLat, elevation);\n        if (!this.isSurfacePointVisible(location)) return true;\n        if (!coverage) return false;\n\n        const p = this._projectSurfacePointToScreen(location);\n        const origin = this.cameraPosition;\n        const direction = this.getRayDirectionFromPixel(p);\n        const tLocation = rayParameter(origin, direction, location);\n        if (tLocation <= 0) return true;\n\n        const hit = this.screenTerrainPointToMercatorCoordinate(p, terrain);\n        return hit != null && rayParameter(origin, direction, raisedSurfaceVector(hit.toLngLat(), hit.z)) < tLocation * (1 - TERRAIN_OCCLUSION_MARGIN);\n    }\n\n    public transformLightDirection(dir: vec3): vec3 {\n        const sphereX = this._cameraState.center.lng * Math.PI / 180.0;\n        const sphereY = this._cameraState.center.lat * Math.PI / 180.0;\n\n        const len = Math.cos(sphereY);\n        const spherePos: vec3 = [\n            Math.sin(sphereX) * len,\n            Math.sin(sphereY),\n            Math.cos(sphereX) * len\n        ];\n\n        const axisRight: vec3 = [spherePos[2], 0.0, -spherePos[0]]; // Equivalent to cross(vec3(0.0, 1.0, 0.0), vec)\n        const axisDown: vec3 = [0, 0, 0];\n        vec3.cross(axisDown, axisRight, spherePos);\n        vec3.normalize(axisRight, axisRight);\n        vec3.normalize(axisDown, axisDown);\n\n        const transformed: vec3 = [\n            axisRight[0] * dir[0] + axisDown[0] * dir[1] + spherePos[0] * dir[2],\n            axisRight[1] * dir[0] + axisDown[1] * dir[1] + spherePos[1] * dir[2],\n            axisRight[2] * dir[0] + axisDown[2] * dir[1] + spherePos[2] * dir[2]\n        ];\n\n        const normalized: vec3 = [0, 0, 0];\n        vec3.normalize(normalized, transformed);\n        return normalized;\n    }\n\n    public getPixelScale(): number {\n        return 1.0 / planetScaleAtLatitude(this._cameraState.center.lat);\n    }\n\n    public getCircleRadiusCorrection(): number {\n        return planetScaleAtLatitude(this._cameraState.center.lat);\n    }\n\n    public getPitchedTextCorrection(textAnchorX: number, textAnchorY: number, tileID: UnwrappedTileID): number {\n        const mercator = tileCoordinatesToMercatorCoordinates(textAnchorX, textAnchorY, tileID.canonical);\n        const angular = mercatorCoordinatesToAngularCoordinatesRadians(mercator.x, mercator.y);\n        return this.getCircleRadiusCorrection() / Math.cos(angular[1]);\n    }\n\n    public projectTileCoordinates(x: number, y: number, unwrappedTileID: UnwrappedTileID, elevation?: number): PointProjection {\n        const canonical = unwrappedTileID.canonical;\n        const spherePos = projectTileCoordinatesToSphere(x, y, canonical.x, canonical.y, canonical.z);\n        const vectorMultiplier = 1.0 + (elevation ?? 0.0) / earthRadius;\n        const elevatedX = spherePos[0] * vectorMultiplier;\n        const elevatedY = spherePos[1] * vectorMultiplier;\n        const elevatedZ = spherePos[2] * vectorMultiplier;\n        const pos: vec4 = [elevatedX, elevatedY, elevatedZ, 1];\n        vec4.transformMat4(pos, pos, this._globeViewProjMatrixF64);\n\n        let isOccluded: boolean;\n        if (vectorMultiplier <= 1.0) {\n            const plane = this._cachedClippingPlane;\n            isOccluded = plane[0] * spherePos[0] + plane[1] * spherePos[1] + plane[2] * spherePos[2] + plane[3] < 0.0;\n        } else {\n            isOccluded = this._isLineOfSightBlocked(elevatedX, elevatedY, elevatedZ);\n        }\n\n        return {\n            point: new Point(pos[0] / pos[3], pos[1] / pos[3]),\n            signedDistanceFromCamera: pos[3],\n            isOccluded\n        };\n    }\n\n    /**\n     * True when the segment from the camera to the given point, both in unit-globe coordinates, passes through the planet.\n     */\n    private _isLineOfSightBlocked(x: number, y: number, z: number): boolean {\n        const cam = this._cameraPosition;\n        const dx = x - cam[0];\n        const dy = y - cam[1];\n        const dz = z - cam[2];\n        const lengthSq = dx * dx + dy * dy + dz * dz;\n        if (lengthSq === 0) return false;\n        const t = clamp(-(cam[0] * dx + cam[1] * dy + cam[2] * dz) / lengthSq, 0, 1);\n        const cx = cam[0] + t * dx;\n        const cy = cam[1] + t * dy;\n        const cz = cam[2] + t * dz;\n        return cx * cx + cy * cy + cz * cz < 1.0;\n    }\n\n    /**\n     * The computed far plane only has to be far enough to take in the globe, since the vertex shader computes its own\n     * depth.\n     * @param nearFarZ - The depth range to use instead of computing one, by default the camera state's override.\n     */\n    _calcMatrices(nearFarZ: NearFarZ | null = this._cameraState.nearFarZOverride): void {\n        const globeRadiusPixels = getGlobeRadiusPixels(getWorldSize(this._cameraState), this._cameraState.center.lat);\n\n        // Construct a completely separate matrix for globe view\n        const globeMatrix = createMat4f64();\n        const {nearZ, farZ} = nearFarZ ?? {nearZ: 0.5, farZ: this._cameraState.cameraToCenterDistance + globeRadiusPixels * 2.0};\n        this._nearZ = nearZ;\n        this._farZ = farZ;\n        mat4.perspective(globeMatrix, this._cameraState.fovInRadians, this._cameraState.width / this._cameraState.height, this._nearZ, this._farZ);\n\n        // Apply center of perspective offset\n        const offset = getCenterOffset(this._cameraState);\n        globeMatrix[8] = -offset.x * 2 / this._cameraState.width;\n        globeMatrix[9] = offset.y * 2 / this._cameraState.height;\n        this._projectionMatrix = mat4.clone(globeMatrix);\n\n        this._globeProjMatrixInverted = createMat4f64();\n        mat4.invert(this._globeProjMatrixInverted, globeMatrix);\n        mat4.translate(globeMatrix, globeMatrix, [0, 0, -this._cameraState.cameraToCenterDistance]);\n        mat4.rotateZ(globeMatrix, globeMatrix, this._cameraState.rollInRadians);\n        mat4.rotateX(globeMatrix, globeMatrix, -this._cameraState.pitchInRadians);\n        mat4.rotateZ(globeMatrix, globeMatrix, this._cameraState.bearingInRadians);\n        mat4.translate(globeMatrix, globeMatrix, [0.0, 0, -globeRadiusPixels]);\n        // Rotate the sphere to center it on viewed coordinates\n\n        const scaleVec = createVec3f64();\n        scaleVec[0] = globeRadiusPixels;\n        scaleVec[1] = globeRadiusPixels;\n        scaleVec[2] = globeRadiusPixels;\n\n        mat4.rotateX(globeMatrix, globeMatrix, this._cameraState.center.lat * Math.PI / 180.0);\n        mat4.rotateY(globeMatrix, globeMatrix, -this._cameraState.center.lng * Math.PI / 180.0);\n        mat4.scale(globeMatrix, globeMatrix, scaleVec); // Scale the unit sphere to a sphere with diameter of 1\n        this._globeViewProjMatrixF64 = globeMatrix;\n        this._globeViewProjMatrix32f = new Float32Array(globeMatrix);\n\n        this._globeViewProjMatrixF64Inverted = createMat4f64();\n        mat4.invert(this._globeViewProjMatrixF64Inverted, globeMatrix);\n\n        const zero = createVec3f64();\n        this._cameraPosition = createVec3f64();\n        this._cameraPosition[2] = this._cameraState.cameraToCenterDistance / globeRadiusPixels;\n        vec3.rotateZ(this._cameraPosition, this._cameraPosition, zero, -this._cameraState.rollInRadians);\n        vec3.rotateX(this._cameraPosition, this._cameraPosition, zero, this._cameraState.pitchInRadians);\n        vec3.rotateZ(this._cameraPosition, this._cameraPosition, zero, -this._cameraState.bearingInRadians);\n        vec3.add(this._cameraPosition, this._cameraPosition, [0, 0, 1]);\n        vec3.rotateX(this._cameraPosition, this._cameraPosition, zero, -this._cameraState.center.lat * Math.PI / 180.0);\n        vec3.rotateY(this._cameraPosition, this._cameraPosition, zero, this._cameraState.center.lng * Math.PI / 180.0);\n\n        this._cachedClippingPlane = this._computeClippingPlane(globeRadiusPixels);\n\n        const matrix = mat4.clone(this._globeViewProjMatrixF64Inverted);\n        mat4.scale(matrix, matrix, [1, 1, -1]);\n        this._cachedFrustum = Frustum.fromInvProjectionMatrix(matrix, 1, 0, this._cachedClippingPlane, true);\n    }\n\n    calculateFogMatrix(_unwrappedTileID: UnwrappedTileID): mat4 {\n        warnOnce('calculateFogMatrix is not supported on globe projection.');\n        const m = createMat4f64();\n        mat4.identity(m);\n        return m;\n    }\n\n    getVisibleUnwrappedCoordinates(tileID: CanonicalTileID): UnwrappedTileID[] {\n        // Globe has no wrap.\n        return [new UnwrappedTileID(0, tileID)];\n    }\n\n    getCameraFrustum(): Frustum {\n        return this._cachedFrustum;\n    }\n    getClippingPlane(): vec4 | null {\n        return this._cachedClippingPlane;\n    }\n    getCoveringTilesDetailsProvider(): CoveringTilesDetailsProvider {\n        return this._coveringTilesDetailsProvider;\n    }\n\n    recalculateZoomAndCenter(terrain?: Terrain): void {\n        if (terrain) {\n            warnOnce('terrain is not fully supported on vertical perspective projection.');\n            return;\n        }\n        this._helper.recalculateZoomAndCenter(0);\n    }\n\n    maxPitchScaleFactor(): number {\n        // In mercaltor it uses the pixelMatrix, but this is not available here...\n        return 1;\n    }\n\n    getCameraPoint(): Point {\n        return this._helper.getCameraPoint();\n    }\n\n    /**\n     * The altitude of the rendered camera above sea level. The sphere keeps the center point at sea level whatever its\n     * elevation (`_calcMatrices` does not apply it), so unlike on mercator the center elevation does not lift the camera.\n     * {@link calculateCameraOptionsFromTo} is the inverse.\n     */\n    getCameraAltitude(): number {\n        // The camera position is in unit-globe coordinates, with the sea-level surface at radius 1.\n        return (vec3.length(this._cameraPosition) - 1) * earthRadius;\n    }\n\n    getCameraLngLat(): LngLat {\n        const surface = createVec3f64();\n        vec3.normalize(surface, this._cameraPosition);\n        return sphereSurfacePointToCoordinates(surface);\n    }\n\n    get worldCoordinateHelper(): WorldCoordinateHelper {\n        return this._helper.worldCoordinateHelper;\n    }\n\n    getBounds(): LngLatBounds {\n        const xMid = this._cameraState.width * 0.5;\n        const yMid = this._cameraState.height * 0.5;\n\n        // LngLat extremes will probably tend to be in screen corners or in middle of screen edges.\n        // These test points should result in a pretty good approximation.\n        const testPoints = [\n            new Point(0, 0),\n            new Point(xMid, 0),\n            new Point(this._cameraState.width, 0),\n            new Point(this._cameraState.width, yMid),\n            new Point(this._cameraState.width, this._cameraState.height),\n            new Point(xMid, this._cameraState.height),\n            new Point(0, this._cameraState.height),\n            new Point(0, yMid),\n        ];\n\n        const projectedPoints = [];\n        for (const p of testPoints) {\n            projectedPoints.push(this.unprojectScreenPoint(p));\n        }\n\n        // We can't construct a simple min/max aabb, since points might lie on either side of the antimeridian.\n        // We will instead compute the furthest points relative to map center.\n        // We also take advantage of the fact that `unprojectScreenPoint` will snap pixels\n        // outside the planet to the closest point on the planet's horizon.\n        let mostEast = 0, mostWest = 0, mostNorth = 0, mostSouth = 0; // We will store these values signed.\n        const center = this._cameraState.center;\n        for (const p of projectedPoints) {\n            const dLng = differenceOfAnglesDegrees(center.lng, p.lng);\n            const dLat = differenceOfAnglesDegrees(center.lat, p.lat);\n            if (dLng < mostWest) {\n                mostWest = dLng;\n            }\n            if (dLng > mostEast) {\n                mostEast = dLng;\n            }\n            if (dLat < mostSouth) {\n                mostSouth = dLat;\n            }\n            if (dLat > mostNorth) {\n                mostNorth = dLat;\n            }\n        }\n\n        const boundsArray: [number, number, number, number] = [\n            center.lng + mostWest,  // west\n            center.lat + mostSouth, // south\n            center.lng + mostEast,  // east\n            center.lat + mostNorth  // north\n        ];\n\n        // Sometimes the poles might end up not being on the horizon,\n        // thus not being detected as the northernmost/southernmost points.\n        // We fix that here.\n        if (this.isSurfacePointOnScreen([0, 1, 0])) {\n            // North pole is visible\n            // This also means that the entire longitude range must be visible\n            boundsArray[3] = 90;\n            boundsArray[0] = -180;\n            boundsArray[2] = 180;\n        }\n        if (this.isSurfacePointOnScreen([0, -1, 0])) {\n            // South pole is visible\n            boundsArray[1] = -90;\n            boundsArray[0] = -180;\n            boundsArray[2] = 180;\n        }\n\n        return new LngLatBounds(boundsArray);\n    }\n\n    defaultConstrain: TransformConstrainFunction = (lngLat, zoom) => {\n        // Globe: TODO: respect _lngRange, _latRange\n        // It is possible to implement exact constrain for globe, but I don't think it is worth the effort.\n        const constrainedZoom = clamp(+zoom, this._cameraState.minZoom + getZoomAdjustment(0, lngLat.lat), this._cameraState.maxZoom);\n        const maxLatitude = this._getMaxLatitude(constrainedZoom);\n        return {\n            center: new LngLat(\n                lngLat.lng,\n                clamp(lngLat.lat, -maxLatitude, maxLatitude)\n            ),\n            zoom: constrainedZoom\n        };\n    };\n\n    /**\n     * Returns how close to a pole the center can be at the given zoom. Past the mercator edge there is no data,\n     * so the center reaches the pole only while that area fits in the viewport, and eases back to the edge as it outgrows it.\n     */\n    private _getMaxLatitude(zoom: number): number {\n        const areaRadians = degreesToRadians(90 - MAX_VALID_LATITUDE);\n        const areaPixels = getGlobeRadiusPixels(this._cameraState.tileSize * zoomScale(zoom), MAX_VALID_LATITUDE) * areaRadians;\n        const reachPixels = Math.min(this._cameraState.width, this._cameraState.height) / 2;\n        const centerPixels = Math.min(areaPixels, reachPixels) * remapSaturate(areaPixels, reachPixels, reachPixels * POLE_AREA_FADE_SCALE, 1, 0);\n        return MAX_VALID_LATITUDE + radiansToDegrees(areaRadians * centerPixels / areaPixels);\n    }\n\n    applyConstrain: TransformConstrainFunction = (lngLat, zoom) => {\n        return this._helper.applyConstrain(lngLat, zoom);\n    };\n\n    calculateCenterFromCameraLngLatAlt(lngLat: LngLatLike, alt: number, bearing?: number, pitch?: number): {center: LngLat; elevation: number; zoom: number} {\n        return this._helper.calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch);\n    }\n\n    /**\n     * Inverts the camera placement of `_calcMatrices` in unit-globe coordinates: the camera sits at radius\n     * `1 + altitudeFrom / earthRadius` and looks at the center on the sea-level sphere, the target altitude only becoming\n     * the center elevation (the inverse of {@link getCameraAltitude}). Pitch and bearing are read in the center's local\n     * frame, +z up, +y north, +x east. A camera straight above the center keeps the transform's bearing.\n     */\n    calculateCameraOptionsFromTo(from: LngLatLike, altitudeFrom: number, to: LngLatLike, altitudeTo: number): CameraOptionsFromTo {\n        const center = LngLat.convert(to);\n        const camera = angularCoordinatesToSurfaceVector(LngLat.convert(from));\n        vec3.scale(camera, camera, 1 + altitudeFrom / earthRadius);\n        const target = angularCoordinatesToSurfaceVector(center);\n        const targetAtAltitude = vec3.scale(createVec3f64(), target, 1 + altitudeTo / earthRadius);\n        const toCamera = vec3.subtract(createVec3f64(), camera, target);\n        const distance = vec3.length(toCamera);\n        if (distance < SAME_POINT_DISTANCE || vec3.distance(camera, targetAtAltitude) < SAME_POINT_DISTANCE) {\n            throw new Error('Can\\'t calculate camera options with same From and To');\n        }\n\n        const zero = createVec3f64();\n        vec3.rotateY(toCamera, toCamera, zero, -degreesToRadians(center.lng));\n        vec3.rotateX(toCamera, toCamera, zero, degreesToRadians(center.lat));\n        const pitch = radiansToDegrees(Math.acos(clamp(toCamera[2] / distance, -1, 1)));\n        const straightAbove = Math.hypot(toCamera[0], toCamera[1]) < distance * STRAIGHT_ABOVE_RATIO;\n        const bearing = straightAbove ? getBearing(this._cameraState) : radiansToDegrees(Math.atan2(-toCamera[0], -toCamera[1]));\n\n        // The camera sits cameraToCenterDistance / getGlobeRadiusPixels(worldSize, lat) from the center, and the radius doubles per zoom level.\n        const zoom = scaleZoom(this._cameraState.cameraToCenterDistance / distance / getGlobeRadiusPixels(this._cameraState.tileSize, center.lat));\n\n        return {center, elevation: altitudeTo, zoom, pitch, bearing};\n    }\n\n    /**\n     * Note: automatically adjusts zoom to keep planet size consistent\n     * (same size before and after a {@link setLocationAtPoint} call).\n     */\n    setLocationAtPoint(lnglat: LngLat, point: Point, _elevation?: number): void {\n        const camera = this.getCameraForLocationAtPoint(lnglat, point);\n        if (camera) this._helper.setCenterAndZoom(camera.center, camera.zoom);\n    }\n\n    /**\n     * The center and zoom that {@link setLocationAtPoint} moves the camera to, or null where the camera stays where it\n     * is. The zoom keeps the planet at the size it has now, from the latitude the constrain lets the center reach.\n     */\n    getCameraForLocationAtPoint(lnglat: LngLat, point: Point): {center: LngLat; zoom: number} | null {\n        // The elevation is ignored: this transform solves on the planet's surface.\n        // This returns some fake coordinates for pixels that do not lie on the planet.\n        // Whatever uses this `setLocationAtPoint` function will need to account for that.\n        const pointLngLat = this.unprojectScreenPoint(point);\n        const vecToPixelCurrent = angularCoordinatesToSurfaceVector(pointLngLat);\n        const vecToTarget = angularCoordinatesToSurfaceVector(lnglat);\n\n        const zero = createVec3f64();\n        vec3.zero(zero);\n\n        const rotatedPixelVector = createVec3f64();\n        vec3.rotateY(rotatedPixelVector, vecToPixelCurrent, zero, -this._cameraState.center.lng * Math.PI / 180.0);\n        vec3.rotateX(rotatedPixelVector, rotatedPixelVector, zero, this._cameraState.center.lat * Math.PI / 180.0);\n\n        // We are looking for the lng,lat that will rotate `vecToTarget`\n        // so that it is equal to `rotatedPixelVector`.\n\n        // The second rotation around X axis cannot change the X component,\n        // so we first must find the longitude such that rotating `vecToTarget` with it\n        // will place it so its X component is equal to X component of `rotatedPixelVector`.\n        // There will exist zero, one or two longitudes that satisfy this.\n\n        //      x  |\n        //     /   |\n        //    /    | the line is the target X - rotatedPixelVector.x\n        //   /     | the x is vecToTarget projected to x,z plane\n        //  .      | the dot is origin\n        //\n        // We need to rotate vecToTarget so that it intersects the line.\n        // If vecToTarget is shorter than the distance to the line from origin, it is impossible.\n\n        // Otherwise, we compute the intersection of the line with a ring with radius equal to\n        // length of vecToTarget projected to XZ plane.\n\n        const vecToTargetXZLengthSquared = vecToTarget[0] * vecToTarget[0] + vecToTarget[2] * vecToTarget[2];\n        const targetXSquared = rotatedPixelVector[0] * rotatedPixelVector[0];\n        if (vecToTargetXZLengthSquared < targetXSquared) {\n            // Zero solutions - setLocationAtPoint is impossible.\n            return null;\n        }\n\n        // The intersection's Z coordinates\n        const intersectionA = Math.sqrt(vecToTargetXZLengthSquared - targetXSquared);\n        const intersectionB = -intersectionA; // the second solution\n\n        const lngA = angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionA);\n        const lngB = angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionB);\n\n        const vecToTargetLngA = createVec3f64();\n        vec3.rotateY(vecToTargetLngA, vecToTarget, zero, -lngA);\n        const latA = angleToRotateBetweenVectors2D(vecToTargetLngA[1], vecToTargetLngA[2], rotatedPixelVector[1], rotatedPixelVector[2]);\n        const vecToTargetLngB = createVec3f64();\n        vec3.rotateY(vecToTargetLngB, vecToTarget, zero, -lngB);\n        const latB = angleToRotateBetweenVectors2D(vecToTargetLngB[1], vecToTargetLngB[2], rotatedPixelVector[1], rotatedPixelVector[2]);\n        // Is at least one of the needed latitudes valid?\n\n        const limit = Math.PI * 0.5;\n\n        const isValidA = latA >= -limit && latA <= limit;\n        const isValidB = latB >= -limit && latB <= limit;\n\n        let validLng: number;\n        let validLat: number;\n        if (isValidA && isValidB) {\n            // Pick the solution that is closer to current map center.\n            const centerLngRadians = this._cameraState.center.lng * Math.PI / 180.0;\n            const centerLatRadians = this._cameraState.center.lat * Math.PI / 180.0;\n            const lngDistA = distanceOfAnglesRadians(lngA, centerLngRadians);\n            const latDistA = distanceOfAnglesRadians(latA, centerLatRadians);\n            const lngDistB = distanceOfAnglesRadians(lngB, centerLngRadians);\n            const latDistB = distanceOfAnglesRadians(latB, centerLatRadians);\n\n            if ((lngDistA + latDistA) < (lngDistB + latDistB)) {\n                validLng = lngA;\n                validLat = latA;\n            } else {\n                validLng = lngB;\n                validLat = latB;\n            }\n        } else if (isValidA) {\n            validLng = lngA;\n            validLat = latA;\n        } else if (isValidB) {\n            validLng = lngB;\n            validLat = latB;\n        } else {\n            // No solution.\n            return null;\n        }\n\n        const newLng = validLng / Math.PI * 180;\n        const newLat = clamp(validLat / Math.PI * 180, -90, 90);\n        const moved = newLng !== this._cameraState.center.lng || newLat !== this._cameraState.center.lat;\n        const {center, zoom} = moved ?\n            this._helper.getConstrainedCamera(new LngLat(newLng, newLat), this._cameraState.zoom) :\n            {center: this._cameraState.center, zoom: this._cameraState.zoom};\n        const adjustedZoom = this.applyConstrain(center, zoom + getZoomAdjustment(this._cameraState.center.lat, center.lat)).zoom;\n        if (adjustedZoom !== zoom) return this._helper.getConstrainedCamera(center, adjustedZoom);\n        return moved ? {center, zoom} : null;\n    }\n\n    locationToScreenPoint(lnglat: LngLat, terrain?: Terrain): Point {\n        const pos = angularCoordinatesToSurfaceVector(lnglat);\n\n        if (terrain) {\n            const elevation = terrain.getElevationForLngLat(lnglat, this._cameraState.tileZoom);\n            vec3.scale(pos, pos, 1.0 + elevation / earthRadius);\n        }\n\n        return this._projectSurfacePointToScreen(pos);\n    }\n\n    /**\n     * Projects a given vector on the surface of a unit sphere (or possible above the surface)\n     * and returns its coordinates on screen in pixels.\n     */\n    private _projectSurfacePointToScreen(pos: vec3): Point {\n        const projected = createVec4f64();\n        vec4.transformMat4(projected, [...pos, 1] as vec4, this._globeViewProjMatrixF64);\n        projected[0] /= projected[3];\n        projected[1] /= projected[3];\n        return new Point(\n            (projected[0] * 0.5 + 0.5) * this._cameraState.width,\n            (-projected[1] * 0.5 + 0.5) * this._cameraState.height\n        );\n    }\n\n    screenPointToMercatorCoordinate(p: Point, terrain?: Terrain): MercatorCoordinate {\n        if (terrain) {\n            const coordinate = this.screenTerrainPointToMercatorCoordinate(p, terrain);\n            if (coordinate) {\n                return coordinate;\n            }\n        }\n        return MercatorCoordinate.fromLngLat(this.unprojectScreenPoint(p));\n    }\n\n    /** {@inheritDoc ITransform.screenTerrainPointToMercatorCoordinate} */\n    screenTerrainPointToMercatorCoordinate(p: Point, terrain: Terrain): MercatorCoordinate | null {\n        const index = terrain.getCoverageIndex();\n        if (!index) return null;\n\n        const origin = this.cameraPosition;\n        const direction = this.getRayDirectionFromPixel(p);\n        const outer = raySphereIntersection(origin, direction, 1 + index.maxElevation / earthRadius);\n        if (!outer) return null;\n        const inner = raySphereIntersection(origin, direction, 1 + index.minElevation / earthRadius);\n\n        const tStart = Math.max(outer.tMin, 0);\n        const tEnd = inner ? inner.tMin : outer.tMax;\n        if (tEnd <= tStart) return null;\n\n        const ray: GlobeRay = {index, exaggeration: terrain.exaggeration, origin, direction};\n\n        let previousT = 0;\n        for (let i = 0; i <= GLOBE_SAMPLES; i++) {\n            const t = tStart + (tEnd - tStart) * i / GLOBE_SAMPLES;\n            if (globeIsBelowTerrain(ray, t)) {\n                const {hi} = bisect(ray, globeIsBelowTerrain, previousT, t, GLOBE_BISECT_EPSILON_T);\n                const {sample, mercator} = globeSampleAt(ray, hi);\n                return new MercatorCoordinate(mercator.x, mercator.y, sample.elevation);\n            }\n            previousT = t;\n        }\n\n        return null;\n    }\n\n    screenPointToLocation(p: Point, terrain?: Terrain): LngLat {\n        return this.screenPointToMercatorCoordinate(p, terrain)?.toLngLat();\n    }\n\n    screenPointToLocationAtElevation(p: Point, _elevation: number): LngLat {\n        // No flat ground plane to intersect at an elevation: use the planet surface.\n        return this.screenPointToLocation(p);\n    }\n\n    isPointOnMapSurface(p: Point, _terrain?: Terrain): boolean {\n        const rayOrigin = this._cameraPosition;\n        const rayDirection = this.getRayDirectionFromPixel(p);\n\n        const intersection = raySphereIntersection(rayOrigin, rayDirection);\n\n        return !!intersection;\n    }\n\n    /**\n     * Computes normalized direction of a ray from the camera to the given screen pixel.\n     */\n    getRayDirectionFromPixel(p: Point): vec3 {\n        const pos = createVec4f64();\n        pos[0] = (p.x / this._cameraState.width) * 2.0 - 1.0;\n        pos[1] = ((p.y / this._cameraState.height) * 2.0 - 1.0) * -1.0;\n        pos[2] = 1;\n        pos[3] = 1;\n        vec4.transformMat4(pos, pos, this._globeViewProjMatrixF64Inverted);\n        pos[0] /= pos[3];\n        pos[1] /= pos[3];\n        pos[2] /= pos[3];\n        const ray = createVec3f64();\n        ray[0] = pos[0] - this._cameraPosition[0];\n        ray[1] = pos[1] - this._cameraPosition[1];\n        ray[2] = pos[2] - this._cameraPosition[2];\n        const rayNormalized: vec3 = createVec3f64();\n        vec3.normalize(rayNormalized, ray);\n        return rayNormalized;\n    }\n\n    /**\n     * For a given point on the unit sphere of the planet, or raised above it, returns whether it lies on the camera's\n     * side of the horizon plane, the plane the globe shaders clip with (not taking into account camera rotation at all).\n     */\n    private isSurfacePointVisible(p: vec3): boolean {\n        const plane = this._cachedClippingPlane;\n        // dot(position on sphere, occlusion plane equation)\n        const dotResult = plane[0] * p[0] + plane[1] * p[1] + plane[2] * p[2] + plane[3];\n        return dotResult >= 0.0;\n    }\n\n    /**\n     * Returns whether surface point is visible on screen.\n     * It must both project to a pixel in screen bounds and not be occluded by the planet.\n     */\n    private isSurfacePointOnScreen(vec: vec3): boolean {\n        if (!this.isSurfacePointVisible(vec)) {\n            return false;\n        }\n\n        const projected = createVec4f64();\n        vec4.transformMat4(projected, [...vec, 1] as vec4, this._globeViewProjMatrixF64);\n        projected[0] /= projected[3];\n        projected[1] /= projected[3];\n        projected[2] /= projected[3];\n        return projected[0] > -1 && projected[0] < 1 &&\n            projected[1] > -1 && projected[1] < 1 &&\n            projected[2] > -1 && projected[2] < 1;\n    }\n\n    /**\n     * @internal\n     * Returns a {@link LngLat} representing geographical coordinates that correspond to the specified pixel coordinates.\n     * Note: if the point does not lie on the globe, returns a location on the visible globe horizon (edge) that is\n     * as close to the point as possible.\n     * @param p - Screen point in pixels to unproject.\n     * @param terrain - Optional terrain.\n     */\n    private unprojectScreenPoint(p: Point): LngLat {\n        // Here we compute the intersection of the ray towards the pixel at `p` and the planet sphere.\n        // As always, we assume that the planet is centered at 0,0,0 and has radius 1.\n        // Ray origin is `_cameraPosition` and direction is `rayNormalized`.\n        const rayOrigin = this._cameraPosition;\n        const rayDirection = this.getRayDirectionFromPixel(p);\n        const intersection = raySphereIntersection(rayOrigin, rayDirection);\n\n        if (intersection) {\n            // Ray intersects the sphere -> compute intersection LngLat.\n            // Assume the ray origin is never inside the sphere - just use tMin\n            const intersectionPoint = createVec3f64();\n            vec3.add(intersectionPoint, rayOrigin, [\n                rayDirection[0] * intersection.tMin,\n                rayDirection[1] * intersection.tMin,\n                rayDirection[2] * intersection.tMin\n            ]);\n            const sphereSurface = createVec3f64();\n            vec3.normalize(sphereSurface, intersectionPoint);\n            return sphereSurfacePointToCoordinates(sphereSurface);\n        }\n\n        // Ray does not intersect the sphere -> find the closest point on the horizon to the ray.\n        // Intersect the ray with the clipping plane, since we know that the intersection of the clipping plane and the sphere is the horizon.\n        const horizonPlane = this._cachedClippingPlane;\n        const directionDotPlaneXyz = horizonPlane[0] * rayDirection[0] + horizonPlane[1] * rayDirection[1] + horizonPlane[2] * rayDirection[2];\n        const originToPlaneDistance = pointPlaneSignedDistance(horizonPlane, rayOrigin);\n        const distanceToIntersection = -originToPlaneDistance / directionDotPlaneXyz;\n\n        const maxRayLength = 2.0; // One globe diameter\n        const planeIntersection = createVec3f64();\n\n        if (distanceToIntersection > 0) {\n            vec3.add(planeIntersection, rayOrigin, [\n                rayDirection[0] * distanceToIntersection,\n                rayDirection[1] * distanceToIntersection,\n                rayDirection[2] * distanceToIntersection\n            ]);\n        } else {\n            // When the ray takes too long to hit the plane (>maxRayLength), or if the plane intersection is behind the camera, handle things differently.\n            // Take a point along the ray at distance maxRayLength, project it to clipping plane, then continue as normal to find the horizon point.\n            const distantPoint = createVec3f64();\n            vec3.add(distantPoint, rayOrigin, [\n                rayDirection[0] * maxRayLength,\n                rayDirection[1] * maxRayLength,\n                rayDirection[2] * maxRayLength\n            ]);\n            const distanceFromPlane = pointPlaneSignedDistance(this._cachedClippingPlane, distantPoint);\n            vec3.sub(planeIntersection, distantPoint, [\n                this._cachedClippingPlane[0] * distanceFromPlane,\n                this._cachedClippingPlane[1] * distanceFromPlane,\n                this._cachedClippingPlane[2] * distanceFromPlane\n            ]);\n        }\n\n        const horizonDisk = horizonPlaneToCenterAndRadius(horizonPlane);\n        const closestOnHorizon = clampToSphere(horizonDisk.center, horizonDisk.radius, planeIntersection);\n\n        return sphereSurfacePointToCoordinates(closestOnHorizon);\n    }\n\n    getProjectionDataForCustomLayer(applyGlobeMatrix: boolean = true): CustomLayerProjectionData {\n        const globeData = this.getProjectionData({overscaledTileID: new OverscaledTileID(0, 0, 0, 0, 0), applyGlobeMatrix});\n        globeData.tileMercatorCoords = [0, 0, 1, 1];\n        return globeData;\n    }\n\n    getFastPathSimpleProjectionMatrix(_tileID: OverscaledTileID): mat4 {\n        return undefined;\n    }\n}\n\n/**\n * Creates a transform for the vertical perspective projection.\n */\nexport function createVerticalPerspectiveTransform(options?: TransformOptions): VerticalPerspectiveTransform {\n    return new VerticalPerspectiveTransform(options);\n}\n\nfunction globeSampleAt(ray: GlobeRay, t: number): {sample: TerrainSample; radius: number; mercator: MercatorCoordinate} {\n    const position = createVec3f64();\n    vec3.scaleAndAdd(position, ray.origin, ray.direction, t);\n    const radius = vec3.length(position);\n    const surface = createVec3f64();\n    vec3.scale(surface, position, 1 / radius);\n    const lngLat = sphereSurfacePointToCoordinates(surface);\n    const projected = MercatorCoordinate.fromLngLat(lngLat);\n    const mercator = new MercatorCoordinate(projected.x, clamp(projected.y, 0, MAX_MERCATOR_Y));\n    const sample = sampleAt(ray.index, ray.exaggeration, mercator.x, mercator.y, false);\n    // The globe mesh caps the poles at elevation zero, matching the GLOBE branch of get_elevation.\n    const elevation = Math.abs(lngLat.lat) > MAX_VALID_LATITUDE ? 0 : sample.elevation;\n    return {sample: {...sample, elevation}, radius, mercator};\n}\n\nfunction globeIsBelowTerrain(ray: GlobeRay, t: number): boolean {\n    const {sample, radius} = globeSampleAt(ray, t);\n    return isBelowTerrainSample(sample, (radius - 1) * earthRadius);\n}\n\n/**\n * The location as a vector from the globe's center in globe radii, raised `elevation` meters above the surface.\n */\nfunction raisedSurfaceVector(lngLat: LngLat, elevation: number): vec3 {\n    const vector = angularCoordinatesToSurfaceVector(lngLat);\n    return vec3.scale(vector, vector, 1 + elevation / earthRadius);\n}\n\n/**\n * Where the point of the ray closest to `point` lies along it, in units of `direction` from `origin`.\n */\nfunction rayParameter(origin: vec3, direction: vec3, point: vec3): number {\n    const offset = vec3.subtract(createVec3f64(), point, origin);\n    return vec3.dot(offset, direction);\n}\n", "import {TransformHelper} from '../transform_helper.ts';\nimport {MercatorTransform} from './mercator_transform.ts';\nimport {VerticalPerspectiveTransform} from './vertical_perspective_transform.ts';\nimport {lerp} from '../../util/util.ts';\n\nimport type {CameraState} from '../camera_state.ts';\nimport type {LngLat, LngLatLike} from '../lng_lat.ts';\nimport type {mat2, mat4, vec3, vec4} from 'gl-matrix';\nimport type {OverscaledTileID, UnwrappedTileID, CanonicalTileID} from '../../tile/tile_id.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {MercatorCoordinate} from '../mercator_coordinate.ts';\nimport type {LngLatBounds} from '../lng_lat_bounds.ts';\nimport type {Frustum} from '../../util/primitives/frustum.ts';\nimport type {Terrain} from '../../render/terrain.ts';\nimport type {PointProjection} from '../../symbol/projection.ts';\nimport type {CameraOptionsFromTo, IReadonlyTransform, ITransform, NearFarZ, TransformConstrainFunction, WorldCoordinateHelper} from '../transform_interface.ts';\nimport type {TransformOptions} from '../transform_helper.ts';\nimport type {PaddingOptions} from '../edge_insets.ts';\nimport type {CustomLayerProjectionData, ProjectionDataParams, RendererProjectionData} from './projection_data.ts';\nimport type {CoveringTilesDetailsProvider} from './covering_tiles_details_provider.ts';\n\n/**\n * Globe transform is a transform that moves between vertical perspective and mercator projections.\n *\n * The two child transforms share this transform's {@link TransformHelper}, so the camera exists exactly once:\n * a child that moves itself - as {@link setLocationAtPoint} has it do, since only the child knows its own\n * projection's geometry - has moved this transform too, with no copying back. The children own only what they\n * derive from that shared camera, such as their matrices, and this transform drives their `_calcMatrices`\n * because a helper has a single `calcMatrices` callback.\n */\nexport class GlobeTransform implements ITransform {\n    private _helper: TransformHelper;\n\n    //\n    // Implementation of transform getters and setters\n    //\n\n    get pixelsToClipSpaceMatrix(): mat4 {\n        return this._helper.pixelsToClipSpaceMatrix;\n    }\n    get clipSpaceToPixelsMatrix(): mat4 {\n        return this._helper.clipSpaceToPixelsMatrix;\n    }\n    get pixelsToGLUnits(): [number, number] {\n        return this._helper.pixelsToGLUnits;\n    }\n    get size(): Point {\n        return this._helper.size;\n    }\n    get rotationMatrix(): mat2 {\n        return this._helper.rotationMatrix;\n    }\n    get centerPoint(): Point {\n        return this._helper.centerPoint;\n    }\n    get pixelsPerMeter(): number {\n        return this._helper.pixelsPerMeter;\n    }\n    setMinZoom(zoom: number): void {\n        this._helper.setMinZoom(zoom);\n    }\n    setMaxZoom(zoom: number): void {\n        this._helper.setMaxZoom(zoom);\n    }\n    setMinPitch(pitch: number): void {\n        this._helper.setMinPitch(pitch);\n    }\n    setMaxPitch(pitch: number): void {\n        this._helper.setMaxPitch(pitch);\n    }\n    setRenderWorldCopies(renderWorldCopies: boolean): void {\n        this._helper.setRenderWorldCopies(renderWorldCopies);\n    }\n    setBearing(bearing: number): void {\n        this._helper.setBearing(bearing);\n    }\n    setPitch(pitch: number): void {\n        this._helper.setPitch(pitch);\n    }\n    setRoll(roll: number): void {\n        this._helper.setRoll(roll);\n    }\n    setFov(fov: number): void {\n        this._helper.setFov(fov);\n    }\n    setZoom(zoom: number): void {\n        this._helper.setZoom(zoom);\n    }\n    setCenter(center: LngLat): void {\n        this._helper.setCenter(center);\n    }\n    setElevation(elevation: number): void {\n        this._helper.setElevation(elevation);\n    }\n    setMinElevationForCurrentTile(elevation: number): void {\n        this._helper.setMinElevationForCurrentTile(elevation);\n    }\n    setPadding(padding: PaddingOptions): void {\n        this._helper.setPadding(padding);\n    }\n    interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number): void {\n        this._helper.interpolatePadding(start, target, t);\n    }\n    isPaddingEqual(padding: PaddingOptions): boolean {\n        return this._helper.isPaddingEqual(padding);\n    }\n    resize(width: number, height: number, constrainTransform: boolean = true): void {\n        this._helper.resize(width, height, constrainTransform);\n    }\n    getMaxBounds(): LngLatBounds {\n        return this._helper.getMaxBounds();\n    }\n    setMaxBounds(bounds?: LngLatBounds): void {\n        this._helper.setMaxBounds(bounds);\n    }\n    setConstrainOverride(constrain?: TransformConstrainFunction | null): void {\n        this._helper.setConstrainOverride(constrain);\n    }\n    overrideNearFarZ(nearZ: number, farZ: number): void {\n        this._helper.overrideNearFarZ(nearZ, farZ);\n    }\n    clearNearFarZOverride(): void {\n        this._helper.clearNearFarZOverride();\n    }\n    getCameraQueryGeometry(queryGeometry: Point[]): Point[] {\n        return this._helper.getCameraQueryGeometry(queryGeometry);\n    }\n\n    get tileSize(): number {\n        return this._helper.tileSize;\n    }\n    get tileZoom(): number {\n        return this._helper.tileZoom;\n    }\n    get scale(): number {\n        return this._helper.scale;\n    }\n    get worldSize(): number {\n        return this._helper.worldSize;\n    }\n    get width(): number {\n        return this._helper.width;\n    }\n    get height(): number {\n        return this._helper.height;\n    }\n    get lngRange(): [number, number] {\n        return this._helper.lngRange;\n    }\n    get latRange(): [number, number] {\n        return this._helper.latRange;\n    }\n    get minZoom(): number {\n        return this._helper.minZoom;\n    }\n    get maxZoom(): number {\n        return this._helper.maxZoom;\n    }\n    get zoom(): number {\n        return this._helper.zoom;\n    }\n    get center(): LngLat {\n        return this._helper.center;\n    }\n    get minPitch(): number {\n        return this._helper.minPitch;\n    }\n    get maxPitch(): number {\n        return this._helper.maxPitch;\n    }\n    get pitch(): number {\n        return this._helper.pitch;\n    }\n    get pitchInRadians(): number {\n        return this._helper.pitchInRadians;\n    }\n    get roll(): number {\n        return this._helper.roll;\n    }\n    get rollInRadians(): number {\n        return this._helper.rollInRadians;\n    }\n    get bearing(): number {\n        return this._helper.bearing;\n    }\n    get bearingInRadians(): number {\n        return this._helper.bearingInRadians;\n    }\n    get fov(): number {\n        return this._helper.fov;\n    }\n    get fovInRadians(): number {\n        return this._helper.fovInRadians;\n    }\n    get elevation(): number {\n        return this._helper.elevation;\n    }\n    get minElevationForCurrentTile(): number {\n        return this._helper.minElevationForCurrentTile;\n    }\n    get padding(): PaddingOptions {\n        return this._helper.padding;\n    }\n    get unmodified(): boolean {\n        return this._helper.unmodified;\n    }\n    get renderWorldCopies(): boolean {\n        return this._helper.renderWorldCopies;\n    }\n    get cameraToCenterDistance(): number {\n        return this._helper.cameraToCenterDistance;\n    }\n    get constrainOverride(): TransformConstrainFunction {\n        return this._helper.constrainOverride;\n    }\n    public get nearZ(): number {\n        return this.currentTransform.nearZ;\n    }\n    public get farZ(): number {\n        return this.currentTransform.farZ;\n    }\n    public get nearFarZOverride(): NearFarZ | null {\n        return this._helper.nearFarZOverride;\n    }\n    public get autoCalculateNearFarZ(): boolean {\n        return this._helper.autoCalculateNearFarZ;\n    }\n    //\n    // Implementation of globe transform\n    //\n\n    /**\n     * True when globe render path should be used instead of the old but simpler mercator rendering.\n     * Globe automatically transitions to mercator at high zoom levels, which causes a switch from\n     * globe to mercator render path.\n     */\n    get isGlobeRendering(): boolean {\n        return this._globeness > 0;\n    }\n\n    setTransitionState(globeness: number): void {\n        this._globeness = globeness;\n        this._calcMatrices();\n        this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame();\n        this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();\n    }\n\n    private get currentTransform(): ITransform {\n        return this.isGlobeRendering ? this._verticalPerspectiveTransform : this._mercatorTransform;\n    }\n\n    /**\n     * Globe projection can smoothly interpolate between globe view and mercator. This variable controls this interpolation.\n     * Value 0 is mercator, value 1 is globe, anything between is an interpolation between the two projections.\n     */\n    private _globeness: number = 1.0;\n    private _mercatorTransform: MercatorTransform;\n    private _verticalPerspectiveTransform: VerticalPerspectiveTransform;\n\n    public constructor(options?: TransformOptions) {\n        this._helper = new TransformHelper({\n            calcMatrices: () => this._calcMatrices(),\n            defaultConstrain: (center, zoom) => { return this.defaultConstrain(center, zoom); }\n        }, options);\n        this._globeness = 1; // When transform is cloned for use in symbols, `_updateAnimation` function which usually sets this value never gets called.\n        this._mercatorTransform = new MercatorTransform(undefined, this._helper);\n        this._verticalPerspectiveTransform = new VerticalPerspectiveTransform(undefined, this._helper);\n    }\n\n    private get _cameraState(): Readonly<CameraState> {\n        return this._helper.cameraState;\n    }\n\n    clone(): ITransform {\n        const clone = new GlobeTransform();\n        clone._globeness = this._globeness;\n        clone.apply(this, false);\n        return clone;\n    }\n\n    public apply(that: IReadonlyTransform, constrain: boolean): void {\n        this._helper.apply(that, constrain);\n    }\n\n    public get projectionMatrix(): mat4 { return this.currentTransform.projectionMatrix; }\n\n    public get modelViewProjectionMatrix(): mat4 { return this.currentTransform.modelViewProjectionMatrix; }\n\n    public get inverseProjectionMatrix(): mat4 { return this.currentTransform.inverseProjectionMatrix; }\n\n    public get cameraPosition(): vec3 { return this.currentTransform.cameraPosition; }\n\n    getProjectionData(params: ProjectionDataParams): RendererProjectionData {\n        const mercatorProjectionData = this._mercatorTransform.getProjectionData(params);\n        const verticalPerspectiveProjectionData = this._verticalPerspectiveTransform.getProjectionData(params);\n\n        return {\n            mainMatrix: this.isGlobeRendering ? verticalPerspectiveProjectionData.mainMatrix : mercatorProjectionData.mainMatrix,\n            clippingPlane: verticalPerspectiveProjectionData.clippingPlane,\n            tileMercatorCoords: verticalPerspectiveProjectionData.tileMercatorCoords,\n            projectionTransition: params.applyGlobeMatrix ? this._globeness : 0,\n            fallbackMatrix: mercatorProjectionData.fallbackMatrix,\n            clipAntimeridian: verticalPerspectiveProjectionData.clipAntimeridian,\n        };\n    }\n\n    /** {@inheritDoc ITransform.isLocationOccluded} */\n    public isLocationOccluded(lngLat: LngLat, terrain?: Terrain, elevation?: number): boolean {\n        return this.currentTransform.isLocationOccluded(lngLat, terrain, elevation);\n    }\n\n    public transformLightDirection(dir: vec3): vec3 {\n        return this.currentTransform.transformLightDirection(dir);\n    }\n\n    public getPixelScale(): number {\n        return lerp(this._mercatorTransform.getPixelScale(), this._verticalPerspectiveTransform.getPixelScale(), this._globeness);\n    }\n\n    public getCircleRadiusCorrection(): number {\n        return this.currentTransform.getCircleRadiusCorrection();\n    }\n\n    public getPitchedTextCorrection(textAnchorX: number, textAnchorY: number, tileID: UnwrappedTileID): number {\n        const mercatorCorrection = this._mercatorTransform.getPitchedTextCorrection(textAnchorX, textAnchorY, tileID);\n        const verticalCorrection = this._verticalPerspectiveTransform.getPitchedTextCorrection(textAnchorX, textAnchorY, tileID);\n        return lerp(mercatorCorrection, verticalCorrection, this._globeness);\n    }\n\n    public projectTileCoordinates(x: number, y: number, unwrappedTileID: UnwrappedTileID, elevation?: number): PointProjection {\n        return this.currentTransform.projectTileCoordinates(x, y, unwrappedTileID, elevation);\n    }\n\n    /**\n     * Vertical perspective computes its depth range first, and while the globe is rendering, mercator uses that range\n     * instead of its own, which keeps the two render paths at the same depth across the globe-to-mercator transition.\n     */\n    private _calcMatrices(): void {\n        if (!this._cameraState.width || !this._cameraState.height) {\n            return;\n        }\n        const verticalPerspective = this._verticalPerspectiveTransform;\n        verticalPerspective._calcMatrices();\n        const nearFarZ = this.isGlobeRendering ? {nearZ: verticalPerspective.nearZ, farZ: verticalPerspective.farZ} : this._cameraState.nearFarZOverride;\n        this._mercatorTransform._calcMatrices(nearFarZ);\n    }\n\n    calculateFogMatrix(unwrappedTileID: UnwrappedTileID): mat4 {\n        return this.currentTransform.calculateFogMatrix(unwrappedTileID);\n    }\n\n    getVisibleUnwrappedCoordinates(tileID: CanonicalTileID): UnwrappedTileID[] {\n        return this.currentTransform.getVisibleUnwrappedCoordinates(tileID);\n    }\n\n    getCameraFrustum(): Frustum {\n        return this.currentTransform.getCameraFrustum();\n    }\n    getClippingPlane(): vec4 | null {\n        return this.currentTransform.getClippingPlane();\n    }\n    getCoveringTilesDetailsProvider(): CoveringTilesDetailsProvider {\n        return this.currentTransform.getCoveringTilesDetailsProvider();\n    }\n\n    recalculateZoomAndCenter(terrain?: Terrain): void {\n        this.currentTransform.recalculateZoomAndCenter(terrain);\n    }\n\n    maxPitchScaleFactor(): number {\n        // Using mercator version of this should be good enough approximation for globe.\n        return this._mercatorTransform.maxPitchScaleFactor();\n    }\n\n    getCameraPoint(): Point {\n        return this._helper.getCameraPoint();\n    }\n\n    /** The camera of the child that renders the current frame. */\n    getCameraAltitude(): number {\n        return this.currentTransform.getCameraAltitude();\n    }\n\n    /** See {@link getCameraAltitude}. */\n    getCameraLngLat(): LngLat {\n        return this.currentTransform.getCameraLngLat();\n    }\n\n    get worldCoordinateHelper(): WorldCoordinateHelper {\n        return this._helper.worldCoordinateHelper;\n    }\n\n    getBounds(): LngLatBounds {\n        return this.currentTransform.getBounds();\n    }\n\n    defaultConstrain: TransformConstrainFunction = (lngLat, zoom) => {\n        return this.currentTransform.defaultConstrain(lngLat, zoom);\n    };\n\n    applyConstrain: TransformConstrainFunction = (lngLat, zoom) => {\n        return this._helper.applyConstrain(lngLat, zoom);\n    };\n\n    calculateCenterFromCameraLngLatAlt(lngLat: LngLatLike, alt: number, bearing?: number, pitch?: number): {center: LngLat; elevation: number; zoom: number} {\n        return this._helper.calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch);\n    }\n\n    /** See {@link getCameraAltitude}. */\n    calculateCameraOptionsFromTo(from: LngLatLike, altitudeFrom: number, to: LngLatLike, altitudeTo: number): CameraOptionsFromTo {\n        return this.currentTransform.calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo);\n    }\n\n    /**\n     * Note: automatically adjusts zoom to keep planet size consistent\n     * (same size before and after a {@link setLocationAtPoint} call).\n     */\n    setLocationAtPoint(lnglat: LngLat, point: Point, elevation?: number): void {\n        this.currentTransform.setLocationAtPoint(lnglat, point, elevation);\n    }\n\n    locationToScreenPoint(lnglat: LngLat, terrain?: Terrain): Point {\n        return this.currentTransform.locationToScreenPoint(lnglat, terrain);\n    }\n\n    screenPointToMercatorCoordinate(p: Point, terrain?: Terrain): MercatorCoordinate {\n        return this.currentTransform.screenPointToMercatorCoordinate(p, terrain);\n    }\n\n    /** {@inheritDoc ITransform.screenTerrainPointToMercatorCoordinate} */\n    screenTerrainPointToMercatorCoordinate(p: Point, terrain: Terrain): MercatorCoordinate | null {\n        return this.currentTransform.screenTerrainPointToMercatorCoordinate(p, terrain);\n    }\n\n    screenPointToLocation(p: Point, terrain?: Terrain): LngLat {\n        return this.currentTransform.screenPointToLocation(p, terrain);\n    }\n\n    screenPointToLocationAtElevation(p: Point, elevation: number): LngLat {\n        return this.currentTransform.screenPointToLocationAtElevation(p, elevation);\n    }\n\n    isPointOnMapSurface(p: Point, terrain?: Terrain): boolean {\n        return this.currentTransform.isPointOnMapSurface(p, terrain);\n    }\n\n    /**\n     * Computes normalized direction of a ray from the camera to the given screen pixel.\n     *\n     * Always answered by the vertical perspective child: the ray is in unit-sphere space, so it is only meaningful\n     * to the globe camera controls that ask for it, and the mercator transform does not implement it at all.\n     */\n    getRayDirectionFromPixel(p: Point): vec3 {\n        return this._verticalPerspectiveTransform.getRayDirectionFromPixel(p);\n    }\n\n    getProjectionDataForCustomLayer(applyGlobeMatrix: boolean = true): CustomLayerProjectionData {\n        const mercatorData = this._mercatorTransform.getProjectionDataForCustomLayer(applyGlobeMatrix);\n\n        if (!this.isGlobeRendering) {\n            return mercatorData;\n        }\n\n        const globeData = this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(applyGlobeMatrix);\n        globeData.fallbackMatrix = mercatorData.mainMatrix;\n        globeData.projectionTransition = this._globeness;\n        return globeData;\n    }\n\n    getFastPathSimpleProjectionMatrix(tileID: OverscaledTileID): mat4 {\n        return this.currentTransform.getFastPathSimpleProjectionMatrix(tileID);\n    }\n}\n\n/**\n * Creates a transform for the globe projection.\n */\nexport function createGlobeTransform(options?: TransformOptions): GlobeTransform {\n    return new GlobeTransform(options);\n}\n", "import Point from '@mapbox/point-geometry';\nimport {cameraBoundsWarning, type CameraForBoxAndBearingHandlerResult, type EaseToHandlerResult, type EaseToHandlerOptions, type FlyToHandlerResult, type FlyToHandlerOptions, type ICameraHelper, type MapControlsDeltas, updateRotation, cameraForBoxAndBearing} from './camera_helper.ts';\nimport {LngLat, type LngLatLike} from '../lng_lat.ts';\nimport {angularCoordinatesToSurfaceVector, computeGlobePanCenter, getGlobeRadiusPixels, getZoomAdjustment, globeDistanceOfLocationsPixels, interpolateLngLatForGlobe, versorSetLocationAtPoint} from './globe_utils.ts';\nimport {clamp, createVec3f64, differenceOfAnglesDegrees, lerp, remapSaturate, rollPitchBearingEqual, scaleZoom, warnOnce, zoomScale} from '../../util/util.ts';\nimport {type mat4, vec3} from 'gl-matrix';\nimport {normalizeCenter} from '../transform_helper.ts';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {IReadonlyTransform, ITransform} from '../transform_interface.ts';\nimport type {CameraForBoundsOptions} from '../../ui/camera.ts';\nimport type {LngLatBounds} from '../lng_lat_bounds.ts';\nimport type {PaddingOptions} from '../edge_insets.ts';\n\n/**\n * Zoom movement slowing starts when the mouse ray passes further than this above the planet surface,\n * so a cursor off the globe does not move the map unnaturally. Globe radius is 1, so 0.3 is ~2000 km.\n */\nconst RAY_SURFACE_DISTANCE_FOR_SLOWING_START = 0.3;\n\n/** How sharply zoom movement slows as the mouse ray rises above the planet surface. Lower is more gradual. */\nconst SLOWING_MULTIPLIER = 0.5;\n\n/** Longitude difference between zoom location and map center at which the blend from exact to heuristic zooming starts, in degrees. */\nconst INTERPOLATE_TO_HEURISTIC_START_LNG = 45;\n\n/** Longitude difference at which the blend to heuristic zooming is complete, in degrees. */\nconst INTERPOLATE_TO_HEURISTIC_END_LNG = 85;\n\n/** Exponent applied to the blend factor: below 1, so the blend leans towards heuristic zooming and flattens as it completes. */\nconst INTERPOLATE_TO_HEURISTIC_EXPONENT = 0.25;\n\n/**\n * Distance of the mouse ray from the globe center at which the blend from exact to heuristic zooming\n * starts. Globe radius is 1, so 1 is a ray grazing the horizon.\n */\nconst INTERPOLATE_TO_HEURISTIC_START_HORIZON = 0.95;\n\n/** Ray distance at which the blend to heuristic zooming is complete. */\nconst INTERPOLATE_TO_HEURISTIC_END_HORIZON = 0.999;\n\n/**\n * Globe radius relative to the smaller viewport dimension below which zoom movement near the horizon\n * starts being inhibited, avoiding unnatural movements when the map is zoomed out a lot.\n */\nconst SLOWING_RADIUS_START = 0.9;\n\n/** Globe radius relative to the smaller viewport dimension at which that inhibition is at full strength. */\nconst SLOWING_RADIUS_STOP = 0.5;\n\n/** Fraction of the zoom movement that remains once the globe has shrunk to `SLOWING_RADIUS_STOP`. */\nconst SLOWING_RADIUS_SLOW_FACTOR = 0.25;\n\n/**\n * @internal\n */\nexport class VerticalPerspectiveCameraHelper implements ICameraHelper {\n\n    get useGlobeControls(): boolean { return true; }\n\n    handlePanInertia(pan: Point, transform: IReadonlyTransform): {\n        easingCenter: LngLat;\n        easingOffset: Point;\n    } {\n        const panCenter = computeGlobePanCenter(pan, transform);\n        if (Math.abs(panCenter.lng - transform.center.lng) > 180) {\n            // If easeTo target would be over 180° distant, the animation would move\n            // in the opposite direction that what the user intended.\n            // Thus we clamp the movement to 179.5°.\n            panCenter.lng = transform.center.lng + 179.5 * Math.sign(panCenter.lng - transform.center.lng);\n        }\n        return {\n            easingCenter: panCenter,\n            easingOffset: new Point(0, 0),\n        };\n    }\n\n    /**\n     * Zooms around the pointer.\n     *\n     * `setLocationAtPoint` is exact but degenerates when called repeatedly for a\n     * location whose longitude is far from the center's, or one near the horizon,\n     * so those cases blend towards a heuristic.\n     */\n    handleMapControlsRollPitchBearingZoom(deltas: MapControlsDeltas, tr: ITransform): void {\n        const zoomPixel = deltas.around;\n        const zoomLoc = tr.screenPointToLocation(zoomPixel);\n\n        if (deltas.bearingDelta) tr.setBearing(tr.bearing + deltas.bearingDelta);\n        if (deltas.pitchDelta) tr.setPitch(tr.pitch + deltas.pitchDelta);\n        if (deltas.rollDelta) tr.setRoll(tr.roll + deltas.rollDelta);\n        const oldZoomPreZoomDelta = tr.zoom;\n        if (deltas.zoomDelta) tr.setZoom(tr.zoom + deltas.zoomDelta);\n        const actualZoomDelta = tr.zoom - oldZoomPreZoomDelta;\n\n        if (actualZoomDelta === 0) {\n            return;\n        }\n\n        const dLngRaw = differenceOfAnglesDegrees(tr.center.lng, zoomLoc.lng);\n        const dLng = dLngRaw / (Math.abs(dLngRaw / 180) + 1.0); // This gradually reduces the amount of longitude change if the zoom location is very far, eg. on the other side of the pole (possible when looking at a pole).\n        const dLat = differenceOfAnglesDegrees(tr.center.lat, zoomLoc.lat);\n\n        // Slow zoom movement down if the mouse ray is far from the planet.\n        const rayDirection = tr.getRayDirectionFromPixel(zoomPixel);\n        const rayOrigin = tr.cameraPosition;\n        const distanceToClosestPoint = vec3.dot(rayOrigin, rayDirection) * -1; // Globe center relative to ray origin is equal to -rayOrigin and rayDirection is normalized, thus we want to compute dot(-rayOrigin, rayDirection).\n        const closestPoint = createVec3f64();\n        vec3.add(closestPoint, rayOrigin, [\n            rayDirection[0] * distanceToClosestPoint,\n            rayDirection[1] * distanceToClosestPoint,\n            rayDirection[2] * distanceToClosestPoint\n        ]);\n        const rayDistanceFromGlobeCenter = vec3.length(closestPoint); // 0 for a ray straight under the camera, 1 for one grazing the horizon.\n        const distanceFromSurface = rayDistanceFromGlobeCenter - 1;\n        const distanceFactor = Math.exp(-Math.max(distanceFromSurface - RAY_SURFACE_DISTANCE_FOR_SLOWING_START, 0) * SLOWING_MULTIPLIER);\n\n        // Near the horizon a pixel is worth degrees of arc and `setLocationAtPoint` can have no solution at all.\n        const interpolationFactorHorizon = remapSaturate(rayDistanceFromGlobeCenter, INTERPOLATE_TO_HEURISTIC_START_HORIZON, INTERPOLATE_TO_HEURISTIC_END_HORIZON, 0, 1);\n\n        // Slow zoom movement down if the globe is too small on viewport\n        const radius = getGlobeRadiusPixels(tr.worldSize, tr.center.lat) / Math.min(tr.width, tr.height); // Radius relative to smaller viewport dimension\n        const radiusFactor = remapSaturate(radius, SLOWING_RADIUS_START, SLOWING_RADIUS_STOP, 1.0, SLOWING_RADIUS_SLOW_FACTOR);\n        // Globe size only stands in for how close the zoom location is to the horizon, so apply the slowdown where that is actually the case.\n        const slowingFactor = Math.min(distanceFactor, lerp(1.0, radiusFactor, interpolationFactorHorizon));\n\n        // Compute how much to move towards the zoom location\n        const factor = (1.0 - zoomScale(-actualZoomDelta)) * slowingFactor;\n\n        const oldCenterLat = tr.center.lat;\n        const oldZoom = tr.zoom;\n        const heuristicCenter = new LngLat(\n            tr.center.lng + dLng * factor,\n            clamp(tr.center.lat + dLat * factor, -90, 90)\n        );\n\n        // Now compute the map center exact zoom\n        tr.setLocationAtPoint(zoomLoc, zoomPixel);\n        const exactCenter = tr.center;\n\n        // Interpolate between exact zooming and heuristic zooming depending on the longitude difference between current center and zoom location.\n        const interpolationFactorLongitude = remapSaturate(Math.abs(dLngRaw), INTERPOLATE_TO_HEURISTIC_START_LNG, INTERPOLATE_TO_HEURISTIC_END_LNG, 0, 1);\n        const heuristicFactor = Math.pow(Math.max(interpolationFactorLongitude, interpolationFactorHorizon), INTERPOLATE_TO_HEURISTIC_EXPONENT);\n\n        const lngExactToHeuristic = differenceOfAnglesDegrees(exactCenter.lng, heuristicCenter.lng);\n        const latExactToHeuristic = differenceOfAnglesDegrees(exactCenter.lat, heuristicCenter.lat);\n\n        tr.setCenter(new LngLat(\n            exactCenter.lng + lngExactToHeuristic * heuristicFactor,\n            clamp(exactCenter.lat + latExactToHeuristic * heuristicFactor, -90, 90)\n        ).wrap());\n        tr.setZoom(oldZoom + getZoomAdjustment(oldCenterLat, tr.center.lat));\n    }\n\n    /**\n     * Pans the globe by rotating it with a single quaternion that brings the grabbed location back\n     * under the cursor. This stays consistent near and across the poles, where the previous\n     * bearing-preserving mapping inverted and stalled (#5296).\n     * @param deltas - The deltas accumulated for this frame.\n     * @param tr - The transform to pan.\n     * @param preZoomAroundLoc - The location that was under the cursor before this frame.\n     */\n    handleMapControlsPan(deltas: MapControlsDeltas, tr: ITransform, preZoomAroundLoc: LngLat): void {\n        if (!deltas.panDelta) {\n            return;\n        }\n\n        const anchor = tr.isPointOnMapSurface(deltas.around) ? deltas.around : tr.centerPoint;\n        versorSetLocationAtPoint(tr, preZoomAroundLoc, anchor, deltas.panDelta);\n    }\n\n    cameraForBoxAndBearing(options: CameraForBoundsOptions, fitPadding: PaddingOptions, mapPadding: PaddingOptions, bounds: LngLatBounds, bearing: number, tr: ITransform): CameraForBoxAndBearingHandlerResult {\n        const result = cameraForBoxAndBearing(options, fitPadding, mapPadding, bounds, bearing, tr);\n        if (!result) {\n            return undefined;\n        }\n        // If globe is enabled, we use the parameters computed for mercator, and just update the zoom to fit the bounds.\n\n        // Get clip space bounds including fitPadding\n        const xLeft = (fitPadding.left) / tr.width * 2.0 - 1.0;\n        const xRight = (tr.width - fitPadding.right) / tr.width * 2.0 - 1.0;\n        const yTop = (fitPadding.top) / tr.height * -2.0 + 1.0;\n        const yBottom = (tr.height - fitPadding.bottom) / tr.height * -2.0 + 1.0;\n\n        // Get camera bounds\n        const flipEastWest = differenceOfAnglesDegrees(bounds.getWest(), bounds.getEast()) < 0;\n        const lngWest = flipEastWest ? bounds.getEast() : bounds.getWest();\n        const lngEast = flipEastWest ? bounds.getWest() : bounds.getEast();\n\n        const latNorth = Math.max(bounds.getNorth(), bounds.getSouth()); // \"getNorth\" doesn't always return north...\n        const latSouth = Math.min(bounds.getNorth(), bounds.getSouth());\n\n        // Additional vectors will be tested for the rectangle midpoints\n        const lngMid = lngWest + differenceOfAnglesDegrees(lngWest, lngEast) * 0.5;\n        const latMid = latNorth + differenceOfAnglesDegrees(latNorth, latSouth) * 0.5;\n\n        // Obtain a globe projection matrix that does not include pitch (unsupported)\n        const clonedTr = tr.clone();\n        clonedTr.setCenter(result.center);\n        clonedTr.setPadding(mapPadding);\n        clonedTr.setBearing(result.bearing);\n        clonedTr.setPitch(0);\n        clonedTr.setRoll(0);\n        clonedTr.setZoom(result.zoom);\n        const matrix = clonedTr.modelViewProjectionMatrix;\n\n        // Vectors to test - the bounds' corners and edge midpoints\n        const testVectors = [\n            angularCoordinatesToSurfaceVector(bounds.getNorthWest()),\n            angularCoordinatesToSurfaceVector(bounds.getNorthEast()),\n            angularCoordinatesToSurfaceVector(bounds.getSouthWest()),\n            angularCoordinatesToSurfaceVector(bounds.getSouthEast()),\n            // Also test edge midpoints\n            angularCoordinatesToSurfaceVector(new LngLat(lngEast, latMid)),\n            angularCoordinatesToSurfaceVector(new LngLat(lngWest, latMid)),\n            angularCoordinatesToSurfaceVector(new LngLat(lngMid, latNorth)),\n            angularCoordinatesToSurfaceVector(new LngLat(lngMid, latSouth))\n        ];\n        const vecToCenter = angularCoordinatesToSurfaceVector(result.center);\n\n        // Test each vector, measure how much to scale down the globe to satisfy all tested points that they are inside clip space.\n        let smallestNeededScale = Number.POSITIVE_INFINITY;\n        for (const vec of testVectors) {\n            if (xLeft < 0)\n                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'x', xLeft));\n            if (xRight > 0)\n                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'x', xRight));\n            if (yTop > 0)\n                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'y', yTop));\n            if (yBottom < 0)\n                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'y', yBottom));\n        }\n\n        if (!Number.isFinite(smallestNeededScale) || smallestNeededScale === 0) {\n            cameraBoundsWarning();\n            return undefined;\n        }\n\n        // Compute target zoom from the obtained scale.\n        result.zoom = Math.min(clonedTr.zoom + scaleZoom(smallestNeededScale), options.maxZoom);\n        return result;\n    }\n\n    /**\n     * Handles the zoom and center change during camera jumpTo.\n     * The zoom decides how close to a pole the center can be, so the center is set again once the zoom has changed.\n     */\n    handleJumpToCenterZoom(tr: ITransform, options: { zoom?: number; center?: LngLatLike }): void {\n        const startingLat = tr.center.lat;\n        const center = options.center ? LngLat.convert(options.center) : tr.center;\n        tr.setCenter(tr.applyConstrain(center, tr.zoom).center.wrap());\n\n        // Make sure to compute correct target zoom level if no zoom is specified\n        const targetZoom = (typeof options.zoom !== 'undefined') ? +options.zoom : (tr.zoom + getZoomAdjustment(startingLat, tr.center.lat));\n        if (tr.zoom !== targetZoom) {\n            tr.setZoom(targetZoom);\n            tr.setCenter(tr.applyConstrain(center, tr.zoom).center.wrap());\n        }\n    }\n\n    /**\n     * The zoom decides how close to a pole the center can be, so the last frame sets the center again after the zoom.\n     */\n    handleEaseTo(tr: ITransform, options: EaseToHandlerOptions): EaseToHandlerResult {\n        const startZoom = tr.zoom;\n        const startCenter = tr.center;\n        const startPadding = tr.padding;\n        const startEulerAngles = {roll: tr.roll, pitch: tr.pitch, bearing: tr.bearing};\n        const endRoll = options.roll === undefined ? tr.roll : options.roll;\n        const endPitch = options.pitch === undefined ? tr.pitch : options.pitch;\n        const endBearing = options.bearing === undefined ? tr.bearing : options.bearing;\n        const endEulerAngles = {roll: endRoll, pitch: endPitch, bearing: endBearing};\n\n        const optionsZoom = typeof options.zoom !== 'undefined';\n\n        const doPadding = !tr.isPaddingEqual(options.padding);\n\n        let isZooming = false;\n\n        // Globe needs special handling for how zoom should be animated.\n        // 1) if zoom is set, ease to the given mercator zoom\n        // 2) if neither is set, assume constant apparent zoom (constant planet size) is to be kept\n        const preConstrainCenter = options.center ?\n            LngLat.convert(options.center) :\n            startCenter;\n        const constrainedCenter = tr.applyConstrain(\n            preConstrainCenter,\n            optionsZoom ? +options.zoom : startZoom\n        ).center;\n        normalizeCenter(tr, constrainedCenter);\n\n        const clonedTr = tr.clone();\n        clonedTr.setCenter(constrainedCenter);\n\n        clonedTr.setZoom(optionsZoom ?\n            +options.zoom :\n            startZoom + getZoomAdjustment(startCenter.lat, preConstrainCenter.lat));\n        clonedTr.setBearing(options.bearing);\n        const clampedPoint = new Point(\n            clamp(tr.centerPoint.x + options.offsetAsPoint.x, 0, tr.width),\n            clamp(tr.centerPoint.y + options.offsetAsPoint.y, 0, tr.height)\n        );\n        clonedTr.setLocationAtPoint(constrainedCenter, clampedPoint);\n        // Find final animation targets\n        const endCenterWithShift = (options.offset && options.offsetAsPoint.mag()) > 0 ? clonedTr.center : constrainedCenter;\n        const endZoomWithShift = optionsZoom ?\n            +options.zoom :\n            startZoom + getZoomAdjustment(startCenter.lat, endCenterWithShift.lat);\n\n        // Planet radius for a given zoom level differs according to latitude\n        // Convert zooms to what they would be at equator for the given planet radius\n        const normalizedStartZoom = startZoom + getZoomAdjustment(startCenter.lat, 0);\n        const normalizedEndZoom = endZoomWithShift + getZoomAdjustment(endCenterWithShift.lat, 0);\n        const deltaLng = differenceOfAnglesDegrees(startCenter.lng, endCenterWithShift.lng);\n        const deltaLat = differenceOfAnglesDegrees(startCenter.lat, endCenterWithShift.lat);\n\n        const finalScale = zoomScale(normalizedEndZoom - normalizedStartZoom);\n        isZooming = (endZoomWithShift !== startZoom);\n\n        const easeFunc = (k: number) => {\n            if (!rollPitchBearingEqual(startEulerAngles, endEulerAngles)) {\n                updateRotation({\n                    startEulerAngles,\n                    endEulerAngles,\n                    tr,\n                    k,\n                    useSlerp: startEulerAngles.roll != endEulerAngles.roll});\n            }\n\n            if (doPadding) {\n                tr.interpolatePadding(startPadding, options.padding,k);\n            }\n\n            if (options.around) {\n                warnOnce('Easing around a point is not supported under globe projection.');\n                tr.setLocationAtPoint(options.around, options.aroundPoint);\n            } else {\n                const base = normalizedEndZoom > normalizedStartZoom ?\n                    Math.min(2, finalScale) :\n                    Math.max(0.5, finalScale);\n                const speedup = Math.pow(base, 1 - k);\n                const factor = k * speedup;\n\n                // Spherical lerp might be used here instead, but that was tested and it leads to very weird paths when the interpolated arc gets near the poles.\n                // Instead we interpolate LngLat almost directly, but taking into account that\n                // one degree of longitude gets progressively smaller relative to latitude towards the poles.\n                const newCenter = interpolateLngLatForGlobe(startCenter, deltaLng, deltaLat, factor);\n                tr.setCenter(newCenter.wrap());\n            }\n\n            if (isZooming) {\n                const normalizedInterpolatedZoom = interpolates.number(normalizedStartZoom, normalizedEndZoom, k);\n                const interpolatedZoom = normalizedInterpolatedZoom + getZoomAdjustment(0, tr.center.lat);\n                tr.setZoom(interpolatedZoom);\n            }\n\n            if (k === 1 && !options.around) {\n                tr.setCenter(endCenterWithShift.wrap());\n            }\n        };\n\n        return {\n            easeFunc,\n            isZooming,\n            elevationCenter: endCenterWithShift,\n        };\n    }\n\n    /**\n     * The zoom decides how close to a pole the center can be, so the last frame sets the center again after the zoom.\n     */\n    handleFlyTo(tr: ITransform, options: FlyToHandlerOptions): FlyToHandlerResult {\n        const optionsZoom = typeof options.zoom !== 'undefined';\n\n        const startCenter = tr.center;\n        const startZoom = tr.zoom;\n        const startPadding = tr.padding;\n\n        const doPadding = !tr.isPaddingEqual(options.padding);\n\n        // Obtain target center and zoom\n        const constrainedCenter = tr.applyConstrain(\n            LngLat.convert(options.center || options.locationAtOffset),\n            optionsZoom ? +options.zoom : startZoom\n        ).center;\n        const targetZoom = optionsZoom ? +options.zoom : tr.zoom + getZoomAdjustment(tr.center.lat, constrainedCenter.lat);\n\n        // Compute target center that respects offset by creating a temporary transform and calling its `setLocationAtPoint`.\n        const clonedTr = tr.clone();\n        clonedTr.setCenter(constrainedCenter);\n\n        clonedTr.setZoom(targetZoom);\n        clonedTr.setBearing(options.bearing);\n        const clampedPoint = new Point(\n            clamp(tr.centerPoint.x + options.offsetAsPoint.x, 0, tr.width),\n            clamp(tr.centerPoint.y + options.offsetAsPoint.y, 0, tr.height)\n        );\n        clonedTr.setLocationAtPoint(constrainedCenter, clampedPoint);\n        const targetCenter = clonedTr.center;\n\n        normalizeCenter(tr, targetCenter);\n\n        const pixelPathLength = globeDistanceOfLocationsPixels(tr, startCenter, targetCenter);\n\n        const normalizedStartZoom = startZoom + getZoomAdjustment(startCenter.lat, 0);\n        const normalizedTargetZoom = targetZoom + getZoomAdjustment(targetCenter.lat, 0);\n        const scaleOfZoom = zoomScale(normalizedTargetZoom - normalizedStartZoom);\n\n        const requestedMinZoom = typeof options.minZoom === 'number' ? +options.minZoom : tr.minZoom;\n        const effectiveMinZoom = Math.max(requestedMinZoom, tr.minZoom);\n        const normalizedEffectiveMinZoom = effectiveMinZoom + getZoomAdjustment(targetCenter.lat, 0);\n        const normalizedMinZoomPreConstrain = Math.min(normalizedEffectiveMinZoom, normalizedStartZoom, normalizedTargetZoom);\n        const minZoomPreConstrain = normalizedMinZoomPreConstrain + getZoomAdjustment(0, targetCenter.lat);\n        const minZoom = tr.applyConstrain(targetCenter, minZoomPreConstrain).zoom;\n        const normalizedMinZoom = minZoom + getZoomAdjustment(targetCenter.lat, 0);\n        const scaleOfMinZoom = zoomScale(normalizedMinZoom - normalizedStartZoom);\n\n        const deltaLng = differenceOfAnglesDegrees(startCenter.lng, targetCenter.lng);\n        const deltaLat = differenceOfAnglesDegrees(startCenter.lat, targetCenter.lat);\n\n        const easeFunc = (k: number, scale: number, centerFactor: number, _pointAtOffset: Point) => {\n            const interpolatedCenter = interpolateLngLatForGlobe(startCenter, deltaLng, deltaLat, centerFactor);\n\n            if (doPadding) {\n                tr.interpolatePadding(startPadding, options.padding,k);\n            }\n\n            const newCenter = k === 1 ? targetCenter : interpolatedCenter;\n            tr.setCenter(newCenter.wrap());\n\n            const interpolatedZoom = normalizedStartZoom + scaleZoom(scale);\n            tr.setZoom(k === 1 ? targetZoom : (interpolatedZoom + getZoomAdjustment(0, newCenter.lat)));\n            if (k === 1) {\n                tr.setCenter(targetCenter.wrap());\n            }\n        };\n\n        return {\n            easeFunc,\n            scaleOfZoom,\n            targetCenter,\n            scaleOfMinZoom,\n            pixelPathLength,\n        };\n    }\n\n    /**\n     * Computes how much to scale the globe in order for a given point on its surface (a location) to project to a given clip space coordinate in either the X or the Y axis.\n     * @param vector - Position of the queried location on the surface of the unit sphere globe.\n     * @param toCenter - Position of current transform center on the surface of the unit sphere globe.\n     * This is needed because zooming the globe not only changes its scale,\n     * but also moves the camera closer or further away along this vector (pitch is disregarded).\n     * @param projection - The globe projection matrix.\n     * @param targetDimension - The dimension in which the scaled vector must match the target value in clip space.\n     * @param targetValue - The target clip space value in the specified dimension to which the queried vector must project.\n     * @returns How much to scale the globe.\n     */\n    private static solveVectorScale(vector: vec3, toCenter: vec3, projection: mat4, targetDimension: 'x' | 'y', targetValue: number): number | null {\n        // We want to compute how much to scale the sphere in order for the input `vector` to project to `targetValue` in the given `targetDimension` (X or Y).\n        const k = targetValue;\n        const columnXorY = targetDimension === 'x' ?\n            [projection[0], projection[4], projection[8], projection[12]] : // X\n            [projection[1], projection[5], projection[9], projection[13]];  // Y\n        const columnZ = [projection[3], projection[7], projection[11], projection[15]];\n\n        const vecDotXY = vector[0] * columnXorY[0] + vector[1] * columnXorY[1] + vector[2] * columnXorY[2];\n        const vecDotZ = vector[0] * columnZ[0] + vector[1] * columnZ[1] + vector[2] * columnZ[2];\n        const toCenterDotXY = toCenter[0] * columnXorY[0] + toCenter[1] * columnXorY[1] + toCenter[2] * columnXorY[2];\n        const toCenterDotZ = toCenter[0] * columnZ[0] + toCenter[1] * columnZ[1] + toCenter[2] * columnZ[2];\n\n        // The following can be derived from writing down what happens to a vector scaled by a parameter (\"V * t\") when it is multiplied by a projection matrix, then solving for \"t\".\n        // Or rather, we derive it for a vector \"V * t + (1-t) * C\". Where V is `vector` and C is `toCenter`. The extra addition is needed because zooming out also moves the camera along \"C\".\n\n        const t = (toCenterDotXY + columnXorY[3] - k * toCenterDotZ - k * columnZ[3]) / (toCenterDotXY - vecDotXY - k * toCenterDotZ + k * vecDotZ);\n\n        if (\n            toCenterDotXY + k * vecDotZ === vecDotXY + k * toCenterDotZ ||\n            columnZ[3] * (vecDotXY - toCenterDotXY) + columnXorY[3] * (toCenterDotZ - vecDotZ) + vecDotXY * toCenterDotZ === toCenterDotXY * vecDotZ\n        ) {\n            // The computed result is invalid.\n            return null;\n        }\n        return t;\n    }\n\n    /**\n     * Returns `newValue` if it is:\n     *\n     * - not null AND\n     * - not negative AND\n     * - smaller than `newValue`,\n     *\n     * ...otherwise returns `oldValue`.\n     */\n    private static getLesserNonNegativeNonNull(oldValue: number, newValue: number): number {\n        if (newValue !== null && newValue >= 0 && newValue < oldValue) {\n            return newValue;\n        } else {\n            return oldValue;\n        }\n    }\n}\n", "import {MercatorCameraHelper} from './mercator_camera_helper.ts';\nimport {VerticalPerspectiveCameraHelper} from './vertical_perspective_camera_helper.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {CameraForBoxAndBearingHandlerResult, EaseToHandlerResult, EaseToHandlerOptions, FlyToHandlerResult, FlyToHandlerOptions, ICameraHelper, MapControlsDeltas} from './camera_helper.ts';\nimport type {LngLat, LngLatLike} from '../lng_lat.ts';\nimport type {IReadonlyTransform, ITransform} from '../transform_interface.ts';\nimport type {GlobeProjection} from './globe_projection.ts';\nimport type {CameraForBoundsOptions} from '../../ui/camera.ts';\nimport type {LngLatBounds} from '../lng_lat_bounds.ts';\nimport type {PaddingOptions} from '../edge_insets.ts';\n\n/**\n * @internal\n */\nexport class GlobeCameraHelper implements ICameraHelper {\n    private _globe: GlobeProjection;\n    private _mercatorCameraHelper: MercatorCameraHelper;\n    private _verticalPerspectiveCameraHelper: VerticalPerspectiveCameraHelper;\n\n    constructor(globe: GlobeProjection) {\n        this._globe = globe;\n        this._mercatorCameraHelper = new MercatorCameraHelper();\n        this._verticalPerspectiveCameraHelper = new VerticalPerspectiveCameraHelper();\n    }\n\n    get useGlobeControls(): boolean { return this._globe.useGlobeRendering; }\n\n    get currentHelper(): ICameraHelper {\n        return this.useGlobeControls ? this._verticalPerspectiveCameraHelper : this._mercatorCameraHelper;\n    }\n\n    handlePanInertia(pan: Point, transform: IReadonlyTransform): {\n        easingCenter: LngLat;\n        easingOffset: Point;\n    } {\n        return this.currentHelper.handlePanInertia(pan, transform);\n    }\n\n    handleMapControlsRollPitchBearingZoom(deltas: MapControlsDeltas, tr: ITransform): void {\n        this.currentHelper.handleMapControlsRollPitchBearingZoom(deltas, tr);\n    }\n\n    handleMapControlsPan(deltas: MapControlsDeltas, tr: ITransform, preZoomAroundLoc: LngLat): void {\n        this.currentHelper.handleMapControlsPan(deltas, tr, preZoomAroundLoc);\n    }\n\n    cameraForBoxAndBearing(options: CameraForBoundsOptions, fitPadding: PaddingOptions, mapPadding: PaddingOptions, bounds: LngLatBounds, bearing: number, tr: ITransform): CameraForBoxAndBearingHandlerResult {\n        return this.currentHelper.cameraForBoxAndBearing(options, fitPadding, mapPadding, bounds, bearing, tr);\n    }\n\n    /**\n     * Handles the zoom and center change during camera jumpTo.\n     */\n    handleJumpToCenterZoom(tr: ITransform, options: { zoom?: number; center?: LngLatLike }): void {\n        this.currentHelper.handleJumpToCenterZoom(tr, options);\n    }\n\n    handleEaseTo(tr: ITransform, options: EaseToHandlerOptions): EaseToHandlerResult {\n        return this.currentHelper.handleEaseTo(tr, options);\n    }\n\n    handleFlyTo(tr: ITransform, options: FlyToHandlerOptions): FlyToHandlerResult {\n        return this.currentHelper.handleFlyTo(tr, options);\n    }\n}", "import {warnOnce} from '../../util/util.ts';\nimport {MercatorProjection} from './mercator_projection.ts';\nimport {createMercatorTransform} from './mercator_transform.ts';\nimport {MercatorCameraHelper} from './mercator_camera_helper.ts';\nimport {GlobeProjection} from './globe_projection.ts';\nimport {createGlobeTransform} from './globe_transform.ts';\nimport {GlobeCameraHelper} from './globe_camera_helper.ts';\nimport {VerticalPerspectiveCameraHelper} from './vertical_perspective_camera_helper.ts';\nimport {createVerticalPerspectiveTransform} from './vertical_perspective_transform.ts';\nimport {VerticalPerspectiveProjection} from './vertical_perspective_projection.ts';\nimport {CRSWorldCoordinateHelper} from './crs.ts';\nimport {getRegisteredProjection} from './projection_crud.ts';\n\nimport type {ProjectionSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Projection} from './projection.ts';\nimport type {ITransform, TransformConstrainFunction} from '../transform_interface.ts';\nimport type {ICameraHelper} from './camera_helper.ts';\n\nexport function createProjectionFromName(name: ProjectionSpecification['type'], transformConstrain: TransformConstrainFunction | undefined, globalState: Record<string, any>): {\n    projection: Projection;\n    transform: ITransform;\n    cameraHelper: ICameraHelper;\n} {\n    const transformOptions = {constrainOverride: transformConstrain};\n    if (Array.isArray(name)) {\n        const registeredName = findRegisteredProjectionName(name);\n        if (registeredName) {\n            warnOnce(`Projection expressions cannot use the registered projection \"${registeredName}\", which only works as a plain name. Falling back to the globe projection.`);\n        }\n        const globeProjection = new GlobeProjection({type: name}, globalState);\n        return {\n            projection: globeProjection,\n            transform: createGlobeTransform(transformOptions),\n            cameraHelper: new GlobeCameraHelper(globeProjection),\n        };\n    }\n    const registered = getRegisteredProjection(name);\n    if (registered) {\n        const worldCoordinateHelper = new CRSWorldCoordinateHelper(registered);\n        return {\n            projection: new MercatorProjection(worldCoordinateHelper),\n            transform: createMercatorTransform({...transformOptions, worldCoordinateHelper}),\n            cameraHelper: new MercatorCameraHelper(),\n        };\n    }\n    switch (name) {\n        case 'mercator':\n        {\n            return {\n                projection: new MercatorProjection(),\n                transform: createMercatorTransform(transformOptions),\n                cameraHelper: new MercatorCameraHelper(),\n            };\n        }\n        case 'globe':\n        {\n            const globeProjection = new GlobeProjection({type: [\n                'interpolate',\n                ['linear'],\n                ['zoom'],\n                11,\n                'vertical-perspective',\n                12,\n                'mercator'\n            ]}, {});\n            return {\n                projection: globeProjection,\n                transform: createGlobeTransform(transformOptions),\n                cameraHelper: new GlobeCameraHelper(globeProjection),\n            };\n        }\n        case 'vertical-perspective':\n        {\n            return {\n                projection: new VerticalPerspectiveProjection(),\n                transform: createVerticalPerspectiveTransform(transformOptions),\n                cameraHelper: new VerticalPerspectiveCameraHelper(),\n            };\n        }\n        default:\n        {\n            warnOnce(`Unknown projection name: ${name}. Falling back to mercator projection.`);\n            return {\n                projection: new MercatorProjection(),\n                transform: createMercatorTransform(transformOptions),\n                cameraHelper: new MercatorCameraHelper(),\n            };\n        }\n    }\n}\n\n/**\n * The first registered projection named anywhere in a projection expression, or `undefined` if it names none.\n */\nfunction findRegisteredProjectionName(expression: unknown[]): string | undefined {\n    return expression.flat(Infinity).find((item): item is string => typeof item === 'string' && getRegisteredProjection(item) !== undefined);\n}\n", "import {mat4} from 'gl-matrix';\nimport {throwIfAborted} from '../util/abort_error.ts';\nimport {ErrorEvent, Evented} from '../util/evented.ts';\nimport {MapSourceDataEvent, MapStyleDataEvent, MapStyleLoadEvent, type MapEventType} from '../ui/events.ts';\nimport {isRasterStyleLayer} from './style_layer/raster_style_layer.ts';\nimport {createStyleLayer} from './create_style_layer.ts';\nimport {loadSprite} from './load_sprite.ts';\nimport {ImageManager, type MissingImageRequestHandler} from '../render/image_manager.ts';\nimport {PatternAtlas} from '../render/pattern_atlas.ts';\nimport {GlyphManager} from '../render/glyph_manager.ts';\nimport {Light} from './light.ts';\nimport {Sky} from './sky.ts';\nimport {LineAtlas} from '../render/line_atlas.ts';\nimport {clone, ensureError, extend, deepEqual, filterObject, mapObject} from '../util/util.ts';\nimport {coerceSpriteToArray} from '../util/style.ts';\nimport {getJSON, getReferrer} from '../util/ajax.ts';\nimport {ResourceType} from '../util/request_manager.ts';\nimport {browser} from '../util/browser.ts';\nimport {now} from '../util/time_control.ts';\nimport {Dispatcher} from '../util/dispatcher.ts';\nimport {validateStyle, validateStyleAndEmit, validateAndEmit, emitValidationErrors, SPEC_SOURCE_TYPES} from './validate_style.ts';\nimport {type QueryRenderedFeaturesOptions, type QueryRenderedFeaturesOptionsStrict, type QueryRenderedFeaturesResults, type QueryRenderedFeaturesResultsItem, type QuerySourceFeatureOptions, queryRenderedFeatures, queryRenderedSymbols, querySourceFeatures} from '../source/query_features.ts';\nimport {TileManager} from '../tile/tile_manager.ts';\nimport {derefLayers, emptyStyle, diff as diffStyles, type DiffCommand} from '@maplibre/maplibre-gl-style-spec';\nimport {getGlobalWorkerPool} from '../util/global_worker_pool.ts';\nimport {rtlMainThreadPluginFactory} from '../source/rtl_text_plugin_main_thread.ts';\nimport {RTLPluginLoadedEventName} from '../source/rtl_text_plugin_status.ts';\nimport {PauseablePlacement} from './pauseable_placement.ts';\nimport {ZoomHistory} from './zoom_history.ts';\nimport {CrossTileSymbolIndex} from '../symbol/cross_tile_symbol_index.ts';\nimport {validateCustomStyleLayer} from './style_layer/custom_style_layer.ts';\nimport {\n    type GetDashesParameters,\n    type GetDashesResponse,\n    MessageType,\n    type GetGlyphsParameters,\n    type GetImagesParameters,\n    type GetImagesResponse\n} from '../util/actor_messages.ts';\nimport {createProjectionFromName} from '../geo/projection/projection_factory.ts';\n\nimport type {Source} from '../source/source.ts';\nimport type {GeoJSONSource} from '../source/geojson_source.ts';\nimport type {StyleLayer} from './style_layer.ts';\nimport type {MapGeoJSONFeature, GeoJSONFeature} from '../util/vectortile_to_geojson.ts';\nimport type Point from '@mapbox/point-geometry';\nimport type {Map} from '../ui/map.ts';\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\nimport type {StyleImage} from './style_image.ts';\nimport type {GlyphMap} from './style_glyph.ts';\nimport type {EvaluationParameters} from './evaluation_parameters.ts';\nimport type {Placement} from '../symbol/placement.ts';\nimport type {\n    LayerSpecification,\n    FilterSpecification,\n    StyleSpecification,\n    FontFacesSpecification,\n    LightSpecification,\n    SourceSpecification,\n    SpriteSpecification,\n    ProjectionSpecification,\n    SkySpecification,\n    StateSpecification,\n    AllPaintProperties,\n    AllLayoutProperties,\n    FeatureState,\n    TransitionSpecification,\n} from '@maplibre/maplibre-gl-style-spec';\nimport type {CanvasSourceSpecification} from '../source/canvas_source.ts';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer.ts';\nimport type {Validator} from './validate_style.ts';\nimport type {Projection} from '../geo/projection/projection.ts';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\n\nconst empty = emptyStyle();\n/**\n * A feature identifier that is bound to a source\n */\nexport type FeatureIdentifier = {\n    /**\n     * Unique id of the feature.\n     */\n    id?: string | number | undefined;\n    /**\n     * The id of the vector or GeoJSON source for the feature.\n     */\n    source: string;\n    /**\n     * *For vector tile sources, `sourceLayer` is required.*\n     */\n    sourceLayer?: string | undefined;\n};\n\n/**\n * The options object related to the {@link Map}'s style related methods\n */\nexport type StyleOptions = {\n    /**\n     * If false, style validation will be skipped. Useful in production environment.\n     */\n    validate?: boolean;\n    /**\n     * Defines a CSS\n     * font-family for locally overriding generation of Chinese, Japanese, and Korean characters.\n     * For these characters, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).\n     * Set to `false`, to enable font settings from the map's style for these glyph ranges.\n     * Forces a full update.\n     */\n    localIdeographFontFamily?: string | false;\n    /**\n     * Defines an initial global state for the map style. It overrides the defaults defined in the map style, as if {@link Map.setGlobalStateProperty} was called after loading the style.\n     */\n    globalState?: Record<string, any>;\n};\n\n/**\n * Supporting type to add validation to another style related type\n */\nexport type StyleSetterOptions = {\n    /**\n     * Whether to check if the filter conforms to the MapLibre 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.\n     */\n    validate?: boolean;\n    /**\n     * Defines an initial global state for the map style. It overrides the defaults defined in the map style, as if {@link Map.setGlobalStateProperty} was called after loading the style.\n     */\n    globalState?: Record<string, any>;\n};\n\n/**\n * Part of {@link MapOptions.transformStyle} and {@link Map.setStyle} options, transformStyle is a convenience function that allows to modify a style after it is fetched but before it is committed to the map state.\n *\n * This function exposes previous and next styles, it can be commonly used to support a range of functionalities like:\n *\n * - when previous style carries certain 'state' that needs to be carried over to a new style gracefully;\n * - when a desired style is a certain combination of previous and incoming style;\n * - when an incoming style requires modification based on external state.\n * - when an incoming style uses relative paths, which need to be converted to absolute.\n *\n * @param previous - The current style.\n * @param next - The next style.\n * @returns resulting style that will to be applied to the map\n *\n * @example\n * ```ts\n * map.setStyle('https://demotiles.maplibre.org/style.json', {\n *   transformStyle: (previousStyle, nextStyle) => ({\n *       ...nextStyle,\n *       // make relative sprite path like \"../sprite\" absolute\n *       sprite: new URL(nextStyle.sprite, \"https://demotiles.maplibre.org/styles/osm-bright-gl-style/sprites/\").href,\n *       // make relative glyphs path like \"../fonts/{fontstack}/{range}.pbf\" absolute\n *       glyphs: new URL(nextStyle.glyphs, \"https://demotiles.maplibre.org/font/\").href,\n *       sources: {\n *           // make relative vector url like \"../../\" absolute\n *           ...nextStyle.sources.map(source => {\n *              if (source.url) {\n *                  source.url = new URL(source.url, \"https://tiles.openfreemap.org/planet\");\n *              }\n *              return source;\n *           }),\n *           // copy a source from previous style\n *           'osm': previousStyle.sources.osm\n *       },\n *       layers: [\n *           // background layer\n *           nextStyle.layers[0],\n *           // copy a layer from previous style\n *           previousStyle.layers[0],\n *           // other layers from the next style\n *           ...nextStyle.layers.slice(1).map(layer => {\n *               // hide the layers we don't need from demotiles style\n *               if (layer.id.startsWith('geolines')) {\n *                   layer.layout = {...layer.layout || {}, visibility: 'none'};\n *               // filter out US polygons\n *               } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) {\n *                   layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA'];\n *               }\n *               return layer;\n *           })\n *       ]\n *   })\n * });\n * ```\n */\nexport type TransformStyleFunction = (previous: StyleSpecification | undefined, next: StyleSpecification) => StyleSpecification;\n\n/**\n * The options object related to the {@link Map}'s style related methods\n */\nexport type StyleSwapOptions = {\n    /**\n     * If false, force a 'full' update, removing the current style\n     * and building the given one instead of attempting a diff-based update.\n     */\n    diff?: boolean;\n    /**\n     * TransformStyleFunction is a convenience function\n     * that allows to modify a style after it is fetched but before it is committed to the map state. Refer to {@link TransformStyleFunction}.\n     */\n    transformStyle?: TransformStyleFunction;\n};\n\n/**\n * Specifies a layer to be added to a {@link Style}. In addition to a standard {@link LayerSpecification}\n * or a {@link CustomLayerInterface}, a {@link LayerSpecification} with an embedded {@link SourceSpecification} can also be provided.\n */\nexport type AddLayerObject = LayerSpecification | (Omit<LayerSpecification, 'source'> & {source: SourceSpecification}) | CustomLayerInterface;\n\n/**\n * The Style base class\n */\nexport class Style extends Evented<MapEventType> {\n    map: Map;\n    stylesheet: StyleSpecification;\n    dispatcher: Dispatcher;\n    imageManager: ImageManager;\n    patternAtlas: PatternAtlas;\n    glyphManager: GlyphManager;\n    lineAtlas: LineAtlas;\n    light: Light;\n    projection: Projection | undefined;\n    sky: Sky;\n\n    _frameRequest: AbortController;\n    _loadStyleRequest: AbortController;\n    _spriteRequest: AbortController;\n    _layers: {[_: string]: StyleLayer};\n    _serializedLayers: {[_: string]: LayerSpecification};\n    _order: string[];\n    tileManagers: {[_: string]: TileManager};\n    zoomHistory: ZoomHistory;\n    _loaded: boolean;\n    _changed: boolean;\n    _updatedSources: {[_: string]: 'clear' | 'reload'};\n    _updatedLayers: {[_: string]: true};\n    _removedLayers: {[_: string]: StyleLayer};\n    _changedImages: {[_: string]: true};\n    _imagesListDirty: boolean;\n    _glyphsDidChange: boolean;\n    _updatedPaintProps: {[layer: string]: true};\n    _layerOrderChanged: boolean;\n    _symbolPlacementTriggered: boolean;\n    _placedProjectionTransition: number;\n    _initialGlobalState: Record<string, any>;\n    _globalState: Record<string, any>;\n    crossTileSymbolIndex: CrossTileSymbolIndex;\n    pauseablePlacement: PauseablePlacement;\n    placement: Placement;\n    z: number;\n\n    constructor(map: Map, options: StyleOptions = {}) {\n        super();\n\n        this.map = map;\n        this.dispatcher = new Dispatcher(getGlobalWorkerPool(), map._getMapId()).setEventedParent(this);\n        this.dispatcher.registerMessageHandler(MessageType.getGlyphs, (mapId, params) => {\n            return this.getGlyphs(mapId, params);\n        });\n        this.dispatcher.registerMessageHandler(MessageType.getImages, (mapId, params) => {\n            return this.getImages(mapId, params);\n        });\n        this.dispatcher.registerMessageHandler(MessageType.getDashes, (mapId, params) => {\n            return this.getDashes(mapId, params);\n        });\n        this.imageManager = new ImageManager();\n        this.imageManager.setEventedParent(this);\n        this.imageManager.setMissingImageResolver(map._missingStyleImageResolver);\n        this.patternAtlas = new PatternAtlas(this.imageManager);\n        const glyphLang = map._container?.lang || (typeof document !== 'undefined' && document.documentElement?.lang) || undefined;\n        this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily, glyphLang);\n        this.lineAtlas = new LineAtlas(256, 512);\n        this.crossTileSymbolIndex = new CrossTileSymbolIndex();\n\n        this._setInitialValues();\n        this._initialGlobalState = options.globalState ?? {};\n\n        this._resetUpdates();\n\n        this.dispatcher.broadcast(MessageType.setReferrer, getReferrer());\n        rtlMainThreadPluginFactory().on(RTLPluginLoadedEventName, this._rtlPluginLoaded);\n\n        this.on('data', (event) => {\n            if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') {\n                return;\n            }\n\n            const tileManager = this.tileManagers[event.sourceId];\n            if (!tileManager) {\n                return;\n            }\n\n            const source = tileManager.getSource();\n            if (!source?.vectorLayerIds) {\n                return;\n            }\n\n            for (const layerId in this._layers) {\n                const layer = this._layers[layerId];\n                if (layer.source === source.id) {\n                    this._validateLayer(layer);\n                }\n            }\n        });\n    }\n\n    private _setInitialValues() {\n        this._layers = {};\n        this._order = [];\n        this.tileManagers = {};\n        this.zoomHistory = new ZoomHistory();\n        this._imagesListDirty = false;\n        this._initialGlobalState = {};\n        this._globalState = {};\n        this._serializedLayers = {};\n        this.stylesheet = null;\n        this.light = null;\n        this.sky = null;\n        if (this.projection) {\n            this.projection.destroy();\n            delete this.projection;\n        }\n        this._loaded = false;\n        this._changed = false;\n        this._updatedLayers = {};\n        this._updatedSources = {};\n        this._changedImages = {};\n        this._glyphsDidChange = false;\n        this._updatedPaintProps = {};\n        this._layerOrderChanged = false;\n        this._symbolPlacementTriggered = false;\n        this._placedProjectionTransition = undefined;\n        this.crossTileSymbolIndex = new (this.crossTileSymbolIndex?.constructor || Object)();\n        this.pauseablePlacement = undefined;\n        this.placement = undefined;\n        this.z = 0;\n    }\n\n    _rtlPluginLoaded: () => void = () => {\n        for (const id in this.tileManagers) {\n            const sourceType = this.tileManagers[id].getSource().type;\n            if (sourceType === 'vector' || sourceType === 'geojson') {\n                // Non-vector sources don't have any symbols buckets to reload when the RTL text plugin loads\n                // They also load more quickly, so they're more likely to have already displaying tiles\n                // that would be unnecessarily booted by the plugin load event\n                this.tileManagers[id].reload(); // Should be a no-op if the plugin loads before any tiles load\n            }\n        }\n    };\n\n    setGlobalStateProperty(name: string, value: any): this {\n        this._checkLoaded();\n\n        const newValue = value === null ?\n            this.stylesheet.state?.[name]?.default ?? null :\n            value;\n\n        this._setGlobalStateValues({[name]: newValue});\n        return this;\n    }\n\n    getGlobalState(): Record<string, any> {\n        return this._globalState;\n    }\n\n    setGlobalState(newStylesheetState: StateSpecification): void {\n        this._checkLoaded();\n\n        const values: Record<string, any> = {};\n        const propertyNames = new Set([...Object.keys(newStylesheetState ?? {}), ...Object.keys(this._initialGlobalState)]);\n        for (const propertyName of propertyNames) {\n            // Initial global state has priority over global state defaults defined in the map style\n            values[propertyName] = this._initialGlobalState[propertyName] ?? newStylesheetState[propertyName]?.default ?? null;\n        }\n\n        this._setGlobalStateValues(values);\n    }\n\n    /** Sets the keys in `values` that differ, keeping a copy of the state from before so readers transition from it. */\n    _setGlobalStateValues(values: Record<string, any>): void {\n        const changedGlobalStateRefs: string[] = [];\n        for (const ref in values) {\n            if (!deepEqual(values[ref], this._globalState[ref])) {\n                changedGlobalStateRefs.push(ref);\n            }\n        }\n        if (changedGlobalStateRefs.length === 0) {\n            return;\n        }\n\n        const priorGlobalState = {...this._globalState};\n        for (const ref of changedGlobalStateRefs) {\n            this._globalState[ref] = values[ref];\n        }\n\n        this._applyGlobalStateChanges(changedGlobalStateRefs, priorGlobalState);\n    }\n\n    /**\n     * @internal\n     * Find all sources that are affected by the global state changes and reload them.\n     * Find all paint, light and sky properties that are affected and transition them from `priorGlobalState`, the state before the change.\n     * For example, if a layer filter uses global-state expression, this function will find the source id of that layer.\n     */\n    _applyGlobalStateChanges(globalStateRefs: string[], priorGlobalState: Record<string, any>): void {\n        const sourceIdsToReload = new Set<string>();\n        const globalStateChange = {};\n\n        for (const ref of globalStateRefs) {\n            globalStateChange[ref] = this._globalState[ref];\n        }\n\n        for (const layerId in this._layers) {\n            const layer = this._layers[layerId];\n            layer.retainPriorGlobalState(globalStateRefs, priorGlobalState);\n\n            const layoutAffectingGlobalStateRefs = layer.getLayoutAffectingGlobalStateRefs();\n            const paintAffectingGlobalStateRefs = layer.getPaintAffectingGlobalStateRefs();\n            const visibilityAffectingGlobalStateRefs = layer.getVisibilityAffectingGlobalStateRefs();\n\n            for (const ref of globalStateRefs) {\n                if (layoutAffectingGlobalStateRefs.has(ref)) {\n                    sourceIdsToReload.add(layer.source);\n                }\n                if (paintAffectingGlobalStateRefs.has(ref)) {\n                    for (const {name, value} of paintAffectingGlobalStateRefs.get(ref)) {\n                        this._updatePaintProperty(layer, name, value, {validate: false});\n                    }\n                }\n                if (visibilityAffectingGlobalStateRefs?.has(ref)) {\n                    layer.recalculateVisibility();\n                    this._updateLayer(layer);\n                }\n            }\n        }\n\n        const parameters = {now: now(), transition: this.getTransition()};\n        // Loading applies the stylesheet's state before the light and the sky exist.\n        this.light?.applyGlobalStateChange(globalStateRefs, priorGlobalState, parameters);\n        this.sky?.applyGlobalStateChange(globalStateRefs, priorGlobalState, parameters);\n\n        // Propagate global state changes to workers\n        this.dispatcher.broadcast(MessageType.updateGlobalState, globalStateChange);\n\n        for (const id in this.tileManagers) {\n            if (sourceIdsToReload.has(id)) {\n                this._reloadSource(id);\n                this._changed = true;\n            }\n        }\n    }\n\n    async loadURL(url: string, options: StyleSwapOptions & StyleSetterOptions = {}, previousStyle?: StyleSpecification): Promise<void> {\n        this.fire(new MapStyleDataEvent('dataloading'));\n\n        options.validate = typeof options.validate === 'boolean' ?\n            options.validate : true;\n\n        this._loadStyleRequest = new AbortController();\n        const abortController = this._loadStyleRequest;\n        try {\n            const request = await this.map._requestManager.transformRequest(url, ResourceType.Style);\n            throwIfAborted(abortController.signal);\n\n            const response = await getJSON<StyleSpecification>(request, abortController);\n            if (this._loadStyleRequest === abortController) {\n                // Clear this request only if it is still the active style load. A stale\n                // request can finish after a newer loadURL() call has already installed\n                // another controller, and must not clear that newer abort handle.\n                this._loadStyleRequest = null;\n            }\n            this._load(response.data, options, previousStyle);\n        } catch (error) {\n            if (this._loadStyleRequest === abortController) {\n                this._loadStyleRequest = null;\n            }\n            if (error && !abortController.signal.aborted) { // ignore abort\n                this.fire(new ErrorEvent(ensureError(error)));\n            }\n        }\n    }\n\n    loadJSON(json: StyleSpecification, options: StyleSetterOptions & StyleSwapOptions = {}, previousStyle?: StyleSpecification): void {\n        this.fire(new MapStyleDataEvent('dataloading'));\n\n        this._frameRequest = new AbortController();\n        browser.frameAsync(this._frameRequest, this.map._ownerWindow).then(() => {\n            this._frameRequest = null;\n            options.validate = options.validate !== false;\n            this._load(json, options, previousStyle);\n        }).catch(() => {}); // ignore abort\n    }\n\n    loadEmpty(): void {\n        this.fire(new MapStyleDataEvent('dataloading'));\n        this._load(empty, {validate: false});\n    }\n\n    /**\n     * Loads a style. The global state is set first, since the projection and the layers read it. The projection is\n     * created before the sources, which read it as they are added, and the map migrates to it once the layers and the\n     * light exist, so `projectiontransition` handlers can read them.\n     */\n    _load(json: StyleSpecification, options: StyleSwapOptions & StyleSetterOptions, previousStyle?: StyleSpecification): void {\n        let nextState = options.transformStyle ? options.transformStyle(previousStyle, json) : json;\n        if (options.validate && validateStyleAndEmit(this, nextState)) {\n            return;\n        }\n\n        nextState = {...nextState};\n\n        this._loaded = true;\n        this.stylesheet = nextState;\n\n        this.setGlobalState(this.stylesheet.state ?? null);\n        const projectionObjects = createProjectionFromName(this.stylesheet.projection?.type || 'mercator', this.map._camera?.transform.constrainOverride, this._globalState);\n        this.projection = projectionObjects.projection;\n\n        for (const id in nextState.sources) {\n            this.addSource(id, nextState.sources[id], {validate: false});\n        }\n\n        if (nextState.sprite) {\n            this._loadSprite(nextState.sprite);\n        } else {\n            this.imageManager.setLoaded(true);\n        }\n\n        this.glyphManager.setURL(nextState.glyphs);\n        this.glyphManager.setFontFaces(nextState['font-faces']);\n        this._createLayers();\n\n        this.light = new Light(this.stylesheet.light ?? {}, this._globalState);\n        this._applyProjection(projectionObjects);\n\n        this.sky = new Sky(this.stylesheet.sky, this._globalState);\n        this.sky.setEventedParent(this);\n\n        // The stylesheet's terrain was already validated as part of the style itself.\n        this.map.setTerrain(this.stylesheet.terrain ?? null, {validate: false});\n\n        this.fire(new MapStyleDataEvent('data'));\n        this.fire(new MapStyleLoadEvent());\n    }\n\n    private _createLayers() {\n        const dereferencedLayers = derefLayers(this.stylesheet.layers);\n\n        // Broadcast layers to workers first, so that expensive style processing (createStyleLayer)\n        // can happen in parallel on both main and worker threads.\n        this.dispatcher.broadcast(MessageType.setLayers, dereferencedLayers);\n\n        this._order = dereferencedLayers.map((layer) => layer.id);\n        this._layers = {};\n\n        // reset serialization field, to be populated only when needed\n        this._serializedLayers = null;\n        for (const layer of dereferencedLayers) {\n            const styledLayer = createStyleLayer(layer, this._globalState);\n            styledLayer.setEventedParent(this, {layer: {id: layer.id}});\n            this._layers[layer.id] = styledLayer;\n\n            if (isRasterStyleLayer(styledLayer) && this.tileManagers[styledLayer.source]) {\n                const rasterFadeDuration = layer.paint?.['raster-fade-duration'] ?? styledLayer.paint.get('raster-fade-duration');\n                this.tileManagers[styledLayer.source].setRasterFadeDuration(rasterFadeDuration);\n            }\n        }\n    }\n\n    async _loadSprite(sprite: SpriteSpecification, isUpdate: boolean = false, completion: (err: Error) => void = undefined): Promise<void> {\n        this.imageManager.setLoaded(false);\n\n        const abortController = new AbortController();\n        this._spriteRequest = abortController;\n        let err: Error;\n        try {\n            const images = await loadSprite(sprite, this.map._requestManager, this.map.getPixelRatio(), abortController);\n            if (!images) return;\n\n            for (const spriteId in images) {\n                const {loaded, removed} = this.imageManager.setSpriteImages(spriteId, images[spriteId]);\n                this._markImagesChanged(removed);\n                if (isUpdate) {\n                    this._markImagesChanged(loaded);\n                }\n            }\n        } catch (error) {\n            err = error;\n            if (!abortController.signal.aborted) { // ignore abort\n                this.fire(new ErrorEvent(err));\n            }\n        } finally {\n            this._spriteRequest = null;\n            this.imageManager.setLoaded(true);\n\n            if (isUpdate) {\n                this._changed = true;\n            }\n\n            this.dispatcher.broadcast(MessageType.setImages, this.imageManager.listImages());\n            this.fire(new MapStyleDataEvent('data'));\n\n            completion?.(err);\n        }\n    }\n\n    _unloadSprite(): void {\n        this._markImagesChanged(this.imageManager.removeAllSpriteImages());\n\n        this._imagesListDirty = true;\n        this._changed = true;\n        this.fire(new MapStyleDataEvent('data'));\n    }\n\n    _validateLayer(layer: StyleLayer): void {\n        const tileManager = this.tileManagers[layer.source];\n        if (!tileManager) {\n            return;\n        }\n\n        const sourceLayer = layer.sourceLayer;\n        if (!sourceLayer) {\n            return;\n        }\n\n        const source = tileManager.getSource();\n        if (source.type === 'geojson' || (source.vectorLayerIds && !source.vectorLayerIds.includes(sourceLayer))) {\n            this.fire(new ErrorEvent(new Error(\n                `Source layer \"${sourceLayer}\" ` +\n                `does not exist on source \"${source.id}\" ` +\n                `as specified by style layer \"${layer.id}\".`\n            )));\n        }\n    }\n\n    loaded(): boolean {\n        if (!this._loaded)\n            return false;\n\n        if (Object.keys(this._updatedSources).length)\n            return false;\n\n        for (const id in this.tileManagers)\n            if (!this.tileManagers[id].loaded())\n                return false;\n\n        return this.imageManager.isLoaded();\n    }\n\n    /**\n     * @hidden\n     * take an array of string IDs, and based on this._layers, generate an array of LayerSpecification\n     * @param ids - an array of string IDs, for which serialized layers will be generated. If omitted, all serialized layers will be returned\n     * @param returnClone - if true, return a clone of the layer object\n     * @returns generated result\n     */\n    private _serializeByIds(ids: string[], returnClone: boolean = false): LayerSpecification[] {\n\n        const serializedLayersDictionary = this._serializedAllLayers();\n        if (!ids || ids.length === 0) {\n            return returnClone ? Object.values(clone(serializedLayersDictionary)) : Object.values(serializedLayersDictionary);\n        }\n\n        const serializedLayers = [];\n        for (const id of ids) {\n            // this check will skip all custom layers\n            if (serializedLayersDictionary[id]) {\n                const toPush = returnClone ? clone(serializedLayersDictionary[id]) : serializedLayersDictionary[id];\n                serializedLayers.push(toPush);\n            }\n        }\n\n        return serializedLayers;\n    }\n\n    /**\n     * @hidden\n     * Lazy initialization of this._serializedLayers dictionary and return it\n     * @returns this._serializedLayers dictionary\n     */\n    private _serializedAllLayers(): {[_: string]: LayerSpecification} {\n        let serializedLayers = this._serializedLayers;\n        if (serializedLayers) {\n            return serializedLayers;\n        }\n\n        serializedLayers = this._serializedLayers = {};\n        const allLayerIds: string [] = Object.keys(this._layers);\n        for (const layerId of allLayerIds) {\n            const layer = this._layers[layerId];\n            if (layer.type !== 'custom') {\n                serializedLayers[layerId] = layer.serialize();\n            }\n        }\n\n        return serializedLayers;\n    }\n\n    hasTransitions(): boolean {\n        if (this.light?.hasTransition()) {\n            return true;\n        }\n\n        if (this.sky?.hasTransition()) {\n            return true;\n        }\n\n        if (this.projection?.hasTransition()) {\n            return true;\n        }\n\n        for (const id in this.tileManagers) {\n            if (this.tileManagers[id].hasTransition()) {\n                return true;\n            }\n        }\n\n        for (const id in this._layers) {\n            if (this._layers[id].hasTransition()) {\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n    _checkLoaded(): void {\n        if (!this._loaded) {\n            throw new Error('Style is not done loading.');\n        }\n    }\n\n    /**\n     * @internal\n     * Apply queued style updates in a batch and recalculate zoom-dependent paint properties.\n     */\n    update(parameters: EvaluationParameters): void {\n        if (!this._loaded) {\n            return;\n        }\n\n        const changed = this._changed;\n        if (changed) {\n            if (this._imagesListDirty) {\n                this.dispatcher.broadcast(MessageType.setImages, this.imageManager.listImages());\n                this._imagesListDirty = false;\n            }\n\n            const updatedIds = Object.keys(this._updatedLayers);\n            const removedIds = Object.keys(this._removedLayers);\n\n            if (updatedIds.length || removedIds.length) {\n                this._updateWorkerLayers(updatedIds, removedIds);\n            }\n            for (const id in this._updatedSources) {\n                const action = this._updatedSources[id];\n\n                if (action === 'reload') {\n                    this._reloadSource(id);\n                } else if (action === 'clear') {\n                    this._clearSource(id);\n                } else {\n                    throw new Error(`Invalid action ${action}`);\n                }\n            }\n\n            this._updateTilesForChangedImages();\n            this._updateTilesForChangedGlyphs();\n\n            for (const id in this._updatedPaintProps) {\n                this._layers[id].updateTransitions(parameters);\n            }\n\n            this._resetUpdates();\n        }\n\n        const managersUsedBefore = {};\n\n        // save 'used' status to managersUsedBefore object and reset all tileManagers 'used' field to false\n        for (const id in this.tileManagers) {\n            const tileManager = this.tileManagers[id];\n\n            // tileManager.used could be undefined, and managersUsedBefore[id] is also 'undefined'\n            managersUsedBefore[id] = tileManager.used;\n            tileManager.used = false;\n        }\n\n        // loop all layers and find layers that are not hidden at parameters.zoom\n        // and set used to true in tileManagers dictionary for the sources of these layers\n        const availableImages = this.imageManager.listImages();\n        for (const layerId of this._order) {\n            const layer = this._layers[layerId];\n\n            layer.recalculate(parameters, availableImages);\n            if (!layer.isHidden(parameters.zoom) && layer.source) {\n                this.tileManagers[layer.source].used = true;\n            }\n        }\n\n        // cross check managersUsedBefore against updated this.tileManagers dictionary\n        // if \"used\" field is different fire visibility event\n        for (const id in managersUsedBefore) {\n            const tileManager = this.tileManagers[id];\n\n            // (undefine !== false) will evaluate to true and fire an useless visibility event\n            // need force \"falsy\" values to boolean to avoid the case above\n            if (!!managersUsedBefore[id] !== !!tileManager.used) {\n                tileManager.fire(new MapSourceDataEvent('data',\n                    {\n                        sourceDataType: 'visibility',\n                        sourceId: id\n                    }));\n            }\n        }\n\n        this.light.recalculate(parameters);\n        this.sky.recalculate(parameters);\n        this.projection.recalculate(parameters);\n        this.z = parameters.zoom;\n\n        if (changed) {\n            this.fire(new MapStyleDataEvent('data'));\n        }\n    }\n\n    /*\n     * Apply any queued image changes.\n     */\n    _updateTilesForChangedImages(): void {\n        const changedImages = Object.keys(this._changedImages);\n        if (changedImages.length) {\n            for (const name in this.tileManagers) {\n                this.tileManagers[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages);\n            }\n            this._changedImages = {};\n        }\n    }\n\n    _updateTilesForChangedGlyphs(): void {\n        if (this._glyphsDidChange) {\n            for (const name in this.tileManagers) {\n                this.tileManagers[name].reloadTilesForDependencies(['glyphs'], ['']);\n            }\n            this._glyphsDidChange = false;\n        }\n    }\n\n    _updateWorkerLayers(updatedIds: string[], removedIds: string[]): void {\n        this.dispatcher.broadcast(MessageType.updateLayers, {\n            layers: this._serializeByIds(updatedIds, false),\n            removedIds\n        });\n    }\n\n    /** Tells the layers that the canvas was resized. */\n    resize(): void {\n        for (const layerId of this._order) {\n            this._layers[layerId].resize();\n        }\n    }\n\n    _resetUpdates(): void {\n        this._changed = false;\n\n        this._updatedLayers = {};\n        this._removedLayers = {};\n\n        this._updatedSources = {};\n        this._updatedPaintProps = {};\n\n        this._changedImages = {};\n        this._glyphsDidChange = false;\n    }\n\n    /**\n     * Update this style's state to match the given style JSON, performing only\n     * the necessary mutations.\n     *\n     * May throw an Error ('Unimplemented: METHOD') if the maplibre-gl-style-spec\n     * diff algorithm produces an operation that is not supported.\n     *\n     * @returns true if any changes were made; false otherwise\n     */\n    setState(nextState: StyleSpecification, options: StyleSwapOptions & StyleSetterOptions = {}): boolean {\n        this._checkLoaded();\n\n        const serializedStyle =  this.serialize();\n        nextState = options.transformStyle ? options.transformStyle(serializedStyle, nextState) : nextState;\n        const validate = options.validate ?? true;\n        if (validate && validateStyleAndEmit(this, nextState)) return false;\n\n        nextState = clone(nextState);\n        nextState.layers = derefLayers(nextState.layers);\n\n        const changes = diffStyles(serializedStyle, nextState);\n        const operations = this._getOperationsToPerform(changes);\n\n        if (operations.unimplemented.length > 0) {\n            throw new Error(`Unimplemented: ${operations.unimplemented.join(', ')}.`);\n        }\n\n        if (operations.operations.length === 0) {\n            return false;\n        }\n\n        this._initialGlobalState = options.globalState ?? {};\n        for (const styleChangeOperation of operations.operations) {\n            styleChangeOperation();\n        }\n\n        this.stylesheet = nextState;\n\n        // reset serialization field, to be populated only when needed\n        this._serializedLayers = null;\n\n        this.fire(new MapStyleLoadEvent({style: this}));\n\n        return true;\n    }\n\n    /**\n     * Translates a style diff into the calls that apply it to this style.\n     * @param diff - the operations produced by the style-spec diff algorithm\n     * @returns the operations to run, and the names of the commands that are not supported\n     */\n    _getOperationsToPerform(diff: DiffCommand[]): {operations: Array<() => void>; unimplemented: string[]} {\n        const operations: Array<() => void> = [];\n        const unimplemented: string[] = [];\n        for (const op of diff) {\n            switch (op.command) {\n                case 'setCenter':\n                case 'setZoom':\n                case 'setBearing':\n                case 'setPitch':\n                case 'setRoll':\n                    continue;\n                case 'addLayer': {\n                    const [layer, before] = op.args;\n                    operations.push(() => this.addLayer(layer, before));\n                    break;\n                }\n                case 'removeLayer': {\n                    const [layerId] = op.args;\n                    operations.push(() => this.removeLayer(layerId));\n                    break;\n                }\n                case 'setPaintProperty': {\n                    const [layerId, name, value] = op.args;\n                    operations.push(() => this.setPaintProperty(layerId, name, value));\n                    break;\n                }\n                case 'setLayoutProperty': {\n                    const [layerId, name, value] = op.args;\n                    operations.push(() => this.setLayoutProperty(layerId, name, value));\n                    break;\n                }\n                case 'setFilter': {\n                    const [layerId, filter] = op.args;\n                    operations.push(() => this.setFilter(layerId, filter));\n                    break;\n                }\n                case 'addSource': {\n                    const [id, source] = op.args;\n                    operations.push(() => this.addSource(id, source));\n                    break;\n                }\n                case 'removeSource': {\n                    const [id] = op.args;\n                    operations.push(() => this.removeSource(id));\n                    break;\n                }\n                case 'setLayerZoomRange': {\n                    const [layerId, minzoom, maxzoom] = op.args;\n                    operations.push(() => this.setLayerZoomRange(layerId, minzoom, maxzoom));\n                    break;\n                }\n                case 'setLight': {\n                    const [light] = op.args;\n                    operations.push(() => this.setLight(light));\n                    break;\n                }\n                case 'setGeoJSONSourceData': {\n                    const [id, data] = op.args;\n                    operations.push(() => this.setGeoJSONSourceData(id, data));\n                    break;\n                }\n                case 'setGlyphs': {\n                    const [glyphsUrl] = op.args;\n                    operations.push(() => this.setGlyphs(glyphsUrl));\n                    break;\n                }\n                case 'setFontFaces': {\n                    const [fontFaces] = op.args;\n                    operations.push(() => this.setFontFaces(fontFaces));\n                    break;\n                }\n                case 'setSprite': {\n                    const [sprite] = op.args;\n                    operations.push(() => this.setSprite(sprite));\n                    break;\n                }\n                case 'setTerrain': {\n                    const [terrain] = op.args;\n                    operations.push(() => this.map.setTerrain(terrain));\n                    break;\n                }\n                case 'setSky': {\n                    const [sky] = op.args;\n                    operations.push(() => this.setSky(sky));\n                    break;\n                }\n                case 'setProjection': {\n                    const [projection] = op.args;\n                    operations.push(() => this.setProjection(projection));\n                    break;\n                }\n                case 'setGlobalState': {\n                    const [state] = op.args;\n                    operations.push(() => this.setGlobalState(state));\n                    break;\n                }\n                case 'setTransition':\n                    operations.push(() => {});\n                    break;\n                default:\n                    unimplemented.push(op.command);\n                    break;\n            }\n        }\n        return {operations, unimplemented};\n    }\n\n    addImage(id: string, image: StyleImage): void {\n        if (this.getImage(id)) {\n            this.fire(new ErrorEvent(new Error(`An image named \"${id}\" already exists.`)));\n            return;\n        }\n        this.imageManager.addImage(id, image);\n        this._afterImageUpdated(id);\n    }\n\n    updateImage(id: string, image: StyleImage): void {\n        this.imageManager.updateImage(id, image);\n    }\n\n    getImage(id: string): StyleImage {\n        return this.imageManager.getImage(id);\n    }\n\n    setMissingImageResolver(resolver: MissingImageRequestHandler | null): void {\n        this.imageManager.setMissingImageResolver(resolver);\n    }\n\n    removeImage(id: string): void {\n        if (!this.getImage(id)) {\n            this.fire(new ErrorEvent(new Error(`An image named \"${id}\" does not exist.`)));\n            return;\n        }\n        this.imageManager.removeImage(id);\n        this._afterImageUpdated(id);\n    }\n\n    /**\n     * Queues the tiles that depend on these images to be reloaded on the next update, which is\n     * needed whenever an image appears, disappears or changes size.\n     */\n    _markImagesChanged(ids: string[]): void {\n        for (const id of ids) {\n            this._changedImages[id] = true;\n        }\n    }\n\n    _afterImageUpdated(id: string): void {\n        this._changedImages[id] = true;\n        this._imagesListDirty = true;\n        this._changed = true;\n        this.fire(new MapStyleDataEvent('data'));\n    }\n\n    listImages(): string[] {\n        this._checkLoaded();\n\n        return this.imageManager.listImages();\n    }\n\n    addSource(id: string, source: SourceSpecification | CanvasSourceSpecification, options: StyleSetterOptions = {}): void {\n        this._checkLoaded();\n\n        if (this.tileManagers[id] !== undefined) {\n            throw new Error(`Source \"${id}\" already exists.`);\n        }\n\n        if (!source.type) {\n            throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(', ')}.`);\n        }\n\n        const shouldValidate = SPEC_SOURCE_TYPES.has(source.type);\n        if (shouldValidate && this._validate(validateStyle.source, `sources.${id}`, source, null, options)) return;\n        if (this.map?._collectResourceTiming) (source as any).collectResourceTiming = true;\n        const tileManager = this.tileManagers[id] = new TileManager(id, source, this.dispatcher);\n        tileManager.style = this;\n        tileManager.setEventedParent(this, () => ({\n            isSourceLoaded: tileManager.loaded(),\n            source: tileManager.serialize(),\n            sourceId: id\n        }));\n\n        tileManager.onAdd(this.map);\n        this._changed = true;\n    }\n\n    /**\n     * Remove a source from this stylesheet, given its id.\n     * @param id - id of the source to remove\n     * @throws if no source is found with the given ID\n     */\n    removeSource(id: string): this {\n        this._checkLoaded();\n\n        if (this.tileManagers[id] === undefined) {\n            throw new Error(`There is no source with this ID=${id}`);\n        }\n        for (const layerId in this._layers) {\n            if (this._layers[layerId].source === id) {\n                return this.fire(new ErrorEvent(new Error(`Source \"${id}\" cannot be removed while layer \"${layerId}\" is using it.`)));\n            }\n        }\n\n        const tileManager = this.tileManagers[id];\n        delete this.tileManagers[id];\n        delete this._updatedSources[id];\n        tileManager.fire(new MapSourceDataEvent('data', {sourceDataType: 'metadata', sourceId: id}));\n        tileManager.setEventedParent(null);\n        tileManager.onRemove(this.map);\n        this._changed = true;\n    }\n\n    /**\n     * Set the data of a GeoJSON source, given its id.\n     * @param id - id of the source\n     * @param data - GeoJSON source\n     */\n    setGeoJSONSourceData(id: string, data: GeoJSON.GeoJSON | string): void {\n        this._checkLoaded();\n\n        if (this.tileManagers[id] === undefined) throw new Error(`There is no source with this ID=${id}`);\n        const geojsonSource: GeoJSONSource = (this.tileManagers[id].getSource() as any);\n        if (geojsonSource.type !== 'geojson') throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`);\n\n        geojsonSource.setData(data);\n        this._changed = true;\n    }\n\n    /**\n     * Get a source by ID.\n     * @param id - ID of the desired source\n     * @returns source\n     */\n    getSource(id: string): Source | undefined {\n        return this.tileManagers[id]?.getSource();\n    }\n\n    /**\n     * Add a layer to the map style. The layer will be inserted before the layer with\n     * ID `before`, or appended if `before` is omitted.\n     * @param layerObject - The style layer to add.\n     * @param before - ID of an existing layer to insert before\n     * @param options - Style setter options.\n     */\n    addLayer(layerObject: AddLayerObject, before?: string, options: StyleSetterOptions = {}): this {\n        this._checkLoaded();\n\n        const id = layerObject.id;\n\n        if (this.getLayer(id)) {\n            this.fire(new ErrorEvent(new Error(`Layer \"${id}\" already exists on this map.`)));\n            return;\n        }\n\n        let layer: ReturnType<typeof createStyleLayer>;\n        if (layerObject.type === 'custom') {\n\n            if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) return;\n\n            layer = createStyleLayer(layerObject, this._globalState);\n\n        } else {\n            if ('source' in layerObject && typeof layerObject.source === 'object') {\n                this.addSource(id, layerObject.source);\n                layerObject = clone(layerObject);\n                layerObject = extend(layerObject, {source: id});\n            }\n\n            // this layer is not in the style.layers array, so we pass an impossible array index\n            if (this._validate(validateStyle.layer,\n                `layers.${id}`, layerObject, {arrayIndex: -1}, options)) return;\n\n            layer = createStyleLayer(layerObject as LayerSpecification | CustomLayerInterface, this._globalState);\n            this._validateLayer(layer);\n\n            layer.setEventedParent(this, {layer: {id}});\n        }\n\n        const index = before ? this._order.indexOf(before) : this._order.length;\n        if (before && index === -1) {\n            this.fire(new ErrorEvent(new Error(`Cannot add layer \"${id}\" before non-existing layer \"${before}\".`)));\n            return;\n        }\n\n        this._order.splice(index, 0, id);\n        this._layerOrderChanged = true;\n\n        this._layers[id] = layer;\n\n        if (this._removedLayers[id] && layer.source && layer.type !== 'custom') {\n            // If, in the current batch, we have already removed this layer\n            // and we are now re-adding it with a different `type`, then we\n            // need to clear (rather than just reload) the underlying source's\n            // tiles.  Otherwise, tiles marked 'reloading' will have buckets /\n            // buffers that are set up for the _previous_ version of this\n            // layer, causing, e.g.:\n            // https://github.com/mapbox/mapbox-gl-js/issues/3633\n            const removed = this._removedLayers[id];\n            delete this._removedLayers[id];\n            if (removed.type !== layer.type) {\n                this._updatedSources[layer.source] = 'clear';\n            } else {\n                this._updatedSources[layer.source] = 'reload';\n                this.tileManagers[layer.source].pause();\n            }\n        }\n        this._updateLayer(layer);\n\n        if (layer.onAdd) {\n            layer.onAdd(this.map);\n        }\n    }\n\n    /**\n     * Moves a layer to a different z-position. The layer will be inserted before the layer with\n     * ID `before`, or appended if `before` is omitted.\n     * @param id - ID of the layer to move\n     * @param before - ID of an existing layer to insert before\n     */\n    moveLayer(id: string, before?: string): void {\n        this._checkLoaded();\n        this._changed = true;\n\n        const layer = this._layers[id];\n        if (!layer) {\n            this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`)));\n            return;\n        }\n\n        if (id === before) {\n            return;\n        }\n\n        if (before && !this._order.includes(before)) {\n            this.fire(new ErrorEvent(new Error(`Cannot move layer \"${id}\" before non-existing layer \"${before}\".`)));\n            return;\n        }\n\n        const index = this._order.indexOf(id);\n        this._order.splice(index, 1);\n\n        const newIndex = before ? this._order.indexOf(before) : this._order.length;\n        this._order.splice(newIndex, 0, id);\n\n        this._layerOrderChanged = true;\n    }\n\n    /**\n     * Remove the layer with the given id from the style.\n     * A {@link ErrorEvent} event will be fired if no such layer exists.\n     *\n     * @param id - id of the layer to remove\n     */\n    removeLayer(id: string): void {\n        this._checkLoaded();\n\n        const layer = this._layers[id];\n        if (!layer) {\n            this.fire(new ErrorEvent(new Error(`Cannot remove non-existing layer \"${id}\".`)));\n            return;\n        }\n\n        layer.setEventedParent(null);\n\n        const index = this._order.indexOf(id);\n        this._order.splice(index, 1);\n\n        this._layerOrderChanged = true;\n        this._changed = true;\n        this._removedLayers[id] = layer;\n        delete this._layers[id];\n\n        if (this._serializedLayers) {\n            delete this._serializedLayers[id];\n        }\n        delete this._updatedLayers[id];\n        delete this._updatedPaintProps[id];\n\n        if (layer.type === 'symbol' && layer.source) {\n            this.tileManagers[layer.source]?.resetMaxContentElevation();\n        }\n\n        if (layer.onRemove) {\n            layer.onRemove(this.map);\n        }\n    }\n\n    /**\n     * Return the style layer object with the given `id`.\n     *\n     * @param id - id of the desired layer\n     * @returns a layer, if one with the given `id` exists\n     */\n    getLayer(id: string): StyleLayer | undefined {\n        return this._layers[id];\n    }\n\n    /**\n     * Return the ids of all layers currently in the style, including custom layers, in order.\n     *\n     * @returns ids of layers, in order\n     */\n    getLayersOrder(): string[] {\n        return [...this._order];\n    }\n\n    /**\n     * Checks if a specific layer is present within the style.\n     *\n     * @param id - the id of the desired layer\n     * @returns a boolean specifying if the given layer is present\n     */\n    hasLayer(id: string): boolean {\n        return id in this._layers;\n    }\n\n    setLayerZoomRange(layerId: string, minzoom?: number | null, maxzoom?: number | null): void {\n        this._checkLoaded();\n\n        const layer = this.getLayer(layerId);\n        if (!layer) {\n            this.fire(new ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer \"${layerId}\".`)));\n            return;\n        }\n\n        if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) return;\n\n        if (minzoom != null) {\n            layer.minzoom = minzoom;\n        }\n        if (maxzoom != null) {\n            layer.maxzoom = maxzoom;\n        }\n        this._updateLayer(layer);\n    }\n\n    setFilter(layerId: string, filter?: FilterSpecification | null,  options: StyleSetterOptions = {}): void {\n        this._checkLoaded();\n\n        const layer = this.getLayer(layerId);\n        if (!layer) {\n            this.fire(new ErrorEvent(new Error(`Cannot filter non-existing layer \"${layerId}\".`)));\n            return;\n        }\n\n        if (deepEqual(layer.filter, filter)) {\n            return;\n        }\n\n        if (filter === null || filter === undefined) {\n            layer.setFilter(undefined);\n            this._updateLayer(layer);\n            return;\n        }\n\n        if (this._validate(validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) {\n            return;\n        }\n\n        layer.setFilter(clone(filter));\n        this._updateLayer(layer);\n    }\n\n    /**\n     * Get a layer's filter object\n     * @param layer - the layer to inspect\n     * @returns the layer's filter, if any\n     */\n    getFilter(layer: string): FilterSpecification | void {\n        return clone(this.getLayer(layer).filter);\n    }\n\n    setLayoutProperty<K extends keyof AllLayoutProperties>(layerId: string, name: K, value: AllLayoutProperties[K],  options: StyleSetterOptions = {}): void {\n        this._checkLoaded();\n\n        const layer = this.getLayer(layerId);\n        if (!layer) {\n            this.fire(new ErrorEvent(new Error(`Cannot style non-existing layer \"${layerId}\".`)));\n            return;\n        }\n\n        if (deepEqual(layer.getLayoutProperty(name), value)) return;\n\n        layer.setLayoutProperty(name, value, options);\n        this._updateLayer(layer);\n    }\n\n    /**\n     * Get a layout property's value from a given layer\n     * @param layerId - the layer to inspect\n     * @param name - the name of the layout property\n     * @returns the property value\n     */\n    getLayoutProperty<K extends keyof AllLayoutProperties>(layerId: string, name: K): AllLayoutProperties[K] | undefined {\n        const layer = this.getLayer(layerId);\n        if (!layer) {\n            this.fire(new ErrorEvent(new Error(`Cannot get style of non-existing layer \"${layerId}\".`)));\n            return;\n        }\n\n        return layer.getLayoutProperty(name);\n    }\n\n    setPaintProperty<K extends keyof AllPaintProperties>(layerId: string, name: K, value: AllPaintProperties[K], options: StyleSetterOptions = {}): void {\n        this._checkLoaded();\n\n        const layer = this.getLayer(layerId);\n        if (!layer) {\n            this.fire(new ErrorEvent(new Error(`Cannot style non-existing layer \"${layerId}\".`)));\n            return;\n        }\n\n        if (deepEqual(layer.getPaintProperty(name), value)) return;\n\n        this._updatePaintProperty(layer, name, value, options);\n    }\n\n    _updatePaintProperty<K extends keyof AllPaintProperties>(layer: StyleLayer, name: K, value: AllPaintProperties[K], options: StyleSetterOptions = {}): void {\n        const requiresRelayout = layer.setPaintProperty(name, value, options);\n        if (requiresRelayout) {\n            this._updateLayer(layer);\n        }\n\n        if (isRasterStyleLayer(layer) && name === 'raster-fade-duration') {\n            this.tileManagers[layer.source].setRasterFadeDuration(value as number);\n        }\n\n        this._changed = true;\n        this._updatedPaintProps[layer.id] = true;\n        if (layer.type === 'symbol') this.triggerSymbolPlacement();\n        // reset serialization field, to be populated only when needed\n        this._serializedLayers = null;\n    }\n\n    getPaintProperty<K extends keyof AllPaintProperties>(layer: string, name: K): AllPaintProperties[K] {\n        return this.getLayer(layer).getPaintProperty(name);\n    }\n\n    setFeatureState(target: FeatureIdentifier, state: any): void {\n        this._checkLoaded();\n        const sourceId = target.source;\n        const sourceLayer = target.sourceLayer;\n        const tileManager = this.tileManagers[sourceId];\n\n        if (tileManager === undefined) {\n            this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n            return;\n        }\n        const sourceType = tileManager.getSource().type;\n        if (sourceType === 'geojson' && sourceLayer) {\n            this.fire(new ErrorEvent(new Error('GeoJSON sources cannot have a sourceLayer parameter.')));\n            return;\n        }\n        if (sourceType === 'vector' && !sourceLayer) {\n            this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));\n            return;\n        }\n        if (target.id === undefined) {\n            this.fire(new ErrorEvent(new Error('The feature id parameter must be provided.')));\n            return;\n        }\n        const forbiddenStateKeys = ['__proto__', 'constructor', 'prototype'];\n        if (state && Object.keys(state).some((stateKey: string) => forbiddenStateKeys.includes(stateKey))){\n            this.fire(new ErrorEvent(new Error(`The feature state should not include one of the following keys: ${forbiddenStateKeys}`)));\n            return;\n        }\n\n        tileManager.setFeatureState(sourceLayer, target.id, state);\n    }\n\n    removeFeatureState(target: FeatureIdentifier, key?: string): void {\n        this._checkLoaded();\n        const sourceId = target.source;\n        const tileManager = this.tileManagers[sourceId];\n\n        if (tileManager === undefined) {\n            this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n            return;\n        }\n\n        const sourceType = tileManager.getSource().type;\n        const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined;\n\n        if (sourceType === 'vector' && !sourceLayer) {\n            this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));\n            return;\n        }\n\n        if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) {\n            this.fire(new ErrorEvent(new Error('A feature id is required to remove its specific state property.')));\n            return;\n        }\n\n        tileManager.removeFeatureState(sourceLayer, target.id, key);\n    }\n\n    getFeatureState(target: FeatureIdentifier): FeatureState {\n        this._checkLoaded();\n        const sourceId = target.source;\n        const sourceLayer = target.sourceLayer;\n        const tileManager = this.tileManagers[sourceId];\n\n        if (tileManager === undefined) {\n            this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n            return;\n        }\n        const sourceType = tileManager.getSource().type;\n        if (sourceType === 'vector' && !sourceLayer) {\n            this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));\n            return;\n        }\n        if (target.id === undefined) {\n            this.fire(new ErrorEvent(new Error('The feature id parameter must be provided.')));\n        }\n\n        return tileManager.getFeatureState(sourceLayer, target.id);\n    }\n\n    getTransition(): {duration: number; delay: number} & TransitionSpecification {\n        return extend({duration: 300, delay: 0}, this.stylesheet?.transition);\n    }\n\n    serialize(): StyleSpecification | undefined {\n        // We return undefined before we're loaded, following the pattern of Map.getStyle() before\n        // the Style object is initialized.\n        // Internally, Style._validate() calls Style.serialize() but callers are responsible for\n        // calling Style._checkLoaded() first if their validation requires the style to be loaded.\n        if (!this._loaded) return;\n\n        const sources = mapObject(this.tileManagers, (source) => source.serialize());\n        const layers = this._serializeByIds(this._order, true);\n        const terrain = this.map.getTerrain() || undefined;\n        const myStyleSheet = this.stylesheet;\n\n        return filterObject({\n            version: myStyleSheet.version,\n            name: myStyleSheet.name,\n            metadata: myStyleSheet.metadata,\n            light: myStyleSheet.light,\n            sky: myStyleSheet.sky,\n            center: myStyleSheet.center,\n            zoom: myStyleSheet.zoom,\n            bearing: myStyleSheet.bearing,\n            pitch: myStyleSheet.pitch,\n            sprite: myStyleSheet.sprite,\n            glyphs: myStyleSheet.glyphs,\n            'font-faces': myStyleSheet['font-faces'],\n            transition: myStyleSheet.transition,\n            projection: myStyleSheet.projection,\n            state: myStyleSheet.state,\n            sources,\n            layers,\n            terrain,\n        },\n        (value) => value !== undefined);\n    }\n\n    _updateLayer(layer: StyleLayer): void {\n        this._updatedLayers[layer.id] = true;\n        if (layer.source && !this._updatedSources[layer.source] &&\n            //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865)\n            this.tileManagers[layer.source].getSource().type !== 'raster') {\n            this._updatedSources[layer.source] = 'reload';\n            this.tileManagers[layer.source].pause();\n        }\n\n        // upon updating, serialized layer dictionary should be reset.\n        // When needed, it will be populated with the correct copy again.\n        this._serializedLayers = null;\n        this._changed = true;\n    }\n\n    _flattenAndSortRenderedFeatures(sourceResults: QueryRenderedFeaturesResults[]): MapGeoJSONFeature[] {\n        // Feature order is complicated.\n        // The order between features in two 2D layers is always determined by layer order.\n        // The order between features in two 3D layers is always determined by depth.\n        // The order between a feature in a 2D layer and a 3D layer is tricky:\n        //      Most often layer order determines the feature order in this case. If\n        //      a line layer is above a extrusion layer the line feature will be rendered\n        //      above the extrusion. If the line layer is below the extrusion layer,\n        //      it will be rendered below it.\n        //\n        //      There is a weird case though.\n        //      You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b\n        //      Each layer has a feature that overlaps the other features.\n        //      The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above.\n        //      The feature in line_layer is rendered above extrusion_layer_a.\n        //      This means that that the line_layer feature is above the extrusion_layer_b feature despite\n        //      it being in an earlier layer.\n\n        const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion';\n\n        const layerIndex = {};\n        const features3D: QueryRenderedFeaturesResultsItem[] = [];\n        for (let l = this._order.length - 1; l >= 0; l--) {\n            const layerId = this._order[l];\n            if (isLayer3D(layerId)) {\n                layerIndex[layerId] = l;\n                for (const sourceResult of sourceResults) {\n                    const layerFeatures = sourceResult[layerId];\n                    if (layerFeatures) {\n                        for (const featureWrapper of layerFeatures) {\n                            features3D.push(featureWrapper);\n                        }\n                    }\n                }\n            }\n        }\n\n        features3D.sort((a, b) => {\n            return (b.intersectionZ as number) - (a.intersectionZ as number);\n        });\n\n        const features: MapGeoJSONFeature[] = [];\n        for (let l = this._order.length - 1; l >= 0; l--) {\n            const layerId = this._order[l];\n\n            if (isLayer3D(layerId)) {\n                // add all 3D features that are in or above the current layer\n                for (let i = features3D.length - 1; i >= 0; i--) {\n                    const topmost3D = features3D[i].feature;\n                    if (layerIndex[topmost3D.layer.id] < l) break;\n                    features.push(topmost3D);\n                    features3D.pop();\n                }\n            } else {\n                for (const sourceResult of sourceResults) {\n                    const layerFeatures = sourceResult[layerId];\n                    if (layerFeatures) {\n                        for (const featureWrapper of layerFeatures) {\n                            features.push(featureWrapper.feature);\n                        }\n                    }\n                }\n            }\n        }\n\n        return features;\n    }\n\n    queryRenderedFeatures(queryGeometry: Point[], params: QueryRenderedFeaturesOptions, transform: IReadonlyTransform): MapGeoJSONFeature[] {\n        if (params?.filter) {\n            this._validate(validateStyle.filter, 'queryRenderedFeatures.filter', params.filter, null, params);\n        }\n\n        const includedSources = {};\n        if (params?.layers) {\n            const isArrayOrSet = Array.isArray(params.layers) || params.layers instanceof Set;\n            if (!isArrayOrSet) {\n                this.fire(new ErrorEvent(new Error('parameters.layers must be an Array or a Set of strings')));\n                return [];\n            }\n            for (const layerId of params.layers) {\n                const layer = this._layers[layerId];\n                if (!layer) {\n                    // this layer is not in the style.layers array\n                    this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`)));\n                    return [];\n                }\n                includedSources[layer.source] = true;\n            }\n        }\n\n        const sourceResults: QueryRenderedFeaturesResults[] = [];\n\n        params.availableImages = this.imageManager.listImages();\n\n        // LayerSpecification is serialized StyleLayer, and this casting is safe.\n        const serializedLayers = this._serializedAllLayers() as {[_: string]: StyleLayer};\n\n        const layersAsSet = params.layers instanceof Set ? params.layers : Array.isArray(params.layers) ? new Set(params.layers) : null;\n        const paramsStrict: QueryRenderedFeaturesOptionsStrict = {\n            ...params,\n            layers: layersAsSet,\n            globalState: this._globalState\n        };\n\n        for (const id in this.tileManagers) {\n            if (params.layers && !includedSources[id]) continue;\n            sourceResults.push(\n                queryRenderedFeatures(\n                    this.tileManagers[id],\n                    this._layers,\n                    serializedLayers,\n                    queryGeometry,\n                    paramsStrict,\n                    transform,\n                    this.map.terrain ?\n                        (id: OverscaledTileID, x: number, y: number) =>\n                            this.map.terrain.getElevation(id, x, y) :\n                        undefined)\n            );\n        }\n\n        if (this.placement) {\n            // If a placement has run, query against its CollisionIndex\n            // for symbol results, and treat it as an extra source to merge\n            sourceResults.push(\n                queryRenderedSymbols(\n                    this._layers,\n                    serializedLayers,\n                    this.tileManagers,\n                    queryGeometry,\n                    paramsStrict,\n                    this.placement.collisionIndex,\n                    this.placement.retainedQueryData)\n            );\n        }\n\n        return this._flattenAndSortRenderedFeatures(sourceResults);\n    }\n\n    querySourceFeatures(\n        sourceID: string,\n        params?: QuerySourceFeatureOptions\n    ): GeoJSONFeature[] {\n        if (params?.filter) {\n            this._validate(validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params);\n        }\n        const tileManager = this.tileManagers[sourceID];\n        if (!tileManager) return [];\n        const paramsStrict = {...params, globalState: this._globalState, worldCoordinateHelper: this.projection.worldCoordinateHelper};\n        return querySourceFeatures(tileManager, paramsStrict);\n    }\n\n    getLight(): LightSpecification {\n        return this.light.getLight();\n    }\n\n    setLight(lightOptions: LightSpecification, options: StyleSetterOptions = {}): void {\n        this._checkLoaded();\n\n        const light = this.light.getLight();\n        let _update = false;\n        for (const key in lightOptions) {\n            if (!deepEqual(lightOptions[key], light[key])) {\n                _update = true;\n                break;\n            }\n        }\n        if (!_update) return;\n\n        const parameters = {\n            now: now(),\n            transition: extend({\n                duration: 300,\n                delay: 0\n            }, this.stylesheet.transition)\n        };\n\n        this.light.setLight(lightOptions, options);\n        this.light.updateTransitions(parameters);\n    }\n\n    getProjection(): ProjectionSpecification {\n        return this.stylesheet?.projection;\n    }\n\n    setProjection(projection?: ProjectionSpecification): void {\n        this._checkLoaded();\n        const resolvedProjection = projection ?? {type: 'mercator'};\n        this.stylesheet.projection = projection;\n        if (this.projection) {\n            if (this.projection.name === resolvedProjection.type) {\n                return;\n            }\n            this.projection.destroy();\n            delete this.projection;\n        }\n        this._setProjectionInternal(resolvedProjection.type);\n    }\n\n    getSky(): SkySpecification {\n        return this.stylesheet?.sky;\n    }\n\n    setSky(skyOptions?: SkySpecification, options: StyleSetterOptions = {}): void {\n        this._checkLoaded();\n\n        const sky = this.getSky();\n\n        let update = false;\n        if (!skyOptions && !sky) return;\n\n        if (skyOptions && !sky) {\n            update = true;\n        } else if (!skyOptions && sky) {\n            update = true;\n        } else {\n            for (const key in skyOptions) {\n                if (!deepEqual(skyOptions[key], sky[key])) {\n                    update = true;\n                    break;\n                }\n            }\n        }\n        if (!update) return;\n\n        const parameters = {\n            now: now(),\n            transition: extend({\n                duration: 300,\n                delay: 0\n            }, this.stylesheet.transition)\n        };\n\n        if (!this.sky.setSky(skyOptions, options)) return;\n        this.stylesheet.sky = skyOptions;\n        this.sky.updateTransitions(parameters);\n    }\n\n    _setProjectionInternal(name: ProjectionSpecification['type']): void {\n        this._applyProjection(createProjectionFromName(name, this.map._camera?.transform.constrainOverride, this._globalState));\n    }\n\n    /**\n     * Puts a projection in place and migrates the map to its transform, which fires `projectiontransition`, then\n     * reloads the tiles in it.\n     */\n    private _applyProjection(projectionObjects: ReturnType<typeof createProjectionFromName>): void {\n        this.projection = projectionObjects.projection;\n        this.map.migrateProjection(projectionObjects.transform, projectionObjects.cameraHelper);\n        for (const key in this.tileManagers) {\n            this.tileManagers[key].reload();\n        }\n    }\n\n    _validate(validate: Validator, key: string, value: any, props: any, options: StyleSetterOptions = {}): boolean {\n        if (options.validate === false) return false;\n\n        return validateAndEmit(this, validate, {\n            key,\n            style: this.serialize(),\n            value,\n            ...props\n        }, options);\n    }\n\n    _remove(mapRemoved: boolean = true): void {\n        if (this._frameRequest) {\n            this._frameRequest.abort();\n            this._frameRequest = null;\n        }\n        if (this._loadStyleRequest) {\n            this._loadStyleRequest.abort();\n            this._loadStyleRequest = null;\n        }\n        if (this._spriteRequest) {\n            this._spriteRequest.abort();\n            this._spriteRequest = null;\n        }\n        rtlMainThreadPluginFactory().off(RTLPluginLoadedEventName, this._rtlPluginLoaded);\n        for (const layerId in this._layers) {\n            const layer: StyleLayer = this._layers[layerId];\n            layer.setEventedParent(null);\n        }\n        for (const id in this.tileManagers) {\n            const tileManager = this.tileManagers[id];\n            tileManager.setEventedParent(null);\n            tileManager.onRemove(this.map);\n        }\n        this.imageManager.setEventedParent(null);\n        this.setEventedParent(null);\n        if (mapRemoved) {\n            this.dispatcher.broadcast(MessageType.removeMap, undefined);\n        }\n        this.dispatcher.remove(mapRemoved);\n    }\n\n    _clearSource(id: string): void {\n        this.tileManagers[id].clearTiles();\n    }\n\n    _reloadSource(id: string): void {\n        this.tileManagers[id].resume();\n        this.tileManagers[id].reload();\n    }\n\n    _updateSources(transform: IReadonlyTransform): void {\n        for (const id in this.tileManagers) {\n            this.tileManagers[id].update(transform, this.map.terrain);\n        }\n    }\n\n    _generateCollisionBoxes(): void {\n        for (const id in this.tileManagers) {\n            this._reloadSource(id);\n        }\n    }\n\n    /**\n     * Re-places symbols on the next frame.\n     * Placement is skipped while its inputs look unchanged, so call this when something\n     * the map cannot see for itself has moved symbols.\n     */\n    triggerSymbolPlacement(): void {\n        this._symbolPlacementTriggered = true;\n    }\n\n    /**\n     * Whether re-running symbol placement could produce a different result than the last run.\n     * Every camera and viewport parameter placement can observe perturbs the model-view-projection\n     * matrix, so comparing the matrix covers them all. Inputs the matrix cannot see arrive as\n     * {@link triggerSymbolPlacement} calls.\n     *\n     * @internal\n     */\n    _placementInputsChanged(transform: IReadonlyTransform, showCollisionBoxes: boolean, crossSourceCollisions: boolean): boolean {\n        const lastPlacement = this.pauseablePlacement;\n        return !lastPlacement ||\n            this._symbolPlacementTriggered ||\n            this._placedProjectionTransition !== this.projection?.transitionState ||\n            lastPlacement._showCollisionBoxes !== showCollisionBoxes ||\n            lastPlacement.placement.collisionGroups.crossSourceCollisions !== crossSourceCollisions ||\n            lastPlacement.placement.transform.renderWorldCopies !== transform.renderWorldCopies ||\n            !mat4.exactEquals(lastPlacement.placement.transform.modelViewProjectionMatrix, transform.modelViewProjectionMatrix);\n    }\n\n    _updatePlacement(transform: IReadonlyTransform, showCollisionBoxes: boolean, fadeDuration: number, crossSourceCollisions: boolean, forceFullPlacement: boolean = false): boolean {\n        let symbolBucketsChanged = false;\n        let placementCommitted = false;\n\n        const layerTiles = {};\n\n        for (const layerID of this._order) {\n            const styleLayer = this._layers[layerID];\n            if (styleLayer.type !== 'symbol') continue;\n\n            if (!layerTiles[styleLayer.source]) {\n                const tileManager = this.tileManagers[styleLayer.source];\n                layerTiles[styleLayer.source] = tileManager.getRenderableIds(true)\n                    .map((id) => tileManager.getTileByID(id))\n                    .sort((a, b) => (b.tileID.overscaledZ - a.tileID.overscaledZ) || (a.tileID.isLessThan(b.tileID) ? -1 : 1));\n            }\n\n            const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.worldCoordinateHelper.wraps ? transform.center.lng : 0);\n            symbolBucketsChanged ||= layerBucketsChanged;\n        }\n        this.crossTileSymbolIndex.pruneUnusedLayers(this._order);\n\n        // Anything that changes our \"in progress\" layer and tile indices requires us\n        // to start over. When we start over, we do a full placement instead of incremental\n        // to prevent starvation.\n        // We need to restart placement to keep layer indices in sync.\n        // Also force full placement when fadeDuration === 0 to ensure that newly loaded\n        // tiles will fully display symbols in their first frame\n        forceFullPlacement ||= this._layerOrderChanged || fadeDuration === 0;\n\n        const placementInputsChanged = symbolBucketsChanged || this._placementInputsChanged(transform, showCollisionBoxes, crossSourceCollisions);\n\n        const placementSettled = this.pauseablePlacement?.isDone() && !this.placement.stillRecent(now(), transform.zoom);\n\n        if (forceFullPlacement || !this.pauseablePlacement || (placementSettled && (placementInputsChanged || this.placement.stale))) {\n            this._symbolPlacementTriggered = false;\n            this._placedProjectionTransition = this.projection?.transitionState;\n            this.pauseablePlacement = new PauseablePlacement(transform, this.map.terrain, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement);\n            this._layerOrderChanged = false;\n        }\n\n        if (this.pauseablePlacement.isDone()) {\n            // the last placement finished running, but the next one hasn’t\n            // started yet because of the `stillRecent` check immediately\n            // above, so mark it stale to ensure that we request another\n            // render frame\n            // if nothing changed, skip this so the map can go idle\n            if (placementInputsChanged) this.placement.setStale();\n        } else {\n            this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles);\n\n            if (this.pauseablePlacement.isDone()) {\n                this.placement = this.pauseablePlacement.commit(now());\n                placementCommitted = true;\n            }\n\n            if (symbolBucketsChanged) {\n                // since the placement gets split over multiple frames it is possible\n                // these buckets were processed before they were changed and so the\n                // placement is already stale while it is in progress\n                this.pauseablePlacement.placement.setStale();\n            }\n        }\n\n        if (placementCommitted || symbolBucketsChanged) {\n            for (const layerID of this._order) {\n                const styleLayer = this._layers[layerID];\n                if (styleLayer.type !== 'symbol') continue;\n                this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]);\n            }\n        }\n\n        // false when we have just finished a placement that didn't change the visibility of any symbols\n        return !this.pauseablePlacement.isDone() || this.placement.hasTransitions(now());\n    }\n\n    _releaseSymbolFadeTiles(): void {\n        for (const id in this.tileManagers) {\n            this.tileManagers[id].releaseSymbolFadeTiles();\n        }\n    }\n\n    // Callbacks from web workers\n\n    async getImages(mapId: string | number, params: GetImagesParameters): Promise<GetImagesResponse> {\n        const images = await this.imageManager.getImages(params.icons);\n\n        // Apply queued image changes before setting the tile's dependencies so that the tile\n        // is not reloaded unnecessarily. Without this forced update the reload could happen in cases\n        // like this one:\n        // - icons contains \"my-image\"\n        // - imageManager.getImages(...) resolves \"my-image\" with a missing-image resolver\n        // - addImage adds \"my-image\" to this._changedImages\n        // - the next frame triggers a reload of this tile even though it already has the latest version\n        this._updateTilesForChangedImages();\n\n        const tileManager = this.tileManagers[params.source];\n        if (tileManager) {\n            tileManager.setDependencies(params.tileID.key, params.type, params.icons);\n        }\n        return images;\n    }\n\n    async getGlyphs(mapId: string | number, params: GetGlyphsParameters): Promise<GlyphMap> {\n        const glyphs = await this.glyphManager.getGlyphs(params.stacks);\n        const tileManager = this.tileManagers[params.source];\n        if (tileManager) {\n            // we are not setting stacks as dependencies since for now\n            // we just need to know which tiles have glyph dependencies\n            tileManager.setDependencies(params.tileID.key, params.type, ['']);\n        }\n        return glyphs;\n    }\n\n    getGlyphsUrl(): string | null {\n        return this.stylesheet.glyphs || null;\n    }\n\n    setGlyphs(glyphsUrl: string | null | undefined, options: StyleSetterOptions = {}): void {\n        this._checkLoaded();\n\n        if (glyphsUrl && this._validate(validateStyle.glyphs, 'glyphs', glyphsUrl, null, options)) {\n            return;\n        }\n\n        this._changed = true;\n        this._glyphsDidChange = true;\n        this.stylesheet.glyphs = glyphsUrl;\n        this.glyphManager.entries = {};\n        this.glyphManager.setURL(glyphsUrl);\n    }\n\n    getFontFaces(): FontFacesSpecification | null {\n        return this.stylesheet['font-faces'] || null;\n    }\n\n    setFontFaces(fontFaces: FontFacesSpecification | null | undefined): void {\n        this._checkLoaded();\n\n        this._changed = true;\n        this._glyphsDidChange = true;\n        this.stylesheet['font-faces'] = fontFaces;\n        this.glyphManager.setFontFaces(fontFaces);\n    }\n\n    async getDashes(mapId: string | number, params: GetDashesParameters): Promise<GetDashesResponse> {\n        const result: GetDashesResponse = {};\n        for (const [key, dash] of Object.entries(params.dashes)) {\n            result[key] = this.lineAtlas.getDash(dash.dasharray, dash.round);\n        }\n        return result;\n    }\n\n    /**\n     * Add a sprite.\n     *\n     * @param id - The id of the desired sprite\n     * @param url - The url to load the desired sprite from\n     * @param options - The style setter options\n     * @param completion - The completion handler\n     */\n    addSprite(id: string, url: string, options: StyleSetterOptions = {}, completion?: (err: Error) => void): void {\n        this._checkLoaded();\n\n        const spriteToAdd = [{id, url}];\n        const updatedSprite = [\n            ...coerceSpriteToArray(this.stylesheet.sprite),\n            ...spriteToAdd\n        ];\n\n        if (this._validate(validateStyle.sprite, 'sprite', updatedSprite, null, options)) return;\n\n        this.stylesheet.sprite = updatedSprite;\n        this._loadSprite(spriteToAdd, true, completion);\n    }\n\n    /**\n     * Remove a sprite by its id. When the last sprite is removed, the whole `this.stylesheet.sprite` object becomes\n     * `undefined`. This falsy `undefined` value later prevents attempts to load the sprite when it's absent.\n     *\n     * @param id - the id of the sprite to remove\n     */\n    removeSprite(id: string): void {\n        this._checkLoaded();\n\n        const internalSpriteRepresentation = coerceSpriteToArray(this.stylesheet.sprite);\n\n        if (!internalSpriteRepresentation.find(sprite => sprite.id === id)) {\n            this.fire(new ErrorEvent(new Error(`Sprite \"${id}\" doesn't exists on this map.`)));\n            return;\n        }\n\n        const changedImages = this.imageManager.removeSpriteImages(id);\n        this._markImagesChanged(changedImages);\n\n        internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex(sprite => sprite.id === id), 1);\n        this.stylesheet.sprite = internalSpriteRepresentation.length > 0 ? internalSpriteRepresentation : undefined;\n\n        this._imagesListDirty = true;\n        this._changed = true;\n        this.fire(new MapStyleDataEvent('data'));\n    }\n\n    /**\n     * Get the current sprite value.\n     *\n     * @returns empty array when no sprite is set; id-url pairs otherwise\n     */\n    getSprite(): Array<{id: string; url: string}> {\n        return coerceSpriteToArray(this.stylesheet.sprite);\n    }\n\n    /**\n     * Set a new value for the style's sprite.\n     *\n     * @param sprite - new sprite value\n     * @param options - style setter options\n     * @param completion - the completion handler\n     */\n    setSprite(sprite: SpriteSpecification, options: StyleSetterOptions = {}, completion?: (err: Error) => void): void {\n        this._checkLoaded();\n\n        if (sprite && this._validate(validateStyle.sprite, 'sprite', sprite, null, options)) {\n            return;\n        }\n\n        this.stylesheet.sprite = sprite;\n\n        if (sprite) {\n            this._loadSprite(sprite, true, completion);\n        } else {\n            this._unloadSprite();\n            if (completion) {\n                completion(null);\n            }\n        }\n    }\n\n    /**\n     * Destroys all internal resources of the style (sources, images, layers, etc.)\n     */\n    destroy(): void {\n        // cancel any pending requests\n        if (this._frameRequest) {\n            this._frameRequest.abort();\n            this._frameRequest = null;\n        }\n        if (this._loadStyleRequest) {\n            this._loadStyleRequest.abort();\n            this._loadStyleRequest = null;\n        }\n        if (this._spriteRequest) {\n            this._spriteRequest.abort();\n            this._spriteRequest = null;\n        }\n\n        // remove sourcecaches\n        for (const id in this.tileManagers) {\n            const tileManager = this.tileManagers[id];\n            tileManager.setEventedParent(null);\n            tileManager.onRemove(this.map);\n        }\n        this.tileManagers = {};\n\n        // Destroy imageManager and clear images\n        if (this.imageManager) {\n            this.imageManager.setEventedParent(null);\n            this.imageManager.destroy();\n            this.patternAtlas.destroy();\n        }\n\n        // Destroy glyphManager\n        if (this.glyphManager) {\n            this.glyphManager.destroy();\n        }\n\n        // Remove layers\n        for (const layerId in this._layers) {\n            const layer = this._layers[layerId];\n            layer.setEventedParent(null);\n            if (layer.onRemove) layer.onRemove(this.map);\n        }\n\n        // reset internal state\n        this._setInitialValues();\n\n        // Remove event listeners\n        this.setEventedParent(null);\n        this.dispatcher.unregisterMessageHandler(MessageType.getGlyphs);\n        this.dispatcher.unregisterMessageHandler(MessageType.getImages);\n        this.dispatcher.unregisterMessageHandler(MessageType.getDashes);\n        this.dispatcher.remove(true);\n        this._listeners = {};\n        this._oneTimeListeners = {};\n    }\n}\n", "import {createLayout, type StructArrayLayout} from '../util/struct_array.ts';\n\nconst rasterBoundsAttributes: StructArrayLayout = createLayout([\n    {name: 'a_pos', type: 'Int16', components: 2},\n    {name: 'a_texture_pos', type: 'Int16', components: 2}\n]);\n\nexport default rasterBoundsAttributes;\n", "\nimport type {StructArray} from '../util/struct_array.ts';\nimport type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type.ts';\nimport type {Context} from './context.ts';\n\n/**\n * @internal\n * an index buffer class\n */\nexport class IndexBuffer {\n    context: Context;\n    buffer: WebGLBuffer;\n    dynamicDraw: boolean;\n\n    constructor(context: Context, array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean) {\n        this.context = context;\n        const gl = context.gl;\n        this.buffer = gl.createBuffer();\n        this.dynamicDraw = Boolean(dynamicDraw);\n\n        // The bound index buffer is part of vertex array object state. We don't want to\n        // modify whatever VAO happens to be currently bound, so make sure the default\n        // vertex array provided by the context is bound instead.\n        this.context.unbindVAO();\n\n        context.bindElementBuffer.set(this.buffer);\n        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);\n\n        if (!this.dynamicDraw) {\n            array.freeBufferAfterUpload();\n        }\n    }\n\n    bind(): void {\n        this.context.bindElementBuffer.set(this.buffer);\n    }\n\n    updateData(array: StructArray): void {\n        const gl = this.context.gl;\n        if (!this.dynamicDraw) throw new Error('Attempted to update data while not in dynamic mode.');\n        // As in the constructor, leave the bound vertex array's element array binding alone; vertex arrays\n        // using this buffer read the new data through their own binding. See https://github.com/mapbox/mapbox-gl-js/issues/5620\n        this.context.unbindVAO();\n        this.bind();\n        gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer);\n    }\n\n    destroy(): void {\n        const gl = this.context.gl;\n        if (this.buffer) {\n            gl.deleteBuffer(this.buffer);\n            delete this.buffer;\n        }\n    }\n}\n", "\nimport type {\n    StructArray,\n    StructArrayMember\n} from '../util/struct_array.ts';\nimport type {Program} from './program.ts';\nimport type {Context} from './context.ts';\n\n/**\n * An Enum for AttributeType\n */\nconst AttributeType = {\n    Int8: 'BYTE',\n    Uint8: 'UNSIGNED_BYTE',\n    Int16: 'SHORT',\n    Uint16: 'UNSIGNED_SHORT',\n    Int32: 'INT',\n    Uint32: 'UNSIGNED_INT',\n    Float32: 'FLOAT'\n};\n\n/**\n * @internal\n * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's\n * Struct type is converted to a WebGL attribute.\n */\nexport class VertexBuffer {\n    length: number;\n    attributes: readonly StructArrayMember[];\n    itemSize: number;\n    dynamicDraw: boolean;\n    context: Context;\n    buffer: WebGLBuffer;\n\n    /**\n     * @param dynamicDraw - Whether this buffer will be repeatedly updated.\n     */\n    constructor(context: Context, array: StructArray, attributes: readonly StructArrayMember[], dynamicDraw?: boolean) {\n        this.length = array.length;\n        this.attributes = attributes;\n        this.itemSize = array.bytesPerElement;\n        this.dynamicDraw = dynamicDraw;\n\n        this.context = context;\n        const gl = context.gl;\n        this.buffer = gl.createBuffer();\n        context.bindVertexBuffer.set(this.buffer);\n        gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);\n\n        if (!this.dynamicDraw) {\n            array.freeBufferAfterUpload();\n        }\n    }\n\n    bind(): void {\n        this.context.bindVertexBuffer.set(this.buffer);\n    }\n\n    updateData(array: StructArray): void {\n        if (array.length !== this.length) throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`);\n        const gl = this.context.gl;\n        this.bind();\n        gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer);\n    }\n\n    enableAttributes(gl: WebGL2RenderingContext, program: Program<any>): void {\n        for (const member of this.attributes) {\n            const attribute = program.attributes[member.name];\n            if (attribute !== undefined) {\n                gl.enableVertexAttribArray(attribute.location);\n            }\n        }\n    }\n\n    /**\n     * Set the attribute pointers in a WebGL context\n     * @param gl - The WebGL context\n     * @param program - The active WebGL program\n     * @param vertexOffset - Index of the starting vertex of the segment\n     */\n    setVertexAttribPointers(gl: WebGL2RenderingContext, program: Program<any>, vertexOffset?: number | null): void {\n        for (const member of this.attributes) {\n            const attribute = program.attributes[member.name];\n\n            if (attribute !== undefined) {\n                const offset = member.offset + (this.itemSize * (vertexOffset || 0));\n                if (attribute.isInteger) {\n                    gl.vertexAttribIPointer(\n                        attribute.location,\n                        member.components,\n                        gl[AttributeType[member.type]],\n                        this.itemSize,\n                        offset\n                    );\n                } else {\n                    gl.vertexAttribPointer(\n                        attribute.location,\n                        member.components,\n                        gl[AttributeType[member.type]],\n                        false,\n                        this.itemSize,\n                        offset\n                    );\n                }\n            }\n        }\n    }\n\n    /**\n     * Destroy the GL buffer bound to the given WebGL context\n     */\n    destroy(): void {\n        const gl = this.context.gl;\n        if (this.buffer) {\n            gl.deleteBuffer(this.buffer);\n            delete this.buffer;\n        }\n    }\n}\n", "import {Color} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {Context} from './context.ts';\nimport type {\n    BlendFuncType,\n    BlendEquationType,\n    ColorMaskType,\n    DepthRangeType,\n    DepthMaskType,\n    StencilFuncType,\n    StencilOpType,\n    DepthFuncType,\n    TextureUnitType,\n    ViewportType,\n    CullFaceModeType,\n    FrontFaceType,\n} from './types.ts';\n\nexport interface IValue<T> {\n    current: T;\n    default: T;\n    dirty: boolean;\n    get(): T;\n    setDefault(): void;\n    set(value: T): void;\n}\n\nclass BaseValue<T> implements IValue<T> {\n    gl: WebGL2RenderingContext;\n    current: T;\n    default: T;\n    dirty: boolean;\n\n    constructor(context: Context) {\n        this.gl = context.gl;\n        this.default = this.getDefault();\n        this.current = this.default;\n        this.dirty = false;\n    }\n\n    get(): T {\n        return this.current;\n    }\n    set(value: T): void { // eslint-disable-line\n        // overridden in child classes;\n    }\n\n    getDefault(): T {\n        return this.default; // overridden in child classes\n    }\n    setDefault(): void {\n        this.set(this.default);\n    }\n}\n\nexport class ClearColor extends BaseValue<Color> {\n    getDefault(): Color {\n        return Color.transparent;\n    }\n    set(v: Color): void {\n        const c = this.current;\n        if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;\n        this.gl.clearColor(v.r, v.g, v.b, v.a);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class ClearDepth extends BaseValue<number> {\n    getDefault(): number {\n        return 1;\n    }\n    set(v: number): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.clearDepth(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class ClearStencil extends BaseValue<number> {\n    getDefault(): number {\n        return 0;\n    }\n    set(v: number): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.clearStencil(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class ColorMask extends BaseValue<ColorMaskType> {\n    getDefault(): ColorMaskType {\n        return [true, true, true, true];\n    }\n    set(v: ColorMaskType): void {\n        const c = this.current;\n        if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;\n        this.gl.colorMask(v[0], v[1], v[2], v[3]);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class DepthMask extends BaseValue<DepthMaskType> {\n    getDefault(): DepthMaskType {\n        return true;\n    }\n    set(v: DepthMaskType): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.depthMask(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class StencilMask extends BaseValue<number> {\n    getDefault(): number {\n        return 0xFF;\n    }\n    set(v: number): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.stencilMask(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class StencilFunc extends BaseValue<StencilFuncType> {\n    getDefault(): StencilFuncType {\n        return {\n            func: this.gl.ALWAYS,\n            ref: 0,\n            mask: 0xFF\n        };\n    }\n    set(v: StencilFuncType): void {\n        const c = this.current;\n        if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) return;\n        this.gl.stencilFunc(v.func, v.ref, v.mask);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class StencilOp extends BaseValue<StencilOpType> {\n    getDefault(): StencilOpType {\n        const gl = this.gl;\n        return [gl.KEEP, gl.KEEP, gl.KEEP];\n    }\n    set(v: StencilOpType): void {\n        const c = this.current;\n        if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) return;\n        this.gl.stencilOp(v[0], v[1], v[2]);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class StencilTest extends BaseValue<boolean> {\n    getDefault(): boolean {\n        return false;\n    }\n    set(v: boolean): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        if (v) {\n            gl.enable(gl.STENCIL_TEST);\n        } else {\n            gl.disable(gl.STENCIL_TEST);\n        }\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class DepthRange extends BaseValue<DepthRangeType> {\n    getDefault(): DepthRangeType {\n        return [0, 1];\n    }\n    set(v: DepthRangeType): void {\n        const c = this.current;\n        if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;\n        this.gl.depthRange(v[0], v[1]);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class DepthTest extends BaseValue<boolean> {\n    getDefault(): boolean {\n        return false;\n    }\n    set(v: boolean): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        if (v) {\n            gl.enable(gl.DEPTH_TEST);\n        } else {\n            gl.disable(gl.DEPTH_TEST);\n        }\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class DepthFunc extends BaseValue<DepthFuncType> {\n    getDefault(): DepthFuncType {\n        return this.gl.LESS;\n    }\n    set(v: DepthFuncType): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.depthFunc(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class Blend extends BaseValue<boolean> {\n    getDefault(): boolean {\n        return false;\n    }\n    set(v: boolean): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        if (v) {\n            gl.enable(gl.BLEND);\n        } else {\n            gl.disable(gl.BLEND);\n        }\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BlendFunc extends BaseValue<BlendFuncType> {\n    getDefault(): BlendFuncType {\n        const gl = this.gl;\n        return [gl.ONE, gl.ZERO];\n    }\n    set(v: BlendFuncType): void {\n        const c = this.current;\n        if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;\n        this.gl.blendFunc(v[0], v[1]);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BlendColor extends BaseValue<Color> {\n    getDefault(): Color {\n        return Color.transparent;\n    }\n    set(v: Color): void {\n        const c = this.current;\n        if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;\n        this.gl.blendColor(v.r, v.g, v.b, v.a);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BlendEquation extends BaseValue<BlendEquationType> {\n    getDefault(): BlendEquationType {\n        return this.gl.FUNC_ADD;\n    }\n    set(v: BlendEquationType): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.blendEquation(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class CullFace extends BaseValue<boolean> {\n    getDefault(): boolean {\n        return false;\n    }\n    set(v: boolean): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        if (v) {\n            gl.enable(gl.CULL_FACE);\n        } else {\n            gl.disable(gl.CULL_FACE);\n        }\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class CullFaceSide extends BaseValue<CullFaceModeType> {\n    getDefault(): CullFaceModeType {\n        return this.gl.BACK;\n    }\n    set(v: CullFaceModeType): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.cullFace(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class FrontFace extends BaseValue<FrontFaceType> {\n    getDefault(): FrontFaceType {\n        return this.gl.CCW;\n    }\n    set(v: FrontFaceType): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.frontFace(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class ProgramValue extends BaseValue<WebGLProgram> {\n    getDefault(): WebGLProgram {\n        return null;\n    }\n    set(v?: WebGLProgram | null): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.useProgram(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class ActiveTextureUnit extends BaseValue<TextureUnitType> {\n    getDefault(): TextureUnitType {\n        return this.gl.TEXTURE0;\n    }\n    set(v: TextureUnitType): void {\n        if (v === this.current && !this.dirty) return;\n        this.gl.activeTexture(v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class Viewport extends BaseValue<ViewportType> {\n    getDefault(): ViewportType {\n        const gl = this.gl;\n        return [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight];\n    }\n    set(v: ViewportType): void {\n        const c = this.current;\n        if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;\n        this.gl.viewport(v[0], v[1], v[2], v[3]);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BindFramebuffer extends BaseValue<WebGLFramebuffer> {\n    getDefault(): WebGLFramebuffer {\n        return null;\n    }\n    set(v?: WebGLFramebuffer | null): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        gl.bindFramebuffer(gl.FRAMEBUFFER, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BindRenderbuffer extends BaseValue<WebGLRenderbuffer> {\n    getDefault(): WebGLRenderbuffer {\n        return null;\n    }\n    set(v?: WebGLRenderbuffer | null): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        gl.bindRenderbuffer(gl.RENDERBUFFER, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BindTexture extends BaseValue<WebGLTexture> {\n    getDefault(): WebGLTexture {\n        return null;\n    }\n    set(v?: WebGLTexture | null): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        gl.bindTexture(gl.TEXTURE_2D, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BindVertexBuffer extends BaseValue<WebGLBuffer> {\n    getDefault(): WebGLBuffer {\n        return null;\n    }\n    set(v?: WebGLBuffer | null): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        gl.bindBuffer(gl.ARRAY_BUFFER, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BindElementBuffer extends BaseValue<WebGLBuffer> {\n    getDefault(): WebGLBuffer {\n        return null;\n    }\n    set(v?: WebGLBuffer | null): void {\n        // Always rebind\n        const gl = this.gl;\n        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class BindVertexArray extends BaseValue<WebGLVertexArrayObject | null> {\n    getDefault(): WebGLVertexArrayObject | null {\n        return null;\n    }\n    set(v: WebGLVertexArrayObject | null): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n\n        gl.bindVertexArray(v);\n\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class PixelStoreUnpack extends BaseValue<number> {\n    getDefault(): number {\n        return 4;\n    }\n    set(v: number): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        gl.pixelStorei(gl.UNPACK_ALIGNMENT, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class PixelStoreUnpackPremultiplyAlpha extends BaseValue<boolean> {\n    getDefault(): boolean {\n        return false;\n    }\n    set(v: boolean): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, ((v)));\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class PixelStoreUnpackFlipY extends BaseValue<boolean> {\n    getDefault(): boolean {\n        return false;\n    }\n    set(v: boolean): void {\n        if (v === this.current && !this.dirty) return;\n        const gl = this.gl;\n        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, ((v)));\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nclass FramebufferAttachment<T> extends BaseValue<T> {\n    parent: WebGLFramebuffer;\n    context: Context;\n\n    constructor(context: Context, parent: WebGLFramebuffer) {\n        super(context);\n        this.context = context;\n        this.parent = parent;\n    }\n    getDefault(): T {\n        return null;\n    }\n}\n\nexport class ColorAttachment extends FramebufferAttachment<WebGLTexture> {\n    setDirty(): void {\n        this.dirty = true;\n    }\n    set(v?: WebGLTexture | null): void {\n        if (v === this.current && !this.dirty) return;\n        this.context.bindFramebuffer.set(this.parent);\n        // note: it's possible to attach a renderbuffer to the color\n        // attachment point, but thus far MBGL only uses textures for color\n        const gl = this.gl;\n        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0);\n\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class DepthAttachment extends FramebufferAttachment<WebGLRenderbuffer> {\n    set(v?: WebGLRenderbuffer | null): void {\n        if (v === this.current && !this.dirty) return;\n        this.context.bindFramebuffer.set(this.parent);\n        // note: it's possible to attach a texture to the depth attachment\n        // point, but thus far MBGL only uses renderbuffers for depth\n        const gl = this.gl;\n        gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n\nexport class DepthStencilAttachment extends FramebufferAttachment<WebGLRenderbuffer> {\n    set(v?: WebGLRenderbuffer | null): void {\n        if (v === this.current && !this.dirty) return;\n        this.context.bindFramebuffer.set(this.parent);\n        // note: it's possible to attach a texture to the depth attachment\n        // point, but thus far MBGL only uses renderbuffers for depth\n        const gl = this.gl;\n        gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, v);\n        this.current = v;\n        this.dirty = false;\n    }\n}\n", "import {ColorAttachment, DepthAttachment, DepthStencilAttachment} from './value.ts';\n\nimport type {Context} from './context.ts';\n\n/**\n * @internal\n * A framebuffer holder object\n */\nexport class Framebuffer {\n    context: Context;\n    width: number;\n    height: number;\n    framebuffer: WebGLFramebuffer;\n    colorAttachment: ColorAttachment;\n    depthAttachment: DepthAttachment;\n\n    constructor(context: Context, width: number, height: number, hasDepth: boolean, hasStencil: boolean) {\n        this.context = context;\n        this.width = width;\n        this.height = height;\n        const gl = context.gl;\n        const fbo = this.framebuffer = gl.createFramebuffer();\n\n        this.colorAttachment = new ColorAttachment(context, fbo);\n        if (hasDepth) {\n            this.depthAttachment = hasStencil ? new DepthStencilAttachment(context, fbo) : new DepthAttachment(context, fbo);\n        } else if (hasStencil) {\n            throw new Error('Stencil cannot be set without depth');\n        }\n    }\n\n    destroy(): void {\n        const gl = this.context.gl;\n\n        const texture = this.colorAttachment.get();\n        if (texture) gl.deleteTexture(texture);\n\n        if (this.depthAttachment) {\n            const renderbuffer = this.depthAttachment.get();\n            if (renderbuffer) gl.deleteRenderbuffer(renderbuffer);\n        }\n\n        gl.deleteFramebuffer(this.framebuffer);\n    }\n}\n", "import type {Context} from './context.ts';\n\nexport const UBO_BINDINGS = {\n    ProjectionUBO: 0,\n    TerrainUBO: 1,\n    FrameUBO: 2,\n};\n\nexport function applyUBOBindings(gl: WebGL2RenderingContext, program: WebGLProgram): void {\n    for (const [name, binding] of Object.entries(UBO_BINDINGS)) {\n        const index = gl.getUniformBlockIndex(program, name);\n        if (index !== gl.INVALID_INDEX) {\n            gl.uniformBlockBinding(program, index, binding);\n        }\n    }\n}\n\nexport type Std140Member = {name: string; type: 'float' | 'int' | 'vec2' | 'vec4' | 'mat4'};\nexport type Std140Layout = {offsets: Record<string, number>; contentWords: number; sizeWords: number};\n\nconst STD140_SIZE_AND_ALIGNMENT_WORDS = {float: [1, 1], int: [1, 1], vec2: [2, 2], vec4: [4, 4], mat4: [16, 4]};\n\nexport function std140Layout(members: readonly Std140Member[]): Std140Layout {\n    const offsets: Record<string, number> = {};\n    let words = 0;\n    for (const {name, type} of members) {\n        const [size, alignment] = STD140_SIZE_AND_ALIGNMENT_WORDS[type];\n        words = Math.ceil(words / alignment) * alignment;\n        offsets[name] = words;\n        words += size;\n    }\n    return {offsets, contentWords: words, sizeWords: Math.ceil(words / 4) * 4};\n}\n\n/**\n * @internal\n * The buffer behind one std140 uniform block, bound to a fixed binding point. Callers write members into\n * `pending` at the layout's offsets and call `upload`, which skips the GPU write when nothing changed. Uploads\n * use `bufferData` because Apple's OpenGL driver stalls a `bufferSubData` into a buffer a pending draw still reads (#8468).\n */\nexport class UniformBuffer {\n    context: Context;\n    buffer: WebGLBuffer;\n    binding: number;\n    contentWords: number;\n    uploaded: Float32Array;\n    pending: Float32Array;\n    uploadedWords: Uint32Array;\n    pendingWords: Uint32Array;\n    hasData: boolean;\n\n    constructor(context: Context, binding: number, layout: Std140Layout) {\n        this.context = context;\n        this.binding = binding;\n        this.contentWords = layout.contentWords;\n        const gl = context.gl;\n        this.buffer = gl.createBuffer();\n        gl.bindBuffer(gl.UNIFORM_BUFFER, this.buffer);\n        gl.bufferData(gl.UNIFORM_BUFFER, layout.sizeWords * 4, gl.DYNAMIC_DRAW);\n        this.uploaded = new Float32Array(layout.sizeWords);\n        this.pending = new Float32Array(layout.sizeWords);\n        this.uploadedWords = new Uint32Array(this.uploaded.buffer);\n        this.pendingWords = new Uint32Array(this.pending.buffer);\n        this.hasData = false;\n    }\n\n    upload(): void {\n        const gl = this.context.gl;\n        let changed = !this.hasData;\n        if (!changed) {\n            const words = this.pendingWords;\n            const uploadedWords = this.uploadedWords;\n            for (let i = 0; i < this.contentWords; i++) {\n                if (words[i] !== uploadedWords[i]) {\n                    changed = true;\n                    break;\n                }\n            }\n        }\n\n        if (!changed) {\n            this.bind();\n            return;\n        }\n\n        gl.bindBufferBase(gl.UNIFORM_BUFFER, this.binding, this.buffer);\n        this.context.boundUniformBuffers[this.binding] = this.buffer;\n        gl.bufferData(gl.UNIFORM_BUFFER, this.pending, gl.DYNAMIC_DRAW);\n        this.uploaded.set(this.pending);\n        this.hasData = true;\n    }\n\n    /** Restores the indexed binding after external rendering without uploading unchanged data. */\n    bind(): void {\n        const boundUniformBuffers = this.context.boundUniformBuffers;\n        if (boundUniformBuffers[this.binding] === this.buffer) return;\n        const gl = this.context.gl;\n        gl.bindBufferBase(gl.UNIFORM_BUFFER, this.binding, this.buffer);\n        boundUniformBuffers[this.binding] = this.buffer;\n    }\n\n    destroy(): void {\n        const gl = this.context.gl;\n        if (this.buffer) {\n            gl.deleteBuffer(this.buffer);\n            delete this.buffer;\n        }\n    }\n}\n", "import {UBO_BINDINGS, UniformBuffer, std140Layout} from './uniform_buffer.ts';\n\nimport type {Context} from './context.ts';\nimport type {ProjectionData, RendererProjectionData} from '../geo/projection/projection_data.ts';\n\nconst layout = std140Layout([\n    {name: 'u_projection_matrix', type: 'mat4'},\n    {name: 'u_projection_fallback_matrix', type: 'mat4'},\n    {name: 'u_projection_tile_mercator_coords', type: 'vec4'},\n    {name: 'u_projection_clipping_plane', type: 'vec4'},\n    {name: 'u_projection_transition', type: 'float'},\n    {name: 'u_projection_clip_antimeridian', type: 'int'},\n]);\n\nconst offsets = layout.offsets;\n\n/**\n * @internal\n * The buffer behind the `ProjectionUBO` block in the shader preludes.\n */\nexport function createProjectionUniformBuffer(context: Context): UniformBuffer {\n    return new UniformBuffer(context, UBO_BINDINGS.ProjectionUBO, layout);\n}\n\nfunction updateProjectionUniformBuffer(buffer: UniformBuffer, projectionData: ProjectionData): void {\n    const f32 = buffer.pending;\n    f32.set(projectionData.mainMatrix, offsets.u_projection_matrix);\n    f32.set(projectionData.fallbackMatrix, offsets.u_projection_fallback_matrix);\n    f32.set(projectionData.tileMercatorCoords, offsets.u_projection_tile_mercator_coords);\n    f32.set(projectionData.clippingPlane, offsets.u_projection_clipping_plane);\n    f32[offsets.u_projection_transition] = projectionData.projectionTransition;\n    buffer.pendingWords[offsets.u_projection_clip_antimeridian] = projectionData.clipAntimeridian ? 1 : 0;\n    buffer.upload();\n}\n\nexport function bindProjectionUniformBuffer(context: Context, projectionData: ProjectionData & Pick<RendererProjectionData, 'uniformBufferKey'>): void {\n    if (!projectionData) {\n        context.projectionUniformBuffer.bind();\n        return;\n    }\n    const key = projectionData.uniformBufferKey;\n    if (key === undefined) {\n        updateProjectionUniformBuffer(context.projectionUniformBuffer, projectionData);\n        return;\n    }\n    const keyedBuffer = context.keyedProjectionUniformBuffers.get(key);\n    if (keyedBuffer) {\n        keyedBuffer.bind();\n        return;\n    }\n    const buffer = context.freeProjectionUniformBuffers.pop() ?? createProjectionUniformBuffer(context);\n    context.keyedProjectionUniformBuffers.set(key, buffer);\n    updateProjectionUniformBuffer(buffer, projectionData);\n}\n\nexport function releaseProjectionUniformBuffers(context: Context): void {\n    context.freeProjectionUniformBuffers.push(...context.keyedProjectionUniformBuffers.values());\n    context.keyedProjectionUniformBuffers.clear();\n}\n\nexport function destroyProjectionUniformBuffers(context: Context): void {\n    context.projectionUniformBuffer.destroy();\n    for (const buffer of context.keyedProjectionUniformBuffers.values()) buffer.destroy();\n    for (const buffer of context.freeProjectionUniformBuffers) buffer.destroy();\n}\n", "import {UBO_BINDINGS, UniformBuffer, std140Layout} from './uniform_buffer.ts';\n\nimport type {Context} from './context.ts';\nimport type {FrameRenderData} from '../render/frame_render_context.ts';\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\n\nconst layout = std140Layout([\n    {name: 'u_units_to_pixels', type: 'vec2'},\n    {name: 'u_world_size', type: 'vec2'},\n    {name: 'u_camera_to_center_distance', type: 'float'},\n    {name: 'u_symbol_fade_change', type: 'float'},\n    {name: 'u_aspect_ratio', type: 'float'},\n    {name: 'u_device_pixel_ratio', type: 'float'},\n    {name: 'u_viewport_size', type: 'vec2'},\n    {name: 'u_pixel_extrude_scale', type: 'vec2'},\n    {name: 'u_pitch', type: 'float'},\n]);\nconst offsets = layout.offsets;\n\n/**\n * @internal\n * The buffer behind the `FrameUBO` block in the shader preludes. `Painter.render` fills it at the start of a frame,\n * and the terrain pass rewrites `u_world_size` around the renders into its textures.\n */\nexport function createFrameUniformBuffer(context: Context): UniformBuffer {\n    return new UniformBuffer(context, UBO_BINDINGS.FrameUBO, layout);\n}\n\nexport function updateFrameUniformBuffer(buffer: UniformBuffer, transform: IReadonlyTransform, data: FrameRenderData): void {\n    const f32 = buffer.pending;\n    const gl = buffer.context.gl;\n    f32[offsets.u_units_to_pixels] = 1 / transform.pixelsToGLUnits[0];\n    f32[offsets.u_units_to_pixels + 1] = 1 / transform.pixelsToGLUnits[1];\n    f32[offsets.u_world_size] = gl.drawingBufferWidth;\n    f32[offsets.u_world_size + 1] = gl.drawingBufferHeight;\n    f32[offsets.u_camera_to_center_distance] = transform.cameraToCenterDistance;\n    f32[offsets.u_symbol_fade_change] = data.fadeDuration ? data.symbolFadeChange : 1;\n    f32[offsets.u_aspect_ratio] = transform.width / transform.height;\n    f32[offsets.u_device_pixel_ratio] = data.pixelRatio;\n    f32[offsets.u_viewport_size] = transform.width;\n    f32[offsets.u_viewport_size + 1] = transform.height;\n    f32[offsets.u_pixel_extrude_scale] = 1 / transform.width;\n    f32[offsets.u_pixel_extrude_scale + 1] = 1 / transform.height;\n    f32[offsets.u_pitch] = transform.pitch / 360 * 2 * Math.PI;\n    buffer.upload();\n}\n\n/**\n * @internal\n * Sets `u_world_size` to the size of the render target about to be drawn into. It is the canvas size,\n * except while layers are drawn into a terrain texture; the fill outline shaders compare it with `gl_FragCoord`.\n */\nexport function setFrameUniformWorldSize(buffer: UniformBuffer, width: number, height: number): void {\n    const f32 = buffer.pending;\n    f32[offsets.u_world_size] = width;\n    f32[offsets.u_world_size + 1] = height;\n    buffer.upload();\n}\n", "import {UBO_BINDINGS, UniformBuffer, std140Layout} from './uniform_buffer.ts';\n\nimport type {Context} from './context.ts';\nimport type {TerrainData} from '../render/terrain.ts';\n\nconst layout = std140Layout([\n    {name: 'u_terrain_matrix', type: 'mat4'},\n    {name: 'u_terrain_unpack', type: 'vec4'},\n    {name: 'u_terrain_dim', type: 'float'},\n    {name: 'u_terrain_exaggeration', type: 'float'},\n]);\n\nconst offsets = layout.offsets;\n\n/**\n * @internal\n * The buffer behind the `TerrainUBO` block in the vertex prelude, written by `Program.draw` for every draw with terrain.\n */\nexport function createTerrainUniformBuffer(context: Context): UniformBuffer {\n    return new UniformBuffer(context, UBO_BINDINGS.TerrainUBO, layout);\n}\n\nexport function updateTerrainUniformBuffer(buffer: UniformBuffer, terrain: TerrainData): void {\n    const f32 = buffer.pending;\n    f32.set(terrain.u_terrain_matrix, offsets.u_terrain_matrix);\n    f32.set(terrain.u_terrain_unpack, offsets.u_terrain_unpack);\n    f32[offsets.u_terrain_dim] = terrain.u_terrain_dim;\n    f32[offsets.u_terrain_exaggeration] = terrain.u_terrain_exaggeration;\n    buffer.upload();\n}\n", "import {Color} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {BlendFuncType, ColorMaskType} from './types.ts';\n\nconst ZERO = 0x0000;\nconst ONE = 0x0001;\nconst ONE_MINUS_SRC_ALPHA = 0x0303;\n\nexport class ColorMode {\n    blendFunction: BlendFuncType;\n    blendColor: Color;\n    mask: ColorMaskType;\n\n    constructor(blendFunction: BlendFuncType, blendColor: Color, mask: ColorMaskType) {\n        this.blendFunction = blendFunction;\n        this.blendColor = blendColor;\n        this.mask = mask;\n    }\n\n    static Replace: BlendFuncType;\n\n    static disabled: Readonly<ColorMode>;\n    static unblended: Readonly<ColorMode>;\n    static alphaBlended: Readonly<ColorMode>;\n}\n\nColorMode.Replace = [ONE, ZERO];\n\nColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [false, false, false, false]);\nColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [true, true, true, true]);\nColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [true, true, true, true]);\n", "import {IndexBuffer} from './index_buffer.ts';\nimport {VertexBuffer} from './vertex_buffer.ts';\nimport {Framebuffer} from './framebuffer.ts';\nimport {createProjectionUniformBuffer, destroyProjectionUniformBuffers} from './projection_uniform_buffer.ts';\nimport {createFrameUniformBuffer} from './frame_uniform_buffer.ts';\nimport {createTerrainUniformBuffer} from './terrain_uniform_buffer.ts';\nimport {ColorMode} from './color_mode.ts';\nimport {deepEqual} from '../util/util.ts';\nimport {ClearColor, ClearDepth, ClearStencil, ColorMask, DepthMask, StencilMask, StencilFunc, StencilOp, StencilTest, DepthRange, DepthTest, DepthFunc, Blend, BlendFunc, BlendColor, BlendEquation, CullFace, CullFaceSide, FrontFace, ProgramValue, ActiveTextureUnit, Viewport, BindFramebuffer, BindRenderbuffer, BindTexture, BindVertexBuffer, BindElementBuffer, BindVertexArray, PixelStoreUnpack, PixelStoreUnpackPremultiplyAlpha, PixelStoreUnpackFlipY} from './value.ts';\n\nimport type {DepthMode} from './depth_mode.ts';\nimport type {StencilMode} from './stencil_mode.ts';\nimport type {CullFaceMode} from './cull_face_mode.ts';\nimport type {UniformBuffer} from './uniform_buffer.ts';\nimport type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type.ts';\nimport type {\n    StructArray,\n    StructArrayMember\n} from '../util/struct_array.ts';\nimport type {Color} from '@maplibre/maplibre-gl-style-spec';\n\ntype ClearArgs = {\n    color?: Color;\n    depth?: number;\n    stencil?: number;\n};\n\n/**\n * @internal\n * A webgl wrapper class to allow injection, mocking and abstraction\n */\nexport class Context {\n    gl: WebGL2RenderingContext;\n\n    currentNumAttributes: number;\n    maxTextureSize: number;\n\n    clearColor: ClearColor;\n    clearDepth: ClearDepth;\n    clearStencil: ClearStencil;\n    colorMask: ColorMask;\n    depthMask: DepthMask;\n    stencilMask: StencilMask;\n    stencilFunc: StencilFunc;\n    stencilOp: StencilOp;\n    stencilTest: StencilTest;\n    depthRange: DepthRange;\n    depthTest: DepthTest;\n    depthFunc: DepthFunc;\n    blend: Blend;\n    blendFunc: BlendFunc;\n    blendColor: BlendColor;\n    blendEquation: BlendEquation;\n    cullFace: CullFace;\n    cullFaceSide: CullFaceSide;\n    frontFace: FrontFace;\n    program: ProgramValue;\n    activeTexture: ActiveTextureUnit;\n    viewport: Viewport;\n    bindFramebuffer: BindFramebuffer;\n    bindRenderbuffer: BindRenderbuffer;\n    bindTexture: BindTexture;\n    bindVertexBuffer: BindVertexBuffer;\n    bindElementBuffer: BindElementBuffer;\n    bindVertexArray: BindVertexArray;\n    pixelStoreUnpack: PixelStoreUnpack;\n    pixelStoreUnpackPremultiplyAlpha: PixelStoreUnpackPremultiplyAlpha;\n    pixelStoreUnpackFlipY: PixelStoreUnpackFlipY;\n    boundUniformBuffers: WebGLBuffer[];\n    projectionUniformBuffer: UniformBuffer;\n    keyedProjectionUniformBuffers: Map<string, UniformBuffer>;\n    freeProjectionUniformBuffers: UniformBuffer[];\n    terrainUniformBuffer: UniformBuffer;\n    frameUniformBuffer: UniformBuffer;\n\n    extTextureFilterAnisotropic: EXT_texture_filter_anisotropic | null;\n    extTextureFilterAnisotropicMax?: GLfloat;\n\n    constructor(gl: WebGL2RenderingContext) {\n        this.gl = gl;\n        this.clearColor = new ClearColor(this);\n        this.clearDepth = new ClearDepth(this);\n        this.clearStencil = new ClearStencil(this);\n        this.colorMask = new ColorMask(this);\n        this.depthMask = new DepthMask(this);\n        this.stencilMask = new StencilMask(this);\n        this.stencilFunc = new StencilFunc(this);\n        this.stencilOp = new StencilOp(this);\n        this.stencilTest = new StencilTest(this);\n        this.depthRange = new DepthRange(this);\n        this.depthTest = new DepthTest(this);\n        this.depthFunc = new DepthFunc(this);\n        this.blend = new Blend(this);\n        this.blendFunc = new BlendFunc(this);\n        this.blendColor = new BlendColor(this);\n        this.blendEquation = new BlendEquation(this);\n        this.cullFace = new CullFace(this);\n        this.cullFaceSide = new CullFaceSide(this);\n        this.frontFace = new FrontFace(this);\n        this.program = new ProgramValue(this);\n        this.activeTexture = new ActiveTextureUnit(this);\n        this.viewport = new Viewport(this);\n        this.bindFramebuffer = new BindFramebuffer(this);\n        this.bindRenderbuffer = new BindRenderbuffer(this);\n        this.bindTexture = new BindTexture(this);\n        this.bindVertexBuffer = new BindVertexBuffer(this);\n        this.bindElementBuffer = new BindElementBuffer(this);\n        this.bindVertexArray = new BindVertexArray(this);\n        this.pixelStoreUnpack = new PixelStoreUnpack(this);\n        this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this);\n        this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this);\n\n        this.extTextureFilterAnisotropic = gl.getExtension('EXT_texture_filter_anisotropic');\n\n        if (this.extTextureFilterAnisotropic) {\n            this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);\n        }\n\n        this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);\n\n        gl.getExtension('EXT_color_buffer_half_float');\n        gl.getExtension('EXT_color_buffer_float');\n\n        this.boundUniformBuffers = [];\n        this.projectionUniformBuffer = createProjectionUniformBuffer(this);\n        this.keyedProjectionUniformBuffers = new Map();\n        this.freeProjectionUniformBuffers = [];\n        this.terrainUniformBuffer = createTerrainUniformBuffer(this);\n        this.frameUniformBuffer = createFrameUniformBuffer(this);\n    }\n\n    /** Destroys the uniform buffers the context created. */\n    destroy(): void {\n        destroyProjectionUniformBuffers(this);\n        this.terrainUniformBuffer.destroy();\n        this.frameUniformBuffer.destroy();\n    }\n\n    setDefault(): void {\n        this.unbindVAO();\n\n        this.clearColor.setDefault();\n        this.clearDepth.setDefault();\n        this.clearStencil.setDefault();\n        this.colorMask.setDefault();\n        this.depthMask.setDefault();\n        this.stencilMask.setDefault();\n        this.stencilFunc.setDefault();\n        this.stencilOp.setDefault();\n        this.stencilTest.setDefault();\n        this.depthRange.setDefault();\n        this.depthTest.setDefault();\n        this.depthFunc.setDefault();\n        this.blend.setDefault();\n        this.blendFunc.setDefault();\n        this.blendColor.setDefault();\n        this.blendEquation.setDefault();\n        this.cullFace.setDefault();\n        this.cullFaceSide.setDefault();\n        this.frontFace.setDefault();\n        this.program.setDefault();\n        this.activeTexture.setDefault();\n        this.bindFramebuffer.setDefault();\n        this.pixelStoreUnpack.setDefault();\n        this.pixelStoreUnpackPremultiplyAlpha.setDefault();\n        this.pixelStoreUnpackFlipY.setDefault();\n    }\n\n    setDirty(): void {\n        this.clearColor.dirty = true;\n        this.clearDepth.dirty = true;\n        this.clearStencil.dirty = true;\n        this.colorMask.dirty = true;\n        this.depthMask.dirty = true;\n        this.stencilMask.dirty = true;\n        this.stencilFunc.dirty = true;\n        this.stencilOp.dirty = true;\n        this.stencilTest.dirty = true;\n        this.depthRange.dirty = true;\n        this.depthTest.dirty = true;\n        this.depthFunc.dirty = true;\n        this.blend.dirty = true;\n        this.blendFunc.dirty = true;\n        this.blendColor.dirty = true;\n        this.blendEquation.dirty = true;\n        this.cullFace.dirty = true;\n        this.cullFaceSide.dirty = true;\n        this.frontFace.dirty = true;\n        this.program.dirty = true;\n        this.activeTexture.dirty = true;\n        this.viewport.dirty = true;\n        this.bindFramebuffer.dirty = true;\n        this.bindRenderbuffer.dirty = true;\n        this.bindTexture.dirty = true;\n        this.bindVertexBuffer.dirty = true;\n        this.bindElementBuffer.dirty = true;\n        this.bindVertexArray.dirty = true;\n        this.pixelStoreUnpack.dirty = true;\n        this.pixelStoreUnpackPremultiplyAlpha.dirty = true;\n        this.pixelStoreUnpackFlipY.dirty = true;\n        this.boundUniformBuffers = [];\n    }\n\n    /**\n     * Reset some GL state to default values before handing users the raw context, as we do for\n     * custom layers and WebGL style images, to avoid hard-to-debug bugs in their code.\n     *\n     * MapLibre restores all of its own state afterwards, so the only state worth resetting first\n     * is state users would be surprised to find dirty: `CULL_FACE`, `TEXTURE0` and the three\n     * `UNPACK_` settings, whose defaults are meaningful enough that most code assumes them.\n     * The vertex array is unbound rather than reset, so that MapLibre never has to track it and\n     * a user's `vertexAttribPointer` calls cannot land on one of ours.\n     */\n    setCustomLayerDefaults(): void {\n        this.unbindVAO();\n\n        this.cullFace.setDefault();\n        this.activeTexture.setDefault();\n        this.pixelStoreUnpack.setDefault();\n        this.pixelStoreUnpackPremultiplyAlpha.setDefault();\n        this.pixelStoreUnpackFlipY.setDefault();\n    }\n\n    createIndexBuffer(array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean): IndexBuffer {\n        return new IndexBuffer(this, array, dynamicDraw);\n    }\n\n    createVertexBuffer(array: StructArray, attributes: readonly StructArrayMember[], dynamicDraw?: boolean): VertexBuffer {\n        return new VertexBuffer(this, array, attributes, dynamicDraw);\n    }\n\n    createRenderbuffer(storageFormat: number, width: number, height: number): WebGLRenderbuffer {\n        const gl = this.gl;\n\n        const rbo = gl.createRenderbuffer();\n        this.bindRenderbuffer.set(rbo);\n        gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height);\n        this.bindRenderbuffer.set(null);\n\n        return rbo;\n    }\n\n    createFramebuffer(width: number, height: number, hasDepth: boolean, hasStencil: boolean): Framebuffer {\n        return new Framebuffer(this, width, height, hasDepth, hasStencil);\n    }\n\n    clear({\n        color,\n        depth,\n        stencil\n    }: ClearArgs): void {\n        const gl = this.gl;\n        let mask = 0;\n\n        if (color) {\n            mask |= gl.COLOR_BUFFER_BIT;\n            this.clearColor.set(color);\n            this.colorMask.set([true, true, true, true]);\n        }\n\n        if (typeof depth !== 'undefined') {\n            mask |= gl.DEPTH_BUFFER_BIT;\n\n            // Workaround for platforms where clearDepth doesn't seem to work\n            // without resetting the depthRange. See https://github.com/mapbox/mapbox-gl-js/issues/3437\n            this.depthRange.set([0, 1]);\n\n            this.clearDepth.set(depth);\n            this.depthMask.set(true);\n        }\n\n        if (typeof stencil !== 'undefined') {\n            mask |= gl.STENCIL_BUFFER_BIT;\n            this.clearStencil.set(stencil);\n            this.stencilMask.set(0xFF);\n        }\n\n        gl.clear(mask);\n    }\n\n    setCullFace(cullFaceMode: Readonly<CullFaceMode>): void {\n        if (cullFaceMode.enable === false) {\n            this.cullFace.set(false);\n        } else {\n            this.cullFace.set(true);\n            this.cullFaceSide.set(cullFaceMode.mode);\n            this.frontFace.set(cullFaceMode.frontFace);\n        }\n    }\n\n    setDepthMode(depthMode: Readonly<DepthMode>): void {\n        if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) {\n            this.depthTest.set(false);\n        } else {\n            this.depthTest.set(true);\n            this.depthFunc.set(depthMode.func);\n            this.depthMask.set(depthMode.mask);\n            this.depthRange.set(depthMode.range);\n        }\n    }\n\n    setStencilMode(stencilMode: Readonly<StencilMode>): void {\n        if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) {\n            this.stencilTest.set(false);\n        } else {\n            this.stencilTest.set(true);\n            this.stencilMask.set(stencilMode.mask);\n            this.stencilOp.set([stencilMode.fail, stencilMode.depthFail, stencilMode.pass]);\n            this.stencilFunc.set({\n                func: stencilMode.test.func,\n                ref: stencilMode.ref,\n                mask: stencilMode.test.mask\n            });\n        }\n    }\n\n    setColorMode(colorMode: Readonly<ColorMode>): void {\n        if (deepEqual(colorMode.blendFunction, ColorMode.Replace)) {\n            this.blend.set(false);\n        } else {\n            this.blend.set(true);\n            this.blendFunc.set(colorMode.blendFunction);\n            this.blendColor.set(colorMode.blendColor);\n        }\n\n        this.colorMask.set(colorMode.mask);\n    }\n\n    createVertexArray(): WebGLVertexArrayObject | undefined {\n        return this.gl.createVertexArray();\n    }\n\n    deleteVertexArray(x: WebGLVertexArrayObject | undefined): void {\n        this.gl.deleteVertexArray(x);\n    }\n\n    unbindVAO(): void {\n        // Unbinding the VAO prevents other things (custom layers, new buffer creation) from\n        // unintentionally changing the state of the last VAO used.\n        this.bindVertexArray.set(null);\n    }\n}\n", "\nimport type {Program} from './program.ts';\nimport type {VertexBuffer} from './vertex_buffer.ts';\nimport type {IndexBuffer} from './index_buffer.ts';\nimport type {Context} from './context.ts';\n\n/**\n * @internal\n * A vertex array object used to pass data to the webgl code\n */\nexport class VertexArrayObject {\n    context: Context;\n    boundProgram: Program<any>;\n    boundLayoutVertexBuffer: VertexBuffer;\n    boundPaintVertexBuffers: VertexBuffer[];\n    boundIndexBuffer: IndexBuffer;\n    boundVertexOffset: number;\n    boundDynamicVertexBuffer: VertexBuffer;\n    boundDynamicVertexBuffer2: VertexBuffer;\n    boundDynamicVertexBuffer3: VertexBuffer;\n    vao: any;\n\n    constructor() {\n        this.boundProgram = null;\n        this.boundLayoutVertexBuffer = null;\n        this.boundPaintVertexBuffers = [];\n        this.boundIndexBuffer = null;\n        this.boundVertexOffset = null;\n        this.boundDynamicVertexBuffer = null;\n        this.vao = null;\n    }\n\n    bind(context: Context,\n        program: Program<any>,\n        layoutVertexBuffer: VertexBuffer,\n        paintVertexBuffers: VertexBuffer[],\n        indexBuffer?: IndexBuffer | null,\n        vertexOffset?: number | null,\n        dynamicVertexBuffer?: VertexBuffer | null,\n        dynamicVertexBuffer2?: VertexBuffer | null,\n        dynamicVertexBuffer3?: VertexBuffer | null): void {\n\n        this.context = context;\n\n        let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length;\n        for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) {\n            if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) {\n                paintBuffersDiffer = true;\n            }\n        }\n\n        const isFreshBindRequired = (\n            !this.vao ||\n            this.boundProgram !== program ||\n            this.boundLayoutVertexBuffer !== layoutVertexBuffer ||\n            paintBuffersDiffer ||\n            this.boundIndexBuffer !== indexBuffer ||\n            this.boundVertexOffset !== vertexOffset ||\n            this.boundDynamicVertexBuffer !== dynamicVertexBuffer ||\n            this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2 ||\n            this.boundDynamicVertexBuffer3 !== dynamicVertexBuffer3\n        );\n\n        if (isFreshBindRequired) {\n            this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3);\n        } else {\n            context.bindVertexArray.set(this.vao);\n        }\n    }\n\n    freshBind(program: Program<any>,\n        layoutVertexBuffer: VertexBuffer,\n        paintVertexBuffers: VertexBuffer[],\n        indexBuffer?: IndexBuffer | null,\n        vertexOffset?: number | null,\n        dynamicVertexBuffer?: VertexBuffer | null,\n        dynamicVertexBuffer2?: VertexBuffer | null,\n        dynamicVertexBuffer3?: VertexBuffer | null): void {\n\n        const numNextAttributes = program.numAttributes;\n\n        const context = this.context;\n        const gl = context.gl;\n\n        if (this.vao) this.destroy();\n        this.vao = context.createVertexArray();\n        context.bindVertexArray.set(this.vao);\n\n        // store the arguments so that we can verify them when the vao is bound again\n        this.boundProgram = program;\n        this.boundLayoutVertexBuffer = layoutVertexBuffer;\n        this.boundPaintVertexBuffers = paintVertexBuffers;\n        this.boundIndexBuffer = indexBuffer;\n        this.boundVertexOffset = vertexOffset;\n        this.boundDynamicVertexBuffer = dynamicVertexBuffer;\n        this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2;\n        this.boundDynamicVertexBuffer3 = dynamicVertexBuffer3;\n\n        layoutVertexBuffer.enableAttributes(gl, program);\n        for (const vertexBuffer of paintVertexBuffers) {\n            vertexBuffer.enableAttributes(gl, program);\n        }\n\n        if (dynamicVertexBuffer) {\n            dynamicVertexBuffer.enableAttributes(gl, program);\n        }\n        if (dynamicVertexBuffer2) {\n            dynamicVertexBuffer2.enableAttributes(gl, program);\n        }\n        if (dynamicVertexBuffer3) {\n            dynamicVertexBuffer3.enableAttributes(gl, program);\n        }\n\n        layoutVertexBuffer.bind();\n        layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n        for (const vertexBuffer of paintVertexBuffers) {\n            vertexBuffer.bind();\n            vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n        }\n\n        if (dynamicVertexBuffer) {\n            dynamicVertexBuffer.bind();\n            dynamicVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n        }\n        if (indexBuffer) {\n            indexBuffer.bind();\n        }\n        if (dynamicVertexBuffer2) {\n            dynamicVertexBuffer2.bind();\n            dynamicVertexBuffer2.setVertexAttribPointers(gl, program, vertexOffset);\n        }\n        if (dynamicVertexBuffer3) {\n            dynamicVertexBuffer3.bind();\n            dynamicVertexBuffer3.setVertexAttribPointers(gl, program, vertexOffset);\n        }\n\n        context.currentNumAttributes = numNextAttributes;\n    }\n\n    destroy(): void {\n        if (this.vao) {\n            this.context.deleteVertexArray(this.vao);\n            this.vao = null;\n        }\n    }\n}\n", "import {\n    Uniform1i,\n    Uniform1f,\n    Uniform4f,\n    UniformMatrix4f,\n    UniformColor\n} from '../uniform_binding.ts';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {calculateFogBlendOpacity} from '../../style/sky.ts';\n\nimport type {SkyPropsPossiblyEvaluated} from '../../style/sky_properties.g.ts';\nimport type {mat4} from 'gl-matrix';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Context} from '../../webgl/context.ts';\n\nexport type TerrainPreludeUniformsType = {\n    'u_depth': Uniform1i;\n    'u_terrain': Uniform1i;\n};\n\nexport type TerrainUniformsType = {\n    'u_texture': Uniform1i;\n    'u_ele_delta': Uniform1f;\n    'u_fog_matrix': UniformMatrix4f;\n    'u_fog_color': UniformColor;\n    'u_fog_ground_blend': Uniform1f;\n    'u_fog_ground_blend_opacity': Uniform1f;\n    'u_horizon_color': UniformColor;\n    'u_horizon_fog_blend': Uniform1f;\n    'u_is_globe_mode': Uniform1f;\n};\n\nexport type TerrainDepthUniformsType = {\n    'u_ele_delta': Uniform1f;\n};\n\nexport type TerrainHeightUniformsType = {\n    'u_tile_bounds': Uniform4f;\n};\n\nconst terrainPreludeUniforms = (context: Context, locations: UniformLocations): TerrainPreludeUniformsType => ({\n    'u_depth': new Uniform1i(context, locations.u_depth),\n    'u_terrain': new Uniform1i(context, locations.u_terrain)\n});\n\nconst terrainUniforms = (context: Context, locations: UniformLocations): TerrainUniformsType => ({\n    'u_texture': new Uniform1i(context, locations.u_texture),\n    'u_ele_delta': new Uniform1f(context, locations.u_ele_delta),\n    'u_fog_matrix': new UniformMatrix4f(context, locations.u_fog_matrix),\n    'u_fog_color': new UniformColor(context, locations.u_fog_color),\n    'u_fog_ground_blend': new Uniform1f(context, locations.u_fog_ground_blend),\n    'u_fog_ground_blend_opacity': new Uniform1f(context, locations.u_fog_ground_blend_opacity),\n    'u_horizon_color': new UniformColor(context, locations.u_horizon_color),\n    'u_horizon_fog_blend': new Uniform1f(context, locations.u_horizon_fog_blend),\n    'u_is_globe_mode': new Uniform1f(context, locations.u_is_globe_mode)\n});\n\nconst terrainDepthUniforms = (context: Context, locations: UniformLocations): TerrainDepthUniformsType => ({\n    'u_ele_delta': new Uniform1f(context, locations.u_ele_delta)\n});\n\nconst terrainHeightUniforms = (context: Context, locations: UniformLocations): TerrainHeightUniformsType => ({\n    'u_tile_bounds': new Uniform4f(context, locations.u_tile_bounds)\n});\n\nconst terrainUniformValues = (\n    eleDelta: number,\n    fogMatrix: mat4,\n    sky: Readonly<SkyPropsPossiblyEvaluated> | undefined,\n    pitch: number,\n    isGlobeMode: boolean): UniformValues<TerrainUniformsType> => ({\n    'u_texture': 0,\n    'u_ele_delta': eleDelta,\n    'u_fog_matrix': fogMatrix,\n    'u_fog_color': sky ? sky['fog-color'] : Color.white,\n    'u_fog_ground_blend': sky ? sky['fog-ground-blend'] : 1,\n    // Set opacity to 0 when in globe mode to disable fog\n    'u_fog_ground_blend_opacity': isGlobeMode ? 0 : (sky ? calculateFogBlendOpacity(pitch) : 0),\n    'u_horizon_color': sky ? sky['horizon-color'] : Color.white,\n    'u_horizon_fog_blend': sky ? sky['horizon-fog-blend'] : 1,\n    'u_is_globe_mode': isGlobeMode ? 1 : 0\n});\n\nconst terrainDepthUniformValues = (\n    eleDelta: number\n): UniformValues<TerrainDepthUniformsType> => ({\n    'u_ele_delta': eleDelta\n});\n\n/**\n * @param tileBounds - the tile's west and north edge and its width and height, as fractions of the height map\n */\nconst terrainHeightUniformValues = (\n    tileBounds: [number, number, number, number]\n): UniformValues<TerrainHeightUniformsType> => ({\n    'u_tile_bounds': tileBounds\n});\n\nexport {terrainUniforms, terrainDepthUniforms, terrainHeightUniforms, terrainPreludeUniforms, terrainUniformValues, terrainDepthUniformValues, terrainHeightUniformValues};\n", "import {type PreparedShader, shaders} from '../shaders/shaders.ts';\nimport {VertexArrayObject} from './vertex_array_object.ts';\nimport {terrainPreludeUniforms, type TerrainPreludeUniformsType} from './program/terrain_program.ts';\nimport {applyUBOBindings} from './uniform_buffer.ts';\nimport {bindProjectionUniformBuffer} from './projection_uniform_buffer.ts';\nimport {updateTerrainUniformBuffer} from './terrain_uniform_buffer.ts';\n\nimport type {ProgramConfiguration} from '../data/program_configuration.ts';\nimport type {Context} from './context.ts';\nimport type {SegmentVector} from '../data/segment.ts';\nimport type {VertexBuffer} from './vertex_buffer.ts';\nimport type {IndexBuffer} from './index_buffer.ts';\nimport type {DepthMode} from './depth_mode.ts';\nimport type {StencilMode} from './stencil_mode.ts';\nimport type {ColorMode} from './color_mode.ts';\nimport type {CullFaceMode} from './cull_face_mode.ts';\nimport type {UniformBindings, UniformValues, UniformLocations} from './uniform_binding.ts';\nimport type {BinderUniform} from '../data/program_configuration.ts';\nimport type {TerrainData} from '../render/terrain.ts';\nimport type {ProjectionData} from '../geo/projection/projection_data.ts';\n\nexport type DrawMode = WebGLRenderingContextBase['LINES'] | WebGLRenderingContextBase['TRIANGLES'] | WebGL2RenderingContext['LINE_STRIP'];\n\nfunction getTokenizedAttributesAndUniforms(array: string[]): string[] {\n    const result = [];\n\n    for (const entry of array) {\n        if (entry === null) continue;\n        const token = entry.split(' ');\n        result.push(token.pop());\n    }\n    return result;\n}\n\nfunction getIntegerAttributeNames(gl: WebGL2RenderingContext, program: WebGLProgram): Set<string> {\n    const integerTypes = new Set<number>([\n        gl.INT, gl.INT_VEC2, gl.INT_VEC3, gl.INT_VEC4,\n        gl.UNSIGNED_INT, gl.UNSIGNED_INT_VEC2, gl.UNSIGNED_INT_VEC3, gl.UNSIGNED_INT_VEC4\n    ]);\n    const names = new Set<string>();\n    const numActiveAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);\n    for (let i = 0; i < numActiveAttributes; i++) {\n        const attribute = gl.getActiveAttrib(program, i);\n        if (attribute && integerTypes.has(attribute.type)) {\n            names.add(attribute.name);\n        }\n    }\n    return names;\n}\n\nexport type ProgramAttribute = {\n    location: number;\n    isInteger: boolean;\n};\n\n/**\n * @internal\n * A webgl program to execute in the GPU space\n */\nexport class Program<Us extends UniformBindings> {\n    program: WebGLProgram;\n    attributes: {[_: string]: ProgramAttribute};\n    numAttributes: number;\n    fixedUniforms: Us;\n    terrainUniforms: TerrainPreludeUniformsType;\n    binderUniforms: BinderUniform[];\n    failedToCreate: boolean;\n\n    constructor(context: Context,\n        source: PreparedShader,\n        configuration: ProgramConfiguration,\n        fixedUniforms: (b: Context, a: UniformLocations) => Us,\n        showOverdrawInspector: boolean,\n        useTerrain: boolean,\n        projectionPrelude: PreparedShader,\n        projectionDefine: string,\n        extraDefines: string[] = []) {\n\n        const gl = context.gl;\n        this.program = gl.createProgram();\n\n        const staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes);\n        const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : [];\n        const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo);\n\n        const preludeUniformsInfo = shaders.prelude.staticUniforms ? getTokenizedAttributesAndUniforms(shaders.prelude.staticUniforms) : [];\n        const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : [];\n        const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : [];\n        // remove duplicate uniforms\n        const uniformList = preludeUniformsInfo.concat(staticUniformsInfo).concat(dynamicUniformsInfo);\n        const allUniformsInfo = [];\n        for (const uniform of uniformList) {\n            if (!allUniformsInfo.includes(uniform)) allUniformsInfo.push(uniform);\n        }\n\n        const defines = configuration ? configuration.defines() : [];\n        defines.unshift('#version 300 es');\n        if (showOverdrawInspector) {\n            defines.push('#define OVERDRAW_INSPECTOR;');\n        }\n        if (useTerrain) {\n            defines.push('#define TERRAIN3D;');\n        }\n        if (projectionDefine) {\n            defines.push(projectionDefine);\n        }\n        if (extraDefines) {\n            defines.push(...extraDefines);\n        }\n\n        const fragmentSource = defines.concat(shaders.prelude.fragmentSource, projectionPrelude.fragmentSource, source.fragmentSource).join('\\n');\n        const vertexSource = defines.concat(shaders.prelude.vertexSource, projectionPrelude.vertexSource, source.vertexSource).join('\\n');\n\n        const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n        if (gl.isContextLost()) {\n            this.failedToCreate = true;\n            return;\n        }\n        gl.shaderSource(fragmentShader, fragmentSource);\n        gl.compileShader(fragmentShader);\n        gl.attachShader(this.program, fragmentShader);\n\n        const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n        if (gl.isContextLost()) {\n            this.failedToCreate = true;\n            return;\n        }\n        gl.shaderSource(vertexShader, vertexSource);\n        gl.compileShader(vertexShader);\n        gl.attachShader(this.program, vertexShader);\n\n        this.attributes = {};\n        const uniformLocations = {};\n\n        this.numAttributes = allAttrInfo.length;\n\n        // Link before reading any status so the driver can overlap both compiles; the shaders are\n        // only asked how they compiled when the link failed, to name the one at fault.\n        gl.linkProgram(this.program);\n\n        if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {\n            // A dead GPU process answers every query with 0 until isContextLost() turns true, so a\n            // failed link with zero attached shaders means the driver died, not the shaders (#8607).\n            if (gl.isContextLost() || gl.getProgramParameter(this.program, gl.ATTACHED_SHADERS) === 0) {\n                this.failedToCreate = true;\n                return;\n            }\n            if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {\n                throw new Error(`Could not compile fragment shader: ${gl.getShaderInfoLog(fragmentShader)}`);\n            }\n            if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {\n                throw new Error(`Could not compile vertex shader: ${gl.getShaderInfoLog(vertexShader)}`);\n            }\n            throw new Error(`Program failed to link: ${gl.getProgramInfoLog(this.program)}`);\n        }\n\n        applyUBOBindings(gl, this.program);\n\n        const integerAttributeNames = getIntegerAttributeNames(gl, this.program);\n        for (const name of allAttrInfo) {\n            if (!name) continue;\n            const location = gl.getAttribLocation(this.program, name);\n            if (location >= 0) {\n                this.attributes[name] = {location, isInteger: integerAttributeNames.has(name)};\n            }\n        }\n\n        gl.deleteShader(vertexShader);\n        gl.deleteShader(fragmentShader);\n\n        for (const uniform of allUniformsInfo) {\n            if (uniform && !uniformLocations[uniform]) {\n                const uniformLocation = gl.getUniformLocation(this.program, uniform);\n                if (uniformLocation) {\n                    uniformLocations[uniform] = uniformLocation;\n                }\n            }\n        }\n\n        this.fixedUniforms = fixedUniforms(context, uniformLocations);\n        this.terrainUniforms = terrainPreludeUniforms(context, uniformLocations);\n        this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : [];\n    }\n\n    draw(context: Context,\n        drawMode: DrawMode,\n        depthMode: Readonly<DepthMode>,\n        stencilMode: Readonly<StencilMode>,\n        colorMode: Readonly<ColorMode>,\n        cullFaceMode: Readonly<CullFaceMode>,\n        uniformValues: UniformValues<Us>,\n        terrain: TerrainData,\n        projectionData: ProjectionData,\n        layerID: string,\n        layoutVertexBuffer: VertexBuffer,\n        indexBuffer: IndexBuffer,\n        segments: SegmentVector,\n        currentProperties?: any,\n        zoom?: number | null,\n        configuration?: ProgramConfiguration | null,\n        dynamicLayoutBuffer?: VertexBuffer | null,\n        dynamicLayoutBuffer2?: VertexBuffer | null,\n        dynamicLayoutBuffer3?: VertexBuffer | null): void {\n\n        const gl = context.gl;\n\n        if (this.failedToCreate) return;\n\n        context.program.set(this.program);\n        context.terrainUniformBuffer.bind();\n        context.frameUniformBuffer.bind();\n        context.setDepthMode(depthMode);\n        context.setStencilMode(stencilMode);\n        context.setColorMode(colorMode);\n        context.setCullFace(cullFaceMode);\n\n        // set variables used by the 3d functions defined in _prelude.vertex.glsl\n        if (terrain) {\n            context.activeTexture.set(gl.TEXTURE2);\n            gl.bindTexture(gl.TEXTURE_2D, terrain.depthTexture);\n            context.activeTexture.set(gl.TEXTURE3);\n            gl.bindTexture(gl.TEXTURE_2D, terrain.texture);\n            for (const name in this.terrainUniforms) {\n                this.terrainUniforms[name].set(terrain[name]);\n            }\n            updateTerrainUniformBuffer(context.terrainUniformBuffer, terrain);\n        }\n\n        bindProjectionUniformBuffer(context, projectionData);\n\n        if (uniformValues) {\n            for (const name in this.fixedUniforms) {\n                this.fixedUniforms[name].set(uniformValues[name]);\n            }\n        }\n\n        if (configuration) {\n            configuration.setUniforms(context, this.binderUniforms, currentProperties, {zoom});\n        }\n\n        let primitiveSize = 0;\n        switch (drawMode) {\n            case gl.LINES:\n                primitiveSize = 2;\n                break;\n            case gl.TRIANGLES:\n                primitiveSize = 3;\n                break;\n            case gl.LINE_STRIP:\n                primitiveSize = 1;\n                break;\n        }\n\n        for (const segment of segments.get()) {\n            segment.vaos ||= {};\n            segment.vaos[layerID] ||= new VertexArrayObject();\n            segment.vaos[layerID].bind(\n                context,\n                this,\n                layoutVertexBuffer,\n                configuration ? configuration.getPaintVertexBuffers() : [],\n                indexBuffer,\n                segment.vertexOffset,\n                dynamicLayoutBuffer,\n                dynamicLayoutBuffer2,\n                dynamicLayoutBuffer3\n            );\n\n            gl.drawElements(\n                drawMode,\n                segment.primitiveLength * primitiveSize,\n                gl.UNSIGNED_SHORT,\n                segment.primitiveOffset * primitiveSize * 2);\n        }\n    }\n}\n", "import {pixelsToTileUnits} from '../../source/pixels_to_tile_units.ts';\n\nimport type {\n    Uniform1i,\n    Uniform1f,\n    Uniform2f,\n    Uniform3f\n} from '../uniform_binding.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {PatternAtlas} from '../../render/pattern_atlas.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\nimport type {CrossFaded} from '../../style/properties.ts';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters.ts';\nimport type {UniformValues} from '../uniform_binding.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\n\ntype BackgroundPatternUniformsType = {\n    'u_image': Uniform1i;\n    'u_pattern_tl_a': Uniform2f;\n    'u_pattern_br_a': Uniform2f;\n    'u_pattern_tl_b': Uniform2f;\n    'u_pattern_br_b': Uniform2f;\n    'u_texsize': Uniform2f;\n    'u_mix': Uniform1f;\n    'u_pattern_size_a': Uniform2f;\n    'u_pattern_size_b': Uniform2f;\n    'u_scale_a': Uniform1f;\n    'u_scale_b': Uniform1f;\n    'u_pixel_coord_upper': Uniform2f;\n    'u_pixel_coord_lower': Uniform2f;\n    'u_tile_units_to_pixels': Uniform1f;\n};\n\nexport type PatternUniformsType = {\n    // pattern uniforms:\n    'u_image': Uniform1i;\n    'u_texsize': Uniform2f;\n    'u_scale': Uniform3f;\n    'u_fade': Uniform1f;\n    'u_pixel_coord_upper': Uniform2f;\n    'u_pixel_coord_lower': Uniform2f;\n};\n\nfunction patternUniformValues(crossfade: CrossfadeParameters, transform: IReadonlyTransform, tile: Tile): UniformValues<PatternUniformsType> {\n\n    const tileRatio = 1 / pixelsToTileUnits(tile, 1, transform.tileZoom);\n\n    const numTiles = Math.pow(2, tile.tileID.overscaledZ);\n    const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, transform.tileZoom) / numTiles;\n\n    const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);\n    const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;\n\n    return {\n        'u_image': 0,\n        'u_texsize': tile.imageAtlasTexture.size,\n        'u_scale': [tileRatio, crossfade.fromScale, crossfade.toScale],\n        'u_fade': crossfade.t,\n        // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.\n        'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16],\n        'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF]\n    };\n}\n\nfunction bgPatternUniformValues(\n    image: CrossFaded<ResolvedImage>,\n    crossfade: CrossfadeParameters,\n    patternAtlas: PatternAtlas,\n    transform: IReadonlyTransform,\n    tile: {\n        tileID: OverscaledTileID;\n        tileSize: number;\n    }\n): UniformValues<BackgroundPatternUniformsType> {\n    const imagePosA = patternAtlas.getPattern(image.from.toString());\n    const imagePosB = patternAtlas.getPattern(image.to.toString());\n    const {width, height} = patternAtlas.getPixelSize();\n\n    const numTiles = Math.pow(2, tile.tileID.overscaledZ);\n    const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, transform.tileZoom) / numTiles;\n\n    const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);\n    const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;\n\n    return {\n        'u_image': 0,\n        'u_pattern_tl_a': (imagePosA as any).tl,\n        'u_pattern_br_a': (imagePosA as any).br,\n        'u_pattern_tl_b': (imagePosB as any).tl,\n        'u_pattern_br_b': (imagePosB as any).br,\n        'u_texsize': [width, height],\n        'u_mix': crossfade.t,\n        'u_pattern_size_a': (imagePosA as any).displaySize,\n        'u_pattern_size_b': (imagePosB as any).displaySize,\n        'u_scale_a': crossfade.fromScale,\n        'u_scale_b': crossfade.toScale,\n        'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, transform.tileZoom),\n        // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.\n        'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16],\n        'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF]\n    };\n}\nexport {bgPatternUniformValues, patternUniformValues};\n", "import {patternUniformValues} from './pattern.ts';\nimport {\n    Uniform1i,\n    Uniform1f,\n    Uniform2f,\n    Uniform3f\n} from '../uniform_binding.ts';\nimport {mat3, vec3} from 'gl-matrix';\nimport {extend, sphericalToCartesian} from '../../util/util.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {LightPropsPossiblyEvaluated} from '../../style/light_properties.g.ts';\n\nexport type FillExtrusionUniformsType = {\n    'u_lightpos': Uniform3f;\n    'u_lightpos_globe': Uniform3f;\n    'u_lightintensity': Uniform1f;\n    'u_lightcolor': Uniform3f;\n    'u_vertical_gradient': Uniform1f;\n    'u_opacity': Uniform1f;\n    'u_fill_translate': Uniform2f;\n};\n\nexport type FillExtrusionPatternUniformsType = {\n    'u_lightpos': Uniform3f;\n    'u_lightpos_globe': Uniform3f;\n    'u_lightintensity': Uniform1f;\n    'u_lightcolor': Uniform3f;\n    'u_height_factor': Uniform1f;\n    'u_vertical_gradient': Uniform1f;\n    'u_opacity': Uniform1f;\n    'u_fill_translate': Uniform2f;\n    // pattern uniforms:\n    'u_texsize': Uniform2f;\n    'u_image': Uniform1i;\n    'u_pixel_coord_upper': Uniform2f;\n    'u_pixel_coord_lower': Uniform2f;\n    'u_scale': Uniform3f;\n    'u_fade': Uniform1f;\n};\n\nconst fillExtrusionUniforms = (context: Context, locations: UniformLocations): FillExtrusionUniformsType => ({\n    'u_lightpos': new Uniform3f(context, locations.u_lightpos),\n    'u_lightpos_globe': new Uniform3f(context, locations.u_lightpos_globe),\n    'u_lightintensity': new Uniform1f(context, locations.u_lightintensity),\n    'u_lightcolor': new Uniform3f(context, locations.u_lightcolor),\n    'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient),\n    'u_opacity': new Uniform1f(context, locations.u_opacity),\n    'u_fill_translate': new Uniform2f(context, locations.u_fill_translate),\n});\n\nconst fillExtrusionPatternUniforms = (context: Context, locations: UniformLocations): FillExtrusionPatternUniformsType => ({\n    'u_lightpos': new Uniform3f(context, locations.u_lightpos),\n    'u_lightpos_globe': new Uniform3f(context, locations.u_lightpos_globe),\n    'u_lightintensity': new Uniform1f(context, locations.u_lightintensity),\n    'u_lightcolor': new Uniform3f(context, locations.u_lightcolor),\n    'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient),\n    'u_height_factor': new Uniform1f(context, locations.u_height_factor),\n    'u_opacity': new Uniform1f(context, locations.u_opacity),\n    'u_fill_translate': new Uniform2f(context, locations.u_fill_translate),\n    // pattern uniforms\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n    'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n    'u_scale': new Uniform3f(context, locations.u_scale),\n    'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst fillExtrusionUniformValues = (\n    transform: IReadonlyTransform,\n    light: Readonly<LightPropsPossiblyEvaluated>,\n    shouldUseVerticalGradient: boolean,\n    opacity: number,\n    translate: [number, number],\n): UniformValues<FillExtrusionUniformsType> => {\n    const lightPos = sphericalToCartesian(light.position);\n    const lightMat = mat3.create();\n    if (light.anchor === 'viewport') {\n        mat3.fromRotation(lightMat, transform.bearingInRadians);\n    }\n    vec3.transformMat3(lightPos, lightPos, lightMat);\n    const transformedLightPos = transform.transformLightDirection(lightPos);\n\n    const lightColor = light.color;\n\n    return {\n        'u_lightpos': lightPos,\n        'u_lightpos_globe': transformedLightPos,\n        'u_lightintensity': light.intensity,\n        'u_lightcolor': [lightColor.r, lightColor.g, lightColor.b],\n        'u_vertical_gradient': +shouldUseVerticalGradient,\n        'u_opacity': opacity,\n        'u_fill_translate': translate,\n    };\n};\n\nconst fillExtrusionPatternUniformValues = (\n    transform: IReadonlyTransform,\n    light: Readonly<LightPropsPossiblyEvaluated>,\n    shouldUseVerticalGradient: boolean,\n    opacity: number,\n    translate: [number, number],\n    coord: OverscaledTileID,\n    crossfade: CrossfadeParameters,\n    tile: Tile\n): UniformValues<FillExtrusionPatternUniformsType> => {\n    return extend(fillExtrusionUniformValues(transform, light, shouldUseVerticalGradient, opacity, translate),\n        patternUniformValues(crossfade, transform, tile),\n        {\n            'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8\n        });\n};\n\nexport {\n    fillExtrusionUniforms,\n    fillExtrusionPatternUniforms,\n    fillExtrusionUniformValues,\n    fillExtrusionPatternUniformValues\n};\n", "import {patternUniformValues} from './pattern.ts';\nimport {\n    Uniform1i,\n    Uniform1f,\n    Uniform2f,\n    Uniform3f,\n} from '../uniform_binding.ts';\nimport {extend} from '../../util/util.ts';\n\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters.ts';\nimport type {Tile} from '../../tile/tile.ts';\n\nexport type FillUniformsType = {\n    'u_fill_translate': Uniform2f;\n};\n\nexport type FillOutlineUniformsType = {\n    'u_fill_translate': Uniform2f;\n};\n\nexport type FillPatternUniformsType = {\n    // pattern uniforms:\n    'u_texsize': Uniform2f;\n    'u_image': Uniform1i;\n    'u_pixel_coord_upper': Uniform2f;\n    'u_pixel_coord_lower': Uniform2f;\n    'u_scale': Uniform3f;\n    'u_fade': Uniform1f;\n    'u_sdf_pattern': Uniform1i;\n    'u_fill_translate': Uniform2f;\n};\n\nexport type FillOutlinePatternUniformsType = {\n    // pattern uniforms:\n    'u_texsize': Uniform2f;\n    'u_image': Uniform1i;\n    'u_pixel_coord_upper': Uniform2f;\n    'u_pixel_coord_lower': Uniform2f;\n    'u_scale': Uniform3f;\n    'u_fade': Uniform1f;\n    'u_sdf_pattern': Uniform1i;\n    'u_fill_translate': Uniform2f;\n};\n\nconst fillUniforms = (context: Context, locations: UniformLocations): FillUniformsType => ({\n    'u_fill_translate': new Uniform2f(context, locations.u_fill_translate)\n});\n\nconst fillPatternUniforms = (context: Context, locations: UniformLocations): FillPatternUniformsType => ({\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n    'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n    'u_scale': new Uniform3f(context, locations.u_scale),\n    'u_fade': new Uniform1f(context, locations.u_fade),\n    'u_sdf_pattern': new Uniform1i(context, locations.u_sdf_pattern),\n    'u_fill_translate': new Uniform2f(context, locations.u_fill_translate)\n});\n\nconst fillOutlineUniforms = (context: Context, locations: UniformLocations): FillOutlineUniformsType => ({\n    'u_fill_translate': new Uniform2f(context, locations.u_fill_translate)\n});\n\nconst fillOutlinePatternUniforms = (context: Context, locations: UniformLocations): FillOutlinePatternUniformsType => ({\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n    'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n    'u_scale': new Uniform3f(context, locations.u_scale),\n    'u_fade': new Uniform1f(context, locations.u_fade),\n    'u_sdf_pattern': new Uniform1i(context, locations.u_sdf_pattern),\n    'u_fill_translate': new Uniform2f(context, locations.u_fill_translate)\n});\n\nconst fillPatternUniformValues = (\n    transform: IReadonlyTransform,\n    crossfade: CrossfadeParameters,\n    tile: Tile,\n    translate: [number, number],\n    isSdfPattern: boolean\n): UniformValues<FillPatternUniformsType> => extend(\n    patternUniformValues(crossfade, transform, tile),\n    {\n        'u_fill_translate': translate,\n        'u_sdf_pattern': isSdfPattern ? 1 : 0,\n    }\n);\n\nconst fillUniformValues = (translate: [number, number]): UniformValues<FillUniformsType> => ({\n    'u_fill_translate': translate,\n});\n\nconst fillOutlineUniformValues = (translate: [number, number]): UniformValues<FillOutlineUniformsType> => ({\n    'u_fill_translate': translate,\n});\n\nconst fillOutlinePatternUniformValues = (\n    transform: IReadonlyTransform,\n    crossfade: CrossfadeParameters,\n    tile: Tile,\n    translate: [number, number],\n    isSdfPattern: boolean\n): UniformValues<FillOutlinePatternUniformsType> => fillPatternUniformValues(transform, crossfade, tile, translate, isSdfPattern);\n\nexport {\n    fillUniforms,\n    fillPatternUniforms,\n    fillOutlineUniforms,\n    fillOutlinePatternUniforms,\n    fillUniformValues,\n    fillPatternUniformValues,\n    fillOutlineUniformValues,\n    fillOutlinePatternUniformValues\n};\n", "import {Uniform1i, Uniform1f, Uniform2f} from '../uniform_binding.ts';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units.ts';\nimport {EXTENT} from '../../data/extent.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {CircleStyleLayer} from '../../style/style_layer/circle_style_layer.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\n\nexport type CircleUniformsType = {\n    'u_scale_with_map': Uniform1i;\n    'u_pitch_with_map': Uniform1i;\n    'u_extrude_scale': Uniform2f;\n    'u_globe_extrude_scale': Uniform1f;\n    'u_translate': Uniform2f;\n};\n\nconst circleUniforms = (context: Context, locations: UniformLocations): CircleUniformsType => ({\n    'u_scale_with_map': new Uniform1i(context, locations.u_scale_with_map),\n    'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n    'u_extrude_scale': new Uniform2f(context, locations.u_extrude_scale),\n    'u_globe_extrude_scale': new Uniform1f(context, locations.u_globe_extrude_scale),\n    'u_translate': new Uniform2f(context, locations.u_translate),\n});\n\nconst circleUniformValues = (\n    transform: IReadonlyTransform,\n    tile: Tile,\n    layer: CircleStyleLayer,\n    translate: [number, number],\n    radiusCorrectionFactor: number\n): UniformValues<CircleUniformsType> => {\n    let pitchWithMap: boolean, extrudeScale: [number, number];\n    let globeExtrudeScale: number = 0;\n    if (layer.paint.get('circle-pitch-alignment') === 'map') {\n        const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);\n        pitchWithMap = true;\n        extrudeScale = [pixelRatio, pixelRatio];\n\n        // For globe rendering we need to know how much to extrude the circle as an *angle*.\n        // The calculation: (one pixel in tile units) / (earth circumference in tile units) * (2PI radians) * radiusCorrectionFactor\n        globeExtrudeScale = pixelRatio / (EXTENT * Math.pow(2, tile.tileID.overscaledZ)) * 2.0 * Math.PI * radiusCorrectionFactor;\n    } else {\n        pitchWithMap = false;\n        extrudeScale = transform.pixelsToGLUnits;\n    }\n\n    return {\n        'u_scale_with_map': +(layer.paint.get('circle-pitch-scale') === 'map'),\n        'u_pitch_with_map': +(pitchWithMap),\n        'u_extrude_scale': extrudeScale,\n        'u_globe_extrude_scale': globeExtrudeScale,\n        'u_translate': translate,\n    };\n};\n\nexport {circleUniforms, circleUniformValues};\n", "import {UniformColor, Uniform1i, Uniform1f} from '../uniform_binding.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Color} from '@maplibre/maplibre-gl-style-spec';\n\nexport type DebugUniformsType = {\n    'u_color': UniformColor;\n    'u_overlay': Uniform1i;\n    'u_overlay_scale': Uniform1f;\n};\n\nconst debugUniforms = (context: Context, locations: UniformLocations): DebugUniformsType => ({\n    'u_color': new UniformColor(context, locations.u_color),\n    'u_overlay': new Uniform1i(context, locations.u_overlay),\n    'u_overlay_scale': new Uniform1f(context, locations.u_overlay_scale)\n});\n\nconst debugUniformValues = (color: Color, scaleRatio: number = 1): UniformValues<DebugUniformsType> => ({\n    'u_color': color,\n    'u_overlay': 0,\n    'u_overlay_scale': scaleRatio\n});\n\nexport {debugUniforms, debugUniformValues};\n", "import {mat4} from 'gl-matrix';\nimport {\n    Uniform1i,\n    Uniform1f,\n    UniformMatrix4f\n} from '../uniform_binding.ts';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units.ts';\nimport {EXTENT} from '../../data/extent.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {HeatmapStyleLayer} from '../../style/style_layer/heatmap_style_layer.ts';\n\nexport type HeatmapUniformsType = {\n    'u_extrude_scale': Uniform1f;\n    'u_intensity': Uniform1f;\n    'u_globe_extrude_scale': Uniform1f;\n};\n\nexport type HeatmapTextureUniformsType = {\n    'u_matrix': UniformMatrix4f;\n    'u_image': Uniform1i;\n    'u_color_ramp': Uniform1i;\n    'u_opacity': Uniform1f;\n};\n\nconst heatmapUniforms = (context: Context, locations: UniformLocations): HeatmapUniformsType => ({\n    'u_extrude_scale': new Uniform1f(context, locations.u_extrude_scale),\n    'u_intensity': new Uniform1f(context, locations.u_intensity),\n    'u_globe_extrude_scale': new Uniform1f(context, locations.u_globe_extrude_scale)\n});\n\nconst heatmapTextureUniforms = (context: Context, locations: UniformLocations): HeatmapTextureUniformsType => ({\n    'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_color_ramp': new Uniform1i(context, locations.u_color_ramp),\n    'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst heatmapUniformValues = (tile: Tile, zoom: number, intensity: number, radiusCorrectionFactor: number): UniformValues<HeatmapUniformsType> => {\n    const pixelRatio = pixelsToTileUnits(tile, 1, zoom);\n    // See comment in circle_program.ts\n    const globeExtrudeScale = pixelRatio / (EXTENT * Math.pow(2, tile.tileID.overscaledZ)) * 2.0 * Math.PI * radiusCorrectionFactor;\n    return {\n        'u_extrude_scale': pixelsToTileUnits(tile, 1, zoom),\n        'u_intensity': intensity,\n        'u_globe_extrude_scale': globeExtrudeScale\n    };\n};\n\nconst heatmapTextureUniformValues = (\n    painter: Painter,\n    layer: HeatmapStyleLayer,\n    textureUnit: number,\n    colorRampUnit: number\n): UniformValues<HeatmapTextureUniformsType> => {\n    const matrix = mat4.create();\n    mat4.ortho(matrix, 0, painter.width, painter.height, 0, 0, 1);\n\n    return {\n        'u_matrix': matrix,\n        'u_image': textureUnit,\n        'u_color_ramp': colorRampUnit,\n        'u_opacity': layer.paint.get('heatmap-opacity')\n    };\n};\n\nexport {\n    heatmapUniforms,\n    heatmapTextureUniforms,\n    heatmapUniformValues,\n    heatmapTextureUniformValues\n};\n", "import {mat4} from 'gl-matrix';\nimport {\n    Uniform1i,\n    Uniform1f,\n    Uniform2f,\n    UniformColor,\n    UniformFloatArray,\n    UniformColorArray,\n    UniformMatrix4f,\n    Uniform4f\n} from '../uniform_binding.ts';\nimport {EXTENT} from '../../data/extent.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {HillshadeStyleLayer} from '../../style/style_layer/hillshade_style_layer.ts';\nimport type {DEMData} from '../../data/dem_data.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport type HillshadeUniformsType = {\n    'u_image': Uniform1i;\n    'u_latrange': Uniform2f;\n    'u_exaggeration': Uniform1f;\n    'u_altitudes': UniformFloatArray;\n    'u_azimuths': UniformFloatArray;\n    'u_accent': UniformColor;\n    'u_method': Uniform1i;\n    'u_shadows': UniformColorArray;\n    'u_highlights': UniformColorArray;\n};\n\nexport type HillshadePrepareUniformsType = {\n    'u_matrix': UniformMatrix4f;\n    'u_image': Uniform1i;\n    'u_dimension': Uniform2f;\n    'u_zoom': Uniform1f;\n    'u_unpack': Uniform4f;\n    'u_log2_world_width': Uniform1f;\n};\n\nconst hillshadeUniforms = (context: Context, locations: UniformLocations): HillshadeUniformsType => ({\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_latrange': new Uniform2f(context, locations.u_latrange),\n    'u_exaggeration': new Uniform1f(context, locations.u_exaggeration),\n    'u_altitudes': new UniformFloatArray(context, locations.u_altitudes),\n    'u_azimuths': new UniformFloatArray(context, locations.u_azimuths),\n    'u_accent': new UniformColor(context, locations.u_accent),\n    'u_method': new Uniform1i(context, locations.u_method),\n    'u_shadows': new UniformColorArray(context, locations.u_shadows),\n    'u_highlights': new UniformColorArray(context, locations.u_highlights)\n});\n\nconst hillshadePrepareUniforms = (context: Context, locations: UniformLocations): HillshadePrepareUniformsType => ({\n    'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_dimension': new Uniform2f(context, locations.u_dimension),\n    'u_zoom': new Uniform1f(context, locations.u_zoom),\n    'u_unpack': new Uniform4f(context, locations.u_unpack),\n    'u_log2_world_width': new Uniform1f(context, locations.u_log2_world_width)\n});\n\nconst hillshadeUniformValues = (\n    transform: IReadonlyTransform,\n    tile: Tile,\n    layer: HillshadeStyleLayer,\n): UniformValues<HillshadeUniformsType> => {\n    const accent = layer.paint.get('hillshade-accent-color');\n    let method;\n    switch (layer.paint.get('hillshade-method')) {\n        case 'basic':\n            method = 4;\n            break;\n        case 'combined':\n            method = 1;\n            break;\n        case 'igor':\n            method = 2;\n            break;\n        case 'multidirectional':\n            method = 3;\n            break;\n        case 'standard':\n        default:\n            method = 0;\n            break;\n    }\n\n    const illumination = layer.getIlluminationProperties();\n\n    for (let i = 0; i < illumination.directionRadians.length; i++) {\n        // modify azimuthal angle by map rotation if light is anchored at the viewport\n        if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') {\n            illumination.directionRadians[i] += transform.bearingInRadians;\n        }\n    }\n    return {\n        'u_image': 0,\n        'u_latrange': getTileLatRange(transform, tile.tileID),\n        'u_exaggeration': layer.paint.get('hillshade-exaggeration'),\n        'u_altitudes': illumination.altitudeRadians,\n        'u_azimuths': illumination.directionRadians,\n        'u_accent': accent,\n        'u_method': method,\n        'u_highlights': illumination.highlightColor,\n        'u_shadows': illumination.shadowColor\n    };\n};\n\nconst hillshadeUniformPrepareValues = (transform: IReadonlyTransform, tileID: OverscaledTileID, dem: DEMData): UniformValues<HillshadePrepareUniformsType> => {\n\n    const stride = dem.stride;\n    const matrix = mat4.create();\n    // Flip rendering at y axis.\n    mat4.ortho(matrix, 0, EXTENT, -EXTENT, 0, 0, 1);\n    mat4.translate(matrix, matrix, [0, -EXTENT, 0]);\n\n    return {\n        'u_matrix': matrix,\n        'u_image': 1,\n        'u_dimension': [stride, stride],\n        'u_zoom': tileID.overscaledZ,\n        'u_unpack': dem.getUnpackVector(),\n        'u_log2_world_width': getLog2WorldWidth(transform)\n    };\n};\n\n/**\n * The log2 of the zoom 0 world's width in meters, from which the prepare shader gets the meters per DEM pixel that\n * it divides elevation differences by. A registered CRS's world is its zoom 0 extent wide, in CRS units taken as\n * meters. Mercator keeps 25.2562, which with the shader's 3 for the 8 in its slope kernel is the 28.2562 the shader\n * used before, so its hillshade does not change.\n */\nfunction getLog2WorldWidth(transform: IReadonlyTransform): number {\n    const worldCoordinateHelper = transform.worldCoordinateHelper;\n    return worldCoordinateHelper.wraps ? 25.2562 : Math.log2(worldCoordinateHelper.metersPerWorldUnit(0.5, 0.5));\n}\n\n/**\n * The latitudes of the tile's top and bottom edges, which the hillshade shader uses to correct the mercator\n * scale distortion of slopes (it scales by `cos(lat)`). Only the wrapping, cylindrical mercator plane stretches\n * with latitude; any other plane is rendered in its own units and gets `[0, 0]`: `cos(0)` is 1 and the shader\n * applies no correction.\n */\nfunction getTileLatRange(transform: IReadonlyTransform, tileID: OverscaledTileID): [number, number] {\n    const worldCoordinateHelper = transform.worldCoordinateHelper;\n    if (!worldCoordinateHelper.wraps) return [0, 0];\n    // for scaling the magnitude of a points slope by its latitude\n    const tilesAtZoom = Math.pow(2, tileID.canonical.z);\n    const y = tileID.canonical.y;\n    return [\n        worldCoordinateHelper.lngLatFromWorld(0, y / tilesAtZoom).lat,\n        worldCoordinateHelper.lngLatFromWorld(0, (y + 1) / tilesAtZoom).lat];\n}\n\nexport {\n    hillshadeUniforms,\n    hillshadePrepareUniforms,\n    hillshadeUniformValues,\n    hillshadeUniformPrepareValues\n};\n", "import {\n    Uniform1i,\n    Uniform1f,\n    Uniform2f,\n    Uniform4f\n} from '../uniform_binding.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {ColorReliefStyleLayer} from '../../style/style_layer/color_relief_style_layer.ts';\nimport type {DEMData} from '../../data/dem_data.ts';\n\nexport type ColorReliefUniformsType = {\n    'u_image': Uniform1i;\n    'u_unpack': Uniform4f;\n    'u_dimension': Uniform2f;\n    'u_elevation_stops': Uniform1i;\n    'u_color_stops': Uniform1i;\n    'u_color_ramp_size': Uniform1i;\n    'u_opacity': Uniform1f;\n};\n\nconst colorReliefUniforms = (context: Context, locations: UniformLocations): ColorReliefUniformsType => ({\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_unpack': new Uniform4f(context, locations.u_unpack),\n    'u_dimension': new Uniform2f(context, locations.u_dimension),\n    'u_elevation_stops': new Uniform1i(context, locations.u_elevation_stops),\n    'u_color_stops': new Uniform1i(context, locations.u_color_stops),\n    'u_color_ramp_size': new Uniform1i(context, locations.u_color_ramp_size),\n    'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst colorReliefUniformValues = (\n    layer: ColorReliefStyleLayer,\n    dem: DEMData,\n    colorRampSize: number = 0\n): UniformValues<ColorReliefUniformsType> => {\n\n    return {\n        'u_image': 0,\n        'u_unpack': dem.getUnpackVector(),\n        'u_dimension': [dem.stride, dem.stride],\n        'u_elevation_stops': 1,\n        'u_color_stops': 4,\n        'u_color_ramp_size': colorRampSize,\n        'u_opacity': layer.paint.get('color-relief-opacity')\n    };\n};\n\nexport {\n    colorReliefUniforms,\n    colorReliefUniformValues,\n};\n", "import {Uniform1i, Uniform1f, Uniform2f, Uniform3f} from '../uniform_binding.ts';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units.ts';\nimport {extend, translatePosition} from '../../util/util.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer.ts';\nimport type {LineAtlas} from '../../render/line_atlas.ts';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters.ts';\n\nexport type LineUniformsType = {\n    'u_translation': Uniform2f;\n    'u_ratio': Uniform1f;\n};\n\nexport type LineGradientUniformsType = {\n    'u_translation': Uniform2f;\n    'u_ratio': Uniform1f;\n    'u_image': Uniform1i;\n    'u_image_height': Uniform1f;\n};\n\nexport type LinePatternUniformsType = {\n    'u_translation': Uniform2f;\n    'u_texsize': Uniform2f;\n    'u_ratio': Uniform1f;\n    'u_image': Uniform1i;\n    'u_scale': Uniform3f;\n    'u_fade': Uniform1f;\n};\n\nexport type LineSDFUniformsType = {\n    'u_translation': Uniform2f;\n    'u_ratio': Uniform1f;\n    'u_tileratio': Uniform1f;\n    'u_crossfade_from': Uniform1f;\n    'u_crossfade_to': Uniform1f;\n    'u_image': Uniform1i;\n    'u_mix': Uniform1f;\n    'u_lineatlas_width': Uniform1f;\n    'u_lineatlas_height': Uniform1f;\n};\n\nexport type LineGradientSDFUniformsType = {\n    'u_translation': Uniform2f;\n    'u_ratio': Uniform1f;\n    'u_image': Uniform1i;\n    'u_image_height': Uniform1f;\n    'u_tileratio': Uniform1f;\n    'u_crossfade_from': Uniform1f;\n    'u_crossfade_to': Uniform1f;\n    'u_image_dash': Uniform1i;\n    'u_mix': Uniform1f;\n    'u_lineatlas_width': Uniform1f;\n    'u_lineatlas_height': Uniform1f;\n};\n\nconst lineUniforms = (context: Context, locations: UniformLocations): LineUniformsType => ({\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_ratio': new Uniform1f(context, locations.u_ratio),\n});\n\nconst lineGradientUniforms = (context: Context, locations: UniformLocations): LineGradientUniformsType => ({\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_ratio': new Uniform1f(context, locations.u_ratio),\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_image_height': new Uniform1f(context, locations.u_image_height)\n});\n\nconst linePatternUniforms = (context: Context, locations: UniformLocations): LinePatternUniformsType => ({\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_ratio': new Uniform1f(context, locations.u_ratio),\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_scale': new Uniform3f(context, locations.u_scale),\n    'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst lineSDFUniforms = (context: Context, locations: UniformLocations): LineSDFUniformsType => ({\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_ratio': new Uniform1f(context, locations.u_ratio),\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_mix': new Uniform1f(context, locations.u_mix),\n    'u_tileratio': new Uniform1f(context, locations.u_tileratio),\n    'u_crossfade_from': new Uniform1f(context, locations.u_crossfade_from),\n    'u_crossfade_to': new Uniform1f(context, locations.u_crossfade_to),\n    'u_lineatlas_width': new Uniform1f(context, locations.u_lineatlas_width),\n    'u_lineatlas_height': new Uniform1f(context, locations.u_lineatlas_height)\n});\n\nconst lineGradientSDFUniforms = (context: Context, locations: UniformLocations): LineGradientSDFUniformsType => ({\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_ratio': new Uniform1f(context, locations.u_ratio),\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_image_height': new Uniform1f(context, locations.u_image_height),\n    'u_tileratio': new Uniform1f(context, locations.u_tileratio),\n    'u_crossfade_from': new Uniform1f(context, locations.u_crossfade_from),\n    'u_crossfade_to': new Uniform1f(context, locations.u_crossfade_to),\n    'u_image_dash': new Uniform1i(context, locations.u_image_dash),\n    'u_mix': new Uniform1f(context, locations.u_mix),\n    'u_lineatlas_width': new Uniform1f(context, locations.u_lineatlas_width),\n    'u_lineatlas_height': new Uniform1f(context, locations.u_lineatlas_height)\n});\n\nconst lineUniformValues = (\n    transform: IReadonlyTransform,\n    tile: Tile,\n    layer: LineStyleLayer,\n    ratioScale: number,\n): UniformValues<LineUniformsType> => {\n    return {\n        'u_translation': calculateTranslation(transform, tile, layer),\n        'u_ratio': ratioScale / pixelsToTileUnits(tile, 1, transform.zoom),\n    };\n};\n\nconst lineGradientUniformValues = (\n    transform: IReadonlyTransform,\n    tile: Tile,\n    layer: LineStyleLayer,\n    ratioScale: number,\n    imageHeight: number,\n): UniformValues<LineGradientUniformsType> => {\n    return extend(lineUniformValues(transform, tile, layer, ratioScale), {\n        'u_image': 0,\n        'u_image_height': imageHeight,\n    });\n};\n\nconst linePatternUniformValues = (\n    transform: IReadonlyTransform,\n    tile: Tile,\n    layer: LineStyleLayer,\n    ratioScale: number,\n    crossfade: CrossfadeParameters,\n): UniformValues<LinePatternUniformsType> => {\n    const tileZoomRatio = calculateTileRatio(tile, transform);\n    return {\n        'u_translation': calculateTranslation(transform, tile, layer),\n        'u_texsize': tile.imageAtlasTexture.size,\n        // camera zoom ratio\n        'u_ratio': ratioScale / pixelsToTileUnits(tile, 1, transform.zoom),\n        'u_image': 0,\n        'u_scale': [tileZoomRatio, crossfade.fromScale, crossfade.toScale],\n        'u_fade': crossfade.t,\n    };\n};\n\nconst lineSDFUniformValues = (\n    transform: IReadonlyTransform,\n    lineAtlas: LineAtlas,\n    tile: Tile,\n    layer: LineStyleLayer,\n    ratioScale: number,\n    crossfade: CrossfadeParameters,\n): UniformValues<LineSDFUniformsType> => {\n    const tileRatio = calculateTileRatio(tile, transform);\n\n    return extend(lineUniformValues(transform, tile, layer, ratioScale), {\n        'u_tileratio': tileRatio,\n        'u_crossfade_from': crossfade.fromScale,\n        'u_crossfade_to': crossfade.toScale,\n        'u_image': 0,\n        'u_mix': crossfade.t,\n        'u_lineatlas_width': lineAtlas.width,\n        'u_lineatlas_height': lineAtlas.height,\n    });\n};\n\nconst lineGradientSDFUniformValues = (\n    transform: IReadonlyTransform,\n    lineAtlas: LineAtlas,\n    tile: Tile,\n    layer: LineStyleLayer,\n    ratioScale: number,\n    crossfade: CrossfadeParameters,\n    imageHeight: number,\n): UniformValues<LineGradientSDFUniformsType> => {\n    const tileRatio = calculateTileRatio(tile, transform);\n\n    return extend(lineUniformValues(transform, tile, layer, ratioScale), {\n        'u_image': 0,\n        'u_image_height': imageHeight,\n        'u_tileratio': tileRatio,\n        'u_crossfade_from': crossfade.fromScale,\n        'u_crossfade_to': crossfade.toScale,\n        'u_image_dash': 1,\n        'u_mix': crossfade.t,\n        'u_lineatlas_width': lineAtlas.width,\n        'u_lineatlas_height': lineAtlas.height,\n    });\n};\n\nfunction calculateTileRatio(tile: Tile, transform: IReadonlyTransform) {\n    return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom);\n}\n\nfunction calculateTranslation(transform: IReadonlyTransform, tile: Tile, layer: LineStyleLayer): [number, number] {\n    // Translate line points prior to any transformation\n    return translatePosition(\n        transform,\n        tile,\n        layer.paint.get('line-translate'),\n        layer.paint.get('line-translate-anchor')\n    );\n}\n\nexport {\n    lineUniforms,\n    lineGradientUniforms,\n    linePatternUniforms,\n    lineSDFUniforms,\n    lineGradientSDFUniforms,\n    lineUniformValues,\n    lineGradientUniformValues,\n    linePatternUniformValues,\n    lineSDFUniformValues,\n    lineGradientSDFUniformValues\n};\n", "import {Uniform1i, Uniform1f} from '../uniform_binding.ts';\n\nimport type {Context} from '../../webgl/context.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\n\nexport type LayerOpacityUniformsType = {\n    'u_image': Uniform1i;\n    'u_opacity': Uniform1f;\n};\n\nexport const layerOpacityUniforms = (context: Context, locations: UniformLocations): LayerOpacityUniformsType => ({\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nexport const layerOpacityUniformValues = (\n    opacity: number,\n    textureUnit: number\n): UniformValues<LayerOpacityUniformsType> => ({\n    'u_image': textureUnit,\n    'u_opacity': opacity\n});\n", "import {Uniform1i, Uniform1f, Uniform2f, UniformMatrix4f} from '../uniform_binding.ts';\nimport {extend} from '../../util/util.ts';\n\nimport type {mat4} from 'gl-matrix';\nimport type {Context} from '../../webgl/context.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\n\nexport type SymbolIconUniformsType = {\n    'u_is_size_zoom_constant': Uniform1i;\n    'u_is_size_feature_constant': Uniform1i;\n    'u_size_t': Uniform1f;\n    'u_size': Uniform1f;\n    'u_rotate_symbol': Uniform1i;\n    'u_label_plane_matrix': UniformMatrix4f;\n    'u_coord_matrix': UniformMatrix4f;\n    'u_is_text': Uniform1i;\n    'u_pitch_with_map': Uniform1i;\n    'u_is_along_line': Uniform1i;\n    'u_is_variable_anchor': Uniform1i;\n    'u_texsize': Uniform2f;\n    'u_texture': Uniform1i;\n    'u_translation': Uniform2f;\n    'u_pitched_scale': Uniform1f;\n    'u_is_offset': Uniform1i;\n    'u_height_anchor_ground': Uniform1i;\n};\n\nexport type SymbolSDFUniformsType = {\n    'u_is_size_zoom_constant': Uniform1i;\n    'u_is_size_feature_constant': Uniform1i;\n    'u_size_t': Uniform1f;\n    'u_size': Uniform1f;\n    'u_rotate_symbol': Uniform1i;\n    'u_label_plane_matrix': UniformMatrix4f;\n    'u_coord_matrix': UniformMatrix4f;\n    'u_is_text': Uniform1i;\n    'u_pitch_with_map': Uniform1i;\n    'u_is_along_line': Uniform1i;\n    'u_is_variable_anchor': Uniform1i;\n    'u_texsize': Uniform2f;\n    'u_texture': Uniform1i;\n    'u_gamma_scale': Uniform1f;\n    'u_is_halo': Uniform1i;\n    'u_is_plain': Uniform1i;\n    'u_translation': Uniform2f;\n    'u_pitched_scale': Uniform1f;\n    'u_is_offset': Uniform1i;\n    'u_height_anchor_ground': Uniform1i;\n};\n\nexport type symbolTextAndIconUniformsType = {\n    'u_is_size_zoom_constant': Uniform1i;\n    'u_is_size_feature_constant': Uniform1i;\n    'u_size_t': Uniform1f;\n    'u_size': Uniform1f;\n    'u_rotate_symbol': Uniform1i;\n    'u_label_plane_matrix': UniformMatrix4f;\n    'u_coord_matrix': UniformMatrix4f;\n    'u_is_text': Uniform1i;\n    'u_pitch_with_map': Uniform1i;\n    'u_is_along_line': Uniform1i;\n    'u_is_variable_anchor': Uniform1i;\n    'u_texsize': Uniform2f;\n    'u_texsize_icon': Uniform2f;\n    'u_texture': Uniform1i;\n    'u_texture_icon': Uniform1i;\n    'u_gamma_scale': Uniform1f;\n    'u_is_halo': Uniform1i;\n    'u_translation': Uniform2f;\n    'u_pitched_scale': Uniform1f;\n    'u_is_offset': Uniform1i;\n    'u_height_anchor_ground': Uniform1i;\n};\n\nconst symbolIconUniforms = (context: Context, locations: UniformLocations): SymbolIconUniformsType => ({\n    'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n    'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n    'u_size_t': new Uniform1f(context, locations.u_size_t),\n    'u_size': new Uniform1f(context, locations.u_size),\n    'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n    'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n    'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n    'u_is_text': new Uniform1i(context, locations.u_is_text),\n    'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n    'u_is_along_line': new Uniform1i(context, locations.u_is_along_line),\n    'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_texture': new Uniform1i(context, locations.u_texture),\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale),\n    'u_is_offset': new Uniform1i(context, locations.u_is_offset),\n    'u_height_anchor_ground': new Uniform1i(context, locations.u_height_anchor_ground),\n});\n\nconst symbolSDFUniforms = (context: Context, locations: UniformLocations): SymbolSDFUniformsType => ({\n    'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n    'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n    'u_size_t': new Uniform1f(context, locations.u_size_t),\n    'u_size': new Uniform1f(context, locations.u_size),\n    'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n    'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n    'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n    'u_is_text': new Uniform1i(context, locations.u_is_text),\n    'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n    'u_is_along_line': new Uniform1i(context, locations.u_is_along_line),\n    'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_texture': new Uniform1i(context, locations.u_texture),\n    'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale),\n    'u_is_halo': new Uniform1i(context, locations.u_is_halo),\n    'u_is_plain': new Uniform1i(context, locations.u_is_plain),\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale),\n    'u_is_offset': new Uniform1i(context, locations.u_is_offset),\n    'u_height_anchor_ground': new Uniform1i(context, locations.u_height_anchor_ground),\n});\n\nconst symbolTextAndIconUniforms = (context: Context, locations: UniformLocations): symbolTextAndIconUniformsType => ({\n    'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n    'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n    'u_size_t': new Uniform1f(context, locations.u_size_t),\n    'u_size': new Uniform1f(context, locations.u_size),\n    'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n    'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n    'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n    'u_is_text': new Uniform1i(context, locations.u_is_text),\n    'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n    'u_is_along_line': new Uniform1i(context, locations.u_is_along_line),\n    'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_texsize_icon': new Uniform2f(context, locations.u_texsize_icon),\n    'u_texture': new Uniform1i(context, locations.u_texture),\n    'u_texture_icon': new Uniform1i(context, locations.u_texture_icon),\n    'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale),\n    'u_is_halo': new Uniform1i(context, locations.u_is_halo),\n    'u_translation': new Uniform2f(context, locations.u_translation),\n    'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale),\n    'u_is_offset': new Uniform1i(context, locations.u_is_offset),\n    'u_height_anchor_ground': new Uniform1i(context, locations.u_height_anchor_ground),\n});\n\nconst symbolIconUniformValues = (\n    functionType: string,\n    size: {\n        uSizeT: number;\n        uSize: number;\n    },\n    rotateInShader: boolean,\n    pitchWithMap: boolean,\n    isAlongLine: boolean,\n    isVariableAnchor: boolean,\n    labelPlaneMatrix: mat4,\n    glCoordMatrix: mat4,\n    translation: [number, number],\n    isText: boolean,\n    texSize: [number, number],\n    pitchedScale: number,\n    isOffset: boolean,\n    heightAnchorGround: boolean\n): UniformValues<SymbolIconUniformsType> => {\n    return {\n        'u_is_size_zoom_constant': +(functionType === 'constant' || functionType === 'source'),\n        'u_is_size_feature_constant': +(functionType === 'constant' || functionType === 'camera'),\n        'u_size_t': size ? size.uSizeT : 0,\n        'u_size': size ? size.uSize : 0,\n        'u_rotate_symbol': +rotateInShader,\n        'u_label_plane_matrix': labelPlaneMatrix,\n        'u_coord_matrix': glCoordMatrix,\n        'u_is_text': +isText,\n        'u_pitch_with_map': +pitchWithMap,\n        'u_is_along_line': isAlongLine,\n        'u_is_variable_anchor': isVariableAnchor,\n        'u_texsize': texSize,\n        'u_texture': 0,\n        'u_translation': translation,\n        'u_pitched_scale': pitchedScale,\n        'u_is_offset': isOffset,\n        'u_height_anchor_ground': +heightAnchorGround,\n    };\n};\n\nconst symbolSDFUniformValues = (\n    functionType: string,\n    size: {\n        uSizeT: number;\n        uSize: number;\n    },\n    rotateInShader: boolean,\n    pitchWithMap: boolean,\n    isAlongLine: boolean,\n    isVariableAnchor: boolean,\n    transform: IReadonlyTransform,\n    labelPlaneMatrix: mat4,\n    glCoordMatrix: mat4,\n    translation: [number, number],\n    isText: boolean,\n    texSize: [number, number],\n    isHalo: boolean,\n    pitchedScale: number,\n    isOffset: boolean,\n    heightAnchorGround: boolean\n): UniformValues<SymbolSDFUniformsType> => {\n    return extend(symbolIconUniformValues(functionType, size,\n        rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, labelPlaneMatrix,\n        glCoordMatrix, translation, isText, texSize, pitchedScale, isOffset, heightAnchorGround), {\n        'u_gamma_scale': (pitchWithMap ? Math.cos(transform.pitch * Math.PI / 180.0) * transform.cameraToCenterDistance : 1),\n        'u_is_halo': isHalo ? 1 : 0,\n        'u_is_plain': 1\n    });\n};\n\nconst symbolTextAndIconUniformValues = (\n    functionType: string,\n    size: {\n        uSizeT: number;\n        uSize: number;\n    },\n    rotateInShader: boolean,\n    pitchWithMap: boolean,\n    isAlongLine: boolean,\n    isVariableAnchor: boolean,\n    transform: IReadonlyTransform,\n    labelPlaneMatrix: mat4,\n    glCoordMatrix: mat4,\n    translation: [number, number],\n    texSizeSDF: [number, number],\n    texSizeIcon: [number, number],\n    pitchedScale: number,\n    isOffset: boolean,\n    heightAnchorGround: boolean\n): UniformValues<SymbolIconUniformsType> => {\n    return extend(symbolSDFUniformValues(functionType, size,\n        rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, transform, labelPlaneMatrix,\n        glCoordMatrix, translation, true, texSizeSDF, true, pitchedScale, isOffset, heightAnchorGround), {\n        'u_texsize_icon': texSizeIcon,\n        'u_texture_icon': 1\n    });\n};\n\nexport {symbolIconUniforms, symbolSDFUniforms, symbolIconUniformValues, symbolSDFUniformValues, symbolTextAndIconUniformValues, symbolTextAndIconUniforms};\n", "import {bgPatternUniformValues} from './pattern.ts';\nimport {\n    Uniform1i,\n    Uniform1f,\n    Uniform2f,\n    UniformColor\n} from '../uniform_binding.ts';\nimport {extend} from '../../util/util.ts';\n\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {PatternAtlas} from '../../render/pattern_atlas.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Context} from '../../webgl/context.ts';\nimport type {Color, ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\nimport type {CrossFaded} from '../../style/properties.ts';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport type BackgroundUniformsType = {\n    'u_opacity': Uniform1f;\n    'u_color': UniformColor;\n};\n\nexport type BackgroundPatternUniformsType = {\n    'u_opacity': Uniform1f;\n    // pattern uniforms:\n    'u_image': Uniform1i;\n    'u_pattern_tl_a': Uniform2f;\n    'u_pattern_br_a': Uniform2f;\n    'u_pattern_tl_b': Uniform2f;\n    'u_pattern_br_b': Uniform2f;\n    'u_texsize': Uniform2f;\n    'u_mix': Uniform1f;\n    'u_pattern_size_a': Uniform2f;\n    'u_pattern_size_b': Uniform2f;\n    'u_scale_a': Uniform1f;\n    'u_scale_b': Uniform1f;\n    'u_pixel_coord_upper': Uniform2f;\n    'u_pixel_coord_lower': Uniform2f;\n    'u_tile_units_to_pixels': Uniform1f;\n};\n\nconst backgroundUniforms = (context: Context, locations: UniformLocations): BackgroundUniformsType => ({\n    'u_opacity': new Uniform1f(context, locations.u_opacity),\n    'u_color': new UniformColor(context, locations.u_color)\n});\n\nconst backgroundPatternUniforms = (context: Context, locations: UniformLocations): BackgroundPatternUniformsType => ({\n    'u_opacity': new Uniform1f(context, locations.u_opacity),\n    'u_image': new Uniform1i(context, locations.u_image),\n    'u_pattern_tl_a': new Uniform2f(context, locations.u_pattern_tl_a),\n    'u_pattern_br_a': new Uniform2f(context, locations.u_pattern_br_a),\n    'u_pattern_tl_b': new Uniform2f(context, locations.u_pattern_tl_b),\n    'u_pattern_br_b': new Uniform2f(context, locations.u_pattern_br_b),\n    'u_texsize': new Uniform2f(context, locations.u_texsize),\n    'u_mix': new Uniform1f(context, locations.u_mix),\n    'u_pattern_size_a': new Uniform2f(context, locations.u_pattern_size_a),\n    'u_pattern_size_b': new Uniform2f(context, locations.u_pattern_size_b),\n    'u_scale_a': new Uniform1f(context, locations.u_scale_a),\n    'u_scale_b': new Uniform1f(context, locations.u_scale_b),\n    'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n    'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n    'u_tile_units_to_pixels': new Uniform1f(context, locations.u_tile_units_to_pixels)\n});\n\nconst backgroundUniformValues = (opacity: number, color: Color): UniformValues<BackgroundUniformsType> => ({\n    'u_opacity': opacity,\n    'u_color': color\n});\n\nconst backgroundPatternUniformValues = (\n    opacity: number,\n    patternAtlas: PatternAtlas,\n    transform: IReadonlyTransform,\n    image: CrossFaded<ResolvedImage>,\n    tile: {\n        tileID: OverscaledTileID;\n        tileSize: number;\n    },\n    crossfade: CrossfadeParameters\n): UniformValues<BackgroundPatternUniformsType> => extend(\n    bgPatternUniformValues(image, crossfade, patternAtlas, transform, tile),\n    {\n        'u_opacity': opacity\n    }\n);\n\nexport {\n    backgroundUniforms,\n    backgroundPatternUniforms,\n    backgroundUniformValues,\n    backgroundPatternUniformValues\n};\n", "import {type UniformValues, type UniformLocations, Uniform1f, Uniform3f, UniformMatrix4f} from '../uniform_binding.ts';\n\nimport type {mat4, vec3} from 'gl-matrix';\nimport type {Context} from '../../webgl/context.ts';\n\nexport type atmosphereUniformsType = {\n    'u_sun_pos': Uniform3f;\n    'u_atmosphere_blend': Uniform1f;\n    'u_globe_position': Uniform3f;\n    'u_globe_radius': Uniform1f;\n    'u_inv_proj_matrix': UniformMatrix4f;\n};\n\nconst atmosphereUniforms = (context: Context, locations: UniformLocations): atmosphereUniformsType => ({\n    'u_sun_pos': new Uniform3f(context, locations.u_sun_pos),\n    'u_atmosphere_blend': new Uniform1f(context, locations.u_atmosphere_blend),\n    'u_globe_position': new Uniform3f(context, locations.u_globe_position),\n    'u_globe_radius': new Uniform1f(context, locations.u_globe_radius),\n    'u_inv_proj_matrix': new UniformMatrix4f(context, locations.u_inv_proj_matrix),\n});\n\nconst atmosphereUniformValues = (\n    sunPos: vec3,\n    atmosphereBlend: number,\n    globePosition: vec3,\n    globeRadius: number,\n    invProjMatrix: mat4,\n): UniformValues<atmosphereUniformsType> => ({\n    'u_sun_pos': sunPos,\n    'u_atmosphere_blend': atmosphereBlend,\n    'u_globe_position': globePosition,\n    'u_globe_radius': globeRadius,\n    'u_inv_proj_matrix': invProjMatrix,\n});\n\nexport {atmosphereUniforms, atmosphereUniformValues};\n", "import {UniformColor, Uniform1f, Uniform2f, Uniform3f, UniformMatrix4f} from '../uniform_binding.ts';\nimport {getMercatorHorizon} from '../../geo/projection/mercator_utils.ts';\nimport {getAtmosphereAltitudeBlend, getGlobeCenterInViewSpace, getGlobeRadiusPixels} from '../../geo/projection/globe_utils.ts';\nimport {vec3} from 'gl-matrix';\n\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {SkyPropsPossiblyEvaluated} from '../../style/sky_properties.g.ts';\nimport type {UniformValues, UniformLocations} from '../uniform_binding.ts';\nimport type {Context} from '../../webgl/context.ts';\n\nexport type SkyUniformsType = {\n    'u_sky_color': UniformColor;\n    'u_horizon_color': UniformColor;\n    'u_horizon': Uniform2f;\n    'u_horizon_normal': Uniform2f;\n    'u_sky_horizon_blend': Uniform1f;\n    'u_sky_blend': Uniform1f;\n    'u_inv_proj_matrix': UniformMatrix4f;\n    'u_globe_position': Uniform3f;\n    'u_globe_radius': Uniform1f;\n    'u_atmosphere_blend': Uniform1f;\n};\n\nconst skyUniforms = (context: Context, locations: UniformLocations): SkyUniformsType => ({\n    'u_sky_color': new UniformColor(context, locations.u_sky_color),\n    'u_horizon_color': new UniformColor(context, locations.u_horizon_color),\n    'u_horizon': new Uniform2f(context, locations.u_horizon),\n    'u_horizon_normal': new Uniform2f(context, locations.u_horizon_normal),\n    'u_sky_horizon_blend': new Uniform1f(context, locations.u_sky_horizon_blend),\n    'u_sky_blend': new Uniform1f(context, locations.u_sky_blend),\n    'u_inv_proj_matrix': new UniformMatrix4f(context, locations.u_inv_proj_matrix),\n    'u_globe_position': new Uniform3f(context, locations.u_globe_position),\n    'u_globe_radius': new Uniform1f(context, locations.u_globe_radius),\n    'u_atmosphere_blend': new Uniform1f(context, locations.u_atmosphere_blend),\n});\n\nconst skyUniformValues = (sky: Readonly<SkyPropsPossiblyEvaluated>, transform: IReadonlyTransform, pixelRatio: number): UniformValues<SkyUniformsType> => {\n    const cosRoll = Math.cos(transform.rollInRadians);\n    const sinRoll = Math.sin(transform.rollInRadians);\n    const mercatorHorizon  = getMercatorHorizon(transform);\n    const projectionData = transform.getProjectionData({overscaledTileID: null, applyGlobeMatrix: true, applyTerrainMatrix: true});\n    const skyBlend = projectionData.projectionTransition;\n    const globePosition = getGlobeCenterInViewSpace(transform);\n    const globeRadius = getGlobeRadiusPixels(transform.worldSize, transform.center.lat);\n    return {\n        'u_sky_color': sky['sky-color'],\n        'u_horizon_color': sky['horizon-color'],\n        'u_horizon': [(transform.width / 2 - mercatorHorizon * sinRoll)  * pixelRatio,\n            (transform.height / 2 + mercatorHorizon * cosRoll) * pixelRatio],\n        'u_horizon_normal': [-sinRoll, cosRoll],\n        'u_sky_horizon_blend': (sky['sky-horizon-blend'] * transform.height / 2) * pixelRatio,\n        'u_sky_blend': skyBlend,\n        'u_inv_proj_matrix': transform.inverseProjectionMatrix,\n        'u_globe_position': globePosition,\n        'u_globe_radius': globeRadius,\n        'u_atmosphere_blend': sky['atmosphere-blend'] * getAtmosphereAltitudeBlend(vec3.length(globePosition) - globeRadius, globeRadius),\n    };\n};\n\nexport {skyUniforms, skyUniformValues};\n", "import {fillExtrusionUniforms, fillExtrusionPatternUniforms, type FillExtrusionUniformsType, type FillExtrusionPatternUniformsType} from './fill_extrusion_program.ts';\nimport {fillPatternUniforms, fillOutlineUniforms, fillOutlinePatternUniforms, fillUniforms, type FillUniformsType, type FillPatternUniformsType, type FillOutlineUniformsType, type FillOutlinePatternUniformsType} from './fill_program.ts';\nimport {circleUniforms, type CircleUniformsType} from './circle_program.ts';\nimport {debugUniforms, type DebugUniformsType} from './debug_program.ts';\nimport {heatmapUniforms, heatmapTextureUniforms, type HeatmapUniformsType, type HeatmapTextureUniformsType} from './heatmap_program.ts';\nimport {hillshadeUniforms, hillshadePrepareUniforms, type HillshadeUniformsType, type HillshadePrepareUniformsType} from './hillshade_program.ts';\nimport {colorReliefUniforms, type ColorReliefUniformsType} from './color_relief_program.ts';\nimport {lineUniforms, lineGradientUniforms, linePatternUniforms, lineSDFUniforms, lineGradientSDFUniforms, type LineUniformsType, type LineGradientUniformsType, type LinePatternUniformsType, type LineSDFUniformsType, type LineGradientSDFUniformsType} from './line_program.ts';\nimport {layerOpacityUniforms, type LayerOpacityUniformsType} from './layer_opacity_program.ts';\nimport {rasterUniforms, type RasterUniformsType} from './raster_program.ts';\nimport {symbolIconUniforms, symbolSDFUniforms, symbolTextAndIconUniforms, type SymbolIconUniformsType, type SymbolSDFUniformsType, type symbolTextAndIconUniformsType} from './symbol_program.ts';\nimport {backgroundUniforms, backgroundPatternUniforms, type BackgroundUniformsType, type BackgroundPatternUniformsType} from './background_program.ts';\nimport {terrainUniforms, terrainDepthUniforms, terrainHeightUniforms, type TerrainUniformsType, type TerrainDepthUniformsType, type TerrainHeightUniformsType} from './terrain_program.ts';\nimport {atmosphereUniforms, type atmosphereUniformsType} from './atmosphere_program.ts';\nimport {skyUniforms, type SkyUniformsType} from './sky_program.ts';\n\nimport type {Context} from '../context.ts';\nimport type {UniformLocations} from '../uniform_binding.ts';\n\ntype EmptyUniforms = Record<string, never>;\n\nconst emptyUniforms = (_: Context, __: UniformLocations): EmptyUniforms => ({});\n\nexport const programUniforms: {\n    fillExtrusion: (context: Context, locations: UniformLocations) => FillExtrusionUniformsType;\n    fillExtrusionPattern: (context: Context, locations: UniformLocations) => FillExtrusionPatternUniformsType;\n    fill: (context: Context, locations: UniformLocations) => FillUniformsType;\n    fillPattern: (context: Context, locations: UniformLocations) => FillPatternUniformsType;\n    fillOutline: (context: Context, locations: UniformLocations) => FillOutlineUniformsType;\n    fillOutlinePattern: (context: Context, locations: UniformLocations) => FillOutlinePatternUniformsType;\n    circle: (context: Context, locations: UniformLocations) => CircleUniformsType;\n    collisionBox: (context: Context, locations: UniformLocations) => EmptyUniforms;\n    collisionCircle: (context: Context, locations: UniformLocations) => EmptyUniforms;\n    debug: (context: Context, locations: UniformLocations) => DebugUniformsType;\n    depth: (context: Context, locations: UniformLocations) => EmptyUniforms;\n    clippingMask: (context: Context, locations: UniformLocations) => EmptyUniforms;\n    heatmap: (context: Context, locations: UniformLocations) => HeatmapUniformsType;\n    heatmapTexture: (context: Context, locations: UniformLocations) => HeatmapTextureUniformsType;\n    hillshade: (context: Context, locations: UniformLocations) => HillshadeUniformsType;\n    hillshadePrepare: (context: Context, locations: UniformLocations) => HillshadePrepareUniformsType;\n    colorRelief: (context: Context, locations: UniformLocations) => ColorReliefUniformsType;\n    line: (context: Context, locations: UniformLocations) => LineUniformsType;\n    lineGradient: (context: Context, locations: UniformLocations) => LineGradientUniformsType;\n    linePattern: (context: Context, locations: UniformLocations) => LinePatternUniformsType;\n    lineSDF: (context: Context, locations: UniformLocations) => LineSDFUniformsType;\n    lineGradientSDF: (context: Context, locations: UniformLocations) => LineGradientSDFUniformsType;\n    layerOpacity: (context: Context, locations: UniformLocations) => LayerOpacityUniformsType;\n    raster: (context: Context, locations: UniformLocations) => RasterUniformsType;\n    symbolIcon: (context: Context, locations: UniformLocations) => SymbolIconUniformsType;\n    symbolSDF: (context: Context, locations: UniformLocations) => SymbolSDFUniformsType;\n    symbolTextAndIcon: (context: Context, locations: UniformLocations) => symbolTextAndIconUniformsType;\n    background: (context: Context, locations: UniformLocations) => BackgroundUniformsType;\n    backgroundPattern: (context: Context, locations: UniformLocations) => BackgroundPatternUniformsType;\n    terrain: (context: Context, locations: UniformLocations) => TerrainUniformsType;\n    terrainDepth: (context: Context, locations: UniformLocations) => TerrainDepthUniformsType;\n    terrainHeight: (context: Context, locations: UniformLocations) => TerrainHeightUniformsType;\n    atmosphere: (context: Context, locations: UniformLocations) => atmosphereUniformsType;\n    sky: (context: Context, locations: UniformLocations) => SkyUniformsType;\n} = {\n    fillExtrusion: fillExtrusionUniforms,\n    fillExtrusionPattern: fillExtrusionPatternUniforms,\n    fill: fillUniforms,\n    fillPattern: fillPatternUniforms,\n    fillOutline: fillOutlineUniforms,\n    fillOutlinePattern: fillOutlinePatternUniforms,\n    circle: circleUniforms,\n    collisionBox: emptyUniforms,\n    collisionCircle: emptyUniforms,\n    debug: debugUniforms,\n    depth: emptyUniforms,\n    clippingMask: emptyUniforms,\n    heatmap: heatmapUniforms,\n    heatmapTexture: heatmapTextureUniforms,\n    hillshade: hillshadeUniforms,\n    hillshadePrepare: hillshadePrepareUniforms,\n    colorRelief: colorReliefUniforms,\n    line: lineUniforms,\n    lineGradient: lineGradientUniforms,\n    linePattern: linePatternUniforms,\n    lineSDF: lineSDFUniforms,\n    lineGradientSDF: lineGradientSDFUniforms,\n    layerOpacity: layerOpacityUniforms,\n    raster: rasterUniforms,\n    symbolIcon: symbolIconUniforms,\n    symbolSDF: symbolSDFUniforms,\n    symbolTextAndIcon: symbolTextAndIconUniforms,\n    background: backgroundUniforms,\n    backgroundPattern: backgroundPatternUniforms,\n    terrain: terrainUniforms,\n    terrainDepth: terrainDepthUniforms,\n    terrainHeight: terrainHeightUniforms,\n    atmosphere: atmosphereUniforms,\n    sky: skyUniforms\n};\n", "import {shaders} from '../shaders/shaders.ts';\nimport {Program} from './program.ts';\nimport {programUniforms} from './program/program_uniforms.ts';\n\nimport type {Context} from './context.ts';\nimport type {ProgramConfiguration} from '../data/program_configuration.ts';\nimport type {UniformBindings} from './uniform_binding.ts';\nimport type {ProjectionShaderVariant} from '../render/frame_render_context.ts';\n\ntype ProgramVariant = {\n    name: string;\n    programConfiguration?: ProgramConfiguration | null;\n    projectionShaderVariant: ProjectionShaderVariant;\n    showOverdrawInspector: boolean;\n    useTerrain: boolean;\n    defines: string[];\n};\n\n/**\n * @internal\n * Compiles each shader variant the first time it is asked for and deletes all of them on destroy.\n */\nexport class ProgramCache {\n    private readonly context: Context;\n    private programs: Record<string, Program<UniformBindings>> = {};\n\n    constructor(context: Context) {\n        this.context = context;\n    }\n\n    /**\n     * Returns the program for a shader variant, compiling it if the cache doesn't hold it yet.\n     */\n    getProgram(variant: ProgramVariant): Program<UniformBindings> {\n        const configurationKey = (variant.programConfiguration ? variant.programConfiguration.cacheKey : '');\n        const projectionKey = `/${variant.projectionShaderVariant.name}`;\n        const overdrawKey = (variant.showOverdrawInspector ? '/overdraw' : '');\n        const terrainKey = (variant.useTerrain ? '/terrain' : '');\n        const definesKey = (variant.defines ? `/${variant.defines.join('/')}` : '');\n\n        const key = variant.name + configurationKey + projectionKey + overdrawKey + terrainKey + definesKey;\n\n        this.programs[key] ||= new Program(\n            this.context,\n            shaders[variant.name],\n            variant.programConfiguration,\n            programUniforms[variant.name],\n            variant.showOverdrawInspector,\n            variant.useTerrain,\n            variant.projectionShaderVariant.prelude,\n            variant.projectionShaderVariant.define,\n            variant.defines\n        );\n        return this.programs[key];\n    }\n\n    destroy(): void {\n        for (const program of Object.values(this.programs)) {\n            if (program.program) {\n                this.context.gl.deleteProgram(program.program);\n            }\n        }\n        this.programs = {};\n    }\n}\n", "import type {StencilOpConstant, StencilTestGL} from './types.ts';\n\nconst ALWAYS = 0x0207;\nconst KEEP = 0x1E00;\n\nexport class StencilMode {\n    test: StencilTestGL;\n    ref: number;\n    mask: number;\n    fail: StencilOpConstant;\n    depthFail: StencilOpConstant;\n    pass: StencilOpConstant;\n\n    constructor(test: StencilTestGL, ref: number, mask: number, fail: StencilOpConstant,\n        depthFail: StencilOpConstant, pass: StencilOpConstant) {\n        this.test = test;\n        this.ref = ref;\n        this.mask = mask;\n        this.fail = fail;\n        this.depthFail = depthFail;\n        this.pass = pass;\n    }\n\n    static disabled: Readonly<StencilMode>;\n}\n\nStencilMode.disabled = new StencilMode({func: ALWAYS, mask: 0}, 0, 0, KEEP, KEEP, KEEP);\n", "import type {CullFaceModeType, FrontFaceType} from './types.ts';\n\nconst FRONT = 0x0404;\nconst BACK = 0x0405;\nconst CCW = 0x0901;\n\nexport class CullFaceMode {\n    enable: boolean;\n    mode: CullFaceModeType;\n    frontFace: FrontFaceType;\n\n    constructor(enable: boolean, mode: CullFaceModeType, frontFace: FrontFaceType) {\n        this.enable = enable;\n        this.mode = mode;\n        this.frontFace = frontFace;\n    }\n\n    static disabled: Readonly<CullFaceMode>;\n\n    /**\n     * The standard GL cull mode. Culls backfacing triangles when counterclockwise vertex order is used.\n     * Use for 3D geometry such as terrain.\n     */\n    static backCCW: Readonly<CullFaceMode>;\n\n    /**\n     * Opposite of {@link backCCW}. Culls front-facing triangles when counterclockwise vertex order is used.\n     */\n    static frontCCW: Readonly<CullFaceMode>;\n}\n\nCullFaceMode.disabled = new CullFaceMode(false, BACK, CCW);\nCullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW);\nCullFaceMode.frontCCW = new CullFaceMode(true, FRONT, CCW);\n", "import type {DepthFuncType, DepthMaskType, DepthRangeType} from './types.ts';\n\nconst ALWAYS = 0x0207;\n\nexport class DepthMode {\n    func: DepthFuncType;\n    mask: DepthMaskType;\n    range: DepthRangeType;\n\n    // DepthMask enums\n    static ReadOnly: boolean;\n    static ReadWrite: boolean;\n\n    constructor(depthFunc: DepthFuncType, depthMask: DepthMaskType, depthRange: DepthRangeType) {\n        this.func = depthFunc;\n        this.mask = depthMask;\n        this.range = depthRange;\n    }\n\n    static disabled: Readonly<DepthMode>;\n}\n\nDepthMode.ReadOnly = false;\nDepthMode.ReadWrite = true;\n\nDepthMode.disabled = new DepthMode(ALWAYS, DepthMode.ReadOnly, [0, 1]);\n", "import {DepthMode} from '../depth_mode.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {QuadTriangleArray, CollisionCircleLayoutArray} from '../../data/array_types.g.ts';\nimport {collisionCircleLayout} from '../../data/bucket/symbol_attributes.ts';\nimport {SegmentVector} from '../../data/segment.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {VertexBuffer} from '../vertex_buffer.ts';\nimport type {IndexBuffer} from '../index_buffer.ts';\nimport type {SymbolBucket} from '../../data/bucket/symbol_bucket.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\nimport type {StyleLayer} from '../../style/style_layer.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\n\ntype TileBatch = {\n    circleArray: number[];\n    circleOffset: number;\n    coord: OverscaledTileID;\n};\n\nlet quadTriangles: QuadTriangleArray;\n\nexport function drawCollisionDebug(tileManager: TileManager, layer: StyleLayer, coords: OverscaledTileID[], isText: boolean, frameRenderContext: FrameRenderContext): void {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const program = frameRenderContext.useProgram('collisionBox');\n    const tileBatches: TileBatch[] = [];\n    let circleCount = 0;\n    let circleOffset = 0;\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n        const bucket: SymbolBucket = (tile.getBucket(layer) as any);\n        if (!bucket) {\n            continue;\n        }\n        const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox;\n        // Get collision circle data of this bucket\n        const circleArray: number[] = bucket.collisionCircleArray;\n        if (circleArray.length > 0) {\n            tileBatches.push({\n                circleArray,\n                circleOffset,\n                coord\n            });\n\n            circleCount += circleArray.length / 4;  // 4 values per circle\n            circleOffset = circleCount;\n        }\n\n        // Draw collision boxes\n        if (!buffers) {\n            continue;\n        }\n\n        program.draw(context, gl.LINES,\n            DepthMode.disabled, StencilMode.disabled,\n            frameRenderContext.colorModeForRenderPass(),\n            CullFaceMode.disabled,\n            null,\n            frameRenderContext.getTerrainDataForTile(coord),\n            frameRenderContext.getProjectionDataForTile(coord),\n            layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer,\n            buffers.segments, null, frameRenderContext.transform.zoom, null, null,\n            buffers.collisionVertexBuffer);\n    }\n\n    if (!isText || !tileBatches.length) {\n        return;\n    }\n\n    // Render collision circles\n    const circleProgram = frameRenderContext.useProgram('collisionCircle');\n\n    // Construct vertex data\n    const vertexData = new CollisionCircleLayoutArray();\n    vertexData.resize(circleCount * 4);\n    vertexData._trim();\n\n    let vertexOffset = 0;\n\n    for (const batch of tileBatches) {\n        for (let i = 0; i < batch.circleArray.length / 4; i++) {\n            const circleIdx = i * 4;\n            const x = batch.circleArray[circleIdx + 0];\n            const y = batch.circleArray[circleIdx + 1];\n            const radius = batch.circleArray[circleIdx + 2];\n            const collision = batch.circleArray[circleIdx + 3];\n\n            // 4 floats per vertex, 4 vertices per quad\n            vertexData.emplace(vertexOffset++, x, y, radius, collision, 0);\n            vertexData.emplace(vertexOffset++, x, y, radius, collision, 1);\n            vertexData.emplace(vertexOffset++, x, y, radius, collision, 2);\n            vertexData.emplace(vertexOffset++, x, y, radius, collision, 3);\n        }\n    }\n    if (!quadTriangles || quadTriangles.length < circleCount * 2) {\n        quadTriangles = createQuadTriangles(circleCount);\n    }\n\n    const indexBuffer: IndexBuffer = context.createIndexBuffer(quadTriangles, true);\n    const vertexBuffer: VertexBuffer = context.createVertexBuffer(vertexData, collisionCircleLayout.members, true);\n\n    // Render batches\n    for (const batch of tileBatches) {\n\n        circleProgram.draw(\n            context,\n            gl.TRIANGLES,\n            DepthMode.disabled,\n            StencilMode.disabled,\n            frameRenderContext.colorModeForRenderPass(),\n            CullFaceMode.disabled,\n            null,\n            frameRenderContext.getTerrainDataForTile(batch.coord),\n            null,\n            layer.id,\n            vertexBuffer,\n            indexBuffer,\n            SegmentVector.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2),\n            null,\n            frameRenderContext.transform.zoom,\n            null,\n            null,\n            null);\n    }\n\n    vertexBuffer.destroy();\n    indexBuffer.destroy();\n}\n\nfunction createQuadTriangles(quadCount: number): QuadTriangleArray {\n    const triCount = quadCount * 2;\n    const array = new QuadTriangleArray();\n\n    array.resize(triCount);\n    array._trim();\n\n    // Two triangles and 4 vertices per quad.\n    for (let i = 0; i < triCount; i++) {\n        const idx = i * 6;\n\n        array.uint16[idx + 0] = i * 4 + 0;\n        array.uint16[idx + 1] = i * 4 + 1;\n        array.uint16[idx + 2] = i * 4 + 2;\n        array.uint16[idx + 3] = i * 4 + 2;\n        array.uint16[idx + 4] = i * 4 + 3;\n        array.uint16[idx + 5] = i * 4 + 0;\n    }\n\n    return array;\n}\n", "import Point from '@mapbox/point-geometry';\nimport {drawCollisionDebug} from './draw_collision_debug.ts';\nimport {SegmentVector} from '../../data/segment.ts';\nimport {pixelsToTileUnits} from '../../source/pixels_to_tile_units.ts';\nimport {type EvaluatedZoomSize, evaluateSizeForFeature, evaluateSizeForZoom} from '../../symbol/symbol_size.ts';\nimport {mat4} from 'gl-matrix';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {addDynamicAttributes} from '../../data/bucket/symbol_bucket.ts';\nimport {fastInvertTransformMat4} from '../../util/fast_maths.ts';\nimport {getAnchorAlignment, WritingMode} from '../../symbol/shaping.ts';\nimport {getGlCoordMatrix, getPerspectiveRatio, getPitchedLabelPlaneMatrix, hideGlyphs, projectWithMatrix, projectTileCoordinatesToClipSpace, projectTileCoordinatesToLabelPlane, type SymbolProjectionContext, updateLineLabels, elevationAt} from '../../symbol/projection.ts';\nimport {translatePosition} from '../../util/util.ts';\nimport ONE_EM from '../../symbol/one_em.ts';\nimport {\n    type SymbolIconUniformsType,\n    symbolIconUniformValues,\n    symbolSDFUniformValues,\n    symbolTextAndIconUniformValues\n} from '../program/symbol_program.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {SymbolStyleLayer} from '../../style/style_layer/symbol_style_layer.ts';\nimport type {Texture, TextureFilter} from '../texture.ts';\nimport type {OverscaledTileID, UnwrappedTileID} from '../../tile/tile_id.ts';\nimport type {UniformValues} from '../uniform_binding.ts';\nimport type {SymbolSDFUniformsType} from '../program/symbol_program.ts';\nimport type {CrossTileID, VariableOffset} from '../../symbol/placement.ts';\nimport type {SymbolBucket, SymbolBuffers} from '../../data/bucket/symbol_bucket.ts';\nimport type {TerrainData} from '../../render/terrain.ts';\nimport type {SymbolLayerSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {IReadonlyTransform, GetElevation} from '../../geo/transform_interface.ts';\nimport type {ColorMode} from '../color_mode.ts';\nimport type {Program} from '../program.ts';\nimport type {TextAnchor} from '../../style/style_layer/variable_text_anchor.ts';\nimport type {ProjectionData} from '../../geo/projection/projection_data.ts';\n\ntype SymbolTileRenderState = {\n    segments: SegmentVector;\n    sortKey: number;\n    terrainData: TerrainData;\n    state: {\n        program: Program<any>;\n        buffers: SymbolBuffers;\n        uniformValues: UniformValues<SymbolSDFUniformsType | SymbolIconUniformsType>;\n        projectionData: ProjectionData;\n        atlasTexture: Texture;\n        atlasTextureIcon: Texture | null;\n        atlasInterpolation: TextureFilter;\n        atlasInterpolationIcon: TextureFilter;\n        isSDF: boolean;\n        hasHalo: boolean;\n    };\n};\n\nconst identityMat4 = mat4.identity(new Float32Array(16));\n\nexport function drawSymbols(painter: Painter, tileManager: TileManager, layer: SymbolStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (frameRenderContext.currentPass !== 'translucent') return;\n\n    // Disable the stencil test so that labels aren't clipped to tile boundaries.\n    const stencilMode = StencilMode.disabled;\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n    const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset');\n\n    // Compute variable-offsets before painting since icons and text data positioning\n    // depend on each other in this case.\n    if (hasVariablePlacement) {\n        updateVariableAnchors(coords, layer, tileManager,\n            layer.layout.get('text-rotation-alignment'),\n            layer.layout.get('text-pitch-alignment'),\n            layer.paint.get('text-translate'),\n            layer.paint.get('text-translate-anchor'),\n            frameRenderContext\n        );\n    }\n\n    if (layer.paint.get('icon-opacity').constantOr(1) !== 0) {\n        drawLayerSymbols(painter, tileManager, layer, coords, false,\n            layer.paint.get('icon-translate'),\n            layer.paint.get('icon-translate-anchor'),\n            layer.layout.get('icon-rotation-alignment').constantOr('viewport'),\n            layer.layout.get('icon-pitch-alignment'),\n            layer.layout.get('icon-keep-upright'),\n            stencilMode, colorMode, frameRenderContext\n        );\n    }\n\n    if (layer.paint.get('text-opacity').constantOr(1) !== 0) {\n        drawLayerSymbols(painter, tileManager, layer, coords, true,\n            layer.paint.get('text-translate'),\n            layer.paint.get('text-translate-anchor'),\n            layer.layout.get('text-rotation-alignment'),\n            layer.layout.get('text-pitch-alignment'),\n            layer.layout.get('text-keep-upright'),\n            stencilMode, colorMode, frameRenderContext\n        );\n    }\n\n    if (tileManager.map.showCollisionBoxes) {\n        drawCollisionDebug(tileManager, layer, coords, true, frameRenderContext);\n        drawCollisionDebug(tileManager, layer, coords, false, frameRenderContext);\n    }\n}\n\nfunction calculateVariableRenderShift(\n    anchor: TextAnchor,\n    width: number,\n    height: number,\n    textOffset: [number, number],\n    textBoxScale: number,\n    renderTextSize: number): Point {\n    const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n    const shiftX = -(horizontalAlign - 0.5) * width;\n    const shiftY = -(verticalAlign - 0.5) * height;\n    return new Point(\n        (shiftX / textBoxScale + textOffset[0]) * renderTextSize,\n        (shiftY / textBoxScale + textOffset[1]) * renderTextSize\n    );\n}\n\nfunction updateVariableAnchors(coords: OverscaledTileID[],\n    layer:SymbolStyleLayer, tileManager: TileManager,\n    rotationAlignment: SymbolLayerSpecification['layout']['text-rotation-alignment'],\n    pitchAlignment: SymbolLayerSpecification['layout']['text-pitch-alignment'],\n    translate: [number, number],\n    translateAnchor: 'map' | 'viewport',\n    frameRenderContext: FrameRenderContext) {\n    const transform = frameRenderContext.transform;\n    const terrain = frameRenderContext.terrain;\n    const variableOffsets = frameRenderContext.data.variableOffsets;\n    const rotateWithMap = rotationAlignment === 'map';\n    const pitchWithMap = pitchAlignment === 'map';\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n        const bucket = tile.getBucket(layer) as SymbolBucket;\n        if (!bucket?.text?.segments.get().length) continue;\n\n        const sizeData = bucket.textSizeData;\n        const size = evaluateSizeForZoom(sizeData, transform.zoom);\n\n        const pixelToTileScale = pixelsToTileUnits(tile, 1, transform.zoom);\n        const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(rotateWithMap, transform, pixelToTileScale);\n        const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && bucket.hasIconData();\n\n        if (size) {\n            const tileScale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);\n            const getElevation = terrain ? (x: number, y: number) => terrain.getElevation(coord, x, y) : undefined;\n            const translation = translatePosition(transform, tile, translate, translateAnchor);\n            updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets,\n                transform, pitchedLabelPlaneMatrix, tileScale, size, updateTextFitIcon, translation, coord.toUnwrapped(), getElevation,\n                layer.layout.get('symbol-height-anchor') === 'ground');\n        }\n    }\n}\n\nfunction getShiftedAnchor(projectedAnchorPoint: Point, projectionContext: SymbolProjectionContext, rotateWithMap, shift: Point, transformAngle: number, pitchedTextShiftCorrection: number) {\n    // Usual case is that we take the projected anchor and add the pixel-based shift\n    // calculated earlier. In the (somewhat weird) case of pitch-aligned text, we add an equivalent\n    // tile-unit based shift to the anchor before projecting to the label plane.\n    const translatedAnchor = projectionContext.tileAnchorPoint.add(new Point(projectionContext.translation[0], projectionContext.translation[1]));\n    if (projectionContext.pitchWithMap) {\n        let adjustedShift = shift.mult(pitchedTextShiftCorrection);\n        if (!rotateWithMap) {\n            adjustedShift = adjustedShift.rotate(-transformAngle);\n        }\n        const tileAnchorShifted = translatedAnchor.add(adjustedShift);\n        return projectWithMatrix(tileAnchorShifted.x, tileAnchorShifted.y, projectionContext.pitchedLabelPlaneMatrix, elevationAt(projectionContext, tileAnchorShifted.x, tileAnchorShifted.y)).point;\n    } else {\n        if (rotateWithMap) {\n            // Compute the angle with which to rotate the anchor, so that it is aligned with\n            // the map's actual east-west axis. Very similar to what is done in the shader.\n            // Note that the label plane must be screen pixels here.\n            const projectedAnchorRight = projectTileCoordinatesToLabelPlane(projectionContext.tileAnchorPoint.x + 1, projectionContext.tileAnchorPoint.y, projectionContext);\n            const east = projectedAnchorRight.point.sub(projectedAnchorPoint);\n            const angle = Math.atan(east.y / east.x) + (east.x < 0 ? Math.PI : 0);\n            return projectedAnchorPoint.add(shift.rotate(angle));\n        } else {\n            return projectedAnchorPoint.add(shift);\n        }\n    }\n}\n\nfunction updateVariableAnchorsForBucket(\n    bucket: SymbolBucket,\n    rotateWithMap: boolean,\n    pitchWithMap: boolean,\n    variableOffsets: {[_ in CrossTileID]: VariableOffset},\n    transform: IReadonlyTransform,\n    pitchedLabelPlaneMatrix: mat4,\n    tileScale: number,\n    size: EvaluatedZoomSize,\n    updateTextFitIcon: boolean,\n    translation: [number, number],\n    unwrappedTileID: UnwrappedTileID,\n    getElevation: GetElevation | undefined,\n    heightAnchorGround: boolean) {\n    const placedSymbols = bucket.text.placedSymbolArray;\n    const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;\n    const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray;\n    const placedTextShifts = {};\n\n    dynamicTextLayoutVertexArray.clear();\n    for (let s = 0; s < placedSymbols.length; s++) {\n        const symbol = placedSymbols.get(s);\n        const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation;\n        const variableOffset = (!symbol.hidden && symbol.crossTileID && !skipOrientation) ? variableOffsets[symbol.crossTileID] : null;\n\n        if (!variableOffset) {\n            // These symbols are from a justification that is not being used, or a label that wasn't placed\n            // so we don't need to do the extra math to figure out what incremental shift to apply.\n            hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray);\n        } else  {\n            const tileAnchor = new Point(symbol.anchorX, symbol.anchorY);\n            const projectionContext: SymbolProjectionContext = {\n                getElevation,\n                heightOffset: symbol.heightOffset,\n                heightAnchorGround,\n                width: transform.width,\n                height: transform.height,\n                pitchedLabelPlaneMatrix,\n                lineVertexArray: null,\n                pitchWithMap,\n                transform,\n                projectionCache: null,\n                tileAnchorPoint: tileAnchor,\n                translation,\n                unwrappedTileID\n            };\n            const projectedAnchor = pitchWithMap ?\n                projectTileCoordinatesToClipSpace(tileAnchor.x, tileAnchor.y, projectionContext) :\n                projectTileCoordinatesToLabelPlane(tileAnchor.x, tileAnchor.y, projectionContext);\n            const perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera);\n            let renderTextSize = evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / ONE_EM;\n            if (pitchWithMap) {\n                // Go from size in pixels to equivalent size in tile units\n                renderTextSize *= bucket.tilePixelRatio / tileScale;\n            }\n\n            const {width, height, anchor, textOffset, textBoxScale} = variableOffset;\n            const shift = calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize);\n\n            const pitchedTextCorrection = transform.getPitchedTextCorrection(tileAnchor.x + translation[0], tileAnchor.y + translation[1], unwrappedTileID);\n            const shiftedAnchor = getShiftedAnchor(projectedAnchor.point, projectionContext, rotateWithMap, shift, -transform.bearingInRadians, pitchedTextCorrection);\n\n            const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === WritingMode.vertical) ? Math.PI / 2 : 0;\n            for (let g = 0; g < symbol.numGlyphs; g++) {\n                addDynamicAttributes(dynamicTextLayoutVertexArray, shiftedAnchor, angle);\n            }\n            //Only offset horizontal text icons\n            if (updateTextFitIcon && symbol.associatedIconIndex >= 0) {\n                placedTextShifts[symbol.associatedIconIndex] = {shiftedAnchor, angle};\n            }\n        }\n    }\n\n    if (updateTextFitIcon) {\n        dynamicIconLayoutVertexArray.clear();\n        const placedIcons = bucket.icon.placedSymbolArray;\n        for (let i = 0; i < placedIcons.length; i++) {\n            const placedIcon = placedIcons.get(i);\n            if (placedIcon.hidden) {\n                hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);\n            } else {\n                const shift = placedTextShifts[i];\n                if (!shift) {\n                    hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);\n                } else {\n                    for (let g = 0; g < placedIcon.numGlyphs; g++) {\n                        addDynamicAttributes(dynamicIconLayoutVertexArray, shift.shiftedAnchor, shift.angle);\n                    }\n                }\n            }\n        }\n        bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray);\n    }\n    bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray);\n}\n\nfunction getSymbolProgramName(isSDF: boolean, isText: boolean, bucket: SymbolBucket) {\n    if (bucket.iconsInText && isText) {\n        return 'symbolTextAndIcon';\n    } else if (isSDF) {\n        return 'symbolSDF';\n    } else {\n        return 'symbolIcon';\n    }\n}\n\nfunction drawLayerSymbols(\n    painter: Painter,\n    tileManager: TileManager,\n    layer: SymbolStyleLayer,\n    coords: OverscaledTileID[],\n    isText: boolean,\n    translate: [number, number],\n    translateAnchor: 'map' | 'viewport',\n    rotationAlignment: SymbolLayerSpecification['layout']['text-rotation-alignment'],\n    pitchAlignment: SymbolLayerSpecification['layout']['text-pitch-alignment'],\n    keepUpright: boolean,\n    stencilMode: StencilMode,\n    colorMode: Readonly<ColorMode>,\n    frameRenderContext: FrameRenderContext) {\n\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const transform = frameRenderContext.transform;\n\n    const rotateWithMap = rotationAlignment === 'map';\n    const pitchWithMap = pitchAlignment === 'map';\n    const alongLine = rotationAlignment !== 'viewport' && layer.layout.get('symbol-placement') !== 'point';\n    // Line label rotation happens in `updateLineLabels`\n    // Pitched point labels are automatically rotated by the pitchedLabelPlaneMatrix projection\n    // Unpitched point labels need to have their rotation applied after projection\n    const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine;\n\n    const hasSortKey = !layer.layout.get('symbol-sort-key').isConstant();\n    let sortFeaturesByKey = false;\n\n    const depthMode = frameRenderContext.getDepthModeForSublayer(0, DepthMode.ReadOnly);\n\n    const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset');\n\n    const tileRenderState: SymbolTileRenderState[] = [];\n\n    const pitchedTextRescaling = transform.getCircleRadiusCorrection();\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n        const bucket = tile.getBucket(layer) as SymbolBucket;\n        if (!bucket) continue;\n        const buffers = isText ? bucket.text : bucket.icon;\n\n        if (!buffers?.segments.get().length || !buffers.hasVisibleVertices) continue;\n        const programConfiguration = buffers.programConfigurations.get(layer.id);\n\n        const isSDF = isText || bucket.sdfIcons;\n\n        const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;\n        const transformed = pitchWithMap || transform.pitch !== 0;\n\n        const program = frameRenderContext.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration);\n        const size = evaluateSizeForZoom(sizeData, transform.zoom);\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n\n        let texSize: [number, number];\n        let texSizeIcon: [number, number] = [0, 0];\n        let atlasTexture: Texture;\n        let atlasInterpolation: TextureFilter;\n        let atlasTextureIcon = null;\n        let atlasInterpolationIcon: TextureFilter;\n        if (isText) {\n            atlasTexture = tile.glyphAtlasTexture;\n            atlasInterpolation = gl.LINEAR;\n            texSize = tile.glyphAtlasTexture.size;\n            if (bucket.iconsInText) {\n                texSizeIcon = tile.imageAtlasTexture.size;\n                atlasTextureIcon = tile.imageAtlasTexture;\n                const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera';\n                atlasInterpolationIcon = transformed || frameRenderContext.data.rotating || frameRenderContext.data.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST;\n            }\n        } else {\n            const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear;\n            atlasTexture = tile.imageAtlasTexture;\n            atlasInterpolation = isSDF || frameRenderContext.data.rotating || frameRenderContext.data.zooming || iconScaled || transformed ?\n                gl.LINEAR :\n                gl.NEAREST;\n            texSize = tile.imageAtlasTexture.size;\n        }\n\n        // See the comment at the beginning of src/symbol/projection.ts for an overview of the symbol projection process\n        const s = pixelsToTileUnits(tile, 1, frameRenderContext.transform.zoom);\n        const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(rotateWithMap, frameRenderContext.transform, s);\n        const glCoordMatrixForShader = getGlCoordMatrix(pitchWithMap, rotateWithMap, frameRenderContext.transform, s);\n\n        const translation = translatePosition(transform, tile, translate, translateAnchor);\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord);\n\n        const hasVariableAnchors = hasVariablePlacement && bucket.hasTextData();\n        const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' &&\n            hasVariableAnchors &&\n            bucket.hasIconData();\n        const isOffset = layer._unevaluatedLayout.hasValue('icon-offset');\n        const heightAnchorGround = layer.layout.get('symbol-height-anchor') === 'ground';\n\n        if (alongLine) {\n            const pitchedLabelPlaneMatrixInverse = mat4.create();\n            fastInvertTransformMat4(pitchedLabelPlaneMatrixInverse, pitchedLabelPlaneMatrix);\n\n            const getElevation = frameRenderContext.terrain ? (x: number, y: number) => frameRenderContext.terrain.getElevation(coord, x, y) : undefined;\n            const rotateToLine = layer.layout.get('text-rotation-alignment') === 'map';\n            updateLineLabels(bucket, painter, transform, isText, pitchedLabelPlaneMatrix, pitchedLabelPlaneMatrixInverse, pitchWithMap, keepUpright, rotateToLine, coord.toUnwrapped(), translation, getElevation);\n        }\n\n        const shaderVariableAnchor = (isText && hasVariablePlacement) || updateTextFitIcon;\n\n        // If the label plane matrix is used, it transforms either map-pitch-aligned pixels, or to screenspace pixels\n        const combinedLabelPlaneMatrix = pitchWithMap ? pitchedLabelPlaneMatrix : frameRenderContext.transform.clipSpaceToPixelsMatrix;\n        // Label plane matrix is unused in the shader if variable anchors are used or the text is placed along a line\n        const noLabelPlane = (alongLine || shaderVariableAnchor);\n        const uLabelPlaneMatrix = noLabelPlane ? identityMat4 : combinedLabelPlaneMatrix;\n\n        const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0;\n\n        let uniformValues: UniformValues<SymbolSDFUniformsType | SymbolIconUniformsType>;\n        if (isSDF) {\n            if (!bucket.iconsInText) {\n                uniformValues = symbolSDFUniformValues(sizeData.kind,\n                    size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, transform,\n                    uLabelPlaneMatrix, glCoordMatrixForShader, translation, isText, texSize, hasHalo, pitchedTextRescaling, isOffset, heightAnchorGround);\n            } else {\n                uniformValues = symbolTextAndIconUniformValues(sizeData.kind,\n                    size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, transform,\n                    uLabelPlaneMatrix, glCoordMatrixForShader, translation, texSize, texSizeIcon, pitchedTextRescaling, isOffset, heightAnchorGround);\n            }\n        } else {\n            uniformValues = symbolIconUniformValues(sizeData.kind,\n                size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor,\n                uLabelPlaneMatrix, glCoordMatrixForShader, translation, isText, texSize, pitchedTextRescaling, isOffset, heightAnchorGround);\n        }\n\n        const state = {\n            program,\n            buffers,\n            uniformValues,\n            projectionData,\n            atlasTexture,\n            atlasTextureIcon,\n            atlasInterpolation,\n            atlasInterpolationIcon,\n            isSDF,\n            hasHalo\n        };\n\n        if (hasSortKey && bucket.canOverlap) {\n            sortFeaturesByKey = true;\n            const oldSegments = buffers.segments.get();\n            for (const segment of oldSegments) {\n                tileRenderState.push({\n                    segments: new SegmentVector([segment]),\n                    sortKey: segment.sortKey,\n                    state,\n                    terrainData\n                });\n            }\n        } else {\n            tileRenderState.push({\n                segments: buffers.segments,\n                sortKey: 0,\n                state,\n                terrainData\n            });\n        }\n    }\n\n    if (sortFeaturesByKey) {\n        tileRenderState.sort((a, b) => a.sortKey - b.sortKey);\n    }\n\n    const haloWidthProperty = layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width');\n    const haloWidth = haloWidthProperty.constantOr(null) ?? Infinity;\n    const isGlyphOverlap = layer.layout.get('text-letter-spacing').constantOr(0) * ONE_EM < 0 || haloWidth > 1;\n\n    for (const segmentState of tileRenderState) {\n        const state = segmentState.state;\n\n        context.activeTexture.set(gl.TEXTURE0);\n        state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE);\n        if (state.atlasTextureIcon) {\n            context.activeTexture.set(gl.TEXTURE1);\n            if (state.atlasTextureIcon) {\n                state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE);\n            }\n        }\n\n        const isHalo = state.isSDF && state.hasHalo;\n        if (isHalo) {\n            const uniformValues = state.uniformValues;\n            uniformValues['u_is_halo'] = 1;\n            if (isGlyphOverlap){\n                // render halo in 2 pass (1 for the halo only, 1 for the text only)\n                uniformValues['u_is_plain'] = 0;\n                drawSymbolElements(state.buffers, segmentState.segments, layer, frameRenderContext, state.program, depthMode, stencilMode, colorMode, uniformValues, state.projectionData, segmentState.terrainData);\n                uniformValues['u_is_halo'] = 0;\n                uniformValues['u_is_plain'] = 1;\n            }\n        }\n\n        drawSymbolElements(state.buffers, segmentState.segments, layer, frameRenderContext, state.program, depthMode, stencilMode, colorMode, state.uniformValues, state.projectionData, segmentState.terrainData);\n\n        if (isHalo && !isGlyphOverlap) {\n            // for 1 pass halo rendering, restore the uniforms state\n            state.uniformValues['u_is_halo'] = 0;\n        }\n    }\n}\n\nfunction drawSymbolElements(\n    buffers: SymbolBuffers,\n    segments: SegmentVector,\n    layer: SymbolStyleLayer,\n    frameRenderContext: FrameRenderContext,\n    program: Program<any>,\n    depthMode: Readonly<DepthMode>,\n    stencilMode: StencilMode,\n    colorMode: Readonly<ColorMode>,\n    uniformValues: UniformValues<SymbolSDFUniformsType | SymbolIconUniformsType>,\n    projectionData: ProjectionData,\n    terrainData: TerrainData) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW,\n        uniformValues, terrainData, projectionData, layer.id, buffers.layoutVertexBuffer,\n        buffers.indexBuffer, segments, layer.paint,\n        frameRenderContext.transform.zoom, buffers.programConfigurations.get(layer.id),\n        buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer);\n}\n", "import {StencilMode} from '../stencil_mode.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {circleUniformValues} from '../program/circle_program.ts';\nimport {SegmentVector} from '../../data/segment.ts';\nimport {translatePosition} from '../../util/util.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\nimport type {Program} from '../program.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {CircleStyleLayer} from '../../style/style_layer/circle_style_layer.ts';\nimport type {CircleBucket} from '../../data/bucket/circle_bucket.ts';\nimport type {ProgramConfiguration} from '../../data/program_configuration.ts';\nimport type {VertexBuffer} from '../vertex_buffer.ts';\nimport type {IndexBuffer} from '../index_buffer.ts';\nimport type {UniformValues} from '../uniform_binding.ts';\nimport type {CircleUniformsType} from '../program/circle_program.ts';\nimport type {TerrainData} from '../../render/terrain.ts';\nimport type {ProjectionData} from '../../geo/projection/projection_data.ts';\n\ntype TileRenderState = {\n    programConfiguration: ProgramConfiguration;\n    program: Program<any>;\n    layoutVertexBuffer: VertexBuffer;\n    indexBuffer: IndexBuffer;\n    uniformValues: UniformValues<CircleUniformsType>;\n    terrainData: TerrainData;\n    projectionData: ProjectionData;\n};\n\ntype SegmentsTileRenderState = {\n    segments: SegmentVector;\n    sortKey: number;\n    state: TileRenderState;\n};\n\nexport function drawCircles(tileManager: TileManager, layer: CircleStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (frameRenderContext.currentPass !== 'translucent') return;\n\n    const opacity = layer.paint.get('circle-opacity');\n    const strokeWidth = layer.paint.get('circle-stroke-width');\n    const strokeOpacity = layer.paint.get('circle-stroke-opacity');\n    const sortFeaturesByKey = !layer.layout.get('circle-sort-key').isConstant();\n\n    if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) {\n        return;\n    }\n\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const transform = frameRenderContext.transform;\n\n    const depthMode = frameRenderContext.getDepthModeForSublayer(0, DepthMode.ReadOnly);\n    // Turn off stencil testing to allow circles to be drawn across boundaries,\n    // so that large circles are not clipped to tiles\n    const stencilMode = StencilMode.disabled;\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n\n    const segmentsRenderStates: SegmentsTileRenderState[] = [];\n\n    // Note: due to how the shader is written, this value only has effect when globe rendering is enabled and `circle-pitch-alignment` is set to 'map'.\n    const radiusCorrectionFactor = transform.getCircleRadiusCorrection();\n\n    for (const coord of coords) {\n\n        const tile = tileManager.getTile(coord);\n        const bucket: CircleBucket<any> = (tile.getBucket(layer) as any);\n        if (!bucket) continue;\n\n        const styleTranslate = layer.paint.get('circle-translate');\n        const styleTranslateAnchor = layer.paint.get('circle-translate-anchor');\n        const translateForUniforms = translatePosition(transform, tile, styleTranslate, styleTranslateAnchor);\n\n        const programConfiguration = bucket.programConfigurations.get(layer.id);\n        const program = frameRenderContext.useProgram('circle', programConfiguration);\n        const layoutVertexBuffer = bucket.layoutVertexBuffer;\n        const indexBuffer = bucket.indexBuffer;\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n        const uniformValues = circleUniformValues(transform, tile, layer, translateForUniforms, radiusCorrectionFactor);\n\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord);\n\n        const state: TileRenderState = {\n            programConfiguration,\n            program,\n            layoutVertexBuffer,\n            indexBuffer,\n            uniformValues,\n            terrainData,\n            projectionData\n        };\n\n        if (sortFeaturesByKey) {\n            const oldSegments = bucket.segments.get();\n            for (const segment of oldSegments) {\n                segmentsRenderStates.push({\n                    segments: new SegmentVector([segment]),\n                    sortKey: (segment.sortKey),\n                    state\n                });\n            }\n        } else {\n            segmentsRenderStates.push({\n                segments: bucket.segments,\n                sortKey: 0,\n                state\n            });\n        }\n\n    }\n\n    if (sortFeaturesByKey) {\n        segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey);\n    }\n\n    for (const segmentsState of segmentsRenderStates) {\n        const {programConfiguration, program, layoutVertexBuffer, indexBuffer, uniformValues, terrainData, projectionData} = segmentsState.state;\n        const segments = segmentsState.segments;\n\n        program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW,\n            uniformValues, terrainData, projectionData, layer.id,\n            layoutVertexBuffer, indexBuffer, segments,\n            layer.paint, frameRenderContext.transform.zoom, programConfiguration);\n    }\n}\n", "import {Texture} from '../texture.ts';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {DepthMode} from '../depth_mode.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {ColorMode} from '../color_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {\n    heatmapUniformValues,\n    heatmapTextureUniformValues\n} from '../program/heatmap_program.ts';\nimport {HEATMAP_FULL_RENDER_FBO_KEY} from '../../style/style_layer/heatmap_style_layer.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {Context} from '../context.ts';\nimport type {Framebuffer} from '../framebuffer.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {HeatmapStyleLayer} from '../../style/style_layer/heatmap_style_layer.ts';\nimport type {HeatmapBucket} from '../../data/bucket/heatmap_bucket.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport function drawHeatmap(painter: Painter, tileManager: TileManager, layer: HeatmapStyleLayer, tileIDs: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (layer.paint.get('heatmap-opacity') === 0) {\n        return;\n    }\n    const context = frameRenderContext.context;\n\n    if (frameRenderContext.terrain) {\n        for (const coord of tileIDs) {\n            const tile = tileManager.getTile(coord);\n            // Skip tiles that have uncovered parents to avoid flickering; we don't need\n            // to use complex tile masking here because the change between zoom levels is subtle,\n            // so it's fine to simply render the parent until all its 4 children are loaded\n            if (tileManager.hasRenderableParent(coord)) continue;\n            if (frameRenderContext.currentPass === 'offscreen') {\n                prepareHeatmapTerrain(tile, layer, coord, frameRenderContext);\n            } else if (frameRenderContext.currentPass === 'translucent') {\n                renderHeatmapTerrain(painter, layer, coord, frameRenderContext);\n            }\n        }\n        context.viewport.set([0, 0, painter.width, painter.height]);\n    } else {\n        if (frameRenderContext.currentPass === 'offscreen') {\n            prepareHeatmapFlat(painter, tileManager, layer, tileIDs, frameRenderContext);\n        } else if (frameRenderContext.currentPass === 'translucent') {\n            renderHeatmapFlat(painter, layer, frameRenderContext);\n        }\n\n    }\n}\n\nfunction prepareHeatmapFlat(painter: Painter, tileManager: TileManager, layer: HeatmapStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const transform = frameRenderContext.transform;\n\n    // Allow kernels to be drawn across boundaries, so that\n    // large kernels are not clipped to tiles\n    const stencilMode = StencilMode.disabled;\n    // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula\n    const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [true, true, true, true]);\n\n    bindFramebuffer(context, painter, layer);\n\n    context.clear({color: Color.transparent});\n\n    for (const coord of coords) {\n\n        // Skip tiles that have uncovered parents to avoid flickering; we don't need\n        // to use complex tile masking here because the change between zoom levels is subtle,\n        // so it's fine to simply render the parent until all its 4 children are loaded\n        if (tileManager.hasRenderableParent(coord)) continue;\n\n        const tile = tileManager.getTile(coord);\n        const bucket: HeatmapBucket = (tile.getBucket(layer) as any);\n        if (!bucket) continue;\n\n        const programConfiguration = bucket.programConfigurations.get(layer.id);\n        const program = frameRenderContext.useProgram('heatmap', programConfiguration);\n\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord, {applyTerrainMatrix: false});\n\n        const radiusCorrectionFactor = transform.getCircleRadiusCorrection();\n\n        program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.backCCW,\n            heatmapUniformValues(tile, transform.zoom, layer.paint.get('heatmap-intensity'), radiusCorrectionFactor),\n            null, projectionData,\n            layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n            bucket.segments, layer.paint, transform.zoom,\n            programConfiguration);\n    }\n\n    context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction renderHeatmapFlat(painter: Painter, layer: HeatmapStyleLayer, frameRenderContext: FrameRenderContext) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n\n    context.setColorMode(frameRenderContext.colorModeForRenderPass());\n\n    // Here we bind two different textures from which we'll sample in drawing\n    // heatmaps: the kernel texture, prepared in the offscreen pass, and a\n    // color ramp texture.\n    const fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY);\n    if (!fbo) return;\n    context.activeTexture.set(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n    context.activeTexture.set(gl.TEXTURE1);\n    const colorRampTexture = getColorRampTexture(context, layer);\n    colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n    frameRenderContext.useProgram('heatmapTexture').draw(context, gl.TRIANGLES,\n        DepthMode.disabled, StencilMode.disabled, frameRenderContext.colorModeForRenderPass(), CullFaceMode.disabled,\n        heatmapTextureUniformValues(painter, layer, 0, 1), null, null,\n        layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer,\n        painter.viewportSegments, layer.paint, frameRenderContext.transform.zoom);\n}\n\nfunction prepareHeatmapTerrain(tile: Tile, layer: HeatmapStyleLayer, coord: OverscaledTileID, frameRenderContext: FrameRenderContext) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n\n    const stencilMode = StencilMode.disabled;\n    // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula\n    const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [true, true, true, true]);\n\n    const bucket: HeatmapBucket = (tile.getBucket(layer) as any);\n    if (!bucket) return;\n\n    const tileKey = coord.key;\n    let fbo = layer.heatmapFbos.get(tileKey);\n    if (!fbo) {\n        fbo = createHeatmapFbo(context, tile.tileSize, tile.tileSize);\n        layer.heatmapFbos.set(tileKey, fbo);\n    }\n\n    context.bindFramebuffer.set(fbo.framebuffer);\n    context.viewport.set([0, 0, tile.tileSize, tile.tileSize]);\n\n    context.clear({color: Color.transparent});\n\n    const programConfiguration = bucket.programConfigurations.get(layer.id);\n    const program = frameRenderContext.useProgram('heatmap', programConfiguration, !frameRenderContext.data.isRenderingGlobe);\n\n    const projectionData = frameRenderContext.getProjectionDataForTile(tile.tileID);\n\n    const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n    program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled,\n        heatmapUniformValues(tile, frameRenderContext.transform.zoom, layer.paint.get('heatmap-intensity'), 1.0), terrainData, projectionData,\n        layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n        bucket.segments, layer.paint, frameRenderContext.transform.zoom,\n        programConfiguration);\n}\n\nfunction renderHeatmapTerrain(painter: Painter, layer: HeatmapStyleLayer, coord: OverscaledTileID, frameRenderContext: FrameRenderContext) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const transform = frameRenderContext.transform;\n\n    context.setColorMode(frameRenderContext.colorModeForRenderPass());\n\n    const colorRampTexture = getColorRampTexture(context, layer);\n\n    // Here we bind two different textures from which we'll sample in drawing\n    // heatmaps: the kernel texture, prepared in the offscreen pass, and a\n    // color ramp texture.\n    const tileKey = coord.key;\n    const fbo = layer.heatmapFbos.get(tileKey);\n    if (!fbo) return;\n\n    context.activeTexture.set(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n    context.activeTexture.set(gl.TEXTURE1);\n    colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n    const projectionData = frameRenderContext.getProjectionDataForTile(coord, {applyTerrainMatrix: frameRenderContext.data.isRenderingGlobe});\n\n    frameRenderContext.useProgram('heatmapTexture').draw(context, gl.TRIANGLES,\n        DepthMode.disabled, StencilMode.disabled, frameRenderContext.colorModeForRenderPass(), CullFaceMode.disabled,\n        heatmapTextureUniformValues(painter, layer, 0, 1), null, projectionData,\n        layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer,\n        painter.rasterBoundsSegments, layer.paint, transform.zoom);\n\n    // destroy the FBO after rendering\n    fbo.destroy();\n    layer.heatmapFbos.delete(tileKey);\n}\n\nfunction bindFramebuffer(context: Context, painter: Painter, layer: HeatmapStyleLayer) {\n    const gl = context.gl;\n    context.activeTexture.set(gl.TEXTURE1);\n\n    // Use a 4x downscaled screen texture for better performance\n    context.viewport.set([0, 0, painter.width / 4, painter.height / 4]);\n\n    let fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY);\n\n    if (!fbo) {\n        fbo = createHeatmapFbo(context, painter.width / 4, painter.height / 4);\n        layer.heatmapFbos.set(HEATMAP_FULL_RENDER_FBO_KEY, fbo);\n    } else {\n        gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n        context.bindFramebuffer.set(fbo.framebuffer);\n    }\n}\n\nfunction createHeatmapFbo(context: Context, width: number, height: number): Framebuffer {\n    const gl = context.gl;\n    const texture = gl.createTexture();\n    gl.bindTexture(gl.TEXTURE_2D, texture);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n\n    gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA16F, width, height);\n\n    const fbo = context.createFramebuffer(width, height, false, false);\n    fbo.colorAttachment.set(texture);\n\n    return fbo;\n}\n\nfunction getColorRampTexture(context: Context, layer: HeatmapStyleLayer): Texture {\n    layer.colorRampTexture ||= new Texture(context, layer.colorRamp, context.gl.RGBA);\n    return layer.colorRampTexture;\n}\n", "import {DepthMode} from '../depth_mode.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {layerOpacityUniformValues} from '../program/layer_opacity_program.ts';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer.ts';\nimport type {FillStyleLayer} from '../../style/style_layer/fill_style_layer.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport type PrepareDrawLayerOpacityResult = {\n    compositeTarget: WebGLFramebuffer;\n    compositeViewport: [number, number, number, number];\n};\n\n/**\n * Partial line-layer-opacity\n * render the whole layer to a scratch FBO, then composite with `layerOpacity`.\n * Applies opacity uniformly to the layer instead of accumulating alpha across overlapping segments.\n */\nexport function prepareDrawLayerOpacity(painter: Painter, layer: LineStyleLayer | FillStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): PrepareDrawLayerOpacityResult {\n    const context = frameRenderContext.context;\n    const compositeTarget = context.bindFramebuffer.get();\n    const compositeViewport = context.viewport.get();\n    const [, , width, height] = compositeViewport;\n\n    bindLayerOpacity(painter, width, height);\n\n    context.viewport.set([0, 0, width, height]);\n    context.clear({color: Color.transparent, depth: 1, stencil: 0});\n\n    frameRenderContext.invalidateTileClippingMasks();\n    frameRenderContext.renderTileClippingMasks(layer, coords);\n\n    return {\n        compositeTarget,\n        compositeViewport\n    };\n}\n\nfunction bindLayerOpacity(painter: Painter, width: number, height: number): void {\n    const gl = painter.context.gl;\n\n    if (!painter.layerOpacityFbo) {\n        const fbo = painter.context.createFramebuffer(width, height, true, true);\n        const texture = gl.createTexture();\n        gl.bindTexture(gl.TEXTURE_2D, texture);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n        fbo.colorAttachment.set(texture);\n        fbo.depthAttachment.set(painter.context.createRenderbuffer(gl.DEPTH_STENCIL, width, height));\n        painter.layerOpacityFbo = fbo;\n        painter.context.bindFramebuffer.set(painter.layerOpacityFbo.framebuffer);\n        return;\n    }\n    if (painter.layerOpacityFbo.width === width && painter.layerOpacityFbo.height === height) {\n        painter.context.bindFramebuffer.set(painter.layerOpacityFbo.framebuffer);\n        return;\n    }\n    const fbo = painter.layerOpacityFbo;\n    gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n    painter.context.bindRenderbuffer.set(fbo.depthAttachment.get());\n    gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);\n    painter.context.bindRenderbuffer.set(null);\n    fbo.width = width;\n    fbo.height = height;\n    painter.context.bindFramebuffer.set(fbo.framebuffer);\n}\n\nexport function drawLayerOpacity(painter: Painter, opacity: number, prepareDrawLayerOpacityResult: PrepareDrawLayerOpacityResult, layer: LineStyleLayer | FillStyleLayer, frameRenderContext: FrameRenderContext): void {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n\n    context.bindFramebuffer.set(prepareDrawLayerOpacityResult.compositeTarget);\n    context.viewport.set(prepareDrawLayerOpacityResult.compositeViewport);\n\n    context.activeTexture.set(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, painter.layerOpacityFbo.colorAttachment.get());\n\n    frameRenderContext.useProgram('layerOpacity').draw(context, gl.TRIANGLES,\n        DepthMode.disabled, StencilMode.disabled, frameRenderContext.colorModeForRenderPass(), CullFaceMode.disabled,\n        layerOpacityUniformValues(opacity, 0), null, null,\n        layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer,\n        painter.viewportSegments, layer.paint, frameRenderContext.transform.zoom);\n\n    frameRenderContext.invalidateTileClippingMasks();\n}\n", "import {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {Texture} from '../texture.ts';\nimport {\n    lineUniformValues,\n    linePatternUniformValues,\n    lineSDFUniformValues,\n    lineGradientUniformValues,\n    lineGradientSDFUniformValues\n} from '../program/line_program.ts';\nimport {clamp, nextPowerOfTwo} from '../../util/util.ts';\nimport {renderColorRamp} from '../../util/color_ramp.ts';\nimport {EXTENT} from '../../data/extent.ts';\nimport {drawLayerOpacity, prepareDrawLayerOpacity} from './draw_layer_opacity.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {LineStyleLayer} from '../../style/style_layer/line_style_layer.ts';\nimport type {LineBucket} from '../../data/bucket/line_bucket.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {Context} from '../context.ts';\nimport type {ProgramConfiguration} from '../../data/program_configuration.ts';\nimport type {RGBAImage} from '../../util/image.ts';\n\ntype GradientTexture = {\n    texture?: Texture;\n    gradient?: RGBAImage;\n    version?: number;\n};\n\nfunction updateGradientTexture(\n    tileManager: TileManager,\n    context: Context,\n    gl: WebGLRenderingContext,\n    layer: LineStyleLayer,\n    bucket: LineBucket,\n    coord: OverscaledTileID,\n    layerGradient: GradientTexture,\n    frameRenderContext: FrameRenderContext\n): Texture {\n    let textureResolution = 256;\n    if (layer.stepInterpolant) {\n        const sourceMaxZoom = tileManager.getSource().maxzoom;\n        const potentialOverzoom = coord.canonical.z === sourceMaxZoom ?\n            Math.ceil(1 << (frameRenderContext.transform.maxZoom - coord.canonical.z)) : 1;\n        const lineLength = bucket.maxLineLength / EXTENT;\n        // Logical pixel tile size is 512px, and 1024px right before current zoom + 1\n        const maxTilePixelSize = 1024;\n        // Maximum possible texture coverage heuristic, bound by hardware max texture size\n        const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom;\n        textureResolution = clamp(nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize);\n    }\n    layerGradient.gradient = renderColorRamp({\n        expression: layer.gradientExpression(),\n        evaluationKey: 'lineProgress',\n        resolution: textureResolution,\n        image: layerGradient.gradient || undefined,\n        clips: bucket.lineClipsArray\n    });\n    if (layerGradient.texture) {\n        layerGradient.texture.update(layerGradient.gradient);\n    } else {\n        layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA);\n    }\n    layerGradient.version = layer.gradientVersion;\n    return layerGradient.texture;\n}\n\nfunction bindImagePatternTextures(\n    context: Context,\n    gl: WebGLRenderingContext,\n    tile: Tile,\n    programConfiguration: ProgramConfiguration,\n    crossfade: ReturnType<LineStyleLayer['getCrossfadeParameters']>\n) {\n    context.activeTexture.set(gl.TEXTURE0);\n    tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n    programConfiguration.updatePaintBuffers(crossfade);\n}\n\nfunction bindDasharrayTextures(\n    painter: Painter,\n    context: Context,\n    gl: WebGLRenderingContext,\n    programConfiguration: ProgramConfiguration,\n    programChanged: boolean,\n    crossfade: ReturnType<LineStyleLayer['getCrossfadeParameters']>\n) {\n    if (programChanged || painter.lineAtlas.dirty) {\n        context.activeTexture.set(gl.TEXTURE0);\n        painter.lineAtlas.bind(context);\n    }\n    programConfiguration.updatePaintBuffers(crossfade);\n}\n\nfunction bindGradientTextures(\n    tileManager: TileManager,\n    context: Context,\n    gl: WebGLRenderingContext,\n    layer: LineStyleLayer,\n    bucket: LineBucket,\n    coord: OverscaledTileID,\n    frameRenderContext: FrameRenderContext\n) {\n    const layerGradient = bucket.gradients[layer.id];\n    let gradientTexture = layerGradient.texture;\n    if (layer.gradientVersion !== layerGradient.version) {\n        gradientTexture = updateGradientTexture(tileManager, context, gl, layer, bucket, coord, layerGradient, frameRenderContext);\n    }\n    context.activeTexture.set(gl.TEXTURE0);\n    gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);\n}\n\nfunction bindGradientAndDashTextures(\n    painter: Painter,\n    tileManager: TileManager,\n    context: Context,\n    gl: WebGLRenderingContext,\n    layer: LineStyleLayer,\n    bucket: LineBucket,\n    coord: OverscaledTileID,\n    programConfiguration: ProgramConfiguration,\n    crossfade: ReturnType<LineStyleLayer['getCrossfadeParameters']>,\n    frameRenderContext: FrameRenderContext\n) {\n    // Bind gradient texture to TEXTURE0\n    const layerGradient = bucket.gradients[layer.id];\n    let gradientTexture = layerGradient.texture;\n    if (layer.gradientVersion !== layerGradient.version) {\n        gradientTexture = updateGradientTexture(tileManager, context, gl, layer, bucket, coord, layerGradient, frameRenderContext);\n    }\n    context.activeTexture.set(gl.TEXTURE0);\n    gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n    // Bind dash atlas to TEXTURE1\n    context.activeTexture.set(gl.TEXTURE1);\n    painter.lineAtlas.bind(context);\n\n    programConfiguration.updatePaintBuffers(crossfade);\n}\n\nexport function drawLine(painter: Painter, tileManager: TileManager, layer: LineStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (frameRenderContext.currentPass !== 'translucent') return;\n\n    const opacity = layer.paint.get('line-opacity');\n    const width = layer.paint.get('line-width');\n    const layerOpacity = layer.paint.get('line-layer-opacity');\n    if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0 || layerOpacity === 0) return;\n\n    if (layerOpacity < 1) {\n        const results = prepareDrawLayerOpacity(painter, layer, coords, frameRenderContext);\n        drawLineTiles(painter, tileManager, layer, coords, frameRenderContext);\n        drawLayerOpacity(painter, layerOpacity, results, layer, frameRenderContext);\n        return;\n    }\n\n    drawLineTiles(painter, tileManager, layer, coords, frameRenderContext);\n}\n\nfunction drawLineTiles(\n    painter: Painter,\n    tileManager: TileManager,\n    layer: LineStyleLayer,\n    coords: OverscaledTileID[],\n    frameRenderContext: FrameRenderContext\n) {\n    const depthMode = frameRenderContext.getDepthModeForSublayer(0, DepthMode.ReadOnly);\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n\n    const dasharrayProperty = layer.paint.get('line-dasharray');\n    const dasharray = dasharrayProperty.constantOr(1 as any);\n    const patternProperty = layer.paint.get('line-pattern');\n    const image = patternProperty.constantOr(1 as any);\n\n    const gradient = layer.paint.get('line-gradient');\n    const crossfade = layer.getCrossfadeParameters();\n\n    let programId: string;\n    if (image) programId = 'linePattern';\n    else if (dasharray && gradient) programId = 'lineGradientSDF';\n    else if (dasharray) programId = 'lineSDF';\n    else if (gradient) programId = 'lineGradient';\n    else programId = 'line';\n\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const transform = frameRenderContext.transform;\n\n    let firstTile = true;\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n\n        if (image && !tile.patternsLoaded()) continue;\n\n        const bucket: LineBucket = (tile.getBucket(layer) as any);\n        if (!bucket) continue;\n\n        const programConfiguration = bucket.programConfigurations.get(layer.id);\n        const prevProgram = context.program.get();\n        const program = frameRenderContext.useProgram(programId, programConfiguration);\n        const programChanged = firstTile || program.program !== prevProgram;\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n\n        const constantPattern = patternProperty.constantOr(null);\n        const constantDasharray = dasharrayProperty?.constantOr(null);\n\n        if (constantPattern && tile.imageAtlas) {\n            const atlas = tile.imageAtlas;\n            const posTo = atlas.patternPositions[constantPattern.to.toString()];\n            const posFrom = atlas.patternPositions[constantPattern.from.toString()];\n            if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n        } else if (constantDasharray) {\n            const round = layer.layout.get('line-cap').constantOr(null) === 'round';\n            const dashTo = painter.lineAtlas.getDash(constantDasharray.to, round);\n            const dashFrom = painter.lineAtlas.getDash(constantDasharray.from, round);\n            programConfiguration.setConstantDashPositions(dashTo, dashFrom);\n        }\n\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord);\n\n        const pixelRatio = transform.getPixelScale();\n\n        let uniformValues;\n        if (image) {\n            uniformValues = linePatternUniformValues(transform, tile, layer, pixelRatio, crossfade);\n            bindImagePatternTextures(context, gl, tile, programConfiguration, crossfade);\n        } else if (dasharray && gradient) {\n            uniformValues = lineGradientSDFUniformValues(transform, painter.lineAtlas, tile, layer, pixelRatio, crossfade, bucket.lineClipsArray.length);\n            bindGradientAndDashTextures(painter, tileManager, context, gl, layer, bucket, coord, programConfiguration, crossfade, frameRenderContext);\n        } else if (dasharray) {\n            uniformValues = lineSDFUniformValues(transform, painter.lineAtlas, tile, layer, pixelRatio, crossfade);\n            bindDasharrayTextures(painter, context, gl, programConfiguration, programChanged, crossfade);\n        } else if (gradient) {\n            uniformValues = lineGradientUniformValues(transform, tile, layer, pixelRatio, bucket.lineClipsArray.length);\n            bindGradientTextures(tileManager, context, gl, layer, bucket, coord, frameRenderContext);\n        } else {\n            uniformValues = lineUniformValues(transform, tile, layer, pixelRatio);\n        }\n\n        const stencil = frameRenderContext.stencilModeForClipping(coord);\n\n        program.draw(context, gl.TRIANGLES, depthMode,\n            stencil, colorMode, CullFaceMode.disabled, uniformValues, terrainData, projectionData,\n            layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments,\n            layer.paint, frameRenderContext.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2);\n\n        firstTile = false;\n        // once refactored so that bound texture state is managed, we'll also be able to remove this firstTile/programChanged logic\n    }\n}\n", "import type {CrossFaded} from '../style/properties.ts';\nimport type {ResolvedImage} from '@maplibre/maplibre-gl-style-spec';\nimport type {Tile} from '../tile/tile.ts';\nimport type {ProgramConfiguration} from '../data/program_configuration.ts';\nimport type {FillExtrusionStyleLayer} from '../style/style_layer/fill_extrusion_style_layer.ts';\nimport type {FillStyleLayer} from '../style/style_layer/fill_style_layer.ts';\n\n/**\n * A simple helper shared by draw_fill and draw_fill_extrusions to find the correct pattern positions AND update program.\n * For transitionable properties, especially 'fill-pattern' and 'fill-extrusion-pattern', while rendering certain frames\n * tile.imageAtlas has been updated by worker to hold the new pattern only, but rendering code is still looking for the previous image.\n * The mismatch was causing setConstantPatternPositions method not being called and pixelRatio was always the\n * default of 1, instead of actual values set by original map.addImage.\n *\n * @param programConfiguration - to be used to set pattern position and device pixel ratio.\n * @param propertyName - 'fill-pattern' or 'fill-extrusion-pattern' property key\n * @param constantPattern - either 'fill-pattern' or 'fill-extrusion-pattern' property value\n * @param tile - current tile being drawn\n * @param layer - current layer being rendered\n */\nexport function updatePatternPositionsInProgram(\n    programConfiguration: ProgramConfiguration,\n    propertyName: 'fill-pattern' | 'fill-extrusion-pattern',\n    constantPattern: CrossFaded<ResolvedImage>,\n    tile: Tile,\n    layer: FillStyleLayer | FillExtrusionStyleLayer): void {\n\n    if (!constantPattern || !tile?.imageAtlas) {\n        return;\n    }\n\n    const patternPositions = tile.imageAtlas.patternPositions;\n    let posTo = patternPositions[constantPattern.to.toString()];\n    let posFrom = patternPositions[constantPattern.from.toString()];\n\n    // https://github.com/maplibre/maplibre-gl-js/issues/3377\n    if (!posTo && posFrom) posTo = posFrom;\n    if (!posFrom && posTo) posFrom = posTo;\n\n    // try again in case patternPositions has been updated by worker\n    if (!posTo || !posFrom) {\n        const transitioned = layer.getPaintProperty(propertyName) as string;\n        posTo = patternPositions[transitioned];\n        posFrom = patternPositions[transitioned];\n    }\n\n    if (posTo && posFrom) {\n        programConfiguration.setConstantPatternPositions(posTo, posFrom);\n    }\n}\n", "import {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {\n    fillUniformValues,\n    fillPatternUniformValues,\n    fillOutlineUniformValues,\n    fillOutlinePatternUniformValues\n} from '../program/fill_program.ts';\nimport {updatePatternPositionsInProgram} from '../../render/update_pattern_positions_in_program.ts';\nimport {translatePosition} from '../../util/util.ts';\nimport {drawLayerOpacity, prepareDrawLayerOpacity} from './draw_layer_opacity.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {ColorMode} from '../color_mode.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {FillStyleLayer} from '../../style/style_layer/fill_style_layer.ts';\nimport type {FillBucket} from '../../data/bucket/fill_bucket.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport function drawFill(painter: Painter, tileManager: TileManager, layer: FillStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    const color = layer.paint.get('fill-color');\n    const opacity = layer.paint.get('fill-opacity');\n    const layerOpacity = layer.paint.get('fill-layer-opacity');\n    if (opacity.constantOr(1) === 0 || layerOpacity === 0) return;\n\n    if (layerOpacity < 1) {\n        if (frameRenderContext.currentPass !== 'translucent') return;\n        const results = prepareDrawLayerOpacity(painter, layer, coords, frameRenderContext);\n        drawFillAndOutline(tileManager, layer, coords, frameRenderContext);\n        drawLayerOpacity(painter, layerOpacity, results, layer, frameRenderContext);\n        return;\n    }\n\n    const pattern = layer.paint.get('fill-pattern');\n    const fillEligibleForOpaque = frameRenderContext.opaquePassEnabledForLayer() &&\n        !pattern.constantOr(1 as any) &&\n        color.constantOr(Color.transparent).a === 1 &&\n        opacity.constantOr(0) === 1;\n\n    if (fillEligibleForOpaque && frameRenderContext.currentPass === 'opaque') {\n        // Opaque-eligible fill draws standalone in the opaque pass with ReadWrite depth;\n        // its outline (always translucent) runs in the translucent pass below.\n        const colorMode = frameRenderContext.colorModeForRenderPass();\n        const depthMode = frameRenderContext.getDepthModeForSublayer(1, DepthMode.ReadWrite);\n        drawFillTiles(tileManager, layer, coords, depthMode, colorMode, false, frameRenderContext);\n        return;\n    }\n    if (fillEligibleForOpaque && frameRenderContext.currentPass === 'translucent') {\n        // Fill already drew in the opaque pass; just draw the outline here.\n        drawOutline(tileManager, layer, coords, frameRenderContext);\n        return;\n    }\n    if (frameRenderContext.currentPass === 'translucent') {\n        drawFillAndOutline(tileManager, layer, coords, frameRenderContext);\n    }\n}\n\n/**\n * Draw fill + outline in a single translucent pass with ReadOnly depth.\n * Shared by the layer-opacity subpass (always) and the normal translucent path\n * (when the fill is not opaque-pass-eligible).\n */\nfunction drawFillAndOutline(\n    tileManager: TileManager,\n    layer: FillStyleLayer,\n    coords: OverscaledTileID[],\n    frameRenderContext: FrameRenderContext\n) {\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n\n    const fillDepthMode = frameRenderContext.getDepthModeForSublayer(1, DepthMode.ReadOnly);\n    drawFillTiles(tileManager, layer, coords, fillDepthMode, colorMode, false, frameRenderContext);\n\n    drawOutline(tileManager, layer, coords, frameRenderContext);\n}\n\nfunction drawOutline(\n    tileManager: TileManager,\n    layer: FillStyleLayer,\n    coords: OverscaledTileID[],\n    frameRenderContext: FrameRenderContext\n) {\n    if (!layer.paint.get('fill-antialias')) return;\n\n    // If we defined a different color for the fill outline, we are\n    // going to ignore the bits in 0x07 and just care about the global\n    // clipping mask.\n    // Otherwise, we only want to drawFill the antialiased parts that are\n    // *outside* the current shape. This is important in case the fill\n    // or stroke color is translucent. If we wouldn't clip to outside\n    // the current shape, some pixels from the outline stroke overlapped\n    // the (non-antialiased) fill.\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n    const depthMode = frameRenderContext.getDepthModeForSublayer(\n        layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly);\n    drawFillTiles(tileManager, layer, coords, depthMode, colorMode, true, frameRenderContext);\n}\n\nfunction drawFillTiles(\n    tileManager: TileManager,\n    layer: FillStyleLayer,\n    coords: OverscaledTileID[],\n    depthMode: Readonly<DepthMode>,\n    colorMode: Readonly<ColorMode>,\n    isOutline: boolean,\n    frameRenderContext: FrameRenderContext) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const fillPropertyName = 'fill-pattern';\n    const patternProperty = layer.paint.get(fillPropertyName);\n    const image = patternProperty?.constantOr(1 as any);\n    const crossfade = layer.getCrossfadeParameters();\n    let drawMode, programName, uniformValues, indexBuffer, segments;\n\n    const transform = frameRenderContext.transform;\n\n    const propertyFillTranslate = layer.paint.get('fill-translate');\n    const propertyFillTranslateAnchor = layer.paint.get('fill-translate-anchor');\n\n    if (!isOutline) {\n        programName = image ? 'fillPattern' : 'fill';\n        drawMode = gl.TRIANGLES;\n    } else {\n        programName = image && !layer.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline';\n        drawMode = gl.LINES;\n    }\n\n    const constantPattern = patternProperty.constantOr(null);\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n        if (image && !tile.patternsLoaded()) continue;\n\n        const bucket: FillBucket = (tile.getBucket(layer) as any);\n        if (!bucket) continue;\n\n        const isSdfPattern = bucket.sdfPatterns[layer.id] ?? false;\n        const programConfiguration = bucket.programConfigurations.get(layer.id);\n        const program = frameRenderContext.useProgram(programName, programConfiguration);\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n\n        if (image) {\n            context.activeTexture.set(gl.TEXTURE0);\n            tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n            programConfiguration.updatePaintBuffers(crossfade);\n        }\n\n        updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer);\n\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord);\n\n        const translateForUniforms = translatePosition(transform, tile, propertyFillTranslate, propertyFillTranslateAnchor);\n\n        if (!isOutline) {\n            indexBuffer = bucket.indexBuffer;\n            segments = bucket.segments;\n            uniformValues = image ? fillPatternUniformValues(transform, crossfade, tile, translateForUniforms, isSdfPattern) : fillUniformValues(translateForUniforms);\n        } else {\n            indexBuffer = bucket.indexBuffer2;\n            segments = bucket.segments2;\n            uniformValues = (programName === 'fillOutlinePattern' && image) ?\n                fillOutlinePatternUniformValues(transform, crossfade, tile, translateForUniforms, isSdfPattern) :\n                fillOutlineUniformValues(translateForUniforms);\n        }\n\n        const stencil = frameRenderContext.stencilModeForClipping(coord);\n\n        program.draw(context, drawMode, depthMode,\n            stencil, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData,\n            layer.id, bucket.layoutVertexBuffer, indexBuffer, segments,\n            layer.paint, frameRenderContext.transform.zoom, programConfiguration);\n    }\n}\n", "import {DepthMode} from '../depth_mode.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {ColorMode} from '../color_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {\n    fillExtrusionUniformValues,\n    fillExtrusionPatternUniformValues,\n} from '../program/fill_extrusion_program.ts';\nimport {updatePatternPositionsInProgram} from '../../render/update_pattern_positions_in_program.ts';\nimport {translatePosition} from '../../util/util.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {FillExtrusionStyleLayer} from '../../style/style_layer/fill_extrusion_style_layer.ts';\nimport type {FillExtrusionBucket} from '../../data/bucket/fill_extrusion_bucket.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport function drawFillExtrusion(tileManager: TileManager, layer: FillExtrusionStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    const opacity = layer.paint.get('fill-extrusion-opacity');\n    if (opacity === 0) {\n        return;\n    }\n\n    if (frameRenderContext.currentPass === 'translucent') {\n        const depthMode = new DepthMode(frameRenderContext.context.gl.LEQUAL, DepthMode.ReadWrite, frameRenderContext.depthRangeFor3D);\n\n        if (opacity === 1 && !layer.paint.get('fill-extrusion-pattern').constantOr(1 as any)) {\n            const colorMode = frameRenderContext.colorModeForRenderPass();\n            drawExtrusionTiles(tileManager, layer, coords, depthMode, StencilMode.disabled, colorMode, frameRenderContext);\n\n        } else {\n            // Draw transparent buildings in two passes so that only the closest surface is drawn.\n            // First draw all the extrusions into only the depth buffer. No colors are drawn.\n            drawExtrusionTiles(tileManager, layer, coords, depthMode,\n                StencilMode.disabled,\n                ColorMode.disabled, frameRenderContext);\n\n            // Then draw all the extrusions a second type, only coloring fragments if they have the\n            // same depth value as the closest fragment in the previous pass. Use the stencil buffer\n            // to prevent the second draw in cases where we have coincident polygons.\n            drawExtrusionTiles(tileManager, layer, coords, depthMode,\n                frameRenderContext.stencilModeFor3D(),\n                frameRenderContext.colorModeForRenderPass(), frameRenderContext);\n        }\n    }\n}\n\nfunction drawExtrusionTiles(\n    tileManager: TileManager,\n    layer: FillExtrusionStyleLayer,\n    coords: OverscaledTileID[],\n    depthMode: DepthMode,\n    stencilMode: Readonly<StencilMode>,\n    colorMode: Readonly<ColorMode>,\n    frameRenderContext: FrameRenderContext) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const fillPropertyName = 'fill-extrusion-pattern';\n    const patternProperty = layer.paint.get(fillPropertyName);\n    const image = patternProperty.constantOr(1 as any);\n    const crossfade = layer.getCrossfadeParameters();\n    const opacity = layer.paint.get('fill-extrusion-opacity');\n    const constantPattern = patternProperty.constantOr(null);\n    const transform = frameRenderContext.transform;\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n        const bucket: FillExtrusionBucket = (tile.getBucket(layer) as any);\n        if (!bucket) continue;\n\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n        const programConfiguration = bucket.programConfigurations.get(layer.id);\n        const program = frameRenderContext.useProgram(image ? 'fillExtrusionPattern' : 'fillExtrusion', programConfiguration);\n\n        if (image) {\n            context.activeTexture.set(gl.TEXTURE0);\n            tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n            programConfiguration.updatePaintBuffers(crossfade);\n        }\n\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord);\n        updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer);\n\n        const translate = translatePosition(\n            transform,\n            tile,\n            layer.paint.get('fill-extrusion-translate'),\n            layer.paint.get('fill-extrusion-translate-anchor')\n        );\n\n        const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient');\n        const uniformValues = image ?\n            fillExtrusionPatternUniformValues(transform, frameRenderContext.data.light, shouldUseVerticalGradient, opacity, translate, coord, crossfade, tile) :\n            fillExtrusionUniformValues(transform, frameRenderContext.data.light, shouldUseVerticalGradient, opacity, translate);\n\n        program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW,\n            uniformValues, terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n            bucket.segments, layer.paint, frameRenderContext.transform.zoom,\n            programConfiguration, frameRenderContext.terrain && bucket.centroidVertexBuffer);\n    }\n}\n", "import {Texture} from '../texture.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {\n    hillshadeUniformValues,\n    hillshadeUniformPrepareValues\n} from '../program/hillshade_program.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {ColorMode} from '../color_mode.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {HillshadeStyleLayer} from '../../style/style_layer/hillshade_style_layer.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport function drawHillshade(painter: Painter, tileManager: TileManager, layer: HillshadeStyleLayer, tileIDs: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (frameRenderContext.currentPass !== 'offscreen' && frameRenderContext.currentPass !== 'translucent') return;\n\n    const context = frameRenderContext.context;\n    const {useSubdivision} = frameRenderContext.data;\n\n    const depthMode = frameRenderContext.getDepthModeForSublayer(0, DepthMode.ReadOnly);\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n\n    if (frameRenderContext.currentPass === 'offscreen') {\n        // Prepare tiles\n        prepareHillshade(painter, tileManager, tileIDs, layer, depthMode, StencilMode.disabled, colorMode, frameRenderContext);\n        context.viewport.set([0, 0, painter.width, painter.height]);\n    } else if (frameRenderContext.currentPass === 'translucent') {\n        // Globe (or any projection with subdivision) needs two-pass rendering to avoid artifacts when rendering texture tiles.\n        // See comments in draw_raster.ts for more details.\n        if (useSubdivision) {\n            // Two-pass rendering\n            const [stencilBorderless, stencilBorders, coords] = frameRenderContext.stencilConfigForOverlapTwoPass(tileIDs);\n            renderHillshade(tileManager, layer, coords, stencilBorderless, depthMode, colorMode, false, frameRenderContext); // draw without borders\n            renderHillshade(tileManager, layer, coords, stencilBorders, depthMode, colorMode, true, frameRenderContext); // draw with borders\n        } else {\n            // Simple rendering\n            const [stencil, coords] = frameRenderContext.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);\n            renderHillshade(tileManager, layer, coords, stencil, depthMode, colorMode, false, frameRenderContext);\n        }\n    }\n}\n\nfunction renderHillshade(\n    tileManager: TileManager,\n    layer: HillshadeStyleLayer,\n    coords: OverscaledTileID[],\n    stencilModes: {[_: number]: Readonly<StencilMode>},\n    depthMode: Readonly<DepthMode>,\n    colorMode: Readonly<ColorMode>,\n    useBorder: boolean,\n    frameRenderContext: FrameRenderContext\n) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n\n    const defines = [`#define NUM_ILLUMINATION_SOURCES ${layer.paint.get('hillshade-highlight-color').values.length}`];\n    const program = frameRenderContext.useProgram('hillshade', null, false, defines);\n    const align = !frameRenderContext.data.moving;\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n        const fbo = tile.fbo;\n        if (!fbo) {\n            continue;\n        }\n        const mesh = frameRenderContext.getMeshFromTileID(coord.canonical, useBorder, true, 'raster');\n\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n\n        context.activeTexture.set(gl.TEXTURE0);\n        gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord, {aligned: align});\n\n        program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.backCCW,\n            hillshadeUniformValues(frameRenderContext.transform, tile, layer), terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n    }\n}\n\n// hillshade rendering is done in two steps. the prepare step first calculates the slope of the terrain in the x and y\n// directions for each pixel, and saves those values to a framebuffer texture in the r and g channels.\nfunction prepareHillshade(\n    painter: Painter,\n    tileManager: TileManager,\n    tileIDs: OverscaledTileID[],\n    layer: HillshadeStyleLayer,\n    depthMode: Readonly<DepthMode>,\n    stencilMode: Readonly<StencilMode>,\n    colorMode: Readonly<ColorMode>,\n    frameRenderContext: FrameRenderContext) {\n\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n\n    const textureFilter = layer.paint.get('resampling') === 'nearest' ?  gl.NEAREST : gl.LINEAR;\n\n    for (const coord of tileIDs) {\n        const tile = tileManager.getTile(coord);\n        const dem = tile.dem;\n\n        if (!dem?.data) {\n            continue;\n        }\n\n        if (!tile.needsHillshadePrepare) {\n            continue;\n        }\n\n        const hillshadeTextureSize = dem.dim + 2;\n        const textureStride = dem.stride;\n\n        const pixelData = dem.getPixels();\n        context.activeTexture.set(gl.TEXTURE1);\n\n        context.pixelStoreUnpackPremultiplyAlpha.set(false);\n        tile.demTexture ||= painter.getTileTexture(textureStride);\n        if (tile.demTexture) {\n            const demTexture = tile.demTexture;\n            demTexture.update(pixelData, {premultiply: false});\n            demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n        } else {\n            tile.demTexture = new Texture(context, pixelData, gl.RGBA, {premultiply: false});\n            tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n        }\n\n        context.activeTexture.set(gl.TEXTURE0);\n\n        let fbo = tile.fbo;\n\n        if (!fbo) {\n            const renderTexture = new Texture(context, {width: hillshadeTextureSize, height: hillshadeTextureSize, data: null}, gl.RGBA);\n            renderTexture.bind(textureFilter, gl.CLAMP_TO_EDGE);\n\n            fbo = tile.fbo = context.createFramebuffer(hillshadeTextureSize, hillshadeTextureSize, true, false);\n            fbo.colorAttachment.set(renderTexture.texture);\n        }\n\n        context.bindFramebuffer.set(fbo.framebuffer);\n        context.viewport.set([0, 0, hillshadeTextureSize, hillshadeTextureSize]);\n\n        frameRenderContext.useProgram('hillshadePrepare').draw(context, gl.TRIANGLES,\n            depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n            hillshadeUniformPrepareValues(frameRenderContext.transform, tile.tileID, dem),\n            null, null, layer.id, painter.rasterBoundsBuffer,\n            painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n\n        tile.needsHillshadePrepare = false;\n    }\n}\n", "import {Texture} from '../texture.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {\n    colorReliefUniformValues\n} from '../program/color_relief_program.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {ColorMode} from '../color_mode.ts';\nimport type {StencilMode} from '../stencil_mode.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {ColorReliefStyleLayer} from '../../style/style_layer/color_relief_style_layer.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nexport function drawColorRelief(painter: Painter, tileManager: TileManager, layer: ColorReliefStyleLayer, tileIDs: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (frameRenderContext.currentPass !== 'translucent') return;\n    if (!tileIDs.length) return;\n\n    const {useSubdivision} = frameRenderContext.data;\n\n    const depthMode = frameRenderContext.getDepthModeForSublayer(0, DepthMode.ReadOnly);\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n\n    // Globe (or any projection with subdivision) needs two-pass rendering to avoid artifacts when rendering texture tiles.\n    // See comments in draw_raster.ts for more details.\n    if (useSubdivision) {\n        // Two-pass rendering\n        const [stencilBorderless, stencilBorders, coords] = frameRenderContext.stencilConfigForOverlapTwoPass(tileIDs);\n        renderColorRelief(painter, tileManager, layer, coords, stencilBorderless, depthMode, colorMode, false, frameRenderContext); // draw without borders\n        renderColorRelief(painter, tileManager, layer, coords, stencilBorders, depthMode, colorMode, true, frameRenderContext); // draw with borders\n    } else {\n        // Simple rendering\n        const [stencil, coords] = frameRenderContext.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);\n        renderColorRelief(painter, tileManager, layer, coords, stencil, depthMode, colorMode, false, frameRenderContext);\n    }\n}\n\nlet textureMaxSize = 0;\n/**\n * Draws the color-relief tiles of one pass.\n *\n * A loaded raster-DEM tile can carry no DEM at all (e.g. an empty 204 response);\n * such tiles are skipped before the first-tile setup reads from them.\n */\nfunction renderColorRelief(\n    painter: Painter,\n    tileManager: TileManager,\n    layer: ColorReliefStyleLayer,\n    coords: OverscaledTileID[],\n    stencilModes: {[_: number]: Readonly<StencilMode>},\n    depthMode: Readonly<DepthMode>,\n    colorMode: Readonly<ColorMode>,\n    useBorder: boolean,\n    frameRenderContext: FrameRenderContext\n) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const program = frameRenderContext.useProgram('colorRelief');\n    const align = !frameRenderContext.data.moving;\n\n    const textureFilter = layer.paint.get('resampling') === 'nearest' ?  gl.NEAREST : gl.LINEAR;\n\n    let firstTile = true;\n    let colorRampSize = 0;\n\n    for (const coord of coords) {\n        const tile = tileManager.getTile(coord);\n        const dem = tile.dem;\n        if (!dem?.data) {\n            continue;\n        }\n        if(firstTile) {\n            // we should avoid calling gl.getParameter at runtime (GPU stall risk)\n            textureMaxSize ||= gl.getParameter(gl.MAX_TEXTURE_SIZE);\n            const maxLength = textureMaxSize;\n            const {elevationTexture, colorTexture} = layer.getColorRampTextures(context, maxLength, dem.getUnpackVector());\n            context.activeTexture.set(gl.TEXTURE1);\n            elevationTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n            context.activeTexture.set(gl.TEXTURE4);\n            colorTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n            firstTile = false;\n            colorRampSize = elevationTexture.size[0];\n        }\n\n        const textureStride = dem.stride;\n\n        context.activeTexture.set(gl.TEXTURE0);\n\n        if (!tile.demTexture || tile.needsColorReliefPrepare) {\n            context.pixelStoreUnpackPremultiplyAlpha.set(false);\n            tile.demTexture ||= painter.getTileTexture(textureStride) ??\n                new Texture(context, {width: textureStride, height: textureStride, data: null}, gl.RGBA);\n            tile.demTexture.update(dem.getPixels(), {premultiply: false});\n            tile.needsColorReliefPrepare = false;\n        }\n        tile.demTexture.bind(textureFilter, gl.CLAMP_TO_EDGE);\n\n        const mesh = frameRenderContext.getMeshFromTileID(coord.canonical, useBorder, true, 'raster');\n\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord, {aligned: align});\n\n        program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.backCCW,\n            colorReliefUniformValues(layer, tile.dem, colorRampSize), terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n    }\n}\n", "import {clamp} from '../../util/util.ts';\nimport {ImageSource} from '../../source/image_source.ts';\nimport {now} from '../../util/time_control.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {\n    bilinearImageWarp,\n    rasterUniformValues,\n    type RasterImageWarp\n} from '../program/raster_program.ts';\nimport {EXTENT} from '../../data/extent.ts';\nimport {FadingDirections} from '../../tile/tile.ts';\nimport Point from '@mapbox/point-geometry';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {RasterStyleLayer} from '../../style/style_layer/raster_style_layer.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {Mesh} from '../../render/mesh.ts';\n\ntype FadeProperties = {\n    parentTile: Tile;\n    parentScaleBy: number;\n    parentTopLeft: [number, number];\n    fadeValues: FadeValues;\n};\n\ntype FadeValues = {\n    tileOpacity: number;\n    parentTileOpacity?: number;\n    fadeMix: {opacity: number; mix: number};\n};\n\nconst cornerCoords = [\n    new Point(0, 0),\n    new Point(EXTENT, 0),\n    new Point(EXTENT, EXTENT),\n    new Point(0, EXTENT),\n];\n\nexport function drawRaster(tileManager: TileManager, layer: RasterStyleLayer, tileIDs: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (frameRenderContext.currentPass !== 'translucent') return;\n    if (layer.paint.get('raster-opacity') === 0) return;\n    if (!tileIDs.length) return;\n\n    const source = tileManager.getSource();\n\n    const {useSubdivision} = frameRenderContext.data;\n\n    // When rendering globe (or any other subdivided projection), two passes are needed.\n    // Subdivided tiles with different granularities might have tiny gaps between them.\n    // To combat this, tile meshes for globe have a slight border region.\n    // However tiles borders will overlap, and a part of a tile often\n    // gets hidden by its neighbour's border, which displays an ugly stretched texture.\n    // To both hide the border stretch and avoid tiny gaps, tiles are first drawn without borders (with gaps),\n    // and then any missing pixels (gaps, not marked in stencil) get overdrawn with tile borders.\n    // This approach also avoids pixel shader overdraw, as any pixel is drawn at most once.\n\n    // Stencil mask and two-pass is not used for ImageSource sources regardless of projection.\n    if (source instanceof ImageSource) {\n        // Image source - no stencil is used\n        drawTiles(tileManager, layer, tileIDs, null, false, false, source.tileCoords, source.imageWarp, source.flippedWindingOrder, frameRenderContext, source.getMesh(frameRenderContext.context, useSubdivision));\n    } else if (useSubdivision) {\n        // Two-pass rendering\n        const [stencilBorderless, stencilBorders, coords] = frameRenderContext.stencilConfigForOverlapTwoPass(tileIDs);\n        drawTiles(tileManager, layer, coords, stencilBorderless, false, true, cornerCoords, bilinearImageWarp, false, frameRenderContext); // draw without borders\n        drawTiles(tileManager, layer, coords, stencilBorders, true, true, cornerCoords, bilinearImageWarp, false, frameRenderContext); // draw with borders\n    } else {\n        // Simple rendering\n        const [stencil, coords] = frameRenderContext.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);\n        drawTiles(tileManager, layer, coords, stencil, false, true, cornerCoords, bilinearImageWarp, false, frameRenderContext);\n    }\n}\n\nfunction drawTiles(\n    tileManager: TileManager,\n    layer: RasterStyleLayer,\n    coords: OverscaledTileID[],\n    stencilModes: {[_: number]: Readonly<StencilMode>} | null,\n    useBorder: boolean,\n    allowPoles: boolean,\n    corners: Point[],\n    imageWarp: RasterImageWarp,\n    flipCullfaceMode: boolean = false,\n    frameRenderContext: FrameRenderContext,\n    sourceMesh: Mesh | null = null) {\n    const minTileZ = coords[coords.length - 1].overscaledZ;\n\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const program = frameRenderContext.useProgram('raster');\n\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n    const align = !frameRenderContext.data.moving;\n    const rasterOpacity = layer.paint.get('raster-opacity');\n    const useNearest = layer.paint.get('resampling') === 'nearest' || layer.paint.get('raster-resampling') === 'nearest';\n    const textureFilter = useNearest ?  gl.NEAREST : gl.LINEAR;\n    const fadeDuration = layer.paint.get('raster-fade-duration');\n    const isTerrain = !!frameRenderContext.terrain;\n\n    // Draw all tiles\n    for (const coord of coords) {\n        // Set the lower zoom level to sublayer 0, and higher zoom levels to higher sublayers\n        // Use gl.LESS to prevent double drawing in areas where tiles overlap.\n        const depthMode = frameRenderContext.getDepthModeForSublayer(coord.overscaledZ - minTileZ,\n            rasterOpacity === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS);\n\n        const tile = tileManager.getTile(coord);\n\n        // create and bind first texture\n        context.activeTexture.set(gl.TEXTURE0);\n        tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n\n        // create second texture - use either the current tile or fade tile to bind second texture below\n        context.activeTexture.set(gl.TEXTURE1);\n        const {parentTile, parentScaleBy, parentTopLeft, fadeValues} = getFadeProperties(tile, tileManager, fadeDuration, isTerrain);\n        tile.fadeOpacity = fadeValues.tileOpacity;\n        if (parentTile) {\n            parentTile.fadeOpacity = fadeValues.parentTileOpacity;\n            parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n        } else {\n            tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n        }\n\n        // Enable anisotropic filtering only when the pitch is greater than the threshold pitch.\n        // The default threshold is 20 degrees to preserve image sharpness on flat or slightly tilted maps.\n        if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && frameRenderContext.transform.pitch > frameRenderContext.data.anisotropicFilterPitch) {\n            gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,\n                context.extTextureFilterAnisotropicMax);\n        }\n\n        const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n        const projectionData = frameRenderContext.getProjectionDataForTile(coord, {aligned: align});\n        const uniformValues = rasterUniformValues(parentTopLeft, parentScaleBy, fadeValues.fadeMix, layer, corners, imageWarp);\n\n        const mesh = sourceMesh ?? frameRenderContext.getMeshFromTileID(coord.canonical, useBorder, allowPoles, 'raster');\n        const stencilMode = stencilModes ? stencilModes[coord.overscaledZ] : StencilMode.disabled;\n\n        program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, flipCullfaceMode ? CullFaceMode.frontCCW : CullFaceMode.backCCW,\n            uniformValues, terrainData, projectionData, layer.id, mesh.vertexBuffer,\n            mesh.indexBuffer, mesh.segments);\n    }\n}\n\n/**\n * Get fade properties for current tile - either cross-fading or self-fading properties.\n */\nfunction getFadeProperties(tile: Tile, tileManager: TileManager, fadeDuration: number, isTerrain: boolean): FadeProperties {\n    const defaults: FadeProperties = {\n        parentTile: null,\n        parentScaleBy: 1,\n        parentTopLeft: [0, 0],\n        fadeValues: {tileOpacity: 1, parentTileOpacity: 1, fadeMix: {opacity: 1, mix: 0}}\n    };\n\n    if (fadeDuration === 0 || isTerrain) return defaults;\n\n    // cross-fade with parent first if available\n    if (tile.fadingParentID) {\n        const parentTile = tileManager.getLoadedTile(tile.fadingParentID);\n        if (!parentTile) return defaults;\n\n        const parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ);\n        const parentTopLeft: [number, number] = [\n            (tile.tileID.canonical.x * parentScaleBy) % 1,\n            (tile.tileID.canonical.y * parentScaleBy) % 1\n        ];\n\n        const fadeValues = getCrossFadeValues(tile, parentTile, fadeDuration);\n        return {parentTile, parentScaleBy, parentTopLeft, fadeValues};\n    }\n\n    // self-fade for edge tiles\n    if (tile.selfFading) {\n        const fadeValues = getSelfFadeValues(tile, fadeDuration);\n        return {parentTile: null, parentScaleBy: 1, parentTopLeft: [0, 0], fadeValues};\n    }\n\n    return defaults;\n}\n\n/**\n * Cross-fade values for a base tile with a parent tile (for zooming in/out)\n */\nfunction getCrossFadeValues(tile: Tile, parentTile: Tile, fadeDuration: number): FadeValues {\n    const currentTime = now();\n\n    const timeSinceTile = (currentTime - tile.timeAdded) / fadeDuration;\n    const timeSinceParent = (currentTime - parentTile.timeAdded) / fadeDuration;\n\n    // get fading opacity based on current fade direction\n    const doFadeIn = (tile.fadingDirection === FadingDirections.Incoming);\n    const opacity1 = clamp(timeSinceTile, 0, 1);\n    const opacity2 = clamp(1 - timeSinceParent, 0, 1);\n\n    const tileOpacity = doFadeIn ? opacity1 : opacity2;\n    const parentTileOpacity = doFadeIn ? opacity2 : opacity1;\n    const fadeMix = {\n        opacity: 1,\n        mix: 1 - tileOpacity\n    };\n\n    return {tileOpacity, parentTileOpacity, fadeMix};\n}\n\n/**\n * Simple fade-in values for tile without a parent (i.e. edge tiles)\n */\nfunction getSelfFadeValues(tile: Tile, fadeDuration: number): FadeValues {\n    const currentTime = now();\n\n    const timeSinceTile = (currentTime - tile.timeAdded) / fadeDuration;\n    const tileOpacity = clamp(timeSinceTile, 0, 1);\n    const fadeMix = {\n        opacity: tileOpacity,\n        mix: 0\n    };\n\n    return {tileOpacity, fadeMix};\n}\n", "import {StencilMode} from '../stencil_mode.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {\n    backgroundUniformValues,\n    backgroundPatternUniformValues\n} from '../program/background_program.ts';\nimport {coveringTiles} from '../../geo/projection/covering_tiles.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {BackgroundStyleLayer} from '../../style/style_layer/background_style_layer.ts';\n\nexport function drawBackground(painter: Painter, tileManager: TileManager, layer: BackgroundStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    const color = layer.paint.get('background-color');\n    const opacity = layer.paint.get('background-opacity');\n\n    if (opacity === 0) return;\n\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const transform = frameRenderContext.transform;\n    const tileSize = transform.tileSize;\n    const image = layer.paint.get('background-pattern');\n\n    if (painter.patternAtlas.isPatternMissing(image)) return;\n\n    const pass = (!image && color.a === 1 && opacity === 1 && frameRenderContext.opaquePassEnabledForLayer()) ? 'opaque' : 'translucent';\n    if (frameRenderContext.currentPass !== pass) return;\n\n    const stencilMode = StencilMode.disabled;\n    const depthMode = frameRenderContext.getDepthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n    const program = frameRenderContext.useProgram(image ? 'backgroundPattern' : 'background');\n    const tileIDs = coords ? coords : coveringTiles(transform, {tileSize, terrain: frameRenderContext.terrain});\n\n    if (image) {\n        context.activeTexture.set(gl.TEXTURE0);\n        painter.patternAtlas.bind(context);\n    }\n\n    const crossfade = layer.getCrossfadeParameters();\n    \n    for (const tileID of tileIDs) {\n        const projectionData = frameRenderContext.getProjectionDataForTile(tileID);\n\n        const uniformValues = image ?\n            backgroundPatternUniformValues(opacity, painter.patternAtlas, transform, image, {tileID, tileSize}, crossfade) :\n            backgroundUniformValues(opacity, color);\n        const terrainData = frameRenderContext.getTerrainDataForTile(tileID);\n\n        // For globe rendering, background uses tile meshes *without* borders and no stencil clipping.\n        // This works assuming the tileIDs list contains only tiles of the same zoom level.\n        // This seems to always be the case for background layers, but I'm leaving this comment\n        // here in case this assumption is false in the future.\n\n        // In case background starts having tiny holes at tile boundaries, switch to meshes with borders\n        // and also enable stencil clipping. Make sure to render a proper tile clipping mask into stencil\n        // first though, as that doesn't seem to happen for background layers as of writing this.\n\n        const mesh = frameRenderContext.getMeshFromTileID(tileID.canonical, false, true, 'raster');\n        program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW,\n            uniformValues, terrainData, projectionData, layer.id,\n            mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n    }\n}\n", "import {DepthMode} from '../depth_mode.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {debugUniformValues} from '../program/debug_program.ts';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {ColorMode} from '../color_mode.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {Style} from '../../style/style.ts';\nimport type {Painter} from '../../render/painter.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {OverscaledTileID} from '../../tile/tile_id.ts';\n\nconst topColor = new Color(1, 0, 0, 1);\nconst btmColor = new Color(0, 1, 0, 1);\nconst leftColor = new Color(0, 0, 1, 1);\nconst rightColor = new Color(1, 0, 1, 1);\nconst centerColor = new Color(0, 1, 1, 1);\n\nexport function drawDebugPadding(frameRenderContext: FrameRenderContext): void {\n    const padding = frameRenderContext.transform.padding;\n    const lineWidth = 3;\n    // Top\n    drawHorizontalLine(frameRenderContext, frameRenderContext.transform.height - (padding.top || 0), lineWidth, topColor);\n    // Bottom\n    drawHorizontalLine(frameRenderContext, padding.bottom || 0, lineWidth, btmColor);\n    // Left\n    drawVerticalLine(frameRenderContext, padding.left || 0, lineWidth, leftColor);\n    // Right\n    drawVerticalLine(frameRenderContext, frameRenderContext.transform.width - (padding.right || 0), lineWidth, rightColor);\n    // Center\n    const center = frameRenderContext.transform.centerPoint;\n    drawCrosshair(frameRenderContext, center.x, frameRenderContext.transform.height - center.y, centerColor);\n}\n\nfunction drawCrosshair(frameRenderContext: FrameRenderContext, x: number, y: number, color: Color) {\n    const size = 20;\n    const lineWidth = 2;\n    //Vertical line\n    drawDebugSSRect(frameRenderContext, x - lineWidth / 2, y - size / 2, lineWidth, size, color);\n    //Horizontal line\n    drawDebugSSRect(frameRenderContext, x - size / 2, y - lineWidth / 2, size, lineWidth, color);\n}\n\nfunction drawHorizontalLine(frameRenderContext: FrameRenderContext, y: number, lineWidth: number, color: Color) {\n    drawDebugSSRect(frameRenderContext, 0, y  + lineWidth / 2, frameRenderContext.transform.width,  lineWidth, color);\n}\n\nfunction drawVerticalLine(frameRenderContext: FrameRenderContext, x: number, lineWidth: number, color: Color) {\n    drawDebugSSRect(frameRenderContext, x - lineWidth / 2, 0, lineWidth,  frameRenderContext.transform.height, color);\n}\n\nfunction drawDebugSSRect(frameRenderContext: FrameRenderContext, x: number, y: number, width: number, height: number, color: Color) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const pixelRatio = frameRenderContext.data.pixelRatio;\n\n    gl.enable(gl.SCISSOR_TEST);\n    gl.scissor(x * pixelRatio, y * pixelRatio, width * pixelRatio, height * pixelRatio);\n    context.clear({color});\n    gl.disable(gl.SCISSOR_TEST);\n}\n\nexport function drawDebug(painter: Painter, tileManager: TileManager, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    for (const coord of coords) {\n        drawDebugTile(painter, tileManager, coord, frameRenderContext);\n    }\n}\n\nfunction drawDebugTile(painter: Painter, tileManager: TileManager, coord: OverscaledTileID, frameRenderContext: FrameRenderContext) {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n\n    const program = frameRenderContext.useProgram('debug');\n\n    const depthMode = DepthMode.disabled;\n    const stencilMode = StencilMode.disabled;\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n    const id = '$debug';\n    const terrainData = frameRenderContext.getTerrainDataForTile(coord);\n\n    context.activeTexture.set(gl.TEXTURE0);\n\n    const tileRawData = tileManager.getTileByID(coord.key).latestRawTileData;\n    const tileByteLength = (tileRawData?.byteLength) || 0;\n    const tileSizeKb = Math.floor(tileByteLength / 1024);\n    const tileSize = tileManager.getTile(coord).tileSize;\n    const scaleRatio = (512 / Math.min(tileSize, 512) * (coord.overscaledZ / frameRenderContext.transform.zoom)) * 0.5;\n    let tileIdText = coord.canonical.toString();\n    if (coord.overscaledZ !== coord.canonical.z) {\n        tileIdText += ` => ${coord.overscaledZ}`;\n    }\n    const tileLabel = `${tileIdText} ${tileSizeKb}kB`;\n    drawTextToOverlay(painter, tileLabel);\n\n    const projectionData = frameRenderContext.getProjectionDataForTile(coord);\n\n    program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled,\n        debugUniformValues(Color.transparent, scaleRatio), null, projectionData, id,\n        painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments);\n    program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n        debugUniformValues(Color.red), terrainData, projectionData, id,\n        painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments);\n}\n\nfunction drawTextToOverlay(painter: Painter, text: string) {\n    painter.initDebugOverlayCanvas();\n    const canvas = painter.debugOverlayCanvas;\n    const gl = painter.context.gl;\n    const ctx2d = painter.debugOverlayCanvas.getContext('2d');\n    ctx2d.clearRect(0, 0, canvas.width, canvas.height);\n\n    ctx2d.shadowColor = 'white';\n    ctx2d.shadowBlur = 2;\n    ctx2d.lineWidth = 1.5;\n    ctx2d.strokeStyle = 'white';\n    ctx2d.textBaseline = 'top';\n    ctx2d.font = `bold ${36}px Open Sans, sans-serif`;\n    ctx2d.fillText(text, 5, 5);\n    ctx2d.strokeText(text, 5, 5);\n\n    painter.debugOverlayTexture.update(canvas);\n    painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n}\n\nexport function selectDebugSource(style: Style, zoom: number): TileManager | null {\n    // Use vector source with highest maxzoom\n    // Else use source with highest maxzoom of any type\n    let selectedSource: TileManager = null;\n    const layers = Object.values(style._layers);\n    const sources = layers.flatMap((layer) => {\n        if (layer.source && !layer.isHidden(zoom)) {\n            const tileManager = style.tileManagers[layer.source];\n            return [tileManager];\n        } else {\n            return [];\n        }\n    });\n    const vectorSources = sources.filter((source) => source.getSource().type === 'vector');\n    const otherSources = sources.filter((source) => source.getSource().type !== 'vector');\n    const considerSource = (source: TileManager) => {\n        if (!selectedSource || (selectedSource.getSource().maxzoom < source.getSource().maxzoom)) {\n            selectedSource = source;\n        }\n    };\n    for (const source of vectorSources) {\n        considerSource(source);\n    }\n    if (!selectedSource) {\n        for (const source of otherSources) {\n            considerSource(source);\n        }\n    }\n    return selectedSource;\n}\n", "import {StencilMode} from '../stencil_mode.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {terrainUniformValues, terrainDepthUniformValues, terrainHeightUniformValues} from '../program/terrain_program.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {ColorMode} from '../color_mode.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {Terrain, TerrainHeightMapTarget} from '../../render/terrain.ts';\nimport type {Tile} from '../../tile/tile.ts';\nimport type {Painter} from '../../render/painter.ts';\n\n/**\n * Redraw the Depth Framebuffer\n * @param painter - the painter\n * @param terrain - the terrain\n * @param frameRenderContext - shared state for the current render\n */\nfunction drawDepth(painter: Painter, terrain: Terrain, frameRenderContext: FrameRenderContext): void {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const tr = frameRenderContext.transform;\n    const colorMode = ColorMode.unblended;\n    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);\n    const tiles = terrain.tileManager.getRenderableTiles();\n    const program = frameRenderContext.useProgram('terrainDepth');\n    context.bindFramebuffer.set(terrain.getFramebuffer().framebuffer);\n    context.viewport.set([0, 0, painter.width  / devicePixelRatio, painter.height / devicePixelRatio]);\n    context.clear({color: Color.white, depth: 1});\n    for (const tile of tiles) {\n        const mesh = terrain.getTerrainMesh(tile.tileID, frameRenderContext.data.isRenderingGlobe);\n        const terrainData = terrain.getTerrainData(tile.tileID);\n        const projectionData = tr.getProjectionData({overscaledTileID: tile.tileID, applyTerrainMatrix: false, applyGlobeMatrix: true});\n        const uniformValues = terrainDepthUniformValues(terrain.getSkirtLength(tr.zoom));\n        program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n    }\n    context.bindFramebuffer.set(null);\n    context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction drawTerrain(painter: Painter, terrain: Terrain, tiles: Tile[], frameRenderContext: FrameRenderContext): void {\n    const {isRenderingGlobe} = frameRenderContext.data;\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const tr = frameRenderContext.transform;\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n    const depthMode = frameRenderContext.getDepthModeFor3D();\n    const program = frameRenderContext.useProgram('terrain');\n\n    context.bindFramebuffer.set(null);\n    context.viewport.set([0, 0, painter.width, painter.height]);\n\n    for (const tile of tiles) {\n        const mesh = terrain.getTerrainMesh(tile.tileID, isRenderingGlobe);\n        const texture = painter.renderToTexture.getTexture(tile);\n        const terrainData = terrain.getTerrainData(tile.tileID);\n        context.activeTexture.set(gl.TEXTURE0);\n        texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_LINEAR);\n        const eleDelta = terrain.getSkirtLength(tr.zoom);\n        const fogMatrix = tr.calculateFogMatrix(tile.tileID.toUnwrapped());\n        const uniformValues = terrainUniformValues(eleDelta, fogMatrix, frameRenderContext.data.sky, tr.pitch, isRenderingGlobe);\n        const projectionData = frameRenderContext.getProjectionDataForTile(tile.tileID, {applyTerrainMatrix: false});\n        program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n    }\n}\n\n/**\n * Draws the elevation of the loaded renderable terrain tiles into a texture, see {@link CustomRenderMethodInput.renderTerrainHeightMap}.\n */\nfunction drawTerrainHeightMap(frameRenderContext: FrameRenderContext, terrain: Terrain, target: TerrainHeightMapTarget): void {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const [minX, minY, maxX, maxY] = target.bounds;\n    context.setDirty();\n    const framebuffer = terrain.getHeightMapFramebuffer(target.texture);\n    context.viewport.set([0, 0, target.width, target.height]);\n    context.clear({color: Color.transparent});\n\n    const program = frameRenderContext.useProgram('terrainHeight', null, true);\n    for (const tile of terrain.tileManager.getRenderableTiles()) {\n        const terrainData = terrain.getTerrainData(tile.tileID);\n        if (!terrainData.tile?.dem) continue;\n        const {canonical, wrap} = tile.tileID;\n        const tileSize = 1 / (1 << canonical.z);\n        const uniformValues = terrainHeightUniformValues([\n            (canonical.x * tileSize + wrap - minX) / (maxX - minX),\n            (canonical.y * tileSize - minY) / (maxY - minY),\n            tileSize / (maxX - minX),\n            tileSize / (maxY - minY)\n        ]);\n        const mesh = terrain.getTerrainMesh(tile.tileID, frameRenderContext.data.isRenderingGlobe);\n        program.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.unblended, CullFaceMode.disabled, uniformValues, terrainData, null, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n    }\n    framebuffer.colorAttachment.set(null);\n}\n\nexport {\n    drawTerrain,\n    drawDepth,\n    drawTerrainHeightMap\n};\n", "import {DepthMode} from '../depth_mode.ts';\nimport {StencilMode} from '../stencil_mode.ts';\nimport {OverscaledTileID} from '../../tile/tile_id.ts';\nimport {drawTerrainHeightMap} from './draw_terrain.ts';\n\nimport type {Painter} from '../../render/painter.ts';\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {TileManager} from '../../tile/tile_manager.ts';\nimport type {CustomLayerProjectionDataParams, CustomRenderMethodInput, CustomStyleLayer} from '../../style/style_layer/custom_style_layer.ts';\nimport type {TerrainHeightMapTarget} from '../../render/terrain.ts';\n\nexport function drawCustom(painter: Painter, tileManager: TileManager, layer: CustomStyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n    if (frameRenderContext.isRenderingToTexture) {\n        drawCustomTerrainTile(painter, layer, coords[0], frameRenderContext);\n        return;\n    }\n\n    const {isRenderingGlobe, projectionShaderVariant} = frameRenderContext.data;\n    const {terrain} = frameRenderContext;\n    const context = frameRenderContext.context;\n    const implementation = layer.implementation;\n    const transform = frameRenderContext.transform;\n\n    const projectionData = transform.getProjectionDataForCustomLayer(isRenderingGlobe);\n\n    const customLayerArgs: CustomRenderMethodInput = {\n        farZ: transform.farZ,\n        nearZ: transform.nearZ,\n        fov: transform.fov * Math.PI / 180, // fov converted to radians\n        modelViewProjectionMatrix: transform.modelViewProjectionMatrix,\n        projectionMatrix: transform.projectionMatrix,\n        shaderData: {\n            variantName: projectionShaderVariant.name,\n            vertexShaderPrelude: `const float PI = 3.141592653589793;\\nuniform mat4 u_projection_matrix;\\n${projectionShaderVariant.prelude.vertexSource}`,\n            define: projectionShaderVariant.define,\n        },\n        defaultProjectionData: projectionData,\n        getProjectionData: (params: CustomLayerProjectionDataParams) => {\n            return transform.getProjectionData({\n                overscaledTileID: new OverscaledTileID(\n                    params.tileID.canonical.z,\n                    params.tileID.wrap ?? 0,\n                    params.tileID.canonical.z,\n                    params.tileID.canonical.x,\n                    params.tileID.canonical.y,\n                ),\n                aligned: params.aligned,\n                applyGlobeMatrix: params.applyGlobeMatrix,\n                applyTerrainMatrix: params.applyTerrainMatrix,\n            });\n        },\n        renderTerrainHeightMap: terrain && frameRenderContext.currentPass === 'offscreen' ? (target: TerrainHeightMapTarget) => drawTerrainHeightMap(frameRenderContext, terrain, target) : undefined\n    };\n\n    const renderingMode = implementation.renderingMode ? implementation.renderingMode : '2d';\n\n    if (frameRenderContext.currentPass === 'offscreen') {\n        const prerender = implementation.prerender;\n        if (prerender) {\n            context.setCustomLayerDefaults();\n            context.setColorMode(frameRenderContext.colorModeForRenderPass());\n\n            prerender.call(implementation, context.gl, customLayerArgs);\n\n            context.setDirty();\n            painter.setBaseState();\n        }\n    } else if (frameRenderContext.currentPass === 'translucent') {\n\n        context.setCustomLayerDefaults();\n\n        context.setColorMode(frameRenderContext.colorModeForRenderPass());\n        context.setStencilMode(StencilMode.disabled);\n\n        const depthMode = renderingMode === '3d' ?\n            frameRenderContext.getDepthModeFor3D() :\n            frameRenderContext.getDepthModeForSublayer(0, DepthMode.ReadOnly);\n\n        context.setDepthMode(depthMode);\n\n        implementation.render(context.gl, customLayerArgs);\n\n        context.setDirty();\n        painter.setBaseState();\n        context.bindFramebuffer.set(null);\n    }\n}\n\n/**\n * Draws a custom layer into the terrain tile texture that is bound, see {@link CustomLayerInterface.renderToTerrainTile},\n * and binds that texture again for the layers after it.\n */\nfunction drawCustomTerrainTile(painter: Painter, layer: CustomStyleLayer, tileID: OverscaledTileID, frameRenderContext: FrameRenderContext): void {\n    const context = frameRenderContext.context;\n    const framebuffer = context.bindFramebuffer.get();\n    const viewport = context.viewport.get();\n\n    context.setCustomLayerDefaults();\n    context.setColorMode(frameRenderContext.colorModeForRenderPass());\n    context.setDepthMode(DepthMode.disabled);\n    context.setStencilMode(StencilMode.disabled);\n\n    layer.implementation.renderToTerrainTile(context.gl, {\n        tileID: {canonical: tileID.canonical, wrap: tileID.wrap},\n        width: viewport[2],\n        height: viewport[3]\n    });\n\n    context.setDirty();\n    painter.setBaseState();\n    context.bindFramebuffer.set(framebuffer);\n    context.viewport.set(viewport);\n}\n", "import {StencilMode} from '../stencil_mode.ts';\nimport {DepthMode} from '../depth_mode.ts';\nimport {CullFaceMode} from '../cull_face_mode.ts';\nimport {skyUniformValues} from '../program/sky_program.ts';\nimport {atmosphereUniformValues} from '../program/atmosphere_program.ts';\nimport {getAtmosphereAltitudeBlend, getGlobeCenterInViewSpace, getGlobeRadiusPixels} from '../../geo/projection/globe_utils.ts';\nimport {mat4, vec3} from 'gl-matrix';\nimport {ColorMode} from '../color_mode.ts';\nimport {sphericalToCartesian} from '../../util/util.ts';\n\nimport type {FrameRenderContext} from '../../render/frame_render_context.ts';\nimport type {LightPropsPossiblyEvaluated} from '../../style/light_properties.g.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {Mesh} from '../../render/mesh.ts';\n\nexport function drawSky(mesh: Mesh, frameRenderContext: FrameRenderContext): void {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const {sky, pixelRatio} = frameRenderContext.data;\n\n    const skyUniforms = skyUniformValues(sky, frameRenderContext.transform, pixelRatio);\n\n    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);\n    const stencilMode = StencilMode.disabled;\n    const colorMode = frameRenderContext.colorModeForRenderPass();\n    const program = frameRenderContext.useProgram('sky');\n\n    program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode,\n        CullFaceMode.disabled, skyUniforms, null, undefined, 'sky', mesh.vertexBuffer,\n        mesh.indexBuffer, mesh.segments);\n}\n\nfunction getSunPos(light: Readonly<LightPropsPossiblyEvaluated>, transform: IReadonlyTransform): vec3 {\n    const lightPos = sphericalToCartesian(light.position);\n    vec3.negate(lightPos, lightPos);\n\n    const lightMat = mat4.identity(new Float64Array(16));\n\n    if (light.anchor === 'map') {\n        mat4.rotateZ(lightMat, lightMat, transform.rollInRadians);\n        mat4.rotateX(lightMat, lightMat, -transform.pitchInRadians);\n        mat4.rotateZ(lightMat, lightMat, transform.bearingInRadians);\n        mat4.rotateX(lightMat, lightMat, transform.center.lat * Math.PI / 180.0);\n        mat4.rotateY(lightMat, lightMat, -transform.center.lng * Math.PI / 180.0);\n    }\n\n    vec3.transformMat4(lightPos, lightPos, lightMat);\n\n    return lightPos;\n}\n\nexport function drawAtmosphere(mesh: Mesh, frameRenderContext: FrameRenderContext): void {\n    const context = frameRenderContext.context;\n    const gl = context.gl;\n    const {sky, light} = frameRenderContext.data;\n    const program = frameRenderContext.useProgram('atmosphere');\n    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadOnly, [0, 1]);\n    const transform = frameRenderContext.transform;\n\n    const sunPos = getSunPos(light, transform);\n\n    const projectionData = transform.getProjectionData({overscaledTileID: null, applyGlobeMatrix: true, applyTerrainMatrix: true});\n    const globeRadius = getGlobeRadiusPixels(transform.worldSize, transform.center.lat);\n    const globePosition = getGlobeCenterInViewSpace(transform);\n    const altitudeBlend = getAtmosphereAltitudeBlend(vec3.length(globePosition) - globeRadius, globeRadius);\n    const atmosphereBlend = sky['atmosphere-blend'] * projectionData.projectionTransition * altitudeBlend;\n\n    if (atmosphereBlend === 0) {\n        // Don't draw anything if atmosphere is fully transparent\n        return;\n    }\n\n    const uniformValues = atmosphereUniformValues(sunPos, atmosphereBlend, globePosition, globeRadius, transform.inverseProjectionMatrix);\n\n    program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniformValues, null, null, 'atmosphere', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);\n}\n", "import {drawSymbols} from './draw_symbol.ts';\nimport {drawCircles} from './draw_circle.ts';\nimport {drawHeatmap} from './draw_heatmap.ts';\nimport {drawLine} from './draw_line.ts';\nimport {drawFill} from './draw_fill.ts';\nimport {drawFillExtrusion} from './draw_fill_extrusion.ts';\nimport {drawHillshade} from './draw_hillshade.ts';\nimport {drawColorRelief} from './draw_color_relief.ts';\nimport {drawRaster} from './draw_raster.ts';\nimport {drawBackground} from './draw_background.ts';\nimport {drawDebug, drawDebugPadding, selectDebugSource} from './draw_debug.ts';\nimport {drawCustom} from './draw_custom.ts';\nimport {drawDepth} from './draw_terrain.ts';\nimport {drawSky, drawAtmosphere} from './draw_sky.ts';\n\nexport {drawSymbols, drawCircles, drawHeatmap, drawLine, drawFill, drawFillExtrusion,\n    drawHillshade, drawColorRelief, drawRaster, drawBackground,\n    drawDebug, drawDebugPadding, selectDebugSource, drawCustom,\n    drawDepth, drawSky, drawAtmosphere};\n\nexport type DrawFunctions = {\n    symbol: typeof drawSymbols;\n    circle: typeof drawCircles;\n    heatmap: typeof drawHeatmap;\n    line: typeof drawLine;\n    fill: typeof drawFill;\n    fillExtrusion: typeof drawFillExtrusion;\n    hillshade: typeof drawHillshade;\n    colorRelief: typeof drawColorRelief;\n    raster: typeof drawRaster;\n    background: typeof drawBackground;\n    sky: typeof drawSky;\n    atmosphere: typeof drawAtmosphere;\n    custom: typeof drawCustom;\n    debug: typeof drawDebug;\n    debugPadding: typeof drawDebugPadding;\n    terrainDepth: typeof drawDepth;\n};\n\nexport const webglDrawFunctions: DrawFunctions = {\n    symbol: drawSymbols,\n    circle: drawCircles,\n    heatmap: drawHeatmap,\n    line: drawLine,\n    fill: drawFill,\n    fillExtrusion: drawFillExtrusion,\n    hillshade: drawHillshade,\n    colorRelief: drawColorRelief,\n    raster: drawRaster,\n    background: drawBackground,\n    sky: drawSky,\n    atmosphere: drawAtmosphere,\n    custom: drawCustom,\n    debug: drawDebug,\n    debugPadding: drawDebugPadding,\n    terrainDepth: drawDepth,\n};\n", "import {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {TileManager} from '../tile/tile_manager.ts';\nimport {DepthMode} from '../webgl/depth_mode.ts';\nimport {ColorMode} from '../webgl/color_mode.ts';\nimport {StencilMode} from '../webgl/stencil_mode.ts';\nimport {CullFaceMode} from '../webgl/cull_face_mode.ts';\nimport {shaders} from '../shaders/shaders.ts';\nimport {MercatorShaderDefine, MercatorShaderVariantKey} from '../geo/projection/mercator_projection.ts';\n\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\nimport type {Terrain, TerrainData} from './terrain.ts';\nimport type {RendererProjectionData} from '../geo/projection/projection_data.ts';\nimport type {CanonicalTileID, OverscaledTileID} from '../tile/tile_id.ts';\nimport type {DepthRangeType, DepthMaskType, DepthFuncType} from '../webgl/types.ts';\nimport type {Context} from '../webgl/context.ts';\nimport type {Program} from '../webgl/program.ts';\nimport type {ProgramCache} from '../webgl/program_cache.ts';\nimport type {ProgramConfiguration} from '../data/program_configuration.ts';\nimport type {PreparedShader} from '../shaders/shaders.ts';\nimport type {Mesh} from './mesh.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {LightPropsPossiblyEvaluated} from '../style/light_properties.g.ts';\nimport type {SkyPropsPossiblyEvaluated} from '../style/sky_properties.g.ts';\nimport type {Projection, TileMeshUsage} from '../geo/projection/projection.ts';\nimport type {CrossTileID, VariableOffset} from '../symbol/placement.ts';\n\nexport type RenderPass = 'offscreen' | 'opaque' | 'translucent';\n\n/** The code a projection adds to every shader, and the name that tells its programs apart. */\nexport type ProjectionShaderVariant = {\n    readonly name: string;\n    readonly define: string;\n    readonly prelude: PreparedShader;\n};\n\n/** Plain values that describe one frame. The map builds them once per frame. */\nexport type FrameRenderData = {\n    readonly showOverdrawInspector: boolean;\n    readonly showTileBoundaries: boolean;\n    readonly showPadding: boolean;\n    readonly rotating: boolean;\n    readonly zooming: boolean;\n    readonly moving: boolean;\n    readonly fadeDuration: number;\n    /** Progress of the symbol fade since the last placement. */\n    readonly symbolFadeChange: number;\n    /** The anchors the last placement chose for symbols with variable anchors. */\n    readonly variableOffsets: Readonly<Record<CrossTileID, VariableOffset>>;\n    readonly anisotropicFilterPitch: number;\n    readonly projectionTransition: number;\n    readonly isRenderingGlobe: boolean;\n    /** The projection's shader variant for this frame, undefined until the style has a projection. Globe switches it during its transition. */\n    readonly projectionShaderVariant: ProjectionShaderVariant | undefined;\n    /** Whether the projection subdivides tile meshes this frame. */\n    readonly useSubdivision: boolean;\n    /** Drawing buffer pixels per CSS pixel, after the map clamps it to the largest canvas the GPU supports. */\n    readonly pixelRatio: number;\n    /** The style's light, evaluated for this frame, undefined until the style has loaded. */\n    readonly light: Readonly<LightPropsPossiblyEvaluated> | undefined;\n    /** The style's sky, evaluated for this frame, undefined until the style has loaded. */\n    readonly sky: Readonly<SkyPropsPossiblyEvaluated> | undefined;\n};\n\ntype FrameRenderContextOptions = {\n    transform: IReadonlyTransform;\n    terrain: Terrain | null;\n    data: FrameRenderData;\n    context: Context;\n    programCache: ProgramCache;\n    currentPass: RenderPass;\n    /** The projection that builds the tile meshes, undefined until the style has one. */\n    projection: Projection | undefined;\n};\n\n/** Distinct z-planes within each layer that can be drawn to, implemented with the WebGL depth buffer. */\nconst NUM_SUBLAYERS: number = TileManager.maxOverzooming + TileManager.maxUnderzooming + 1;\n\n/** Depth distance between two neighboring sublayers. */\nconst DEPTH_EPSILON: number = 1 / Math.pow(2, 16);\n\n/** The mercator variant, for draws that force the simple projection, like fullscreen quads. */\nconst MERCATOR_SHADER_VARIANT: ProjectionShaderVariant = {\n    name: MercatorShaderVariantKey,\n    define: MercatorShaderDefine,\n    prelude: shaders.projectionMercator\n};\n\n/**\n * @internal\n * The state of one frame, created per render and updated as rendering proceeds.\n * Corresponds to part of MapLibre Native's `PaintParameters`.\n */\nexport class FrameRenderContext {\n    currentPass: RenderPass;\n    currentLayer: number = 0;\n    opaquePassCutoff: number = Infinity;\n    depthRangeFor3D: DepthRangeType = [0, 1];\n    isRenderingToTexture: boolean = false;\n    readonly transform: IReadonlyTransform;\n    readonly terrain: Terrain | null;\n    readonly data: FrameRenderData;\n    readonly context: Context;\n    readonly programCache: ProgramCache;\n    private readonly projection: Projection | undefined;\n    /** The source whose clipping masks are in the stencil buffer. */\n    private currentStencilSource: string;\n    private nextStencilID: number = 1;\n    private tileClippingMaskIDs: Record<string, number> = {};\n\n    constructor(options: FrameRenderContextOptions) {\n        this.transform = options.transform;\n        this.terrain = options.terrain;\n        this.data = options.data;\n        this.context = options.context;\n        this.programCache = options.programCache;\n        this.currentPass = options.currentPass;\n        this.projection = options.projection;\n    }\n\n    getProjectionDataForTile(tileID: OverscaledTileID, options: {aligned?: boolean; applyTerrainMatrix?: boolean} = {}): RendererProjectionData {\n        const projectionData = this.transform.getProjectionData({\n            overscaledTileID: tileID,\n            aligned: options.aligned,\n            applyGlobeMatrix: !this.isRenderingToTexture,\n            applyTerrainMatrix: options.applyTerrainMatrix ?? true\n        });\n        if (this.isRenderingToTexture) return projectionData;\n\n        projectionData.uniformBufferKey = options.aligned ? `${tileID.key}/aligned` : tileID.key;\n        return projectionData;\n    }\n\n    /**\n     * Returns terrain data for a tile.\n     * Returns null if terrain is not configured or tiles are being rendered to a texture.\n     */\n    getTerrainDataForTile(tileID: OverscaledTileID): TerrainData | null {\n        if (this.isRenderingToTexture) return null;\n        return this.terrain?.getTerrainData(tileID) ?? null;\n    }\n\n    /** Returns the mesh the projection draws a tile with. */\n    getMeshFromTileID(tileID: CanonicalTileID, hasBorder: boolean, allowPoles: boolean, usage: TileMeshUsage): Mesh {\n        return this.projection.getMeshFromTileID(this.context, tileID, hasBorder, allowPoles, usage);\n    }\n\n    /**\n     * Finds the required shader and its variant (base/terrain/globe, etc.) and binds it, compiling a new shader if required.\n     * @param name - Name of the desired shader.\n     * @param programConfiguration - Configuration of shader's inputs.\n     * @param forceSimpleProjection - Whether to force the use of a shader variant with simple mercator projection vertex shader.\n     * False by default. Use true when drawing with a simple projection matrix is desired, eg. when drawing a fullscreen quad.\n     * @param defines - Additional macros to be injected at the beginning of the shader. Expected format is `['#define XYZ']`, etc.\n     */\n    useProgram(name: string, programConfiguration?: ProgramConfiguration | null, forceSimpleProjection: boolean = false, defines: string[] = []): Program<any> {\n        return this.programCache.getProgram({\n            name,\n            programConfiguration,\n            projectionShaderVariant: forceSimpleProjection ? MERCATOR_SHADER_VARIANT : this.data.projectionShaderVariant,\n            showOverdrawInspector: this.data.showOverdrawInspector,\n            useTerrain: this.terrain !== null,\n            defines\n        });\n    }\n\n    colorModeForRenderPass(): Readonly<ColorMode> {\n        const gl = this.context.gl;\n        if (this.data.showOverdrawInspector) {\n            const numOverdrawSteps = 8;\n            const a = 1 / numOverdrawSteps;\n\n            return new ColorMode([gl.CONSTANT_COLOR, gl.ONE], new Color(a, a, a, 0), [true, true, true, true]);\n        } else if (this.currentPass === 'opaque') {\n            return ColorMode.unblended;\n        } else {\n            return ColorMode.alphaBlended;\n        }\n    }\n\n    getDepthModeForSublayer(n: number, mask: DepthMaskType, func?: DepthFuncType | null): Readonly<DepthMode> {\n        if (!this.opaquePassEnabledForLayer()) return DepthMode.disabled;\n        const depth = 1 - ((1 + this.currentLayer) * NUM_SUBLAYERS + n) * DEPTH_EPSILON;\n        return new DepthMode(func || this.context.gl.LEQUAL, mask, [depth, depth]);\n    }\n\n    getDepthModeFor3D(): Readonly<DepthMode> {\n        return new DepthMode(this.context.gl.LEQUAL, DepthMode.ReadWrite, this.depthRangeFor3D);\n    }\n\n    /** Sets the depth range that 3D layers draw into, which lies below the depth values of every sublayer of the `layerCount` layers. */\n    setDepthRangeFor3D(layerCount: number): void {\n        this.depthRangeFor3D = [0, 1 - ((layerCount + 2) * NUM_SUBLAYERS * DEPTH_EPSILON)];\n    }\n\n    /**\n     * Returns whether the current layer can be drawn in the opaque pass. The opaque pass and 3D layers both use the depth buffer,\n     * so layers drawn above 3D layers use the painter's algorithm to appear above 3D features.\n     */\n    opaquePassEnabledForLayer(): boolean {\n        return this.currentLayer < this.opaquePassCutoff;\n    }\n\n    /**\n     * Reset the drawing canvas by clearing the stencil buffer so that we can draw\n     * new tiles at the same location, while retaining previously drawn pixels.\n     */\n    clearStencil(): void {\n        this.nextStencilID = 1;\n        this.currentStencilSource = undefined;\n        this.context.clear({stencil: 0});\n    }\n\n    /** Makes the next tile-clipped layer draw its clipping masks again. */\n    invalidateTileClippingMasks(): void {\n        this.currentStencilSource = undefined;\n    }\n\n    /** Draws the clipping masks of a layer's tiles into the stencil buffer, unless its source's masks are already there. */\n    renderTileClippingMasks(layer: StyleLayer, tileIDs: OverscaledTileID[]): void {\n        if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs?.length) {\n            return;\n        }\n\n        this.currentStencilSource = layer.source;\n\n        if (this.nextStencilID + tileIDs.length > 256) {\n            this.clearStencil();\n        }\n\n        const context = this.context;\n        context.setColorMode(ColorMode.disabled);\n        context.setDepthMode(DepthMode.disabled);\n\n        const stencilRefs: Record<string, number> = {};\n        for (const tileID of tileIDs) {\n            stencilRefs[tileID.key] = this.nextStencilID++;\n        }\n\n        if (this.data.useSubdivision) {\n            this.renderTileMasks(stencilRefs, tileIDs, true);\n        }\n        this.renderTileMasks(stencilRefs, tileIDs, false);\n\n        this.tileClippingMaskIDs = stencilRefs;\n    }\n\n    private renderTileMasks(tileStencilRefs: Record<string, number>, tileIDs: OverscaledTileID[], useBorders: boolean): void {\n        const context = this.context;\n        const gl = context.gl;\n        const program = this.useProgram('clippingMask');\n\n        for (const tileID of tileIDs) {\n            const stencilRef = tileStencilRefs[tileID.key];\n            const terrainData = this.getTerrainDataForTile(tileID);\n            const mesh = this.getMeshFromTileID(tileID.canonical, useBorders, true, 'stencil');\n            const projectionData = this.getProjectionDataForTile(tileID);\n\n            program.draw(context, gl.TRIANGLES, DepthMode.disabled,\n                new StencilMode({func: gl.ALWAYS, mask: 0}, stencilRef, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE),\n                ColorMode.disabled, this.isRenderingToTexture ? CullFaceMode.disabled : CullFaceMode.backCCW, null,\n                terrainData, projectionData, '$clipping', mesh.vertexBuffer,\n                mesh.indexBuffer, mesh.segments);\n        }\n    }\n\n    /** Returns a stencil mode that draws each pixel of a 3D layer only once. */\n    stencilModeFor3D(): StencilMode {\n        this.currentStencilSource = undefined;\n\n        if (this.nextStencilID + 1 > 256) {\n            this.clearStencil();\n        }\n\n        const id = this.nextStencilID++;\n        const gl = this.context.gl;\n        return new StencilMode({func: gl.NOTEQUAL, mask: 0xFF}, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n    }\n\n    stencilModeForClipping(tileID: OverscaledTileID): StencilMode {\n        const gl = this.context.gl;\n        return new StencilMode({func: gl.EQUAL, mask: 0xFF}, this.tileClippingMaskIDs[tileID.key], 0x00, gl.KEEP, gl.KEEP, gl.REPLACE);\n    }\n\n    /**\n     * Sort coordinates by Z as drawing tiles is done in Z-descending order.\n     * All children with the same Z write the same stencil value.  Children\n     * stencil values are greater than parent's.  This is used only for raster\n     * and raster-dem tiles, which are already clipped to tile boundaries, to\n     * mask area of tile overlapped by children tiles.\n     * Stencil ref values continue the range used by the tile clipping masks.\n     *\n     * Attention: This function changes the next stencil ID even if the result of it\n     * is not used, which might cause problems when rendering due to invalid stencil\n     * values.\n     * Returns [StencilMode for tile overscaleZ map, sortedCoords].\n     */\n    getStencilConfigForOverlapAndUpdateStencilID(tileIDs: OverscaledTileID[]): [Record<number, Readonly<StencilMode>>, OverscaledTileID[]] {\n        const gl = this.context.gl;\n        const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ);\n        const minTileZ = coords[coords.length - 1].overscaledZ;\n        const stencilValues = coords[0].overscaledZ - minTileZ + 1;\n        if (stencilValues > 1) {\n            this.currentStencilSource = undefined;\n            if (this.nextStencilID + stencilValues > 256) {\n                this.clearStencil();\n            }\n            const zToStencilMode: Record<number, Readonly<StencilMode>> = {};\n            for (let i = 0; i < stencilValues; i++) {\n                zToStencilMode[i + minTileZ] = new StencilMode({func: gl.GEQUAL, mask: 0xFF}, i + this.nextStencilID, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n            }\n            this.nextStencilID += stencilValues;\n            return [zToStencilMode, coords];\n        }\n        return [{[minTileZ]: StencilMode.disabled}, coords];\n    }\n\n    stencilConfigForOverlapTwoPass(tileIDs: OverscaledTileID[]): [\n        Record<number, Readonly<StencilMode>>, // borderless tiles - high priority & high stencil values\n        Record<number, Readonly<StencilMode>>, // tiles with border - low priority\n        OverscaledTileID[]\n    ] {\n        const gl = this.context.gl;\n        const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ);\n        const minTileZ = coords[coords.length - 1].overscaledZ;\n        const stencilValues = coords[0].overscaledZ - minTileZ + 1;\n\n        this.clearStencil();\n\n        if (stencilValues > 1) {\n            const zToStencilModeHigh: Record<number, Readonly<StencilMode>> = {};\n            const zToStencilModeLow: Record<number, Readonly<StencilMode>> = {};\n            for (let i = 0; i < stencilValues; i++) {\n                zToStencilModeHigh[i + minTileZ] = new StencilMode({func: gl.GREATER, mask: 0xFF}, stencilValues + 1 + i, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n                zToStencilModeLow[i + minTileZ] = new StencilMode({func: gl.GREATER, mask: 0xFF}, 1 + i, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n            }\n            this.nextStencilID = stencilValues * 2 + 1;\n            return [\n                zToStencilModeHigh,\n                zToStencilModeLow,\n                coords\n            ];\n        } else {\n            this.nextStencilID = 3;\n            return [\n                {[minTileZ]: new StencilMode({func: gl.GREATER, mask: 0xFF}, 2, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE)},\n                {[minTileZ]: new StencilMode({func: gl.GREATER, mask: 0xFF}, 1, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE)},\n                coords\n            ];\n        }\n    }\n}\n", "import {now} from '../util/time_control.ts';\nimport {mat4} from 'gl-matrix';\nimport {EXTENT} from '../data/extent.ts';\nimport {SegmentVector} from '../data/segment.ts';\nimport {RasterBoundsArray, PosArray, TriangleIndexArray, LineStripIndexArray} from '../data/array_types.g.ts';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes.ts';\nimport posAttributes from '../data/pos_attributes.ts';\nimport {Context} from '../webgl/context.ts';\nimport {ProgramCache} from '../webgl/program_cache.ts';\nimport {StencilMode} from '../webgl/stencil_mode.ts';\nimport {ColorMode} from '../webgl/color_mode.ts';\nimport {CullFaceMode} from '../webgl/cull_face_mode.ts';\nimport {Texture} from '../webgl/texture.ts';\nimport {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {selectDebugSource, webglDrawFunctions, type DrawFunctions} from '../webgl/draw/index.ts';\nimport {Mesh} from './mesh.ts';\nimport {FrameRenderContext, type FrameRenderData} from './frame_render_context.ts';\nimport {updateFrameUniformBuffer} from '../webgl/frame_uniform_buffer.ts';\nimport {releaseProjectionUniformBuffers} from '../webgl/projection_uniform_buffer.ts';\nimport {coveringTiles} from '../geo/projection/covering_tiles.ts';\nimport {isSymbolStyleLayer} from '../style/style_layer/symbol_style_layer.ts';\nimport {isCircleStyleLayer} from '../style/style_layer/circle_style_layer.ts';\nimport {isHeatmapStyleLayer} from '../style/style_layer/heatmap_style_layer.ts';\nimport {isLineStyleLayer} from '../style/style_layer/line_style_layer.ts';\nimport {isFillStyleLayer} from '../style/style_layer/fill_style_layer.ts';\nimport {isFillExtrusionStyleLayer} from '../style/style_layer/fill_extrusion_style_layer.ts';\nimport {isHillshadeStyleLayer} from '../style/style_layer/hillshade_style_layer.ts';\nimport {isColorReliefStyleLayer} from '../style/style_layer/color_relief_style_layer.ts';\nimport {isRasterStyleLayer} from '../style/style_layer/raster_style_layer.ts';\nimport {isBackgroundStyleLayer} from '../style/style_layer/background_style_layer.ts';\nimport {isCustomStyleLayer} from '../style/style_layer/custom_style_layer.ts';\n\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\nimport type {TileManager} from '../tile/tile_manager.ts';\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\nimport type {Style} from '../style/style.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {LineAtlas} from './line_atlas.ts';\nimport type {PatternAtlas} from './pattern_atlas.ts';\nimport type {VertexBuffer} from '../webgl/vertex_buffer.ts';\nimport type {IndexBuffer} from '../webgl/index_buffer.ts';\nimport type {IRenderToTexture} from './render_to_texture_interface.ts';\nimport type {Framebuffer} from '../webgl/framebuffer.ts';\n\n/**\n * Holds the texture used to render a 2D tile so it can be draped over 3D\n * terrain. All RTTObjects share a single FBO owned by the Painter; the\n * texture is swapped in via `Painter.bindRTT` before each render pass.\n * Owned by a `Tile` while in use, recycled via `Painter.releaseRTT` when\n * the tile no longer needs it.\n */\nexport type RTTObject = {\n    texture: Texture;\n    size: number;\n};\n\n/**\n * @internal\n * Initialize a new painter object.\n */\nexport class Painter {\n    drawFunctions: DrawFunctions;\n    context: Context;\n    renderToTexture: IRenderToTexture;\n    _tileTextures: {\n        [_: number]: Texture[];\n    };\n    /**\n     * A pool of recyclable {@link RTTObject}s (textures only; the FBO is shared).\n     */\n    _rttObjectRecyclePool: RTTObject[];\n    /**\n     * Shared FBO used by all RTT render passes. The color attachment is\n     * swapped to the target RTTObject's texture via {@link bindRTT}.\n     * Created lazily on first use.\n     */\n    _rttSharedFbo: {\n        fbo: Framebuffer;\n        depthRenderbuffer: WebGLRenderbuffer;\n        size: number;\n    } | null;\n    /**\n     * Shared scratch FBO (color + depth-stencil) used by `{line,fill}-layer-opacity`.\n     * The layer is rendered into this FBO, then composited into whatever framebuffer was previously bound\n     * The canvas in the flat case, the per-terrain-tile RTT texture in the terrain case.\n     * Resized in place to match the target dimensions.\n     */\n    layerOpacityFbo: Framebuffer | null;\n    width: number;\n    height: number;\n    tileExtentBuffer: VertexBuffer;\n    tileExtentSegments: SegmentVector;\n    tileExtentMesh: Mesh;\n    /** A quad covering the viewport in clip space, which the sky and the atmosphere are drawn on. */\n    skyMesh: Mesh;\n\n    debugBuffer: VertexBuffer;\n    debugSegments: SegmentVector;\n    rasterBoundsBuffer: VertexBuffer;\n    rasterBoundsSegments: SegmentVector;\n    viewportBuffer: VertexBuffer;\n    viewportSegments: SegmentVector;\n    quadTriangleIndexBuffer: IndexBuffer;\n    tileBorderIndexBuffer: IndexBuffer;\n    lineAtlas: LineAtlas;\n    patternAtlas: PatternAtlas;\n    programCache: ProgramCache;\n    debugOverlayTexture: Texture;\n    debugOverlayCanvas: HTMLCanvasElement;\n    // this object stores the current camera-matrix and the last render time\n    // of the terrain depth framebuffer.\n    // every time the camera-matrix changes the depth framebuffer will be redrawn.\n    terrainFacilitator: {depthDirty: boolean; matrix: mat4; renderTime: number};\n\n    constructor(gl: WebGL2RenderingContext) {\n        this.drawFunctions = webglDrawFunctions;\n        this.context = new Context(gl);\n        this.programCache = new ProgramCache(this.context);\n        this.layerOpacityFbo = null;\n        this._tileTextures = {};\n        this._rttObjectRecyclePool = [];\n        this._rttSharedFbo = null;\n        this.terrainFacilitator = {depthDirty: true, matrix: mat4.identity(new Float64Array(16)), renderTime: 0};\n\n        this.setup();\n    }\n\n    /*\n     * Update the GL viewport, projection matrix, and transforms to compensate\n     * for a new width and height value.\n     *\n     * The viewport is the canvas' backing store, so it rounds as {@link Map._resizeCanvas} does.\n     */\n    resize(width: number, height: number, pixelRatio: number): void {\n        this.width = Math.round(width * pixelRatio);\n        this.height = Math.round(height * pixelRatio);\n        this.context.viewport.set([0, 0, this.width, this.height]);\n    }\n\n    setup(): void {\n        const context = this.context;\n\n        const tileExtentArray = new PosArray();\n        tileExtentArray.emplaceBack(0, 0);\n        tileExtentArray.emplaceBack(EXTENT, 0);\n        tileExtentArray.emplaceBack(0, EXTENT);\n        tileExtentArray.emplaceBack(EXTENT, EXTENT);\n        this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);\n        this.tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n        const debugArray = new PosArray();\n        debugArray.emplaceBack(0, 0);\n        debugArray.emplaceBack(EXTENT, 0);\n        debugArray.emplaceBack(0, EXTENT);\n        debugArray.emplaceBack(EXTENT, EXTENT);\n        this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members);\n        this.debugSegments = SegmentVector.simpleSegment(0, 0, 4, 5);\n\n        const rasterBoundsArray = new RasterBoundsArray();\n        rasterBoundsArray.emplaceBack(0, 0, 0, 0);\n        rasterBoundsArray.emplaceBack(EXTENT, 0, EXTENT, 0);\n        rasterBoundsArray.emplaceBack(0, EXTENT, 0, EXTENT);\n        rasterBoundsArray.emplaceBack(EXTENT, EXTENT, EXTENT, EXTENT);\n        this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members);\n        this.rasterBoundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n        const viewportArray = new PosArray();\n        viewportArray.emplaceBack(0, 0);\n        viewportArray.emplaceBack(1, 0);\n        viewportArray.emplaceBack(0, 1);\n        viewportArray.emplaceBack(1, 1);\n        this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members);\n        this.viewportSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n        const tileLineStripIndices = new LineStripIndexArray();\n        tileLineStripIndices.emplaceBack(0);\n        tileLineStripIndices.emplaceBack(1);\n        tileLineStripIndices.emplaceBack(3);\n        tileLineStripIndices.emplaceBack(2);\n        tileLineStripIndices.emplaceBack(0);\n        this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices);\n\n        const quadTriangleIndices = new TriangleIndexArray();\n        quadTriangleIndices.emplaceBack(1, 0, 2);\n        quadTriangleIndices.emplaceBack(1, 2, 3);\n        this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);\n\n        this.tileExtentMesh = new Mesh(this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments);\n\n        const skyArray = new PosArray();\n        skyArray.emplaceBack(-1, -1);\n        skyArray.emplaceBack(1, -1);\n        skyArray.emplaceBack(1, 1);\n        skyArray.emplaceBack(-1, 1);\n\n        const skyIndices = new TriangleIndexArray();\n        skyIndices.emplaceBack(0, 1, 2);\n        skyIndices.emplaceBack(0, 2, 3);\n\n        this.skyMesh = new Mesh(\n            context.createVertexBuffer(skyArray, posAttributes.members),\n            context.createIndexBuffer(skyIndices),\n            SegmentVector.simpleSegment(0, 0, skyArray.length, skyIndices.length)\n        );\n    }\n\n    /**\n     * Fills the depth buffer with the geometry of all supplied tiles.\n     * Does not change the color buffer or the stencil buffer.\n     */\n    _renderTilesDepthBuffer(frameRenderContext: FrameRenderContext): void {\n        const context = this.context;\n        const gl = context.gl;\n        const transform = frameRenderContext.transform;\n\n        const program = frameRenderContext.useProgram('depth');\n        const depthMode = frameRenderContext.getDepthModeFor3D();\n        const tileIDs = coveringTiles(transform, {tileSize: transform.tileSize});\n\n        // tiles are usually supplied in ascending order of z, then y, then x\n        for (const tileID of tileIDs) {\n            const terrainData = frameRenderContext.getTerrainDataForTile(tileID);\n            const mesh = frameRenderContext.getMeshFromTileID(tileID.canonical, true, true, 'raster');\n\n            const projectionData = frameRenderContext.getProjectionDataForTile(tileID);\n\n            program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled,\n                ColorMode.disabled, CullFaceMode.backCCW, null,\n                terrainData, projectionData, '$clipping', mesh.vertexBuffer,\n                mesh.indexBuffer, mesh.segments);\n        }\n    }\n\n    render(style: Style, transform: IReadonlyTransform, data: FrameRenderData): void {\n        if (this.context.gl.isContextLost()) return;\n\n        const frameRenderContext = new FrameRenderContext({\n            transform,\n            terrain: style.map.terrain ?? null,\n            data,\n            context: this.context,\n            programCache: this.programCache,\n            currentPass: 'offscreen',\n            projection: style.projection\n        });\n\n        this.lineAtlas = style.lineAtlas;\n        this.patternAtlas = style.patternAtlas;\n\n        updateFrameUniformBuffer(this.context.frameUniformBuffer, transform, data);\n\n        style.imageManager.beginFrame();\n        releaseProjectionUniformBuffers(this.context);\n\n        const layerIds = style._order;\n        const tileManagers = style.tileManagers;\n\n        const coordsAscending: {[_: string]: OverscaledTileID[]} = {};\n        const coordsDescending: {[_: string]: OverscaledTileID[]} = {};\n        const coordsDescendingSymbol: {[_: string]: OverscaledTileID[]} = {};\n\n        for (const id in tileManagers) {\n            const tileManager = tileManagers[id];\n            if (tileManager.used) {\n                tileManager.prepare(this.context);\n            }\n\n            coordsAscending[id] = tileManager.getVisibleCoordinates(false);\n            coordsDescending[id] = coordsAscending[id].slice().reverse();\n            coordsDescendingSymbol[id] = tileManager.getVisibleCoordinates(true).reverse();\n        }\n\n        frameRenderContext.opaquePassCutoff = Infinity;\n        for (let i = 0; i < layerIds.length; i++) {\n            const layerId = layerIds[i];\n            if (style._layers[layerId].is3D()) {\n                frameRenderContext.opaquePassCutoff = i;\n                break;\n            }\n        }\n\n        this.maybeDrawDepth(frameRenderContext);\n\n        if (this.renderToTexture) {\n            this.renderToTexture.prepareForRender(style, transform.zoom, data.moving);\n            // this is disabled, because render-to-texture is rendering all layers from bottom to top.\n            frameRenderContext.opaquePassCutoff = 0;\n        }\n\n        // Offscreen pass ===============================================\n        // We first do all rendering that requires rendering to a separate\n        // framebuffer, and then save those for rendering back to the map\n        // later: in doing this we avoid doing expensive framebuffer restores.\n        frameRenderContext.currentPass = 'offscreen';\n\n        for (const layerId of layerIds) {\n            const layer = style._layers[layerId];\n            if (!layer.hasOffscreenPass() || layer.isHidden(transform.zoom)) continue;\n\n            const coords = coordsDescending[layer.source];\n            if (layer.type !== 'custom' && !coords.length) continue;\n\n            this.renderLayer(this, tileManagers[layer.source], layer, coords, frameRenderContext);\n        }\n\n        // Rebind the main framebuffer now that all offscreen layers have been rendered:\n        this.context.viewport.set([0, 0, this.width, this.height]);\n        this.context.bindFramebuffer.set(null);\n\n        // Clear buffers in preparation for drawing to the main framebuffer\n        this.context.clear({color: data.showOverdrawInspector ? Color.black : Color.transparent, depth: 1});\n        frameRenderContext.clearStencil();\n\n        // draw sky first to not overwrite symbols\n        if (data.sky) this.drawFunctions.sky(this.skyMesh, frameRenderContext);\n\n        frameRenderContext.setDepthRangeFor3D(style._order.length);\n\n        // Opaque pass ===============================================\n        // Draw opaque layers top-to-bottom first.\n        if (!this.renderToTexture) {\n            frameRenderContext.currentPass = 'opaque';\n\n            for (frameRenderContext.currentLayer = layerIds.length - 1; frameRenderContext.currentLayer >= 0; frameRenderContext.currentLayer--) {\n                const layer = style._layers[layerIds[frameRenderContext.currentLayer]];\n                if (layer.isHidden(transform.zoom)) continue;\n                const tileManager = tileManagers[layer.source];\n                const coords = coordsAscending[layer.source];\n\n                frameRenderContext.renderTileClippingMasks(layer, coords);\n                this.renderLayer(this, tileManager, layer, coords, frameRenderContext);\n            }\n        }\n\n        // Translucent pass ===============================================\n        // Draw all other layers bottom-to-top.\n        frameRenderContext.currentPass = 'translucent';\n\n        let globeDepthRendered = false;\n\n        for (frameRenderContext.currentLayer = 0; frameRenderContext.currentLayer < layerIds.length; frameRenderContext.currentLayer++) {\n            const layer = style._layers[layerIds[frameRenderContext.currentLayer]];\n            if (layer.isHidden(transform.zoom)) continue;\n            const tileManager = tileManagers[layer.source];\n\n            if (this.renderToTexture?.renderLayer(layer, style, frameRenderContext)) continue;\n\n            if (!frameRenderContext.opaquePassEnabledForLayer() && !globeDepthRendered) {\n                globeDepthRendered = true;\n                // Render the globe sphere into the depth buffer - but only if globe is enabled and terrain is disabled.\n                // There should be no need for explicitly writing tile depths when terrain is enabled.\n                if (data.isRenderingGlobe && !frameRenderContext.terrain) {\n                    this._renderTilesDepthBuffer(frameRenderContext);\n                }\n            }\n\n            // For symbol layers in the translucent pass, we add extra tiles to the renderable set\n            // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render\n            // separate clipping masks\n            const coords = (layer.type === 'symbol' ? coordsDescendingSymbol : coordsDescending)[layer.source];\n\n            frameRenderContext.renderTileClippingMasks(layer, coordsAscending[layer.source]);\n            this.renderLayer(this, tileManager, layer, coords, frameRenderContext);\n        }\n\n        // Render atmosphere, only for Globe projection\n        if (data.isRenderingGlobe) {\n            this.drawFunctions.atmosphere(this.skyMesh, frameRenderContext);\n        }\n\n        if (data.showTileBoundaries) {\n            const selectedSource = selectDebugSource(style, transform.zoom);\n            if (selectedSource) {\n                this.drawFunctions.debug(this, selectedSource, selectedSource.getVisibleCoordinates(), frameRenderContext);\n            }\n        }\n\n        if (data.showPadding) {\n            this.drawFunctions.debugPadding(frameRenderContext);\n        }\n\n        // a frame at rest has reused every pooled drape it needs; the rest stay resident until freed here\n        if (this.renderToTexture && !data.moving) this.clearRTTPool();\n\n        // Set defaults for most GL values so that anyone using the state after the render\n        // encounters more expected values.\n        this.context.setDefault();\n    }\n\n    /**\n     * Invalidates cached terrain depth so the next eligible depth pass redraws it.\n     * DEM data can change the rendered surface while the camera and terrain tile set stay unchanged.\n     * Repeated calls coalesce without rendering or scheduling a frame, even if terrain is not yet present.\n     */\n    markTerrainDepthDirty(): void {\n        this.terrainFacilitator.depthDirty = true;\n    }\n\n    /**\n     * Updates the depth framebuffer after explicit invalidation, camera movement, or tile reloading.\n     */\n    maybeDrawDepth(frameRenderContext: FrameRenderContext): void {\n        if (!frameRenderContext.data.projectionShaderVariant || !frameRenderContext.terrain) {\n            return;\n        }\n        const prevMatrix = this.terrainFacilitator.matrix;\n        const currMatrix = frameRenderContext.transform.modelViewProjectionMatrix;\n\n        // Update depth-framebuffer on camera movement, or tile reloading\n        let doUpdate = this.terrainFacilitator.depthDirty;\n        doUpdate ||= !mat4.equals(prevMatrix, currMatrix);\n        doUpdate ||= frameRenderContext.terrain.tileManager.anyTilesAfterTime(this.terrainFacilitator.renderTime);\n\n        if (!doUpdate) {\n            return;\n        }\n\n        mat4.copy(prevMatrix, currMatrix);\n        this.terrainFacilitator.renderTime = now();\n        this.terrainFacilitator.depthDirty = false;\n        this.drawFunctions.terrainDepth(this, frameRenderContext.terrain, frameRenderContext);\n    }\n\n    renderLayer(painter: Painter, tileManager: TileManager, layer: StyleLayer, coords: OverscaledTileID[], frameRenderContext: FrameRenderContext): void {\n        if (layer.isHidden(frameRenderContext.transform.zoom)) return;\n        if (layer.type !== 'background' && layer.type !== 'custom' && !(coords || []).length) return;\n\n        const draw = this.drawFunctions;\n        if (isSymbolStyleLayer(layer)) {\n            draw.symbol(painter, tileManager, layer, coords, frameRenderContext);\n        } else if (isCircleStyleLayer(layer)) {\n            draw.circle(tileManager, layer, coords, frameRenderContext);\n        } else if (isHeatmapStyleLayer(layer)) {\n            draw.heatmap(painter, tileManager, layer, coords, frameRenderContext);\n        } else if (isLineStyleLayer(layer)) {\n            draw.line(painter, tileManager, layer, coords, frameRenderContext);\n        } else if (isFillStyleLayer(layer)) {\n            draw.fill(painter, tileManager, layer, coords, frameRenderContext);\n        } else if (isFillExtrusionStyleLayer(layer)) {\n            draw.fillExtrusion(tileManager, layer, coords, frameRenderContext);\n        } else if (isHillshadeStyleLayer(layer)) {\n            draw.hillshade(painter, tileManager, layer, coords, frameRenderContext);\n        } else if (isColorReliefStyleLayer(layer)) {\n            draw.colorRelief(painter, tileManager, layer, coords, frameRenderContext);\n        } else if (isRasterStyleLayer(layer)) {\n            draw.raster(tileManager, layer, coords, frameRenderContext);\n        } else if (isBackgroundStyleLayer(layer)) {\n            draw.background(painter, tileManager, layer, coords, frameRenderContext);\n        } else if (isCustomStyleLayer(layer)) {\n            draw.custom(painter, tileManager, layer, coords, frameRenderContext);\n        }\n    }\n\n    static readonly MAX_TEXTURE_POOL_SIZE_PER_BUCKET = 50;\n\n    saveTileTexture(texture: Texture): void {\n        const textures = this._tileTextures[texture.size[0]];\n        if (!textures) {\n            this._tileTextures[texture.size[0]] = [texture];\n        } else if (textures.length < Painter.MAX_TEXTURE_POOL_SIZE_PER_BUCKET) {\n            textures.push(texture);\n        } else {\n            texture.destroy();\n        }\n    }\n\n    getTileTexture(size: number): Texture {\n        const textures = this._tileTextures[size];\n        return textures && textures.length > 0 ? textures.pop() : null;\n    }\n\n    acquireRTT(size: number): RTTObject {\n        const gl = this.context.gl;\n        const obj = this._rttObjectRecyclePool.pop();\n        if (obj) {\n            if (obj.size !== size) {\n                obj.texture.update({width: size, height: size, data: null}, {premultiply: false, useMipmap: true});\n                obj.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_LINEAR);\n                if (this.context.extTextureFilterAnisotropic) {\n                    gl.texParameterf(gl.TEXTURE_2D, this.context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, this.context.extTextureFilterAnisotropicMax);\n                }\n                obj.size = size;\n            }\n            return obj;\n        }\n        const texture = new Texture(this.context, {width: size, height: size, data: null}, gl.RGBA, {premultiply: false, useMipmap: true});\n        texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_LINEAR);\n        if (this.context.extTextureFilterAnisotropic) {\n            gl.texParameterf(gl.TEXTURE_2D, this.context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, this.context.extTextureFilterAnisotropicMax);\n        }\n        return {texture, size};\n    }\n\n    /**\n     * Binds the shared RTT FBO with the given RTTObject's texture attached\n     * as color target. Creates / resizes the shared FBO and depth-stencil\n     * renderbuffer lazily.\n     */\n    bindRTT(obj: RTTObject): void {\n        const gl = this.context.gl;\n        const size = obj.size;\n\n        // Lazy-create the shared FBO + depth-stencil renderbuffer\n        if (!this._rttSharedFbo) {\n            const fbo = this.context.createFramebuffer(size, size, true, true);\n            const depthRenderbuffer = this.context.createRenderbuffer(gl.DEPTH_STENCIL, size, size);\n            fbo.depthAttachment.set(depthRenderbuffer);\n            this._rttSharedFbo = {fbo, depthRenderbuffer, size};\n        }\n\n        // Resize the shared depth-stencil renderbuffer if needed\n        if (this._rttSharedFbo.size !== size) {\n            this.context.bindRenderbuffer.set(this._rttSharedFbo.depthRenderbuffer);\n            gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);\n            this.context.bindRenderbuffer.set(null);\n            this._rttSharedFbo.fbo.width = size;\n            this._rttSharedFbo.fbo.height = size;\n            this._rttSharedFbo.size = size;\n        }\n\n        // Swap in the target texture and bind\n        this._rttSharedFbo.fbo.colorAttachment.set(obj.texture.texture);\n        this.context.bindFramebuffer.set(this._rttSharedFbo.fbo.framebuffer);\n    }\n\n    releaseRTT(obj: RTTObject): void {\n        this._rttObjectRecyclePool.push(obj);\n    }\n\n    /**\n     * Destroys the pooled {@link RTTObject}s, the drapes no tile holds. Called at the end of a frame at rest,\n     * when they would otherwise stay resident until the next gesture reuses them.\n     */\n    clearRTTPool(): void {\n        for (const obj of this._rttObjectRecyclePool) {\n            obj.texture.destroy();\n        }\n        this._rttObjectRecyclePool.length = 0;\n    }\n\n    /**\n     * Frees the pooled drapes and the shared render-to-texture FBO. Called when terrain is removed, after its tiles\n     * released their drapes.\n     */\n    destroyRTTResources(): void {\n        this.clearRTTPool();\n        if (!this._rttSharedFbo) return;\n        // Detach so Framebuffer.destroy() doesn't delete the texture/renderbuffer\n        // that we already manage separately.\n        this._rttSharedFbo.fbo.colorAttachment.set(null);\n        this._rttSharedFbo.fbo.depthAttachment.set(null);\n        const gl = this.context.gl;\n        gl.deleteRenderbuffer(this._rttSharedFbo.depthRenderbuffer);\n        gl.deleteFramebuffer(this._rttSharedFbo.fbo.framebuffer);\n        this._rttSharedFbo = null;\n    }\n\n    /*\n     * Set GL state shared by all layers.\n     */\n    setBaseState(): void {\n        const gl = this.context.gl;\n        this.context.cullFace.set(false);\n        this.context.viewport.set([0, 0, this.width, this.height]);\n        this.context.blendEquation.set(gl.FUNC_ADD);\n    }\n\n    initDebugOverlayCanvas(): void {\n        if (this.debugOverlayCanvas == null) {\n            this.debugOverlayCanvas = document.createElement('canvas');\n            this.debugOverlayCanvas.width = 512;\n            this.debugOverlayCanvas.height = 512;\n            const gl = this.context.gl;\n            this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA);\n        }\n    }\n\n    destroy(): void {\n        if (this._tileTextures) {\n            for (const size in this._tileTextures) {\n                const textures = this._tileTextures[size];\n                if (textures) {\n                    for (const texture of textures) {\n                        texture.destroy();\n                    }\n                }\n            }\n            this._tileTextures = {};\n        }\n\n        this.destroyRTTResources();\n\n        this.layerOpacityFbo?.destroy();\n        this.layerOpacityFbo = null;\n\n        if (this.tileExtentBuffer) this.tileExtentBuffer.destroy();\n        if (this.debugBuffer) this.debugBuffer.destroy();\n        if (this.rasterBoundsBuffer) this.rasterBoundsBuffer.destroy();\n        if (this.viewportBuffer) this.viewportBuffer.destroy();\n        if (this.tileBorderIndexBuffer) this.tileBorderIndexBuffer.destroy();\n        if (this.quadTriangleIndexBuffer) this.quadTriangleIndexBuffer.destroy();\n        if (this.tileExtentMesh) this.tileExtentMesh.vertexBuffer?.destroy();\n        if (this.tileExtentMesh) this.tileExtentMesh.indexBuffer?.destroy();\n        this.skyMesh?.destroy();\n        this.skyMesh = null;\n\n        if (this.debugOverlayTexture) {\n            this.debugOverlayTexture.destroy();\n        }\n\n        this.context.destroy();\n\n        this.programCache.destroy();\n\n        if (this.context) {\n            this.context.setDefault();\n        }\n    }\n\n    /*\n     * Return true if drawing buffer size is != from requested size.\n     * That means that we've reached GL limits somehow.\n     * Note: drawing buffer size changes only when canvas size changes\n     */\n    overLimit(): boolean {\n        const {drawingBufferWidth, drawingBufferHeight} = this.context.gl;\n        return this.width !== drawingBufferWidth || this.height !== drawingBufferHeight;\n    }\n}\n", "/**\n * Thrown by the `Map` constructor when a GPU rendering context cannot be created,\n * or fired via the map's `error` event when recreating the context after a `webglcontextrestored` fails.\n *\n * Carries the canvas attributes that were requested and, when the browser provided one,\n * the originating `webglcontextcreationerror` `statusMessage`.\n * Consumers can branch on `instanceof GPUInitializationError` and inspect the cause programmatically.\n * @see https://wiki.openstreetmap.org/wiki/This_map_requires_WebGL\n */\nexport class GPUInitializationError extends Error {\n    readonly requestedAttributes: WebGLContextAttributes;\n    readonly statusMessage: string | null;\n\n    constructor(requestedAttributes: WebGLContextAttributes, creationEvent: WebGLContextEvent | null) {\n        super('WebGL2 is required to display this map. We are sorry, but it seems that your browser does not support WebGL2, a technology for rendering 3D graphics on the web. Read more on https://wiki.openstreetmap.org/wiki/This_map_requires_WebGL');\n        this.name = 'GPUInitializationError';\n        this.requestedAttributes = requestedAttributes;\n        this.statusMessage = creationEvent?.statusMessage ?? null;\n    }\n}\n", "/**\n * Throttle the given function to run at most every `period` milliseconds.\n */\nexport function throttle<T extends (...args: any) => void>(fn: T, time: number): (...args: Parameters<T>) => ReturnType<typeof setTimeout> {\n    let pending = false;\n    let timerId: ReturnType<typeof setTimeout> = null;\n    let lastCallArgs: Parameters<T>;\n\n    const later = () => {\n        timerId = null;\n        if (pending) {\n            fn(...lastCallArgs);\n            timerId = setTimeout(later, time);\n            pending = false;\n        }\n    };\n\n    return (...args: Parameters<T>) => {\n        pending = true;\n        lastCallArgs = args;\n        if (!timerId) {\n            later();\n        }\n        return timerId;\n    };\n}\n", "import {throttle} from '../util/throttle.ts';\nimport {LngLat} from '../geo/lng_lat.ts';\nimport {degreesPerWorldUnit} from '../geo/projection/mercator_utils.ts';\n\nimport type {Map} from './map.ts';\n\n/**\n * Adds the map's position to its page's location hash.\n * Passed as an option to the map object.\n *\n * @group Markers and Controls\n */\nexport class Hash {\n    _map: Map;\n    _hashName: string;\n\n    constructor(hashName?: string | null) {\n        this._hashName = hashName && encodeURIComponent(hashName);\n    }\n\n    /**\n     * Map element to listen for coordinate changes\n     *\n     * @param map - The map object\n     */\n    addTo(map: Map): this {\n        this._map = map;\n        addEventListener('hashchange', this._onHashChange, false);\n        this._map.on('moveend', this._updateHash);\n        return this;\n    }\n\n    /**\n     * Removes hash\n     */\n    remove(): this {\n        removeEventListener('hashchange', this._onHashChange, false);\n        this._map.off('moveend', this._updateHash);\n        clearTimeout(this._updateHash());\n        this._removeHash();\n\n        delete this._map;\n        return this;\n    }\n\n    getHashString(mapFeedback?: boolean): string {\n        const center = this._map.getCenter(),\n            zoom = Math.round(this._map.getZoom() * 100) / 100,\n            degreesPerWorld = degreesPerWorldUnit(this._map._camera.transform.worldCoordinateHelper, center),\n            // derived from equation: 512px * 2^z / degreesPerWorld / 10^d < 0.5px\n            precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / degreesPerWorld / 0.5)) / Math.LN10),\n            m = Math.pow(10, precision),\n            lng = Math.round(center.lng * m) / m,\n            lat = Math.round(center.lat * m) / m,\n            bearing = this._map.getBearing(),\n            pitch = this._map.getPitch();\n        let hash = '';\n        if (mapFeedback) {\n            // new map feedback site has some constraints that don't allow\n            // us to use the same hash format as we do for the Map hash option.\n            hash += `/${lng}/${lat}/${zoom}`;\n        } else {\n            hash += `${zoom}/${lat}/${lng}`;\n        }\n\n        if (bearing || pitch) hash += (`/${Math.round(bearing * 10) / 10}`);\n        if (pitch) hash += (`/${Math.round(pitch)}`);\n\n        if (this._hashName) {\n            const params = this._getHashParams();\n            params.set(this._hashName, hash);\n            return `#${decodeURIComponent(params.toString()).replace(/=&/g, '&').replace(/=$/g, '')}`;\n        }\n\n        return `#${hash}`;\n    }\n\n    _getHashParams = (): URLSearchParams => {\n        return new URLSearchParams(window.location.hash.replace('#', ''));\n    };\n\n    _getCurrentHash = (): string[] => {\n        const params = this._getHashParams();\n        if (this._hashName) {\n            return (params.get(this._hashName) || '').split('/');\n        }\n        // For unnamed hashes, get the first key\n        const hash = [...params.keys()][0] ?? '';\n        return hash.split('/');\n    };\n\n    _onHashChange = (): boolean => {\n        const hash = this._getCurrentHash();\n\n        if (!this._isValidHash(hash)) {\n            return false;\n        }\n\n        const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(hash[3] || 0) : this._map.getBearing();\n        this._map.jumpTo({\n            center: [+hash[2], +hash[1]],\n            zoom: +hash[0],\n            bearing,\n            pitch: +(hash[4] || 0)\n        });\n\n        return true;\n    };\n\n    _updateHashUnthrottled = (): void => {\n        const location = window.location.href.replace(/(#.*)?$/, this.getHashString());\n        window.history.replaceState(window.history.state, null, location);\n    };\n\n    _removeHash = (): void => {\n        const params = this._getHashParams();\n\n        if (this._hashName) {\n            params.delete(this._hashName);\n        } else {\n            // For unnamed hash (#zoom/lat/lng&other=params), remove first entry\n            const keys = Array.from(params.keys());\n            if (keys.length > 0) {\n                params.delete(keys[0]);\n            }\n        }\n\n        const newHash = decodeURIComponent(params.toString()).replace(/=&/g, '&').replace(/=$/g, '');\n        const replaceString = newHash ? `#${newHash}` : '';\n        let location = window.location.href.replace(/(#.+)?$/, replaceString);\n        location = location.replace('&&', '&');\n        window.history.replaceState(window.history.state, null, location);\n    };\n\n    /**\n     * Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds.\n     */\n    _updateHash: () => ReturnType<typeof setTimeout> = throttle(this._updateHashUnthrottled, 30 * 1000 / 100);\n\n    _isValidHash(hash: string[]): boolean {\n        if (hash.length < 3 || hash.some(h => isNaN(+h))) {\n            return false;\n        }\n\n        // LngLat() throws error if latitude is out of range, and it's valid if it succeeds.\n        try {\n            new LngLat(+hash[2], +hash[1]);\n        } catch {\n            return false;\n        }\n\n        const zoom = +hash[0];\n        const bearing = +(hash[3] || 0);\n        const pitch = +(hash[4] || 0);\n\n        return zoom >= this._map.getMinZoom() && zoom <= this._map.getMaxZoom() &&\n            bearing >= -180 && bearing <= 180 &&\n            pitch >= this._map.getMinPitch() && pitch <= this._map.getMaxPitch();\n    };\n}\n", "import {now} from '../util/time_control.ts';\nimport {bezier, clamp, extend, evaluateZoomSnap} from '../util/util.ts';\nimport Point from '@mapbox/point-geometry';\n\nimport type {DragPanOptions} from './handler/shim/drag_pan.ts';\nimport type {HandlerResult} from './handler_manager.ts';\nimport type {EaseToOptions} from './camera.ts';\nimport type {Map} from './map.ts';\n\nconst defaultInertiaOptions = {\n    linearity: 0.3,\n    easing: bezier(0, 0, 0.3, 1),\n};\n\nconst defaultPanInertiaOptions = extend({\n    deceleration: 2500,\n    maxSpeed: 1400\n}, defaultInertiaOptions);\n\nconst defaultZoomInertiaOptions = extend({\n    deceleration: 20,\n    maxSpeed: 1400\n}, defaultInertiaOptions);\n\nconst defaultBearingInertiaOptions = extend({\n    deceleration: 1000,\n    maxSpeed: 360\n}, defaultInertiaOptions);\n\nconst defaultPitchInertiaOptions = extend({\n    deceleration: 1000,\n    maxSpeed: 90\n}, defaultInertiaOptions);\n\nconst defaultRollInertiaOptions = extend({\n    deceleration: 1000,\n    maxSpeed: 360\n}, defaultInertiaOptions);\n\nexport type InertiaOptions = {\n    linearity: number;\n    easing: (t: number) => number;\n    deceleration: number;\n    maxSpeed: number;\n};\n\n/**\n * The maximum age of a recorded gesture update, in milliseconds.\n */\nconst BUFFER_CUTOFF = 160;\n\n/**\n * The time window the gesture velocity is measured over, in milliseconds.\n */\nconst VELOCITY_WINDOW = 60;\n\ntype InertiaBufferEntry = {\n    time: number;\n    settings: HandlerResult;\n};\n\nexport class HandlerInertia {\n    _map: Map;\n    _inertiaBuffer: InertiaBufferEntry[];\n\n    constructor(map: Map) {\n        this._map = map;\n        this.clear();\n    }\n\n    clear(): void {\n        this._inertiaBuffer = [];\n    }\n\n    record(settings: HandlerResult): void {\n        this._drainInertiaBuffer();\n        this._inertiaBuffer.push({time: now(), settings});\n    }\n\n    _drainInertiaBuffer(): void {\n        const inertia = this._inertiaBuffer,\n            currentTime = now();\n\n        while (inertia.length > 0 && currentTime - inertia[0].time > BUFFER_CUTOFF)\n            inertia.shift();\n    }\n\n    /**\n     * Returns the entries the velocity is measured from: everything recorded within\n     * {@link VELOCITY_WINDOW} before now, but never fewer than the last two, so that\n     * inertia also works below two recorded updates per window.\n     */\n    _getVelocityEntries(): InertiaBufferEntry[] {\n        const inertia = this._inertiaBuffer;\n        const windowStart = now() - VELOCITY_WINDOW;\n\n        let firstIndex = Math.max(0, inertia.length - 2);\n        while (firstIndex > 0 && inertia[firstIndex - 1].time >= windowStart) {\n            firstIndex--;\n        }\n\n        return inertia.slice(firstIndex);\n    }\n\n    /**\n     * Returns the ease which continues the gesture that has just ended.\n     *\n     * The velocity is measured over the time up to the release and not up to the last\n     * recorded movement, so that a gesture held still before being released has a lower\n     * velocity, down to no inertia at all. The delta of an entry happened before it was\n     * recorded, so the first entry only marks the start of the measured interval; anchors\n     * are the exception, as they describe the state at the moment of their entry.\n     *\n     * @param panInertiaOptions - overrides for the pan inertia defaults\n     * @returns the ease options, or `undefined` when the measured interval holds no\n     * movement, which terrain gestures produce by recording updates without any delta\n     */\n    _onMoveEnd(panInertiaOptions?: DragPanOptions | boolean): EaseToOptions {\n        this._drainInertiaBuffer();\n        const entries = this._getVelocityEntries();\n        if (entries.length < 2) {\n            this.clear();\n            return;\n        }\n\n        const deltas = {\n            zoom: 0,\n            bearing: 0,\n            pitch: 0,\n            roll: 0,\n            pan: new Point(0, 0),\n            pinchAround: undefined,\n            around: undefined\n        };\n\n        for (const {settings} of entries) {\n            if (settings.around) deltas.around = settings.around;\n            if (settings.pinchAround) deltas.pinchAround = settings.pinchAround;\n        }\n\n        for (const {settings} of entries.slice(1)) {\n            deltas.zoom += settings.zoomDelta || 0;\n            deltas.bearing += settings.bearingDelta || 0;\n            deltas.pitch += settings.pitchDelta || 0;\n            deltas.roll += settings.rollDelta || 0;\n            if (settings.panDelta) deltas.pan._add(settings.panDelta);\n        }\n\n        if (!deltas.pan.mag() && !deltas.zoom && !deltas.bearing && !deltas.pitch && !deltas.roll) {\n            this.clear();\n            return;\n        }\n\n        const duration = now() - entries[0].time;\n\n        const easeOptions = {} as any;\n\n        if (deltas.pan.mag()) {\n            const result = calculateEasing(deltas.pan.mag(), duration, extend({}, defaultPanInertiaOptions, panInertiaOptions || {}));\n            const finalPan = deltas.pan.mult(result.amount / deltas.pan.mag());\n            const computedEaseOptions = this._map._camera.cameraHelper.handlePanInertia(finalPan, this._map._camera.transform);\n            easeOptions.center = computedEaseOptions.easingCenter;\n            easeOptions.offset = computedEaseOptions.easingOffset;\n            extendDuration(easeOptions, result);\n        }\n\n        if (deltas.zoom) {\n            const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions);\n            easeOptions.zoom = evaluateZoomSnap(this._map.getZoom() + result.amount, this._map.getZoomSnap(), result.amount);\n            extendDuration(easeOptions, result);\n        }\n\n        if (deltas.bearing) {\n            const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions);\n            easeOptions.bearing = this._map.getBearing() + clamp(result.amount, -179, 179);\n            extendDuration(easeOptions, result);\n        }\n\n        if (deltas.pitch) {\n            const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions);\n            easeOptions.pitch = this._map.getPitch() + result.amount;\n            extendDuration(easeOptions, result);\n        }\n\n        if (deltas.roll) {\n            const result = calculateEasing(deltas.roll, duration, defaultRollInertiaOptions);\n            easeOptions.roll = this._map.getRoll() + clamp(result.amount, -179, 179);\n            extendDuration(easeOptions, result);\n        }\n\n        if (easeOptions.zoom || easeOptions.bearing) {\n            const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround;\n            easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter();\n        }\n\n        this.clear();\n        return extend(easeOptions, {\n            noMoveStart: true\n        });\n\n    }\n}\n\n// Unfortunately zoom, bearing, etc can't have different durations and easings so\n// we need to choose one. We use the longest duration and it's corresponding easing.\nfunction extendDuration(easeOptions, result) {\n    if (!easeOptions.duration || easeOptions.duration < result.duration) {\n        easeOptions.duration = result.duration;\n        easeOptions.easing = result.easing;\n    }\n}\n\nfunction calculateEasing(amount, inertiaDuration: number, inertiaOptions) {\n    const {maxSpeed, linearity, deceleration} = inertiaOptions;\n    const speed = clamp(\n        amount * linearity / (inertiaDuration / 1000),\n        -maxSpeed,\n        maxSpeed);\n    const duration = Math.abs(speed) / (deceleration * linearity);\n    return {\n        easing: inertiaOptions.easing,\n        duration: duration * 1000,\n        amount: speed * (duration / 2)\n    };\n}\n", "import {MapMouseEvent, MapTouchEvent, MapWheelEvent} from '../events.ts';\n\nimport type {Handler, HandlerResult} from '../handler_manager.ts';\nimport type {Map} from '../map.ts';\nimport type Point from '@mapbox/point-geometry';\n\nexport class MapEventHandler implements Handler {\n\n    _mousedownPos: Point;\n    _clickTolerance: number;\n    _map: Map;\n\n    constructor(map: Map, options: {\n        clickTolerance: number;\n    }) {\n        this._map = map;\n        this._clickTolerance = options.clickTolerance;\n    }\n\n    reset(): void {\n        delete this._mousedownPos;\n    }\n\n    wheel(e: WheelEvent): HandlerResult | void {\n        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n        // - ScrollZoom\n        return this._firePreventable(new MapWheelEvent(this._map, e));\n    }\n\n    mousedown(e: MouseEvent, point: Point): HandlerResult | void {\n        this._mousedownPos = point;\n        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n        // - MousePan\n        // - MouseRotate\n        // - MousePitch\n        // - DblclickHandler\n        return this._firePreventable(new MapMouseEvent(e.type, this._map, e));\n    }\n\n    mouseup(e: MouseEvent): void {\n        this._map.fire(new MapMouseEvent(e.type, this._map, e));\n    }\n\n    click(e: MouseEvent, point: Point): void {\n        if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) return;\n        this._map.fire(new MapMouseEvent(e.type, this._map, e));\n    }\n\n    dblclick(e: MouseEvent): HandlerResult | void {\n        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n        // - DblClickZoom\n        return this._firePreventable(new MapMouseEvent(e.type, this._map, e));\n    }\n\n    mouseover(e: MouseEvent): void {\n        this._map.fire(new MapMouseEvent(e.type, this._map, e));\n    }\n\n    mouseout(e: MouseEvent): void {\n        this._map.fire(new MapMouseEvent(e.type, this._map, e));\n    }\n\n    touchstart(e: TouchEvent): HandlerResult | void {\n        // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n        // - TouchPan\n        // - TouchZoom\n        // - TouchRotate\n        // - TouchPitch\n        // - TapZoom\n        // - SwipeZoom\n        return this._firePreventable(new MapTouchEvent(e.type, this._map, e));\n    }\n\n    touchmove(e: TouchEvent): void {\n        this._map.fire(new MapTouchEvent(e.type, this._map, e));\n    }\n\n    touchend(e: TouchEvent): void {\n        this._map.fire(new MapTouchEvent(e.type, this._map, e));\n    }\n\n    touchcancel(e: TouchEvent): void {\n        this._map.fire(new MapTouchEvent(e.type, this._map, e));\n    }\n\n    _firePreventable(mapEvent: MapMouseEvent | MapTouchEvent | MapWheelEvent): HandlerResult | void {\n        this._map.fire(mapEvent);\n        if (mapEvent.defaultPrevented) {\n            // returning an object marks the handler as active and resets other handlers\n            return {};\n        }\n    }\n\n    isEnabled(): boolean {\n        return true;\n    }\n\n    isActive(): boolean {\n        return false;\n    }\n    enable(): void {}\n    disable(): void {}\n}\n\n/**\n * A single finger held in place this long fires a long-press contextmenu.\n */\nconst LONG_PRESS_DELAY = 500;\n\nexport class BlockableMapEventHandler {\n    _map: Map;\n    _clickTolerance: number;\n    _delayContextMenu: boolean;\n    _ignoreContextMenu: boolean;\n    _contextMenuEvent: MouseEvent;\n    _touchActive: boolean;\n    _longPressTimer: ReturnType<typeof setTimeout>;\n    _longPressStart: Point;\n\n    constructor(map: Map, options: {\n        clickTolerance: number;\n    }) {\n        this._map = map;\n        this._clickTolerance = options.clickTolerance;\n    }\n\n    reset(): void {\n        this._delayContextMenu = false;\n        this._ignoreContextMenu = true;\n        delete this._contextMenuEvent;\n        this._clearLongPress();\n        this._touchActive = false;\n    }\n\n    mousemove(e: MouseEvent): void {\n        // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active\n        this._map.fire(new MapMouseEvent(e.type, this._map, e));\n    }\n\n    mousedown(): void {\n        this._delayContextMenu = true;\n        this._ignoreContextMenu = false;\n    }\n\n    mouseup(): void {\n        this._delayContextMenu = false;\n        if (this._contextMenuEvent) {\n            this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent));\n            delete this._contextMenuEvent;\n        }\n    }\n\n    /**\n     * Starts the touch long press. Touch devices have no right click, so a long press opens\n     * the context menu. It is detected with a timer rather than by relying on a native\n     * contextmenu event, because Android Chrome fires one on a long press but iOS\n     * Safari does not. A single finger held past the delay without moving fires a\n     * contextmenu at that point; a pan or a lift cancels it.\n     * @param e - the touch event\n     * @param points - the touch points, in map coordinates\n     * @param mapTouches - the touches that are on the map\n     */\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        this._clearLongPress();\n        this._touchActive = mapTouches.length > 0;\n        if (mapTouches.length !== 1) return; // single finger only, never during a pinch\n        this._longPressStart = points[0];\n        const touch = mapTouches[0];\n        this._longPressTimer = setTimeout(() => {\n            this._longPressTimer = undefined;\n            const originalEvent = new MouseEvent('contextmenu', {clientX: touch.clientX, clientY: touch.clientY, button: 2, bubbles: true, cancelable: true});\n            this._map.fire(new MapMouseEvent('contextmenu', this._map, originalEvent));\n        }, LONG_PRESS_DELAY);\n    }\n\n    /**\n     * Cancels a pending long press once the finger has moved further than the map's\n     * click tolerance, or once a second finger lands.\n     * @param e - the touch event\n     * @param points - the touch points, in map coordinates\n     * @param mapTouches - the touches that are on the map\n     */\n    touchmove(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        if (!this._longPressTimer) return;\n        if (mapTouches.length !== 1 || !this._longPressStart || points[0].dist(this._longPressStart) > this._clickTolerance) {\n            this._clearLongPress();\n        }\n    }\n\n    touchend(): void {\n        this._touchActive = false;\n        this._clearLongPress();\n    }\n\n    touchcancel(): void {\n        this._touchActive = false;\n        this._clearLongPress();\n    }\n\n    _clearLongPress(): void {\n        if (this._longPressTimer) {\n            clearTimeout(this._longPressTimer);\n            this._longPressTimer = undefined;\n        }\n        this._longPressStart = undefined;\n    }\n\n    /**\n     * Handles a contextmenu event. A native one during a touch is suppressed, because the\n     * long press timer already fires the event and the browser menu would double up.\n     * @param e - the mouse event\n     */\n    contextmenu(e: MouseEvent): void {\n        if (this._touchActive) {\n            e.preventDefault();\n            return;\n        }\n        if (this._delayContextMenu) {\n            // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake\n            this._contextMenuEvent = e;\n        } else if (!this._ignoreContextMenu) {\n            // Windows: contextmenu fired on mouseup, so fire event now\n            this._map.fire(new MapMouseEvent(e.type, this._map, e));\n        }\n\n        // prevent browser context menu when necessary\n        if (this._map.listens('contextmenu')) {\n            e.preventDefault();\n        }\n    }\n\n    isEnabled(): boolean {\n        return true;\n    }\n\n    isActive(): boolean {\n        return false;\n    }\n    enable(): void {}\n    disable(): void {}\n}\n", "import {DOM} from '../../util/dom.ts';\nimport {MapBoxZoomEvent} from '../events.ts';\n\nimport type {Map} from '../map.ts';\nimport type {Handler} from '../handler_manager.ts';\nimport type {TransformProvider} from './transform-provider.ts';\nimport type Point from '@mapbox/point-geometry';\n\n/**\n * Callback for customizing what happens when a box zoom gesture ends.\n */\nexport type BoxZoomEndHandler = (map: Map, startPos: Point, endPos: Point, originalEvent: MouseEvent) => void;\n\n/**\n * A {@link BoxZoomHandler} options object.\n */\nexport type BoxZoomHandlerOptions = {\n    /**\n     * A callback that runs when the user completes the Shift-drag box gesture.\n     * Providing this callback suppresses the default fit-to-box zoom behavior.\n     */\n    boxZoomEnd?: BoxZoomEndHandler;\n};\n\n/**\n * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box.\n * The bounding box is defined by clicking and holding `shift` while dragging the cursor.\n *\n * @group Handlers\n */\nexport class BoxZoomHandler implements Handler {\n    _map: Map;\n    _tr: TransformProvider;\n    _el: HTMLElement;\n    _container: HTMLElement;\n    _enabled: boolean;\n    _active: boolean;\n    _startPos: Point;\n    _lastPos: Point;\n    _box: HTMLElement;\n    _clickTolerance: number;\n    _boxZoomEnd?: BoxZoomEndHandler;\n\n    /** @internal */\n    constructor(map: Map, options: {\n        clickTolerance: number;\n        boxZoom?: boolean | BoxZoomHandlerOptions;\n    }, transformProvider: TransformProvider) {\n        this._map = map;\n        this._tr = transformProvider;\n        this._el = map.getCanvasContainer();\n        this._container = map.getContainer();\n        this._clickTolerance = options.clickTolerance || 1;\n        if (options.boxZoom && typeof options.boxZoom === 'object') {\n            this._boxZoomEnd = options.boxZoom.boxZoomEnd;\n        }\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"box zoom\" interaction is enabled.\n     *\n     * @returns `true` if the \"box zoom\" interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return !!this._enabled;\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"box zoom\" interaction is active, i.e. currently being used.\n     *\n     * @returns `true` if the \"box zoom\" interaction is active.\n     */\n    isActive(): boolean {\n        return !!this._active;\n    }\n\n    /**\n     * Enables the \"box zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.boxZoom.enable();\n     * ```\n     */\n    enable(): void {\n        if (this.isEnabled()) return;\n        this._enabled = true;\n    }\n\n    /**\n     * Disables the \"box zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.boxZoom.disable();\n     * ```\n     */\n    disable(): void {\n        if (!this.isEnabled()) return;\n        this._enabled = false;\n    }\n\n    mousedown(e: MouseEvent, point: Point): void {\n        if (!this.isEnabled()) return;\n        if (!(e.shiftKey && e.button === 0)) return;\n\n        DOM.disableDrag();\n        this._startPos = this._lastPos = point;\n        this._active = true;\n    }\n\n    mousemoveWindow(e: MouseEvent, point: Point): void {\n        if (!this._active) return;\n\n        const pos = point;\n\n        if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) {\n            return;\n        }\n\n        const p0 = this._startPos;\n        this._lastPos = pos;\n\n        if (!this._box) {\n            this._box = DOM.create('div', 'maplibregl-boxzoom', this._container);\n            this._container.classList.add('maplibregl-crosshair');\n            this._fireEvent('boxzoomstart', e);\n        }\n\n        const minX = Math.min(p0.x, pos.x),\n            maxX = Math.max(p0.x, pos.x),\n            minY = Math.min(p0.y, pos.y),\n            maxY = Math.max(p0.y, pos.y);\n\n        this._box.style.transform = `translate(${minX}px,${minY}px)`;\n\n        this._box.style.width = `${maxX - minX}px`;\n        this._box.style.height = `${maxY - minY}px`;\n    }\n\n    mouseupWindow(e: MouseEvent, point: Point): {cameraAnimation: (map: Map) => Map} | void {\n        if (!this._active) return;\n\n        if (e.button !== 0) return;\n\n        const p0 = this._startPos,\n            p1 = point;\n\n        this.reset();\n\n        DOM.suppressClick();\n\n        if (p0.x === p1.x && p0.y === p1.y) {\n            this._fireEvent('boxzoomcancel', e);\n        } else {\n            this._map.fire(new MapBoxZoomEvent('boxzoomend', {originalEvent: e}));\n            if (this._boxZoomEnd) {\n                this._boxZoomEnd(this._map, p0, p1, e);\n                return;\n            }\n            return {\n                cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._tr.bearing, {linear: true})\n            };\n        }\n    }\n\n    keydown(e: KeyboardEvent): void {\n        if (!this._active) return;\n\n        if (e.keyCode === 27) {\n            this.reset();\n            this._fireEvent('boxzoomcancel', e);\n        }\n    }\n\n    reset(): void {\n        this._active = false;\n\n        this._container.classList.remove('maplibregl-crosshair');\n\n        if (this._box) {\n            this._box.remove();\n            this._box = null;\n        }\n\n        DOM.enableDrag();\n\n        delete this._startPos;\n        delete this._lastPos;\n    }\n\n    _fireEvent(type: string, e: MouseEvent | KeyboardEvent): Map {\n        return this._map.fire(new MapBoxZoomEvent(type, {originalEvent: e}));\n    }\n}\n", "import type Point from '@mapbox/point-geometry';\n\nexport function indexTouches(touches: Touch[], points: Point[]): Record<number, Point> {\n    if (touches.length !== points.length) throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`);\n    const obj: Record<number, Point> = {};\n    for (let i = 0; i < touches.length; i++) {\n        obj[touches[i].identifier] = points[i];\n    }\n    return obj;\n}\n", "import Point from '@mapbox/point-geometry';\nimport {indexTouches} from './handler_util.ts';\n\nfunction getCentroid(points: Point[]) {\n    const sum = new Point(0, 0);\n    for (const point of points) {\n        sum._add(point);\n    }\n    return sum.div(points.length);\n}\n\nexport const MAX_TAP_INTERVAL = 500;\nconst MAX_TOUCH_TIME = 500;\nexport const MAX_DIST = 30;\n\nexport class SingleTapRecognizer {\n\n    numTouches: number;\n    centroid: Point;\n    startTime: number;\n    aborted: boolean;\n    touches: {\n        [k in number | string]: Point;\n    };\n\n    constructor(options: {\n        numTouches: number;\n    }) {\n        this.reset();\n        this.numTouches = options.numTouches;\n    }\n\n    reset(): void {\n        delete this.centroid;\n        delete this.startTime;\n        delete this.touches;\n        this.aborted = false;\n    }\n\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n\n        if (this.centroid || mapTouches.length > this.numTouches) {\n            this.aborted = true;\n        }\n        if (this.aborted) {\n            return;\n        }\n\n        if (this.startTime === undefined) {\n            this.startTime = e.timeStamp;\n        }\n\n        if (mapTouches.length === this.numTouches) {\n            this.centroid = getCentroid(points);\n            this.touches = indexTouches(mapTouches, points);\n        }\n    }\n\n    touchmove(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        if (this.aborted || !this.centroid) return;\n\n        const newTouches = indexTouches(mapTouches, points);\n        for (const id in this.touches) {\n            const prevPos = this.touches[id];\n            const pos = newTouches[id];\n            if (!pos || pos.dist(prevPos) > MAX_DIST) {\n                this.aborted = true;\n            }\n        }\n    }\n\n    touchend(e: TouchEvent, points: Point[], mapTouches: Touch[]): Point | void {\n        if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) {\n            this.aborted = true;\n        }\n\n        if (mapTouches.length === 0) {\n            const centroid = !this.aborted && this.centroid;\n            this.reset();\n            if (centroid) return centroid;\n        }\n    }\n\n}\n\nexport class TapRecognizer {\n\n    singleTap: SingleTapRecognizer;\n    numTaps: number;\n    lastTime: number;\n    lastTap: Point;\n    count: number;\n\n    constructor(options: {\n        numTaps: number;\n        numTouches: number;\n    }) {\n        this.singleTap = new SingleTapRecognizer(options);\n        this.numTaps = options.numTaps;\n        this.reset();\n    }\n\n    reset(): void {\n        this.lastTime = Infinity;\n        delete this.lastTap;\n        this.count = 0;\n        this.singleTap.reset();\n    }\n\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        this.singleTap.touchstart(e, points, mapTouches);\n    }\n\n    touchmove(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        this.singleTap.touchmove(e, points, mapTouches);\n    }\n\n    touchend(e: TouchEvent, points: Point[], mapTouches: Touch[]): Point | void {\n        const tap = this.singleTap.touchend(e, points, mapTouches);\n        if (tap) {\n            const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL;\n            const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST;\n\n            if (!soonEnough || !closeEnough) {\n                this.reset();\n            }\n\n            this.count++;\n            this.lastTime = e.timeStamp;\n            this.lastTap = tap;\n\n            if (this.count === this.numTaps) {\n                this.reset();\n                return tap;\n            }\n        }\n    }\n}\n", "import {TapRecognizer} from './tap_recognizer.ts';\nimport {evaluateZoomSnap} from '../../util/util.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Map} from '../map.ts';\nimport type {TransformProvider} from './transform-provider.ts';\nimport type {Handler} from '../handler_manager.ts';\n\n/**\n * A `TapZoomHandler` allows the user to zoom the map at a point by double tapping\n */\nexport class TapZoomHandler implements Handler {\n    _tr: TransformProvider;\n    _enabled: boolean;\n    _active: boolean;\n    _zoomIn: TapRecognizer;\n    _zoomOut: TapRecognizer;\n\n    constructor(map: Map, transformProvider: TransformProvider) {\n        this._tr = transformProvider;\n        this._zoomIn = new TapRecognizer({\n            numTouches: 1,\n            numTaps: 2\n        });\n\n        this._zoomOut = new TapRecognizer({\n            numTouches: 2,\n            numTaps: 1\n        });\n\n        this.reset();\n    }\n\n    reset(): void {\n        this._active = false;\n        this._zoomIn.reset();\n        this._zoomOut.reset();\n    }\n\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        this._zoomIn.touchstart(e, points, mapTouches);\n        this._zoomOut.touchstart(e, points, mapTouches);\n    }\n\n    touchmove(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        this._zoomIn.touchmove(e, points, mapTouches);\n        this._zoomOut.touchmove(e, points, mapTouches);\n    }\n\n    touchend(e: TouchEvent, points: Point[], mapTouches: Touch[]): {cameraAnimation: (map: Map) => Map} | void {\n        const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches);\n        const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches);\n        const tr = this._tr;\n\n        if (zoomInPoint) {\n            this._active = true;\n            e.preventDefault();\n            setTimeout(() => this.reset(), 0);\n            return {\n                cameraAnimation: (map: Map) => map.easeTo({\n                    duration: 300,\n                    zoom: evaluateZoomSnap(tr.zoom + 1, map.getZoomSnap()),\n                    around: tr.transform.isPointOnMapSurface(zoomInPoint) ? tr.unproject(zoomInPoint) : undefined\n                }, {originalEvent: e})\n            };\n        } else if (zoomOutPoint) {\n            this._active = true;\n            e.preventDefault();\n            setTimeout(() => this.reset(), 0);\n            return {\n                cameraAnimation: (map: Map) => map.easeTo({\n                    duration: 300,\n                    zoom: evaluateZoomSnap(tr.zoom - 1, map.getZoomSnap()),\n                    around: tr.transform.isPointOnMapSurface(zoomOutPoint) ? tr.unproject(zoomOutPoint) : undefined\n                }, {originalEvent: e})\n            };\n        }\n    }\n\n    touchcancel(): void {\n        this.reset();\n    }\n\n    enable(): void {\n        this._enabled = true;\n    }\n\n    disable(): void {\n        this._enabled = false;\n        this.reset();\n    }\n\n    isEnabled(): boolean {\n        return this._enabled;\n    }\n\n    isActive(): boolean {\n        return this._active;\n    }\n}\n", "import {DOM} from '../../util/dom.ts';\n\nimport type {DragMoveStateManager} from './drag_move_state_manager.ts';\nimport type {Handler} from '../handler_manager.ts';\nimport type Point from '@mapbox/point-geometry';\n\ntype DragMovementResult = {\n    bearingDelta?: number;\n    pitchDelta?: number;\n    rollDelta?: number;\n    around?: Point;\n    panDelta?: Point;\n};\n\nexport interface DragPanResult extends DragMovementResult {\n    around: Point;\n    panDelta: Point;\n}\n\nexport interface DragRotateResult extends DragMovementResult {\n    bearingDelta: number;\n}\n\nexport interface DragPitchResult extends DragMovementResult {\n    pitchDelta: number;\n}\n\nexport interface DragRollResult extends DragMovementResult {\n    rollDelta: number;\n}\n\ntype DragMoveFunction<T extends DragMovementResult> = (lastPoint: Point, currentPoint: Point, startPoint: Point) => T;\n\nexport interface DragMoveHandler<T extends DragMovementResult, E extends Event> extends Handler {\n    dragStart: (e: E, point: Point) => void;\n    dragMove: (e: E, point: Point) => T | void;\n    dragEnd: (e: E) => void;\n}\n\nexport type DragMoveHandlerOptions<T, E extends Event> = {\n    /**\n     * If the movement is shorter than this value, consider it a click.\n     */\n    clickTolerance: number;\n    /**\n     * The move function to run on a valid movement.\n     */\n    move: DragMoveFunction<T>;\n    /**\n     * A class used to manage the state of the drag event - start, checking valid moves, end. See the class documentation for more details.\n     */\n    moveStateManager: DragMoveStateManager<E>;\n    /**\n     * A method used to assign the dragStart, dragMove, and dragEnd methods to the relevant event handlers, as well as assigning the contextmenu handler\n     * @param handler - the handler\n     */\n    assignEvents: (handler: DragMoveHandler<T, E>) => void;\n    /**\n     * Should the move start on the \"start\" event, or should it start on the first valid move.\n     */\n    activateOnStart?: boolean;\n    /**\n     * If true, handler will be enabled during construction\n     */\n    enable?: boolean;\n};\n\n/**\n * A generic class to create handlers for drag events, from both mouse and touch events.\n */\nexport class DragHandler<T extends DragMovementResult, E extends Event> implements DragMoveHandler<T, E> {\n    // Event handlers that may be assigned by the implementations of this class\n    contextmenu?: Handler['contextmenu'];\n    mousedown?: Handler['mousedown'];\n    mousemoveWindow?: Handler['mousemoveWindow'];\n    mouseup?: Handler['mouseup'];\n    touchstart?: Handler['touchstart'];\n    touchmoveWindow?: Handler['touchmoveWindow'];\n    touchend?: Handler['touchend'];\n\n    _clickTolerance: number;\n    _moveFunction: DragMoveFunction<T>;\n    _activateOnStart: boolean;\n    _active: boolean;\n    _enabled: boolean;\n    _moved: boolean;\n    _lastPoint: Point | null;\n    _startPoint: Point | null;\n    _moveStateManager: DragMoveStateManager<E>;\n\n    constructor(options: DragMoveHandlerOptions<T, E>) {\n        this._enabled = !!options.enable;\n        this._moveStateManager = options.moveStateManager;\n        this._clickTolerance = options.clickTolerance || 1;\n        this._moveFunction = options.move;\n        this._activateOnStart = !!options.activateOnStart;\n\n        options.assignEvents(this);\n\n        this.reset();\n    }\n\n    reset(e?: E): void {\n        this._active = false;\n        this._moved = false;\n        delete this._lastPoint;\n        delete this._startPoint;\n        this._moveStateManager.endMove(e);\n    }\n\n    _move(...params: Parameters<DragMoveFunction<T>>): T | void {\n        const move = this._moveFunction(...params);\n        if (move.bearingDelta || move.pitchDelta || move.rollDelta || move.around || move.panDelta) {\n            this._active = true;\n            return move;\n        }\n    }\n\n    dragStart(e: E, point: Point): void;\n    dragStart(e: E, point: Point[]): void;\n    dragStart(e: E, point: Point | Point[]): void {\n        if (!this.isEnabled() || this._lastPoint) return;\n\n        if (!this._moveStateManager.isValidStartEvent(e)) return;\n        this._moveStateManager.startMove(e);\n\n        this._startPoint = Array.isArray(point) ? point[0] : point;\n        this._lastPoint = this._startPoint;\n\n        if (this._activateOnStart && this._lastPoint) this._active = true;\n    }\n\n    dragMove(e: E, point: Point): T | void;\n    dragMove(e: E, point: Point[]): T | void;\n    dragMove(e: E, point: Point | Point[]): T | void {\n        if (!this.isEnabled()) return;\n        const lastPoint = this._lastPoint;\n        if (!lastPoint) return;\n        e.preventDefault();\n\n        if (!this._moveStateManager.isValidMoveEvent(e)) {\n            this.reset(e);\n            return;\n        }\n\n        const movePoint = Array.isArray(point) ? point[0] : point;\n\n        if (!this._moved && movePoint.dist(lastPoint) < this._clickTolerance) return;\n        this._moved = true;\n        this._lastPoint = movePoint;\n\n        return this._move(lastPoint, movePoint, this._startPoint);\n    }\n\n    dragEnd(e: E): void {\n        if (!this.isEnabled() || !this._lastPoint) return;\n        if (!this._moveStateManager.isValidEndEvent(e)) return;\n        if (this._moved) DOM.suppressClick();\n        this.reset(e);\n    }\n\n    enable(): void {\n        this._enabled = true;\n    }\n\n    disable(): void {\n        this._enabled = false;\n        this.reset();\n    }\n\n    isEnabled(): boolean {\n        return this._enabled;\n    }\n\n    isActive(): boolean {\n        return this._active;\n    }\n\n    getClickTolerance(): number {\n        return this._clickTolerance;\n    }\n}\n", "const LEFT_BUTTON = 0;\nconst RIGHT_BUTTON = 2;\n\n// the values for each button in MouseEvent.buttons\nconst BUTTONS_FLAGS = {\n    [LEFT_BUTTON]: 1,\n    [RIGHT_BUTTON]: 2\n};\n\nfunction buttonNoLongerPressed(e: MouseEvent, button: number) {\n    const flag = BUTTONS_FLAGS[button];\n    return e.buttons === undefined || (e.buttons & flag) !== flag;\n}\n\n/*\n * Drag events are initiated by specific interaction which needs to be tracked until it ends.\n * This requires some state management:\n * 1. registering the initiating event,\n * 2. tracking that it was not canceled / not confusing it with another event firing.\n * 3. recognizing the ending event and cleaning up any internal state\n *\n * Concretely, we implement two state managers:\n * 1. MouseMoveStateManager\n *      Receives a functions that is used to recognize mouse events that should be registered as the\n *      relevant drag interactions - i.e. dragging with the right mouse button, or while CTRL is pressed.\n * 2. OneFingerTouchMoveStateManager\n *      Checks if a drag event is using one finger, and continuously tracking that this is the same event\n *      (i.e. to make sure not additional finger has started interacting with the screen before raising\n *      the first finger).\n */\nexport interface DragMoveStateManager<E extends Event> {\n    startMove: (e: E) => void;\n    endMove: (e?: E) => void;\n    isValidStartEvent: (e: E) => boolean;\n    isValidMoveEvent: (e: E) => boolean;\n    isValidEndEvent: (e?: E) => boolean;\n}\n\nexport class MouseMoveStateManager implements DragMoveStateManager<MouseEvent> {\n    _eventButton: number | undefined;\n    _correctEvent: (e: MouseEvent) => boolean;\n\n    constructor(options: {\n        checkCorrectEvent: (e: MouseEvent) => boolean;\n    }) {\n        this._correctEvent = options.checkCorrectEvent;\n    }\n\n    startMove(e: MouseEvent): void {\n        this._eventButton = e.button;\n    }\n\n    endMove(_e?: MouseEvent): void {\n        delete this._eventButton;\n    }\n\n    isValidStartEvent(e: MouseEvent): boolean {\n        return this._correctEvent(e);\n    }\n\n    isValidMoveEvent(e: MouseEvent): boolean {\n        // Some browsers don't fire a `mouseup` when the mouseup occurs outside\n        // the window or iframe:\n        // https://github.com/mapbox/mapbox-gl-js/issues/4622\n        //\n        // If the button is no longer pressed during this `mousemove` it may have\n        // been released outside of the window or iframe.\n        return !buttonNoLongerPressed(e, this._eventButton);\n    }\n\n    isValidEndEvent(e: MouseEvent): boolean {\n        const eventButton = e.button;\n        return eventButton === this._eventButton;\n    }\n}\n\nexport class OneFingerTouchMoveStateManager implements DragMoveStateManager<TouchEvent> {\n    _firstTouch: number | undefined;\n\n    constructor() {\n        this._firstTouch = undefined;\n    }\n\n    _isOneFingerTouch(e: TouchEvent): boolean {\n        return e.targetTouches.length === 1;\n    }\n\n    _isSameTouchEvent(e: TouchEvent): boolean {\n        return e.targetTouches[0].identifier === this._firstTouch;\n    }\n\n    startMove(e: TouchEvent): void {\n        this._firstTouch = e.targetTouches[0].identifier;\n    }\n\n    endMove(_e?: TouchEvent): void {\n        delete this._firstTouch;\n    }\n\n    isValidStartEvent(e: TouchEvent): boolean {\n        return this._isOneFingerTouch(e);\n    }\n\n    isValidMoveEvent(e: TouchEvent): boolean {\n        return this._isOneFingerTouch(e) && this._isSameTouchEvent(e);\n    }\n\n    isValidEndEvent(e: TouchEvent): boolean {\n        return this._isOneFingerTouch(e) && this._isSameTouchEvent(e);\n    }\n}\n\nexport class MouseOrTouchMoveStateManager implements DragMoveStateManager<MouseEvent | TouchEvent> {\n    constructor(\n        private mouseMoveStateManager: MouseMoveStateManager = new MouseMoveStateManager({checkCorrectEvent: () => true}),\n        private oneFingerTouchMoveStateManager: OneFingerTouchMoveStateManager = new OneFingerTouchMoveStateManager()\n    ) {}\n\n    _executeRelevantHandler(e: MouseEvent | TouchEvent, onMouseEvent: (e: MouseEvent) => boolean | void, onTouchEvent: (e: TouchEvent) => boolean | void): boolean | void {\n        if (e instanceof MouseEvent) return onMouseEvent(e);\n        if (typeof TouchEvent !== 'undefined' && e instanceof TouchEvent) return onTouchEvent(e);\n    }\n\n    startMove(e: MouseEvent | TouchEvent): void {\n        this._executeRelevantHandler(e,\n            e => { this.mouseMoveStateManager.startMove(e); },\n            e => { this.oneFingerTouchMoveStateManager.startMove(e); });\n    }\n\n    endMove(e?: MouseEvent | TouchEvent): void {\n        this._executeRelevantHandler(e,\n            e => { this.mouseMoveStateManager.endMove(e); },\n            e => { this.oneFingerTouchMoveStateManager.endMove(e); });\n    }\n\n    isValidStartEvent(e: MouseEvent | TouchEvent): boolean {\n        return !!this._executeRelevantHandler(e,\n            e => this.mouseMoveStateManager.isValidStartEvent(e),\n            e => this.oneFingerTouchMoveStateManager.isValidStartEvent(e));\n    }\n\n    isValidMoveEvent(e: MouseEvent | TouchEvent): boolean {\n        return !!this._executeRelevantHandler(e,\n            e => this.mouseMoveStateManager.isValidMoveEvent(e),\n            e => this.oneFingerTouchMoveStateManager.isValidMoveEvent(e));\n    }\n\n    isValidEndEvent(e?: MouseEvent | TouchEvent): boolean {\n        return !!this._executeRelevantHandler(e,\n            e => this.mouseMoveStateManager.isValidEndEvent(e),\n            e => this.oneFingerTouchMoveStateManager.isValidEndEvent(e));\n    }\n}\n", "import Point from '@mapbox/point-geometry';\nimport {type DragMoveHandler, type DragPanResult, type DragRotateResult, type DragPitchResult, DragHandler, type DragRollResult} from './drag_handler.ts';\nimport {MouseMoveStateManager} from './drag_move_state_manager.ts';\nimport {getAngleDelta} from '../../util/util.ts';\n\n/**\n * `MousePanHandler` allows the user to pan the map by clicking and dragging\n */\nexport interface MousePanHandler extends DragMoveHandler<DragPanResult, MouseEvent> {}\n/**\n * `MouseRotateHandler` allows the user to rotate the map by clicking and dragging\n */\nexport interface MouseRotateHandler extends DragMoveHandler<DragRotateResult, MouseEvent> {}\n/**\n * `MousePitchHandler` allows the user to zoom the map by pitching\n */\nexport interface MousePitchHandler extends DragMoveHandler<DragPitchResult, MouseEvent> {}\n/**\n * `MouseRollHandler` allows the user to roll the camera by holding `Ctrl`, right-clicking and dragging\n */\nexport interface MouseRollHandler extends DragMoveHandler<DragRollResult, MouseEvent> {}\n\nconst LEFT_BUTTON = 0;\nconst RIGHT_BUTTON = 2;\n\n/** Gives a move around the pointer the drag's start point as its `around`, but not a move without a change, which would make the handler active. */\nfunction aroundDragStart<T extends DragRotateResult | DragPitchResult | DragRollResult>(result: T, around: 'center' | 'pointer', startPoint: Point): T {\n    if (around === 'center' || !(result.bearingDelta || result.pitchDelta || result.rollDelta)) return result;\n    return {...result, around: startPoint};\n}\n\nconst assignEvents = <T extends DragPanResult | DragRotateResult | DragPitchResult | DragRollResult>(handler: DragHandler<T, MouseEvent>): void => {\n    handler.mousedown = handler.dragStart;\n    handler.mousemoveWindow = handler.dragMove;\n    handler.mouseup = handler.dragEnd;\n    handler.contextmenu = (e: MouseEvent) => {\n        e.preventDefault();\n    };\n};\n\nexport function generateMousePanHandler({enable, clickTolerance}: {\n    clickTolerance: number;\n    enable?: boolean;\n}): MousePanHandler {\n    const mouseMoveStateManager = new MouseMoveStateManager({\n        checkCorrectEvent: (e: MouseEvent) => e.button === LEFT_BUTTON && !e.ctrlKey,\n    });\n    return new DragHandler<DragPanResult, MouseEvent>({\n        clickTolerance,\n        move: (lastPoint: Point, point: Point) =>\n            ({around: point, panDelta: point.sub(lastPoint)}),\n        activateOnStart: true,\n        moveStateManager: mouseMoveStateManager,\n        enable,\n        assignEvents,\n    });\n};\n\nexport function generateMouseRotationHandler({enable, clickTolerance, minPixelCenterThreshold = 100, rotateSpeed = 0.8}: {\n    clickTolerance: number;\n    enable?: boolean;\n    minPixelCenterThreshold?: number;\n    /**\n     * Degrees the bearing changes per pixel of horizontal drag.\n     * @defaultValue 0.8\n     */\n    rotateSpeed?: number;\n}, getCenter: () => Point, getAround?: () => 'center' | 'pointer', getMovement?: () => 'circular' | 'linear'): MouseRotateHandler {\n    const mouseMoveStateManager = new MouseMoveStateManager({\n        checkCorrectEvent: (e: MouseEvent): boolean =>\n            (e.button === LEFT_BUTTON && e.ctrlKey) ||\n            (e.button === RIGHT_BUTTON && !e.ctrlKey),\n    });\n    return new DragHandler<DragRotateResult, MouseEvent>({\n        clickTolerance,\n        move: (lastPoint: Point, currentPoint: Point, startPoint: Point) => {\n            if (getAround?.() === 'pointer') {\n                return aroundDragStart({bearingDelta: (currentPoint.x - lastPoint.x) * rotateSpeed}, 'pointer', startPoint);\n            }\n            const center = getCenter();\n            const isCircular = (getMovement?.() ?? 'circular') === 'circular';\n            if (isCircular && Math.abs(center.y - lastPoint.y) > minPixelCenterThreshold) {\n                // Avoid rotation related to y axis since it is \"saved\" for pitch\n                return {bearingDelta: getAngleDelta(new Point(lastPoint.x, currentPoint.y), currentPoint, center)};\n            }\n            let bearingDelta = (currentPoint.x - lastPoint.x) * rotateSpeed;\n            if (isCircular && currentPoint.y < center.y) {\n                bearingDelta = -bearingDelta;\n            }\n            return {bearingDelta};\n        },\n        // prevent browser context menu when necessary; we don't allow it with rotation\n        // because we can't discern rotation gesture start from contextmenu on Mac\n        moveStateManager: mouseMoveStateManager,\n        enable,\n        assignEvents,\n    });\n};\n\nexport function generateMousePitchHandler({enable, clickTolerance, pitchSpeed = -0.5}: {\n    clickTolerance: number;\n    /**\n     * Degrees the pitch changes per pixel of vertical drag.\n     * @defaultValue -0.5\n     */\n    pitchSpeed?: number;\n    enable?: boolean;\n}, getAround?: () => 'center' | 'pointer'): MousePitchHandler {\n    const mouseMoveStateManager = new MouseMoveStateManager({\n        checkCorrectEvent: (e: MouseEvent): boolean =>\n            (e.button === LEFT_BUTTON && e.ctrlKey) ||\n            (e.button === RIGHT_BUTTON),\n    });\n    return new DragHandler<DragPitchResult, MouseEvent>({\n        clickTolerance,\n        move: (lastPoint: Point, point: Point, startPoint: Point) =>\n            aroundDragStart({pitchDelta: (point.y - lastPoint.y) * pitchSpeed}, getAround?.() ?? 'center', startPoint),\n        // prevent browser context menu when necessary; we don't allow it with rotation\n        // because we can't discern rotation gesture start from contextmenu on Mac\n        moveStateManager: mouseMoveStateManager,\n        enable,\n        assignEvents,\n    });\n};\n\nexport function generateMouseRollHandler({enable, clickTolerance, rollDegreesPerPixelMoved = 0.3}: {\n    clickTolerance: number;\n    rollDegreesPerPixelMoved?: number;\n    enable?: boolean;\n}, getCenter: () => Point, getAround?: () => 'center' | 'pointer'): MouseRollHandler {\n    const mouseMoveStateManager = new MouseMoveStateManager({\n        checkCorrectEvent: (e: MouseEvent): boolean =>\n            (e.button === RIGHT_BUTTON && e.ctrlKey),\n    });\n    return new DragHandler<DragRollResult, MouseEvent>({\n        clickTolerance,\n        move: (lastPoint: Point, currentPoint: Point, startPoint: Point) => {\n            const center = getCenter();\n            let rollDelta = (currentPoint.x - lastPoint.x) * rollDegreesPerPixelMoved;\n            if (currentPoint.y < center.y) {\n                rollDelta = -rollDelta;\n            }\n            return aroundDragStart({rollDelta}, getAround?.() ?? 'center', startPoint);\n        },\n        // prevent browser context menu when necessary; we don't allow it with roll\n        // because we can't discern roll gesture start from contextmenu on Mac\n        moveStateManager: mouseMoveStateManager,\n        enable,\n        assignEvents,\n    });\n};\n", "import Point from '@mapbox/point-geometry';\nimport {indexTouches} from './handler_util.ts';\n\nimport type {Handler} from '../handler_manager.ts';\nimport type {Map} from '../map.ts';\n\n/**\n * A `TouchPanHandler` allows the user to pan the map using touch gestures.\n */\nexport class TouchPanHandler implements Handler {\n\n    _enabled: boolean;\n    _active: boolean;\n    _touches: {\n        [k in string | number]: Point;\n    };\n    _clickTolerance: number;\n    _sum: Point;\n    _map: Map;\n\n    constructor(options: {clickTolerance: number}, map: Map) {\n        this._clickTolerance = options.clickTolerance || 1;\n        this._map = map;\n        this.reset();\n    }\n\n    reset(): void {\n        this._active = false;\n        this._touches = {};\n        this._sum = new Point(0, 0);\n    }\n\n    _shouldBePrevented(touchesCount: number): boolean {\n        const minTouches = this._map.cooperativeGestures.isEnabled() ? 2 : 1;\n        return touchesCount < minTouches;\n    }\n\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): {around: Point; panDelta: Point} | void {\n        return this._calculateTransform(e, points, mapTouches);\n    }\n\n    touchmove(e: TouchEvent, points: Point[], mapTouches: Touch[]): {around: Point; panDelta: Point} | void {\n        if (!this._active) return;\n        if (this._shouldBePrevented(mapTouches.length)) {\n            this._map.cooperativeGestures.notifyGestureBlocked('touch_pan', e);\n            return;\n        }\n        e.preventDefault();\n        return this._calculateTransform(e, points, mapTouches);\n    }\n\n    touchend(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        this._calculateTransform(e, points, mapTouches);\n\n        if (this._active && this._shouldBePrevented(mapTouches.length)) {\n            this.reset();\n        }\n    }\n\n    touchcancel(): void {\n        this.reset();\n    }\n\n    _calculateTransform(e: TouchEvent, points: Point[], mapTouches: Touch[]): {around: Point; panDelta: Point} | void {\n        if (mapTouches.length > 0) this._active = true;\n\n        const touches = indexTouches(mapTouches, points);\n\n        const touchPointSum = new Point(0, 0);\n        const touchDeltaSum = new Point(0, 0);\n        let touchDeltaCount = 0;\n\n        for (const identifier in touches) {\n            const point = touches[identifier];\n            const prevPoint = this._touches[identifier];\n            if (prevPoint) {\n                touchPointSum._add(point);\n                touchDeltaSum._add(point.sub(prevPoint));\n                touchDeltaCount++;\n                touches[identifier] = point;\n            }\n        }\n\n        this._touches = touches;\n\n        if (this._shouldBePrevented(touchDeltaCount) || !touchDeltaSum.mag()) return;\n\n        const panDelta = touchDeltaSum.div(touchDeltaCount);\n        this._sum._add(panDelta);\n        if (this._sum.mag() < this._clickTolerance) return;\n\n        const around = touchPointSum.div(touchDeltaCount);\n\n        return {\n            around,\n            panDelta\n        };\n    }\n\n    enable(): void {\n        this._enabled = true;\n    }\n\n    disable(): void {\n        this._enabled = false;\n        this.reset();\n    }\n\n    isEnabled(): boolean {\n        return this._enabled;\n    }\n\n    isActive(): boolean {\n        return this._active;\n    }\n}\n", "import {DOM} from '../../util/dom.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Map} from '../map.ts';\nimport type {Handler, HandlerResult} from '../handler_manager.ts';\n\n/**\n * An options object sent to the enable function of some of the handlers\n */\nexport type AroundCenterOptions = {\n    /**\n     * If \"center\" is passed, map will zoom around the center of map\n     */\n    around: 'center';\n};\n\n/**\n * The `TwoFingersTouchHandler`s allows the user to zoom, pitch and rotate the map using two fingers\n *\n */\nabstract class TwoFingersTouchHandler implements Handler {\n\n    _enabled?: boolean;\n    _active?: boolean;\n    _firstTwoTouches?: [number, number];\n    _vector?: Point;\n    _startVector?: Point;\n    _aroundCenter?: boolean;\n\n    /** @internal */\n    constructor() {\n        this.reset();\n    }\n\n    reset(): void {\n        this._active = false;\n        delete this._firstTwoTouches;\n    }\n\n    abstract _start(points: [Point, Point]): void;\n    abstract _move(points: [Point, Point], pinchAround: Point | null, e: TouchEvent): HandlerResult | void;\n\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        if (this._firstTwoTouches || mapTouches.length < 2) return;\n\n        this._firstTwoTouches = [\n            mapTouches[0].identifier,\n            mapTouches[1].identifier\n        ];\n\n        // implemented by child classes\n        this._start([points[0], points[1]]);\n    }\n\n    touchmove(e: TouchEvent, points: Point[], mapTouches: Touch[]): HandlerResult | void {\n        if (!this._firstTwoTouches) return;\n\n        e.preventDefault();\n\n        const [idA, idB] = this._firstTwoTouches;\n        const a = getTouchById(mapTouches, points, idA);\n        const b = getTouchById(mapTouches, points, idB);\n        if (!a || !b) return;\n        const pinchAround = this._aroundCenter ? null : a.add(b).div(2);\n\n        // implemented by child classes\n        return this._move([a, b], pinchAround, e);\n\n    }\n\n    touchend(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        if (!this._firstTwoTouches) return;\n\n        const [idA, idB] = this._firstTwoTouches;\n        const a = getTouchById(mapTouches, points, idA);\n        const b = getTouchById(mapTouches, points, idB);\n        if (a && b) return;\n\n        if (this._active) DOM.suppressClick();\n\n        this.reset();\n    }\n\n    touchcancel(): void {\n        this.reset();\n    }\n\n    /**\n     * Enables the \"drag to pitch\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.touchPitch.enable();\n     * ```\n     */\n    enable(options?: AroundCenterOptions | boolean | null): void {\n        this._enabled = true;\n        this._aroundCenter = !!options && (options as AroundCenterOptions).around === 'center';\n    }\n\n    /**\n     * Disables the \"drag to pitch\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.touchPitch.disable();\n     * ```\n     */\n    disable(): void {\n        this._enabled = false;\n        this.reset();\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"drag to pitch\" interaction is enabled.\n     *\n     * @returns  `true` if the \"drag to pitch\" interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return !!this._enabled;\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"drag to pitch\" interaction is active, i.e. currently being used.\n     *\n     * @returns `true` if the \"drag to pitch\" interaction is active.\n     */\n    isActive(): boolean {\n        return !!this._active;\n    }\n}\n\nfunction getTouchById(mapTouches: Touch[], points: Point[], identifier: number): Point | undefined {\n    for (let i = 0; i < mapTouches.length; i++) {\n        if (mapTouches[i].identifier === identifier) return points[i];\n    }\n    return undefined;\n}\n\n/* ZOOM */\n\nconst defaultZoomRate = 1;\nconst defaultZoomThreshold = 0.1;\n\nfunction getZoomDelta(distance: number, lastDistance: number): number {\n    return Math.log(distance / lastDistance) / Math.LN2;\n}\n\n/**\n * The `TwoFingersTouchHandler`s allows the user to zoom the map two fingers\n *\n * @group Handlers\n */\nexport class TwoFingersTouchZoomHandler extends TwoFingersTouchHandler {\n\n    _distance?: number;\n    _startDistance?: number;\n    _zoomRate: number;\n    _zoomThreshold: number;\n\n    constructor() {\n        super();\n        this._zoomRate = defaultZoomRate;\n        this._zoomThreshold = defaultZoomThreshold;\n    }\n\n    /**\n     * Sets the zoom rate of touch gestures.\n     * @param zoomRate - 1 The rate used to scale touch movement to a zoom value. Set to `undefined` to restore the default.\n     * @example\n     * Slow down touch zoom\n     * ```ts\n     * map.touchZoomRotate.setZoomRate(0.5);\n     * ```\n     */\n    setZoomRate(zoomRate?: number): void {\n        this._zoomRate = zoomRate ?? defaultZoomRate;\n    }\n\n    /**\n     * Sets the threshold before a pinch gesture starts zooming.\n     * @param zoomThreshold - 0.1 The minimum zoom delta before the pinch gesture becomes active. Set to `undefined` to restore the default.\n     * @example\n     * Make pinch zoom less sensitive\n     * ```ts\n     * map.touchZoomRotate.setZoomThreshold(0.3);\n     * ```\n     */\n    setZoomThreshold(zoomThreshold?: number): void {\n        this._zoomThreshold = zoomThreshold ?? defaultZoomThreshold;\n    }\n\n    reset(): void {\n        super.reset();\n        delete this._distance;\n        delete this._startDistance;\n    }\n\n    _start(points: [Point, Point]): void {\n        this._startDistance = this._distance = points[0].dist(points[1]);\n    }\n\n    _move(points: [Point, Point], pinchAround: Point | null): HandlerResult | void {\n        const lastDistance = this._distance;\n        this._distance = points[0].dist(points[1]);\n        if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < this._zoomThreshold) return;\n        this._active = true;\n        return {\n            zoomDelta: getZoomDelta(this._distance, lastDistance) * this._zoomRate,\n            pinchAround\n        };\n    }\n}\n\n/* ROTATE */\n\nconst ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle\n\nfunction getBearingDelta(a: Point, b: Point): number {\n    return a.angleWith(b) * 180 / Math.PI;\n}\n\n/**\n * The `TwoFingersTouchHandler`s allows the user to rotate the map two fingers\n *\n * @group Handlers\n */\nexport class TwoFingersTouchRotateHandler extends TwoFingersTouchHandler {\n    _minDiameter?: number;\n\n    reset(): void {\n        super.reset();\n        delete this._minDiameter;\n        delete this._startVector;\n        delete this._vector;\n    }\n\n    _start(points: [Point, Point]): void {\n        this._startVector = this._vector = points[0].sub(points[1]);\n        this._minDiameter = points[0].dist(points[1]);\n    }\n\n    _move(points: [Point, Point], pinchAround: Point | null, _e: TouchEvent): HandlerResult | void {\n        const lastVector = this._vector;\n        this._vector = points[0].sub(points[1]);\n\n        if (!this._active && this._isBelowThreshold(this._vector)) return;\n        this._active = true;\n\n        return {\n            bearingDelta: getBearingDelta(this._vector, lastVector),\n            pinchAround\n        };\n    }\n\n    _isBelowThreshold(vector: Point): boolean {\n        /*\n         * The threshold before a rotation actually happens is configured in\n         * pixels along the circumference of the circle formed by the two fingers.\n         * This makes the threshold in degrees larger when the fingers are close\n         * together and smaller when the fingers are far apart.\n         *\n         * Use the smallest diameter from the whole gesture to reduce sensitivity\n         * when pinching in and out.\n         */\n\n        this._minDiameter = Math.min(this._minDiameter, vector.mag());\n        const circumference = Math.PI * this._minDiameter;\n        const threshold = ROTATION_THRESHOLD / circumference * 360;\n\n        const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector);\n        return Math.abs(bearingDeltaSinceStart) < threshold;\n    }\n}\n\n/* PITCH */\n\nfunction isVertical(vector: Point): boolean {\n    return Math.abs(vector.y) > Math.abs(vector.x);\n}\n\nconst ALLOWED_SINGLE_TOUCH_TIME = 100;\n\n/**\n * The `TwoFingersTouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers.\n *\n * @group Handlers\n */\nexport class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler {\n\n    _valid?: boolean;\n    _firstMove?: number;\n    _lastPoints?: [Point, Point];\n    _map: Map;\n    _currentTouchCount: number = 0;\n\n    constructor(map: Map) {\n        super();\n        this._map = map;\n    }\n\n    reset(): void {\n        super.reset();\n        this._valid = undefined;\n        delete this._firstMove;\n        delete this._lastPoints;\n    }\n\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        super.touchstart(e, points, mapTouches);\n        this._currentTouchCount = mapTouches.length;\n    }\n\n    _start(points: [Point, Point]): void {\n        this._lastPoints = points;\n        if (isVertical(points[0].sub(points[1]))) {\n            // fingers are more horizontal than vertical\n            this._valid = false;\n        }\n    }\n\n    _move(points: [Point, Point], center: Point | null, e: TouchEvent): HandlerResult | void {\n        // If cooperative gestures is enabled, we need a 3-finger minimum for this gesture to register\n        if (this._map.cooperativeGestures.isEnabled() && this._currentTouchCount < 3) {\n            return;\n        }\n\n        const vectorA = points[0].sub(this._lastPoints[0]);\n        const vectorB = points[1].sub(this._lastPoints[1]);\n\n        this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp);\n        if (!this._valid) return;\n\n        this._lastPoints = points;\n        this._active = true;\n        const yDeltaAverage = (vectorA.y + vectorB.y) / 2;\n        const degreesPerPixelMoved = -0.5;\n        return {\n            pitchDelta: yDeltaAverage * degreesPerPixelMoved\n        };\n    }\n\n    gestureBeginsVertically(vectorA: Point, vectorB: Point, timeStamp: number): boolean | undefined {\n        if (this._valid !== undefined) return this._valid;\n\n        const threshold = 2;\n        const movedA = vectorA.mag() >= threshold;\n        const movedB = vectorB.mag() >= threshold;\n\n        // neither finger has moved a meaningful amount, wait\n        if (!movedA && !movedB) return;\n\n        // One finger has moved and the other has not.\n        // If enough time has passed, decide it is not a pitch.\n        if (!movedA || !movedB) {\n            if (this._firstMove === undefined) {\n                this._firstMove = timeStamp;\n            }\n\n            if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) {\n                // still waiting for a movement from the second finger\n                return undefined;\n            } else {\n                return false;\n            }\n        }\n\n        const isSameDirection = vectorA.y > 0 === vectorB.y > 0;\n        return isVertical(vectorA) && isVertical(vectorB) && isSameDirection;\n    }\n}\n", "import {evaluateZoomSnap} from '../../util/util.ts';\n\nimport type {Handler} from '../handler_manager.ts';\nimport type {Map} from '../map.ts';\nimport type {TransformProvider} from './transform-provider.ts';\n\nconst defaultOptions = {\n    panStep: 100,\n    bearingStep: 15,\n    pitchStep: 10\n};\n\n/**\n * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using\n * the following keyboard shortcuts:\n *\n * - `=` / `+`: Increase the zoom level by 1.\n * - `Shift-=` / `Shift-+`: Increase the zoom level by 2.\n * - `-`: Decrease the zoom level by 1.\n * - `Shift--`: Decrease the zoom level by 2.\n * - Arrow keys: Pan by 100 pixels.\n * - `Shift+⇢`: Increase the rotation by 15 degrees.\n * - `Shift+⇠`: Decrease the rotation by 15 degrees.\n * - `Shift+⇡`: Increase the pitch by 10 degrees.\n * - `Shift+⇣`: Decrease the pitch by 10 degrees.\n *\n * @group Handlers\n */\nexport class KeyboardHandler implements Handler {\n    _tr: TransformProvider;\n    _enabled: boolean;\n    _active: boolean;\n    _panStep: number;\n    _bearingStep: number;\n    _pitchStep: number;\n    _rotationDisabled: boolean;\n\n    /** @internal */\n    constructor(map: Map, transformProvider: TransformProvider) {\n        this._tr = transformProvider;\n        const stepOptions = defaultOptions;\n        this._panStep = stepOptions.panStep;\n        this._bearingStep = stepOptions.bearingStep;\n        this._pitchStep = stepOptions.pitchStep;\n        this._rotationDisabled = false;\n    }\n\n    reset(): void {\n        this._active = false;\n    }\n\n    keydown(e: KeyboardEvent): {cameraAnimation: (map: Map) => void} | void {\n        if (e.altKey || e.ctrlKey || e.metaKey) return;\n\n        let zoomDir = 0;\n        let bearingDir = 0;\n        let pitchDir = 0;\n        let xDir = 0;\n        let yDir = 0;\n\n        switch (e.keyCode) {\n            case 61:\n            case 107:\n            case 171:\n            case 187:\n                zoomDir = 1;\n                break;\n\n            case 189:\n            case 109:\n            case 173:\n                zoomDir = -1;\n                break;\n\n            case 37:\n                if (e.shiftKey) {\n                    bearingDir = -1;\n                } else {\n                    e.preventDefault();\n                    xDir = -1;\n                }\n                break;\n\n            case 39:\n                if (e.shiftKey) {\n                    bearingDir = 1;\n                } else {\n                    e.preventDefault();\n                    xDir = 1;\n                }\n                break;\n\n            case 38:\n                if (e.shiftKey) {\n                    pitchDir = 1;\n                } else {\n                    e.preventDefault();\n                    yDir = -1;\n                }\n                break;\n\n            case 40:\n                if (e.shiftKey) {\n                    pitchDir = -1;\n                } else {\n                    e.preventDefault();\n                    yDir = 1;\n                }\n                break;\n\n            default:\n                return;\n        }\n\n        if (this._rotationDisabled) {\n            bearingDir = 0;\n            pitchDir = 0;\n        }\n\n        return {\n            cameraAnimation: (map: Map) => {\n                const tr = this._tr;\n                map.easeTo({\n                    duration: 300,\n                    easeId: 'keyboardHandler',\n                    easing: easeOut,\n\n                    zoom: zoomDir ? evaluateZoomSnap(tr.zoom + zoomDir * (e.shiftKey ? 2 : 1), map.getZoomSnap()) : tr.zoom,\n                    bearing: tr.bearing + bearingDir * this._bearingStep,\n                    pitch: tr.pitch + pitchDir * this._pitchStep,\n                    offset: [-xDir * this._panStep, -yDir * this._panStep],\n                    center: tr.center\n                }, {originalEvent: e});\n            }\n        };\n    }\n\n    /**\n     * Enables the \"keyboard rotate and zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.keyboard.enable();\n     * ```\n     */\n    enable(): void {\n        this._enabled = true;\n    }\n\n    /**\n     * Disables the \"keyboard rotate and zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.keyboard.disable();\n     * ```\n     */\n    disable(): void {\n        this._enabled = false;\n        this.reset();\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"keyboard rotate and zoom\"\n     * interaction is enabled.\n     *\n     * @returns `true` if the \"keyboard rotate and zoom\"\n     * interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return this._enabled;\n    }\n\n    /**\n     * Returns true if the handler is enabled and has detected the start of a\n     * zoom/rotate gesture.\n     *\n     * @returns `true` if the handler is enabled and has detected the\n     * start of a zoom/rotate gesture.\n     */\n    isActive(): boolean {\n        return this._active;\n    }\n\n    /**\n     * Disables the \"keyboard pan/rotate\" interaction, leaving the\n     * \"keyboard zoom\" interaction enabled.\n     *\n     * @example\n     * ```ts\n     * map.keyboard.disableRotation();\n     * ```\n     */\n    disableRotation(): void {\n        this._rotationDisabled = true;\n    }\n\n    /**\n     * Enables the \"keyboard pan/rotate\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.keyboard.enable();\n     * map.keyboard.enableRotation();\n     * ```\n     */\n    enableRotation(): void {\n        this._rotationDisabled = false;\n    }\n}\n\nfunction easeOut(t: number) {\n    return t * (2 - t);\n}\n", "import {DOM} from '../../util/dom.ts';\nimport {defaultEasing, bezier, zoomScale, scaleZoom, evaluateZoomSnap} from '../../util/util.ts';\nimport {now} from '../../util/time_control.ts';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {LngLat} from '../../geo/lng_lat.ts';\n\nimport type {TransformProvider} from './transform-provider.ts';\nimport type {Map} from '../map.ts';\nimport type {AroundCenterOptions} from './two_fingers_touch.ts';\nimport type {Handler} from '../handler_manager.ts';\nimport type Point from '@mapbox/point-geometry';\n\n// deltaY value for mouse scroll wheel identification\nconst wheelZoomDelta = 4.000244140625;\n\n// These magic numbers control the rate of zoom. Trackpad events fire at a greater\n// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick\nconst defaultZoomRate = 1 / 100;\nconst wheelZoomRate = 1 / 450;\n\n// upper bound on how much we scale the map in any single render frame; this\n// is used to limit zoom rate in the case of very fast scrolling\nconst maxScalePerFrame = 2;\n\n// Minimum time difference value to be used for calculating zoom easing in renderFrame();\n// this is used to normalise very fast (typically 0 to 0.3ms) repeating lastWheelEventTimeDiff\n// values generated by Chromium based browsers during fast scrolling wheel events.\nconst wheelEventTimeDiffAdjustment = 5;\n\n/**\n * The `ScrollZoomHandler` allows the user to zoom the map by scrolling.\n *\n * @group Handlers\n */\nexport class ScrollZoomHandler implements Handler {\n    _map: Map;\n    _tr: TransformProvider;\n    _enabled: boolean;\n    _active: boolean;\n    _zooming: boolean;\n    _aroundCenter: boolean;\n    _aroundPoint: Point;\n    _type: 'wheel' | 'trackpad' | null;\n    _lastValue: number;\n    _timeout: ReturnType<typeof setTimeout>; // used for delayed-handling of a single wheel movement\n    _finishTimeout: ReturnType<typeof setTimeout>; // used to delay final '{move,zoom}end' events\n\n    _lastWheelEvent: WheelEvent;\n    _lastWheelEventTime: number;\n\n    _lastExpectedZoom: number;\n    _startZoom: number;\n    _targetZoom: number;\n    _delta: number;\n    _easing: ((a: number) => number);\n    _prevEase: {\n        start: number;\n        duration: number;\n        easing: (_: number) => number;\n    };\n\n    _needsRerender: boolean;\n    _triggerRenderFrame: () => void;\n\n    _defaultZoomRate: number;\n    _wheelZoomRate: number;\n\n    /** @internal */\n    constructor(map: Map, triggerRenderFrame: () => void, transformProvider: TransformProvider) {\n        this._map = map;\n        this._tr = transformProvider;\n        this._triggerRenderFrame = triggerRenderFrame;\n\n        this._delta = 0;\n\n        this._defaultZoomRate = defaultZoomRate;\n        this._wheelZoomRate = wheelZoomRate;\n    }\n\n    /**\n     * Set the zoom rate of a trackpad\n     * @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value.\n     * @example\n     * Speed up trackpad zoom\n     * ```ts\n     * map.scrollZoom.setZoomRate(1/25);\n     * ```\n     */\n    setZoomRate(zoomRate: number): void {\n        this._defaultZoomRate = zoomRate;\n    }\n\n    /**\n     * Set the zoom rate of a mouse wheel\n     * @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value.\n     * @example\n     * Slow down zoom of mouse wheel\n     * ```ts\n     * map.scrollZoom.setWheelZoomRate(1/600);\n     * ```\n     */\n    setWheelZoomRate(wheelZoomRate: number): void {\n        this._wheelZoomRate = wheelZoomRate;\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"scroll to zoom\" interaction is enabled.\n     * @returns `true` if the \"scroll to zoom\" interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return !!this._enabled;\n    }\n\n    /*\n    * Active state is turned on and off with every scroll wheel event and is set back to false before the map\n    * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in\n    * progress.\n    */\n    isActive(): boolean {\n        return !!this._active || this._finishTimeout !== undefined;\n    }\n\n    isZooming(): boolean {\n        return !!this._zooming;\n    }\n\n    /**\n     * Enables the \"scroll to zoom\" interaction.\n     *\n     * @param options - Options object.\n     * @example\n     * ```ts\n     * map.scrollZoom.enable();\n     * map.scrollZoom.enable({ around: 'center' })\n     * ```\n     */\n    enable(options?: AroundCenterOptions | boolean): void {\n        if (this.isEnabled()) return;\n        this._enabled = true;\n        this._aroundCenter = !!options && (options as AroundCenterOptions).around === 'center';\n    }\n\n    /**\n     * Disables the \"scroll to zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.scrollZoom.disable();\n     * ```\n     */\n    disable(): void {\n        if (!this.isEnabled()) return;\n        this._enabled = false;\n    }\n\n    /**\n     * Determines whether or not the gesture is blocked due to cooperativeGestures.\n     */\n    _shouldBePrevented(e: WheelEvent): boolean {\n        if (!this._map.cooperativeGestures.isEnabled()) {\n            return false;\n        }\n\n        const isTrackpadPinch = e.ctrlKey;\n        const isBypassed = isTrackpadPinch || this._map.cooperativeGestures.isBypassed(e);\n\n        return !isBypassed;\n    }\n\n    wheel(e: WheelEvent): void {\n        if (!this.isEnabled()) return;\n        if (this._shouldBePrevented(e)) {\n            this._map.cooperativeGestures.notifyGestureBlocked('wheel_zoom', e);\n            return;\n        }\n        let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY;\n        const currentTime = now(),\n            timeDelta = currentTime - (this._lastWheelEventTime || 0);\n\n        this._lastWheelEventTime = currentTime;\n\n        if (value !== 0 && (value % wheelZoomDelta) === 0) {\n            // This one is definitely a mouse wheel event.\n            this._type = 'wheel';\n\n        } else if (value !== 0 && Math.abs(value) < 4) {\n            // This one is definitely a trackpad event because it is so small.\n            this._type = 'trackpad';\n\n        } else if (timeDelta > 400) {\n            // This is likely a new scroll action.\n            this._type = null;\n            this._lastValue = value;\n\n            // Start a timeout in case this was a singular event, and delay it by up to 40ms.\n            this._timeout = setTimeout(this._onTimeout, 40, e);\n\n        } else if (!this._type) {\n            // This is a repeating event, but we don't know the type of event just yet.\n            // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode.\n            this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel';\n\n            // Make sure our delayed event isn't fired again, because we accumulate\n            // the previous event (which was less than 40ms ago) into this event.\n            if (this._timeout) {\n                clearTimeout(this._timeout);\n                this._timeout = null;\n                value += this._lastValue;\n            }\n        }\n\n        // Slow down zoom if shift key is held for more precise zooming\n        if (e.shiftKey && value) value = value / 4;\n\n        // Only fire the callback if we actually know what type of scrolling device the user uses.\n        if (this._type) {\n            this._lastWheelEvent = e;\n            this._delta -= value;\n            if (!this._active) {\n                this._start(e);\n            }\n        }\n\n        e.preventDefault();\n    }\n\n    _onTimeout = (initialEvent: MouseEvent): void => {\n        this._type = 'wheel';\n        this._delta -= this._lastValue;\n        if (!this._active) {\n            this._start(initialEvent);\n        }\n    };\n\n    _start(e: MouseEvent): void {\n        if (!this._delta) return;\n\n        this._needsRerender = false;\n\n        this._active = true;\n        if (!this.isZooming()) {\n            this._zooming = true;\n        }\n\n        if (this._finishTimeout) {\n            clearTimeout(this._finishTimeout);\n            delete this._finishTimeout;\n        }\n\n        const pos = DOM.mousePos(this._map.getCanvas(), e);\n        const tr = this._tr;\n\n        // Whether aroundPoint is actually unprojectable is not a problem to be solved here, but in handler_manager.ts instead.\n        if (this._aroundCenter) {\n            this._aroundPoint = tr.transform.locationToScreenPoint(LngLat.convert(tr.center));\n        } else {\n            this._aroundPoint = pos;\n        }\n\n        if (!this._needsRerender) {\n            this._needsRerender = true;\n            this._triggerRenderFrame();\n        }\n    }\n\n    renderFrame(): {\n        noInertia: boolean;\n        needsRenderFrame: boolean;\n        zoomDelta: number;\n        around: Point;\n        originalEvent: WheelEvent;\n    } | void {\n        if (!this._needsRerender) return;\n        this._needsRerender = false;\n\n        if (!this.isActive()) return;\n        const tr = this._tr.transform;\n\n        // When globe is enabled zoom might be modified by the map center latitude being changes (either by panning or by zoom moving the map)\n        if (typeof this._lastExpectedZoom === 'number') {\n            const externalZoomChange = tr.zoom - this._lastExpectedZoom;\n            if (typeof this._startZoom === 'number') {\n                this._startZoom += externalZoomChange;\n            }\n            if (typeof this._targetZoom === 'number') {\n                this._targetZoom += externalZoomChange;\n            }\n        }\n\n        // if we've had scroll events since the last render frame, consume the\n        // accumulated delta, and update the target zoom level accordingly\n        if (this._delta !== 0) {\n            // For trackpad events and single mouse wheel ticks, use the default zoom rate\n            const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate;\n            // Scale by sigmoid of scroll wheel delta so the map responds to small scrolls and compresses large scrolls\n            let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate)));\n\n            if (this._delta < 0 && scale !== 0) {\n                scale = 1 / scale;\n            }\n\n            const fromScale = typeof this._targetZoom !== 'number' ? tr.scale : zoomScale(this._targetZoom);\n            const target = tr.applyConstrain(tr.getCameraLngLat(), scaleZoom(fromScale * scale)).zoom;\n            const zoomSnap = this._map.getZoomSnap();\n\n            if (this._type === 'wheel' && zoomSnap > 0) {\n                const currentSnapped = evaluateZoomSnap(tr.zoom, zoomSnap);\n                this._targetZoom = evaluateZoomSnap(target, zoomSnap, target - currentSnapped);\n            } else {\n                this._targetZoom = target;\n            }\n\n            // if this is a mouse wheel, refresh the starting zoom and easing\n            // function we're using to smooth out the zooming between wheel\n            // events\n            if (this._type === 'wheel') {\n                this._startZoom = tr.zoom;\n                this._easing = this._smoothOutEasing(200);\n            }\n\n            this._delta = 0;\n        }\n\n        const targetZoom = typeof this._targetZoom !== 'number' ? tr.zoom : this._targetZoom;\n        const startZoom = this._startZoom;\n        const easing = this._easing;\n\n        let finished = false;\n        let zoom;\n\n        if (this._type === 'wheel' && startZoom && easing) {\n            const lastWheelEventTimeDiff = now() - this._lastWheelEventTime;\n\n            const t = Math.min((lastWheelEventTimeDiff + wheelEventTimeDiffAdjustment) / 200, 1);\n\n            const k = easing(t);\n            zoom = interpolates.number(startZoom, targetZoom, k);\n            if (t < 1) {\n                this._needsRerender = true;\n            } else {\n                finished = true;\n            }\n        } else {\n            zoom = targetZoom;\n            finished = true;\n        }\n\n        this._active = true;\n\n        if (finished) {\n            this._active = false;\n            this._finishTimeout = setTimeout(() => {\n                this._zooming = false;\n                this._triggerRenderFrame();\n                delete this._targetZoom;\n                delete this._lastExpectedZoom;\n                delete this._finishTimeout;\n            }, 200);\n        }\n\n        this._lastExpectedZoom = zoom;\n\n        return {\n            noInertia: true,\n            needsRenderFrame: !finished,\n            zoomDelta: zoom - tr.zoom,\n            around: this._aroundPoint,\n            originalEvent: this._lastWheelEvent\n        };\n    }\n\n    _smoothOutEasing(duration: number): (t: number) => number {\n        let easing = defaultEasing;\n\n        if (this._prevEase) {\n            const currentEase = this._prevEase;\n            const t = (now() - currentEase.start) / currentEase.duration;\n            const speed = currentEase.easing(t + 0.01) - currentEase.easing(t);\n\n            // Quick hack to make new bezier that is continuous with last\n            const x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01;\n            const y = Math.sqrt(0.27 * 0.27 - x * x);\n\n            easing = bezier(x, y, 0.25, 1);\n        }\n\n        this._prevEase = {\n            start: now(),\n            duration,\n            easing\n        };\n\n        return easing;\n    }\n\n    reset(): void {\n        this._active = false;\n        this._zooming = false;\n        delete this._targetZoom;\n        delete this._lastExpectedZoom;\n        if (this._finishTimeout) {\n            clearTimeout(this._finishTimeout);\n            delete this._finishTimeout;\n        }\n    }\n}\n", "import type {ClickZoomHandler} from '../click_zoom.ts';\nimport type {TapZoomHandler} from './../tap_zoom.ts';\n\n/**\n * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by\n * double clicking or double tapping.\n *\n * @group Handlers\n */\nexport class DoubleClickZoomHandler {\n\n    _clickZoom: ClickZoomHandler;\n    _tapZoom: TapZoomHandler;\n\n    /** @internal */\n    constructor(clickZoom: ClickZoomHandler, TapZoom: TapZoomHandler) {\n        this._clickZoom = clickZoom;\n        this._tapZoom = TapZoom;\n    }\n\n    /**\n     * Enables the \"double click to zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.doubleClickZoom.enable();\n     * ```\n     */\n    enable(): void {\n        this._clickZoom.enable();\n        this._tapZoom.enable();\n    }\n\n    /**\n     * Disables the \"double click to zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.doubleClickZoom.disable();\n     * ```\n     */\n    disable(): void {\n        this._clickZoom.disable();\n        this._tapZoom.disable();\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"double click to zoom\" interaction is enabled.\n     *\n     * @returns `true` if the \"double click to zoom\" interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return this._clickZoom.isEnabled() && this._tapZoom.isEnabled();\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"double click to zoom\" interaction is active, i.e. currently being used.\n     *\n     * @returns `true` if the \"double click to zoom\" interaction is active.\n     */\n    isActive(): boolean {\n        return this._clickZoom.isActive() || this._tapZoom.isActive();\n    }\n}\n", "import {evaluateZoomSnap} from '../../util/util.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Map} from '../map.ts';\nimport type {TransformProvider} from './transform-provider.ts';\nimport type {Handler} from '../handler_manager.ts';\n\n/**\n * The `ClickZoomHandler` allows the user to zoom the map at a point by double clicking\n * It is used by other handlers\n */\nexport class ClickZoomHandler implements Handler {\n\n    _tr: TransformProvider;\n    _enabled: boolean;\n    _active: boolean;\n\n    /** @internal */\n    constructor(map: Map, transformProvider: TransformProvider) {\n        this._tr = transformProvider;\n        this.reset();\n    }\n\n    reset(): void {\n        this._active = false;\n    }\n\n    dblclick(e: MouseEvent, point: Point): {cameraAnimation: (map: Map) => void} {\n        e.preventDefault();\n        return {\n            cameraAnimation: (map: Map): void => {\n                map.easeTo({\n                    duration: 300,\n                    zoom: evaluateZoomSnap(this._tr.zoom + (e.shiftKey ? -1 : 1), map.getZoomSnap()),\n                    around: this._tr.transform.isPointOnMapSurface(point) ? this._tr.unproject(point) : undefined\n                }, {originalEvent: e});\n            }\n        };\n    }\n\n    enable(): void {\n        this._enabled = true;\n    }\n\n    disable(): void {\n        this._enabled = false;\n        this.reset();\n    }\n\n    isEnabled(): boolean {\n        return this._enabled;\n    }\n\n    isActive(): boolean {\n        return this._active;\n    }\n}\n", "import {TapRecognizer, MAX_TAP_INTERVAL, MAX_DIST} from './tap_recognizer.ts';\n\nimport type {Handler} from '../handler_manager.ts';\nimport type Point from '@mapbox/point-geometry';\n\nconst defaultZoomRate = 1;\n\n/**\n * A `TapDragZoomHandler` allows the user to zoom the map at a point by double tapping. It also allows the user pan the map by dragging.\n */\nexport class TapDragZoomHandler implements Handler {\n\n    _enabled: boolean;\n    _active: boolean;\n    _swipePoint: Point;\n    _swipeTouch: number;\n    _tapTime: number;\n    _tapPoint: Point;\n    _tap: TapRecognizer;\n    _zoomRate: number;\n\n    constructor() {\n\n        this._tap = new TapRecognizer({\n            numTouches: 1,\n            numTaps: 1\n        });\n        this._zoomRate = defaultZoomRate;\n\n        this.reset();\n    }\n\n    setZoomRate(zoomRate?: number): void {\n        this._zoomRate = zoomRate ?? defaultZoomRate;\n    }\n\n    reset(): void {\n        this._active = false;\n        delete this._swipePoint;\n        delete this._swipeTouch;\n        delete this._tapTime;\n        delete this._tapPoint;\n        this._tap.reset();\n    }\n\n    touchstart(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        if (this._swipePoint) return;\n\n        if (!this._tapTime) {\n            this._tap.touchstart(e, points, mapTouches);\n        } else {\n            const swipePoint = points[0];\n\n            const soonEnough = e.timeStamp - this._tapTime < MAX_TAP_INTERVAL;\n            const closeEnough =  this._tapPoint.dist(swipePoint) < MAX_DIST;\n\n            if (!soonEnough || !closeEnough) {\n                this.reset();\n            } else if (mapTouches.length > 0) {\n                this._swipePoint = swipePoint;\n                this._swipeTouch = mapTouches[0].identifier;\n            }\n        }\n    }\n\n    touchmove(e: TouchEvent, points: Point[], mapTouches: Touch[]): {zoomDelta: number} | void {\n        if (!this._tapTime) {\n            this._tap.touchmove(e, points, mapTouches);\n        } else if (this._swipePoint) {\n            if (mapTouches[0].identifier !== this._swipeTouch) {\n                return;\n            }\n\n            const newSwipePoint = points[0];\n            const dist = newSwipePoint.y - this._swipePoint.y;\n            this._swipePoint = newSwipePoint;\n\n            e.preventDefault();\n            this._active = true;\n\n            return {\n                zoomDelta: dist / 128 * this._zoomRate\n            };\n        }\n    }\n\n    touchend(e: TouchEvent, points: Point[], mapTouches: Touch[]): void {\n        if (!this._tapTime) {\n            const point = this._tap.touchend(e, points, mapTouches);\n            if (point) {\n                this._tapTime = e.timeStamp;\n                this._tapPoint = point;\n            }\n        } else if (this._swipePoint) {\n            if (mapTouches.length === 0) {\n                this.reset();\n            }\n        }\n    }\n\n    touchcancel(): void {\n        this.reset();\n    }\n\n    enable(): void {\n        this._enabled = true;\n    }\n\n    disable(): void {\n        this._enabled = false;\n        this.reset();\n    }\n\n    isEnabled(): boolean {\n        return this._enabled;\n    }\n\n    isActive(): boolean {\n        return this._active;\n    }\n}\n", "import type {MousePanHandler} from '../mouse.ts';\nimport type {TouchPanHandler} from './../touch_pan.ts';\n\n/**\n * A {@link DragPanHandler} options object\n */\nexport type DragPanOptions = {\n    /**\n     * factor used to scale the drag velocity\n     * @defaultValue 0\n     */\n    linearity?: number;\n    /**\n     * easing function applied to `map.panTo` when applying the drag.\n     * @param t - the easing function\n     * @defaultValue bezier(0, 0, 0.3, 1)\n     */\n    easing?: (t: number) => number;\n    /**\n     * the maximum value of the drag velocity.\n     * @defaultValue 1400\n     */\n    deceleration?: number;\n    /**\n     * the rate at which the speed reduces after the pan ends.\n     * @defaultValue 2500\n     */\n    maxSpeed?: number;\n};\n\n/**\n * The `DragPanHandler` allows the user to pan the map by clicking and dragging\n * the cursor.\n *\n * @group Handlers\n */\nexport class DragPanHandler {\n\n    _el: HTMLElement;\n    _mousePan: MousePanHandler;\n    _touchPan: TouchPanHandler;\n    _inertiaOptions: DragPanOptions | boolean;\n\n    /** @internal */\n    constructor(el: HTMLElement, mousePan: MousePanHandler, touchPan: TouchPanHandler) {\n        this._el = el;\n        this._mousePan = mousePan;\n        this._touchPan = touchPan;\n    }\n\n    /**\n     * Enables the \"drag to pan\" interaction.\n     *\n     * @param options - Options object\n     * @example\n     * ```ts\n     *   map.dragPan.enable();\n     *   map.dragPan.enable({\n     *      linearity: 0.3,\n     *      easing: bezier(0, 0, 0.3, 1),\n     *      maxSpeed: 1400,\n     *      deceleration: 2500,\n     *   });\n     * ```\n     */\n    enable(options?: DragPanOptions | boolean): void {\n        this._inertiaOptions = options || {};\n        this._mousePan.enable();\n        this._touchPan.enable();\n        this._el.classList.add('maplibregl-touch-drag-pan');\n    }\n\n    /**\n     * Disables the \"drag to pan\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.dragPan.disable();\n     * ```\n     */\n    disable(): void {\n        this._mousePan.disable();\n        this._touchPan.disable();\n        this._el.classList.remove('maplibregl-touch-drag-pan');\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"drag to pan\" interaction is enabled.\n     *\n     * @returns `true` if the \"drag to pan\" interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return this._mousePan.isEnabled() && this._touchPan.isEnabled();\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"drag to pan\" interaction is active, i.e. currently being used.\n     *\n     * @returns `true` if the \"drag to pan\" interaction is active.\n     */\n    isActive(): boolean {\n        return this._mousePan.isActive() || this._touchPan.isActive();\n    }\n}\n", "import type {MousePitchHandler, MouseRollHandler, MouseRotateHandler} from '../mouse.ts';\n\n/**\n * Options object for `DragRotateHandler`.\n */\nexport type DragRotateHandlerOptions = {\n    /**\n     * Control the map pitch in addition to the bearing\n     * @defaultValue true\n     */\n    pitchWithRotate: boolean;\n    /**\n     * Control the map roll in addition to the bearing\n     * @defaultValue false\n     */\n    rollEnabled: boolean;\n    /**\n     * The {@link DragRotateOptions.movement} to use when none is passed, `'circular'` if `true` and `'linear'` if `false`\n     * @defaultValue true\n     */\n    aroundCenter?: boolean;\n};\n\n/**\n * Options object for {@link DragRotateHandler.enable}. A drag around the pointer always turns the map linearly,\n * so `movement` is only set with `around: 'center'`.\n */\nexport type DragRotateOptions = {\n    /**\n     * The map turns and tilts around its center.\n     * @defaultValue 'center'\n     */\n    around?: 'center';\n    /**\n     * How a drag around the center turns the map. If `'circular'` is passed, the map follows the pointer around the center like a wheel,\n     * so the same drag turns it one way above the center and the other way below. If `'linear'` is passed, the bearing follows\n     * the horizontal movement of the pointer, the same way anywhere on the map.\n     * @defaultValue 'circular', or 'linear' if {@link MapOptions.aroundCenter} is `false`\n     */\n    movement?: 'circular' | 'linear';\n} | {\n    /**\n     * The map turns and tilts around the point under the pointer where the drag starts, on the terrain where there is any,\n     * which keeps its place on the screen and its distance from the camera, so tilting also zooms. The bearing follows the\n     * horizontal movement of the pointer. A drag that starts in the sky turns around the center.\n     */\n    around: 'pointer';\n};\n\n/**\n * The `DragRotateHandler` allows the user to rotate the map by clicking and\n * dragging the cursor while holding the right mouse button or `ctrl` key.\n *\n * @group Handlers\n */\nexport class DragRotateHandler {\n\n    _mouseRotate: MouseRotateHandler;\n    _mousePitch: MousePitchHandler;\n    _mouseRoll: MouseRollHandler;\n    _pitchWithRotate: boolean;\n    _rollEnabled: boolean;\n    _defaultMovement: 'circular' | 'linear';\n    /** @internal */\n    around: 'center' | 'pointer';\n    /** @internal */\n    movement: 'circular' | 'linear';\n\n    /** @internal */\n    constructor(options: DragRotateHandlerOptions, mouseRotate: MouseRotateHandler, mousePitch: MousePitchHandler, mouseRoll: MouseRollHandler) {\n        this._pitchWithRotate = options.pitchWithRotate;\n        this._rollEnabled = options.rollEnabled;\n        this._mouseRotate = mouseRotate;\n        this._mousePitch = mousePitch;\n        this._mouseRoll = mouseRoll;\n        const {aroundCenter = true} = options;\n        this._defaultMovement = aroundCenter ? 'circular' : 'linear';\n        this.around = 'center';\n        this.movement = this._defaultMovement;\n    }\n\n    /**\n     * Enables the \"drag to rotate\" interaction.\n     *\n     * @param options - Options object\n     * @example\n     * ```ts\n     * map.dragRotate.enable();\n     * map.dragRotate.enable({around: 'pointer'});\n     * map.dragRotate.enable({around: 'center', movement: 'linear'});\n     * ```\n     */\n    enable(options?: DragRotateOptions | boolean): void {\n        const enableOptions: DragRotateOptions = typeof options === 'object' ? options : {};\n        this.around = enableOptions.around ?? 'center';\n        this.movement = enableOptions.around === 'pointer' ? 'linear' : enableOptions.movement ?? this._defaultMovement;\n        this._mouseRotate.enable();\n        if (this._pitchWithRotate) this._mousePitch.enable();\n        if (this._rollEnabled) this._mouseRoll.enable();\n    }\n\n    /**\n     * Disables the \"drag to rotate\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.dragRotate.disable();\n     * ```\n     */\n    disable(): void {\n        this._mouseRotate.disable();\n        this._mousePitch.disable();\n        this._mouseRoll.disable();\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"drag to rotate\" interaction is enabled.\n     *\n     * @returns `true` if the \"drag to rotate\" interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled()) && (!this._rollEnabled || this._mouseRoll.isEnabled());\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"drag to rotate\" interaction is active, i.e. currently being used.\n     *\n     * @returns `true` if the \"drag to rotate\" interaction is active.\n     */\n    isActive(): boolean {\n        return this._mouseRotate.isActive() || this._mousePitch.isActive() || this._mouseRoll.isActive();\n    }\n}\n", "import type {TwoFingersTouchZoomHandler, TwoFingersTouchRotateHandler, AroundCenterOptions} from '../two_fingers_touch.ts';\nimport type {TapDragZoomHandler} from '../tap_drag_zoom.ts';\n\n/**\n * The `TwoFingersTouchZoomRotateHandler` allows the user to zoom and rotate the map by\n * pinching on a touchscreen.\n *\n * They can zoom with one finger by double tapping and dragging. On the second tap,\n * hold the finger down and drag up or down to zoom in or out.\n *\n * @group Handlers\n */\nexport class TwoFingersTouchZoomRotateHandler {\n\n    _el: HTMLElement;\n    _touchZoom: TwoFingersTouchZoomHandler;\n    _touchRotate: TwoFingersTouchRotateHandler;\n    _tapDragZoom: TapDragZoomHandler;\n    _rotationDisabled: boolean;\n    _enabled: boolean;\n\n    /** @internal */\n    constructor(el: HTMLElement, touchZoom: TwoFingersTouchZoomHandler, touchRotate: TwoFingersTouchRotateHandler, tapDragZoom: TapDragZoomHandler) {\n        this._el = el;\n        this._touchZoom = touchZoom;\n        this._touchRotate = touchRotate;\n        this._tapDragZoom = tapDragZoom;\n        this._rotationDisabled = false;\n        this._enabled = true;\n    }\n\n    /**\n     * Enables the \"pinch to rotate and zoom\" interaction.\n     *\n     * @param options - Options object.\n     *\n     * @example\n     * ```ts\n     * map.touchZoomRotate.enable();\n     * map.touchZoomRotate.enable({ around: 'center' });\n     * ```\n     */\n    enable(options?: AroundCenterOptions | boolean | null): void {\n        this._touchZoom.enable(options);\n        if (!this._rotationDisabled) this._touchRotate.enable(options);\n        this._tapDragZoom.enable();\n        this._el.classList.add('maplibregl-touch-zoom-rotate');\n    }\n\n    /**\n     * Disables the \"pinch to rotate and zoom\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.touchZoomRotate.disable();\n     * ```\n     */\n    disable(): void {\n        this._touchZoom.disable();\n        this._touchRotate.disable();\n        this._tapDragZoom.disable();\n        this._el.classList.remove('maplibregl-touch-zoom-rotate');\n    }\n\n    /**\n     * Returns a Boolean indicating whether the \"pinch to rotate and zoom\" interaction is enabled.\n     *\n     * @returns `true` if the \"pinch to rotate and zoom\" interaction is enabled.\n     */\n    isEnabled(): boolean {\n        return this._touchZoom.isEnabled() &&\n            (this._rotationDisabled || this._touchRotate.isEnabled()) &&\n            this._tapDragZoom.isEnabled();\n    }\n\n    /**\n     * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture.\n     *\n     * @returns `true` if the handler is active, `false` otherwise\n     */\n    isActive(): boolean {\n        return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive();\n    }\n\n    /**\n     * Sets the zoom rate of touch gestures.\n     * @param zoomRate - 1 The rate used to scale touch movement to a zoom value. Set to `undefined` to restore the default.\n     * @example\n     * Slow down touch zoom\n     * ```ts\n     * map.touchZoomRotate.setZoomRate(0.5);\n     * ```\n     */\n    setZoomRate(zoomRate?: number): void {\n        this._touchZoom.setZoomRate(zoomRate);\n        this._tapDragZoom.setZoomRate(zoomRate);\n    }\n\n    /**\n     * Sets the threshold before a pinch gesture starts zooming.\n     * @param zoomThreshold - 0.1 The minimum zoom delta before the pinch gesture becomes active. Set to `undefined` to restore the default.\n     * @example\n     * Make pinch zoom less sensitive\n     * ```ts\n     * map.touchZoomRotate.setZoomThreshold(0.3);\n     * ```\n     */\n    setZoomThreshold(zoomThreshold?: number): void {\n        this._touchZoom.setZoomThreshold(zoomThreshold);\n    }\n\n    /**\n     * Disables the \"pinch to rotate\" interaction, leaving the \"pinch to zoom\"\n     * interaction enabled.\n     *\n     * @example\n     * ```ts\n     * map.touchZoomRotate.disableRotation();\n     * ```\n     */\n    disableRotation(): void {\n        this._rotationDisabled = true;\n        this._touchRotate.disable();\n    }\n\n    /**\n     * Enables the \"pinch to rotate\" interaction.\n     *\n     * @example\n     * ```ts\n     * map.touchZoomRotate.enable();\n     * map.touchZoomRotate.enableRotation();\n     * ```\n     */\n    enableRotation(): void {\n        this._rotationDisabled = false;\n        if (this._touchZoom.isEnabled()) this._touchRotate.enable();\n    }\n}\n", "import {DOM} from '../../util/dom.ts';\nimport {MapLibreEvent} from '../events.ts';\n\nimport type {Event} from '../../util/evented.ts';\nimport type {Handler} from '../handler_manager.ts';\nimport type {Map} from '../map.ts';\n\n/**\n * The {@link CooperativeGesturesHandler} options object for the gesture settings\n */\nexport type GestureOptions = boolean;\n\n/**\n * A `CooperativeGestureHandler` is a control that adds cooperative gesture info when user tries to zoom in/out.\n *\n * When the CooperativeGestureHandler blocks a gesture, it will emit a `cooperativegestureprevented` event.\n *\n * @group Handlers\n *\n * @example\n * ```ts\n * const map = new Map({\n *   cooperativeGestures: true\n * });\n * ```\n * @see [Example: cooperative gestures](https://maplibre.org/maplibre-gl-js/docs/examples/cooperative-gestures/)\n **/\nexport class CooperativeGesturesHandler implements Handler {\n    _options: GestureOptions;\n    _map: Map;\n    _container: HTMLElement;\n    /**\n     * This is the key that will allow to bypass the cooperative gesture protection\n     */\n    _bypassKey: 'metaKey' | 'ctrlKey' = navigator.userAgent.includes('Mac') ? 'metaKey' : 'ctrlKey';\n    _enabled: boolean;\n\n    constructor(map: Map, options: GestureOptions) {\n        this._map = map;\n        this._options = options;\n        this._enabled = false;\n    }\n    isActive(): boolean {\n        return false;\n    }\n    reset(): void {}\n\n    _setupUI(): void {\n        if (this._container) return;\n        const mapCanvasContainer = this._map.getCanvasContainer();\n        // Add a cooperative gestures class (enable touch-action: pan-x pan-y;)\n        mapCanvasContainer.classList.add('maplibregl-cooperative-gestures');\n        this._container = DOM.create('div', 'maplibregl-cooperative-gesture-screen', mapCanvasContainer);\n        let desktopMessage = this._map._getUIString('CooperativeGesturesHandler.WindowsHelpText');\n        if (this._bypassKey === 'metaKey') {\n            desktopMessage = this._map._getUIString('CooperativeGesturesHandler.MacHelpText');\n        }\n        const mobileMessage = this._map._getUIString('CooperativeGesturesHandler.MobileHelpText');\n        // Create and append the desktop message div\n        const desktopDiv = document.createElement('div');\n        desktopDiv.className = 'maplibregl-desktop-message';\n        desktopDiv.textContent = desktopMessage;\n        this._container.appendChild(desktopDiv);\n        // Create and append the mobile message div\n        const mobileDiv = document.createElement('div');\n        mobileDiv.className = 'maplibregl-mobile-message';\n        mobileDiv.textContent = mobileMessage;\n        this._container.appendChild(mobileDiv);\n        // Remove cooperative gesture screen from the accessibility tree since screenreaders cannot interact with the map using gestures\n        this._container.setAttribute('aria-hidden', 'true');\n    }\n\n    _destroyUI(): void {\n        if (this._container) {\n            this._container.remove();\n            const mapCanvasContainer = this._map.getCanvasContainer();\n            mapCanvasContainer.classList.remove('maplibregl-cooperative-gestures');\n        }\n        delete this._container;\n    }\n\n    enable(): void {\n        this._setupUI();\n        this._enabled = true;\n    }\n\n    disable(): void {\n        this._enabled = false;\n        this._destroyUI();\n    }\n\n    isEnabled(): boolean {\n        return this._enabled;\n    }\n\n    isBypassed(event: MouseEvent | WheelEvent | PointerEvent): boolean {\n        return event[this._bypassKey];\n    }\n\n    notifyGestureBlocked(gestureType: 'wheel_zoom' | 'touch_pan', originalEvent: Event): void {\n        if (!this._enabled) return;\n\n        // notify subscribers that a cooperative gesture was prevented\n        this._map.fire(new MapLibreEvent('cooperativegestureprevented', {gestureType, originalEvent}));\n\n        // Alert user how to scroll/pan\n        this._container.classList.add('maplibregl-show');\n        setTimeout(() => {\n            this._container.classList.remove('maplibregl-show');\n        }, 100);\n    }\n}\n", "import Point from '@mapbox/point-geometry';\n\nimport type {Camera} from '../camera.ts';\nimport type {PointLike} from '../camera.ts';\nimport type {IReadonlyTransform} from '../../geo/transform_interface.ts';\nimport type {LngLat} from '../../geo/lng_lat.ts';\n\n/**\n * @internal\n * Shared utilities for the Handler classes to access the correct camera state.\n * If Camera.transformCameraUpdate is specified or terrain is enabled, the\n * \"desired state\" of camera may differ from the state used for rendering. The\n * handlers need the \"desired state\" to track accumulated changes.\n */\nexport class TransformProvider {\n    _camera: Camera;\n\n    constructor(camera: Camera) {\n        this._camera = camera;\n    }\n\n    get transform(): IReadonlyTransform {\n        return this._camera._requestedCameraState || this._camera.transform;\n    }\n\n    get center(): {lng: number; lat: number} {\n        return {lng: this.transform.center.lng, lat: this.transform.center.lat};\n    }\n\n    get zoom(): number {\n        return this.transform.zoom;\n    }\n\n    get pitch(): number {\n        return this.transform.pitch;\n    }\n\n    get bearing(): number {\n        return this.transform.bearing;\n    }\n\n    unproject(point: PointLike): LngLat {\n        return this.transform.screenPointToLocation(Point.convert(point), this._camera.terrain);\n    }\n}\n", "import {Event} from '../util/evented.ts';\nimport {MapMovementEvent} from './events.ts';\nimport {DOM} from '../util/dom.ts';\nimport {HandlerInertia} from './handler_inertia.ts';\nimport {MapEventHandler, BlockableMapEventHandler} from './handler/map_event.ts';\nimport {BoxZoomHandler} from './handler/box_zoom.ts';\nimport {TapZoomHandler} from './handler/tap_zoom.ts';\nimport {generateMouseRotationHandler, generateMousePitchHandler, generateMousePanHandler, generateMouseRollHandler} from './handler/mouse.ts';\nimport {TouchPanHandler} from './handler/touch_pan.ts';\nimport {TwoFingersTouchZoomHandler, TwoFingersTouchRotateHandler, TwoFingersTouchPitchHandler} from './handler/two_fingers_touch.ts';\nimport {KeyboardHandler} from './handler/keyboard.ts';\nimport {ScrollZoomHandler} from './handler/scroll_zoom.ts';\nimport {DoubleClickZoomHandler} from './handler/shim/dblclick_zoom.ts';\nimport {ClickZoomHandler} from './handler/click_zoom.ts';\nimport {TapDragZoomHandler} from './handler/tap_drag_zoom.ts';\nimport {DragPanHandler} from './handler/shim/drag_pan.ts';\nimport {DragRotateHandler} from './handler/shim/drag_rotate.ts';\nimport {TwoFingersTouchZoomRotateHandler} from './handler/shim/two_fingers_touch.ts';\nimport {CooperativeGesturesHandler} from './handler/cooperative_gestures.ts';\nimport {TransformProvider} from './handler/transform-provider.ts';\nimport {extend, isPointableEvent, isTouchableEvent, isTouchableOrPointableType} from '../util/util.ts';\nimport {browser} from '../util/browser.ts';\nimport Point from '@mapbox/point-geometry';\n\nimport type {Map, CompleteMapOptions} from './map.ts';\nimport type {Camera, RotationPivot} from './camera.ts';\nimport type {MapControlsDeltas} from '../geo/projection/camera_helper.ts';\nimport type {LngLat} from '../geo/lng_lat.ts';\nimport type {ITransform} from '../geo/transform_interface.ts';\nimport type {Terrain} from '../render/terrain.ts';\n\nconst isMoving = (p: EventsInProgress) => p.zoom || p.drag || p.roll || p.pitch || p.rotate;\n\n/**\n * A terrain gesture's anchor plane must stay below this fraction of the camera's\n * altitude over the center-elevation plane, or the ray-plane solve degenerates.\n */\nconst TERRAIN_ANCHOR_MAX_CAMERA_ALTITUDE_FRACTION = 0.9;\n\n/**\n * State of a gesture in flight over terrain, all of it living from the gesture's\n * first handler frame to the end of its movement.\n */\ntype TerrainGesture = {\n    /** Whether a gesture over terrain is in flight, and the center elevation frozen with it. */\n    inFlight: boolean;\n    /**\n     * Elevation in meters of the plane a drag or zoom is solved on, sampled from the terrain under the pointer on\n     * the gesture's first drag or zoom frame and again whenever the hold has changed the center elevation since:\n     * `null` not sampled yet, a number the terrain point that frame grabbed, `undefined` no terrain loaded under\n     * the pointer (the gesture is solved on the center's elevation; sampling on other frames would change how far\n     * the map moves per pixel mid-gesture).\n     */\n    anchorElevation: number | null | undefined;\n    /** The center elevation the anchor was sampled at, or null while it has not been sampled. */\n    anchorCenterElevation: number | null;\n};\n\nclass RenderFrameEvent extends Event {\n    type: 'renderFrame';\n    timeStamp: number;\n}\n\n/**\n * Handlers interpret dom events and return camera changes that should be\n * applied to the map (`HandlerResult`s). The camera changes are all deltas.\n * The handler itself should have no knowledge of the map's current state.\n * This makes it easier to merge multiple results and keeps handlers simpler.\n * For example, if there is a mousedown and mousemove, the mousePan handler\n * would return a `panDelta` on the mousemove.\n */\nexport interface Handler {\n    enable(): void;\n    disable(): void;\n    isEnabled(): boolean;\n    /**\n     * This is used to indicate if the handler is currently active or not.\n     * In case a handler is active, it will block other handlers from getting the relevant events.\n     * There is an allow list of handlers that can be active at the same time, which is configured when adding a handler.\n     */\n    isActive(): boolean;\n    /**\n     * `reset` can be called by the manager at any time and must reset everything to it's original state\n     */\n    reset(): void;\n    // Handlers can optionally implement these methods.\n    // They are called with dom events whenever those dom evens are received.\n    readonly touchstart?: (e: TouchEvent, points: Point[], mapTouches: Touch[]) => HandlerResult | void;\n    readonly touchmove?: (e: TouchEvent, points: Point[], mapTouches: Touch[]) => HandlerResult | void;\n    readonly touchmoveWindow?: (e: TouchEvent, points: Point[], mapTouches: Touch[]) => HandlerResult | void;\n    readonly touchend?: (e: TouchEvent, points: Point[], mapTouches: Touch[]) => HandlerResult | void;\n    readonly touchcancel?: (e: TouchEvent, points: Point[], mapTouches: Touch[]) => HandlerResult | void;\n    readonly mousedown?: (e: MouseEvent, point: Point) => HandlerResult | void;\n    readonly mousemove?: (e: MouseEvent, point: Point) => HandlerResult | void;\n    readonly mousemoveWindow?: (e: MouseEvent, point: Point) => HandlerResult | void;\n    readonly mouseup?: (e: MouseEvent, point: Point) => HandlerResult | void;\n    readonly mouseupWindow?: (e: MouseEvent, point: Point) => HandlerResult | void;\n    readonly dblclick?: (e: MouseEvent, point: Point) => HandlerResult | void;\n    readonly contextmenu?: (e: MouseEvent) => HandlerResult | void;\n    readonly wheel?: (e: WheelEvent, point: Point) => HandlerResult | void;\n    readonly keydown?: (e: KeyboardEvent) => HandlerResult | void;\n    readonly keyup?: (e: KeyboardEvent) => HandlerResult | void;\n    /**\n     * `renderFrame` is the only non-dom event. It is called during render\n     * frames and can be used to smooth camera changes (see scroll handler).\n     */\n    readonly renderFrame?: () => HandlerResult | void;\n}\n\n/**\n * All handler methods that are called with events can optionally return a `HandlerResult`.\n */\nexport type HandlerResult = {\n    panDelta?: Point;\n    zoomDelta?: number;\n    bearingDelta?: number;\n    pitchDelta?: number;\n    rollDelta?: number;\n    /**\n     * the point to not move when changing the camera\n     */\n    around?: Point | null;\n    /**\n     * same as above, except for pinch actions, which are given higher priority\n     */\n    pinchAround?: Point | null;\n    /**\n     * A method that can fire a one-off easing by directly changing the map's camera. The gesture ends with it: every\n     * handler is reset before it runs, so that the next frame of a handler does not stop the easing.\n     */\n    cameraAnimation?: (map: Map) => void;\n    /**\n     * The last three properties are needed by only one handler: scrollzoom.\n     * The DOM event to be used as the `originalEvent` on any camera change events.\n     */\n    originalEvent?: Event;\n    /**\n     * Makes the manager trigger a frame, allowing the handler to return multiple results over time (see scrollzoom).\n     */\n    needsRenderFrame?: boolean;\n    /**\n     * The camera changes won't get recorded for inertial zooming.\n     */\n    noInertia?: boolean;\n};\n\nexport type EventInProgress = {\n    handlerName: string;\n    originalEvent: Event;\n};\n\nexport type EventsInProgress = {\n    zoom?: EventInProgress;\n    roll?: EventInProgress;\n    pitch?: EventInProgress;\n    rotate?: EventInProgress;\n    drag?: EventInProgress;\n};\n\nexport type MapControlsScenarioOptions = {\n    terrain?: Terrain | null;\n    tr: ITransform;\n    deltasForHelper: MapControlsDeltas;\n    preZoomAroundLoc: LngLat;\n    combinedEventsInProgress: EventsInProgress;\n    panDelta?: Point;\n};\n\nfunction hasChange(result: HandlerResult) {\n    return result.panDelta?.mag() || result.zoomDelta || result.bearingDelta || result.pitchDelta || result.rollDelta;\n}\n\nexport class HandlerManager {\n    _map: Map;\n    _camera: Camera;\n    _transformProvider: TransformProvider;\n    _el: HTMLElement;\n    _handlers: Array<{\n        handlerName: string;\n        handler: Handler;\n        allowed: string[];\n    }>;\n    _eventsInProgress: EventsInProgress;\n    _frameId: number;\n    _inertia: HandlerInertia;\n    _bearingSnap: number;\n    _handlersById: {[x: string]: Handler};\n    _updatingCamera: boolean;\n    _changes: Array<[HandlerResult, EventsInProgress, {[handlerName: string]: Event}]>;\n    /**\n     * The gesture in flight over terrain, from its first handler frame to the `_fireEvents` call that sees the\n     * movement end. It holds the center elevation (see {@link Camera.holdElevation}), which\n     * {@link Camera._keepCameraAboveTerrain} may raise to keep the camera out of the terrain and lower again, and a\n     * frame that zooms in moves the held center onto the terrain the camera looks at, with the camera where it is\n     * (see {@link Camera.moveCenterOntoTerrain}); its end puts the center back onto the terrain, or at 0 keeping the\n     * zoom with the terrain off.\n     */\n    _terrainGesture: TerrainGesture = {inFlight: false, anchorElevation: null, anchorCenterElevation: null};\n    /** The point a drag turns the camera around, picked on its first frame and kept until it ends or cannot be held. */\n    _rotationPivot: RotationPivot | null = null;\n    _zoom: {handlerName: string};\n    _previousActiveHandlers: {[x: string]: Handler};\n    _listeners: Array<[Window | Document | HTMLElement, string, {\n        passive?: boolean;\n        capture?: boolean;\n    } | undefined]>;\n\n    /**\n     * @internal\n     * The document that contains the map container element, for cross-window support.\n     */\n    get _ownerDocument(): Document {\n        return this._el?.ownerDocument || document;\n    }\n\n    /**\n     * @internal\n     * The window that contains the map container element, for cross-window support.\n     */\n    get _ownerWindow(): Window {\n        return this._el?.ownerDocument?.defaultView || window;\n    }\n\n    constructor(map: Map, camera: Camera, options: CompleteMapOptions) {\n        this._map = map;\n        this._camera = camera;\n        this._transformProvider = new TransformProvider(this._camera);\n        this._el = this._map.getCanvasContainer();\n        this._handlers = [];\n        this._handlersById = {};\n        this._changes = [];\n\n        this._inertia = new HandlerInertia(map);\n        this._bearingSnap = options.bearingSnap;\n        this._previousActiveHandlers = {};\n\n        // Track whether map is currently moving, to compute start/move/end events\n        this._eventsInProgress = {};\n\n        this._addDefaultHandlers(options);\n\n        const el = this._el;\n\n        this._listeners = [\n            // This needs to be `passive: true` so that a double tap fires two\n            // pairs of touchstart/end events in iOS Safari 13. If this is set to\n            // `passive: false` then the second pair of events is only fired if\n            // preventDefault() is called on the first touchstart. Calling preventDefault()\n            // undesirably prevents click events.\n            [el, 'touchstart', {passive: true}],\n            // This needs to be `passive: false` so that scrolls and pinches can be\n            // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12.\n            [el, 'touchmove', {passive: false}],\n            [el, 'touchend', undefined],\n            [el, 'touchcancel', undefined],\n\n            [el, 'mousedown', undefined],\n            [el, 'mousemove', undefined],\n            [el, 'mouseup', undefined],\n\n            // Bind window-level event listeners for move and up/end events. In the absence of\n            // the pointer capture API, which is not supported by all necessary platforms,\n            // window-level event listeners give us the best shot at capturing events that\n            // fall outside the map canvas element. Use `{capture: true}` for the move event\n            // to prevent map move events from being fired during a drag.\n            [this._ownerDocument, 'mousemove', {capture: true}],\n            [this._ownerDocument, 'mouseup', undefined],\n\n            [el, 'mouseover', undefined],\n            [el, 'mouseout', undefined],\n            [el, 'dblclick', undefined],\n            [el, 'click', undefined],\n\n            [el, 'keydown', {capture: false}],\n            [el, 'keyup', undefined],\n\n            [el, 'wheel', {passive: false}],\n            [el, 'contextmenu', undefined],\n\n            [this._ownerWindow, 'blur', undefined]\n        ];\n\n        for (const [target, type, listenerOptions] of this._listeners) {\n            target.addEventListener(type, target === this._ownerDocument ? this.handleWindowEvent : this.handleEvent, listenerOptions);\n        }\n    }\n\n    destroy(): void {\n        for (const [target, type, listenerOptions] of this._listeners) {\n            target.removeEventListener(type, target === this._ownerDocument ? this.handleWindowEvent : this.handleEvent, listenerOptions);\n        }\n    }\n\n    _addDefaultHandlers(options: CompleteMapOptions): void {\n        const map = this._map;\n        const el = map.getCanvasContainer();\n        this._add('mapEvent', new MapEventHandler(map, options));\n\n        const boxZoom = map.boxZoom = new BoxZoomHandler(map, options, this._transformProvider);\n        this._add('boxZoom', boxZoom);\n        if (options.interactive && options.boxZoom) {\n            boxZoom.enable();\n        }\n\n        const cooperativeGestures = map.cooperativeGestures = new CooperativeGesturesHandler(map, options.cooperativeGestures);\n        this._add('cooperativeGestures', cooperativeGestures);\n        if (options.cooperativeGestures) {\n            cooperativeGestures.enable();\n        }\n\n        const tapZoom = new TapZoomHandler(map, this._transformProvider);\n        const clickZoom = new ClickZoomHandler(map, this._transformProvider);\n        map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);\n        this._add('tapZoom', tapZoom);\n        this._add('clickZoom', clickZoom);\n        if (options.interactive && options.doubleClickZoom) {\n            map.doubleClickZoom.enable();\n        }\n\n        const tapDragZoom = new TapDragZoomHandler();\n        this._add('tapDragZoom', tapDragZoom);\n\n        const touchPitch = map.touchPitch = new TwoFingersTouchPitchHandler(map);\n        this._add('touchPitch', touchPitch);\n        if (options.interactive && options.touchPitch) {\n            map.touchPitch.enable(options.touchPitch);\n        }\n        const getCenter = () => this._camera.transform.centerPoint;\n        const getAround = () => map.dragRotate.around;\n        const getMovement = () => map.dragRotate.movement;\n        const mouseRotate = generateMouseRotationHandler(options, getCenter, getAround, getMovement);\n        const mousePitch = generateMousePitchHandler(options, getAround);\n        const mouseRoll = generateMouseRollHandler(options, getCenter, getAround);\n        map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch, mouseRoll);\n        this._add('mouseRotate', mouseRotate, ['mousePitch']);\n        this._add('mousePitch', mousePitch, ['mouseRotate', 'mouseRoll']);\n        this._add('mouseRoll', mouseRoll, ['mousePitch']);\n        if (options.interactive && options.dragRotate) {\n            map.dragRotate.enable(options.dragRotate);\n        }\n\n        const mousePan = generateMousePanHandler(options);\n        const touchPan = new TouchPanHandler(options, map);\n        map.dragPan = new DragPanHandler(el, mousePan, touchPan);\n        this._add('mousePan', mousePan);\n        this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']);\n        if (options.interactive && options.dragPan) {\n            map.dragPan.enable(options.dragPan);\n        }\n\n        const touchRotate = new TwoFingersTouchRotateHandler();\n        const touchZoom = new TwoFingersTouchZoomHandler();\n        map.touchZoomRotate = new TwoFingersTouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);\n        this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']);\n        this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']);\n        if (options.interactive && options.touchZoomRotate) {\n            map.touchZoomRotate.enable(options.touchZoomRotate);\n        }\n\n        this._add('blockableMapEvent', new BlockableMapEventHandler(map, options), ['touchPan']);\n\n        const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, () => this._triggerRenderFrame(), this._transformProvider);\n        this._add('scrollZoom', scrollZoom, ['mousePan']);\n        if (options.interactive && options.scrollZoom) {\n            map.scrollZoom.enable(options.scrollZoom);\n        }\n\n        const keyboard = map.keyboard = new KeyboardHandler(map, this._transformProvider);\n        this._add('keyboard', keyboard);\n        if (options.interactive && options.keyboard) {\n            map.keyboard.enable();\n        }\n    }\n\n    _add(handlerName: string, handler: Handler, allowed?: string[]): void {\n        this._handlers.push({handlerName, handler, allowed});\n        this._handlersById[handlerName] = handler;\n    }\n\n    stop(allowEndAnimation: boolean): void {\n        // do nothing if this method was triggered by a gesture update\n        if (this._updatingCamera) return;\n\n        for (const {handler} of this._handlers) {\n            handler.reset();\n        }\n        this._inertia.clear();\n        this._fireEvents({}, {}, allowEndAnimation);\n        this._changes = [];\n    }\n\n    isActive(): boolean {\n        for (const {handler} of this._handlers) {\n            if (handler.isActive()) return true;\n        }\n        return false;\n    }\n\n    isZooming(): boolean {\n        return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();\n    }\n    isRotating(): boolean {\n        return !!this._eventsInProgress.rotate;\n    }\n\n    isMoving(): boolean {\n        return Boolean(isMoving(this._eventsInProgress)) || this.isZooming();\n    }\n\n    _blockedByActive(activeHandlers: {[x: string]: Handler}, allowed: string[], myName: string): boolean {\n        for (const name in activeHandlers) {\n            if (name === myName) continue;\n            if (!allowed?.includes(name)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    handleWindowEvent = (e: Event): void => {\n        this.handleEvent(e, `${e.type}Window` as keyof Handler);\n    };\n\n    _getMapTouches(touches: TouchList): TouchList {\n        const mapTouches = [];\n        for (const t of touches) {\n            const target = (t.target as any as Node);\n            if (this._el.contains(target)) {\n                mapTouches.push(t);\n            }\n        }\n        return mapTouches as any as TouchList;\n    }\n\n    handleEvent = (e: Event, eventName?: keyof Handler): void => {\n\n        if (e.type === 'blur') {\n            this.stop(true);\n            return;\n        }\n\n        this._updatingCamera = true;\n\n        const inputEvent = e.type === 'renderFrame' ? undefined : e as UIEvent;\n\n        /*\n         * We don't call e.preventDefault() for any events by default.\n         * Handlers are responsible for calling it where necessary.\n         */\n\n        const mergedHandlerResult: HandlerResult = {needsRenderFrame: false};\n        const eventsInProgress: EventsInProgress = {};\n        const activeHandlers = {};\n\n        for (const {handlerName, handler, allowed} of this._handlers) {\n            if (!handler.isEnabled()) continue;\n\n            let data: HandlerResult;\n            if (this._blockedByActive(activeHandlers, allowed, handlerName)) {\n                handler.reset();\n\n            } else {\n                if (handler[eventName || e.type]) {\n                    if (isPointableEvent(e, eventName || e.type)){\n                        const point = DOM.mousePos(this._map.getCanvas(), e);\n                        data = handler[eventName || e.type](e, point);\n                    } else if (isTouchableEvent(e, eventName || e.type)) {\n                        const eventTouches = e.touches;\n                        const mapTouches = this._getMapTouches(eventTouches);\n                        const points = DOM.touchPos(this._map.getCanvas(), mapTouches);\n                        data = handler[eventName || e.type](e, points, mapTouches);\n                    } else if (!isTouchableOrPointableType(eventName || e.type)) {\n                        data = handler[eventName || e.type](e);\n                    }\n                    this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);\n                    if (data?.needsRenderFrame) {\n                        this._triggerRenderFrame();\n                    }\n                }\n            }\n\n            if (data || handler.isActive()) {\n                activeHandlers[handlerName] = handler;\n            }\n        }\n\n        const deactivatedHandlers: {[handlerName: string]: Event} = {};\n        for (const name in this._previousActiveHandlers) {\n            if (!activeHandlers[name]) {\n                deactivatedHandlers[name] = inputEvent;\n            }\n        }\n        this._previousActiveHandlers = activeHandlers;\n\n        if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) {\n            this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]);\n            this._triggerRenderFrame();\n        }\n\n        if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) {\n            this._camera.stop(true);\n        }\n\n        this._updatingCamera = false;\n\n        const {cameraAnimation} = mergedHandlerResult;\n        if (cameraAnimation) {\n            this.stop(true);\n            cameraAnimation(this._map);\n        }\n    };\n\n    mergeHandlerResult(mergedHandlerResult: HandlerResult,\n        eventsInProgress: EventsInProgress,\n        handlerResult: HandlerResult,\n        name: string,\n        e?: UIEvent): void {\n        if (!handlerResult) return;\n\n        extend(mergedHandlerResult, handlerResult);\n\n        const eventData = {handlerName: name, originalEvent: handlerResult.originalEvent || e};\n\n        // track which handler changed which camera property\n        if (handlerResult.zoomDelta !== undefined) {\n            eventsInProgress.zoom = eventData;\n        }\n        if (handlerResult.panDelta !== undefined) {\n            eventsInProgress.drag = eventData;\n        }\n        if (handlerResult.rollDelta !== undefined) {\n            eventsInProgress.roll = eventData;\n        }\n        if (handlerResult.pitchDelta !== undefined) {\n            eventsInProgress.pitch = eventData;\n        }\n        if (handlerResult.bearingDelta !== undefined) {\n            eventsInProgress.rotate = eventData;\n        }\n\n    }\n\n    _applyChanges(): void {\n        const combined: HandlerResult = {};\n        const combinedEventsInProgress: EventsInProgress = {};\n        const combinedDeactivatedHandlers = {};\n\n        for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) {\n\n            if (change.panDelta) combined.panDelta = (combined.panDelta || new Point(0, 0))._add(change.panDelta);\n            if (change.zoomDelta) combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta;\n            if (change.bearingDelta) combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta;\n            if (change.pitchDelta) combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta;\n            if (change.rollDelta) combined.rollDelta = (combined.rollDelta || 0) + change.rollDelta;\n            if (change.around !== undefined) combined.around = change.around;\n            if (change.pinchAround !== undefined) combined.pinchAround = change.pinchAround;\n            if (change.noInertia) combined.noInertia = change.noInertia;\n\n            extend(combinedEventsInProgress, eventsInProgress);\n            extend(combinedDeactivatedHandlers, deactivatedHandlers);\n        }\n\n        this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers);\n        this._changes = [];\n    }\n\n    /**\n     * Applies a frame's combined handler deltas to the requested camera state and fires the movement\n     * events. A frame without a change only fires the events and takes no requested camera state, so a\n     * trailing frame that merely ends a handler leaves none behind for the next gesture to start from.\n     */\n    _updateMapTransform(combinedResult: HandlerResult,\n        combinedEventsInProgress: EventsInProgress,\n        deactivatedHandlers: {[handlerName: string]: Event}): void {\n        const map = this._map;\n        const terrain = map.terrain;\n\n        if (!hasChange(combinedResult)) {\n            this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); return;\n        }\n\n        const tr = this._camera.getTransformForUpdate();\n\n        // stop any ongoing camera animations (easeTo, flyTo)\n        this._camera.stop(true);\n\n        if (this._turnsAroundPivot(combinedResult, combinedEventsInProgress)) {\n            this._orbitRotationPivot(tr, combinedResult, terrain);\n            this._commitFrame(tr, combinedResult, combinedEventsInProgress, deactivatedHandlers);\n            return;\n        }\n\n        const {panDelta, zoomDelta, bearingDelta, pitchDelta, rollDelta} = combinedResult;\n        if (zoomDelta > 0 && this._terrainGesture.inFlight) {\n            this._camera.moveCenterOntoTerrain(tr, zoomDelta);\n        }\n\n        let {around, aroundOnSurface} = this._resolveAround(combinedResult, terrain, tr);\n        const aroundElevation = terrain ? this._terrainGestureElevation(terrain, around, aroundOnSurface, tr, combinedEventsInProgress) : undefined;\n\n        const deltasForHelper: MapControlsDeltas = {\n            panDelta,\n            zoomDelta,\n            rollDelta,\n            pitchDelta,\n            bearingDelta,\n            around,\n            aroundElevation,\n        };\n\n        // Pre-zoom location under the mouse cursor is required for accurate mercator panning and zooming\n        if (this._camera.cameraHelper.useGlobeControls && !tr.isPointOnMapSurface(around)) {\n            around = tr.centerPoint;\n        }\n        const preZoomAroundLoc = this._computePreZoomAroundLoc(tr, around, panDelta, aroundElevation);\n\n        this._handleMapControls({\n            terrain,\n            tr,\n            deltasForHelper,\n            preZoomAroundLoc,\n            combinedEventsInProgress,\n            panDelta,\n        });\n\n        this._commitFrame(tr, combinedResult, combinedEventsInProgress, deactivatedHandlers);\n    }\n\n    /** Applies the frame's camera to the map, records the frame for inertia and fires its events. */\n    _commitFrame(tr: ITransform,\n        combinedResult: HandlerResult,\n        combinedEventsInProgress: EventsInProgress,\n        deactivatedHandlers: Record<string, Event>): void {\n        this._camera.applyUpdatedTransform(tr);\n\n        this._map._update();\n        if (!combinedResult.noInertia) this._inertia.record(combinedResult);\n        this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);\n    }\n\n    /** Whether a frame rotates the camera around its own `around` point, which drag to rotate sets when it turns around the pointer. */\n    _turnsAroundPivot(combinedResult: HandlerResult, combinedEventsInProgress: EventsInProgress): boolean {\n        if (!combinedResult.around) return false;\n        return !combinedEventsInProgress.drag && !combinedEventsInProgress.zoom;\n    }\n\n    /** Turns the camera around the drag's pivot, holding the center elevation over terrain until the drag ends like every gesture. */\n    _orbitRotationPivot(tr: ITransform, combinedResult: HandlerResult, terrain: Terrain | null): void {\n        if (terrain && !this._terrainGesture.inFlight) {\n            this._terrainGesture.inFlight = true;\n            this._camera.holdElevation(tr, 'gesture');\n        }\n        const {panDelta, zoomDelta, bearingDelta, pitchDelta, rollDelta, around} = combinedResult;\n        this._rotationPivot ??= this._camera.captureRotationPivot(tr, around);\n        const held = this._camera.orbitRotationPivot(tr, this._rotationPivot, {panDelta, zoomDelta, bearingDelta, pitchDelta, rollDelta, around});\n        if (!held) this._rotationPivot = null;\n    }\n\n    /**\n     * The gesture's anchor point: the pinch midpoint when pinching, otherwise the\n     * pan's anchor, clamped to the center point when it does not lie on the map.\n     */\n    _resolveAround(combinedResult: HandlerResult, terrain: Terrain | null, tr: ITransform): {around: Point; aroundOnSurface: boolean} {\n        let around = combinedResult.pinchAround !== undefined ? combinedResult.pinchAround : combinedResult.around;\n        around ||= this._camera.transform.centerPoint;\n        if (terrain && !tr.isPointOnMapSurface(around)) {\n            return {around: tr.centerPoint, aroundOnSurface: false};\n        }\n        return {around, aroundOnSurface: true};\n    }\n\n    /**\n     * The elevation of the plane a terrain gesture is solved on: the elevation of the\n     * terrain point grabbed at gesture start, captured here on the gesture's first\n     * frame. Undefined means the gesture is solved at the center's elevation instead —\n     * when the grabbed terrain is not loaded, the anchor is the center point (a\n     * center-point anchor is skipped by the camera helper and would lose the pan), or\n     * the anchor plane is too close to the camera for a stable ray-plane solve.\n     */\n    _terrainGestureElevation(terrain: Terrain, around: Point, aroundOnSurface: boolean, tr: ITransform, combinedEventsInProgress: EventsInProgress): number | undefined {\n        if (!aroundOnSurface) {\n            return undefined;\n        }\n        if (this._terrainGesture.anchorCenterElevation !== tr.elevation && (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) {\n            const anchor = tr.screenTerrainPointToMercatorCoordinate(around, terrain);\n            this._terrainGesture.anchorElevation = anchor ? anchor.z : undefined;\n            this._terrainGesture.anchorCenterElevation = tr.elevation;\n        }\n        const elevation = this._terrainGesture.anchorElevation;\n        if (elevation === null || elevation === undefined) {\n            return undefined;\n        }\n        if (around.distSqr(tr.centerPoint) < 1.0e-2) {\n            return undefined;\n        }\n        if (elevation - tr.elevation >= TERRAIN_ANCHOR_MAX_CAMERA_ALTITUDE_FRACTION * (tr.getCameraAltitude() - tr.elevation)) {\n            return undefined;\n        }\n        return elevation;\n    }\n\n    /**\n     * The location that was under `around` before this frame's deltas — the point the\n     * camera helper re-anchors after zooming — solved at `aroundElevation` when a\n     * terrain gesture provides one. When rotating about the center point, the\n     * transform's center is used directly to avoid numerical issues near the horizon.\n     */\n    _computePreZoomAroundLoc(tr: ITransform, around: Point, panDelta: Point | undefined, aroundElevation: number | undefined): LngLat {\n        if (around.distSqr(tr.centerPoint) < 1.0e-2) {\n            return tr.center;\n        }\n        const aroundPreviousPoint = panDelta ? around.sub(panDelta) : around;\n        if (aroundElevation !== undefined) {\n            return tr.screenPointToLocationAtElevation(aroundPreviousPoint, aroundElevation);\n        }\n        return tr.screenPointToLocation(aroundPreviousPoint);\n    }\n\n    _handleMapControls({\n        terrain,\n        tr,\n        deltasForHelper,\n        preZoomAroundLoc,\n        combinedEventsInProgress,\n        panDelta}: MapControlsScenarioOptions): void {\n\n        const cameraHelper = this._camera.cameraHelper;\n\n        cameraHelper.handleMapControlsRollPitchBearingZoom(deltasForHelper, tr);\n\n        if (!terrain && !cameraHelper.useGlobeControls && !tr.isPointOnMapSurface(deltasForHelper.around)) {\n            if (panDelta) tr.setCenter(tr.screenPointToLocation(tr.centerPoint.sub(panDelta)));\n            return;\n        }\n\n        if (!terrain) {\n            cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);\n            return;\n        }\n\n        if (!this._terrainGesture.inFlight) {\n            this._terrainGesture.inFlight = true;\n            this._camera.holdElevation(tr, 'gesture');\n            cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);\n            return;\n        }\n\n        if (!cameraHelper.useGlobeControls && deltasForHelper.aroundElevation === undefined &&\n            combinedEventsInProgress.drag && panDelta) {\n            // no usable anchor: drag by pixel-delta on the center-elevation plane\n            tr.setCenter(tr.screenPointToLocation(tr.centerPoint.sub(panDelta)));\n            return;\n        }\n\n        cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);\n    }\n\n    _fireEvents(newEventsInProgress: EventsInProgress, deactivatedHandlers: {[handlerName: string]: Event}, allowEndAnimation: boolean): void {\n\n        const wasMoving = isMoving(this._eventsInProgress);\n        const nowMoving = isMoving(newEventsInProgress);\n\n        const startEvents = {};\n\n        for (const eventName in newEventsInProgress) {\n            const {originalEvent} = newEventsInProgress[eventName];\n            if (!this._eventsInProgress[eventName]) {\n                startEvents[`${eventName}start`] = originalEvent;\n            }\n            this._eventsInProgress[eventName] = newEventsInProgress[eventName];\n        }\n\n        // fire start events only after this._eventsInProgress has been updated\n        if (!wasMoving && nowMoving) {\n            this._fireEvent('movestart', nowMoving.originalEvent);\n        }\n\n        for (const name in startEvents) {\n            this._fireEvent(name, startEvents[name]);\n        }\n\n        if (nowMoving) {\n            this._fireEvent('move', nowMoving.originalEvent);\n        }\n\n        for (const eventName in newEventsInProgress) {\n            const {originalEvent} = newEventsInProgress[eventName];\n            this._fireEvent(eventName, originalEvent);\n        }\n\n        const endEvents = {};\n\n        let originalEndEvent;\n        for (const eventName in this._eventsInProgress) {\n            const {handlerName, originalEvent} = this._eventsInProgress[eventName];\n            if (!this._handlersById[handlerName].isActive()) {\n                delete this._eventsInProgress[eventName];\n                originalEndEvent = deactivatedHandlers[handlerName] || originalEvent;\n                endEvents[`${eventName}end`] = originalEndEvent;\n            }\n        }\n\n        for (const name in endEvents) {\n            this._fireEvent(name, endEvents[name]);\n        }\n\n        const stillMoving = isMoving(this._eventsInProgress);\n        const finishedMoving = (wasMoving || nowMoving) && !stillMoving;\n        if (finishedMoving && this._terrainGesture.inFlight) {\n            const tookDem = this._camera.releaseElevation();\n            this._terrainGesture = {inFlight: false, anchorElevation: null, anchorCenterElevation: null};\n            this._camera.applyTransformChange(tr => {\n                if (!this._map.getCenterClampedToGround()) return;\n                if (this._map.terrain) {\n                    this._camera.putCenterBackOnTerrain(tr, this._map.terrain, tookDem);\n                } else {\n                    tr.setElevation(0);\n                }\n            });\n        }\n        if (allowEndAnimation && finishedMoving) {\n            this._updatingCamera = true;\n            const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);\n\n            const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap;\n\n            if (inertialEase && (inertialEase.essential || !browser.prefersReducedMotion)) {\n                if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) {\n                    inertialEase.bearing = 0;\n                }\n                inertialEase.freezeElevation = true;\n                this._map.easeTo(inertialEase, {originalEvent: originalEndEvent});\n            } else {\n                this._fireEvent('moveend', originalEndEvent);\n                if (shouldSnapToNorth(this._map.getBearing())) {\n                    this._map.resetNorth();\n                }\n            }\n            this._updatingCamera = false;\n        }\n        if (finishedMoving) this._rotationPivot = null;\n\n    }\n\n    /**\n     * Fires a movement event through the camera, whose evented parent is the map: the map's listeners\n     * see the event as before, and the camera's own `moveend` listener drops the requested camera state,\n     * so the next gesture starts from the rendered transform instead of the state this one ended in.\n     */\n    _fireEvent(type: string, e?: Event): void {\n        this._camera.fire(new MapMovementEvent(type, e ? {originalEvent: e} : {}));\n    }\n\n    _requestFrame(): number {\n        this._map.triggerRepaint();\n        return this._map._renderTaskQueue.add(timeStamp => {\n            delete this._frameId;\n            this.handleEvent(new RenderFrameEvent('renderFrame', {timeStamp}));\n            this._applyChanges();\n        });\n    }\n\n    _triggerRenderFrame(): void {\n        if (this._frameId === undefined) {\n            this._frameId = this._requestFrame();\n        }\n    }\n}\n", "import type {Terrain} from '../render/terrain.ts';\nimport type {ITransform} from '../geo/transform_interface.ts';\n\n/** Who holds the center elevation: a gesture, or an animation with `freezeElevation`. */\nexport type ElevationHolder = 'gesture' | 'animation';\n\n/**\n * A hold on the center elevation, see {@link Camera.holdElevation}: one that started where no DEM data under a center\n * clamped to the ground had loaded, or whose terrain changed to one without DEM data there, waits for it and follows\n * the terrain drawn under the center until the tile there has its own. It holds no transform: a gesture's takes on the\n * terrain change, on the requested camera state its frames read; an animation's on its next frame, on the transform it\n * edits, which a projection change does not replace, or at its end when nothing ran in between.\n */\nexport class ElevationHold {\n    /**\n     * Where the hold stands with the DEM data under the center:\n     * - `loaded`: the tile under the center had its DEM data when the hold started, so the hold keeps its elevation.\n     * - `awaiting`: no DEM data under the center yet, from the start or since a terrain change left none there; the\n     * hold follows the terrain drawn there, see {@link take}.\n     * - `taken`: the hold waited and then took the elevation of the tile's own DEM data. Unlike `loaded`, the elevation\n     * came during the hold, so the end keeps the zoom where that data is missing again, see\n     * {@link Camera.putCenterBackOnTerrain}.\n     */\n    private _dem: 'loaded' | 'awaiting' | 'taken';\n    /**\n     * While {@link Camera._keepCameraAboveTerrain} has lifted the held elevation: the elevation held and how far above\n     * it the camera was lifted, so later frames can lower it again as the terrain allows and tell the lifted elevation\n     * from one a take set anew, which carries no lift; null while nothing is lifted.\n     */\n    lift: {heldElevation: number; height: number} | null = null;\n    /**\n     * Whether {@link Camera._keepCameraAboveTerrain} keeps the drawn terrain below where the center would sit at maxZoom,\n     * see {@link Camera._terrainHeightAboveMaxZoomForCenter}: from the start of a hold that starts with the terrain below\n     * that point, as on the ground at rest, or from the first frame the terrain is below it. A hold that starts with the\n     * terrain above it, as behind a crest, leaves the terrain there.\n     */\n    keepsTerrainBelowMaxZoomForCenter: boolean;\n    private _terrainChanged = false;\n\n    /**\n     * @param holder - who holds the elevation\n     * @param startedWithoutDem - whether the hold started without DEM data under the center, and so waits for it\n     * @param terrainBelowMaxZoomForCenter - whether the drawn terrain is below where the center would sit at maxZoom when\n     * the hold starts, see {@link Camera._terrainHeightAboveMaxZoomForCenter}\n     */\n    constructor(readonly holder: ElevationHolder, startedWithoutDem: boolean, terrainBelowMaxZoomForCenter: boolean) {\n        this._dem = startedWithoutDem ? 'awaiting' : 'loaded';\n        this.keepsTerrainBelowMaxZoomForCenter = terrainBelowMaxZoomForCenter;\n    }\n\n    /** Whether the hold waited for DEM data under the center and took the data of the tile there. */\n    get tookDem(): boolean {\n        return this._dem === 'taken';\n    }\n\n    /** Asks the next {@link take} to check for DEM data under the center, after the terrain changed. */\n    noteTerrainChange(): void {\n        this._terrainChanged = true;\n    }\n\n    /**\n     * While the hold waits, takes the elevation the terrain draws under the center: a loaded parent tile's DEM data,\n     * drawn in place of the tile's own until that lands, and then the tile's own, which ends the wait. After a terrain\n     * change that leaves no DEM data under the center, puts the center back at the 0 the terrain gives there and\n     * waits again.\n     * @param tr - the transform the gesture or animation edits\n     * @param terrain - the terrain under it\n     * @returns whether it changed the elevation\n     */\n    take(tr: ITransform, terrain: Terrain): boolean {\n        let changed = false;\n        if (this._terrainChanged) {\n            this._terrainChanged = false;\n            if (terrain.getElevationAndDEMStateForLngLat(tr.center, tr.tileZoom).demState !== 'loaded') {\n                tr.setElevation(0);\n                this._dem = 'awaiting';\n                changed = true;\n            }\n        }\n        if (this._dem !== 'awaiting') return changed;\n        const elevation = terrain.getDrawnElevationForLngLat(tr.center, true);\n        if (elevation !== undefined) {\n            tr.setElevation(elevation);\n            this._dem = 'taken';\n            return true;\n        }\n        const drawnElevation = terrain.getDrawnElevationForLngLat(tr.center);\n        if (drawnElevation === undefined || drawnElevation === tr.elevation) return changed;\n        tr.setElevation(drawnElevation);\n        return true;\n    }\n}\n", "import {now} from '../util/time_control.ts';\nimport {Evented} from '../util/evented.ts';\nimport {MapMovementEvent} from './events.ts';\n\nimport type {MapEventType} from './events.ts';\nimport type {TaskID} from '../util/task_queue.ts';\n\n/**\n * A part of the camera, besides its center, that a movement can change. Each has start, during and end events\n * of its own, named after it: `zoomstart`, `zoom`, `zoomend` and so on.\n */\nexport type MovementAxis = 'zoom' | 'rotate' | 'pitch' | 'roll';\n\nconst MOVEMENT_AXES: readonly MovementAxis[] = ['zoom', 'rotate', 'pitch', 'roll'];\n\n/** Which parts of the camera a movement changes. */\nexport type MovementAxes = Record<MovementAxis, boolean>;\n\n/** Movement axes of which none is moving. */\nfunction idleMovementAxes(): MovementAxes {\n    return {zoom: false, rotate: false, pitch: false, roll: false};\n}\n\n/**\n * @internal\n * What one timed piece of a camera movement does to the camera, as an `easeTo` or a `flyTo` hands it to\n * {@link CameraMovementScheduler.scheduleSegment} together with its {@link MovementSegmentOptions}. A movement is\n * one segment, or several when each continues the movement of the one before it, see\n * {@link MovementSegmentOptions.easeId}. Everything a frame needs lives in the segment itself, so a segment started\n * from one of its listeners cannot change what it draws.\n */\nexport interface MovementSegment {\n    /**\n     * Moves the camera to the eased progress `k`, 0 to 1. It fires no events: the scheduler fires them once the\n     * frame is done.\n     */\n    onFrame(k: number): void;\n    /** Runs once when the segment ends, whether it ran to the end or something interrupted it. */\n    onFinish(): void;\n}\n\n/**\n * @internal\n * How the scheduler runs a {@link MovementSegment}, and which events it fires for it.\n */\nexport type MovementSegmentOptions = {\n    /** In milliseconds. A segment of 0 runs its only frame within {@link CameraMovementScheduler.scheduleSegment}. */\n    duration: number;\n    easing: (t: number) => number;\n    /** The parts of the camera the segment changes, for which its movement fires start, during and end events. */\n    axes: MovementAxes;\n    /** The properties every event the segment fires carries. */\n    eventData?: Record<string, unknown>;\n    /**\n     * A segment that replaces one with the same id continues its movement: the replaced one fires no end events, and\n     * this one fires start events only for the parts of the camera the movement did not change yet.\n     */\n    easeId?: string;\n    /** Whether someone else fired the movement's `movestart` already, such as the gesture the segment is the inertia of. */\n    movestartFired?: boolean;\n};\n\n/** A segment as it was scheduled, with its options and the time it started at. */\ntype ScheduledSegment = {\n    segment: MovementSegment;\n    options: MovementSegmentOptions;\n    /** When the segment started, in the time of {@link now}. */\n    startTime: number;\n};\n\ntype PendingEvent = {\n    event: MapMovementEvent;\n    /**\n     * The segment whose frame queued the event, set only on frame events, so that a segment stopped before they are\n     * delivered can drop them.\n     */\n    frameSegment?: ScheduledSegment;\n};\n\n/**\n * @internal\n * The map's render loop, on which the scheduler runs each frame of a segment.\n */\nexport type RenderLoop = {\n    /** Runs the callback before the next frame is rendered, and returns an id to cancel it with. */\n    requestRenderFrame: (callback: () => void) => TaskID;\n    cancelRenderFrame: (id: TaskID) => void;\n};\n\n/**\n * @internal\n * Runs the segments of the camera's movements and fires their movement events, which reach the camera's listeners\n * through the camera being its evented parent.\n *\n * At most one segment runs, on at most one render frame request, and every frame reads which segment is current when\n * it runs rather than when it was requested. A segment started or stopped from a listener therefore replaces or ends\n * what the next frame does, and never runs next to the one it interrupted.\n *\n * Events wait in one list of pending events that only one loop delivers. A call from a listener changes the camera at\n * once, while the events it causes are delivered after the event being delivered. So an interrupted segment's end\n * events always come before the start events of the one that interrupted it, and the events of a frame it never\n * finishes are dropped: no `zoom` can follow its `zoomend`, and nothing it fires follows its `moveend`.\n */\nexport class CameraMovementScheduler extends Evented<MapEventType> {\n    private readonly _renderLoop: RenderLoop;\n    private _currentSegment: ScheduledSegment | null = null;\n    private _frameRequestId: TaskID | null = null;\n    /** The parts of the camera the movement in progress changes, whose start events have been queued. */\n    private _movingAxes: MovementAxes = idleMovementAxes();\n    private _pendingEvents: PendingEvent[] = [];\n    private _deliveringEvents = false;\n\n    constructor(renderLoop: RenderLoop) {\n        super();\n        this._renderLoop = renderLoop;\n    }\n\n    /**\n     * Whether a movement is in progress. A movement lasts as long as a segment runs, and a segment that continues\n     * another's movement replaces it without a gap, see {@link MovementSegmentOptions.easeId}.\n     */\n    isMoving(): boolean {\n        return this._currentSegment !== null;\n    }\n\n    isMovingAxis(axis: MovementAxis): boolean {\n        return this._movingAxes[axis];\n    }\n\n    /**\n     * Whether the current segment is continued by a segment with this `easeId`, which carries on its movement instead\n     * of interrupting it, see {@link MovementSegmentOptions.easeId}.\n     */\n    isContinuedBy(easeId?: string): boolean {\n        return !!easeId && this._currentSegment?.options.easeId === easeId;\n    }\n\n    /**\n     * Makes a segment the current one and schedules its frames on the render loop. The segment that ran until now is\n     * interrupted at once, its end events queued ahead of the new segment's start events, unless the new one continues\n     * its movement. A segment with a duration of 0 runs its frame and ends within this call.\n     */\n    scheduleSegment(segment: MovementSegment, options: MovementSegmentOptions): void {\n        const continuing = this.isContinuedBy(options.easeId);\n        if (continuing) this._stopSegment(this._currentSegment);\n        else this.interrupt();\n\n        this._currentSegment = {segment, options, startTime: now()};\n        this._queueStartEvents(options, continuing);\n\n        if (options.duration === 0) {\n            this._runSegmentFrame(this._currentSegment, 1, true);\n            return;\n        }\n        this._requestRenderFrame();\n        this._deliverPendingEvents();\n    }\n\n    /** Ends the current segment where it is and fires its end events. */\n    interrupt(): void {\n        if (!this._currentSegment) return;\n\n        const {eventData} = this._currentSegment.options;\n        this._stopSegment(this._currentSegment);\n        this._queueEndEvents(eventData);\n        this._deliverPendingEvents();\n    }\n\n    /**\n     * Fires events that are not a segment's, such as those of a `jumpTo`, whose movement has no frames, after the\n     * events already queued, so that they follow the end events of a segment they interrupt.\n     */\n    fireAfterQueued(events: MapMovementEvent[]): void {\n        for (const event of events) this._pendingEvents.push({event});\n        this._deliverPendingEvents();\n    }\n\n    private readonly _onRenderFrame = (): void => {\n        this._frameRequestId = null;\n        if (!this._currentSegment) return;\n\n        const {startTime, options: {duration, easing}} = this._currentSegment;\n        const t = Math.min((now() - startTime) / duration, 1);\n        this._runSegmentFrame(this._currentSegment, easing(t), t === 1);\n    };\n\n    /**\n     * Draws a frame of the segment and delivers its events. The last frame finishes the segment only once its events\n     * are delivered, and only if none of their listeners interrupted it.\n     */\n    private _runSegmentFrame(scheduled: ScheduledSegment, k: number, last: boolean): void {\n        scheduled.segment.onFrame(k);\n        this._queueFrameEvents(scheduled);\n        if (!last) this._requestRenderFrame();\n        this._deliverPendingEvents();\n\n        if (!last || this._currentSegment !== scheduled) return;\n        this._finishSegment(scheduled);\n        this._queueEndEvents(scheduled.options.eventData);\n        this._deliverPendingEvents();\n    }\n\n    /**\n     * Ends a segment before its last frame: cancels the frame it requested and drops the events of a frame of it that\n     * are not delivered yet.\n     */\n    private _stopSegment(scheduled: ScheduledSegment): void {\n        this._cancelRenderFrame();\n        this._pendingEvents = this._pendingEvents.filter(pending => pending.frameSegment !== scheduled);\n        this._finishSegment(scheduled);\n    }\n\n    private _finishSegment(scheduled: ScheduledSegment): void {\n        this._currentSegment = null;\n        scheduled.segment.onFinish();\n    }\n\n    private _requestRenderFrame(): void {\n        this._frameRequestId = this._renderLoop.requestRenderFrame(this._onRenderFrame);\n    }\n\n    private _cancelRenderFrame(): void {\n        if (this._frameRequestId === null) return;\n        this._renderLoop.cancelRenderFrame(this._frameRequestId);\n        this._frameRequestId = null;\n    }\n\n    /**\n     * @param continuing - whether the segment continues the movement of the one it replaced, which fired its\n     * `movestart` and the start events of the parts of the camera it changed\n     */\n    private _queueStartEvents(options: MovementSegmentOptions, continuing: boolean): void {\n        if (!continuing && !options.movestartFired) {\n            this._pendingEvents.push({event: new MapMovementEvent('movestart', options.eventData)});\n        }\n\n        for (const axis of MOVEMENT_AXES) {\n            if (!options.axes[axis] || this._movingAxes[axis]) continue;\n            this._movingAxes[axis] = true;\n            this._pendingEvents.push({event: new MapMovementEvent(`${axis}start`, options.eventData)});\n        }\n    }\n\n    private _queueFrameEvents(scheduled: ScheduledSegment): void {\n        const {eventData} = scheduled.options;\n        this._pendingEvents.push({event: new MapMovementEvent('move', eventData), frameSegment: scheduled});\n        for (const axis of MOVEMENT_AXES) {\n            if (this._movingAxes[axis]) this._pendingEvents.push({event: new MapMovementEvent(axis, eventData), frameSegment: scheduled});\n        }\n    }\n\n    private _queueEndEvents(eventData: Record<string, unknown> | undefined): void {\n        const axes = this._movingAxes;\n        this._movingAxes = idleMovementAxes();\n\n        for (const axis of MOVEMENT_AXES) {\n            if (axes[axis]) this._pendingEvents.push({event: new MapMovementEvent(`${axis}end`, eventData)});\n        }\n        this._pendingEvents.push({event: new MapMovementEvent('moveend', eventData)});\n    }\n\n    /**\n     * Delivers the pending events, unless an outer call is delivering them already, in which case that call delivers\n     * the ones queued now as well. A listener that throws drops the events still pending, as they describe a movement\n     * the camera can no longer finish in order.\n     */\n    private _deliverPendingEvents(): void {\n        if (this._deliveringEvents) return;\n        this._deliveringEvents = true;\n        try {\n            while (this._pendingEvents.length) this.fire(this._pendingEvents.shift().event);\n        } catch (e) {\n            this._pendingEvents = [];\n            throw e;\n        } finally {\n            this._deliveringEvents = false;\n        }\n    }\n}\n", "import Point from '@mapbox/point-geometry';\nimport {vec3} from 'gl-matrix';\nimport {extend, wrap, defaultEasing, evaluateZoomSnap, lerp, scaleZoom, zoomScale} from '../util/util.ts';\nimport {interpolates} from '@maplibre/maplibre-gl-style-spec';\nimport {browser} from '../util/browser.ts';\nimport {LngLat, earthRadius} from '../geo/lng_lat.ts';\nimport {LngLatBounds} from '../geo/lng_lat_bounds.ts';\nimport {Evented} from '../util/evented.ts';\nimport {MapMovementEvent} from './events.ts';\nimport {createMercatorTransform} from '../geo/projection/mercator_transform.ts';\nimport {MercatorCameraHelper} from '../geo/projection/mercator_camera_helper.ts';\nimport {angularCoordinatesToSurfaceVector} from '../geo/projection/globe_utils.ts';\nimport {sampleAt} from '../render/terrain_coverage.ts';\nimport {ElevationHold} from './elevation_hold.ts';\nimport {CameraMovementScheduler} from './camera_movement_scheduler.ts';\n\nimport type {MapEventType} from './events.ts';\nimport type {Terrain} from '../render/terrain.ts';\nimport type {IReadonlyTransform, ITransform, TransformConstrainFunction} from '../geo/transform_interface.ts';\nimport type {LngLatLike} from '../geo/lng_lat.ts';\nimport type {LngLatBoundsLike} from '../geo/lng_lat_bounds.ts';\nimport type {TaskID} from '../util/task_queue.ts';\nimport type {PaddingOptions} from '../geo/edge_insets.ts';\nimport type {ICameraHelper, MapControlsDeltas} from '../geo/projection/camera_helper.ts';\nimport type {ElevationHolder} from './elevation_hold.ts';\n\n/**\n * A [Point](https://github.com/mapbox/point-geometry) or an array of two numbers representing `x` and `y` screen coordinates in pixels.\n *\n * @group Geography and Geometry\n *\n * @example\n * ```ts\n * let p1 = new Point(-77, 38); // a PointLike which is a Point\n * let p2 = [-77, 38]; // a PointLike which is an array of two numbers\n * ```\n */\nexport type PointLike = Point | [number, number];\n\n/**\n * How many times a camera update outside a held gesture raises a camera it found inside the terrain, each time by as far\n * as the terrain still reaches above it; the new pitch and zoom move the near clipping plane, so the remainder shrinks\n * with each pass, and three leave it within a few meters of a floor 20 km above the center in the tests.\n */\nconst MAX_CAMERA_RAISES = 3;\n\n/**\n * How far from the terrain a zoom-in frame's re-solve may leave the held center and still count as moving it onto the\n * terrain. A re-solve that lands leaves the center within a millimeter; a meter or more means the terrain the center ray\n * hits and the terrain the DEM reports under the new center disagree, over a rise the scene has not drawn yet or past a\n * crest the ray slipped over, and the frame keeps the held center instead.\n */\nconst MAX_CENTER_OFF_TERRAIN_M = 1;\n\n/**\n * How far the drawn terrain may rise above where the center would sit at maxZoom, see\n * {@link Camera._terrainHeightAboveMaxZoomForCenter}, and still count as below it: a center on the ground at maxZoom\n * sits there already, and two reads of the same surface under it differ by rounding.\n */\nconst MAX_ZOOM_FOR_CENTER_TOLERANCE_M = 0.01;\n\n/** Pixels a rotation pivot keeps below the horizon, closer to which a pixel spans too much ground to hold it. */\nconst PIVOT_HORIZON_MARGIN_PX = 16;\n\n/** How many times the zoom is corrected to reach a rotation pivot's distance. Mercator needs two, the globe a few more. */\nconst MAX_PIVOT_ZOOM_CORRECTIONS = 5;\n\n/** The share of a rotation pivot's distance within which the camera counts as being at that distance. */\nconst PIVOT_DISTANCE_TOLERANCE = 1e-7;\n\n/** The share of a rotation pivot's distance within which the ground under its screen point counts as the pivot, about a tenth of a pixel. */\nconst PIVOT_POINT_TOLERANCE = 1e-4;\n\n/** The point a drag turns the camera around, with the screen point and the distance in meters from the camera it keeps. */\nexport type RotationPivot = {\n    point: Point;\n    location: LngLat;\n    /** The elevation of a pivot on mercator terrain. Without it the pivot lies on the ground the transform unprojects to. */\n    elevation?: number;\n    distance: number;\n};\n\n/**\n * Options common to {@link Map.jumpTo}, {@link Map.easeTo}, and {@link Map.flyTo}, controlling the desired location,\n * zoom, bearing, pitch, and roll of the camera. All properties are optional, and when a property is omitted, the current\n * camera value for that property will remain unchanged.\n *\n * @example\n * Set the map's initial perspective with CameraOptions\n * ```ts\n * let map = new Map({\n *   container: 'map',\n *   style: 'https://demotiles.maplibre.org/style.json',\n *   center: [-73.5804, 45.53483],\n *   pitch: 60,\n *   bearing: -60,\n *   zoom: 10\n * });\n * ```\n * @see [Set pitch and bearing](https://maplibre.org/maplibre-gl-js/docs/examples/set-pitch-and-bearing/)\n * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to-a-series-of-locations/)\n * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/fly-to-a-location/)\n * @see [Display buildings in 3D](https://maplibre.org/maplibre-gl-js/docs/examples/display-buildings-in-3d/)\n */\nexport type CameraOptions = CenterZoomBearing & {\n    /**\n     * The desired pitch in degrees. The pitch is the angle towards the horizon\n     * measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance\n     * of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon.\n     * Increasing the pitch value is often used to display 3D objects.\n     */\n    pitch?: number;\n    /**\n     * The desired roll in degrees. The roll is the angle about the camera boresight.\n     */\n    roll?: number;\n    /**\n     * The elevation of the center point in meters above sea level.\n     */\n    elevation?: number;\n};\n\n/**\n * Holds center, zoom and bearing properties\n */\nexport type CenterZoomBearing = {\n    /**\n     * The desired center.\n     */\n    center?: LngLatLike;\n    /**\n     * The desired mercator zoom level.\n     */\n    zoom?: number;\n    /**\n     * The desired bearing in degrees. The bearing is the compass direction that\n     * is \"up\". For example, `bearing: 90` orients the map so that east is up.\n     */\n    bearing?: number;\n};\n\n/**\n * The options object related to the {@link Map.jumpTo} method\n */\nexport type JumpToOptions = CameraOptions & {\n    /**\n     * Dimensions in pixels applied on each side of the viewport for shifting the vanishing point.\n     */\n    padding?: PaddingOptions;\n};\n\n/** Options for calculating an anchored camera. */\nexport type AnchoredCameraOptions = {\n    /** Geographic location to anchor. */\n    anchorLocation: LngLatLike;\n    /** Screen position for the anchor. */\n    anchorScreenPoint: PointLike;\n    /** Desired zoom level. */\n    zoom?: number;\n};\n\n/**\n * A options object for the {@link Map.cameraForBounds} method\n */\nexport type CameraForBoundsOptions = CameraOptions & {\n    /**\n     * The amount of padding in pixels to add to the given bounds, on top of the map's current padding.\n     */\n    padding?: number | PaddingOptions;\n    /**\n     * If `true`, `padding` replaces the map's current padding instead of adding to it, and is returned with the result.\n     * This will become the default in version 7.\n     * @defaultValue false\n     */\n    absolutePadding?: boolean;\n    /**\n     * The center of the given bounds relative to the map's center, measured in pixels.\n     * @defaultValue [0, 0]\n     */\n    offset?: PointLike;\n    /**\n     * The maximum zoom level to allow when the camera would transition to the specified bounds.\n     */\n    maxZoom?: number;\n};\n\n/**\n * The {@link Map.flyTo} options object\n */\nexport type FlyToOptions = AnimationOptions & CameraOptions & {\n    /**\n     * The zooming \"curve\" that will occur along the\n     * flight path. A high value maximizes zooming for an exaggerated animation, while a low\n     * value minimizes zooming for an effect closer to {@link Map.easeTo}. 1.42 is the average\n     * value selected by participants in the user study discussed in\n     * [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of\n     * `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A\n     * value of 1 would produce a circular motion.\n     * @defaultValue 1.42\n     */\n    curve?: number;\n    /**\n     * The minimum zoom level that the flight arc may reach. The animation will\n     * not zoom out beyond this level. If the natural flight arc stays within\n     * this boundary, the arc is unchanged. This acts as a ceiling on zoom-out\n     * even when `options.curve` is also specified.\n     */\n    minZoom?: number;\n    /**\n     * The average speed of the animation defined in relation to\n     * `options.curve`. A speed of 1.2 means that the map appears to move along the flight path\n     * by 1.2 times `options.curve` screenfulls every second. A _screenfull_ is the map's visible span.\n     * It does not correspond to a fixed physical distance, but varies by zoom level.\n     * @defaultValue 1.2\n     */\n    speed?: number;\n    /**\n     * The average speed of the animation measured in screenfulls\n     * per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored.\n     */\n    screenSpeed?: number;\n    /**\n     * The animation's maximum duration, measured in milliseconds.\n     * If duration exceeds maximum duration, it resets to 0.\n     */\n    maxDuration?: number;\n    /**\n     * The amount of padding in pixels to add to the given bounds.\n     */\n    padding?: number | PaddingOptions;\n};\n\n/**\n * The {@link Map.easeTo} options object\n */\nexport type EaseToOptions = AnimationOptions & CameraOptions & {\n    /**\n     * @deprecated Has no effect, and will be removed in the next major version.\n     */\n    delayEndEvents?: number;\n    /**\n     * Dimensions in pixels applied on each side of the viewport for shifting the vanishing point, which the transition\n     * animates to. The map keeps this padding once the transition ends.\n     */\n    padding?: number | PaddingOptions;\n    /**\n     * If `zoom` is specified, `around` determines the point around which the zoom is centered.\n     */\n    around?: LngLatLike;\n    /**\n     * @internal\n     * An animation started with the `easeId` of the one running continues its movement instead of interrupting it, so\n     * that no end and start events fire between the two, as for a key the keyboard handler sees held down.\n     * @deprecated Set by MapLibre's own handlers and not meant for applications; it will be removed from this type in\n     * the next major version.\n     */\n    easeId?: string;\n    /**\n     * @internal\n     * Whether the animation continues a movement whose `movestart` someone else fired, such as the gesture whose\n     * inertia it is.\n     * @deprecated Set by MapLibre's own handlers and not meant for applications; it will be removed from this type in\n     * the next major version.\n     */\n    noMoveStart?: boolean;\n};\n\n/**\n * Options for {@link Map.fitBounds} method\n */\nexport type FitBoundsOptions = FlyToOptions & {\n    /**\n     * If `true`, the map transitions using {@link Map.easeTo}. If `false`, the map transitions using {@link Map.flyTo}.\n     * See those functions and {@link AnimationOptions} for information about options available.\n     * @defaultValue false\n     */\n    linear?: boolean;\n    /**\n     * If `true`, `padding` replaces the map's current padding instead of adding to it, and the map transitions to it.\n     * This will become the default in version 7.\n     * @defaultValue false\n     */\n    absolutePadding?: boolean;\n    /**\n     * The center of the given bounds relative to the map's center, measured in pixels.\n     * @defaultValue [0, 0]\n     */\n    offset?: PointLike;\n    /**\n     * The maximum zoom level to allow when the map view transitions to the specified bounds.\n     */\n    maxZoom?: number;\n};\n\n/**\n * Options common to map movement methods that involve animation, such as {@link Map.panBy} and\n * {@link Map.easeTo}, controlling the duration and easing function of the animation. All properties\n * are optional.\n *\n */\nexport type AnimationOptions = {\n    /**\n     * The animation's duration, measured in milliseconds.\n     */\n    duration?: number;\n    /**\n     * A function taking a time in the range 0..1 and returning a number where 0 is\n     * the initial state and 1 is the final state.\n     */\n    easing?: (_: number) => number;\n    /**\n     * of the target center relative to real map container center at the end of animation.\n     */\n    offset?: PointLike;\n    /**\n     * If `false`, no animation will occur.\n     */\n    animate?: boolean;\n    /**\n     * If `true`, then the animation is considered essential and will not be affected by\n     * [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/\\@media/prefers-reduced-motion).\n     */\n    essential?: boolean;\n    /**\n     * Default false. Needed in 3D maps to let the camera stay in a constant\n     * height based on sea-level. After the animation finished the zoom-level will be recalculated in respect of\n     * the distance from the camera to the center-coordinate-altitude.\n     */\n    freezeElevation?: boolean;\n};\n\n/**\n * A callback hook that allows manipulating the camera and being notified about camera updates before they happen\n */\nexport type CameraUpdateTransformFunction =  (next: {\n    center: LngLat;\n    zoom: number;\n    roll: number;\n    pitch: number;\n    bearing: number;\n    elevation: number;\n}) => {\n    center?: LngLat;\n    zoom?: number;\n    roll?: number;\n    pitch?: number;\n    bearing?: number;\n    elevation?: number;\n};\n\nexport type CameraInitOptions = {\n    minZoom: number;\n    maxZoom: number;\n    minPitch: number;\n    maxPitch: number;\n    bearingSnap: number;\n    zoomSnap: number;\n    renderWorldCopies: boolean;\n    centerClampedToGround: boolean;\n    terrain: Terrain;\n    transformConstrain: TransformConstrainFunction;\n    requestRenderFrame: (a: () => void) => TaskID;\n    cancelRenderFrame: (_: TaskID) => void;\n    transformCameraUpdate: CameraUpdateTransformFunction | null;\n    /**\n     * @internal\n     * Callback invoked by {@link Camera.stop} to halt any in-progress user gestures.\n     * The `Camera` does not own the gesture handlers (the `Map` does), so it is injected\n     * with a way to stop them rather than holding a reference to the `HandlerManager`.\n     */\n    stopHandlers?: () => void;\n};\n\nexport class Camera extends Evented<MapEventType> {\n    private _transform: ITransform;\n    /**\n     * @internal\n     * The transform the map is drawn with. Other classes read it here, and a camera movement edits it through\n     * {@link Camera.getTransformForUpdate}.\n     */\n    get transform(): IReadonlyTransform { return this._transform; }\n    /**\n     * @internal\n     * Copy of the map's `terrain` (which the `Map` owns).\n     * The camera reads terrain for elevation handling but does not own it.\n     */\n    terrain: Terrain;\n    cameraHelper: ICameraHelper;\n    /**\n     * @internal\n     * Stops any in-progress user gestures. Injected by the owner so the camera does not need\n     * a reference to the `HandlerManager`. See {@link CameraInitOptions.stopHandlers}.\n     */\n    _stopHandlers: () => void;\n\n    /** Runs `easeTo`, `flyTo` and `jumpTo` and fires their movement events. */\n    private readonly _scheduler: CameraMovementScheduler;\n\n    _bearingSnap: number;\n    _zoomSnap: number;\n\n    /**\n     * @internal\n     * Saves the current state of the elevation freeze - this is used during map movement to prevent \"rocky\" camera movement.\n     */\n    elevationFreeze: boolean;\n    /**\n     * @internal\n     * The hold a gesture or an animation with `freezeElevation` keeps on the center elevation, or null while nothing\n     * holds it, see {@link Camera.holdElevation}. An animation that eases the center elevation sets `elevationFreeze`\n     * without one.\n     */\n    _elevationHold: ElevationHold | null = null;\n    /**\n     * @internal\n     * Used to track accumulated changes during continuous interaction\n     */\n    _requestedCameraState?: ITransform;\n    /**\n     * A callback used to defer camera updates or apply arbitrary constraints.\n     * If specified, this Camera instance can be used as a stateless component in React etc.\n     */\n    transformCameraUpdate: CameraUpdateTransformFunction | null;\n\n    /**\n     * @internal\n     * If true, the elevation of the center point will automatically be set to the terrain elevation\n     * (or zero if terrain is not enabled). If false, the elevation of the center point will default\n     * to sea level and will not automatically update. Defaults to true. Needs to be set to false to\n     * keep the camera above ground when pitch \\> 90 degrees.\n     */\n    _centerClampedToGround: boolean;\n\n    constructor(options: CameraInitOptions) {\n        super();\n        // For now we will use a temporary MercatorTransform instance.\n        // Transform specialization will later be set by style when it creates its projection instance.\n        // When this happens, the new transform will inherit all properties of this temporary transform.\n        this._transform = createMercatorTransform();\n        this.cameraHelper = new MercatorCameraHelper();\n        if (options.minZoom !== undefined) {\n            this._transform.setMinZoom(options.minZoom);\n        }\n        if (options.maxZoom !== undefined) {\n            this._transform.setMaxZoom(options.maxZoom);\n        }\n        if (options.minPitch !== undefined) {\n            this._transform.setMinPitch(options.minPitch);\n        }\n        if (options.maxPitch !== undefined) {\n            this._transform.setMaxPitch(options.maxPitch);\n        }\n        if (options.renderWorldCopies !== undefined) {\n            this._transform.setRenderWorldCopies(options.renderWorldCopies);\n        }\n        if (options.transformConstrain !== null) {\n            this._transform.setConstrainOverride(options.transformConstrain);\n        }\n        this._bearingSnap = options.bearingSnap;\n        this._zoomSnap = options.zoomSnap;\n        this.terrain = options.terrain;\n        this._centerClampedToGround = options.centerClampedToGround ?? true;\n        this.transformCameraUpdate = options.transformCameraUpdate ?? null;\n        this._stopHandlers = options.stopHandlers ?? (() => {});\n        this._scheduler = new CameraMovementScheduler({\n            requestRenderFrame: options.requestRenderFrame,\n            cancelRenderFrame: options.cancelRenderFrame\n        });\n        this._scheduler.setEventedParent(this);\n\n        this.on('moveend', () => {\n            if (!this._scheduler.isMoving()) delete this._requestedCameraState;\n        });\n    }\n\n    /**\n     * @internal\n     * Hands the camera the map's terrain, or null when the map has none, and brings the center elevation up to date\n     * with it, see {@link Camera.applyTerrainChange}. A hold waits again when the terrain changes to one without DEM\n     * data under the center, see {@link ElevationHold.take}.\n     */\n    setTerrain(terrain: Terrain): void {\n        this.terrain = terrain;\n        if (terrain) this._elevationHold?.noteTerrainChange();\n        this.applyTerrainChange();\n    }\n\n    migrateProjection(newTransform: ITransform, newCameraHelper: ICameraHelper): void {\n        newTransform.apply(this.transform, true);\n        this._transform = newTransform;\n        this.cameraHelper = newCameraHelper;\n        if (this._requestedCameraState) {\n            // The requested camera state is a transform of the old projection, so it has to be\n            // moved onto the new one as well, otherwise the camera keeps reading a transform\n            // that the new camera helper cannot use.\n            const requestedCameraState = newTransform.clone();\n            requestedCameraState.apply(this._requestedCameraState, true);\n            this._requestedCameraState = requestedCameraState;\n        }\n    }\n\n    /**\n     * @internal\n     * Resizes the transform, and the requested camera state of a movement that is running, to the map's size.\n     */\n    resize(width: number, height: number, constrainTransform: boolean): void {\n        this._transform.resize(width, height, constrainTransform);\n        this._requestedCameraState?.resize(width, height, constrainTransform);\n    }\n\n    /**\n     * @internal\n     * Prepares the transform for the next frame.\n     * @param transition - how far the style's projection is between mercator, at 0, and globe, at 1\n     */\n    prepareNextFrame(transition: number): void {\n        this._transform.setTransitionState(transition);\n    }\n\n    getCenter(): LngLat { return new LngLat(this.transform.center.lng, this.transform.center.lat); }\n\n    setCenter(center: LngLatLike, eventData?: Record<string, unknown>): this {\n        return this.jumpTo({center}, eventData);\n    }\n\n    getCenterElevation(): number { return this.transform.elevation; }\n\n    setCenterElevation(elevation: number, eventData?: any): this {\n        this.jumpTo({elevation}, eventData);\n        return this;\n    }\n\n    getCenterClampedToGround(): boolean { return this._centerClampedToGround; }\n\n    setCenterClampedToGround(centerClampedToGround: boolean): void {\n        this._centerClampedToGround = centerClampedToGround;\n    }\n\n    panBy(offset: PointLike, options?: EaseToOptions, eventData?: any): this {\n        offset = Point.convert(offset).mult(-1);\n        return this.panTo(this.transform.center, extend({offset}, options), eventData);\n    }\n\n    panTo(lnglat: LngLatLike, options?: EaseToOptions, eventData?: any): this {\n        return this.easeTo(extend({\n            center: lnglat\n        }, options), eventData);\n    }\n\n    getZoom(): number { return this.transform.zoom; }\n\n    setZoom(zoom: number, eventData?: any): this {\n        this.jumpTo({zoom}, eventData);\n        return this;\n    }\n\n    zoomTo(zoom: number, options?: EaseToOptions | null, eventData?: any): this {\n        return this.easeTo(extend({\n            zoom\n        }, options), eventData);\n    }\n\n    zoomIn(options?: AnimationOptions, eventData?: any): this {\n        this.zoomTo(evaluateZoomSnap(this.getZoom() + 1, this._zoomSnap), options, eventData);\n        return this;\n    }\n\n    zoomOut(options?: AnimationOptions, eventData?: any): this {\n        this.zoomTo(evaluateZoomSnap(this.getZoom() - 1, this._zoomSnap), options, eventData);\n        return this;\n    }\n\n    getVerticalFieldOfView(): number { return this.transform.fov; }\n\n    setVerticalFieldOfView(fov: number, eventData?: any): this {\n        if (fov != this.transform.fov) {\n            this.applyTransformChange(tr => tr.setFov(fov));\n            this.fire(new MapMovementEvent('movestart', eventData))\n                .fire(new MapMovementEvent('move', eventData))\n                .fire(new MapMovementEvent('moveend', eventData));\n        }\n        return this;\n    }\n\n    getBearing(): number { return this.transform.bearing; }\n\n    setZoomSnap(snap: number): this {\n        this._zoomSnap = snap;\n        return this;\n    }\n\n    getZoomSnap(): number {\n        return this._zoomSnap;\n    }\n\n    setBearing(bearing: number, eventData?: any): this {\n        this.jumpTo({bearing}, eventData);\n        return this;\n    }\n\n    getPadding(): PaddingOptions { return this.transform.padding; }\n\n    setPadding(padding: PaddingOptions, eventData?: any): this {\n        this.jumpTo({padding}, eventData);\n        return this;\n    }\n\n    rotateTo(bearing: number, options?: EaseToOptions, eventData?: any): this {\n        return this.easeTo(extend({\n            bearing\n        }, options), eventData);\n    }\n\n    resetNorth(options?: AnimationOptions, eventData?: any): this {\n        this.rotateTo(0, extend({duration: 1000}, options), eventData);\n        return this;\n    }\n\n    resetNorthPitch(options?: AnimationOptions, eventData?: any): this {\n        this.easeTo(extend({\n            bearing: 0,\n            pitch: 0,\n            roll: 0,\n            duration: 1000\n        }, options), eventData);\n        return this;\n    }\n\n    snapToNorth(options?: AnimationOptions, eventData?: any): this {\n        if (Math.abs(this.getBearing()) < this._bearingSnap) {\n            return this.resetNorth(options, eventData);\n        }\n        return this;\n    }\n\n    getPitch(): number { return this.transform.pitch; }\n\n    setPitch(pitch: number, eventData?: any): this {\n        this.jumpTo({pitch}, eventData);\n        return this;\n    }\n\n    getRoll(): number { return this.transform.roll; }\n\n    setRoll(roll: number, eventData?: any): this {\n        this.jumpTo({roll}, eventData);\n        return this;\n    }\n\n    /**\n     * Returns {@link JumpToOptions} so the result can carry `padding` when `absolutePadding` is set.\n     * Once that is the default, `padding` can move onto {@link CameraOptions} and this can return it.\n     */\n    cameraForBounds(bounds: LngLatBoundsLike, options?: CameraForBoundsOptions): JumpToOptions | undefined {\n        bounds = LngLatBounds.convert(bounds).adjustAntiMeridian();\n        const bearing = options?.bearing || 0;\n\n        return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options);\n    }\n\n    /**\n     * @internal\n     * Calculate the center of these two points in the viewport and use\n     * the highest zoom level up to and including {@link Map.getMaxZoom} that fits\n     * the AABB defined by these points in the viewport at the specified bearing.\n     * @param p0 - First point\n     * @param p1 - Second point\n     * @param bearing - Desired map bearing at end of animation, in degrees\n     * @param options - the camera options\n     * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`,\n     *      plus `padding` when `absolutePadding` is set.\n     *      If map is unable to fit, method will warn and return undefined.\n     * @example\n     * ```ts\n     * let p0 = [-79, 43];\n     * let p1 = [-73, 45];\n     * let bearing = 90;\n     * let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, {\n     *   padding: {top: 10, bottom:25, left: 15, right: 5}\n     * });\n     * ```\n     */\n    _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraForBoundsOptions): JumpToOptions | undefined {\n        const defaultPadding = {\n            top: 0,\n            bottom: 0,\n            right: 0,\n            left: 0\n        };\n        options = extend({\n            padding: defaultPadding,\n            offset: [0, 0],\n            maxZoom: this.transform.maxZoom\n        }, options);\n\n        if (typeof options.padding === 'number') {\n            const p = options.padding;\n            options.padding = {\n                top: p,\n                bottom: p,\n                right: p,\n                left: p\n            };\n        }\n\n        const padding = extend(defaultPadding, options.padding) as PaddingOptions;\n        options.padding = padding;\n        const tr = this.transform;\n        const bounds = new LngLatBounds(p0, p1);\n\n        const noPadding = {top: 0, bottom: 0, right: 0, left: 0};\n        const fitPadding = options.absolutePadding ? noPadding : padding;\n        const mapPadding = options.absolutePadding ? padding : extend(noPadding, tr.padding) as PaddingOptions;\n\n        const result = this.cameraHelper.cameraForBoxAndBearing(options, fitPadding, mapPadding, bounds, bearing, tr);\n        if (!result) return undefined;\n        if (this._zoomSnap) {\n            result.zoom = evaluateZoomSnap(result.zoom, this._zoomSnap, -1);\n        }\n        return options.absolutePadding ? {...result, padding} : result;\n    }\n\n    fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions, eventData?: any): this {\n        return this._fitInternal(\n            this.cameraForBounds(bounds, options),\n            options,\n            eventData);\n    }\n\n    fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: FitBoundsOptions, eventData?: any): this {\n        return this._fitInternal(\n            this._cameraForBoxAndBearing(\n                this.transform.screenPointToLocation(Point.convert(p0)),\n                this.transform.screenPointToLocation(Point.convert(p1)),\n                bearing,\n                options),\n            options,\n            eventData);\n    }\n\n    _fitInternal(calculatedOptions?: JumpToOptions, options?: FitBoundsOptions, eventData?: any): this {\n        // cameraForBounds warns + returns undefined if unable to fit:\n        if (!calculatedOptions) return this;\n\n        options = extend(calculatedOptions, options);\n        if (options.absolutePadding) {\n            options.padding = calculatedOptions.padding;\n            delete options.absolutePadding;\n        } else {\n            // Explicitly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly.\n            delete options.padding;\n        }\n\n        return options.linear ?\n            this.easeTo(options, eventData) :\n            this.flyTo(options, eventData);\n    }\n\n    jumpTo(options: JumpToOptions, eventData?: any): this {\n        this._scheduler.interrupt();\n\n        if (options.zoom !== undefined && this._zoomSnap) {\n            options.zoom = evaluateZoomSnap(options.zoom, this._zoomSnap);\n        }\n\n        const tr = this.getTransformForUpdate();\n        let bearingChanged = false,\n            pitchChanged = false;\n        let rollChanged = false;\n\n        const oldZoom = tr.zoom;\n        if (this.terrain && this.getCenterClampedToGround()) {\n            const {elevation, demState} = this.terrain.getElevationAndDEMStateForLngLat(options.center ? LngLat.convert(options.center) : tr.center, tr.tileZoom);\n            if (demState !== 'loading') tr.setElevation(elevation);\n        }\n        this.cameraHelper.handleJumpToCenterZoom(tr, options);\n\n        const zoomChanged = tr.zoom !== oldZoom;\n\n        if (options.elevation !== undefined && tr.elevation !== +options.elevation) {\n            tr.setElevation(+options.elevation);\n        }\n\n        if (options.bearing !== undefined && tr.bearing !== +options.bearing) {\n            bearingChanged = true;\n            tr.setBearing(+options.bearing);\n        }\n\n        if (options.pitch !== undefined && tr.pitch !== +options.pitch) {\n            pitchChanged = true;\n            tr.setPitch(+options.pitch);\n        }\n\n        if (options.roll !== undefined && tr.roll !== +options.roll) {\n            rollChanged = true;\n            tr.setRoll(+options.roll);\n        }\n\n        if (options.padding != null && !tr.isPaddingEqual(options.padding)) {\n            tr.setPadding(options.padding);\n        }\n        this.applyUpdatedTransform(tr);\n\n        const events = [\n            new MapMovementEvent('movestart', eventData),\n            new MapMovementEvent('move', eventData)\n        ];\n\n        if (zoomChanged) {\n            events.push(\n                new MapMovementEvent('zoomstart', eventData),\n                new MapMovementEvent('zoom', eventData),\n                new MapMovementEvent('zoomend', eventData));\n        }\n\n        if (bearingChanged) {\n            events.push(\n                new MapMovementEvent('rotatestart', eventData),\n                new MapMovementEvent('rotate', eventData),\n                new MapMovementEvent('rotateend', eventData));\n        }\n\n        if (pitchChanged) {\n            events.push(\n                new MapMovementEvent('pitchstart', eventData),\n                new MapMovementEvent('pitch', eventData),\n                new MapMovementEvent('pitchend', eventData));\n        }\n\n        if (rollChanged) {\n            events.push(\n                new MapMovementEvent('rollstart', eventData),\n                new MapMovementEvent('roll', eventData),\n                new MapMovementEvent('rollend', eventData));\n        }\n\n        events.push(new MapMovementEvent('moveend', eventData));\n        this._scheduler.fireAfterQueued(events);\n        return this;\n    }\n\n    /**\n     * Calculates camera options for moving a geographic anchor to a screen point without\n     * changing this camera.\n     */\n    calculateAnchoredCameraOptions(options: AnchoredCameraOptions): CameraOptions {\n        const tr = this.transform.clone();\n        const anchor = LngLat.convert(options.anchorLocation);\n        const target = Point.convert(options.anchorScreenPoint);\n        const deltas: MapControlsDeltas = {\n            panDelta: target.sub(this.transform.locationToScreenPoint(anchor, this.terrain)),\n            zoomDelta: options.zoom === undefined ? 0 : options.zoom - tr.zoom,\n            bearingDelta: 0,\n            pitchDelta: 0,\n            rollDelta: 0,\n            around: target,\n            aroundElevation: this.terrain?.getElevationForLngLat(anchor, tr.tileZoom)\n        };\n        this.cameraHelper.handleMapControlsRollPitchBearingZoom(deltas, tr);\n        this.cameraHelper.handleMapControlsPan(deltas, tr, anchor);\n\n        return {\n            center: tr.center,\n            zoom: tr.zoom\n        };\n    }\n\n    calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat: LngLatLike, cameraAlt: number, bearing: number, pitch: number, roll?: number): CameraOptions {\n        const centerInfo = this.transform.calculateCenterFromCameraLngLatAlt(cameraLngLat, cameraAlt, bearing, pitch);\n        return {\n            center: centerInfo.center,\n            elevation: centerInfo.elevation,\n            zoom: centerInfo.zoom,\n            bearing,\n            pitch,\n            roll\n        };\n    }\n\n    easeTo(options: EaseToOptions, eventData?: any): this {\n        if (!this._scheduler.isContinuedBy(options.easeId)) this._scheduler.interrupt();\n\n        options = extend({\n            offset: [0, 0],\n            duration: 500,\n            easing: defaultEasing\n        }, options);\n\n        if (options.zoom !== undefined && this._zoomSnap) {\n            options.zoom = evaluateZoomSnap(options.zoom, this._zoomSnap);\n        }\n\n        if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) {\n            options.duration = 0;\n        }\n\n        const tr = this.getTransformForUpdate();\n        const startBearing = this.getBearing(),\n            startPitch = tr.pitch,\n            startRoll = tr.roll,\n            bearing = options.bearing !== undefined ? this._normalizeBearing(options.bearing, startBearing) : startBearing,\n            pitch = options.pitch !== undefined ? +options.pitch : startPitch,\n            roll = options.roll !== undefined ? this._normalizeBearing(options.roll, startRoll) : startRoll,\n            padding = (options.padding !== undefined ? options.padding : tr.padding) as PaddingOptions;\n        const offsetAsPoint = Point.convert(options.offset);\n\n        let around, aroundPoint;\n\n        if (options.around) {\n            around = LngLat.convert(options.around);\n            aroundPoint = tr.locationToScreenPoint(around);\n        }\n\n        const easeHandler = this.cameraHelper.handleEaseTo(tr, {\n            bearing,\n            pitch,\n            roll,\n            padding,\n            around,\n            aroundPoint,\n            offsetAsPoint,\n            offset: options.offset,\n            zoom: options.zoom,\n            center: options.center,\n        });\n\n        const elevationHandler = this._createElevationEase(tr, easeHandler.elevationCenter, options.freezeElevation);\n\n        this._scheduler.scheduleSegment({\n            onFrame: (k) => {\n                easeHandler.easeFunc(k);\n                elevationHandler.easeFunc(k);\n                this.applyUpdatedTransform(tr);\n            },\n            onFinish: () => this._finishAnimationElevation(options.freezeElevation)\n        }, {\n            duration: options.duration,\n            easing: options.easing,\n            axes: {zoom: easeHandler.isZooming, rotate: startBearing !== bearing, pitch: pitch !== startPitch, roll: roll !== startRoll},\n            eventData,\n            easeId: options.easeId,\n            movestartFired: options.noMoveStart\n        });\n\n        return this;\n    }\n\n    /**\n     * Creates the handler of the center elevation for an animation, whose `easeFunc` each frame calls like the camera\n     * helper's, and starts the animation's hold on the elevation when it has one.\n     *\n     * Over terrain the animation either holds the center elevation, with `freezeElevation`, or eases it to the\n     * terrain under the center it ends on. Terrain that is added while an easing animation runs is eased to from the\n     * center the animation has reached by then.\n     * @param tr - the transform the animation edits\n     * @param center - the map center the animation ends on\n     * @param freeze - whether the animation holds the center elevation instead of easing it\n     */\n    private _createElevationEase(tr: ITransform, center: LngLat, freeze: boolean): {easeFunc: (k: number) => void} {\n        if (freeze) {\n            if (this.terrain) this.holdElevation(tr, 'animation');\n            return {easeFunc: () => {}};\n        }\n\n        let easing = this.terrain ? this._startElevationEasing(center, tr) : null;\n        return {\n            easeFunc: (k) => {\n                if (!this.terrain) return;\n                easing ??= this._startElevationEasing(tr.center, tr);\n                easing(k);\n            }\n        };\n    }\n\n    /**\n     * Starts easing the center elevation towards the terrain under `center` and returns what each frame of the\n     * animation does to it. Until the animation ends, this keeps the rendered frames from putting the center onto the\n     * terrain, see {@link Camera.clampCenterToGround}.\n     *\n     * The ease follows a straight line from the elevation it starts at to the terrain elevation under `center`. DEM\n     * tiles that land during the animation move that target, and the line is then turned about the elevation reached\n     * so far, so the camera carries on towards the new target without a jump. While the DEM data under `center` is\n     * still loading, the target stays where it is. A center that is not clamped to the ground keeps its elevation.\n     * @param center - the map center the animation ends on\n     * @param tr - the transform the animation edits\n     */\n    private _startElevationEasing(center: LngLat, tr: ITransform): (k: number) => void {\n        this.elevationFreeze = true;\n        const atStart = this.terrain.getElevationAndDEMStateForLngLat(center, tr.tileZoom);\n        let start = tr.elevation;\n        let target = atStart.demState === 'loading' ? tr.elevation : atStart.elevation;\n\n        return (k) => {\n            tr.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(center, tr.tileZoom));\n            const {elevation, demState} = this.terrain.getElevationAndDEMStateForLngLat(center, tr.tileZoom);\n            if (k < 1 && demState !== 'loading' && elevation !== target) {\n                const reached = interpolates.number(start, target, k);\n                const slope = (elevation - reached) / (1 - k);\n                start = reached - k * slope;\n                target = elevation;\n            }\n            if (this.getCenterClampedToGround()) tr.setElevation(interpolates.number(start, target, k));\n        };\n    }\n\n    /**\n     * @internal\n     * Holds the center elevation for a gesture or an animation with `freezeElevation`: the frames leave it alone and\n     * the end puts the center back onto the terrain. A hold that starts without DEM data under a center clamped to\n     * the ground waits for it, see {@link ElevationHold.take}.\n     * @param tr - the transform the gesture or animation edits, read for the center the hold starts at\n     * @param holder - who holds it\n     */\n    holdElevation(tr: ITransform, holder: ElevationHolder): void {\n        this.elevationFreeze = true;\n        const startedWithoutDem = !!this.terrain && this.getCenterClampedToGround() && this.terrain.getElevationAndDEMStateForLngLat(tr.center, tr.tileZoom).demState !== 'loaded';\n        const terrainAboveMaxZoomForCenter = this.terrain ? this._terrainHeightAboveMaxZoomForCenter(tr) : undefined;\n        this._elevationHold = new ElevationHold(holder, startedWithoutDem, terrainAboveMaxZoomForCenter !== undefined && terrainAboveMaxZoomForCenter <= MAX_ZOOM_FOR_CENTER_TOLERANCE_M);\n    }\n\n    /**\n     * @internal\n     * Ends a hold on the center elevation, and any wait for DEM data with it, see {@link Camera.holdElevation}.\n     */\n    releaseElevation(): boolean {\n        const tookDem = this._elevationHold?.tookDem ?? false;\n        this.elevationFreeze = false;\n        this._elevationHold = null;\n        return tookDem;\n    }\n\n    /**\n     * @internal\n     * Puts the center back onto the terrain at the end of a hold, re-solving zoom and center with the camera in place.\n     * After a hold that took DEM data, a center over a tile without its own DEM data yet keeps the zoom and takes the\n     * drawn elevation instead, with the camera check keeping the camera out of the terrain.\n     * @param tr - the transform the end writes\n     * @param terrain - the terrain the gesture or animation ends over\n     * @param tookDem - whether the hold carried an elevation it took from DEM data, see {@link Camera.releaseElevation}\n     */\n    putCenterBackOnTerrain(tr: ITransform, terrain: Terrain, tookDem: boolean): void {\n        if (tookDem && terrain.getDrawnElevationForLngLat(tr.center, true) === undefined) {\n            tr.setElevation(terrain.getElevationForLngLat(tr.center, tr.tileZoom));\n            const corrected = this._raiseCameraByPitchAndZoom(tr);\n            if (corrected !== tr) tr.apply(corrected, false);\n        } else {\n            tr.recalculateZoomAndCenter(terrain);\n        }\n    }\n\n    /**\n     * @internal\n     * Lets a hold on the center elevation take DEM data that landed, see {@link ElevationHold.take}.\n     * @param tr - the transform the hold's gesture or animation edits\n     * @returns whether it changed the elevation\n     */\n    _takeLandedElevation(tr: ITransform): boolean {\n        if (!this._elevationHold || !this.terrain || !this.getCenterClampedToGround()) return false;\n        return this._elevationHold.take(tr, this.terrain);\n    }\n\n    /**\n     * @internal\n     * Applies a change of the terrain under the center (terrain set or removed, a DEM tile landed): at rest the\n     * camera moves with the center's elevation unless its DEM data is still loading, as on every rendered frame; a\n     * hold keeps the camera where the user put it unless it waits for DEM data. A gesture's hold takes here, on the\n     * requested camera state its frames read; an animation's takes on its next frame, on the transform it edits,\n     * see {@link ElevationHold.take}.\n     */\n    applyTerrainChange(): void {\n        if (this.elevationFreeze) {\n            const tr = this._requestedCameraState;\n            if (this._elevationHold?.holder === 'gesture' && tr && this._takeLandedElevation(tr)) this.applyUpdatedTransform(tr);\n            return;\n        }\n        this.clampCenterToGround(this.terrain);\n    }\n\n    /**\n     * @internal\n     * Tells the transform the lowest elevation of the tile under the center and, with `centerClampedToGround` set, puts\n     * the center onto the terrain, or onto sea level without terrain.\n     */\n    clampCenterToGround(terrain: Terrain | null): void {\n        const tr = this._transform;\n        tr.setMinElevationForCurrentTile(terrain ? terrain.getMinTileElevationForLngLatZoom(tr.center, tr.tileZoom) : 0);\n        if (!this.getCenterClampedToGround()) return;\n        if (!terrain) {\n            tr.setElevation(0);\n            return;\n        }\n        if (this.elevationFreeze) return;\n        const {elevation, demState} = terrain.getElevationAndDEMStateForLngLat(tr.center, tr.tileZoom);\n        if (demState !== 'loading') tr.setElevation(elevation);\n    }\n\n    /**\n     * @internal\n     * Called when the camera is about to be manipulated.\n     * If `transformCameraUpdate` is specified or terrain is enabled, a copy of\n     * the current transform is created to track the accumulated changes.\n     * This underlying transform represents the \"desired state\" proposed by input handlers / animations / UI controls.\n     * It may differ from the state used for rendering (`this.transform`).\n     * @returns Transform to apply changes to\n     */\n    getTransformForUpdate(): ITransform {\n        if (!this.transformCameraUpdate && !this.terrain) return this._transform;\n\n        this._requestedCameraState ||= this.transform.clone();\n        return this._requestedCameraState;\n    }\n\n    /**\n     * @internal\n     * Keeps the camera above the terrain for a camera update. While a gesture or an animation holds the center elevation\n     * over mercator terrain, below a pitch of 90 degrees with the center clamped to the ground, the held elevation is\n     * lifted on the given transform just far enough that the drawn terrain stays below where the center would sit at\n     * maxZoom once the hold keeps it there, see {@link ElevationHold.keepsTerrainBelowMaxZoomForCenter}, so the end does\n     * not move the camera back. A gesture's lift also keeps the camera and its near clipping plane above the terrain,\n     * so its pitch and zoom stay where the user puts them; the camera of an animation, and of any camera update without\n     * a hold, is kept above the terrain by {@link Camera._raiseCameraByPitchAndZoom} instead. The lift is lowered again\n     * as the terrain allows.\n     * @param tr - the transform the camera update edits\n     * @returns the transform to render: `tr`, or its corrected copy\n     */\n    _keepCameraAboveTerrain(tr: ITransform): ITransform {\n        const hold = this._elevationHold;\n        if (!this.terrain || !hold || tr.pitch >= 90 || !this.getCenterClampedToGround() || tr.getClippingPlane()) {\n            return this._raiseCameraByPitchAndZoom(tr);\n        }\n        const isGesture = hold.holder === 'gesture';\n        const lift = hold.lift && hold.lift.heldElevation + hold.lift.height === tr.elevation ? hold.lift : {heldElevation: tr.elevation, height: 0};\n        const terrainAboveMaxZoomForCenter = this._terrainHeightAboveMaxZoomForCenter(tr);\n        if (terrainAboveMaxZoomForCenter !== undefined && terrainAboveMaxZoomForCenter <= MAX_ZOOM_FOR_CENTER_TOLERANCE_M) {\n            hold.keepsTerrainBelowMaxZoomForCenter = true;\n        }\n        const heightForMaxZoom = hold.keepsTerrainBelowMaxZoomForCenter && terrainAboveMaxZoomForCenter !== undefined ? terrainAboveMaxZoomForCenter : -Infinity;\n        const heightForCamera = isGesture ? this._terrainHeightAboveCamera(tr) : -Infinity;\n        const height = Math.max(0, Math.max(heightForCamera, heightForMaxZoom) + lift.height);\n        if (height !== lift.height) {\n            tr.setElevation(lift.heldElevation + height);\n        }\n        hold.lift = height > 0 ? {heldElevation: lift.heldElevation, height} : null;\n        return isGesture ? tr : this._raiseCameraByPitchAndZoom(tr);\n    }\n\n    /**\n     * @internal\n     * Where the camera is inside the terrain, re-solves pitch and zoom on a copy of the transform so the camera sits\n     * above it at the same ground position, still looking at the same center at the same elevation, and the transform\n     * the update edits keeps what it asked for; over mercator terrain high enough that its near clipping plane clears the terrain too. Without\n     * terrain the camera is kept above sea level, which only needs checking where the center elevation is negative or\n     * the pitch passes 90 degrees. On a globe the camera is left where it is.\n     * @param tr - the transform the camera update edits\n     * @returns `tr` while the camera is clear, else the corrected copy\n     */\n    _raiseCameraByPitchAndZoom(tr: ITransform): ITransform {\n        if ((!this.terrain && tr.elevation >= 0 && tr.pitch <= 90) || tr.getClippingPlane()) {\n            return tr;\n        }\n        const cameraLngLat = tr.getCameraLngLat();\n        let height = this.terrain ? this._terrainHeightAboveCamera(tr) : -tr.getCameraAltitude();\n        if (height <= 0) {\n            return tr;\n        }\n        const corrected = tr.clone();\n        for (let pass = 0; pass < MAX_CAMERA_RAISES && height > 0; pass++) {\n            const {zoom, pitch} = corrected.calculateCameraOptionsFromTo(cameraLngLat, corrected.getCameraAltitude() + height, corrected.center, corrected.elevation);\n            corrected.setZoom(zoom);\n            corrected.setPitch(pitch);\n            height = this.terrain ? this._terrainHeightAboveCamera(corrected) : -corrected.getCameraAltitude();\n        }\n        return corrected;\n    }\n\n    /**\n     * @internal\n     * How far the terrain reaches above the camera, or the drawn terrain above one of nine points spread over its\n     * near clipping plane, in meters, whichever is more; zero or less while all are clear. The renderer drops whatever\n     * is nearer than that plane, so terrain reaching above it would show as a hole into the ground. The points are a\n     * 3 by 3 grid weighted bilinearly over the plane's four corners, the frustum's first four points in order around\n     * the plane. The plane is checked on mercator only, where the frustum is in mercator coordinates.\n     * @param tr - the transform whose camera is checked\n     */\n    _terrainHeightAboveCamera(tr: ITransform): number {\n        let height = this.terrain.getElevationForLngLat(tr.getCameraLngLat(), tr.tileZoom) - tr.getCameraAltitude();\n        const index = tr.getClippingPlane() ? null : this.terrain.getCoverageIndex();\n        if (!index) {\n            return height;\n        }\n        const [p0, p1, p2, p3] = tr.getCameraFrustum().points;\n        for (let row = 0; row <= 2; row++) {\n            const v = row / 2;\n            for (let column = 0; column <= 2; column++) {\n                const u = column / 2;\n                const w0 = (1 - u) * (1 - v), w1 = u * (1 - v), w2 = u * v, w3 = (1 - u) * v;\n                const x = w0 * p0[0] + w1 * p1[0] + w2 * p2[0] + w3 * p3[0];\n                const y = w0 * p0[1] + w1 * p1[1] + w2 * p2[1] + w3 * p3[1];\n                const altitude = w0 * p0[2] + w1 * p1[2] + w2 * p2[2] + w3 * p3[2];\n                const sample = sampleAt(index, this.terrain.exaggeration, x, y, tr.worldCoordinateHelper.wraps);\n                if (sample.covered) {\n                    height = Math.max(height, sample.elevation - altitude);\n                }\n            }\n        }\n        return height;\n    }\n\n    /**\n     * @internal\n     * How far the drawn terrain rises above the point on the center ray where the center would sit at maxZoom, with the\n     * camera where it is, in meters; zero or less while the terrain is below that point, undefined where no terrain is\n     * drawn under it. A hold's end puts the center onto the drawn terrain the center ray meets, with the camera where it\n     * is, see {@link Camera.putCenterBackOnTerrain}; terrain above that point puts it nearer than maxZoom allows, and\n     * `setZoom` clamps the zoom it needs by moving the camera back.\n     * @param tr - the transform whose center ray is checked\n     */\n    _terrainHeightAboveMaxZoomForCenter(tr: ITransform): number | undefined {\n        const index = this.terrain.getCoverageIndex();\n        if (!index) {\n            return undefined;\n        }\n        const worldCoordinateHelper = tr.worldCoordinateHelper;\n        const cameraLngLat = tr.getCameraLngLat();\n        const camera = worldCoordinateHelper.worldFromLngLat(cameraLngLat.lng, cameraLngLat.lat);\n        const center = worldCoordinateHelper.worldFromLngLat(tr.center.lng, tr.center.lat);\n        const distanceFractionAtMaxZoom = zoomScale(tr.zoom - tr.maxZoom);\n        const sample = sampleAt(index, this.terrain.exaggeration, lerp(camera.x, center.x, distanceFractionAtMaxZoom), lerp(camera.y, center.y, distanceFractionAtMaxZoom), worldCoordinateHelper.wraps);\n        return sample.covered ? sample.elevation - lerp(tr.getCameraAltitude(), tr.elevation, distanceFractionAtMaxZoom) : undefined;\n    }\n\n    /**\n     * @internal\n     * Moves the center a zoom gesture holds onto the terrain the camera looks at and draws, with the camera where it\n     * is, so a zoom toward rising terrain slows down before it instead of running into it. Farther terrain is followed\n     * only by less than the frame zooms in, so the zoom keeps going in and speeds up gradually; a center ray that slips\n     * over a crest onto terrain far behind it, and terrain so near that the zoom passes maxZoom, which would move the\n     * camera back, are left to the gesture's end, as is everything with the center not clamped to the ground, and a\n     * globe.\n     * @param tr - the requested camera state\n     * @param zoomDelta - how far the frame zooms in\n     */\n    moveCenterOntoTerrain(tr: ITransform, zoomDelta: number): void {\n        if (!this.terrain || !this.getCenterClampedToGround() || tr.getClippingPlane()) {\n            return;\n        }\n        const {center, elevation, zoom} = tr;\n        tr.recalculateZoomAndCenter(this.terrain);\n        const keepsZoomingIn = tr.zoom > zoom - zoomDelta && tr.zoom < tr.maxZoom;\n        if (!keepsZoomingIn || Math.abs(this.terrain.getElevationForLngLat(tr.center, tr.tileZoom) - tr.elevation) >= MAX_CENTER_OFF_TERRAIN_M) {\n            tr.setZoom(zoom);\n            tr.setCenter(center);\n            tr.setElevation(elevation);\n        }\n    }\n\n    /**\n     * @internal\n     * Picks the point a drag turns the camera around, the terrain under the point, or the ground without terrain there,\n     * and the center for a point in the sky. On the globe, which holds no location at an elevation, a pivot on terrain\n     * is held by the planet's surface under it.\n     * @param tr - the camera state the drag starts from\n     * @param point - the screen point the drag starts at\n     */\n    captureRotationPivot(tr: IReadonlyTransform, point: Point): RotationPivot {\n        if (!isBelowHorizon(tr, point)) {\n            return {point: tr.centerPoint, location: tr.center, distance: distanceFromCamera(tr, tr.center)};\n        }\n        const hit = this.terrain ? tr.screenTerrainPointToMercatorCoordinate(point, this.terrain) : null;\n        const location = hit ? hit.toLngLat() : tr.screenPointToLocation(point);\n        if (hit && this.cameraHelper.useGlobeControls) {\n            return {point: tr.locationToScreenPoint(location), location, distance: distanceFromCamera(tr, location)};\n        }\n        return {point, location, elevation: hit?.z, distance: distanceFromCamera(tr, location, hit?.z)};\n    }\n\n    /**\n     * @internal\n     * Turns the camera around a pivot, keeping only the change of bearing where the tilt would bring the pivot close to\n     * the horizon. A pivot at the center turns the camera in place, without that limit.\n     * @param tr - the requested camera state\n     * @param pivot - the pivot, see {@link Camera.captureRotationPivot}\n     * @param deltas - the frame's change of bearing, pitch and roll\n     * @returns false where the pivot cannot be held, as next to a pole of the globe, which turns the camera in place\n     */\n    orbitRotationPivot(tr: ITransform, pivot: RotationPivot, deltas: MapControlsDeltas): boolean {\n        if (pivot.point.equals(tr.centerPoint)) {\n            this.cameraHelper.handleMapControlsRollPitchBearingZoom(deltas, tr);\n            return true;\n        }\n        const camera = this._turnAroundPivot(tr, pivot, deltas) ?? this._turnAroundPivot(tr, pivot, {...deltas, pitchDelta: 0, rollDelta: 0});\n        if (!camera) {\n            this.cameraHelper.handleMapControlsRollPitchBearingZoom(deltas, tr);\n            return false;\n        }\n        tr.apply(camera, false);\n        return true;\n    }\n\n    /**\n     * @internal\n     * Returns the camera turned around the pivot, or null where that would make it look up, bring the pivot close to the\n     * horizon or lose it.\n     */\n    _turnAroundPivot(start: ITransform, pivot: RotationPivot, deltas: MapControlsDeltas): ITransform | null {\n        const camera = start.clone();\n        this.cameraHelper.handleMapControlsRollPitchBearingZoom(deltas, camera);\n        if (camera.pitch >= 90 || !isBelowHorizon(camera, pivot.point)) return null;\n        return holdPivot(camera, pivot) && isAtScreenPoint(camera, pivot) ? camera : null;\n    }\n\n    /**\n     * @internal\n     * Called after the camera is done being manipulated. A hold on the center elevation takes DEM data that landed, see\n     * {@link ElevationHold.take}; then the camera is kept above the terrain, see {@link Camera._keepCameraAboveTerrain};\n     * `transformCameraUpdate`, if present, proposes its changes on a copy, and the \"approved\" result is applied to the\n     * rendered transform.\n     * @param tr - the requested camera end state\n     */\n    applyUpdatedTransform(tr: ITransform): void {\n        this._takeLandedElevation(tr);\n        const corrected = this._keepCameraAboveTerrain(tr);\n        if (!this.transformCameraUpdate) {\n            if (corrected !== this._transform) this._transform.apply(corrected, false);\n            return;\n        }\n        const nextTransform = corrected.clone();\n        const {\n            center,\n            zoom,\n            roll,\n            pitch,\n            bearing,\n            elevation\n        } = this.transformCameraUpdate(nextTransform);\n        if (center) nextTransform.setCenter(center);\n        if (elevation !== undefined) nextTransform.setElevation(elevation);\n        if (zoom !== undefined) nextTransform.setZoom(zoom);\n        if (roll !== undefined) nextTransform.setRoll(roll);\n        if (pitch !== undefined) nextTransform.setPitch(pitch);\n        if (bearing !== undefined) nextTransform.setBearing(bearing);\n        this._transform.apply(elevation === undefined ? nextTransform : this._raiseCameraByPitchAndZoom(nextTransform), false);\n    }\n\n    /**\n     * @internal\n     * Applies a change that is not itself a movement, such as new bounds, limits or field of view, the way\n     * any camera update is applied. A requested camera state created only for this change is dropped again,\n     * so a later movement cannot restore the old values.\n     */\n    applyTransformChange(change: (tr: ITransform) => void): void {\n        const hadRequestedCameraState = this._requestedCameraState !== undefined;\n        const tr = this.getTransformForUpdate();\n        change(tr);\n        this.applyUpdatedTransform(tr);\n        if (!hadRequestedCameraState) {\n            delete this._requestedCameraState;\n        }\n    }\n\n    /**\n     * Ends an animation's work on the center elevation, whether it ran to the end or was interrupted.\n     * @param freezeElevation - whether the animation held the center elevation; its end then takes DEM data that\n     * landed since its last frame and puts the center back onto the terrain, see {@link Camera.putCenterBackOnTerrain}\n     */\n    private _finishAnimationElevation(freezeElevation: boolean = false): void {\n        this._takeLandedElevation(this._transform);\n        const tookDem = this.releaseElevation();\n        if (this.terrain && freezeElevation && this.getCenterClampedToGround()) {\n            this.putCenterBackOnTerrain(this._transform, this.terrain, tookDem);\n        }\n    }\n\n    /*\n     * This method implements an “optimal path” animation, as detailed in:\n     *\n     * Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS\n     * ’03. pp. 15–22. <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>.\n     *\n     * Where applicable, local variable documentation begins with the associated variable or\n     * function in van Wijk (2003).\n     */\n    flyTo(options: FlyToOptions, eventData?: any): this {\n        if (!options.essential && browser.prefersReducedMotion) {\n            return this.easeTo(options, eventData);\n        }\n\n        this._scheduler.interrupt();\n\n        options = extend({\n            offset: [0, 0],\n            speed: 1.2,\n            curve: 1.42,\n            easing: defaultEasing\n        }, options);\n\n        if (options.zoom !== undefined && this._zoomSnap) {\n            options.zoom = evaluateZoomSnap(options.zoom, this._zoomSnap);\n        }\n\n        const tr = this.getTransformForUpdate(),\n            startBearing = tr.bearing,\n            startPitch = tr.pitch,\n            startRoll = tr.roll,\n            startPadding = tr.padding;\n\n        const bearing = options.bearing !== undefined ? this._normalizeBearing(options.bearing, startBearing) : startBearing;\n        const pitch = options.pitch !== undefined ? +options.pitch : startPitch;\n        const roll = options.roll !== undefined ? this._normalizeBearing(options.roll, startRoll) : startRoll;\n        const padding = (options.padding !== undefined ? options.padding : tr.padding) as PaddingOptions;\n\n        const offsetAsPoint = Point.convert(options.offset);\n        let pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n        const locationAtOffset = tr.screenPointToLocation(pointAtOffset);\n\n        const flyToHandler = this.cameraHelper.handleFlyTo(tr, {\n            bearing,\n            pitch,\n            roll,\n            padding,\n            locationAtOffset,\n            offsetAsPoint,\n            center: options.center,\n            minZoom: options.minZoom,\n            zoom: options.zoom,\n        });\n\n        let rho = options.curve;\n\n        // w₀: Initial visible span, measured in pixels at the initial scale.\n        const w0 = Math.max(tr.width, tr.height);\n        // w₁: Final visible span, measured in pixels with respect to the initial scale.\n        const w1 = w0 / flyToHandler.scaleOfZoom;\n        // Length of the flight path as projected onto the ground plane, measured in pixels from\n        // the world image origin at the initial scale.\n        const u1 = flyToHandler.pixelPathLength;\n\n        // w<sub>m</sub>: Maximum visible span, measured in pixels with respect to the initial\n        // scale.\n        const wMax = w0 / flyToHandler.scaleOfMinZoom;\n        // Only reduce rho (limit zoom-out). If the natural arc stays within the minZoom\n        // boundary, preserve the default rho rather than forcing the arc deeper.\n        rho = Math.min(rho, Math.sqrt(wMax / u1 * 2));\n\n        // ρ²\n        const rho2 = rho * rho;\n\n        /**\n         * rᵢ: Returns the zoom-out factor at one end of the animation.\n         *\n         * @param descent - `true` for the descent, `false` for the ascent\n         */\n        function zoomOutFactor(descent: boolean) {\n            const b = (w1 * w1 - w0 * w0 + (descent ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (descent ? w1 : w0) * rho2 * u1);\n            return Math.log(Math.sqrt(b * b + 1) - b);\n        }\n\n        function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }\n        function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }\n        function tanh(n) { return sinh(n) / cosh(n); }\n\n        // r₀: Zoom-out factor during ascent.\n        const r0 = zoomOutFactor(false);\n\n        // w(s): Returns the visible span on the ground, measured in pixels with respect to the\n        // initial scale. Uses the current vertical field of view setting.\n        let w: (_: number) => number = function (s) {\n            return (cosh(r0) / cosh(r0 + rho * s));\n        };\n\n        // u(s): Returns the distance along the flight path as projected onto the ground plane,\n        // measured in pixels from the world image origin at the initial scale.\n        let u: (_: number) => number = function (s) {\n            return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1;\n        };\n\n        // S: Total length of the flight path, measured in ρ-screenfulls.\n        let S = (zoomOutFactor(true) - r0) / rho;\n\n        // When u₀ = u₁, the optimal path doesn’t require both ascent and descent.\n        if (Math.abs(u1) < 0.000002 || !isFinite(S)) {\n            // Perform a more or less instantaneous transition if the path is too short.\n            if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(options, eventData);\n\n            const k = w1 < w0 ? -1 : 1;\n            S = Math.abs(Math.log(w1 / w0)) / rho;\n\n            u = () => 0;\n            w = (s) => Math.exp(k * rho * s);\n        }\n\n        if (options.duration !== undefined) {\n            options.duration = +options.duration;\n        } else {\n            const V = options.screenSpeed !== undefined ? +options.screenSpeed / rho : +options.speed;\n            options.duration = 1000 * S / V;\n        }\n\n        if (options.maxDuration && options.duration > options.maxDuration) {\n            options.duration = 0;\n        }\n\n        const rotating = startBearing !== bearing;\n        const pitching = pitch !== startPitch;\n        const rolling = roll !== startRoll;\n        const paddingChanging = !tr.isPaddingEqual(padding);\n\n        const elevationHandler = this._createElevationEase(tr, flyToHandler.targetCenter, options.freezeElevation);\n\n        this._scheduler.scheduleSegment({\n            onFrame: (k) => {\n                // s: The distance traveled along the flight path, measured in ρ-screenfulls.\n                const s = k * S;\n                const scale = 1 / w(s);\n                const centerFactor = u(s);\n                if (rotating) tr.setBearing(interpolates.number(startBearing, bearing, k));\n                if (pitching) tr.setPitch(interpolates.number(startPitch, pitch, k));\n                if (rolling) tr.setRoll(interpolates.number(startRoll, roll, k));\n                if (paddingChanging) {\n                    tr.interpolatePadding(startPadding, padding, k);\n                    // When padding is being applied, Transform.centerPoint is changing continuously,\n                    // thus we need to recalculate offsetPoint every frame\n                    pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n                }\n\n                flyToHandler.easeFunc(k, scale, centerFactor, pointAtOffset);\n\n                elevationHandler.easeFunc(k);\n                this.applyUpdatedTransform(tr);\n            },\n            onFinish: () => this._finishAnimationElevation(options.freezeElevation)\n        }, {\n            duration: options.animate === false ? 0 : options.duration,\n            easing: options.easing,\n            axes: {zoom: true, rotate: rotating, pitch: pitching, roll: rolling},\n            eventData\n        });\n\n        return this;\n    }\n\n    /**\n     * Ends the running animation where it is, firing its end events.\n     * @param allowGestures - whether to let gestures in progress go on, which are stopped otherwise\n     */\n    stop(allowGestures?: boolean): this {\n        this._scheduler.interrupt();\n        if (!allowGestures) this._stopHandlers();\n        return this;\n    }\n\n    // convert bearing so that it's numerically close to the current one so that it interpolates properly\n    _normalizeBearing(bearing: number, currentBearing: number): number {\n        bearing = wrap(bearing, -180, 180);\n        const diff = Math.abs(bearing - currentBearing);\n        if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360;\n        if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360;\n        return bearing;\n    }\n\n    isMoving(): boolean {\n        return this._scheduler.isMoving();\n    }\n\n    isZooming(): boolean {\n        return this._scheduler.isMovingAxis('zoom');\n    }\n\n    isRotating(): boolean {\n        return this._scheduler.isMovingAxis('rotate');\n    }\n\n    isPitching(): boolean {\n        return this._scheduler.isMovingAxis('pitch');\n    }\n\n    isRolling(): boolean {\n        return this._scheduler.isMovingAxis('roll');\n    }\n}\n\n/**\n * Zooms and moves the camera so the pivot is at its screen point and distance, or as close to the distance as the zoom limits allow.\n * Returns false where no zoom gives the distance, which is where the camera would have to go below the ground.\n *\n * The distance grows with the span of the view, in a straight line on mercator and nearly so on the globe,\n * so the span is found with the secant method.\n */\nfunction holdPivot(tr: ITransform, pivot: RotationPivot): boolean {\n    let span = 1;\n    let distance = placePivot(tr, pivot);\n    let nextSpan = pivot.distance / distance;\n    for (let i = 0; i < MAX_PIVOT_ZOOM_CORRECTIONS && !isAtDistance(distance, pivot); i++) {\n        if (!Number.isFinite(nextSpan) || nextSpan <= 0) return false;\n        const zoom = tr.zoom;\n        tr.setZoom(zoom + scaleZoom(span / nextSpan));\n        const reachedSpan = span * zoomScale(zoom - tr.zoom);\n        if (reachedSpan === span) return true;\n        const reachedDistance = placePivot(tr, pivot);\n        nextSpan = reachedSpan + (pivot.distance - reachedDistance) * (reachedSpan - span) / (reachedDistance - distance);\n        span = reachedSpan;\n        distance = reachedDistance;\n    }\n    return isAtDistance(distance, pivot);\n}\n\n/** Moves the camera so the pivot is at its screen point, and returns the pivot's distance from the camera. */\nfunction placePivot(tr: ITransform, pivot: RotationPivot): number {\n    tr.setLocationAtPoint(pivot.location, pivot.point, pivot.elevation);\n    return distanceFromCamera(tr, pivot.location, pivot.elevation);\n}\n\nfunction isAtDistance(distance: number, pivot: RotationPivot): boolean {\n    return Math.abs(distance / pivot.distance - 1) < PIVOT_DISTANCE_TOLERANCE;\n}\n\n/** Whether the ground under the pivot's screen point is the pivot, which the edge of the map or a pole of the globe can prevent. A pivot on terrain is not checked. */\nfunction isAtScreenPoint(tr: IReadonlyTransform, pivot: RotationPivot): boolean {\n    if (pivot.elevation !== undefined) return true;\n    const offset = vec3.distance(positionOf(tr.screenPointToLocation(pivot.point), 0), positionOf(pivot.location, 0));\n    return offset < pivot.distance * PIVOT_POINT_TOLERANCE;\n}\n\nfunction isBelowHorizon(tr: IReadonlyTransform, point: Point): boolean {\n    return tr.isPointOnMapSurface(new Point(point.x, point.y - PIVOT_HORIZON_MARGIN_PX));\n}\n\n/** Returns the straight-line distance in meters from the camera to a location, at the center's elevation unless it has its own. */\nfunction distanceFromCamera(tr: IReadonlyTransform, location: LngLat, elevation: number = tr.elevation): number {\n    return vec3.distance(positionOf(tr.getCameraLngLat(), tr.getCameraAltitude()), positionOf(location, elevation));\n}\n\n/** Returns the position of a location in meters from the center of the earth. */\nfunction positionOf(location: LngLat, elevation: number): vec3 {\n    const position = angularCoordinatesToSurfaceVector(location);\n    return vec3.scale(position, position, earthRadius + elevation);\n}\n", "import {DOM} from '../../util/dom.ts';\n\nimport type {Map} from '../map.ts';\nimport type {ControlPosition, IControl} from './control.ts';\nimport type {MapSourceDataEvent, MapStyleDataEvent, MapTerrainEvent} from '../events.ts';\nimport type {StyleSpecification} from '@maplibre/maplibre-gl-style-spec';\n/**\n * The {@link AttributionControl} options object\n */\nexport type AttributionControlOptions = {\n    /**\n     * If `true`, the attribution control will always collapse when moving the map. If `false`,\n     * force the expanded attribution control. The default is a responsive attribution that collapses when the user moves the map on maps less than 640 pixels wide.\n     * **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 and when the automatic compact resizing for default settings are not sufficient.**\n     */\n    compact?: boolean;\n    /**\n     * Attributions to show in addition to any other attributions.\n     */\n    customAttribution?: string | string[];\n};\n\nexport const defaultAttributionControlOptions: AttributionControlOptions = {\n    compact: true,\n    customAttribution: '<a href=\"https://maplibre.org/\" target=\"_blank\">MapLibre</a>'\n};\n\n/**\n * An `AttributionControl` control presents the map's attribution information. By default, the attribution control is expanded (regardless of map width).\n * @group Markers and Controls\n * @example\n * ```ts\n * let map = new Map({attributionControl: false})\n *     .addControl(new AttributionControl({\n *         compact: true\n *     }));\n * ```\n * @see [Change the default position for attribution](https://maplibre.org/maplibre-gl-js/docs/examples/change-the-default-position-for-attribution/)\n */\nexport class AttributionControl implements IControl {\n    options: AttributionControlOptions;\n    _map: Map;\n    _compact: boolean | undefined;\n    _container: HTMLElement;\n    _innerContainer: HTMLElement;\n    _compactButton: HTMLElement;\n    _editLink: HTMLAnchorElement;\n    _attribHTML: string;\n    styleId: string;\n    styleOwner: string;\n\n    /**\n     * @param options - the attribution options\n     */\n    constructor(options: AttributionControlOptions = defaultAttributionControlOptions) {\n        this.options = options;\n    }\n\n    getDefaultPosition(): ControlPosition {\n        return 'bottom-right';\n    }\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        this._compact = this.options.compact;\n        this._container = DOM.create('details', 'maplibregl-ctrl maplibregl-ctrl-attrib');\n        this._compactButton = DOM.create('summary', 'maplibregl-ctrl-attrib-button', this._container);\n        this._compactButton.addEventListener('click', this._toggleAttribution);\n        this._setElementTitle(this._compactButton, 'ToggleAttribution');\n        this._innerContainer = DOM.create('div', 'maplibregl-ctrl-attrib-inner', this._container);\n\n        this._updateAttributions();\n        this._updateCompact();\n\n        this._map.on('styledata', this._updateData);\n        this._map.on('sourcedata', this._updateData);\n        this._map.on('terrain', this._updateData);\n        this._map.on('resize', this._updateCompact);\n        this._map.on('drag', this._updateCompactMinimize);\n\n        return this._container;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        this._container.remove();\n\n        this._map.off('styledata', this._updateData);\n        this._map.off('sourcedata', this._updateData);\n        this._map.off('terrain', this._updateData);\n        this._map.off('resize', this._updateCompact);\n        this._map.off('drag', this._updateCompactMinimize);\n\n        this._map = undefined;\n        this._compact = undefined;\n        this._attribHTML = undefined;\n    }\n\n    _setElementTitle(element: HTMLElement, title: 'ToggleAttribution' | 'MapFeedback'): void {\n        const str = this._map._getUIString(`AttributionControl.${title}`);\n        element.title = str;\n        element.setAttribute('aria-label', str);\n    }\n\n    _toggleAttribution = (): void => {\n        if (this._container.classList.contains('maplibregl-compact')) {\n            if (this._container.classList.contains('maplibregl-compact-show')) {\n                this._container.setAttribute('open', '');\n                this._container.classList.remove('maplibregl-compact-show');\n            } else {\n                this._container.classList.add('maplibregl-compact-show');\n                this._container.removeAttribute('open');\n            }\n        }\n    };\n\n    _updateData = (e: MapSourceDataEvent | MapStyleDataEvent | MapTerrainEvent): void => {\n        if (e && (e.type === 'terrain' || e.dataType === 'style' || (e.dataType === 'source' && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility')))) {\n            this._updateAttributions();\n        }\n    };\n\n    _updateAttributions(): void {\n        if (!this._map.style) return;\n        let attributions: string[] = [];\n        if (this.options.customAttribution) {\n            if (Array.isArray(this.options.customAttribution)) {\n                attributions = attributions.concat(\n                    this.options.customAttribution.map(attribution => {\n                        if (typeof attribution !== 'string') return '';\n                        return attribution;\n                    })\n                );\n            } else if (typeof this.options.customAttribution === 'string') {\n                attributions.push(this.options.customAttribution);\n            }\n        }\n\n        if (this._map.style.stylesheet) {\n            const stylesheet = this._map.style.stylesheet as StyleSpecification & { owner: string; id: string };\n            this.styleOwner = stylesheet.owner;\n            this.styleId = stylesheet.id;\n        }\n\n        const tileManagers = this._map.style.tileManagers;\n        for (const id in tileManagers) {\n            const tileManager = tileManagers[id];\n            if (tileManager.used || tileManager.usedForTerrain) {\n                const source = tileManager.getSource();\n                if (source.attribution && !attributions.includes(source.attribution)) {\n                    attributions.push(source.attribution);\n                }\n            }\n        }\n\n        // remove any entries that are whitespace\n        attributions = attributions.filter(e => String(e).trim());\n\n        // remove any entries that are substrings of another entry.\n        // first sort by length so that substrings come first\n        attributions.sort((a, b) => a.length - b.length);\n        attributions = attributions.filter((attrib, i) => {\n            for (let j = i + 1; j < attributions.length; j++) {\n                if (attributions[j].includes(attrib)) { return false; }\n            }\n            return true;\n        });\n\n        // check if attribution string is different to minimize DOM changes\n        const attribHTML = attributions.join(' | ');\n        if (attribHTML === this._attribHTML) return;\n\n        this._attribHTML = attribHTML;\n\n        if (attributions.length) {\n            const fragment = document.createDocumentFragment();\n            let isFirst = true;\n            for (const attribution of attributions) {\n                const sanitizedAttribution = DOM.sanitize(attribution);\n                if (!sanitizedAttribution.hasChildNodes()) continue;\n                if (!isFirst) fragment.append(' | ');\n                fragment.append(sanitizedAttribution);\n                isFirst = false;\n            }\n            this._innerContainer.replaceChildren(fragment);\n            this._container.classList.remove('maplibregl-attrib-empty');\n        } else {\n            this._container.classList.add('maplibregl-attrib-empty');\n        }\n        this._updateCompact();\n        // remove old DOM node from _editLink\n        this._editLink = null;\n    }\n\n    _updateCompact = (): void => {\n        if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) {\n            if (this._compact === false) {\n                this._container.setAttribute('open', '');\n            } else if (!this._container.classList.contains('maplibregl-compact') && !this._container.classList.contains('maplibregl-attrib-empty')) {\n                this._container.setAttribute('open', '');\n                this._container.classList.add('maplibregl-compact', 'maplibregl-compact-show');\n            }\n        } else {\n            this._container.setAttribute('open', '');\n            if (this._container.classList.contains('maplibregl-compact')) {\n                this._container.classList.remove('maplibregl-compact', 'maplibregl-compact-show');\n            }\n        }\n    };\n\n    _updateCompactMinimize = (): void => {\n        if (this._container.classList.contains('maplibregl-compact')) {\n            if (this._container.classList.contains('maplibregl-compact-show')) {\n                this._container.classList.remove('maplibregl-compact-show');\n            }\n        }\n    };\n}\n", "import {DOM} from '../../util/dom.ts';\n\nimport type {Map} from '../map.ts';\nimport type {ControlPosition, IControl} from './control.ts';\n\n/**\n * The {@link LogoControl} options object\n */\nexport type LogoControlOptions = {\n    /**\n     * If `true`, force a compact logo.\n     * If `false`, force the full logo. The default is a responsive logo that collapses when the map is less than 640 pixels wide.\n     */\n    compact?: boolean;\n};\n\n/**\n * A `LogoControl` is a control that adds the watermark.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * map.addControl(new LogoControl({compact: false}));\n * ```\n **/\nexport class LogoControl implements IControl {\n    options: LogoControlOptions;\n    _map: Map;\n    _compact: boolean;\n    _container: HTMLElement;\n\n    /**\n     * @param options - the control's options\n     */\n    constructor(options: LogoControlOptions = {}) {\n        this.options = options;\n    }\n\n    getDefaultPosition(): ControlPosition {\n        return 'bottom-left';\n    }\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        this._compact = this.options?.compact;\n        this._container = DOM.create('div', 'maplibregl-ctrl');\n        const anchor = DOM.create('a', 'maplibregl-ctrl-logo');\n        anchor.target = '_blank';\n        anchor.rel = 'noopener nofollow';\n        anchor.href = 'https://maplibre.org/';\n        anchor.setAttribute('aria-label', this._map._getUIString('LogoControl.Title'));\n        anchor.setAttribute('rel', 'noopener nofollow');\n        this._container.appendChild(anchor);\n        this._container.style.display = 'block';\n\n        this._map.on('resize', this._updateCompact);\n        this._updateCompact();\n\n        return this._container;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        this._container.remove();\n        this._map.off('resize', this._updateCompact);\n        this._map = undefined;\n        this._compact = undefined;\n    }\n\n    _updateCompact = (): void => {\n        const containerChildren = this._container.children;\n        if (containerChildren.length) {\n            const anchor = containerChildren[0];\n            if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) {\n                if (this._compact !== false) {\n                    anchor.classList.add('maplibregl-compact');\n                }\n            } else {\n                anchor.classList.remove('maplibregl-compact');\n            }\n        }\n    };\n\n}\n", "export type TaskID = number;\n\ntype Task = {\n    callback: (timeStamp: number) => void;\n    id: TaskID;\n    cancelled: boolean;\n};\n\nexport class TaskQueue {\n    _queue: Task[];\n    _id: TaskID;\n    _cleared: boolean;\n    _currentlyRunning: Task[] | false;\n\n    constructor()  {\n        this._queue = [];\n        this._id = 0;\n        this._cleared = false;\n        this._currentlyRunning = false;\n    }\n\n    add(callback: (timeStamp: number) => void): TaskID {\n        const id = ++this._id;\n        const queue = this._queue;\n        queue.push({callback, id, cancelled: false});\n        return id;\n    }\n\n    remove(id: TaskID): void {\n        const running = this._currentlyRunning;\n        const queue = running ? this._queue.concat(running) : this._queue;\n        for (const task of queue) {\n            if (task.id === id) {\n                task.cancelled = true;\n                return;\n            }\n        }\n    }\n\n    run(timeStamp: number = 0): void {\n        if (this._currentlyRunning) throw new Error('Attempting to run(), but is already running.');\n        const queue = this._currentlyRunning = this._queue;\n\n        // Tasks queued by callbacks in the current queue should be executed\n        // on the next run, not the current run.\n        this._queue = [];\n\n        let failed = false;\n        let firstError: unknown;\n        for (const task of queue) {\n            if (task.cancelled) continue;\n            try {\n                task.callback(timeStamp);\n            } catch (error) {\n                if (!failed) {\n                    failed = true;\n                    firstError = error;\n                }\n            }\n            if (this._cleared) break;\n        }\n\n        this._cleared = false;\n        this._currentlyRunning = false;\n        if (failed) throw firstError;\n    }\n\n    clear(): void {\n        if (this._currentlyRunning) {\n            this._cleared = true;\n        }\n        this._queue = [];\n    }\n}\n", "import {createLayout, type StructArrayLayout} from '../util/struct_array.ts';\n\nconst pos3dAttributes: StructArrayLayout = createLayout([\n    {name: 'a_pos3d', type: 'Int16', components: 3}\n]);\n\nexport default pos3dAttributes;\n", "import {Tile} from './tile.ts';\nimport {EXTENT} from '../data/extent.ts';\nimport {mat4} from 'gl-matrix';\nimport {Evented} from '../util/evented.ts';\nimport {now} from '../util/time_control.ts';\nimport {coveringTiles} from '../geo/projection/covering_tiles.ts';\nimport {createMat4f64} from '../util/util.ts';\n\nimport type {Terrain} from '../render/terrain.ts';\nimport type {CanonicalTileRange} from '../source/image_source.ts';\nimport type {Source} from '../source/source.ts';\nimport type {TileManager} from './tile_manager.ts';\nimport type {OverscaledTileID} from './tile_id.ts';\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\n\n/**\n * @internal\n * This class is a helper for the Terrain-class, it:\n *\n * - loads raster-dem tiles\n * - manages all renderToTexture tiles.\n * - caches previous rendered tiles.\n * - finds all necessary renderToTexture tiles for a OverscaledTileID area\n * - finds the corresponding raster-dem tile for OverscaledTileID\n */\nexport class TerrainTileManager extends Evented {\n    /**\n     * tile manager for the raster-dem source.\n     */\n    tileManager: TileManager;\n    /**\n     * stores all render-to-texture tiles.\n     */\n    _tiles: {[_: string]: Tile};\n    /**\n     * contains a list of tileID-keys for the current scene. (only for performance)\n     */\n    _renderableTilesKeys: string[];\n    /**\n     * For each tile, the key of its raster-dem tile and the source zoom that key was scaled to, which changes once the\n     * source has loaded its zoom range.\n     */\n    _sourceTileCache: {[_: string]: {zoom: number; key: string}};\n    /**\n     * minimum zoomlevel to render the terrain.\n     */\n    minzoom: number;\n    /**\n     * maximum zoomlevel to render the terrain.\n     */\n    maxzoom: number;\n    /**\n     * render-to-texture tileSize in scene.\n     */\n    tileSize: number;\n    /**\n     * raster-dem tiles will load for performance the actualZoom - deltaZoom zoom-level.\n     */\n    deltaZoom: number;\n    /**\n     * used to determine whether the depth framebuffer needs updating\n     */\n    _lastTilesetChange: number = now();\n\n    constructor(tileManager: TileManager) {\n        super();\n        this.tileManager = tileManager;\n        this._tiles = {};\n        this._renderableTilesKeys = [];\n        this._sourceTileCache = {};\n        this.minzoom = 0;\n        this.maxzoom = 22;\n        this.deltaZoom = 1;\n        this.tileSize = tileManager._source.tileSize * 2 ** this.deltaZoom;\n        tileManager.usedForTerrain = true;\n        tileManager.tileSize = this.tileSize;\n    }\n\n    destruct(): void {\n        this.tileManager.usedForTerrain = false;\n        this.tileManager.tileSize = null;\n        this.releaseAllRTT();\n    }\n\n    getSource(): Source {\n        return this.tileManager._source;\n    }\n\n    /**\n     * Load Terrain Tiles, create internal render-to-texture tiles, free GPU memory.\n     * @param transform - the operation to do\n     * @param terrain - the terrain\n     * @returns true when the set of renderable tiles changed\n     */\n    update(transform: IReadonlyTransform, terrain: Terrain): boolean {\n        // load raster-dem tiles for the current scene.\n        this.tileManager.update(transform, terrain);\n        // create internal render-to-texture tiles for the current scene.\n        this._renderableTilesKeys = [];\n        const keys = {};\n        let changed = false;\n        for (const tileID of coveringTiles(transform, {\n            tileSize: this.tileSize,\n            minzoom: this.minzoom,\n            maxzoom: this.maxzoom,\n            reparseOverscaled: false,\n            terrain\n        })) {\n            keys[tileID.key] = true;\n            this._renderableTilesKeys.push(tileID.key);\n            if (!this._tiles[tileID.key]) {\n                tileID.terrainRttPosMatrix32f = new Float32Array(16);\n                mat4.ortho(tileID.terrainRttPosMatrix32f, 0, EXTENT, EXTENT, 0, 0, 1);\n                this._tiles[tileID.key] = new Tile(tileID, this.tileSize);\n                this._lastTilesetChange = now();\n                changed = true;\n            }\n        }\n        // free unused tiles\n        for (const key in this._tiles) {\n            if (!keys[key]) {\n                this._tiles[key].releaseRTT(this.tileManager.map.painter);\n                delete this._tiles[key];\n                changed = true;\n            }\n        }\n        return changed;\n    }\n\n    /**\n     * Release the RTT objects for `tileID` (and its ancestors/descendants),\n     */\n    releaseRTT(tileID: OverscaledTileID): void {\n        for (const key in this._tiles) {\n            const tile = this._tiles[key];\n            if (tile.tileID.equals(tileID) || tile.tileID.isChildOf(tileID) || tileID.isChildOf(tile.tileID))\n                tile.releaseRTT(this.tileManager.map.painter);\n        }\n    }\n\n    /**\n     * Release the A RTT objects for all tiles.\n     */\n    releaseAllRTT(): void {\n        for (const key in this._tiles) {\n            const tile = this._tiles[key];\n            tile.releaseRTT(this.tileManager.map.painter);\n        }\n    }\n\n    /**\n     * get a list of tiles, which are loaded and should be rendered in the current scene\n     * @returns the renderable tiles\n     */\n    getRenderableTiles(): Tile[] {\n        return this._renderableTilesKeys.map(key => this.getTileByID(key));\n    }\n\n    /**\n     * get terrain tile by the TileID key\n     * @param id - the tile id\n     * @returns the tile\n     */\n    getTileByID(id: string): Tile {\n        return this._tiles[id];\n    }\n\n    /**\n     * Searches for the corresponding current renderable terrain-tiles\n     * @param tileID - the tile to look for\n     * @returns the tiles that were found\n     */\n    getTerrainCoords(\n        tileID: OverscaledTileID,\n        terrainTileRanges?: {[zoom: string]: CanonicalTileRange}\n    ): Record<string, OverscaledTileID> {\n        if (terrainTileRanges) {\n            return this._getTerrainCoordsForTileRanges(tileID, terrainTileRanges);\n        } else {\n            return this._getTerrainCoordsForRegularTile(tileID);\n        }\n    }\n\n    /**\n     * Searches for the corresponding current renderable terrain-tiles.\n     * Includes terrain tiles that are either:\n     * - the same as the tileID\n     * - a parent of the tileID\n     * - a child of the tileID\n     * @param tileID - the tile to look for\n     * @returns the tiles that were found\n     */\n    _getTerrainCoordsForRegularTile(tileID: OverscaledTileID): Record<string, OverscaledTileID> {\n        const coords: Record<string, OverscaledTileID> = {};\n        for (const key of this._renderableTilesKeys) {\n            const terrainTileID = this._tiles[key].tileID;\n            const coord = tileID.clone();\n            const mat = createMat4f64();\n            if (terrainTileID.canonical.equals(tileID.canonical)) {\n                mat4.ortho(mat, 0, EXTENT, EXTENT, 0, 0, 1);\n            } else if (terrainTileID.canonical.isChildOf(tileID.canonical)) {\n                const dz = terrainTileID.canonical.z - tileID.canonical.z;\n                const dx = terrainTileID.canonical.x - (terrainTileID.canonical.x >> dz << dz);\n                const dy = terrainTileID.canonical.y - (terrainTileID.canonical.y >> dz << dz);\n                const size = EXTENT >> dz;\n                mat4.ortho(mat, 0, size, size, 0, 0, 1); // Note: we are using `size` instead of `EXTENT` here\n                mat4.translate(mat, mat, [-dx * size, -dy * size, 0]);\n            } else if (tileID.canonical.isChildOf(terrainTileID.canonical)) {\n                const dz = tileID.canonical.z - terrainTileID.canonical.z;\n                const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);\n                const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);\n                const size = EXTENT >> dz;\n                mat4.ortho(mat, 0, EXTENT, EXTENT, 0, 0, 1);\n                mat4.translate(mat, mat, [dx * size, dy * size, 0]);\n                mat4.scale(mat, mat, [1 / (2 ** dz), 1 / (2 ** dz), 0]);\n            } else {\n                continue;\n            }\n            coord.terrainRttPosMatrix32f = new Float32Array(mat);\n            coords[key] = coord;\n        }\n        return coords;\n    }\n\n    /**\n     * Searches for the corresponding current renderable terrain-tiles.\n     * Includes terrain tiles that are within terrain tile ranges.\n     * @param tileID - the tile to look for\n     * @returns the tiles that were found\n     */\n    _getTerrainCoordsForTileRanges(\n        tileID: OverscaledTileID,\n        terrainTileRanges: {[zoom: string]: CanonicalTileRange}\n    ): Record<string, OverscaledTileID> {\n        const coords: Record<string, OverscaledTileID> = {};\n        for (const key of this._renderableTilesKeys) {\n            const terrainTileID = this._tiles[key].tileID;\n            if (!this._isWithinTileRanges(terrainTileID, terrainTileRanges)) {\n                continue;\n            }\n\n            const coord = tileID.clone();\n            const mat = createMat4f64();\n            if (terrainTileID.canonical.z === tileID.canonical.z) {\n                const dx = tileID.canonical.x - terrainTileID.canonical.x\n                    + tileID.wrap * (1 << tileID.canonical.z); // include wrap shift\n                const dy = tileID.canonical.y - terrainTileID.canonical.y;\n                mat4.ortho(mat, 0, EXTENT, EXTENT, 0, 0, 1);\n                mat4.translate(mat, mat, [dx * EXTENT, dy * EXTENT, 0]);\n            } else if (terrainTileID.canonical.z > tileID.canonical.z) {\n                const dz = terrainTileID.canonical.z - tileID.canonical.z;\n                // this translation is needed to project tileID to terrainTileID zoom level\n                const dx = terrainTileID.canonical.x - (terrainTileID.canonical.x >> dz << dz)\n                    + tileID.wrap * (1 << terrainTileID.canonical.z); // include wrap shift\n                const dy = terrainTileID.canonical.y - (terrainTileID.canonical.y >> dz << dz);\n                // this translation is needed if terrainTileID is not a parent of tileID\n                const dx2 = tileID.canonical.x - (terrainTileID.canonical.x >> dz);\n                const dy2 = tileID.canonical.y - (terrainTileID.canonical.y >> dz);\n\n                const size = EXTENT >> dz;\n                mat4.ortho(mat, 0, size, size, 0, 0, 1);\n                mat4.translate(mat, mat, [-dx * size + dx2 * EXTENT, -dy * size + dy2 * EXTENT, 0]);\n            } else { // terrainTileID.canonical.z < tileID.canonical.z\n                const dz = tileID.canonical.z - terrainTileID.canonical.z;\n                // this translation is needed to project tileID to terrainTileID zoom level\n                const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz)\n                    + tileID.wrap * (1 << tileID.canonical.z); // include wrap shift\n                const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);\n                // this translation is needed if terrainTileID is not a parent of tileID\n                const dx2 = (tileID.canonical.x >> dz) - terrainTileID.canonical.x;\n                const dy2 = (tileID.canonical.y >> dz) - terrainTileID.canonical.y;\n\n                const size = EXTENT << dz;\n                mat4.ortho(mat, 0, size, size, 0, 0, 1);\n                mat4.translate(mat, mat, [dx * EXTENT + dx2 * size, dy * EXTENT + dy2 * size, 0]);\n            }\n            coord.terrainRttPosMatrix32f = new Float32Array(mat);\n            coords[key] = coord;\n        }\n        return coords;\n    }\n\n    /**\n     * find the covering raster-dem tile\n     * @param tileID - the tile to look for\n     * @param searchForDEM - Optional parameter to search for (parent) source tiles with loaded dem.\n     * @returns the tile\n     */\n    getSourceTile(tileID: OverscaledTileID, searchForDEM?: boolean): Tile | undefined {\n        const source = this.tileManager._source;\n        let z = this._getSourceZoom(tileID, source);\n        if (z === undefined) return undefined;\n        // cache for tileID to terrain-tileID\n        if (this._sourceTileCache[tileID.key]?.zoom !== z) this._sourceTileCache[tileID.key] = {zoom: z, key: tileID.scaledTo(z).key};\n        let tile = this.findTileInCaches(this._sourceTileCache[tileID.key].key);\n        // during tile-loading phase look if parent tiles (with loaded dem) are available.\n        if (!tile?.dem && searchForDEM) {\n            while (z >= source.minzoom && !tile?.dem)\n                tile = this.findTileInCaches(tileID.scaledTo(z--).key);\n        }\n        return tile;\n    }\n\n    /**\n     * Whether the terrain is still waiting for DEM data for a terrain tile that has none: the source tile covering it\n     * lies within the source's zoom range and bounds, and has not failed to load.\n     * @param tileID - the terrain tile\n     * @returns false where the source will not serve DEM data for the tile\n     */\n    isStillWaitingForDEM(tileID: OverscaledTileID): boolean {\n        const source = this.tileManager._source;\n        const z = this._getSourceZoom(tileID, source);\n        if (z === undefined) return false;\n        const sourceTileID = tileID.scaledTo(z);\n        if (source.hasTile && !source.hasTile(sourceTileID)) return false;\n        return this.findTileInCaches(sourceTileID.key)?.state !== 'errored';\n    }\n\n    /**\n     * The zoom of the raster-dem tile that covers a terrain tile: `deltaZoom` below the terrain tile, kept within the\n     * source's zoom range, so a terrain tile at the source's minzoom uses the source tile at that zoom.\n     * @param tileID - the terrain tile\n     * @param source - the raster-dem source\n     * @returns the zoom, or undefined where the source has no tiles at or below the terrain tile's zoom\n     */\n    private _getSourceZoom(tileID: OverscaledTileID, source: Source): number | undefined {\n        let z = Math.min(tileID.overscaledZ - this.deltaZoom, source.maxzoom);\n        if (z < source.minzoom) z = source.minzoom;\n        return z <= tileID.overscaledZ ? z : undefined;\n    }\n\n    findTileInCaches(key: string): Tile | undefined {\n        let tile = this.tileManager.getTileByID(key);\n        if (tile) {\n            return tile;\n        }\n        tile = this.tileManager._outOfViewCache.getByKey(key);\n        return tile;\n    }\n\n    /**\n     * gets whether any tiles were loaded after a specific time. This is used to update the depth framebuffer.\n     * @param time - the time\n     * @returns true if any tiles came into view at or after the specified time\n     */\n    anyTilesAfterTime(time: number = now()): boolean {\n        return this._lastTilesetChange >= time;\n    }\n\n    /**\n     * Checks whether a tile is within the canonical tile ranges.\n     * @param tileID - Tile to check\n     * @param canonicalTileRanges - Canonical tile ranges\n     * @returns\n     */\n    private _isWithinTileRanges(\n        tileID: OverscaledTileID,\n        canonicalTileRanges: {[zoom: string]: CanonicalTileRange}\n    ): boolean {\n        const range = canonicalTileRanges[tileID.canonical.z];\n\n        return !!range && (\n            tileID.wrap > range.minWrap || tileID.wrap < range.maxWrap ||\n            tileID.canonical.x >= range.minTileXWrapped &&\n            tileID.canonical.x <= range.maxTileXWrapped &&\n            tileID.canonical.y >= range.minTileY &&\n            tileID.canonical.y <= range.maxTileY\n        );\n    }\n}\n", "import {mat4} from 'gl-matrix';\nimport {OverscaledTileID} from '../tile/tile_id.ts';\nimport {RGBAImage} from '../util/image.ts';\nimport {Pos3dArray, TriangleIndexArray} from '../data/array_types.g.ts';\nimport pos3dAttributes from '../data/pos3d_attributes.ts';\nimport {SegmentVector} from '../data/segment.ts';\nimport {Texture} from '../webgl/texture.ts';\nimport {TerrainTileManager} from '../tile/terrain_tile_manager.ts';\nimport {EXTENT} from '../data/extent.ts';\nimport {Mesh} from './mesh.ts';\nimport {isInBoundsForZoomLngLat} from '../util/world_bounds.ts';\nimport {NORTH_POLE_Y, SOUTH_POLE_Y} from './subdivision.ts';\nimport {TerrainCoverage, type TerrainCoverageIndex} from './terrain_coverage.ts';\nimport {mercatorWorldCoordinateHelper} from '../geo/mercator_coordinate.ts';\n\nimport type {WorldCoordinateHelper} from '../geo/transform_interface.ts';\nimport type {LngLat} from '../geo/lng_lat.ts';\nimport type {Tile} from '../tile/tile.ts';\nimport type {Framebuffer} from '../webgl/framebuffer.ts';\nimport type {TileManager} from '../tile/tile_manager.ts';\nimport type {TerrainSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {Painter} from './painter.ts';\n\n/**\n * @experimental\n * A float texture for {@link CustomRenderMethodInput.renderTerrainHeightMap}, such as `RGBA32F`, which needs the\n * `EXT_color_buffer_float` extension to be drawn into. Red holds the elevation in meters, including the terrain exaggeration, alpha\n * is 1 where terrain is loaded and 0 elsewhere, and the first row is the south edge.\n */\nexport type TerrainHeightMapTarget = {\n    /** A texture in the map's WebGL context. */\n    texture: WebGLTexture;\n    /** The width of the texture in pixels. */\n    width: number;\n    /** The height of the texture in pixels. */\n    height: number;\n    /** The area to draw, `[minX, minY, maxX, maxY]` in {@link MercatorCoordinate} units, with x counting world copies. */\n    bounds: [number, number, number, number];\n};\n\n/**\n * @internal\n * A terrain GPU related object\n */\nexport type TerrainData = {\n    'u_depth': number;\n    'u_terrain': number;\n    'u_terrain_dim': number;\n    'u_terrain_matrix': mat4;\n    'u_terrain_unpack': number[];\n    'u_terrain_exaggeration': number;\n    texture: WebGLTexture;\n    depthTexture: WebGLTexture;\n    tile: Tile;\n};\n\n/**\n * @internal\n * Where the DEM data under a location stands, see {@link Terrain.getElevationAndDEMStateForLngLat}:\n * - `loaded`: it has loaded.\n * - `loading`: none has loaded yet, but it can still arrive.\n * - `none`: none has loaded and none will: the location is outside the source's bounds or zoom range, or its tile\n * failed to load.\n */\nexport type DEMState = 'loaded' | 'loading' | 'none';\n\n/**\n * @internal\n * This is the main class which handles most of the 3D Terrain logic. It has the following topics:\n *\n * 1. loads raster-dem tiles via the internal tileManager this.tileManager\n * 2. creates a depth-framebuffer, which is used to calculate the visibility of coordinates\n * 3. stores all render-to-texture tiles in the this.tileManager._tiles\n * 4. calculates the elevation for a specific tile-coordinate\n * 5. creates a terrain-mesh\n *\n * A note about the GPU resource-usage:\n *\n * Framebuffers:\n *\n * - one for the depth framebuffer with the size of the map-div.\n * - one for rendering a tile to texture with the size of tileSize (= 512x512).\n *\n * Textures:\n *\n * - one texture for an empty raster-dem tile with size 1x1\n * - one texture for an empty depth-buffer, when terrain is disabled with size 1x1\n * - one texture for an each loaded raster-dem with size of the source.tileSize\n * - one texture for the depth-framebuffer with the size of the map-div.\n * - finally for each render-to-texture tile (= this._tiles) a set of textures\n * for each render stack (The stack-concept is documented in painter.ts).\n *\n * Normally there exists 1-3 Textures per tile, depending on the stylesheet.\n * Each Textures has the size 2*tileSize (= 1024x1024). Also there exists a\n * cache of the last 150 newest rendered tiles.\n *\n */\nexport class Terrain {\n    /**\n     * The style this terrain corresponds to\n     */\n    painter: Painter;\n    /**\n     * the tilemanager this terrain is based on\n     */\n    tileManager: TerrainTileManager;\n    /**\n     * the TerrainSpecification object passed to this instance\n     */\n    options: TerrainSpecification;\n    /**\n     * define the meshSize per tile.\n     */\n    meshSize: number;\n    /**\n     * multiplicator for the elevation. Used to make terrain more \"extreme\".\n     */\n    exaggeration: number;\n    /**\n     * to not see pixels in the render-to-texture tiles it is good to render them bigger\n     * this number is the multiplicator (must be a power of 2) for the current tileSize.\n     * So to get good results with not too much memory footprint a value of 2 should be fine.\n     */\n    qualityFactor: number;\n    /**\n     * holds the framebuffer object in size of the screen to render the depth into a texture.\n     */\n    _fbo: Framebuffer;\n    _heightMapFbo: Framebuffer;\n    _fboDepthTexture: Texture;\n    _emptyDepthTexture: Texture;\n    /**\n     * GL Objects for the terrain-mesh\n     * The mesh is a regular mesh, which has the advantage that it can be reused for all tiles.\n     */\n    _meshCache: { [key: string]: Mesh } = {};\n    /**\n     * variables for an empty dem texture, which is used while the raster-dem tile is loading.\n     */\n    _emptyDemUnpack: number[];\n    _emptyDemTexture: Texture;\n    _emptyDemMatrix: mat4;\n    /**\n     * as of overzooming of raster-dem tiles in high zoomlevels, this cache contains\n     * matrices to transform from vector-tile coords to raster-dem-tile coords.\n     */\n    _demMatrixCache: Map<string, mat4>;\n    /** The drawn tiles' DEM data as sampled on the CPU, see {@link TerrainCoverage}. */\n    coverage: TerrainCoverage;\n    /**\n     * Controls how terrain skirt length is calculated.\n     * @see {@link MapOptions.terrainSkirtLength}\n     */\n    _terrainSkirtLength: 'none' | 'auto';\n    /** Reads the lng/lat to world mapping of the map's projection, which the map can switch while the terrain is on. */\n    private readonly _getWorldCoordinateHelper: () => WorldCoordinateHelper;\n    /**\n     * @param getWorldCoordinateHelper - reads the lng/lat to world mapping of the map's projection, mercator's by default\n     */\n    constructor(painter: Painter, tileManager: TileManager, options: TerrainSpecification, terrainSkirtLength: 'none' | 'auto' = 'auto', getWorldCoordinateHelper: () => WorldCoordinateHelper = () => mercatorWorldCoordinateHelper) {\n        this.painter = painter;\n        this._getWorldCoordinateHelper = getWorldCoordinateHelper;\n        this.tileManager = new TerrainTileManager(tileManager);\n        this.options = options;\n        this.exaggeration = typeof options.exaggeration === 'number' ? options.exaggeration : 1.0;\n        this._terrainSkirtLength = terrainSkirtLength;\n        this.qualityFactor = 2;\n        this.meshSize = 128;\n        this._demMatrixCache = new Map();\n        this.coverage = new TerrainCoverage(this.tileManager, this.exaggeration, () => this._worldCoordinateHelper);\n    }\n\n    destroy(): void {\n        if (this._fbo) {\n            this._fbo.destroy();\n            this._fbo = null;\n        }\n        if (this._heightMapFbo) {\n            this._heightMapFbo.destroy();\n            this._heightMapFbo = null;\n        }\n        if (this._fboDepthTexture) {\n            this._fboDepthTexture.destroy();\n            this._fboDepthTexture = null;\n        }\n        if (this._emptyDemTexture) {\n            this._emptyDemTexture.destroy();\n            this._emptyDemTexture = null;\n        }\n        if (this._emptyDepthTexture) {\n            this._emptyDepthTexture.destroy();\n            this._emptyDepthTexture = null;\n        }\n        for (const key in this._meshCache) {\n            this._meshCache[key].destroy();\n        }\n        this._meshCache = {};\n        this.tileManager.destruct();\n    }\n\n    /**\n     * Get the elevation-value from original dem-data for a given tile-coordinate.\n     * Coordinates that fall outside `[0, extent)` are normalized to the\n     * appropriate neighbor tile before lookup.\n     * @param tileID - the tile to get the elevation for\n     * @param x - x coordinate relative to the tile, may be outside `[0, extent)`\n     * @param y - y coordinate relative to the tile, may be outside `[0, extent)`\n     * @param extent - optional, default 8192\n     * @returns the elevation\n     */\n    getDEMElevation(tileID: OverscaledTileID, x: number, y: number, extent: number = EXTENT): number {\n        const normalized = tileID.normalizeCoordinates(x, y, extent);\n        if (!normalized) return 0;\n\n        const sampler = this.coverage.getSampler(normalized.tileID);\n        return sampler ? sampler(normalized.x, normalized.y, extent) : 0;\n    }\n\n    /**\n     * Get the elevation for given {@link LngLat} in respect of exaggeration.\n     * @param lnglat - the location\n     * @param zoom - the zoom, use {@link getElevationForLngLat} if you don't want a specific zoom level, but more accurate results.\n     * @returns the elevation\n     */\n    getElevationForLngLatZoom(lnglat: LngLat, zoom: number): number {\n        const worldCoordinateHelper = this._worldCoordinateHelper;\n        if (!isInBoundsForZoomLngLat(zoom, worldCoordinateHelper.wraps ? lnglat.wrap() : lnglat, worldCoordinateHelper)) return 0;\n        const {tileID, worldX, worldY} = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);\n        return this.getElevation(tileID, worldX % EXTENT, worldY % EXTENT, EXTENT);\n    }\n\n    /**\n     * Get the elevation for given {@link LngLat} in respect of exaggeration.\n     * Where the location is covered by a rendered tile with loaded DEM data this samples the\n     * rendered surface, so the result agrees with what is drawn; elsewhere it traverses up the\n     * zoom levels to find the first tile with data to return. Where no DEM data has loaded it gives 0, which\n     * {@link getElevationAndDEMStateForLngLat} tells apart from 0 m.\n     * @param lnglat - the location\n     * @param tileZoom - the camera's tile zoom, at which the terrain's tiles are loaded\n     * @returns the elevation\n     */\n    getElevationForLngLat(lnglat: LngLat, tileZoom: number): number {\n        const elevation = this.getDrawnElevationForLngLat(lnglat);\n        if (elevation !== undefined) return elevation;\n        return this.getElevationForLngLatZoom(lnglat, this._getFallbackZoom(tileZoom));\n    }\n\n    /**\n     * Get the elevation of the terrain as drawn at the given {@link LngLat}, in respect of exaggeration, where a drawn\n     * tile has DEM data there: its own, or with `ownDemOnly` false a loaded parent's drawn in its place, which can be\n     * a few hundred meters off until the tile's own loads.\n     * @param lnglat - the location\n     * @param ownDemOnly - whether only a drawn tile's own DEM data counts\n     * @returns the elevation, or undefined where no drawn tile has that DEM data\n     */\n    getDrawnElevationForLngLat(lnglat: LngLat, ownDemOnly: boolean = false): number | undefined {\n        return this.coverage.sample(lnglat, ownDemOnly);\n    }\n\n    /**\n     * {@link getElevationForLngLat} together with where the DEM data it reads stands, for a caller that has to tell the\n     * 0 it gives for want of DEM data apart from 0 m. DEM data has loaded where a drawn tile or the tile it falls back\n     * to has it, its own or a loaded parent's, and any elevation other than 0 comes from loaded DEM data.\n     * @param lnglat - the location\n     * @param tileZoom - the camera's tile zoom, which {@link getElevationForLngLat} is given\n     * @returns the elevation, and the state of the DEM data there\n     */\n    getElevationAndDEMStateForLngLat(lnglat: LngLat, tileZoom: number): {elevation: number; demState: DEMState} {\n        const elevation = this.getElevationForLngLat(lnglat, tileZoom);\n        if (elevation !== 0 || this.getDrawnElevationForLngLat(lnglat) !== undefined) return {elevation, demState: 'loaded'};\n        const zoom = this._getFallbackZoom(tileZoom);\n        const worldCoordinateHelper = this._worldCoordinateHelper;\n        if (!isInBoundsForZoomLngLat(zoom, worldCoordinateHelper.wraps ? lnglat.wrap() : lnglat, worldCoordinateHelper)) return {elevation, demState: 'none'};\n        const {tileID} = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);\n        if (this.tileManager.getSourceTile(tileID, true)?.dem) return {elevation, demState: 'loaded'};\n        return {elevation, demState: this.tileManager.isStillWaitingForDEM(tileID) ? 'loading' : 'none'};\n    }\n\n    /**\n     * The zoom {@link getElevationForLngLat} passes to {@link getElevationForLngLatZoom} where no drawn tile has DEM\n     * data: the camera's tile zoom, where the terrain's tiles are loaded.\n     */\n    private _getFallbackZoom(tileZoom: number): number {\n        return Math.min(tileZoom, this.tileManager.maxzoom);\n    }\n\n    /**\n     * Get the elevation for given coordinate in respect of exaggeration.\n     * @param tileID - the tile id\n     * @param x - x coordinate relative to the tile, may be outside `[0, extent)`\n     * @param y - y coordinate relative to the tile, may be outside `[0, extent)`\n     * @param extent - optional, default 8192\n     * @returns the elevation\n     */\n    getElevation(tileID: OverscaledTileID, x: number, y: number, extent: number = EXTENT): number {\n        return this.getDEMElevation(tileID, x, y, extent) * this.exaggeration;\n    }\n\n    /**\n     * Clear the CPU samplers of the drawn tiles' DEM data, which may retain a previously selected DEM tile.\n     * @internal\n     */\n    resetElevationCache(): void {\n        this.coverage.reset();\n    }\n\n    /**\n     * Index of the tiles the terrain currently renders, for sampling the terrain surface on the CPU.\n     * @returns the index, or null when no terrain tile is renderable\n     */\n    getCoverageIndex(): TerrainCoverageIndex | null {\n        return this.coverage.getIndex();\n    }\n\n    /**\n     * Get the matrix that maps a tile's coordinates into the DEM tile it is rendered with.\n     * The transform is derived from the loaded DEM tile's own zoom level, not from the source's\n     * declared maxzoom: getSourceTile falls back to a loaded parent tile while the deepest DEM\n     * tile is still loading, and the scale and offset must match the tile that is actually used.\n     * @param tileID - the tile id\n     * @param sourceTile - the DEM tile that is used for this tile, either its own tile or a loaded parent\n     * @returns the matrix that maps the tile's coordinates onto the DEM tile\n     */\n    _getDEMTileMatrix(tileID: OverscaledTileID, sourceTile: Tile): mat4 {\n        const matrixKey = `${sourceTile.tileID.key}/${tileID.key}`;\n        const cachedMatrix = this._demMatrixCache.get(matrixKey);\n        if (cachedMatrix) return cachedMatrix;\n\n        const dz = tileID.canonical.z - sourceTile.tileID.canonical.z;\n        const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);\n        const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);\n        const demMatrix = mat4.fromScaling(new Float64Array(16), [1 / (EXTENT << dz), 1 / (EXTENT << dz), 0]);\n        mat4.translate(demMatrix, demMatrix, [dx * EXTENT, dy * EXTENT, 0]);\n        this._demMatrixCache.set(matrixKey, demMatrix);\n        return demMatrix;\n    }\n\n    /**\n     * returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object\n     * @param tileID - the tile to get the terrain for\n     * @returns the terrain data to use in the program\n     */\n    getTerrainData(tileID: OverscaledTileID): TerrainData {\n        // create empty DEM Objects, which will used while raster-dem tiles are loading.\n        // creates an empty depth-buffer texture which is needed, during the initialization process of the 3d mesh..\n        if (!this._emptyDemTexture) {\n            const context = this.painter.context;\n            const image = new RGBAImage({width: 1, height: 1}, new Uint8Array(1 * 4));\n            this._emptyDepthTexture = new Texture(context, image, context.gl.RGBA, {premultiply: false});\n            this._emptyDemUnpack = [0, 0, 0, 0];\n            this._emptyDemTexture = new Texture(context, new RGBAImage({width: 1, height: 1}), context.gl.RGBA, {premultiply: false});\n            this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);\n            this._emptyDemMatrix = mat4.identity([]);\n        }\n        // find covering dem tile and prepare demTexture\n        const sourceTile = this.tileManager.getSourceTile(tileID, true);\n        if (sourceTile?.dem && (!sourceTile.demTexture || sourceTile.needsTerrainPrepare)) {\n            const context = this.painter.context;\n            sourceTile.demTexture ||= this.painter.getTileTexture(sourceTile.dem.stride);\n            if (sourceTile.demTexture) sourceTile.demTexture.update(sourceTile.dem.getPixels(), {premultiply: false});\n            else sourceTile.demTexture = new Texture(context, sourceTile.dem.getPixels(), context.gl.RGBA, {premultiply: false});\n            sourceTile.demTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);\n            sourceTile.needsTerrainPrepare = false;\n        }\n        const terrainMatrix = sourceTile ? this._getDEMTileMatrix(tileID, sourceTile) : this._emptyDemMatrix;\n        // return uniform values & textures\n        return {\n            'u_depth': 2,\n            'u_terrain': 3,\n            'u_terrain_dim': sourceTile?.dem?.dim || 1,\n            'u_terrain_matrix': terrainMatrix,\n            'u_terrain_unpack': sourceTile?.dem?.getUnpackVector() || this._emptyDemUnpack,\n            'u_terrain_exaggeration': this.exaggeration,\n            texture: (sourceTile?.demTexture || this._emptyDemTexture).texture,\n            depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture,\n            tile: sourceTile\n        };\n    }\n\n    /**\n     * get a framebuffer as big as the map-div, which will be used to render depth into a texture\n     * @returns the frame buffer\n     */\n    getFramebuffer(): Framebuffer {\n        const painter = this.painter;\n        const width = painter.width / devicePixelRatio;\n        const height = painter.height / devicePixelRatio;\n        if (this._fbo && (this._fbo.width !== width || this._fbo.height !== height)) {\n            this._fbo.destroy();\n            this._fboDepthTexture.destroy();\n            delete this._fbo;\n            delete this._fboDepthTexture;\n        }\n        if (!this._fboDepthTexture) {\n            this._fboDepthTexture = new Texture(painter.context, {width, height, data: null}, painter.context.gl.RGBA, {premultiply: false});\n            this._fboDepthTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE);\n        }\n        if (!this._fbo) {\n            this._fbo = painter.context.createFramebuffer(width, height, true, false);\n            this._fbo.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, width, height));\n        }\n        this._fbo.colorAttachment.set(this._fboDepthTexture.texture);\n        return this._fbo;\n    }\n\n    /**\n     * get the framebuffer that draws the height map into a texture of a custom layer\n     * @param texture - the texture to draw into\n     * @returns the frame buffer\n     */\n    getHeightMapFramebuffer(texture: WebGLTexture): Framebuffer {\n        this._heightMapFbo ||= this.painter.context.createFramebuffer(1, 1, false, false);\n        this._heightMapFbo.colorAttachment.set(texture);\n        return this._heightMapFbo;\n    }\n\n    /**\n     * create a regular mesh which will be used by all terrain-tiles\n     * @param globeEnabled - whether the globe is rendering, which adds the pole geometry of the edge tiles\n     * @returns the created regular mesh\n     */\n    getTerrainMesh(tileId: OverscaledTileID, globeEnabled: boolean): Mesh {\n        const northPole = globeEnabled && tileId.canonical.y === 0;\n        const southPole = globeEnabled && tileId.canonical.y === (1 << tileId.canonical.z) - 1;\n        const key = `m_${northPole ? 'n' : ''}_${southPole ? 's' : ''}`;\n        if (this._meshCache[key]) {\n            return this._meshCache[key];\n        }\n        const context = this.painter.context;\n\n        const vertexArray = new Pos3dArray();\n        const indexArray = new TriangleIndexArray();\n        const meshSize = this.meshSize;\n        const delta = EXTENT / meshSize;\n        const meshSize2 = meshSize * meshSize;\n        for (let y = 0; y <= meshSize; y++) for (let x = 0; x <= meshSize; x++) {\n            vertexArray.emplaceBack(x * delta, y * delta, 0);\n        }\n        for (let y = 0; y < meshSize2; y += meshSize + 1) for (let x = 0; x < meshSize; x++) {\n            indexArray.emplaceBack(x + y, meshSize + x + y + 1, meshSize + x + y + 2);\n            indexArray.emplaceBack(x + y, meshSize + x + y + 2, x + y + 1);\n        }\n        if (this._terrainSkirtLength !== 'none') {\n            this._buildSkirts(vertexArray, indexArray, meshSize, delta, northPole, southPole);\n        }\n\n        const mesh = new Mesh(\n            context.createVertexBuffer(vertexArray, pos3dAttributes.members),\n            context.createIndexBuffer(indexArray),\n            SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)\n        );\n        this._meshCache[key] = mesh;\n        return mesh;\n    }\n\n    /**\n     * Calculates the height of the tile skirts for the \"auto\" strategy: a fifth of the tile width in meters, taking\n     * the meters per world unit at the center of the world square (the equator for mercator, where one world unit\n     * is the earth's circumference).\n     * @see {@link MapOptions.terrainSkirtLength}\n     * @param zoom - current zoomlevel\n     * @returns the elevation delta in meters\n     */\n    getSkirtLength(zoom: number): number {\n        // divide by 5 is evaluated by trial & error to get a frame in the right height\n        return this._worldCoordinateHelper.metersPerWorldUnit(0.5, 0.5) / Math.pow(2, Math.max(zoom, 0)) / 5;\n    }\n\n    getMinTileElevationForLngLatZoom(lnglat: LngLat, zoom: number): number {\n        const worldCoordinateHelper = this._worldCoordinateHelper;\n        if (!isInBoundsForZoomLngLat(zoom, worldCoordinateHelper.wraps ? lnglat.wrap() : lnglat, worldCoordinateHelper)) return 0;\n        const {tileID} = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);\n        return this.getMinMaxElevation(tileID).minElevation ?? 0;\n    }\n\n    /**\n     * Get the minimum and maximum elevation contained in a tile. This includes any\n     * exaggeration included in the terrain.\n     *\n     * @param tileID - ID of the tile to be used as a source for the min/max elevation\n     * @returns the minimum and maximum elevation found in the tile, including the terrain's\n     * exaggeration\n     */\n    getMinMaxElevation(tileID: OverscaledTileID): {minElevation: number | null; maxElevation: number | null} {\n        const tile = this.tileManager.getSourceTile(tileID, true);\n        const minMax: {minElevation: number | null; maxElevation: number | null} = {minElevation: null, maxElevation: null};\n        if (tile?.dem) {\n            minMax.minElevation = tile.dem.min * this.exaggeration;\n            minMax.maxElevation = tile.dem.max * this.exaggeration;\n        }\n        return minMax;\n    }\n\n    /**\n     * The lng/lat to world mapping of the map's projection.\n     */\n    private get _worldCoordinateHelper(): WorldCoordinateHelper {\n        return this._getWorldCoordinateHelper();\n    }\n\n    _getOverscaledTileIDFromLngLatZoom(lnglat: LngLat, zoom: number): { tileID: OverscaledTileID; worldX: number; worldY: number} {\n        const worldCoordinateHelper = this._worldCoordinateHelper;\n        const location = worldCoordinateHelper.wraps ? lnglat.wrap() : lnglat;\n        const worldCoordinate = worldCoordinateHelper.worldFromLngLat(location.lng, location.lat);\n        const worldSize = (1 << zoom) * EXTENT;\n        const worldX = worldCoordinate.x * worldSize;\n        const worldY = worldCoordinate.y * worldSize;\n        const tileX = Math.floor(worldX / EXTENT), tileY = Math.floor(worldY / EXTENT);\n        const tileID = new OverscaledTileID(zoom, 0, zoom, tileX, tileY);\n        return {\n            tileID,\n            worldX,\n            worldY\n        };\n    }\n\n    /** Add an extra frame around the mesh to avoid hairline gaps (stitching) on tile boundaries with different zoomlevels.\n     * @see {@link MapOptions.terrainSkirtLength}\n    */\n    _buildSkirts(vertexArray: Pos3dArray, indexArray: TriangleIndexArray, meshSize: number, delta: number, northPole: boolean, southPole: boolean): void {\n        const offsetTop = vertexArray.length;\n        const offsetTopEdge = 0;\n        const offsetBottom = offsetTop + (meshSize + 1);\n        const offsetBottomEdge = (meshSize + 1) * meshSize;\n        const northY = northPole ? NORTH_POLE_Y : 0;\n        const northZ = northPole ? 0 : 1;\n        const southY = southPole ? SOUTH_POLE_Y : EXTENT;\n        const southZ = southPole ? 0 : 1;\n        for (let x = 0; x <= meshSize; x++) {\n            vertexArray.emplaceBack(x * delta, northY, northZ);\n        }\n        for (let x = 0; x <= meshSize; x++) {\n            vertexArray.emplaceBack(x * delta, southY, southZ);\n        }\n        for (let x = 0; x < meshSize; x++) {\n            indexArray.emplaceBack(offsetBottomEdge + x, offsetBottom + x, offsetBottom + x + 1);\n            indexArray.emplaceBack(offsetBottomEdge + x, offsetBottom + x + 1, offsetBottomEdge + x + 1);\n            indexArray.emplaceBack(offsetTopEdge + x, offsetTop + x + 1, offsetTop + x);\n            indexArray.emplaceBack(offsetTopEdge + x, offsetTopEdge + x + 1, offsetTop + x + 1);\n        }\n        // left-right frame\n        const offsetLeft = vertexArray.length;\n        const offsetRight = offsetLeft + (meshSize + 1) * 2;\n        for (const x of [0, 1]) for (let y = 0; y <= meshSize; y++) for (const z of [0, 1]) {\n            vertexArray.emplaceBack(x * EXTENT, y * delta, z);\n        }\n        for (let y = 0; y < meshSize * 2; y += 2) {\n            indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 1, offsetLeft + y + 3);\n            indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 3, offsetLeft + y + 2);\n            indexArray.emplaceBack(offsetRight + y, offsetRight + y + 3, offsetRight + y + 1);\n            indexArray.emplaceBack(offsetRight + y, offsetRight + y + 2, offsetRight + y + 3);\n        }\n    }\n}\n", "import type {OverscaledTileID} from '../tile/tile_id.ts';\n\n/**\n * What a render-to-texture tile's textures differ in from the state this frame would render them from,\n * least to most severe: `zoom` (the same layers and source tiles, evaluated at another zoom), `sourceTiles`\n * (other source tiles under the terrain tile), `visibleLayers` (a layer entered or left its zoom range) and\n * `revision` (the source data changed, or the textures were rendered without this source).\n *\n * @internal\n */\nexport const RTT_DIFFERENCES = ['none', 'zoom', 'sourceTiles', 'visibleLayers', 'revision'] as const;\nexport type RTTDifference = typeof RTT_DIFFERENCES[number];\n\n/**\n * Immutable value describing the state a render-to-texture tile's textures were rendered from: the source\n * tiles drawn into them, the source data revision, the map zoom (zoom-dependent style properties are\n * evaluated then) and the ids of the layers visible at that zoom.\n *\n * @internal\n */\nexport class RTTFingerprint {\n    private readonly _tileKeys: string;\n    private readonly _revision: number;\n    private readonly _zoom: number;\n    private readonly _visibleLayerIds: string;\n\n    constructor(coords: OverscaledTileID[], revision: number, zoom: number, visibleLayerIds: string) {\n        this._tileKeys = coords.map(c => c.key).sort().join();\n        this._revision = revision;\n        this._zoom = zoom;\n        this._visibleLayerIds = visibleLayerIds;\n    }\n\n    /**\n     * The most severe difference between this fingerprint and the one the textures were rendered from,\n     * `none` when they match. A missing fingerprint counts as a revision difference.\n     */\n    difference(other: RTTFingerprint | undefined): RTTDifference {\n        if (this._revision !== other?._revision) return 'revision';\n        if (this._visibleLayerIds !== other._visibleLayerIds) return 'visibleLayers';\n        if (this._tileKeys !== other._tileKeys) return 'sourceTiles';\n        return this._zoom === other._zoom ? 'none' : 'zoom';\n    }\n}\n", "import {Color} from '@maplibre/maplibre-gl-style-spec';\nimport {drawTerrain} from './draw/draw_terrain.ts';\nimport {setFrameUniformWorldSize} from './frame_uniform_buffer.ts';\nimport {ImageSource} from '../source/image_source.ts';\nimport {RTT_DIFFERENCES, RTTFingerprint, type RTTDifference} from './rtt_fingerprint.ts';\nimport {isCustomStyleLayer} from '../style/style_layer/custom_style_layer.ts';\n\nimport type {Tile} from '../tile/tile.ts';\nimport type {OverscaledTileID} from '../tile/tile_id.ts';\nimport type {Style} from '../style/style.ts';\nimport type {Terrain} from '../render/terrain.ts';\nimport type {Texture} from './texture.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {Painter} from '../render/painter.ts';\nimport type {FrameRenderContext} from '../render/frame_render_context.ts';\n\n/**\n * lookup table which layers should rendered to texture\n */\nconst LAYERS_TO_TEXTURES: { [keyof in StyleLayer['type']]?: boolean } = {\n    background: true,\n    fill: true,\n    line: true,\n    raster: true,\n    hillshade: true,\n    'color-relief': true\n};\n\n/**\n * Returns the key under which a tile keeps the fingerprint of the layer, which is the layer's source, or its id for a custom layer.\n */\nfunction rttFingerprintKey(layer: StyleLayer): string | undefined {\n    return isCustomStyleLayer(layer) ? `custom-layer:${layer.id}` : layer.source;\n}\n\n/**\n * Whether the layer is drawn into the terrain tiles' textures rather than onto the map: the layer types above, and\n * custom layers that implement `renderToTerrainTile`.\n */\nfunction isRenderedToTexture(layer: StyleLayer): boolean {\n    if (isCustomStyleLayer(layer)) return layer.implementation.renderToTerrainTile !== undefined;\n    return LAYERS_TO_TEXTURES[layer.type] === true;\n}\n\n/**\n * Returns the ids of the layers in each render stack, a run of layers rendered to texture that ends at a layer\n * that is not.\n */\nfunction getRenderStacks(style: Style, layerIds: string[]): string[][] {\n    const stacks: string[][] = [];\n    let prevRenderedToTexture = false;\n    for (const layerId of layerIds) {\n        const renderedToTexture = isRenderedToTexture(style._layers[layerId]);\n        if (renderedToTexture && !prevRenderedToTexture) stacks.push([]);\n        if (renderedToTexture) stacks[stacks.length - 1].push(layerId);\n        prevRenderedToTexture = renderedToTexture;\n    }\n    return stacks;\n}\n\n/**\n * @internal\n * Renders RTT-eligible layers into per-tile cached textures, then drapes\n * them onto the terrain mesh. Slots live on each Tile so their lifetime\n * tracks the tile itself; the underlying FBO+texture handles are recycled\n * via the painter's RTT pool.\n */\nexport class RenderToTexture {\n    painter: Painter;\n    terrain: Terrain;\n    /** RTT texture dimension in pixels (tile size × terrain quality factor). */\n    rttSize: number;\n    /**\n     * coordsAscending contains a list of all tiles which should be rendered for one render-to-texture tile\n     * e.g. render 4 raster-tiles with size 256px to the 512px render-to-texture tile\n     */\n    _coordsAscending: {[_: string]: {[_:string]: OverscaledTileID[]}};\n    /**\n     * This frame's fingerprint for each render-to-texture tile, keyed by source id\n     * then tile key. A tile whose stored fingerprint differs has stale textures.\n     */\n    _rttFingerprints: Record<string, Record<string, RTTFingerprint>>;\n    /**\n     * store for render-stacks\n     * a render stack is a set of layers which should be rendered into one texture\n     * every stylesheet can have multiple stacks. A new stack is created if layers which should\n     * not rendered to texture sit between layers which should rendered to texture. e.g. hillshading or symbols\n     */\n    _stacks: string[][];\n    /**\n     * whether the previous processed layer was rendered to texture, to check if a new stack is needed\n     */\n    _prevRenderedToTexture: boolean;\n    /**\n     * a list of tiles that can potentially rendered\n     */\n    _renderableTiles: Tile[];\n    /**\n     * a list of tiles that should be rendered to screen in the next render-call\n     */\n    _rttTiles: Tile[];\n    /**\n     * a list of all layer-ids which should be rendered\n     */\n    _renderableLayerIds: string[];\n    /**\n     * the zoom of the previous prepareForRender call\n     */\n    _lastPrepareZoom: number;\n    /**\n     * whether the render loop needs a follow-up frame to refresh cached textures that were kept this frame:\n     * textures rendered at another zoom, and stale textures beyond the per-frame budget.\n     */\n    needsFollowUpFrame: boolean = false;\n    constructor(painter: Painter, terrain: Terrain) {\n        this.painter = painter;\n        this.terrain = terrain;\n        this.rttSize = terrain.tileManager.tileSize * terrain.qualityFactor;\n    }\n\n    getTexture(tile: Tile): Texture {\n        return tile.getRTT(this._stacks.length - 1).texture;\n    }\n\n    /**\n     * Collects the frame's tiles, layers and source fingerprints and releases the textures that need\n     * re-rendering. Textures that differ only by zoom are kept while the zoom is changing or the map is moving\n     * and re-rendered one tile per frame once it has stopped, nearest to the camera first; textures with other\n     * source tiles under them are re-rendered one per frame too, `needsFollowUpFrame` bringing in the rest.\n     * Textures whose visible layer set changed (a layer entered or left its zoom range) are kept while the zoom\n     * is changing and then all re-rendered in the same frame, since a tile-by-tile change would show; a source\n     * data change re-renders immediately.\n     */\n    prepareForRender(style: Style, zoom: number, isMoving: boolean): void {\n        const zoomChanged = zoom !== this._lastPrepareZoom;\n        this._lastPrepareZoom = zoom;\n        this._stacks = [];\n        this._prevRenderedToTexture = false;\n        this._rttTiles = [];\n        this._renderableTiles = this.terrain.tileManager.getRenderableTiles();\n        this._renderableLayerIds = style._order.filter(id => !style._layers[id].isHidden(zoom));\n        const stacks = getRenderStacks(style, this._renderableLayerIds);\n        const visibleLayerIds = this._renderableLayerIds.join();\n\n        const rttSourceIds = new Set<string>();\n        for (const layerId of this._renderableLayerIds) {\n            const layer = style._layers[layerId];\n            const source = layer.source;\n            if (source && LAYERS_TO_TEXTURES[layer.type]) rttSourceIds.add(source);\n        }\n\n        this._coordsAscending = {};\n        this._rttFingerprints = {};\n        for (const sourceId of rttSourceIds) {\n            const tileManager = style.tileManagers[sourceId];\n            if (!tileManager) continue;\n\n            this._coordsAscending[sourceId] = {};\n            const coordsAscending = this._coordsAscending[sourceId];\n            const source = tileManager.getSource();\n            const terrainTileRanges = source instanceof ImageSource ? source.terrainTileRanges : null;\n            for (const tileID of tileManager.getVisibleCoordinates()) {\n                const keys = this.terrain.tileManager.getTerrainCoords(tileID, terrainTileRanges);\n                for (const key in keys) {\n                    coordsAscending[key] ||= [];\n                    coordsAscending[key].push(keys[key]);\n                }\n            }\n\n            this._rttFingerprints[sourceId] = {};\n            const fingerprints = this._rttFingerprints[sourceId];\n            const revision = tileManager.getState().revision;\n            for (const key in coordsAscending)\n                fingerprints[key] = new RTTFingerprint(coordsAscending[key], revision, zoom, visibleLayerIds);\n        }\n\n        for (const layerId of this._renderableLayerIds) {\n            const layer = style._layers[layerId];\n            if (!isCustomStyleLayer(layer) || !isRenderedToTexture(layer)) continue;\n            const revision = layer.implementation.terrainTileRevision ?? 0;\n            const fingerprints: Record<string, RTTFingerprint> = {};\n            for (const tile of this._renderableTiles) {\n                fingerprints[tile.tileID.key] = new RTTFingerprint([tile.tileID], revision, zoom, visibleLayerIds);\n            }\n            this._rttFingerprints[rttFingerprintKey(layer)] = fingerprints;\n        }\n\n        // check tiles to render\n        this.needsFollowUpFrame = false;\n        const moving = zoomChanged || isMoving;\n        let staleTileReleased = false;\n        for (const tile of this._renderableTiles) {\n            const difference = this._textureDifference(tile);\n            if (difference === 'none') continue;\n            if ((difference === 'zoom' && moving) || (difference === 'visibleLayers' && zoomChanged)) {\n                this.needsFollowUpFrame = true;\n            } else if (difference === 'zoom' || difference === 'sourceTiles') {\n                if (staleTileReleased) this.needsFollowUpFrame = true;\n                else this._releaseChangedTextures(tile, style, stacks);\n                staleTileReleased = true;\n            } else {\n                this._releaseChangedTextures(tile, style, stacks);\n            }\n        }\n    }\n\n    /**\n     * Releases the tile's textures of the stacks whose layers changed, or all of its textures when every stack\n     * changed, which also drops the textures of stacks that the layers no longer form.\n     */\n    _releaseChangedTextures(tile: Tile, style: Style, stacks: string[][]): void {\n        const changedStacks = stacks.map(layerIds => this._hasStackChanged(tile, style, layerIds));\n        if (!changedStacks.includes(false)) {\n            tile.releaseRTT(this.painter);\n            return;\n        }\n        for (const [stack, changed] of changedStacks.entries()) {\n            if (changed) tile.releaseRTTStack(this.painter, stack);\n        }\n    }\n\n    /**\n     * Whether the tile's texture of the stack differs from what this frame would render into it. A stack whose\n     * layers have no fingerprint, background layers only, counts as changed.\n     */\n    _hasStackChanged(tile: Tile, style: Style, layerIds: string[]): boolean {\n        let fingerprinted = false;\n        for (const layerId of layerIds) {\n            const fingerprintKey = rttFingerprintKey(style._layers[layerId]);\n            const frameFingerprint = this._rttFingerprints[fingerprintKey]?.[tile.tileID.key];\n            const tileFingerprint = tile.rttFingerprint[fingerprintKey];\n            if (!frameFingerprint && !tileFingerprint) continue;\n            if (frameFingerprint?.difference(tileFingerprint) !== 'none') return true;\n            fingerprinted = true;\n        }\n        return !fingerprinted;\n    }\n\n    /**\n     * The most severe difference, over the sources rendered to texture, between the tile's cached textures\n     * and what this frame would render into them.\n     */\n    _textureDifference(tile: Tile): RTTDifference {\n        let worst: RTTDifference = 'none';\n        for (const source in this._rttFingerprints) {\n            const frameFingerprint = this._rttFingerprints[source][tile.tileID.key];\n            if (!frameFingerprint) continue;\n            const difference = frameFingerprint.difference(tile.rttFingerprint[source]);\n            if (RTT_DIFFERENCES.indexOf(difference) > RTT_DIFFERENCES.indexOf(worst)) worst = difference;\n        }\n        return worst;\n    }\n\n    /**\n     * due that switching textures is relatively slow, the render\n     * layer-by-layer context is not practicable. To bypass this problem\n     * this lines of code stack all layers and later render all at once.\n     * Because of the stylesheet possibility to mixing render-to-texture layers\n     * and 'live'-layers (f.e. symbols) it is necessary to create more stacks. For example\n     * a symbol-layer is in between of fill-layers.\n     * @param layer - the layer to render\n     * @param style - the style the stacked layers and their tile managers come from\n     * @param frameRenderContext - shared state for the current render\n     * @returns if true layer is rendered to texture, otherwise false\n     */\n    renderLayer(layer: StyleLayer, style: Style, frameRenderContext: FrameRenderContext): boolean {\n        if (layer.isHidden(frameRenderContext.transform.zoom)) return false;\n\n        const renderedToTexture = isRenderedToTexture(layer);\n        const painter = this.painter;\n        const isLastLayer = this._renderableLayerIds[this._renderableLayerIds.length - 1] === layer.id;\n\n        // remember background, fill, line & raster layer to render into a stack\n        if (renderedToTexture) {\n            // create a new stack if previous layer was not rendered to texture (f.e. symbols)\n            if (!this._prevRenderedToTexture) this._stacks.push([]);\n            // push current render-to-texture layer to render-stack\n            this._prevRenderedToTexture = true;\n            this._stacks[this._stacks.length - 1].push(layer.id);\n            // rendering is done later, all in once\n            if (!isLastLayer) return true;\n        }\n\n        // in case a stack is finished render all collected stack-layers into a texture\n        if (this._prevRenderedToTexture || (renderedToTexture && isLastLayer)) {\n            this._prevRenderedToTexture = renderedToTexture;\n            const stack = this._stacks.length - 1, layers = this._stacks[stack] || [];\n            frameRenderContext.isRenderingToTexture = true;\n            setFrameUniformWorldSize(painter.context.frameUniformBuffer, this.rttSize, this.rttSize);\n            for (const tile of this._renderableTiles) {\n                this._rttTiles.push(tile);\n                // Cache hit: this tile already has a RTT object for this stack from a previous frame.\n                if (tile.getRTT(stack)) continue;\n                const obj = tile.acquireRTT(painter, stack, this.rttSize);\n                painter.bindRTT(obj);\n                painter.context.clear({color: Color.transparent, stencil: 0});\n                frameRenderContext.invalidateTileClippingMasks();\n                for (const layerId of layers) {\n                    const layer = style._layers[layerId];\n                    const coords = layer.source ? this._coordsAscending[layer.source][tile.tileID.key] : [tile.tileID];\n                    painter.context.viewport.set([0, 0, this.rttSize, this.rttSize]);\n                    frameRenderContext.renderTileClippingMasks(layer, coords);\n                    painter.renderLayer(painter, style.tileManagers[layer.source], layer, coords, frameRenderContext);\n                    const fingerprintKey = rttFingerprintKey(layer);\n                    if (fingerprintKey) tile.rttFingerprint[fingerprintKey] = this._rttFingerprints[fingerprintKey][tile.tileID.key];\n                }\n                obj.texture.generateMipmap();\n            }\n            frameRenderContext.isRenderingToTexture = false;\n            setFrameUniformWorldSize(painter.context.frameUniformBuffer, painter.context.gl.drawingBufferWidth, painter.context.gl.drawingBufferHeight);\n            drawTerrain(this.painter, this.terrain, this._rttTiles, frameRenderContext);\n            this._rttTiles = [];\n\n            return renderedToTexture;\n        }\n\n        return false;\n    }\n\n}\n", "export const defaultLocale = {\n    'AttributionControl.ToggleAttribution': 'Toggle attribution',\n    'AttributionControl.MapFeedback': 'Map feedback',\n    'FullscreenControl.Enter': 'Enter fullscreen',\n    'FullscreenControl.Exit': 'Exit fullscreen',\n    'GeolocateControl.FindMyLocation': 'Find my location',\n    'GeolocateControl.LocationNotAvailable': 'Location not available',\n    'LogoControl.Title': 'MapLibre logo',\n    'Map.Title': 'Map',\n    'Marker.Title': 'Map marker',\n    'NavigationControl.ResetBearing': 'Drag to rotate map, click to reset north',\n    'NavigationControl.ZoomIn': 'Zoom in',\n    'NavigationControl.ZoomOut': 'Zoom out',\n    'Popup.Close': 'Close popup',\n    'ScaleControl.Feet': 'ft',\n    'ScaleControl.Meters': 'm',\n    'ScaleControl.Kilometers': 'km',\n    'ScaleControl.Miles': 'mi',\n    'ScaleControl.NauticalMiles': 'nm',\n    'GlobeControl.Enable': 'Enable globe',\n    'GlobeControl.Disable': 'Disable globe',\n    'TerrainControl.Enable': 'Enable terrain',\n    'TerrainControl.Disable': 'Disable terrain',\n    'CooperativeGesturesHandler.WindowsHelpText': 'Use Ctrl + scroll to zoom the map',\n    'CooperativeGesturesHandler.MacHelpText': 'Use ⌘ + scroll to zoom the map',\n    'CooperativeGesturesHandler.MobileHelpText': 'Use two fingers to move the map',\n};\n", "import {ensureError, extend, warnOnce, uniqueId, isImageBitmap, type Complete, pick, type Subscription} from '../util/util.ts';\nimport {browser} from '../util/browser.ts';\nimport {now} from '../util/time_control.ts';\nimport {DOM} from '../util/dom.ts';\nimport packageJSON from '../../package.json' with {type: 'json'};\nimport {type GetResourceResponse, getJSON} from '../util/ajax.ts';\nimport {getGlobalDispatcher} from '../util/global_dispatcher.ts';\nimport {getGlobalWorkerPool} from '../util/global_worker_pool.ts';\nimport {ImageRequest} from '../util/image_request.ts';\nimport {RequestManager, ResourceType} from '../util/request_manager.ts';\nimport {Style, type StyleSwapOptions, type TransformStyleFunction} from '../style/style.ts';\nimport {validateStyle, validateAndEmit} from '../style/validate_style.ts';\nimport {EvaluationParameters} from '../style/evaluation_parameters.ts';\nimport {Painter} from '../render/painter.ts';\nimport {GPUInitializationError} from '../util/gpu_initialization_error.ts';\nimport {Hash} from './hash.ts';\nimport {HandlerManager} from './handler_manager.ts';\nimport {Camera, type CameraOptions, type CameraUpdateTransformFunction, type FitBoundsOptions, type EaseToOptions, type FlyToOptions, type JumpToOptions, type AnimationOptions, type AnchoredCameraOptions, type CameraForBoundsOptions} from './camera.ts';\nimport {LngLat} from '../geo/lng_lat.ts';\nimport {LngLatBounds} from '../geo/lng_lat_bounds.ts';\nimport Point from '@mapbox/point-geometry';\nimport {AttributionControl, type AttributionControlOptions, defaultAttributionControlOptions} from './control/attribution_control.ts';\nimport {LogoControl} from './control/logo_control.ts';\nimport {RGBAImage} from '../util/image.ts';\nimport {type Event, ErrorEvent, type Listener, Evented} from '../util/evented.ts';\nimport {type MapEventType, type MapLayerEventType, MapMouseEvent, MapSourceDataEvent, MapStyleDataEvent, MapLibreEvent, MapMovementEvent, MapTerrainEvent, MapProjectionEvent, MapContextEvent} from './events.ts';\nimport {TaskQueue} from '../util/task_queue.ts';\nimport {throttle} from '../util/throttle.ts';\nimport {Terrain} from '../render/terrain.ts';\nimport {RenderToTexture} from '../webgl/render_to_texture.ts';\nimport {config} from '../util/config.ts';\nimport {defaultLocale} from './default_locale.ts';\nimport {isAbortError} from '../util/abort_error.ts';\nimport {coveringTiles, type CoveringTilesOptions, createCalculateTileZoomFunction} from '../geo/projection/covering_tiles.ts';\nimport {CanonicalTileID, type OverscaledTileID} from '../tile/tile_id.ts';\nimport {isStyleImageWebGLData} from '../style/style_image.ts';\nimport {getRegisteredProjection} from '../geo/projection/projection_crud.ts';\n\nimport type {PaddingOptions} from '../geo/edge_insets.ts';\nimport type {Source} from '../source/source.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {RequestTransformFunction} from '../util/request_manager.ts';\nimport type {LngLatLike} from '../geo/lng_lat.ts';\nimport type {LngLatBoundsLike} from '../geo/lng_lat_bounds.ts';\nimport type {AddLayerObject, FeatureIdentifier, StyleOptions, StyleSetterOptions} from '../style/style.ts';\nimport type {StyleImage, StyleImageInterface, StyleImageMetadata} from '../style/style_image.ts';\nimport type {PointLike} from './camera.ts';\nimport type {ScrollZoomHandler} from './handler/scroll_zoom.ts';\nimport type {BoxZoomHandler, BoxZoomHandlerOptions} from './handler/box_zoom.ts';\nimport type {AroundCenterOptions, TwoFingersTouchPitchHandler} from './handler/two_fingers_touch.ts';\nimport type {DragRotateHandler, DragRotateOptions} from './handler/shim/drag_rotate.ts';\nimport type {DragPanHandler, DragPanOptions} from './handler/shim/drag_pan.ts';\nimport type {CooperativeGesturesHandler, GestureOptions} from './handler/cooperative_gestures.ts';\nimport type {KeyboardHandler} from './handler/keyboard.ts';\nimport type {DoubleClickZoomHandler} from './handler/shim/dblclick_zoom.ts';\nimport type {TwoFingersTouchZoomRotateHandler} from './handler/shim/two_fingers_touch.ts';\nimport type {TaskID} from '../util/task_queue.ts';\nimport type {\n    FilterSpecification,\n    FontFacesSpecification,\n    StyleSpecification,\n    LightSpecification,\n    SourceSpecification,\n    TerrainSpecification,\n    ProjectionSpecification,\n    SkySpecification,\n    AllPaintProperties,\n    AllLayoutProperties,\n} from '@maplibre/maplibre-gl-style-spec';\nimport type {CanvasSourceSpecification} from '../source/canvas_source.ts';\nimport type {GeoJSONFeature, MapGeoJSONFeature} from '../util/vectortile_to_geojson.ts';\nimport type {ControlPosition, IControl} from './control/control.ts';\nimport type {QueryRenderedFeaturesOptions, QuerySourceFeatureOptions} from '../source/query_features.ts';\nimport type {ITransform, TransformConstrainFunction} from '../geo/transform_interface.ts';\nimport type {ICameraHelper} from '../geo/projection/camera_helper.ts';\n\nconst version = packageJSON.version;\n\nexport type ContextType = 'webgl2';\n/** @deprecated Use {@link ContextType} instead. */\nexport type WebGLSupportedVersions = ContextType | undefined;\nexport type WebGLContextAttributesWithType = WebGLContextAttributes & {contextType?: ContextType};\n\n/**\n * The {@link Map} options object.\n */\nexport type MapOptions = {\n    /**\n     * 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.\n     * For example, `https://example.com#2.59/39.26/53.07/-24.1/60`.\n     *\n     * An additional string may optionally be provided as an alternative to indicate a parameter-styled hash.\n     * For example, passing `hash: \"foo\"` will produce a hash like `https://example.com#foo=2.59/39.26/53.07/-24.1/60`.\n     * This is usefull for allowing multiple maps or other state.\n     * @defaultValue false\n     */\n    hash?: boolean | string;\n    /**\n     * If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.\n     * @defaultValue true\n     */\n    interactive?: boolean;\n    /**\n     * The HTML element in which MapLibre GL JS will render the map, or the element's string `id`. The specified element must have no children.\n     */\n    container: HTMLElement | string;\n    /**\n     * The threshold, measured in degrees, that determines when the map's\n     * bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates\n     * the map within 7 degrees of north, the map will automatically snap to exact north.\n     * @defaultValue 7\n     */\n    bearingSnap?: number;\n    /**\n     * The step increment the zoom level will snap to.\n     * For example, if `zoomSnap` is 1, the map will snap to whole integers during discrete zoom operations.\n     * If set to 0, zooming is continuous.\n     * @defaultValue 0\n     */\n    zoomSnap?: number;\n    /**\n     * If set, an {@link AttributionControl} will be added to the map with the provided options.\n     * To disable the attribution control, pass `false`.\n     * !!! note\n     *     Showing the logo of MapLibre is not required for using MapLibre.\n     * @defaultValue compact: true, customAttribution: \"MapLibre ...\".\n     */\n    attributionControl?: false | AttributionControlOptions;\n    /**\n     * If `true`, the MapLibre logo will be shown.\n     */\n    maplibreLogo?: boolean;\n    /**\n     * A string representing the position of the MapLibre wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, or `bottom-right`.\n     * @defaultValue 'bottom-left'\n     */\n    logoPosition?: ControlPosition;\n    /**\n     * Set of WebGLContextAttributes that are applied to the WebGL context of the map.\n     * See https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext for more details.\n     * `contextType` is restricted to `'webgl2'`. This option is kept as a forward-looking API for future WebGPU support.\n     * @defaultValue antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: false, failIfMajorPerformanceCaveat: false, desynchronized: false, contextType: 'webgl2'\n     */\n    canvasContextAttributes?: WebGLContextAttributesWithType;\n    /**\n     * If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers.\n     * @defaultValue true\n     */\n    refreshExpiredTiles?: boolean;\n    /**\n     * If set, the map will be constrained to the given bounds.\n     */\n    maxBounds?: LngLatBoundsLike;\n    /**\n     * If `true`, the \"scroll to zoom\" interaction is enabled. {@link AroundCenterOptions} are passed as options to {@link ScrollZoomHandler.enable}.\n     * @defaultValue true\n     */\n    scrollZoom?: boolean | AroundCenterOptions;\n    /**\n     * The minimum zoom level of the map. Users cannot zoom out beyond this level. (-2 – 24)\n     *\n     * With the mercator projection, the map may stop zooming out before it reaches this level, because the world\n     * has to cover the height of the map: a map 512px tall cannot zoom out below zoom 0. {@link Map.getMinZoom}\n     * with `constrained` set to `true` returns the level the map can actually reach.\n     * @defaultValue -2\n     */\n    minZoom?: number | null;\n    /**\n     * The maximum zoom level of the map. Users cannot zoom in beyond this level. (0–24)\n     * @defaultValue 22\n     */\n    maxZoom?: number | null;\n    /**\n     * The minimum pitch of the map (0-180).\n     * @defaultValue 0\n     */\n    minPitch?: number | null;\n    /**\n     * The maximum pitch of the map (0-180).\n     * @defaultValue 60\n     */\n    maxPitch?: number | null;\n    /**\n     * The pitch above which to apply anisotropic filtering to the map's raster layers (0-180).\n     * @defaultValue 20\n     */\n    anisotropicFilterPitch?: number | null;\n    /**\n     * If `true`, the \"box zoom\" interaction is enabled (see {@link BoxZoomHandler}).\n     * An `Object` value configures {@link BoxZoomHandler} options.\n     * If `boxZoomEnd` is provided, the callback runs instead of the default fit-to-box zoom.\n     * @defaultValue true\n     */\n    boxZoom?: boolean | BoxZoomHandlerOptions;\n    /**\n     * If `true`, the \"drag to rotate\" interaction is enabled (see {@link DragRotateHandler}). An `Object` value is passed as options to {@link DragRotateHandler.enable}.\n     * @defaultValue true\n     */\n    dragRotate?: boolean | DragRotateOptions;\n    /**\n     * If `true`, the \"drag to pan\" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler.enable}.\n     * @defaultValue true\n     */\n    dragPan?: boolean | DragPanOptions;\n    /**\n     * If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}).\n     * @defaultValue true\n     */\n    keyboard?: boolean;\n    /**\n     * If `true`, the \"double click to zoom\" interaction is enabled (see {@link DoubleClickZoomHandler}).\n     * @defaultValue true\n     */\n    doubleClickZoom?: boolean;\n    /**\n     * If `true`, the \"pinch to rotate and zoom\" interaction is enabled. An `Object` value is passed as options to {@link TwoFingersTouchZoomRotateHandler.enable}.\n     * @defaultValue true\n     */\n    touchZoomRotate?: boolean | AroundCenterOptions;\n    /**\n     * If `true`, the \"drag to pitch\" interaction is enabled. An `Object` value is passed as options to {@link TwoFingersTouchPitchHandler.enable}.\n     * @defaultValue true\n     */\n    touchPitch?: boolean | AroundCenterOptions;\n    /**\n     * If `true` or set to an options object, the map is only accessible on desktop while holding Command/Ctrl and only accessible on mobile with two fingers. Interacting with the map using normal gestures will trigger an informational screen. With this option enabled, \"drag to pitch\" requires a three-finger gesture. Cooperative gestures are disabled when a map enters fullscreen using {@link FullscreenControl}.\n     * @defaultValue false\n     */\n    cooperativeGestures?: GestureOptions;\n    /**\n     * If `true`, the map will automatically resize when the browser window resizes.\n     * @defaultValue true\n     */\n    trackResize?: boolean;\n    /**\n     * The initial geographical centerpoint of the map. If `center` is not specified in the constructor options, MapLibre 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]`\n     * !!! note\n     *     MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.\n     * @defaultValue [0, 0]\n     */\n    center?: LngLatLike;\n    /**\n     * The elevation of the initial geographical centerpoint of the map, in meters above sea level. If `elevation` is not specified in the constructor options, it will default to `0`.\n     * @defaultValue 0\n     */\n    elevation?: number;\n    /**\n     * The initial zoom level of the map. If `zoom` is not specified in the constructor options, MapLibre 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`.\n     * @defaultValue 0\n     */\n    zoom?: number;\n    /**\n     * The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, MapLibre 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`.\n     * @defaultValue 0\n     */\n    bearing?: number;\n    /**\n     * The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-85). If `pitch` is not specified in the constructor options, MapLibre 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`. Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n     * @defaultValue 0\n     */\n    pitch?: number;\n    /**\n     * The initial roll angle of the map, measured in degrees counter-clockwise about the camera boresight. If `roll` is not specified in the constructor options, MapLibre 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`.\n     * @defaultValue 0\n     */\n    roll?: number;\n    /**\n     * If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n     *\n     * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n     * container, there will be blank space beyond 180 and -180 degrees longitude.\n     * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n     * map and the other on the left edge of the map) at every zoom level.\n     * @defaultValue true\n     */\n    renderWorldCopies?: boolean;\n    /**\n     * 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 which can be set using `maxTileCacheZoomLevels` constructor options.\n     * @defaultValue null\n     */\n    maxTileCacheSize?: number | null;\n    /**\n     * The maximum number of zoom levels for which to store tiles for a given source. Tile cache dynamic size is calculated by multiplying `maxTileCacheZoomLevels` with the approximate number of tiles in the viewport for a given source.\n     * @defaultValue 5\n     */\n    maxTileCacheZoomLevels?: number;\n    /**\n     * 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.\n     * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties.\n     * @defaultValue null\n     */\n    transformRequest?: RequestTransformFunction | null;\n    /**\n     * A callback run before the map's camera is moved due to user input or animation. The callback can be used to modify the new center, zoom, pitch and bearing.\n     * Expected to return an object containing center, zoom, pitch or bearing values to overwrite.\n     * @defaultValue null\n     */\n    transformCameraUpdate?: CameraUpdateTransformFunction | null;\n    /**\n     * A callback that overrides how the map constrains the viewport's lnglat and zoom to respect the longitude and latitude bounds.\n     * @see [Customize the map transform constrain](https://maplibre.org/maplibre-gl-js/docs/examples/customize-the-map-transform-constrain/)\n     * Expected to return an object containing center and zoom.\n     * @defaultValue null\n     */\n    transformConstrain?: TransformConstrainFunction | null;\n    /**\n     * 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).\n     * For an example, see https://maplibre.org/maplibre-gl-js/docs/examples/locale-switching/\n     * Alternatively, search the official plugins page for plugins related to localization.\n     * @defaultValue null\n     */\n    locale?: Record<string, string>;\n    /**\n     * Controls the duration of the fade-in/fade-out animation for label collisions after initial map load, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading.\n     * @defaultValue 300\n     */\n    fadeDuration?: number;\n    /**\n     * 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.\n     * @defaultValue true\n     */\n    crossSourceCollisions?: boolean;\n    /**\n     * 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.\n     * @defaultValue false\n     */\n    collectResourceTiming?: boolean;\n    /**\n     * 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).\n     * @defaultValue 3\n     */\n    clickTolerance?: number;\n    /**\n     * The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options.\n     */\n    bounds?: LngLatBoundsLike;\n    /**\n     * A {@link FitBoundsOptions} options object to use _only_ when fitting the initial `bounds` provided above.\n     */\n    fitBoundsOptions?: FitBoundsOptions;\n    /**\n     * Defines a CSS\n     * font-family for locally overriding generation of Chinese, Japanese, and Korean characters.\n     * For these characters, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).\n     * Set to `false`, to enable font settings from the map's style for these glyph ranges.\n     * The purpose of this option is to avoid bandwidth-intensive glyph server requests.\n     * @see [Use locally generated ideographs](https://maplibre.org/maplibre-gl-js/docs/examples/use-locally-generated-ideographs/)\n     * @defaultValue 'sans-serif'\n     */\n    localIdeographFontFamily?: string | false;\n    /**\n     * The map's MapLibre style. This must be a JSON object conforming to\n     * the schema described in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/),\n     * or a URL to such JSON.\n     * When the style is not specified, calling {@link Map.setStyle} is required to render the map.\n     */\n    style?: StyleSpecification | string;\n    /**\n     * If `false`, the map's pitch (tilt) control with \"drag to rotate\" interaction will be disabled.\n     * @defaultValue true\n     */\n    pitchWithRotate?: boolean;\n    /**\n     * If `false`, the map's roll control with \"drag to rotate\" interaction will be disabled.\n     * @defaultValue false\n     */\n    rollEnabled?: boolean;\n    /**\n     * Degrees the map's bearing changes per pixel of horizontal drag when rotating.\n     * @defaultValue 0.8\n     */\n    rotateSpeed?: number;\n    /**\n     * Degrees the map's pitch changes per pixel of vertical drag. Negative, so that\n     * dragging up pitches the map toward the horizon.\n     * @defaultValue -0.5\n     */\n    pitchSpeed?: number;\n    /**\n     * If `true`, gesture inertia (such as panning) is disabled. If not provided, gesture inertia defaults to the user's device settings.\n     * @defaultValue undefined\n     */\n    reduceMotion?: boolean | undefined;\n    /**\n     * The pixel ratio.\n     * The canvas' `width` attribute will be `container.clientWidth * pixelRatio` and its `height` attribute will be `container.clientHeight * pixelRatio`. Defaults to `devicePixelRatio` if not specified.\n     */\n    pixelRatio?: number;\n    /**\n     * If false, style validation will be skipped.\n     * Useful in production environments due to enabling tree-shaking of the validation code in some environments and minor performance improvements.\n     * Disabling this option comes at the cost of less clear error messages\n     * @defaultValue true\n     */\n    validateStyle?: boolean;\n    /**\n     * Defines an initial global state for the map style. It overrides the defaults defined in the map style, as if {@link Map.setGlobalStateProperty} was called after loading the map. Subsequent calls to {@link Map.setStyle} will use the same defaults if the {@link StyleOptions.globalState} option is not set.\n     */\n    globalState?: Record<string, any>;\n    /**\n     * TransformStyleFunction is a convenience function that allows to modify a style after it is fetched but before it is committed to the map state. Refer to {@link TransformStyleFunction}. Subsequent calls to {@link Map.setStyle} will use the same transform if the {@link StyleSwapOptions.transformStyle} option is not set.\n     */\n    transformStyle?: TransformStyleFunction;\n    /**\n     * The canvas' `width` and `height` max size. The values are passed as an array where the first element is max width and the second element is max height.\n     * You shouldn't set this above WebGl `MAX_TEXTURE_SIZE`.\n     * A larger canvas is not refused: the pixel ratio is lowered to fit and a warning is logged once.\n     * @defaultValue [4096, 4096].\n     */\n    maxCanvasSize?: [number, number];\n    /**\n     * Determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one.\n     * * If `true`, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom.\n     * * If `false`, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time.\n     * @defaultValue true\n     */\n    cancelPendingTileRequestsWhileZooming?: boolean;\n    /**\n     * If true, the elevation of the center point will automatically be set to the terrain elevation\n     * (or zero if terrain is not enabled). If false, the elevation of the center point will default\n     * to sea level and will not automatically update. Defaults to true. Needs to be set to false to\n     * keep the camera above ground when pitch \\> 90 degrees.\n     */\n    centerClampedToGround?: boolean;\n    /**\n     * Controls the length of the vertical extensions which are added to the edges of terrain tiles.\n     *\n     * If the skirts are introducing visually unappealing vertical artifacts, consider avoiding transparent or semi-transparent backgrounds,\n     * for example, by having the first layer be a background layer with a [`background-color`](https://maplibre.org/maplibre-style-spec/layers/#background-color).\n     * If that is impossible or insufficient, you can entirely disable skirts,\n     * at the cost of potentially introducing some horizontal hairline gaps (stitches) on tile boundaries with different zoomlevels for some terrain datasets.\n     *\n     * - `\"none\"` disables skirts entirely.\n     * - `\"auto\"` renders skirts with an automatically chosen length.\n     * @defaultValue \"auto\"\n     */\n    terrainSkirtLength?: 'none' | 'auto';\n    /**\n     * Defines the number of zoom level that will overscale instead of split tiles below (inclusive) a map's `maxZoom`.\n     * When `undefined`, all zoom levels after source's max zoom will be overscaled.\n     *\n     * This can help in reducing the size of the overscaling and improve performance in high zoom levels.\n     * The drawback is that it changes rendering for polygon centered labels and changes the results of query rendered features.\n     *\n     * For example if map's `maxZoom` is 20, the source's `maxzoom` is 10 (tiles are avaliable until zoom 10) and `zoomLevelsToOverscale` is set to 3:\n     * - The zoom levels of 20, 19, 18 will be overscaled.\n     * - The zoom levels 11 to 17 will be split.\n     * @defaultValue 4\n     */\n    zoomLevelsToOverscale?: number;\n    /**\n     * Determines the rotation interaction model:\n     * - When true: Uses \"Orbital\" logic where rotation is relative to the pivot center.\n     *   Dragging right at the top rotates clockwise, while dragging right at the bottom\n     *   rotates counter-clockwise (like spinning a physical globe).\n     * - When false: Uses \"Linear\" logic where horizontal mouse movement translates directly\n     *   to bearing change regardless of cursor position.\n     *\n     * @deprecated Use {@link MapOptions.dragRotate} instead, with `{around: 'center', movement: 'circular'}` for `true`\n     * and `{around: 'center', movement: 'linear'}` for `false`. Its `movement` takes precedence over this option when both are passed.\n     */\n    aroundCenter?: boolean;\n};\n\nexport type AddImageOptions = {\n\n};\n\n/**\n * Image data accepted by {@link Map.addImage}.\n */\nexport type StyleImageSource = HTMLImageElement | ImageBitmap | ImageData | {\n    width: number;\n    height: number;\n    data: Uint8Array | Uint8ClampedArray;\n} | StyleImageInterface;\n\n/**\n * Callback used by {@link Map.setMissingStyleImageResolver} to resolve missing style images,\n * typically by calling {@link Map.addImage}. MapLibre awaits the returned promise before\n * treating the image as missing.\n */\nexport type MissingStyleImageResolver = (id: string) => void | Promise<void>;\n\n// This type is used inside map since all properties are assigned a default value.\nexport type CompleteMapOptions = Complete<MapOptions>;\n\ntype DelegatedListener = {\n    layers: string[];\n    listener: Listener;\n    delegates: {[E in keyof MapEventType]?: Delegate<MapEventType[E]>};\n};\n\ntype Delegate<E extends Event = Event> = (e: E) => void;\n\ntype StyleSnapshot = {\n    style: StyleSpecification | null;\n    images: {[_: string]: StyleImage};\n};\n\nconst defaultMinZoom = -2;\nconst defaultMaxZoom = 22;\n\n// the default values, but also the valid range\nconst defaultMinPitch = 0;\nconst defaultMaxPitch = 60;\nconst defaultAnisotropicFilterPitch = 20;\n\n// use this variable to check maxPitch and anisotropicFilterPitch for validity\nconst maxPitchThreshold = 180;\n\nconst defaultOptions: Readonly<Partial<MapOptions>> = {\n    hash: false,\n    interactive: true,\n    bearingSnap: 7,\n    zoomSnap: 0,\n    attributionControl: defaultAttributionControlOptions,\n    maplibreLogo: false,\n    refreshExpiredTiles: true,\n\n    canvasContextAttributes: {\n        antialias: false,\n        preserveDrawingBuffer: false,\n        powerPreference: 'high-performance',\n        failIfMajorPerformanceCaveat: false,\n        desynchronized: false,\n        contextType: undefined\n    },\n\n    scrollZoom: true,\n    minZoom: defaultMinZoom,\n    maxZoom: defaultMaxZoom,\n    minPitch: defaultMinPitch,\n    maxPitch: defaultMaxPitch,\n\n    boxZoom: true,\n    dragRotate: true,\n    dragPan: true,\n    keyboard: true,\n    doubleClickZoom: true,\n    touchZoomRotate: true,\n    touchPitch: true,\n    cooperativeGestures: false,\n\n    trackResize: true,\n\n    center: [0, 0],\n    elevation: 0,\n    zoom: 0,\n    bearing: 0,\n    pitch: 0,\n    roll: 0,\n\n    renderWorldCopies: true,\n    maxTileCacheSize: null,\n    maxTileCacheZoomLevels: config.MAX_TILE_CACHE_ZOOM_LEVELS,\n    transformRequest: null,\n    transformCameraUpdate: null,\n    transformConstrain: null,\n    fadeDuration: 300,\n    crossSourceCollisions: true,\n    clickTolerance: 3,\n    localIdeographFontFamily: 'sans-serif',\n    pitchWithRotate: true,\n    rollEnabled: false,\n    rotateSpeed: 0.8,\n    pitchSpeed: -0.5,\n    reduceMotion: undefined,\n    validateStyle: true,\n    globalState: undefined,\n    transformStyle: undefined,\n    /**Because GL MAX_TEXTURE_SIZE is usually at least 4096px. */\n    maxCanvasSize: [4096, 4096],\n    cancelPendingTileRequestsWhileZooming: true,\n    centerClampedToGround: true,\n    terrainSkirtLength: 'auto',\n    zoomLevelsToOverscale: 4,\n    anisotropicFilterPitch: defaultAnisotropicFilterPitch,\n};\n\n/**\n * The `Map` object represents the map on your page. It exposes methods\n * and properties that enable you to programmatically change the map,\n * and fires events as users interact with it.\n *\n * You create a `Map` by specifying a `container` and other options, see {@link MapOptions} for the full list.\n * Then MapLibre GL JS initializes the map on the page and returns your `Map` object.\n *\n * @group Main\n *\n * @example\n * ```ts\n * const map = new Map({\n *   container: 'map',\n *   center: [-122.420679, 37.772537],\n *   zoom: 13,\n *   style: style_object,\n *   hash: true,\n *   transformRequest: (url, resourceType) => {\n *     if (resourceType === 'Source' && url.startsWith('http://myHost')) {\n *       return {\n *        url: url.replace('http', 'https'),\n *        headers: { 'my-custom-header': true},\n *        credentials: 'include', // Include cookies for cross-origin requests\n *      }\n *     }\n *   }\n * });\n * ```\n * @see [Display a map](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-map/)\n */\nexport class Map extends Evented<MapEventType> {\n    terrain: Terrain;\n    style: Style;\n    painter: Painter;\n    _camera: Camera;\n    _handlers: HandlerManager;\n    _container: HTMLElement;\n    _canvasContainer: HTMLElement;\n    _controlContainer: HTMLElement;\n    _controlPositions: Partial<Record<ControlPosition, HTMLElement>>;\n    _interactive: boolean;\n    _showTileBoundaries: boolean;\n    _showCollisionBoxes: boolean;\n    _showPadding: boolean;\n    _showOverdrawInspector: boolean;\n    _repaint: boolean;\n    _vertices: boolean;\n    _canvas: HTMLCanvasElement;\n    _maxTileCacheSize: number | null;\n    _maxTileCacheZoomLevels: number;\n    _frameRequest: AbortController;\n    _styleDirty: boolean;\n    _sourcesDirty: boolean;\n    _placementDirty: boolean;\n    _anisotropicFilterPitch: number;\n\n    _loaded: boolean;\n    _idleTriggered = false;\n    // accounts for placement finishing as well\n    _fullyLoaded: boolean;\n    _trackResize: boolean;\n    _resizeObserver: ResizeObserver;\n    _canvasContextAttributes: WebGLContextAttributesWithType;\n    _refreshExpiredTiles: boolean;\n    _hash: Hash;\n    _delegatedListeners: Record<keyof MapEventType, DelegatedListener[]>;\n    _fadeDuration: number;\n    _crossSourceCollisions: boolean;\n    _crossFadingFactor = 1;\n    _collectResourceTiming: boolean;\n    _renderTaskQueue: TaskQueue = new TaskQueue();\n    _controls: IControl[] = [];\n    _mapId: number = uniqueId();\n    _localIdeographFontFamily: string | false;\n    _validateStyle: boolean;\n    _initialGlobalState: Record<string, any>;\n    _transformStyle: TransformStyleFunction | undefined;\n    _styleUrl: string | null = null;\n    _requestManager: RequestManager;\n    _locale: Record<string, string>;\n    _removed: boolean;\n    _diffStyleRequest: AbortController;\n    _clickTolerance: number;\n    _overridePixelRatio: number | null | undefined;\n    _maxCanvasSize: [number, number];\n    _clampedPixelRatio: number;\n    _terrainDataCallback: (e: MapStyleDataEvent | MapSourceDataEvent) => void;\n    _missingStyleImageResolver: MissingStyleImageResolver | null = null;\n    /** @internal */\n    _zoomLevelsToOverscale: number | undefined;\n    _terrainSkirtLength: 'none' | 'auto';\n\n    /**\n     * @internal\n     * The window that owns the map container element, for cross-window support.\n     * Returns `typeof window` to include global constructors like ResizeObserver.\n     */\n    get _ownerWindow(): typeof window {\n        return this._container?.ownerDocument?.defaultView || window;\n    }\n\n    /**\n     * @internal\n     * image queue throttling handle. To be used later when clean up\n     */\n    _imageQueueHandle: number;\n\n    /**\n     * @internal\n     * The style snapshot taken at context loss, held until context restoration rebuilds from it.\n     */\n    _lostContextSnapshot: StyleSnapshot = {\n        style: null,\n        images: {}\n    };\n\n    /**\n     * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad.\n     * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section.\n     */\n    scrollZoom: ScrollZoomHandler;\n\n    /**\n     * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed.\n     * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section.\n     */\n    boxZoom: BoxZoomHandler;\n\n    /**\n     * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right\n     * mouse button or with the Control key pressed. Find more details and examples using `dragRotate`\n     * in the {@link DragRotateHandler} section.\n     */\n    dragRotate: DragRotateHandler;\n\n    /**\n     * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture.\n     * Find more details and examples using `dragPan` in the {@link DragPanHandler} section.\n     */\n    dragPan: DragPanHandler;\n\n    /**\n     * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard\n     * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section.\n     */\n    keyboard: KeyboardHandler;\n\n    /**\n     * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking.\n     * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section.\n     */\n    doubleClickZoom: DoubleClickZoomHandler;\n\n    /**\n     * The map's {@link TwoFingersTouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures.\n     * Find more details and examples using `touchZoomRotate` in the {@link TwoFingersTouchZoomRotateHandler} section.\n     */\n    touchZoomRotate: TwoFingersTouchZoomRotateHandler;\n\n    /**\n     * The map's {@link TwoFingersTouchPitchHandler}, which allows the user to pitch the map with touch gestures.\n     * Find more details and examples using `touchPitch` in the {@link TwoFingersTouchPitchHandler} section.\n     */\n    touchPitch: TwoFingersTouchPitchHandler;\n\n    /**\n     * The map's {@link CooperativeGesturesHandler}, which allows the user to see cooperative gesture info when user tries to zoom in/out.\n     * Find more details and examples using `cooperativeGestures` in the {@link CooperativeGesturesHandler} section.\n     */\n    cooperativeGestures: CooperativeGesturesHandler;\n\n    /**\n     * The map's property which determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one.\n     * * If `true`, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom.\n     * * If `false`, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time.\n     * @defaultValue true\n     */\n    cancelPendingTileRequestsWhileZooming: boolean;\n\n    constructor(options: MapOptions) {\n        super();\n        getGlobalWorkerPool().on('restart', this._handleWorkersRestarted);\n        getGlobalDispatcher().watchWorkers();\n        const resolvedOptions = {...defaultOptions, ...options, canvasContextAttributes: {\n            ...defaultOptions.canvasContextAttributes,\n            ...options.canvasContextAttributes\n        }} as CompleteMapOptions;\n\n        if (resolvedOptions.minZoom != null && resolvedOptions.maxZoom != null && resolvedOptions.minZoom > resolvedOptions.maxZoom) {\n            throw new Error('maxZoom must be greater than or equal to minZoom');\n        }\n\n        if (resolvedOptions.minPitch != null && resolvedOptions.maxPitch != null && resolvedOptions.minPitch > resolvedOptions.maxPitch) {\n            throw new Error('maxPitch must be greater than or equal to minPitch');\n        }\n\n        if (resolvedOptions.minPitch != null && resolvedOptions.minPitch < defaultMinPitch) {\n            throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);\n        }\n\n        if (resolvedOptions.maxPitch != null && resolvedOptions.maxPitch > maxPitchThreshold) {\n            throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`);\n        }\n\n        this._camera = new Camera({\n            minZoom: resolvedOptions.minZoom,\n            maxZoom: resolvedOptions.maxZoom,\n            minPitch: resolvedOptions.minPitch,\n            maxPitch: resolvedOptions.maxPitch,\n            bearingSnap: resolvedOptions.bearingSnap,\n            zoomSnap: resolvedOptions.zoomSnap,\n            renderWorldCopies: resolvedOptions.renderWorldCopies,\n            centerClampedToGround: resolvedOptions.centerClampedToGround,\n            terrain: this.terrain,\n            transformConstrain: resolvedOptions.transformConstrain,\n            requestRenderFrame: (callback) => this._requestRenderFrame(callback),\n            cancelRenderFrame: (id) => this._cancelRenderFrame(id),\n            transformCameraUpdate: resolvedOptions.transformCameraUpdate,\n            stopHandlers: () => this._handlers?.stop(false),\n        });\n        this._camera.setEventedParent(this);\n\n        this._interactive = resolvedOptions.interactive;\n        this._maxTileCacheSize = resolvedOptions.maxTileCacheSize;\n        this._maxTileCacheZoomLevels = resolvedOptions.maxTileCacheZoomLevels;\n        this._canvasContextAttributes = {...resolvedOptions.canvasContextAttributes};\n        this._trackResize = resolvedOptions.trackResize === true;\n        this._terrainSkirtLength = resolvedOptions.terrainSkirtLength;\n        this._refreshExpiredTiles = resolvedOptions.refreshExpiredTiles === true;\n        this._fadeDuration = resolvedOptions.fadeDuration;\n        this._crossSourceCollisions = resolvedOptions.crossSourceCollisions === true;\n        this._collectResourceTiming = resolvedOptions.collectResourceTiming === true;\n        this._locale = {...defaultLocale, ...resolvedOptions.locale};\n        this._clickTolerance = resolvedOptions.clickTolerance;\n        this._overridePixelRatio = resolvedOptions.pixelRatio;\n        this._maxCanvasSize = resolvedOptions.maxCanvasSize;\n        this._zoomLevelsToOverscale = resolvedOptions.zoomLevelsToOverscale;\n        this.cancelPendingTileRequestsWhileZooming = resolvedOptions.cancelPendingTileRequestsWhileZooming === true;\n        this.setAnisotropicFilterPitch(resolvedOptions.anisotropicFilterPitch);\n\n        if (resolvedOptions.reduceMotion !== undefined) {\n            browser.prefersReducedMotion = resolvedOptions.reduceMotion;\n        }\n\n        this._requestManager = new RequestManager(resolvedOptions.transformRequest);\n\n        this._container = this._resolveContainer(resolvedOptions.container);\n\n        if (resolvedOptions.maxBounds) {\n            this.setMaxBounds(resolvedOptions.maxBounds);\n        }\n\n        this._setupContainer();\n        try {\n            this._setupPainter();\n        } catch (error) {\n            this._cleanupContainer();\n            throw error;\n        }\n        this._imageQueueHandle = ImageRequest.addThrottleControl(() => this.isMoving());\n\n        this.on('move', () => this._update(false));\n        this.on('moveend', () => this._update(false));\n        this.on('zoom', () => this._update(true));\n        this.on('terrain', () => {\n            this.painter.markTerrainDepthDirty();\n            this._update(true);\n        });\n        this.once('idle', () => this._idleTriggered = true);\n\n        this._handlers = new HandlerManager(this, this._camera, resolvedOptions);\n\n        if (typeof window !== 'undefined') {\n            this._ownerWindow.addEventListener('online', this._onWindowOnline, false);\n            this._setupResizeObserver();\n        }\n\n        const hashName = (typeof resolvedOptions.hash === 'string' && resolvedOptions.hash) || undefined;\n        this._hash = resolvedOptions.hash ? (new Hash(hashName)).addTo(this) : undefined;\n        // don't set position from options if set through hash\n        if (!this._hash?._onHashChange()) {\n            this.jumpTo({\n                center: resolvedOptions.center,\n                elevation: resolvedOptions.elevation,\n                zoom: resolvedOptions.zoom,\n                bearing: resolvedOptions.bearing,\n                pitch: resolvedOptions.pitch,\n                roll: resolvedOptions.roll\n            });\n\n            if (resolvedOptions.bounds) {\n                this.resize();\n                this.fitBounds(resolvedOptions.bounds, extend({}, resolvedOptions.fitBoundsOptions, {duration: 0}));\n            }\n        }\n\n        // When no style is set or it's using something other than the globe projection or a registered planar CRS, we can constrain the camera.\n        // When a style is set with those projections though, we can't constrain the camera until the style is loaded\n        // and the correct transform is used. Otherwise, valid points in the desired projection could be rejected\n        const styleProjectionType = typeof resolvedOptions.style === 'string' ? undefined : resolvedOptions.style?.projection?.type;\n        const shouldConstrainUsingMercatorTransform = styleProjectionType !== 'globe' && !getRegisteredProjection(styleProjectionType);\n        this.resize(null, shouldConstrainUsingMercatorTransform);\n\n        this._localIdeographFontFamily = resolvedOptions.localIdeographFontFamily;\n        this._validateStyle = resolvedOptions.validateStyle;\n        this._initialGlobalState = resolvedOptions.globalState;\n        this._transformStyle = resolvedOptions.transformStyle;\n\n        if (resolvedOptions.style) this.setStyle(resolvedOptions.style, {localIdeographFontFamily: resolvedOptions.localIdeographFontFamily});\n\n        if (resolvedOptions.attributionControl)\n            this.addControl(new AttributionControl(typeof resolvedOptions.attributionControl === 'boolean' ? undefined : resolvedOptions.attributionControl));\n\n        if (resolvedOptions.maplibreLogo)\n            this.addControl(new LogoControl(), resolvedOptions.logoPosition);\n\n        this.on('style.load', () => {\n            // If we didn't constrain the camera before, we do it now\n            if (!shouldConstrainUsingMercatorTransform) this._resizeTransform();\n            if (this._camera.transform.unmodified) {\n                const coercedOptions = pick(this.style.stylesheet, ['center', 'zoom', 'bearing', 'pitch', 'roll']) as CameraOptions;\n                this.jumpTo(coercedOptions);\n            }\n        });\n        this.on('data', (event: MapSourceDataEvent | MapStyleDataEvent) => {\n            this._update(event.dataType === 'style');\n            this.fire(event.dataType === 'style' ? new MapStyleDataEvent('styledata', event) : new MapSourceDataEvent('sourcedata', event));\n        });\n        this.on('dataloading', (event: MapSourceDataEvent | MapStyleDataEvent) => {\n            this.fire(event.dataType === 'style' ? new MapStyleDataEvent('styledataloading', event) : new MapSourceDataEvent('sourcedataloading', event));\n        });\n        this.on('dataabort', (event: MapSourceDataEvent | MapStyleDataEvent) => {\n            this.fire(new MapSourceDataEvent('sourcedataabort', event));\n        });\n    }\n\n    /**\n     * @internal\n     * Returns a unique number for this map instance which is used for the MapLoadEvent\n     * to make sure we only fire one event per instantiated map object.\n     * @returns the uniq map ID\n     */\n    _getMapId(): number {\n        return this._mapId;\n    }\n\n    /**\n     * Sets a global state property that can be retrieved with the [`global-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#global-state).\n     * If the value is null, it resets the property to its default value defined in the [`state` style property](https://maplibre.org/maplibre-style-spec/root/#state).\n     *\n     * @param propertyName - The name of the state property to set.\n     * @param value - The value of the state property to set.\n     */\n    setGlobalStateProperty(propertyName: string, value: any): this {\n        this.style.setGlobalStateProperty(propertyName, value);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the global map state\n     *\n     * @returns The map state object.\n    */\n    getGlobalState(): Record<string, any> {\n        return this.style.getGlobalState();\n    }\n\n    /**\n     * Adds an {@link IControl} to the map, calling `control.onAdd(this)`.\n     *\n     * An {@link ErrorEvent} will be fired if the control is invalid.\n     *\n     * @param control - The {@link IControl} to add.\n     * @param position - position on the map to which the control will be added.\n     * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`.\n     * @example\n     * Add zoom and rotation controls to the map.\n     * ```ts\n     * map.addControl(new NavigationControl());\n     * ```\n     * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/display-map-navigation-controls/)\n     */\n    addControl(control: IControl, position?: ControlPosition): this {\n        if (position === undefined) {\n            if (control.getDefaultPosition) {\n                position = control.getDefaultPosition();\n            } else {\n                position = 'top-right';\n            }\n        }\n        if (!control?.onAdd) {\n            return this.fire(new ErrorEvent(new Error(\n                'Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.')));\n        }\n        const controlElement = control.onAdd(this);\n        this._controls.push(control);\n\n        const positionContainer = this._controlPositions[position];\n        if (position.includes('bottom')) {\n            positionContainer.insertBefore(controlElement, positionContainer.firstChild);\n        } else {\n            positionContainer.appendChild(controlElement);\n        }\n        return this;\n    }\n\n    /**\n     * Removes the control from the map.\n     *\n     * An {@link ErrorEvent} will be fired if the control is invalid.\n     *\n     * @param control - The {@link IControl} to remove.\n     * @example\n     * ```ts\n     * // Define a new navigation control.\n     * let navigation = new NavigationControl();\n     * // Add zoom and rotation controls to the map.\n     * map.addControl(navigation);\n     * // Remove zoom and rotation controls from the map.\n     * map.removeControl(navigation);\n     * ```\n     */\n    removeControl(control: IControl): this {\n        if (!control?.onRemove) {\n            return this.fire(new ErrorEvent(new Error(\n                'Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.')));\n        }\n        const ci = this._controls.indexOf(control);\n        if (ci > -1) this._controls.splice(ci, 1);\n        control.onRemove(this);\n        return this;\n    }\n\n    /**\n     * Checks if a control exists on the map.\n     *\n     * @param control - The {@link IControl} to check.\n     * @returns true if map contains control.\n     * @example\n     * ```ts\n     * // Define a new navigation control.\n     * let navigation = new NavigationControl();\n     * // Add zoom and rotation controls to the map.\n     * map.addControl(navigation);\n     * // Check that the navigation control exists on the map.\n     * map.hasControl(navigation);\n     * ```\n     */\n    hasControl(control: IControl): boolean {\n        return this._controls.includes(control);\n    }\n\n    /**\n    * Returns an array of `OverscaledTileID` objects that cover the current viewport for a given tile size.\n    * This method is useful for determining which tiles are visible in the current viewport.\n    *\n    * @param options - Options for calculating the covering tiles.\n    * @returns An array of `OverscaledTileID` objects.\n    * @example\n    * ```ts\n    * // Get the tiles to cover the view for a 512x512px tile source\n    * const tiles = map.coveringTiles({tileSize: 512});\n    * ```\n    */\n    coveringTiles(options: CoveringTilesOptions): OverscaledTileID[] {\n        return coveringTiles(this._camera.transform, options);\n    }\n\n    /**\n     * Sets the callback used to defer camera updates or apply arbitrary constraints.\n     * If specified, this Camera instance can be used as a stateless component in React etc.\n     */\n    setTransformCameraUpdate(value: CameraUpdateTransformFunction | null): void { this._camera.transformCameraUpdate = value; }\n\n    /**\n     * Returns the map's geographical centerpoint.\n     *\n     * @returns The map's geographical centerpoint.\n     * @example\n     * Return a LngLat object such as `{lng: 0, lat: 0}`\n     * ```ts\n     * let center = map.getCenter();\n     * // access longitude and latitude values directly\n     * let {lng, lat} = map.getCenter();\n     * ```\n     */\n    getCenter(): LngLat { return new LngLat(this._camera.transform.center.lng, this._camera.transform.center.lat); }\n    /**\n     * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`.\n     *\n     * Triggers the following events: `movestart` and `moveend`.\n     *\n     * @param center - The centerpoint to set.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * ```ts\n     * map.setCenter([-74, 38]);\n     * ```\n     */\n    setCenter(center: LngLatLike, eventData?: Record<string, unknown>): this { this._camera.setCenter(center, eventData); return this; }\n    /**\n     * Returns the elevation of the map's center point.\n     *\n     * @returns The elevation of the map's center point, in meters above sea level.\n     */\n    getCenterElevation(): number { return this._camera.transform.elevation; }\n    /**\n     * Sets the elevation of the map's center point, in meters above sea level. Equivalent to `jumpTo({elevation: elevation})`.\n     *\n     * Triggers the following events: `movestart` and `moveend`.\n     *\n     * @param elevation - The elevation to set, in meters above sea level.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     */\n    setCenterElevation(elevation: number, eventData?: any): this { this._camera.setCenterElevation(elevation, eventData); return this; }\n    /**\n     * Sets the value of `centerClampedToGround`.\n     *\n     * If true, the elevation of the center point will automatically be set to the terrain elevation\n     * (or zero if terrain is not enabled). If false, the elevation of the center point will default\n     * to sea level and will not automatically update. Defaults to true. Needs to be set to false to\n     * keep the camera above ground when pitch \\> 90 degrees.\n     */\n    setCenterClampedToGround(centerClampedToGround: boolean): void { this._camera.setCenterClampedToGround(centerClampedToGround); }\n    /**\n     * Pans the map by the specified offset.\n     *\n     * Triggers the following events: `movestart` and `moveend`.\n     *\n     * @param offset - `x` and `y` coordinates by which to pan the map.\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigate-the-map-with-game-like-controls/)\n     */\n    panBy(offset: PointLike, options?: EaseToOptions, eventData?: any): this { this._camera.panBy(offset, options, eventData); return this; }\n    /**\n     * Pans the map to the specified location with an animated transition.\n     *\n     * Triggers the following events: `movestart` and `moveend`.\n     *\n     * @param lnglat - The location to pan the map to.\n     * @param options - Options describing the destination and animation of the transition.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * ```ts\n     * map.panTo([-74, 38]);\n     * // Specify that the panTo animation should last 5000 milliseconds.\n     * map.panTo([-74, 38], {duration: 5000});\n     * ```\n     * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/update-a-feature-in-realtime/)\n     */\n    panTo(lnglat: LngLatLike, options?: EaseToOptions, eventData?: any): this { this._camera.panTo(lnglat, options, eventData); return this; }\n    /**\n     * Returns the map's current zoom level.\n     *\n     * @returns The map's current zoom level.\n     * @example\n     * ```ts\n     * map.getZoom();\n     * ```\n     */\n    getZoom(): number { return this._camera.transform.zoom; }\n    /**\n     * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n     *\n     * @param zoom - The zoom level to set (0-20).\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * Zoom to the zoom level 5 without an animated transition\n     * ```ts\n     * map.setZoom(5);\n     * ```\n     */\n    setZoom(zoom: number, eventData?: any): this { this._camera.setZoom(zoom, eventData); return this; }\n    /**\n     * Zooms the map to the specified zoom level, with an animated transition.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n     *\n     * @param zoom - The zoom level to transition to.\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * ```ts\n     * // Zoom to the zoom level 5 without an animated transition\n     * map.zoomTo(5);\n     * // Zoom to the zoom level 8 with an animated transition\n     * map.zoomTo(8, {\n     *   duration: 2000,\n     *   offset: [100, 50]\n     * });\n     * ```\n     */\n    zoomTo(zoom: number, options?: EaseToOptions | null, eventData?: any): this { this._camera.zoomTo(zoom, options, eventData); return this; }\n    /**\n     * Incrementally increases the map's zoom level by 1, first snapping to the nearest `zoomSnap` increment.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n     *\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * Zoom the map in one level with a custom animation duration\n     * ```ts\n     * map.zoomIn({duration: 1000});\n     * ```\n     */\n    zoomIn(options?: AnimationOptions, eventData?: any): this { this._camera.zoomIn(options, eventData); return this; }\n    /**\n     * Decreases the map's zoom level by 1, first snapping to the nearest `zoomSnap` increment.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n     *\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * Zoom the map out one level with a custom animation offset\n     * ```ts\n     * map.zoomOut({offset: [80, 60]});\n     * ```\n     */\n    zoomOut(options?: AnimationOptions, eventData?: any): this { this._camera.zoomOut(options, eventData); return this; }\n    /**\n     * Returns the map's current vertical field of view, in degrees.\n     *\n     * @returns The map's current vertical field of view.\n     * @defaultValue 36.87\n     * @example\n     * ```ts\n     * const verticalFieldOfView = map.getVerticalFieldOfView();\n     * ```\n     */\n    getVerticalFieldOfView(): number { return this._camera.transform.fov; }\n    /**\n     * Sets the map's vertical field of view, in degrees.\n     *\n     * Triggers the following events: `movestart`, `move`, and `moveend`.\n     *\n     * @param fov - The vertical field of view to set, in degrees (0-180).\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @defaultValue 36.87\n     * @example\n     * Change vertical field of view to 30 degrees\n     * ```ts\n     * map.setVerticalFieldOfView(30);\n     * ```\n     */\n    setVerticalFieldOfView(fov: number, eventData?: any): this { this._camera.setVerticalFieldOfView(fov, eventData); return this; }\n    /**\n     * Returns the map's current bearing. The bearing is the compass direction that is \"up\"; for example, a bearing\n     * of 90° orients the map so that east is up.\n     *\n     * @returns The map's current bearing.\n     * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigate-the-map-with-game-like-controls/)\n     */\n    getBearing(): number { return this._camera.transform.bearing; }\n    /**\n     * Sets the map's bearing (rotation). The bearing is the compass direction that is \"up\"; for example, a bearing\n     * of 90° orients the map so that east is up.\n     *\n     * Equivalent to `jumpTo({bearing: bearing})`.\n     *\n     * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n     *\n     * @param bearing - The desired bearing.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * Rotate the map to 90 degrees\n     * ```ts\n     * map.setBearing(90);\n     * ```\n     */\n    setBearing(bearing: number, eventData?: any): this { this._camera.setBearing(bearing, eventData); return this; }\n    /**\n     * Returns the map's current zoom snap level.\n     *\n     * @returns The map's current zoom snap level.\n     */\n    getZoomSnap(): number { return this._camera.getZoomSnap(); }\n    /**\n     * Sets the map's zoom snap level.\n     *\n     * @param snap - The zoom snap level to set.\n     */\n    setZoomSnap(snap: number): this { this._camera.setZoomSnap(snap); return this; }\n    /**\n     * Returns the current padding applied around the map viewport.\n     *\n     * @returns The current padding around the map viewport.\n     */\n    getPadding(): PaddingOptions { return this._camera.transform.padding; }\n    /**\n     * Sets the padding in pixels around the viewport.\n     *\n     * Equivalent to `jumpTo({padding: padding})`.\n     *\n     * Triggers the following events: `movestart` and `moveend`.\n     *\n     * @param padding - The desired padding.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * Sets a left padding of 300px, and a top padding of 50px\n     * ```ts\n     * map.setPadding({ left: 300, top: 50 });\n     * ```\n     */\n    setPadding(padding: PaddingOptions, eventData?: any): this { this._camera.setPadding(padding, eventData); return this; }\n    /**\n     * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction\n     * that is \"up\"; for example, a bearing of 90° orients the map so that east is up.\n     *\n     * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n     *\n     * @param bearing - The desired bearing.\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     */\n    rotateTo(bearing: number, options?: EaseToOptions, eventData?: any): this { this._camera.rotateTo(bearing, options, eventData); return this; }\n    /**\n     * Rotates the map so that north is up (0° bearing), with an animated transition.\n     *\n     * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n     *\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     */\n    resetNorth(options?: AnimationOptions, eventData?: any): this { this._camera.resetNorth(options, eventData); return this; }\n    /**\n     * Rotates and pitches the map so that north is up (0° bearing) and pitch and roll are 0°, with an animated transition.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, `rollstart`, `roll`, `rollend`, and `rotate`.\n     *\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     */\n    resetNorthPitch(options?: AnimationOptions, eventData?: any): this { this._camera.resetNorthPitch(options, eventData); return this; }\n    /**\n     * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the\n     * `bearingSnap` threshold).\n     *\n     * Triggers the following events: `movestart`, `moveend`, and `rotate`.\n     *\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     */\n    snapToNorth(options?: AnimationOptions, eventData?: any): this { this._camera.snapToNorth(options, eventData); return this; }\n    /**\n     * Returns the map's current pitch (tilt).\n     *\n     * @returns The map's current pitch, measured in degrees away from the plane of the screen.\n     */\n    getPitch(): number { return this._camera.transform.pitch; }\n    /**\n     * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`.\n     *\n     * Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`.\n     *\n     * @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60).\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     */\n    setPitch(pitch: number, eventData?: any): this { this._camera.setPitch(pitch, eventData); return this; }\n    /**\n     * Returns the map's current roll angle.\n     *\n     * @returns The map's current roll, measured in degrees about the camera boresight.\n     */\n    getRoll(): number { return this._camera.transform.roll; }\n    /**\n     * Sets the map's roll angle. Equivalent to `jumpTo({roll: roll})`.\n     *\n     * Triggers the following events: `movestart`, `moveend`, `rollstart`, and `rollend`.\n     *\n     * @param roll - The roll to set, measured in degrees about the camera boresight\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     */\n    setRoll(roll: number, eventData?: any): this { this._camera.setRoll(roll, eventData); return this; }\n    /**\n     * @param bounds - Calculate the center for these bounds in the viewport and use\n     * the highest zoom level up to and including {@link Map.getMaxZoom} that fits\n     * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.\n     * Bounds will be taken in `[sw, ne]` order. Southwest point will always be to the left of the northeast point.\n     * @param options - Options object\n     * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`,\n     * plus `padding` when `absolutePadding` is set.\n     * If map is unable to fit, method will warn and return undefined.\n     * @example\n     * ```ts\n     * let bbox = [[-79, 43], [-73, 45]];\n     * let newCameraTransform = map.cameraForBounds(bbox, {\n     *   padding: {top: 10, bottom:25, left: 15, right: 5}\n     * });\n     * ```\n     */\n    cameraForBounds(bounds: LngLatBoundsLike, options?: CameraForBoundsOptions): JumpToOptions | undefined { return this._camera.cameraForBounds(bounds, options); }\n    /**\n     * Pans and zooms the map to contain its visible area within the specified geographical bounds.\n     * This function will also reset the map's bearing to 0 if bearing is nonzero.\n     *\n     * Triggers the following events: `movestart` and `moveend`.\n     *\n     * @param bounds - Center these bounds in the viewport and use the highest\n     * zoom level up to and including {@link Map.getMaxZoom} that fits them in the viewport.\n     * Bounds will be taken in `[sw, ne]` order. Southwest point will always be to the left of the northeast point.\n     * @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * ```ts\n     * let bbox = [[-79, 43], [-73, 45]];\n     * map.fitBounds(bbox, {\n     *   padding: {top: 10, bottom:25, left: 15, right: 5}\n     * });\n     * ```\n     * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fit-a-map-to-a-bounding-box/)\n     */\n    fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions, eventData?: any): this { this._camera.fitBounds(bounds, options, eventData); return this; }\n    /**\n     * Pans, rotates and zooms the map to to fit the box made by points p0 and p1\n     * once the map is rotated to the specified bearing. To zoom without rotating,\n     * pass in the current map bearing.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`.\n     *\n     * @param p0 - First point on screen, in pixel coordinates\n     * @param p1 - Second point on screen, in pixel coordinates\n     * @param bearing - Desired map bearing at end of animation, in degrees\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * ```ts\n     * let p0 = [220, 400];\n     * let p1 = [500, 900];\n     * map.fitScreenCoordinates(p0, p1, map.getBearing(), {\n     *   padding: {top: 10, bottom:25, left: 15, right: 5}\n     * });\n     * ```\n     * @see Used by {@link BoxZoomHandler}\n     */\n    fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: FitBoundsOptions, eventData?: any): this { this._camera.fitScreenCoordinates(p0, p1, bearing, options, eventData); return this; }\n    /**\n     * Changes any combination of center, zoom, bearing, pitch, and roll, without\n     * an animated transition. The map will retain its current values for any\n     * details not specified in `options`.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,\n     * `pitch`, `pitchend`, `rollstart`, `roll`, `rollend` and `rotate`.\n     *\n     * @param options - Options object\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * ```ts\n     * // jump to coordinates at current zoom\n     * map.jumpTo({center: [0, 0]});\n     * // jump with zoom, pitch, and bearing options\n     * map.jumpTo({\n     *   center: [0, 0],\n     *   zoom: 8,\n     *   pitch: 45,\n     *   bearing: 90\n     * });\n     * ```\n     * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to-a-series-of-locations/)\n     * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/update-a-feature-in-realtime/)\n     */\n    jumpTo(options: JumpToOptions, eventData?: any): this { this._camera.jumpTo(options, eventData); return this; }\n    /**\n     * Calculates constrained camera options that place a geographic anchor at a screen point\n     * without changing the map, using the same logic as MapLibre's interaction handlers.\n     *\n     * @param options - Anchor and optional zoom.\n     * @returns Camera options that can be passed to {@link Map.jumpTo}.\n     * @example\n     * ```ts\n     * const cameraOptions = map.calculateAnchoredCameraOptions({\n     *   anchorLocation: map.unproject(pointerDownPosition),\n     *   anchorScreenPoint: currentPointerPosition,\n     *   zoom: map.getZoom() + 1,\n     * });\n     * map.jumpTo(cameraOptions);\n     * ```\n     */\n    calculateAnchoredCameraOptions(options: AnchoredCameraOptions): CameraOptions {\n        return this._camera.calculateAnchoredCameraOptions(options);\n    }\n    /**\n     * Given a camera position and rotation, calculates zoom and center point and returns them as {@link CameraOptions}.\n     * @param cameraLngLat - The lng, lat of the camera to look from\n     * @param cameraAlt - The altitude of the camera to look from, in meters above sea level\n     * @param bearing - Bearing of the camera, in degrees\n     * @param pitch - Pitch of the camera, in degrees\n     * @param roll - Roll of the camera, in degrees\n     * @returns the calculated camera options\n     * @example\n     * ```ts\n     * // Calculate options to look from camera position(1°, 0°, 1000m) with bearing = 90°, pitch = 30°, and roll = 45°\n     * const cameraLngLat = new LngLat(1, 0);\n     * const cameraAltitude = 1000;\n     * const bearing = 90;\n     * const pitch = 30;\n     * const roll = 45;\n     * const cameraOptions = map.calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAltitude, bearing, pitch, roll);\n     * // Apply calculated options\n     * map.jumpTo(cameraOptions);\n     * ```\n     */\n    calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat: LngLatLike, cameraAlt: number, bearing: number, pitch: number, roll?: number): CameraOptions { return this._camera.calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAlt, bearing, pitch, roll); }\n    /**\n     * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, `roll`, and `padding` with an animated transition\n     * between old and new values. The map will retain its current values for any\n     * details not specified in `options`.\n     *\n     * !!! note \"Reduced Motion\"\n     *     The transition will happen instantly if the user has enabled\n     *     the `reduced motion` accessibility feature enabled in their operating system,\n     *     unless `options` includes `essential: true`.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,\n     * `pitch`, `pitchend`, `rollstart`, `roll`, `rollend`, and `rotate`.\n     *\n     * @param options - Options describing the destination and animation of the transition.\n     * Accepts {@link CameraOptions} and {@link AnimationOptions}.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigate-the-map-with-game-like-controls/)\n     */\n    easeTo(options: EaseToOptions, eventData?: any): this { this._camera.easeTo(options, eventData); return this; }\n    /**\n     * Changes any combination of center, zoom, bearing, pitch, and roll, animating the transition along a curve that\n     * evokes flight. The animation seamlessly incorporates zooming and panning to help\n     * the user maintain her bearings even after traversing a great distance.\n     *\n     * !!! note \"Reduced Motion\"\n     *     The animation will be skipped, and this will behave equivalently to `jumpTo`\n     *     if the user has the `reduced motion` accessibility feature enabled in their operating system,\n     *     unless 'options' includes `essential: true`.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,\n     * `pitch`, `pitchend`, `rollstart`, `roll`, `rollend`, and `rotate`.\n     *\n     * @param options - Options describing the destination and animation of the transition.\n     * Accepts {@link CameraOptions}, {@link AnimationOptions},\n     * and the following additional options.\n     * @param eventData - Additional properties to be added to event objects of events triggered by this method.\n     * @example\n     * ```ts\n     * // fly with default options to null island\n     * map.flyTo({center: [0, 0], zoom: 9});\n     * // using flyTo options\n     * map.flyTo({\n     *   center: [0, 0],\n     *   zoom: 9,\n     *   speed: 0.2,\n     *   curve: 1,\n     *   easing(t) {\n     *     return t;\n     *   }\n     * });\n     * ```\n     * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/fly-to-a-location/)\n     * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/slowly-fly-to-a-location/)\n     * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/fly-to-a-location-based-on-scroll-position/)\n     */\n    flyTo(options: FlyToOptions, eventData?: any): this { this._camera.flyTo(options, eventData); return this; }\n    /**\n     * Stops any animated transition underway.\n     */\n    stop(): this { this._camera.stop(); return this; }\n    /**\n     * Gets the elevation at a given location, in meters above sea level.\n     * Returns null if terrain is not enabled.\n     * If terrain is enabled with some exaggeration value, the value returned here will be reflective of (multiplied by) that exaggeration value.\n     * This method should be used for proper positioning of custom 3d objects. If using maplibre-gl-three, see the example [here](https://maplibre-gl-three.readthedocs.io/latest/getting-started/#programmatically-calculating-terrain-height)\n     * @param lngLatLike - `[x, y]` or LngLat coordinates of the location\n     * @returns elevation in meters\n     */\n    queryTerrainElevation(lngLatLike: LngLatLike): number | null {\n        if (!this.terrain) {\n            return null;\n        }\n        return this.terrain.getElevationForLngLat(LngLat.convert(lngLatLike), this._camera.transform.tileZoom);\n    }\n    /**\n     * Returns the value of `centerClampedToGround`.\n     *\n     * If true, the elevation of the center point will automatically be set to the terrain elevation\n     * (or zero if terrain is not enabled). If false, the elevation of the center point will default\n     * to sea level and will not automatically update. Defaults to true. Needs to be set to false to\n     * keep the camera above ground when pitch \\> 90 degrees.\n     */\n    getCenterClampedToGround(): boolean { return this._camera.getCenterClampedToGround(); }\n\n    /**\n     * Given a camera 'from' position and a position to look at (`to`), calculates zoom and camera rotation and returns them as {@link CameraOptions}.\n     * Under `globe` and `vertical-perspective` the calculation follows the sphere while the map renders as a globe, keeping the point looked at on the sea-level sphere; `altitudeTo` only becomes the center elevation.\n     * @param from - The camera to look from\n     * @param altitudeFrom - The altitude of the camera to look from\n     * @param to - The center to look at\n     * @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used.\n     * @returns the calculated camera options\n     * @example\n     * ```ts\n     * // Calculate options to look from (1°, 0°, 1000m) to (1°, 1°, 0m)\n     * const cameraLngLat = new LngLat(1, 0);\n     * const cameraAltitude = 1000;\n     * const targetLngLat = new LngLat(1, 1);\n     * const targetAltitude = 0;\n     * const cameraOptions = map.calculateCameraOptionsFromTo(cameraLngLat, cameraAltitude, targetLngLat, targetAltitude);\n     * // Apply calculated options\n     * map.jumpTo(cameraOptions);\n     * ```\n     */\n    calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo?: number): CameraOptions {\n        if (altitudeTo == null && this.terrain) {\n            altitudeTo = this.terrain.getElevationForLngLat(to, this._camera.transform.tileZoom);\n        }\n        return this._camera.transform.calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo ?? 0);\n    }\n\n    /**\n     * Resizes the map according to the dimensions of its\n     * `container` element.\n     *\n     * Checks if the map container size changed and updates the map if it has changed.\n     * With the default `trackResize: true`, container size changes are picked up automatically,\n     * including a container that becomes visible after being hidden with CSS. Call this method\n     * explicitly when `trackResize` is `false`, or when the map's size changes in a way the\n     * container's `ResizeObserver` cannot observe.\n     *\n     * Triggers the following events: `movestart`, `move`, `moveend`, and `resize`.\n     *\n     * @param eventData - Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend`\n     * events that get triggered as a result of resize. This can be useful for differentiating the\n     * source of an event (for example, user-initiated or programmatically-triggered events).\n     * @example\n     * Resize a map with `trackResize` disabled when its container is shown after being hidden with CSS.\n     * ```ts\n     * let mapDiv = document.getElementById('map');\n     * if (mapDiv.style.visibility === 'visible') map.resize();\n     * ```\n     */\n    resize(eventData?: any, constrainTransform = true): this {\n        // Early out if the context is lost\n        // causes a blank map otherwise\n        const isContextLost = this._lostContextSnapshot.style !== null;\n        if (isContextLost) return this;\n        this._resizeInternal(constrainTransform);\n\n        const fireMoving = !this._camera.isMoving();\n        if (fireMoving) {\n            this.stop();\n            this.fire(new MapMovementEvent('movestart', eventData))\n                .fire(new MapMovementEvent('move', eventData));\n        }\n\n        this.fire(new MapLibreEvent('resize', eventData));\n\n        if (fireMoving) this.fire(new MapMovementEvent('moveend', eventData));\n\n        return this;\n    }\n\n    /**\n     * Resizes the map according to the dimensions of its\n     * `container` element.\n     *\n     * It does not trigger any events, and does not check for context loss.\n     *\n     * It is used internally and by {@link Map.resize}.\n     *\n     * @internal\n     *\n     * @param constrainTransform - whether to constrain the transform after resizing.\n     */\n    _resizeInternal(constrainTransform = true): void {\n        const [width, height] = this._containerDimensions();\n\n        this._clampedPixelRatio = this._getClampedPixelRatio(width, height);\n        this._resizeCanvas(width, height, this._clampedPixelRatio);\n        this.painter.resize(width, height, this._clampedPixelRatio);\n\n        // check if we've reached GL limits, in that case further clamps pixelRatio\n        // a lost context reports a 0x0 drawing buffer, which is not a real limit\n        const gl = this.painter.context.gl;\n        if (!gl.isContextLost() && this.painter.overLimit()) {\n            // store updated _maxCanvasSize value\n            this._maxCanvasSize = [gl.drawingBufferWidth, gl.drawingBufferHeight];\n            this._clampedPixelRatio = this._getClampedPixelRatio(width, height);\n            this._resizeCanvas(width, height, this._clampedPixelRatio);\n            this.painter.resize(width, height, this._clampedPixelRatio);\n        }\n        this.style?.resize();\n\n        this._resizeTransform(constrainTransform);\n    }\n\n    _resizeTransform(constrainTransform = true): void {\n        const [width, height] = this._containerDimensions();\n\n        this._camera.resize(width, height, constrainTransform);\n    }\n\n    /**\n     * @internal\n     * Return the map's pixel ratio eventually scaled down to respect maxCanvasSize.\n     * Internally you should use this and not getPixelRatio().\n     * Warns once when the ratio is scaled down. The message carries no sizes: this runs on every\n     * resize and `warnOnce` de-duplicates by message, so sizes would warn on every drag frame.\n     */\n    _getClampedPixelRatio(width: number, height: number): number {\n        const {0: maxCanvasWidth, 1: maxCanvasHeight} = this._maxCanvasSize;\n        const pixelRatio = this.getPixelRatio();\n\n        const canvasWidth = width * pixelRatio;\n        const canvasHeight = height * pixelRatio;\n\n        const widthScaleFactor = canvasWidth > maxCanvasWidth ? (maxCanvasWidth / canvasWidth) : 1;\n        const heightScaleFactor = canvasHeight > maxCanvasHeight ? (maxCanvasHeight / canvasHeight) : 1;\n\n        const scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);\n\n        if (scaleFactor < 1) {\n            warnOnce('The canvas is larger than maxCanvasSize and is rendered at a lower pixel ratio to fit. Increase maxCanvasSize, within MAX_TEXTURE_SIZE, to render at full resolution.');\n        }\n\n        return scaleFactor * pixelRatio;\n    }\n\n    /**\n     * Returns the map's pixel ratio.\n     * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.\n     * @returns The pixel ratio.\n     */\n    getPixelRatio(): number {\n        return this._overridePixelRatio ?? devicePixelRatio;\n    }\n\n    /**\n     * Sets the map's pixel ratio. This allows to override `devicePixelRatio`.\n     * After this call, the canvas' `width` attribute will be `container.clientWidth * pixelRatio`\n     * and its height attribute will be `container.clientHeight * pixelRatio`.\n     * Set this to null to disable `devicePixelRatio` override.\n     * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.\n     * @param pixelRatio - The pixel ratio.\n     */\n    setPixelRatio(pixelRatio: number): void {\n        this._overridePixelRatio = pixelRatio;\n        this.resize();\n    }\n\n    /**\n     * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not\n     * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.\n     * @returns The geographical bounds of the map as {@link LngLatBounds}.\n     * @example\n     * ```ts\n     * let bounds = map.getBounds();\n     * ```\n     */\n    getBounds(): LngLatBounds {\n        return this._camera.transform.getBounds();\n    }\n\n    /**\n     * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.\n     * @returns The map object.\n     * @example\n     * ```ts\n     * let maxBounds = map.getMaxBounds();\n     * ```\n     */\n    getMaxBounds(): LngLatBounds | null {\n        return this._camera.transform.getMaxBounds();\n    }\n\n    /**\n     * Sets or clears the map's geographical bounds.\n     *\n     * Pan and zoom operations are constrained within these bounds.\n     * If a pan or zoom is performed that would\n     * display regions outside these bounds, the map will\n     * instead display a position and zoom level\n     * as close as possible to the operation's request while still\n     * remaining within the bounds.\n     *\n     * @param bounds - The maximum bounds to set. Use `-Infinity` and `Infinity` for an unconstrained longitude range, with finite latitude limits. Pass `null` or `undefined` to remove all bounds.\n     * @example\n     * Define bounds that conform to the `LngLatBoundsLike` object as set the max bounds.\n     * ```ts\n     * let bounds = [\n     *   [-74.04728, 40.68392], // [west, south]\n     *   [-73.91058, 40.87764]  // [east, north]\n     * ];\n     * map.setMaxBounds(bounds);\n     * ```\n     */\n    setMaxBounds(bounds?: LngLatBoundsLike | null): this {\n        this._camera.applyTransformChange(tr => tr.setMaxBounds(LngLatBounds.convert(bounds)));\n        return this._update();\n    }\n\n    /**\n     * Sets or clears the map's minimum zoom level.\n     * If the map's current zoom level is lower than the new minimum,\n     * the map will zoom to the new minimum and trigger the following events:\n     * `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n     *\n     * It is not always possible to zoom out and reach the set `minZoom`.\n     * Other factors such as map height may restrict zooming. For example,\n     * if the map is 512px tall it will not be possible to zoom below zoom 0\n     * no matter what the `minZoom` is set to.\n     *\n     * A {@link ErrorEvent} event will be fired if minZoom is out of bounds.\n     *\n     * @param minZoom - The minimum zoom level to set (-2 - 24).\n     * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2).\n     * @example\n     * ```ts\n     * map.setMinZoom(12.25);\n     * ```\n     */\n    setMinZoom(minZoom?: number | null): this {\n\n        minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom;\n\n        if (minZoom >= defaultMinZoom && minZoom <= this._camera.transform.maxZoom) {\n            const zoomBefore = this._camera.transform.zoom;\n            this._camera.applyTransformChange(tr => tr.setMinZoom(minZoom));\n            this._update();\n            if (zoomBefore !== this._camera.transform.zoom) {\n                this.fire(new MapMovementEvent('zoomstart'))\n                    .fire(new MapMovementEvent('zoom'))\n                    .fire(new MapMovementEvent('zoomend'))\n                    .fire(new MapMovementEvent('movestart'))\n                    .fire(new MapMovementEvent('move'))\n                    .fire(new MapMovementEvent('moveend'));\n            }\n\n            return this;\n\n        } else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`);\n    }\n\n    /**\n     * Returns the map's minimum allowable zoom level.\n     *\n     * @param constrained - If `true`, returns the effective minimum zoom after applying the map's viewport constraints.\n     * If `false` or omitted, returns the configured minimum zoom.\n     * @returns minZoom\n     * @example\n     * ```ts\n     * let minZoom = map.getMinZoom();\n     * ```\n     */\n    getMinZoom(constrained = false): number {\n        const transform = this._camera.transform;\n        return constrained ? transform.applyConstrain(transform.center, transform.minZoom).zoom : transform.minZoom;\n    }\n\n    /**\n     * Sets or clears the map's maximum zoom level.\n     * If the map's current zoom level is higher than the new maximum,\n     * the map will zoom to the new maximum and trigger the following events:\n     * `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.\n     *\n     * A {@link ErrorEvent} event will be fired if minZoom is out of bounds.\n     *\n     * @param maxZoom - The maximum zoom level to set.\n     * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22).\n     * @example\n     * ```ts\n     * map.setMaxZoom(18.75);\n     * ```\n     */\n    setMaxZoom(maxZoom?: number | null): this {\n\n        maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom;\n\n        if (maxZoom >= this._camera.transform.minZoom) {\n            const zoomBefore = this._camera.transform.zoom;\n            this._camera.applyTransformChange(tr => tr.setMaxZoom(maxZoom));\n            this._update();\n            if (zoomBefore !== this._camera.transform.zoom) {\n                this.fire(new MapMovementEvent('zoomstart'))\n                    .fire(new MapMovementEvent('zoom'))\n                    .fire(new MapMovementEvent('zoomend'))\n                    .fire(new MapMovementEvent('movestart'))\n                    .fire(new MapMovementEvent('move'))\n                    .fire(new MapMovementEvent('moveend'));\n            }\n\n            return this;\n\n        } else throw new Error('maxZoom must be greater than the current minZoom');\n    }\n\n    /**\n     * Returns the map's maximum allowable zoom level.\n     *\n     * @returns The maxZoom\n     * @example\n     * ```ts\n     * let maxZoom = map.getMaxZoom();\n     * ```\n     */\n    getMaxZoom(): number { return this._camera.transform.maxZoom; }\n\n    /**\n     * Sets or clears the map's minimum pitch.\n     * If the map's current pitch is lower than the new minimum,\n     * the map will pitch to the new minimum and trigger the following events:\n     * `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, and `pitchend`.\n     *\n     * A {@link ErrorEvent} event will be fired if minPitch is out of bounds.\n     *\n     * @param minPitch - The minimum pitch to set (0-180). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n     * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0).\n     */\n    setMinPitch(minPitch?: number | null): this {\n\n        minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch;\n\n        if (minPitch < defaultMinPitch) {\n            throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);\n        }\n\n        if (minPitch >= defaultMinPitch && minPitch <= this._camera.transform.maxPitch) {\n            const pitchBefore = this._camera.transform.pitch;\n            this._camera.applyTransformChange(tr => tr.setMinPitch(minPitch));\n            this._update();\n            if (pitchBefore !== this._camera.transform.pitch) {\n                this.fire(new MapMovementEvent('pitchstart'))\n                    .fire(new MapMovementEvent('pitch'))\n                    .fire(new MapMovementEvent('pitchend'))\n                    .fire(new MapMovementEvent('movestart'))\n                    .fire(new MapMovementEvent('move'))\n                    .fire(new MapMovementEvent('moveend'));\n            }\n\n            return this;\n\n        } else throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`);\n    }\n\n    /**\n     * Returns the map's minimum allowable pitch.\n     *\n     * @returns The minPitch\n     */\n    getMinPitch(): number { return this._camera.transform.minPitch; }\n\n    /**\n     * Sets or clears the map's maximum pitch.\n     * If the map's current pitch is higher than the new maximum,\n     * the map will pitch to the new maximum and trigger the following events:\n     * `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, and `pitchend`.\n     *\n     * A {@link ErrorEvent} event will be fired if maxPitch is out of bounds.\n     *\n     * @param maxPitch - The maximum pitch to set (0-180). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.\n     * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60).\n     */\n    setMaxPitch(maxPitch?: number | null): this {\n\n        maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch;\n\n        if (maxPitch > maxPitchThreshold) {\n            throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`);\n        }\n\n        if (maxPitch >= this._camera.transform.minPitch) {\n            const pitchBefore = this._camera.transform.pitch;\n            this._camera.applyTransformChange(tr => tr.setMaxPitch(maxPitch));\n            this._update();\n            if (pitchBefore !== this._camera.transform.pitch) {\n                this.fire(new MapMovementEvent('pitchstart'))\n                    .fire(new MapMovementEvent('pitch'))\n                    .fire(new MapMovementEvent('pitchend'))\n                    .fire(new MapMovementEvent('movestart'))\n                    .fire(new MapMovementEvent('move'))\n                    .fire(new MapMovementEvent('moveend'));\n            }\n\n            return this;\n\n        } else throw new Error('maxPitch must be greater than the current minPitch');\n    }\n\n    /**\n     * Returns the map's maximum allowable pitch.\n     *\n     * @returns The maxPitch\n     */\n    getMaxPitch(): number { return this._camera.transform.maxPitch; }\n\n    /**\n     * Returns the map's anisotropic filter pitch.\n     * If the map is pitched beyond this threshold, anisotropic filtering will be applied to all raster layers.\n     *\n     * @returns The anisotropicFilterPitch\n     * @example\n     * ```ts\n     * let anisotropicFilterPitch = map.getAnisotropicFilterPitch();\n     * ```\n     */\n    getAnisotropicFilterPitch(): number { return this._anisotropicFilterPitch; }\n\n    /**\n     * Sets the map's anisotropic filter pitch or reverts it to its default.\n     *\n     * A {@link ErrorEvent} event will be fired if anisotropicFilterPitch is out of bounds.\n     *\n     * @param anisotropicFilterPitch - The pitch above which to apply anisotropic filtering to the map's raster layers (0-180).\n     * If `null` or `undefined` is provided, the function reverts to the default pitch threshold (20).\n     *\n     *\n     * @example\n     * ```ts\n     * map.setAnisotropicFilterPitch(85);\n     * ```\n     */\n    setAnisotropicFilterPitch(anisotropicFilterPitch?: number | null): this {\n\n        anisotropicFilterPitch = anisotropicFilterPitch === null || anisotropicFilterPitch === undefined ? defaultAnisotropicFilterPitch : anisotropicFilterPitch;\n\n        if (anisotropicFilterPitch > maxPitchThreshold) {\n            throw new Error(`anisotropicFilterPitch must be less than or equal to ${maxPitchThreshold}`);\n        }\n\n        if (anisotropicFilterPitch < defaultMinPitch) {\n            throw new Error(`anisotropicFilterPitch must be greater than or equal to ${defaultMinPitch}`);\n        }\n\n        this._anisotropicFilterPitch = anisotropicFilterPitch;\n        return this._update();\n    }\n\n    /**\n     * 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`:\n     *\n     * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n     * container, there will be blank space beyond 180 and -180 degrees longitude.\n     * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n     * map and the other on the left edge of the map) at every zoom level.\n     *\n     * A projection registered with {@link addProjection} renders a single world whatever this is set to; the setting\n     * is kept and applies again in mercator.\n     * @returns The renderWorldCopies\n     * @example\n     * ```ts\n     * let worldCopiesRendered = map.getRenderWorldCopies();\n     * ```\n     * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/)\n     */\n    getRenderWorldCopies(): boolean { return this._camera.transform.renderWorldCopies; }\n\n    /**\n     * Sets the state of `renderWorldCopies`.\n     *\n     * @param renderWorldCopies - If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n     *\n     * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n     * container, there will be blank space beyond 180 and -180 degrees longitude.\n     * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n     * map and the other on the left edge of the map) at every zoom level.\n     *\n     * `undefined` is treated as `true`, `null` is treated as `false`. The setting has no effect while a projection\n     * registered with {@link addProjection} is active, since such a projection has no world copies.\n     * @example\n     * ```ts\n     * map.setRenderWorldCopies(true);\n     * ```\n     * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/)\n     */\n    setRenderWorldCopies(renderWorldCopies?: boolean | null): this {\n        this._camera.applyTransformChange(tr => tr.setRenderWorldCopies(renderWorldCopies));\n        return this._update();\n    }\n\n    /** Sets or clears the callback overriding how the map constrains the viewport's lnglat and zoom to respect the longitude and latitude bounds.\n     *\n     * @param constrain - A {@link TransformConstrainFunction} callback defining how the viewport should respect the bounds.\n     *\n     * `null` clears the callback and reverts the constrain to the map transform's default constrain function.\n     * @example\n     * ```ts\n     * function customTransformConstrain(lngLat, zoom) {\n     *   return {center: lngLat, zoom: zoom ?? 0};\n     * };\n     * map.setTransformConstrain(customTransformConstrain);\n     * ```\n     * @see [Customize the map transform constrain](https://maplibre.org/maplibre-gl-js/docs/examples/customize-the-map-transform-constrain/)\n     */\n    setTransformConstrain(constrain?: TransformConstrainFunction | null): this {\n        this._camera.applyTransformChange(tr => tr.setConstrainOverride(constrain));\n        return this._update();\n    }\n\n    /**\n     * Returns a [Point](https://github.com/mapbox/point-geometry) representing pixel coordinates, relative to the map's `container`,\n     * that correspond to the specified geographical location.\n     *\n     * A location behind the camera has no corresponding pixel. For such a location the\n     * returned point is outside the viewport, on the side through which the location left\n     * the screen, one viewport width or height away from the edge.\n     *\n     * @param lnglat - The geographical location to project.\n     * @returns The [Point](https://github.com/mapbox/point-geometry) corresponding to `lnglat`, relative to the map's `container`.\n     * @example\n     * ```ts\n     * let coordinate = [-122.420679, 37.772537];\n     * let point = map.project(coordinate);\n     * ```\n     */\n    project(lnglat: LngLatLike): Point {\n        return this._camera.transform.locationToScreenPoint(LngLat.convert(lnglat), this.style && this.terrain);\n    }\n\n    /**\n     * Returns a {@link LngLat} representing geographical coordinates that correspond\n     * to the specified pixel coordinates.\n     *\n     * @param point - The pixel coordinates to unproject.\n     * @returns The {@link LngLat} corresponding to `point`.\n     * @example\n     * ```ts\n     * map.on('click', (e) => {\n     *   // When the map is clicked, get the geographic coordinate.\n     *   let coordinate = map.unproject(e.point);\n     * });\n     * ```\n     */\n    unproject(point: PointLike): LngLat {\n        return this._camera.transform.screenPointToLocation(Point.convert(point), this.terrain);\n    }\n\n    /**\n     * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.\n     * @returns true if the map is moving.\n     * @example\n     * ```ts\n     * let isMoving = map.isMoving();\n     * ```\n     */\n    isMoving(): boolean {\n        return this._camera.isMoving() || this._handlers?.isMoving() || false;\n    }\n\n    /**\n     * Returns true if the map is zooming due to a camera animation or user gesture.\n     * @returns true if the map is zooming.\n     * @example\n     * ```ts\n     * let isZooming = map.isZooming();\n     * ```\n     */\n    isZooming(): boolean {\n        return this._camera.isZooming() || this._handlers?.isZooming() || false;\n    }\n\n    /**\n     * Returns true if the map is rotating due to a camera animation or user gesture.\n     * @returns true if the map is rotating.\n     * @example\n     * ```ts\n     * map.isRotating();\n     * ```\n     */\n    isRotating(): boolean {\n        return this._camera.isRotating() || this._handlers?.isRotating() || false;\n    }\n\n    _createDelegates(type: keyof MapEventType | string, layerIds: string[], listener: Listener): DelegatedListener['delegates'] {\n        if (type === 'mouseenter' || type === 'mouseover') {\n            let mousein = false;\n            const mousemove = (e) => {\n                const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));\n                const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, {layers: existingLayers}) : [];\n                if (!features.length) {\n                    mousein = false;\n                } else if (!mousein) {\n                    mousein = true;\n                    listener.call(this, new MapMouseEvent(type, this, e.originalEvent, {features}));\n                }\n            };\n            const mouseout = () => {\n                mousein = false;\n            };\n            return {mousemove, mouseout};\n        } else if (type === 'mouseleave' || type === 'mouseout') {\n            let mousein = false;\n            const mousemove = (e) => {\n                const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));\n                const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, {layers: existingLayers}) : [];\n                if (features.length) {\n                    mousein = true;\n                } else if (mousein) {\n                    mousein = false;\n                    listener.call(this, new MapMouseEvent(type, this, e.originalEvent));\n                }\n            };\n            const mouseout = (e) => {\n                if (mousein) {\n                    mousein = false;\n                    listener.call(this, new MapMouseEvent(type, this, e.originalEvent));\n                }\n            };\n            return {mousemove, mouseout};\n        } else {\n            const delegate = (e) => {\n                const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));\n                const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, {layers: existingLayers}) : [];\n                if (features.length) {\n                    // Here we need to mutate the original event, so that preventDefault works as expected.\n                    e.features = features;\n                    listener.call(this, e);\n                    delete e.features;\n                }\n            };\n            return {[type]: delegate};\n        }\n    }\n\n    _addDelegatedListener(type: keyof MapEventType | string, delegatedListener: DelegatedListener): void {\n        this._delegatedListeners ||= {} as Record<keyof MapEventType, DelegatedListener[]>;\n        this._delegatedListeners[type] ||= [];\n        this._delegatedListeners[type].push(delegatedListener);\n        for (const event in delegatedListener.delegates) {\n            this.on(event as keyof MapEventType, delegatedListener.delegates[event]);\n        }\n    }\n\n    _removeDelegatedListener(type: string, layerIds: string[], listener: Listener): void {\n        if (!this._delegatedListeners?.[type]) {\n            return;\n        }\n\n        const listeners = this._delegatedListeners[type];\n        for (let i = 0; i < listeners.length; i++) {\n            const delegatedListener = listeners[i];\n            if (\n                delegatedListener.listener === listener &&\n                delegatedListener.layers.length === layerIds.length &&\n                delegatedListener.layers.every((layerId: string) => layerIds.includes(layerId))\n            ) {\n                for (const event in delegatedListener.delegates) {\n                    this.off(event as keyof MapEventType, delegatedListener.delegates[event]);\n                }\n                listeners.splice(i, 1);\n                return;\n            }\n        }\n    }\n\n    /**\n     * @event\n     * Adds a listener for events of a specified type, optionally limited to features in a specified style layer(s).\n     * See {@link MapEventType} and {@link MapLayerEventType} for a full list of events and their description.\n     *\n     * | Event                  | Compatible with `layerId` |\n     * |------------------------|---------------------------|\n     * | `mousedown`            | yes                       |\n     * | `mouseup`              | yes                       |\n     * | `mouseover`            | yes                       |\n     * | `mouseout`             | yes                       |\n     * | `mousemove`            | yes                       |\n     * | `mouseenter`           | yes (required)            |\n     * | `mouseleave`           | yes (required)            |\n     * | `click`                | yes                       |\n     * | `dblclick`             | yes                       |\n     * | `contextmenu`          | yes                       |\n     * | `touchstart`           | yes                       |\n     * | `touchend`             | yes                       |\n     * | `touchcancel`          | yes                       |\n     * | `wheel`                |                           |\n     * | `resize`               |                           |\n     * | `remove`               |                           |\n     * | `touchmove`            |                           |\n     * | `movestart`            |                           |\n     * | `move`                 |                           |\n     * | `moveend`              |                           |\n     * | `dragstart`            |                           |\n     * | `drag`                 |                           |\n     * | `dragend`              |                           |\n     * | `zoomstart`            |                           |\n     * | `zoom`                 |                           |\n     * | `zoomend`              |                           |\n     * | `rotatestart`          |                           |\n     * | `rotate`               |                           |\n     * | `rotateend`            |                           |\n     * | `pitchstart`           |                           |\n     * | `pitch`                |                           |\n     * | `pitchend`             |                           |\n     * | `boxzoomstart`         |                           |\n     * | `boxzoomend`           |                           |\n     * | `boxzoomcancel`        |                           |\n     * | `webglcontextlost`     |                           |\n     * | `webglcontextrestored` |                           |\n     * | `load`                 |                           |\n     * | `render`               |                           |\n     * | `idle`                 |                           |\n     * | `error`                |                           |\n     * | `data`                 |                           |\n     * | `styledata`            |                           |\n     * | `sourcedata`           |                           |\n     * | `dataloading`          |                           |\n     * | `styledataloading`     |                           |\n     * | `sourcedataloading`    |                           |\n     * | `styleimagemissing`    |                           |\n     * | `dataabort`            |                           |\n     * | `sourcedataabort`      |                           |\n     *\n     * @param type - The event type to listen for. Events compatible with the optional `layerId` parameter are triggered\n     * when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.\n     * @param layer - The ID of a style layer or a listener if no ID is provided. Event will only be triggered if its location\n     * is within a visible feature in this layer. The event will have a `features` property containing\n     * an array of the matching features. If `layer` is not supplied, the event will not have a `features` property.\n     * Please note that many event types are not compatible with the optional `layer` parameter.\n     * @param listener - The function to be called when the event is fired.\n     * @example\n     * ```ts\n     * // Set an event listener that will fire\n     * // when the map has finished loading\n     * map.on('load', () => {\n     *   // Once the map has finished loading,\n     *   // add a new layer\n     *   map.addLayer({\n     *     id: 'points-of-interest',\n     *     source: {\n     *       type: 'vector',\n     *       url: 'https://maplibre.org/maplibre-style-spec/'\n     *     },\n     *     'source-layer': 'poi_label',\n     *     type: 'circle',\n     *     paint: {\n     *       // MapLibre Style Specification paint properties\n     *     },\n     *     layout: {\n     *       // MapLibre Style Specification layout properties\n     *     }\n     *   });\n     * });\n     * ```\n     * @example\n     * ```ts\n     * // Set an event listener that will fire\n     * // when a feature on the countries layer of the map is clicked\n     * map.on('click', 'countries', (e) => {\n     *   new Popup()\n     *     .setLngLat(e.lngLat)\n     *     .setText(`Country name: ${e.features[0].properties.name}`)\n     *     .addTo(map);\n     * });\n     * ```\n     * @see [Display popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)\n     * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-the-map-on-a-clicked-symbol/)\n     * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)\n     * @see [Create a draggable marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    on<T extends keyof MapLayerEventType>(\n        type: T,\n        layer: string,\n        listener: (ev: MapLayerEventType[T] & Object) => void,\n    ): Subscription;\n    /**\n     * Overload of the `on` method that allows to listen to events specifying multiple layers.\n     * @event\n     * @param type - The type of the event.\n     * @param layerIds - The array of style layer IDs.\n     * @param listener - The listener callback.\n     */\n    on<T extends keyof MapLayerEventType>(\n        type: T,\n        layerIds: string[],\n        listener: (ev: MapLayerEventType[T] & Object) => void\n    ): Subscription;\n    /**\n     * Overload of the `on` method that allows to listen to events without specifying a layer.\n     * @event\n     * @param type - The type of the event.\n     * @param listener - The listener callback.\n     */\n    on<T extends keyof MapEventType>(type: T, listener: (ev: MapEventType[T] & Object) => void): Subscription;\n    /**\n     * Overload of the `on` method that allows to listen to events without specifying a layer.\n     * @event\n     * @param type - The type of the event.\n     * @param listener - The listener callback.\n     */\n    on(type: keyof MapEventType, listener: Listener): Subscription;\n    on(type: keyof MapEventType, layerIdsOrListener: string | string[] | Listener, listener?: Listener): Subscription {\n        if (listener === undefined) {\n            return super.on(type, layerIdsOrListener as Listener);\n        }\n\n        const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener as string[];\n\n        const delegatedListener: DelegatedListener = {layers: layerIds, listener, delegates: this._createDelegates(type, layerIds, listener)};\n        this._addDelegatedListener(type, delegatedListener);\n\n        return {\n            unsubscribe: () => {\n                this._removeDelegatedListener(type, layerIds, listener);\n            }\n        };\n    }\n\n    /**\n     * Adds a listener that will be called only once to a specified event type, optionally limited to features in a specified style layer.\n     *\n     * @event\n     * @param type - The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`,\n     * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`,\n     * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters\n     * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave`\n     * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves\n     * the map canvas.\n     * @param layer - The ID of a style layer or a listener if no ID is provided. Only events whose location is within a visible\n     * feature in this layer will trigger the listener. The event will have a `features` property containing\n     * an array of the matching features.\n     * @param listener - The function to be called when the event is fired.\n     * @returns `this` if listener is provided, promise otherwise to allow easier usage of async/await\n     */\n    once<T extends keyof MapLayerEventType>(\n        type: T,\n        layer: string,\n        listener: (ev: MapLayerEventType[T] & Object) => void,\n    ): this;\n    /**\n     * Overload of the `once` method that, with a single layer and no listener, returns a promise\n     * resolving with the event for easier usage of async/await.\n     * @event\n     * @param type - The type of the event.\n     * @param layer - The ID of the style layer.\n     */\n    once<T extends keyof MapLayerEventType>(\n        type: T,\n        layer: string,\n    ): Promise<MapLayerEventType[T] & Object>;\n    /**\n     * Overload of the `once` method that allows to listen to events specifying multiple layers.\n     * @event\n     * @param type - The type of the event.\n     * @param layerIds - The array of style layer IDs.\n     * @param listener - The listener callback.\n     */\n    once<T extends keyof MapLayerEventType>(\n        type: T,\n        layerIds: string[],\n        listener: (ev: MapLayerEventType[T] & Object) => void\n    ): this;\n    /**\n     * Overload of the `once` method that, with multiple layers and no listener, returns a promise\n     * resolving with the event for easier usage of async/await.\n     * @event\n     * @param type - The type of the event.\n     * @param layerIds - The array of style layer IDs.\n     */\n    once<T extends keyof MapLayerEventType>(\n        type: T,\n        layerIds: string[],\n    ): Promise<MapLayerEventType[T] & Object>;\n    /**\n     * Overload of the `once` method that allows to listen to events without specifying a layer.\n     * @event\n     * @param type - The type of the event.\n     * @param listener - The listener callback.\n     */\n    once<T extends keyof MapEventType>(type: T, listener: (ev: MapEventType[T] & Object) => void): this;\n    /**\n     * Overload of the `once` method that returns a promise resolving with the event,\n     * for easier usage of async/await, when no listener is provided.\n     * @event\n     * @param type - The type of the event.\n     */\n    once<T extends keyof MapEventType>(type: T): Promise<MapEventType[T] & Object>;\n    /**\n     * Overload of the `once` method that allows to listen to events without specifying a layer.\n     * @event\n     * @param type - The type of the event.\n     * @param listener - The listener callback.\n     */\n    once(type: keyof MapEventType, listener?: Listener): this | Promise<any>;\n    once(type: keyof MapEventType, layerIdsOrListener?: string | string[] | Listener, listener?: Listener): this | Promise<any> {\n        if (listener === undefined) {\n            return super.once(type, layerIdsOrListener as Listener);\n        }\n\n        const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener as string[];\n\n        const delegatedListener: DelegatedListener = {layers: layerIds, listener, delegates: this._createDelegates(type, layerIds, (e) => {\n            this._removeDelegatedListener(type, layerIds, listener);\n            listener.call(this, e);\n        })};\n        this._addDelegatedListener(type, delegatedListener);\n\n        return this;\n    }\n\n    /**\n     * Removes an event listener for events previously added with `{@link Map.on}`.\n     *\n     * @event\n     * @param type - The event type previously used to install the listener.\n     * @param layer - The layer ID or listener previously used to install the listener.\n     * @param listener - The function previously installed as a listener.\n     */\n    off<T extends keyof MapLayerEventType>(\n        type: T,\n        layer: string,\n        listener: (ev: MapLayerEventType[T] & Object) => void,\n    ): this;\n    /**\n     * Overload of the `off` method that allows to remove an event created with multiple layers.\n     * Provide the same layer IDs as to `on` or `once`, when the listener was registered.\n     * @event\n     * @param type - The type of the event.\n     * @param layers - The layer IDs previously used to install the listener.\n     * @param listener - The function previously installed as a listener.\n     */\n    off<T extends keyof MapLayerEventType>(\n        type: T,\n        layers: string[],\n        listener: (ev: MapLayerEventType[T] & Object) => void,\n    ): this;\n    /**\n     * Overload of the `off` method that allows to remove an event created without specifying a layer.\n     * @event\n     * @param type - The type of the event.\n     * @param listener - The function previously installed as a listener.\n     */\n    off<T extends keyof MapEventType>(type: T, listener: (ev: MapEventType[T] & Object) => void): this;\n    /**\n     * Overload of the `off` method that allows to remove an event created without specifying a layer.\n     * @event\n     * @param type - The type of the event.\n     * @param listener - The function previously installed as a listener.\n     */\n    off(type: keyof MapEventType, listener: Listener): this;\n    off(type: keyof MapEventType, layerIdsOrListener: string | string[] | Listener, listener?: Listener): this {\n        if (listener === undefined) {\n            return super.off(type, layerIdsOrListener as Listener);\n        }\n\n        const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener as string[];\n        this._removeDelegatedListener(type, layerIds, listener);\n\n        return this;\n    }\n\n    /**\n     * Returns an array of MapGeoJSONFeature objects\n     * representing visible features that satisfy the query parameters.\n     *\n     * @param geometryOrOptions - (optional) The geometry of the query region in pixel points within the map viewport:\n     * either a single pixel point or a pair of top-left and bottom-right pixel points describing a bounding box.\n     * The origin of the pixel points is at the top-left of the map viewport.\n     * Omitting this parameter (i.e. calling {@link Map.queryRenderedFeatures} with zero arguments,\n     * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire\n     * map viewport.\n     * The geometryOrOptions can receive a {@link QueryRenderedFeaturesOptions} only to support a situation where the function receives only one parameter which is the options parameter.\n     * @param options - (optional) Options object.\n     *\n     * @returns An array of MapGeoJSONFeature objects.\n     *\n     * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only\n     * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported).\n     *\n     * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object\n     * representing the style layer to  which the feature belongs. Layout and paint properties in this object contain values\n     * which are fully evaluated for the given zoom level and feature.\n     *\n     * Only features that are currently rendered are included. Some features will **not** be included, like:\n     *\n     * - Features from layers whose `visibility` property is `\"none\"`.\n     * - Features from layers whose zoom range excludes the current zoom level.\n     * - Symbol features that have been hidden due to text or icon collision.\n     *\n     * Features from all other layers are included, including features that may have no visible\n     * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to\n     * 0.\n     *\n     * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by\n     * descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low\n     * zoom levels) are returned only once (though subject to the following caveat).\n     *\n     * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature\n     * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple\n     * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.\n     * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding\n     * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile\n     * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple\n     * tiles due to tile buffering.\n     *\n     * @example\n     * Find all features at a point\n     * ```ts\n     * let features = map.queryRenderedFeatures(\n     *   [20, 35],\n     *   { layers: ['my-layer-name'] }\n     * );\n     * ```\n     *\n     * @example\n     * Find all features within a static bounding box\n     * ```ts\n     * let features = map.queryRenderedFeatures(\n     *   [[10, 20], [30, 50]],\n     *   { layers: ['my-layer-name'] }\n     * );\n     * ```\n     *\n     * @example\n     * Find all features within a bounding box around a point\n     * ```ts\n     * let width = 10;\n     * let height = 20;\n     * let features = map.queryRenderedFeatures([\n     *   [point.x - width / 2, point.y - height / 2],\n     *   [point.x + width / 2, point.y + height / 2]\n     * ], { layers: ['my-layer-name'] });\n     * ```\n     *\n     * @example\n     * Query all rendered features from a single layer\n     * ```ts\n     * let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });\n     * ```\n     * @see [Get features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-features-under-the-mouse-pointer/)\n     */\n    queryRenderedFeatures(geometryOrOptions?: PointLike | [PointLike, PointLike] | QueryRenderedFeaturesOptions, options?: QueryRenderedFeaturesOptions): MapGeoJSONFeature[] {\n        if (!this.style) {\n            return [];\n        }\n        let queryGeometry: Point[];\n        const isGeometry = geometryOrOptions instanceof Point || Array.isArray(geometryOrOptions);\n        const geometry = isGeometry ? geometryOrOptions : [[0, 0], [this._camera.transform.width, this._camera.transform.height]];\n        options ||= (isGeometry ? {} : geometryOrOptions) || {};\n\n        if (geometry instanceof Point || typeof geometry[0] === 'number') {\n            queryGeometry = [Point.convert(geometry as PointLike)];\n        } else {\n            const tl = Point.convert(geometry[0] as PointLike);\n            const br = Point.convert(geometry[1] as PointLike);\n            queryGeometry = [tl, new Point(br.x, tl.y), br, new Point(tl.x, br.y), tl];\n        }\n\n        return this.style.queryRenderedFeatures(queryGeometry, options, this._camera.transform);\n    }\n\n    /**\n     * Returns an array of MapGeoJSONFeature objects\n     * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.\n     *\n     * @param sourceId - The ID of the vector tile or GeoJSON source to query.\n     * @param parameters - The options object.\n     * @returns An array of MapGeoJSONFeature objects.\n     *\n     * In contrast to {@link Map.queryRenderedFeatures}, this function returns all features matching the query parameters,\n     * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded\n     * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently\n     * visible viewport.\n     *\n     * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature\n     * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple\n     * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.\n     * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding\n     * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile\n     * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple\n     * tiles due to tile buffering.\n     *\n     * @example\n     * Find all features in one source layer in a vector source\n     * ```ts\n     * let features = map.querySourceFeatures('your-source-id', {\n     *   sourceLayer: 'your-source-layer'\n     * });\n     * ```\n     *\n     */\n    querySourceFeatures(sourceId: string, parameters?: QuerySourceFeatureOptions | null): GeoJSONFeature[] {\n        return this.style.querySourceFeatures(sourceId, parameters);\n    }\n\n    /**\n     * Updates the map's MapLibre style object with a new value.\n     *\n     * 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\n     * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites\n     * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current\n     * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building\n     * the given one from scratch.\n     *\n     *\n     * @param style - A JSON object conforming to the schema described in the\n     * [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), or a URL to such JSON.\n     * @param options - The options object.\n     *\n     * @example\n     * ```ts\n     * map.setStyle(\"https://demotiles.maplibre.org/style.json\");\n     *\n     * map.setStyle('https://demotiles.maplibre.org/style.json', {\n     *   transformStyle: (previousStyle, nextStyle) => ({\n     *       ...nextStyle,\n     *       sources: {\n     *           ...nextStyle.sources,\n     *           // copy a source from previous style\n     *           'osm': previousStyle.sources.osm\n     *       },\n     *       layers: [\n     *           // background layer\n     *           nextStyle.layers[0],\n     *           // copy a layer from previous style\n     *           previousStyle.layers[0],\n     *           // other layers from the next style\n     *           ...nextStyle.layers.slice(1).map(layer => {\n     *               // hide the layers we don't need from demotiles style\n     *               if (layer.id.startsWith('geolines')) {\n     *                   layer.layout = {...layer.layout || {}, visibility: 'none'};\n     *               // filter out US polygons\n     *               } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) {\n     *                   layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA'];\n     *               }\n     *               return layer;\n     *           })\n     *       ]\n     *   })\n     * });\n     *\n     * map.setStyle('https://demotiles.maplibre.org/style.json', {\n     *   globalState: {\n     *     showCircles: true,\n     *   }\n     * });\n     * ```\n     */\n    setStyle(style: StyleSpecification | string | null, options?: StyleSwapOptions & StyleOptions): this {\n        options = extend({},\n            {\n                localIdeographFontFamily: this._localIdeographFontFamily,\n                validate: this._validateStyle,\n                globalState: this._initialGlobalState,\n                transformStyle: this._transformStyle,\n            }, options);\n        this._styleUrl = typeof style === 'string' ? style : null;\n\n        if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) {\n            this._diffStyle(style, options);\n            return this;\n        } else {\n            this._localIdeographFontFamily = options.localIdeographFontFamily;\n            return this._updateStyle(style, options);\n        }\n    }\n\n    /**\n     *  Updates the requestManager's transform request with a new function\n     *\n     * @param transformRequest - 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.\n     * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties\n     *\n     * @example\n     * ```ts\n     * map.setTransformRequest((url: string, resourceType: string) => {});\n     * ```\n     */\n    setTransformRequest(transformRequest: RequestTransformFunction | null): this {\n        this._requestManager.setTransformRequest(transformRequest);\n        return this;\n    }\n\n    _getUIString(key: keyof typeof defaultLocale): string {\n        const str = this._locale[key];\n        if (str == null) {\n            throw new Error(`Missing UI string '${key}'`);\n        }\n\n        return str;\n    }\n\n    _updateStyle(style: StyleSpecification | string | null, options?: StyleSwapOptions & StyleOptions): this {\n        this._diffStyleRequest?.abort();\n        this._diffStyleRequest = null;\n        // transformStyle relies on having previous style serialized, if it is not loaded yet, delay _updateStyle until previous style is loaded\n        if (options.transformStyle && this.style && !this.style._loaded) {\n            this.style.once('style.load', () => this._updateStyle(style, options));\n            return;\n        }\n\n        const previousStyle = this.style && options.transformStyle ? this.style.serialize() : undefined;\n        if (this.style) {\n            this.style.off('error', this._onStyleError);\n            this.style.setEventedParent(null);\n\n            // Only release workers when map is getting disposed\n            this.style._remove(!style);\n        }\n\n        if (!style) {\n            if (this._frameRequest) {\n                this._frameRequest.abort();\n                this._frameRequest = null;\n            }\n            this.style?.projection?.destroy();\n            delete this.style;\n            return this;\n        } else {\n            this.style = new Style(this, options || {});\n        }\n\n        this.style.setEventedParent(this, {style: this.style});\n        this.style.on('error', this._onStyleError);\n\n        if (typeof style === 'string') {\n            this.style.loadURL(style, options, previousStyle);\n        } else {\n            this.style.loadJSON(style, options, previousStyle);\n        }\n\n        return this;\n    }\n\n    _lazyInitEmptyStyle(): void {\n        if (!this.style) {\n            this.style = new Style(this, {});\n            this.style.setEventedParent(this, {style: this.style});\n            this.style.on('error', this._onStyleError);\n            this.style.loadEmpty();\n        }\n    }\n\n    async _diffStyle(style: StyleSpecification | string, options?: StyleSwapOptions & StyleOptions): Promise<void> {\n        this._diffStyleRequest?.abort();\n        if (typeof style === 'string') {\n            const url = style;\n            this._diffStyleRequest = new AbortController();\n            const abortController = this._diffStyleRequest;\n            try {\n                const request = await this._requestManager.transformRequest(url, ResourceType.Style);\n                if (abortController.signal.aborted) {\n                    this._diffStyleRequest = null;\n                    return;\n                }\n\n                const response = await getJSON<StyleSpecification>(request, abortController);\n                this._diffStyleRequest = null;\n                this._updateDiff(response.data, options);\n            } catch (error) {\n                this._diffStyleRequest = null;\n                if (!isAbortError(error)) {\n                    this.fire(new ErrorEvent(ensureError(error)));\n                }\n            }\n        } else if (typeof style === 'object') {\n            this._diffStyleRequest = null;\n            this._updateDiff(style, options);\n        }\n    }\n\n    _updateDiff(style: StyleSpecification, options?: StyleSwapOptions & StyleOptions): void {\n        try {\n            if (this.style.setState(style, options)) {\n                this._update(true);\n            }\n        } catch (e) {\n            warnOnce(\n                `Unable to perform style diff: ${ensureError(e).message}.  Rebuilding the style from scratch.`\n            );\n            this._updateStyle(style, options);\n        }\n    }\n\n    /**\n     * Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style.\n     *\n     * @returns The map's style JSON object.\n     *\n     * @example\n     * ```ts\n     * let styleJson = map.getStyle();\n     * ```\n     *\n     */\n    getStyle(): StyleSpecification {\n        if (this.style) {\n            return this.style.serialize();\n        }\n    }\n\n    /**\n     * Returns the URL the map's style was loaded from.\n     *\n     * @returns The URL given to {@link Map.setStyle} or the `style` map option, or `null` when the style was given as an object or the map has no style.\n     *\n     * @example\n     * ```ts\n     * const styleUrl = map.getStyleUrl();\n     * ```\n     */\n    getStyleUrl(): string | null {\n        return this._styleUrl;\n    }\n\n    /**\n     * @internal\n     * Snapshots the serialized style and cloned images so {@link Map._restoreStyleSnapshot} can rebuild them.\n     */\n    _takeStyleSnapshot(): StyleSnapshot {\n        if (this.style) {\n            return {\n                style: this.style.serialize(),\n                images: this.style.imageManager.cloneImages()\n            };\n        }\n        return {style: null, images: {}};\n    }\n\n    /**\n     * Returns a Boolean indicating whether the map's style is fully loaded.\n     *\n     * @returns A Boolean indicating whether the style is fully loaded.\n     *\n     * @example\n     * ```ts\n     * let styleLoadStatus = map.isStyleLoaded();\n     * ```\n     */\n    isStyleLoaded(): boolean | void {\n        if (!this.style) {\n            warnOnce('There is no style added to the map.');\n            return;\n        }\n        return this.style.loaded();\n    }\n\n    /**\n     * Adds a source to the map's style.\n     *\n     * Events triggered:\n     *\n     * Triggers the `source.add` event.\n     *\n     * @param id - The ID of the source to add. Must not conflict with existing sources.\n     * @param source - The source object, conforming to the\n     * MapLibre Style Specification's [source definition](https://maplibre.org/maplibre-style-spec/sources) or\n     * {@link CanvasSourceSpecification}.\n     * @example\n     * ```ts\n     * map.addSource('my-data', {\n     *   type: 'vector',\n     *   url: 'https://demotiles.maplibre.org/tiles/tiles.json'\n     * });\n     * ```\n     * @example\n     * ```ts\n     * map.addSource('my-data', {\n     *   \"type\": \"geojson\",\n     *   \"data\": {\n     *     \"type\": \"Feature\",\n     *     \"geometry\": {\n     *       \"type\": \"Point\",\n     *       \"coordinates\": [-77.0396, 38.8891]\n     *     },\n     *     \"properties\": {\n     *       \"title\": \"Washington DC\",\n     *       \"marker-symbol\": \"monument\"\n     *     }\n     *   }\n     * });\n     * ```\n     * @see GeoJSON source: [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/add-live-realtime-data/)\n     */\n    addSource(id: string, source: SourceSpecification | CanvasSourceSpecification): this {\n        this._lazyInitEmptyStyle();\n        this.style.addSource(id, source);\n        return this._update(true);\n    }\n\n    /**\n     * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with\n     * the given ID in the map's style has no outstanding network requests, otherwise `false`.\n     *\n     * A {@link ErrorEvent} event will be fired if there is no source with the specified ID.\n     *\n     * @param id - The ID of the source to be checked.\n     * @returns A Boolean indicating whether the source is loaded.\n     * @example\n     * ```ts\n     * let sourceLoaded = map.isSourceLoaded('bathymetry-data');\n     * ```\n     */\n    isSourceLoaded(id: string): boolean {\n        const tileManager = this.style?.tileManagers[id];\n        if (tileManager === undefined) {\n            this.fire(new ErrorEvent(new Error(`There is no tile manager with ID '${id}'`)));\n            return;\n        }\n        return tileManager.loaded();\n    }\n\n    /**\n     * Loads a 3D terrain mesh, based on a \"raster-dem\" source.\n     *\n     * Triggers the `terrain` event.\n     *\n     * @param options - Options object.\n     * @example\n     * ```ts\n     * map.setTerrain({ source: 'terrain' });\n     * ```\n     */\n    setTerrain(options: TerrainSpecification | null, styleOptions: StyleSetterOptions = {}): this {\n        this.style._checkLoaded();\n\n        if (options && validateAndEmit(this, validateStyle.terrain, {value: options}, styleOptions)) {\n            return this;\n        }\n\n        // clear event handlers\n        if (this._terrainDataCallback) this.style.off('data', this._terrainDataCallback);\n\n        if (!options) {\n            // remove terrain\n            if (this.terrain) {\n                this.terrain.destroy();\n            }\n            this.terrain = null;\n            this.painter.renderToTexture = null;\n            this.painter.destroyRTTResources();\n            this._camera.setTerrain(null);\n        } else {\n            // add terrain\n            const tileManager = this.style.tileManagers[options.source];\n            if (!tileManager) throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`);\n            // Update terrain tiles when adding new terrain\n            if (this.terrain === null) tileManager.reload();\n            // Warn once if user is using the same source for hillshade/color-relief and terrain\n            for (const index in this.style._layers) {\n                const thisLayer = this.style._layers[index];\n                if (thisLayer.type === 'hillshade' && thisLayer.source === options.source) {\n                    warnOnce('You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.');\n                }\n                if (thisLayer.type === 'color-relief' && thisLayer.source === options.source) {\n                    warnOnce('You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.');\n                }\n            }\n            if (this.terrain) {\n                this.terrain.destroy();\n            }\n            this.terrain = new Terrain(this.painter, tileManager, options, this._terrainSkirtLength, () => this._camera.transform.worldCoordinateHelper);\n            this.painter.renderToTexture = new RenderToTexture(this.painter, this.terrain);\n            this._camera.setTerrain(this.terrain);\n            this._terrainDataCallback = e => this._handleTerrainDataEvent(e, options.source);\n            this.style.on('data', this._terrainDataCallback);\n        }\n\n        this.style.triggerSymbolPlacement();\n        this.fire(new MapTerrainEvent({terrain: options}));\n        return this;\n    }\n\n    private _handleTerrainDataEvent(event: MapStyleDataEvent | MapSourceDataEvent, terrainSourceId: string): void {\n        if (event.dataType === 'style') {\n            this.terrain.tileManager.releaseAllRTT();\n            return;\n        }\n\n        const isTerrainSourceEvent = event.sourceId === terrainSourceId;\n        if (isTerrainSourceEvent) {\n            this.terrain.resetElevationCache();\n            this.style.triggerSymbolPlacement();\n        }\n        if (isTerrainSourceEvent && event.tile) {\n            this.painter.markTerrainDepthDirty();\n            this._camera.applyTerrainChange();\n        }\n\n        if (!event.tile) return;\n        if (event.source?.type === 'image') {\n            this.terrain.tileManager.releaseAllRTT();\n            return;\n        }\n        this.terrain.tileManager.releaseRTT(event.tile.tileID);\n    }\n\n    /**\n     * Get the terrain-options if terrain is loaded\n     * @returns the TerrainSpecification passed to setTerrain\n     * @example\n     * ```ts\n     * map.getTerrain(); // { source: 'terrain' };\n     * ```\n     */\n    getTerrain(): TerrainSpecification | null {\n        return this.terrain?.options ?? null;\n    }\n\n    /**\n     * Returns a Boolean indicating whether all tiles in the viewport from all sources on\n     * the style are loaded.\n     *\n     * @returns A Boolean indicating whether all tiles are loaded.\n     * @example\n     * ```ts\n     * let tilesLoaded = map.areTilesLoaded();\n     * ```\n     */\n    areTilesLoaded(): boolean {\n        const tileManagers = this.style?.tileManagers;\n        for (const tileManager of Object.values(tileManagers)) {\n            if (!tileManager.areTilesLoaded()) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * Removes a source from the map's style.\n     *\n     * @param id - The ID of the source to remove.\n     * @example\n     * ```ts\n     * map.removeSource('bathymetry-data');\n     * ```\n     */\n    removeSource(id: string): this {\n        this.style.removeSource(id);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the source with the specified ID in the map's style.\n     *\n     * This method is often used to update a source using the instance members for the relevant\n     * source type as defined in classes that derive from {@link Source}.\n     * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates`\n     * of an image source.\n     *\n     * @param id - The ID of the source to get.\n     * @returns The style source with the specified ID or `undefined` if the ID\n     * corresponds to no existing sources. Also returns `undefined` after a WebGL context\n     * loss until the restored style fires `style.load`.\n     * The shape of the object varies by source type.\n     * A list of options for each source type is available on the MapLibre Style Specification's\n     * [Sources](https://maplibre.org/maplibre-style-spec/sources/) page.\n     * @example\n     * ```ts\n     * let sourceObject = map.getSource('points');\n     * ```\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-a-point/)\n     * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/add-live-realtime-data/)\n     */\n    getSource<TSource extends Source>(id: string): TSource | undefined {\n        return this.style?.getSource(id) as TSource | undefined;\n    }\n\n    /**\n     * Change the tile Level of Detail behavior of the specified source. These parameters have no effect when\n     * pitch == 0, and the largest effect when the horizon is visible on screen.\n     *\n     * @param maxZoomLevelsOnScreen - The maximum number of distinct zoom levels allowed on screen at a time.\n     * There will generally be fewer zoom levels on the screen, the maximum can only be reached when the horizon\n     * is at the top of the screen. Increasing the maximum number of zoom levels causes the zoom level to decay\n     * faster toward the horizon.\n     * @param tileCountMaxMinRatio - The ratio of the maximum number of tiles loaded (at high pitch) to the minimum\n     * number of tiles loaded. Increasing this ratio allows more tiles to be loaded at high pitch angles. If the ratio\n     * would otherwise be exceeded, the zoom level is reduced uniformly to keep the number of tiles within the limit.\n     * @param sourceId - The ID of the source to set tile LOD parameters for. All sources will be updated if unspecified.\n     * If `sourceId` is specified but a corresponding source does not exist, an error is thrown.\n     * @example\n     * ```ts\n     * map.setSourceTileLodParams(4.0, 3.0, 'terrain');\n     * ```\n     * @see [Modify Level of Detail behavior](https://maplibre.org/maplibre-gl-js/docs/examples/level-of-detail-control/)\n\n     */\n    setSourceTileLodParams(maxZoomLevelsOnScreen: number, tileCountMaxMinRatio: number, sourceId?: string) : this {\n        if (sourceId) {\n            const source = this.getSource(sourceId);\n            if(!source) {\n                throw new Error(`There is no source with ID \"${sourceId}\", cannot set LOD parameters`);\n            }\n            source.calculateTileZoom = createCalculateTileZoomFunction(Math.max(1, maxZoomLevelsOnScreen), Math.max(1, tileCountMaxMinRatio));\n        } else {\n            for (const id in this.style.tileManagers) {\n                this.style.tileManagers[id].getSource().calculateTileZoom = createCalculateTileZoomFunction(Math.max(1, maxZoomLevelsOnScreen), Math.max(1, tileCountMaxMinRatio));\n            }\n        }\n        this._update(true);\n        return this;\n    }\n\n    /**\n     * Triggers a reload of the selected tiles\n     *\n     * @param sourceId - The ID of the source\n     * @param tileIds - An array of tile IDs to be reloaded. If not defined, all tiles will be reloaded.\n     * @example\n     * ```ts\n     * map.refreshTiles('satellite', [{x:1024, y: 1023, z: 11}, {x:1023, y: 1023, z: 11}]);\n     * ```\n     */\n    refreshTiles(sourceId: string, tileIds?: Array<{x: number; y: number; z: number}>): void {\n        const tileManager = this.style.tileManagers[sourceId];\n        if(!tileManager) {\n            throw new Error(`There is no tile manager with ID \"${sourceId}\", cannot refresh tile`);\n        }\n        if (tileIds === undefined) {\n            tileManager.reload(true);\n        } else {\n            tileManager.refreshTiles(tileIds.map((tileId) => {return new CanonicalTileID(tileId.z, tileId.x, tileId.y);}));\n        }\n    }\n\n    /**\n     * Add an image to the style. This image can be displayed on the map like any other icon in the style's\n     * sprite using the image's ID with\n     * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image),\n     * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern),\n     * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern),\n     * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern).\n     *\n     * A {@link ErrorEvent} event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image.\n     *\n     * @param id - The ID of the image.\n     * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`\n     * properties with the same format as `ImageData`.\n     * @param options - Options object.\n     * @example\n     * ```ts\n     * // If the style's sprite does not already contain an image with ID 'cat',\n     * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.\n     * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png');\n     * if (!map.hasImage('cat')) map.addImage('cat', image.data);\n     *\n     * // Add a stretchable image that can be used with `icon-text-fit`\n     * // In this example, the image is 600px wide by 400px high.\n     * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png');\n     * if (map.hasImage('border-image')) return;\n     * map.addImage('border-image', image.data, {\n     *     content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border\n     *     stretchX: [[16, 584]], // stretch everything horizontally except the 16px border\n     *     stretchY: [[16, 384]], // stretch everything vertically except the 16px border\n     * });\n     * ```\n     * @see Use `HTMLImageElement`: [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-an-icon-to-the-map/)\n     * @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-generated-icon-to-the-map/)\n     */\n    addImage(id: string, image: StyleImageSource, options: Partial<StyleImageMetadata> = {}): this {\n        this._lazyInitEmptyStyle();\n        const styleImage = this._createStyleImage(image, options);\n        if (!styleImage) {\n            return this;\n        }\n\n        this.style.addImage(id, styleImage);\n        if (styleImage.userImage?.onAdd) {\n            styleImage.userImage.onAdd(this, id);\n        }\n        return this;\n    }\n\n    /**\n     * Sets a callback that is invoked when an icon or pattern needed by the style is missing.\n     *\n     * The resolver typically loads or generates the image and registers it with {@link Map.addImage}.\n     * MapLibre awaits the returned promise before treating the image as missing, so async work is\n     * supported. If the image is still missing afterwards, the `styleimagemissing` event is fired.\n     *\n     * @param resolver - Callback used to resolve missing images, or `null` to remove the resolver.\n     * @example\n     * ```ts\n     * map.setMissingStyleImageResolver(async (id) => {\n     *     const response = await fetch(`/icons/${id}.png`);\n     *     const image = await createImageBitmap(await response.blob());\n     *     map.addImage(id, image, {pixelRatio: 2});\n     * });\n     * ```\n     */\n    setMissingStyleImageResolver(resolver: MissingStyleImageResolver | null): this {\n        this._missingStyleImageResolver = resolver;\n        this.style?.setMissingImageResolver(resolver);\n        return this;\n    }\n\n    _createStyleImage(image: StyleImageSource, options: Partial<StyleImageMetadata> = {}): StyleImage | null {\n        const {\n            pixelRatio = 1,\n            sdf = false,\n            stretchX,\n            stretchY,\n            content,\n            textFitWidth,\n            textFitHeight\n        } = options;\n        const version = 0;\n\n        if (image instanceof HTMLImageElement || isImageBitmap(image)) {\n            const {width, height, data} = browser.getImageData(image);\n            return {data: new RGBAImage({width, height}, data), pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight, sdf, version};\n        } else if (image.width === undefined || image.height === undefined) {\n            this.fire(new ErrorEvent(new Error(\n                'Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +\n                'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));\n            return null;\n        } else {\n            const {width, height, data} = image as ImageData;\n            const userImage = (image as any as StyleImageInterface);\n            const isWebGLImage = isStyleImageWebGLData(userImage.data);\n\n            return {\n                // A WebGL image paints its own slot, so its pixels are only ever transparent padding.\n                data: isWebGLImage ? new RGBAImage({width, height}) : new RGBAImage({width, height}, new Uint8Array(data)),\n                pixelRatio,\n                stretchX,\n                stretchY,\n                content,\n                textFitWidth,\n                textFitHeight,\n                sdf,\n                version,\n                isWebGLImage,\n                userImage\n            };\n        }\n    }\n\n    /**\n     * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's\n     * sprite using the image's ID with\n     * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image),\n     * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern),\n     * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern),\n     * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern).\n     *\n     * An {@link ErrorEvent} will be fired if the image parameter is invalid.\n     *\n     * @param id - The ID of the image.\n     * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`\n     * properties with the same format as `ImageData`.\n     * @example\n     * ```ts\n     * // If an image with the ID 'cat' already exists in the style's sprite,\n     * // replace that image with a new image, 'other-cat-icon.png'.\n     * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');\n     * ```\n     */\n    updateImage(id: string, image: StyleImageSource): this {\n\n        const existingImage = this.style.getImage(id);\n        if (!existingImage) {\n            return this.fire(new ErrorEvent(new Error(\n                'The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.')));\n        }\n        const imageData = (image instanceof HTMLImageElement || isImageBitmap(image)) ?\n            browser.getImageData(image) :\n            image;\n        const {width, height, data} = imageData;\n\n        if (width === undefined || height === undefined) {\n            return this.fire(new ErrorEvent(new Error(\n                'Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +\n                'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));\n        }\n\n        if (width !== existingImage.data.width || height !== existingImage.data.height) {\n            return this.fire(new ErrorEvent(new Error(\n                'The width and height of the updated image must be that same as the previous version of the image')));\n        }\n\n        existingImage.isWebGLImage = isStyleImageWebGLData(data);\n        if (existingImage.isWebGLImage) {\n            existingImage.userImage = image as StyleImageInterface;\n        } else {\n            const copy = !(image instanceof HTMLImageElement || isImageBitmap(image));\n            existingImage.data.replace(data as Uint8Array | Uint8ClampedArray, copy);\n        }\n\n        this.style.updateImage(id, existingImage);\n        return this;\n    }\n\n    /**\n     * Returns an image, specified by ID, currently available in the map.\n     * This includes both images from the style's original sprite\n     * and any images that have been added at runtime using {@link Map.addImage}.\n     *\n     * @param id - The ID of the image.\n     * @returns An image in the map with the specified ID.\n     *\n     * @example\n     * ```ts\n     * let coffeeShopIcon = map.getImage(\"coffee_cup\");\n     * ```\n     */\n    getImage(id: string): StyleImage {\n        return this.style.getImage(id);\n    }\n\n    /**\n     * Check whether or not an image with a specific ID exists in the style. This checks both images\n     * in the style's original sprite and any images\n     * that have been added at runtime using {@link Map.addImage}.\n     *\n     * An {@link ErrorEvent} will be fired if the image ID is missing.\n     *\n     * @param id - The ID of the image.\n     *\n     * @returns A Boolean indicating whether the image exists.\n     * @example\n     * Check if an image with the ID 'cat' exists in the style's sprite.\n     * ```ts\n     * let catIconExists = map.hasImage('cat');\n     * ```\n     */\n    hasImage(id: string): boolean {\n        if (!id) {\n            this.fire(new ErrorEvent(new Error('Missing required image id')));\n            return false;\n        }\n\n        return !!this.style.getImage(id);\n    }\n\n    /**\n     * Remove an image from a style. This can be an image from the style's original\n     * sprite or any images\n     * that have been added at runtime using {@link Map.addImage}.\n     *\n     * @param id - The ID of the image.\n     *\n     * @example\n     * ```ts\n     * // If an image with the ID 'cat' exists in\n     * // the style's sprite, remove it.\n     * if (map.hasImage('cat')) map.removeImage('cat');\n     * ```\n     */\n    removeImage(id: string): void {\n        this.style.removeImage(id);\n    }\n\n    /**\n     * Load an image from an external URL to be used with {@link Map.addImage}. External\n     * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).\n     *\n     * @param url - The URL of the image file. Image file must be in png, webp, or jpg format.\n     * @returns a promise that is resolved when the image is loaded, or rejected when the response has no image data (for example an HTTP 204)\n     *\n     * @example\n     * Load an image from an external URL.\n     * ```ts\n     * const response = await map.loadImage('https://picsum.photos/50/50');\n     * // Add the loaded image to the style's sprite with the ID 'photo'.\n     * map.addImage('photo', response.data);\n     * ```\n     * @see [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-an-icon-to-the-map/)\n     */\n    async loadImage(url: string): Promise<GetResourceResponse<HTMLImageElement | ImageBitmap>> {\n        const response = await ImageRequest.getImage(await this._requestManager.transformRequest(url, ResourceType.Image), new AbortController());\n        if (!response.data) {\n            throw new Error(`Could not load image ${url}: the response is empty`);\n        }\n        return response;\n    }\n\n    /**\n     * Returns an Array of strings containing the IDs of all images currently available in the map.\n     * This includes both images from the style's original sprite\n     * and any images that have been added at runtime using {@link Map.addImage}.\n     *\n     * @returns An Array of strings containing the names of all sprites/images currently available in the map.\n     *\n     * @example\n     * ```ts\n     * let allImages = map.listImages();\n     * ```\n     */\n    listImages(): string[] {\n        return this.style?.listImages() ?? [];\n    }\n\n    /**\n     * Adds a [MapLibre style layer](https://maplibre.org/maplibre-style-spec/layers)\n     * to the map's style.\n     *\n     * A layer defines how data from a specified source will be styled. Read more about layer types\n     * and available paint and layout properties in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers).\n     *\n     * @param layer - The layer to add,\n     * conforming to either the MapLibre Style Specification's [layer definition](https://maplibre.org/maplibre-style-spec/layers) or,\n     * less commonly, the {@link CustomLayerInterface} specification. Can also be a layer definition with an embedded source definition.\n     * The MapLibre Style Specification's layer definition is appropriate for most layers.\n     *\n     * @param beforeId - The ID of an existing layer to insert the new layer before,\n     * resulting in the new layer appearing visually beneath the existing layer.\n     * If this argument is not specified, the layer will be appended to the end of the layers array\n     * and appear visually above all other layers.\n     *\n     * @example\n     * Add a circle layer with a vector source\n     * ```ts\n     * map.addLayer({\n     *   id: 'points-of-interest',\n     *   source: {\n     *     type: 'vector',\n     *     url: 'https://demotiles.maplibre.org/tiles/tiles.json'\n     *   },\n     *   'source-layer': 'poi_label',\n     *   type: 'circle',\n     *   paint: {\n     *     // MapLibre Style Specification paint properties\n     *   },\n     *   layout: {\n     *     // MapLibre Style Specification layout properties\n     *   }\n     * });\n     * ```\n     *\n     * @example\n     * Define a source before using it to create a new layer\n     * ```ts\n     * map.addSource('state-data', {\n     *   type: 'geojson',\n     *   data: 'path/to/data.geojson'\n     * });\n     *\n     * map.addLayer({\n     *   id: 'states',\n     *   // References the GeoJSON source defined above\n     *   // and does not require a `source-layer`\n     *   source: 'state-data',\n     *   type: 'symbol',\n     *   layout: {\n     *     // Set the label content to the\n     *     // feature's `name` property\n     *     text-field: ['get', 'name']\n     *   }\n     * });\n     * ```\n     *\n     * @example\n     * Add a new symbol layer before an existing layer\n     * ```ts\n     * map.addLayer({\n     *   id: 'states',\n     *   // References a source that's already been defined\n     *   source: 'state-data',\n     *   type: 'symbol',\n     *   layout: {\n     *     // Set the label content to the\n     *     // feature's `name` property\n     *     text-field: ['get', 'name']\n     *   }\n     * // Add the layer before the existing `cities` layer\n     * }, 'cities');\n     * ```\n     * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/create-and-style-clusters/)\n     * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-vector-tile-source/)\n     * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-wms-source/)\n     */\n    addLayer(layer: AddLayerObject, beforeId?: string): this {\n        this._lazyInitEmptyStyle();\n        this.style.addLayer(layer, beforeId);\n        return this._update(true);\n    }\n\n    /**\n     * Moves a layer to a different z-position.\n     *\n     * @param id - The ID of the layer to move.\n     * @param 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.\n     *\n     * @example\n     * 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.\n     * ```ts\n     * map.moveLayer('polygon', 'country-label');\n     * ```\n     */\n    moveLayer(id: string, beforeId?: string): this {\n        this.style.moveLayer(id, beforeId);\n        return this._update(true);\n    }\n\n    /**\n     * Removes the layer with the given ID from the map's style.\n     *\n     * An {@link ErrorEvent} will be fired if no such layer exists.\n     *\n     * @param id - The ID of the layer to remove\n     *\n     * @example\n     * If a layer with ID 'state-data' exists, remove it.\n     * ```ts\n     * if (map.getLayer('state-data')) map.removeLayer('state-data');\n     * ```\n     */\n    removeLayer(id: string): this {\n        this.style.removeLayer(id);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the layer with the specified ID in the map's style.\n     *\n     * @param id - The ID of the layer to get.\n     * @returns The layer with the specified ID, or `undefined`\n     * if the ID corresponds to no existing layers.\n     *\n     * @example\n     * ```ts\n     * let stateDataLayer = map.getLayer('state-data');\n     * ```\n     * @see [Filter symbols by toggling a list](https://maplibre.org/maplibre-gl-js/docs/examples/filter-symbols-by-toggling-a-list/)\n     * @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-symbols-by-text-input/)\n     */\n    getLayer(id: string): StyleLayer | undefined {\n        return this.style?.getLayer(id);\n    }\n\n    /**\n     * Return the ids of all layers currently in the style, including custom layers, in order.\n     *\n     * @returns ids of layers, in order\n     *\n     * @example\n     * ```ts\n     * const orderedLayerIds = map.getLayersOrder();\n     * ```\n     */\n    getLayersOrder(): string[] {\n        return this.style?.getLayersOrder() ?? [];\n    }\n\n    /**\n     * Sets the zoom extent for the specified style layer. The zoom extent includes the\n     * [minimum zoom level](https://maplibre.org/maplibre-style-spec/layers/#minzoom)\n     * and [maximum zoom level](https://maplibre.org/maplibre-style-spec/layers/#maxzoom))\n     * at which the layer will be rendered.\n     *\n     * !!! note\n     *     For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the\n     *     minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum\n     *     zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style\n     *     layer will not be rendered at all zoom levels in the zoom range.\n     *\n     * @param layerId - The ID of the layer to which the zoom extent will be applied.\n     * @param minzoom - The minimum zoom to set (0-24).\n     * @param maxzoom - The maximum zoom to set (0-24).\n     *\n     * @example\n     * ```ts\n     * map.setLayerZoomRange('my-layer', 2, 5);\n     * ```\n     */\n    setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this {\n        this.style.setLayerZoomRange(layerId, minzoom, maxzoom);\n        return this._update(true);\n    }\n\n    /**\n     * Sets the filter for the specified style layer.\n     *\n     * Filters control which features a style layer renders from its source.\n     * Any feature for which the filter expression evaluates to `true` will be\n     * rendered on the map. Those that are false will be hidden.\n     *\n     * Use `setFilter` to show a subset of your source data.\n     *\n     * To clear the filter, pass `null` or `undefined` as the second parameter.\n     *\n     * @param layerId - The ID of the layer to which the filter will be applied.\n     * @param filter - The filter, conforming to the MapLibre Style Specification's\n     * [filter definition](https://maplibre.org/maplibre-style-spec/layers/#filter).  If `null` or `undefined` is provided, the function removes any existing filter from the layer.\n     * @param options - Options object.\n     *\n     * @example\n     * Display only features with the 'name' property 'USA'\n     * ```ts\n     * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);\n     * ```\n     * @example\n     * Display only features with five or more 'available-spots'\n     * ```ts\n     * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);\n     * ```\n     * @example\n     * Remove the filter for the 'bike-docks' style layer\n     * ```ts\n     * map.setFilter('bike-docks', null);\n     * ```\n     * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-time-slider/)\n     */\n    setFilter(layerId: string, filter?: FilterSpecification | null, options: StyleSetterOptions = {}): this {\n        this.style?.setFilter(layerId, filter, options);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the filter applied to the specified style layer.\n     *\n     * @param layerId - The ID of the style layer whose filter to get.\n     * @returns The layer's filter.\n     */\n    getFilter(layerId: string): FilterSpecification | void {\n        return this.style.getFilter(layerId);\n    }\n\n    /**\n     * Sets the value of a paint property in the specified style layer.\n     *\n     * @param layerId - The ID of the layer to set the paint property in.\n     * @param name - The name of the paint property to set.\n     * @param value - The value of the paint property to set.\n     * Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/).\n     * Pass `null` to unset the existing value.\n     * @param options - Options object.\n     * @example\n     * ```ts\n     * map.setPaintProperty('my-layer', 'fill-color', '#faafee');\n     * ```\n     * @see [Change a layer's color with buttons](https://maplibre.org/maplibre-gl-js/docs/examples/change-a-layers-color-with-buttons/)\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    setPaintProperty<K extends keyof AllPaintProperties>(layerId: string, name: K, value: AllPaintProperties[K], options: StyleSetterOptions = {}): this {\n        this.style?.setPaintProperty(layerId, name, value, options);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the value of a paint property in the specified style layer.\n     *\n     * @param layerId - The ID of the layer to get the paint property from.\n     * @param name - The name of a paint property to get.\n     * @returns The value of the specified paint property.\n     */\n    getPaintProperty<K extends keyof AllPaintProperties>(layerId: string, name: K): AllPaintProperties[K] {\n        return this.style.getPaintProperty(layerId, name);\n    }\n\n    /**\n     * Sets the value of a layout property in the specified style layer.\n     *\n     * @param layerId - The ID of the layer to set the layout property in.\n     * @param name - The name of the layout property to set.\n     * @param value - The value of the layout property. Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/).\n     * @param options - The options object.\n     * @example\n     * ```ts\n     * map.setLayoutProperty('my-layer', 'visibility', 'none');\n     * ```\n     */\n    setLayoutProperty<K extends keyof AllLayoutProperties>(layerId: string, name: K, value: AllLayoutProperties[K], options: StyleSetterOptions = {}): this {\n        this.style.setLayoutProperty(layerId, name, value, options);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the value of a layout property in the specified style layer.\n     *\n     * @param layerId - The ID of the layer to get the layout property from.\n     * @param name - The name of the layout property to get.\n     * @returns The value of the specified layout property.\n     */\n    getLayoutProperty<K extends keyof AllLayoutProperties>(layerId: string, name: K): AllLayoutProperties[K] | undefined {\n        return this.style.getLayoutProperty(layerId, name);\n    }\n\n    /**\n    * Sets the value of the style's glyphs property. Pass a falsy value (null or undefined)\n    * to unset glyphs.\n     *\n     * @param glyphsUrl - Glyph URL to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/glyphs/).\n     * @param options - Options object.\n     * @example\n     * ```ts\n     * map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf');\n     * ```\n     */\n    setGlyphs(glyphsUrl: string | null | undefined, options: StyleSetterOptions = {}): this {\n        this._lazyInitEmptyStyle();\n        this.style.setGlyphs(glyphsUrl, options);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the value of the style's glyphs URL\n     *\n     * @returns glyphs Style's glyphs url, or `null` if glyphs are unset.\n     */\n    getGlyphs(): string | null {\n        return this.style.getGlyphsUrl();\n    }\n\n    /**\n     * Sets the value of the style's `font-faces` property, which points at the font files used to\n     * draw text that the style's `glyphs` URL does not cover. Pass a falsy value (null or undefined)\n     * to unset it.\n     *\n     * The files are handed to the browser's CSS Font Loading API, so any format the browser can\n     * render text with may be used, and requests for them go through `transformRequest` as glyph\n     * requests do. Text is drawn a grapheme cluster at a time, so a letter and the marks written on\n     * it are handed to the browser's text engine together and come back as the one shape they are\n     * written as -- which is what a `glyphs` URL, serving one codepoint at a time, cannot do.\n     *\n     * @param fontFaces - The font faces to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/root/#font-faces).\n     * A declaration this cannot make sense of is skipped with a warning, as is a font file that\n     * fails to load, so the text it would have drawn falls back to the `glyphs` URL.\n     * @example\n     * ```ts\n     * map.setFontFaces({\n     *     'Noto Sans Regular': [\n     *         {url: 'https://example.com/NotoSansKhmer-Regular.ttf', 'unicode-range': ['U+1780-17FF']}\n     *     ]\n     * });\n     * ```\n     */\n    setFontFaces(fontFaces: FontFacesSpecification | null | undefined): this {\n        this._lazyInitEmptyStyle();\n        this.style.setFontFaces(fontFaces);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the value of the style's `font-faces` property.\n     *\n     * @returns The style's font faces, or `null` if it declares none.\n     */\n    getFontFaces(): FontFacesSpecification | null {\n        return this.style.getFontFaces();\n    }\n\n    /**\n     * Adds a sprite to the map's style. Fires the `style` event.\n     *\n     * @param id - The ID of the sprite to add. Must not conflict with existing sprites.\n     * @param url - The URL to load the sprite from\n     * @param options - Options object.\n     * @example\n     * ```ts\n     * map.addSprite('sprite-two', 'http://example.com/sprite-two');\n     * ```\n     */\n    addSprite(id: string, url: string, options: StyleSetterOptions = {}): this {\n        this._lazyInitEmptyStyle();\n        this.style.addSprite(id, url, options, (err) => {\n            if (!err) {\n                this._update(true);\n            }\n        });\n        return this;\n    }\n\n    /**\n     * Removes the sprite from the map's style. Fires the `style` event.\n     *\n     * @param id - The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be \"default\".\n     * @example\n     * ```ts\n     * map.removeSprite('sprite-two');\n     * map.removeSprite('default');\n     * ```\n     */\n    removeSprite(id: string): this {\n        this._lazyInitEmptyStyle();\n        this.style.removeSprite(id);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the as-is value of the style's sprite.\n     *\n     * @returns style's sprite list of id-url pairs\n     */\n    getSprite(): Array<{id: string; url: string}> {\n        return this.style.getSprite();\n    }\n\n    /**\n     * Sets the value of the style's sprite property.\n     *\n     * @param spriteUrl - Sprite URL to set.\n     * @param options - Options object.\n     * @example\n     * ```ts\n     * map.setSprite('YOUR_SPRITE_URL');\n     * ```\n     */\n    setSprite(spriteUrl: string | null, options: StyleSetterOptions = {}): this {\n        this._lazyInitEmptyStyle();\n        this.style.setSprite(spriteUrl, options, (err) => {\n            if (!err) {\n                this._update(true);\n            }\n        });\n        return this;\n    }\n\n    /**\n     * Sets the any combination of light values.\n     *\n     * @param light - Light properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/light).\n     * @param options - Options object.\n     *\n     * @example\n     * ```ts\n     * let layerVisibility = map.getLayoutProperty('my-layer', 'visibility');\n     * ```\n     */\n    setLight(light: LightSpecification, options: StyleSetterOptions = {}): this {\n        this._lazyInitEmptyStyle();\n        this.style.setLight(light, options);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the value of the light object.\n     *\n     * @returns light Light properties of the style.\n     */\n    getLight(): LightSpecification {\n        return this.style.getLight();\n    }\n\n    /**\n     * Sets the value of style's sky properties.\n     *\n     * @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/).\n     * @param options - Options object.\n     *\n     * @example\n     * ```ts\n     * map.setSky({'atmosphere-blend': 1.0});\n     * ```\n     */\n    setSky(sky: SkySpecification, options: StyleSetterOptions = {}): this {\n        this._lazyInitEmptyStyle();\n        this.style.setSky(sky, options);\n        return this._update(true);\n    }\n\n    /**\n     * Returns the value of the style's sky.\n     *\n     * @returns the sky properties of the style.\n     * @example\n     * ```ts\n     * map.getSky();\n     * ```\n     */\n    getSky(): SkySpecification {\n        return this.style.getSky();\n    }\n\n    /**\n     * Sets the `state` of a feature.\n     * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.\n     * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state.\n     * Features are identified by their `feature.id` attribute, which can be any number or string.\n     *\n     * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways:\n     *\n     * - For vector or GeoJSON sources, including an `id` attribute in the original data file.\n     * - For vector or GeoJSON sources, using the [`promoteId`](https://maplibre.org/maplibre-style-spec/sources/#promoteid) option at the time the source is defined.\n     * - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-style-spec/sources/#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.\n     *\n     * !!! note\n     *     You can use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling.\n     *\n     * @param feature - Feature identifier. Feature objects returned from\n     * {@link Map.queryRenderedFeatures} or event handlers can be used as feature identifiers.\n     * @param state - A set of key-value pairs. The values should be valid JSON types.\n     *\n     * @example\n     * ```ts\n     * // When the mouse moves over the `my-layer` layer, update\n     * // the feature state for the feature under the mouse\n     * map.on('mousemove', 'my-layer', (e) => {\n     *   if (e.features.length > 0) {\n     *     map.setFeatureState({\n     *       source: 'my-source',\n     *       sourceLayer: 'my-source-layer',\n     *       id: e.features[0].id,\n     *     }, {\n     *       hover: true\n     *     });\n     *   }\n     * });\n     * ```\n     * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)\n     */\n    setFeatureState(feature: FeatureIdentifier, state: any): this {\n        this.style.setFeatureState(feature, state);\n        return this._update();\n    }\n\n    /**\n     * Removes the `state` of a feature, setting it back to the default behavior.\n     * If only a `target.source` is specified, it will remove the state for all features from that source.\n     * If `target.id` is also specified, it will remove all keys for that feature's state.\n     * If `key` is also specified, it removes only that key from that feature's state.\n     * Features are identified by their `feature.id` attribute, which can be any number or string.\n     *\n     * @param target - Identifier of where to remove state. It can be a source, a feature, or a specific key of feature.\n     * Feature objects returned from {@link Map.queryRenderedFeatures} or event handlers can be used as feature identifiers.\n     * @param key - (optional) The key in the feature state to reset.\n     * @example\n     * Reset the entire state object for all features in the `my-source` source\n     * ```ts\n     * map.removeFeatureState({\n     *   source: 'my-source'\n     * });\n     * ```\n     *\n     * @example\n     * When the mouse leaves the `my-layer` layer,\n     * reset the entire state object for the\n     * feature under the mouse\n     * ```ts\n     * map.on('mouseleave', 'my-layer', (e) => {\n     *   map.removeFeatureState({\n     *     source: 'my-source',\n     *     sourceLayer: 'my-source-layer',\n     *     id: e.features[0].id\n     *   });\n     * });\n     * ```\n     *\n     * @example\n     * When the mouse leaves the `my-layer` layer,\n     * reset only the `hover` key-value pair in the\n     * state for the feature under the mouse\n     * ```ts\n     * map.on('mouseleave', 'my-layer', (e) => {\n     *   map.removeFeatureState({\n     *     source: 'my-source',\n     *     sourceLayer: 'my-source-layer',\n     *     id: e.features[0].id\n     *   }, 'hover');\n     * });\n     * ```\n     */\n    removeFeatureState(target: FeatureIdentifier, key?: string): this {\n        this.style.removeFeatureState(target, key);\n        return this._update();\n    }\n\n    /**\n     * Gets the `state` of a feature.\n     * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.\n     * Features are identified by their `feature.id` attribute, which can be any number or string.\n     *\n     * !!! note\n     *     To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state).\n     *\n     * @param feature - Feature identifier. Feature objects returned from\n     * {@link Map.queryRenderedFeatures} or event handlers can be used as feature identifiers.\n     * @returns The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.\n     *\n     * @example\n     * When the mouse moves over the `my-layer` layer,\n     * get the feature state for the feature under the mouse\n     * ```ts\n     * map.on('mousemove', 'my-layer', (e) => {\n     *   if (e.features.length > 0) {\n     *     map.getFeatureState({\n     *       source: 'my-source',\n     *       sourceLayer: 'my-source-layer',\n     *       id: e.features[0].id\n     *     });\n     *   }\n     * });\n     * ```\n     */\n    getFeatureState(feature: FeatureIdentifier): any {\n        return this.style.getFeatureState(feature);\n    }\n\n    /**\n     * Returns the map's containing HTML element.\n     *\n     * @returns The map's container.\n     */\n    getContainer(): HTMLElement {\n        return this._container;\n    }\n\n    /**\n     * Returns the HTML element containing the map's `<canvas>` element.\n     *\n     * If you want to add non-GL overlays to the map, you should append them to this element.\n     *\n     * This is the element to which event bindings for map interactivity (such as panning and zooming) are\n     * attached. It will receive bubbled events from child elements such as the `<canvas>`, but not from\n     * map controls.\n     *\n     * @returns The container of the map's `<canvas>`.\n     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)\n     */\n    getCanvasContainer(): HTMLElement {\n        return this._canvasContainer;\n    }\n\n    /**\n     * Returns the map's `<canvas>` element.\n     *\n     * @returns The map's `<canvas>` element.\n     * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure-distances/)\n     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n     * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-the-map-on-a-clicked-symbol/)\n     */\n    getCanvas(): HTMLCanvasElement {\n        return this._canvas;\n    }\n\n    /**\n     * @internal\n     * The viewport in whole CSS pixels, shared by the canvas, the painter and the transform.\n     */\n    _containerDimensions(): number[] {\n        let width = 0;\n        let height = 0;\n\n        if (this._container) {\n            width = Math.floor(this._container.clientWidth) || 400;\n            height = Math.floor(this._container.clientHeight) || 300;\n        }\n\n        return [width, height];\n    }\n\n    /**\n     * Determines if the initial resize event should be handled based on the container's dimensions.\n     *\n     * @returns `true` if the initial resize event should be handled, `false` otherwise.\n     */\n    _shouldHandleInitialResize(): boolean {\n        if (!this._container?.clientWidth || !this._container.clientHeight) {\n            return false;\n        }\n        const [width, height] = this._containerDimensions();\n        return width !== this._camera.transform.width || height !== this._camera.transform.height;\n    }\n\n    /**\n     * @internal\n     * Sets up the ResizeObserver to track container size changes.\n     * Uses the owning window's ResizeObserver for cross-window support.\n     */\n    private _setupResizeObserver() {\n        let initialResizeEventCaptured = false;\n        const throttledResizeCallback = throttle((entries: ResizeObserverEntry[]) => {\n            if (this._trackResize && !this._removed) {\n                this.resize(entries);\n                this.redraw();\n            }\n        }, 50);\n        // Use owning window's ResizeObserver for cross-window support\n        const ResizeObserverClass = this._ownerWindow.ResizeObserver ?? ResizeObserver;\n        this._resizeObserver = new ResizeObserverClass((entries: ResizeObserverEntry[]) => {\n            if (!initialResizeEventCaptured) {\n                initialResizeEventCaptured = true;\n                if (!this._shouldHandleInitialResize()) {\n                    return;\n                }\n            }\n            throttledResizeCallback(entries);\n        });\n        this._resizeObserver.observe(this._container);\n    }\n\n    /**\n     * @internal\n     * Resolves the container option to an HTMLElement.\n     * Supports string ID, HTMLElement, or cross-window elements (using nodeType check).\n     */\n    private _resolveContainer(container: string | HTMLElement): HTMLElement {\n        if (typeof container === 'string') {\n            const element = document.getElementById(container);\n            if (!element) {\n                throw new Error(`Container '${container}' not found.`);\n            }\n            return element;\n        }\n        if (container instanceof HTMLElement) {\n            return container;\n        }\n        // Cross-window support: use nodeType check as instanceof fails across windows\n        if (container && typeof container === 'object' && (container as Node).nodeType === 1) {\n            return container as HTMLElement;\n        }\n        throw new Error('Invalid type: \\'container\\' must be a String or HTMLElement.');\n    }\n\n    _setupContainer(): void {\n        const dimensions = this._containerDimensions();\n        const clampedPixelRatio = this._getClampedPixelRatio(dimensions[0], dimensions[1]);\n\n        const container = this._container;\n        container.classList.add('maplibregl-map');\n\n        const canvasContainer = this._canvasContainer = DOM.create('div', 'maplibregl-canvas-container', container);\n        if (this._interactive) {\n            canvasContainer.classList.add('maplibregl-interactive');\n        }\n\n        this._canvas = DOM.create('canvas', 'maplibregl-canvas', canvasContainer);\n        this._canvas.addEventListener('webglcontextlost', this._contextLost, false);\n        this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false);\n        this._canvas.setAttribute('tabindex', this._interactive ? '0' : '-1');\n        this._canvas.setAttribute('aria-label', this._getUIString('Map.Title'));\n        this._canvas.setAttribute('role', 'region');\n\n        this._resizeCanvas(dimensions[0], dimensions[1], clampedPixelRatio);\n\n        const controlContainer = this._controlContainer = DOM.create('div', 'maplibregl-control-container', container);\n        const positions = this._controlPositions = {};\n        for (const positionName of ['top-left', 'top-right', 'bottom-left', 'bottom-right'] as const) {\n            positions[positionName] = DOM.create('div', `maplibregl-ctrl-${positionName} `, controlContainer);\n        }\n\n        this._container.addEventListener('scroll', this._onMapScroll, false);\n    }\n\n    /**\n     * @internal\n     * Reverses the DOM mutations of {@link Map._setupContainer}, returning the container element to its pre-construction state.\n     */\n    _cleanupContainer(): void {\n        this._canvas.removeEventListener('webglcontextrestored', this._contextRestored, false);\n        this._canvas.removeEventListener('webglcontextlost', this._contextLost, false);\n        this._canvasContainer.remove();\n        this._controlContainer.remove();\n        this._container.removeEventListener('scroll', this._onMapScroll, false);\n        this._container.classList.remove('maplibregl-map');\n    }\n\n    /**\n     * @internal\n     * Sizes the backing store to whole device pixels and the CSS box to cover exactly that many, so\n     * the compositor never rescales the canvas. A pixel ratio can sit a fraction below a whole\n     * number, where truncating the count would cost a whole pixel per axis.\n     */\n    _resizeCanvas(width: number, height: number, pixelRatio: number): void {\n        const canvasWidth = Math.round(pixelRatio * width);\n        const canvasHeight = Math.round(pixelRatio * height);\n\n        this._canvas.width = canvasWidth;\n        this._canvas.height = canvasHeight;\n\n        this._canvas.style.width = `${canvasWidth / pixelRatio}px`;\n        this._canvas.style.height = `${canvasHeight / pixelRatio}px`;\n    }\n\n    /**\n     * @internal\n     * Creates the WebGL2 context and the painter. Throws {@link GPUInitializationError} when the context cannot be created.\n     */\n    _setupPainter(): void {\n\n        // Maplibre WebGL context requires alpha, depth and stencil buffers. It also forces premultipliedAlpha: true.\n        // We use the values provided in the map constructor for the rest of context attributes\n        const attributes = {\n            ...this._canvasContextAttributes,\n            alpha: true,\n            depth: true,\n            stencil: true,\n            premultipliedAlpha: true\n        };\n\n        let creationEvent: WebGLContextEvent | null = null;\n        this._canvas.addEventListener('webglcontextcreationerror', (event: WebGLContextEvent) => {\n            creationEvent = event;\n        }, {once: true});\n\n        const gl: WebGL2RenderingContext | null = this._canvas.getContext('webgl2', attributes);\n\n        if (!gl) {\n            throw new GPUInitializationError(attributes, creationEvent);\n        }\n\n        this.painter = new Painter(gl);\n    }\n\n    /**\n     * @internal\n     * Creates a new specialized transform instance from a projection instance and migrates\n     * to this new transform, carrying over all the properties of the old transform (center, pitch, etc.).\n     * When the style's projection is changed (or first set), this function should be called.\n     */\n    migrateProjection(newTransform: ITransform, newCameraHelper: ICameraHelper): void {\n        this._camera.migrateProjection(newTransform, newCameraHelper);\n        this.fire(new MapProjectionEvent({\n            newProjection: this.style.projection.name,\n        }));\n    }\n\n    _contextLost = (event: WebGLContextEvent): void => {\n        event.preventDefault();\n        if (this._frameRequest) {\n            this._frameRequest.abort();\n            this._frameRequest = null;\n        }\n        this.painter.destroy();\n\n        this._lostContextSnapshot = this._takeStyleSnapshot();\n\n        if (!this.style) {\n            this.fire(new MapContextEvent('webglcontextlost', {originalEvent: event}));\n            return;\n        }\n\n        this._warnAboutUnrestorableLayers();\n\n        this.style.off('error', this._onStyleError);\n        this.style.destroy();\n        this.style = null;\n\n        this.fire(new MapContextEvent('webglcontextlost', {originalEvent: event}));\n    };\n\n    _contextRestored = (event: WebGLContextEvent): void => {\n        this._restoreStyleSnapshot(this._lostContextSnapshot);\n        this._lostContextSnapshot = {style: null, images: {}};\n\n        try {\n            this._setupPainter();\n        } catch (error) {\n            this.fire(new ErrorEvent(error));\n            return;\n        }\n        this.resize();\n        this._update();\n        this._resizeInternal();\n        this.fire(new MapContextEvent('webglcontextrestored', {originalEvent: event}));\n    };\n\n    /**\n     * Rebuilds the style after `WorkerPool.restart` replaces the workers, which then hold none of this map's state.\n     * Assumes apps treat a worker restart like a WebGL context loss: it fires synthetic `webglcontextlost` and\n     * `webglcontextrestored` events, so the custom layers and feature state the rebuild drops get re-added by the\n     * same listeners. A style still loading is rebuilt once it loads.\n     */\n    private _handleWorkersRestarted = (): void => {\n        if (!this.style) return;\n        if (!this.style._loaded) {\n            this.style.off('style.load', this._handleWorkersRestarted);\n            this.style.once('style.load', this._handleWorkersRestarted);\n            return;\n        }\n\n        const snapshot = this._takeStyleSnapshot();\n        this._warnAboutUnrestorableLayers();\n        this.fire(new MapContextEvent('webglcontextlost', {originalEvent: new globalThis.Event('webglcontextlost') as WebGLContextEvent}));\n\n        this._restoreStyleSnapshot(snapshot);\n        this._update();\n        this.fire(new MapContextEvent('webglcontextrestored', {originalEvent: new globalThis.Event('webglcontextrestored') as WebGLContextEvent}));\n    };\n\n    /** Warns about the custom layers and layer event listeners a style rebuild cannot restore. */\n    private _warnAboutUnrestorableLayers(): void {\n        for (const layer of Object.values(this.style._layers)) {\n            if (layer.type === 'custom') {\n                console.warn(`Custom layer with id '${layer.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`);\n            }\n\n            if (layer._listeners) {\n                for (const [event] of Object.entries(layer._listeners)) {\n                    console.warn(`Custom layer with id '${layer.id}' had event listeners for event '${event}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);\n                }\n            }\n        }\n    }\n\n    /**\n     * Rebuilds the style from a snapshot taken by {@link Map._takeStyleSnapshot}. A rebuilt style\n     * starts with empty atlases, so images that render themselves with WebGL owe every atlas a\n     * fresh render.\n     */\n    private _restoreStyleSnapshot({style, images}: StyleSnapshot): void {\n        if (!style) return;\n        this.setStyle(style, {diff: false});\n\n        if (!this.style) return;\n        this.style.imageManager.images = images;\n        for (const [id, image] of Object.entries(images)) {\n            if (image.isWebGLImage) this.style.imageManager.updateImage(id, image, false);\n        }\n    }\n\n    _onMapScroll = (event: UIEvent): boolean => {\n        if (event.target !== this._container) return;\n\n        // Revert any scroll which would move the canvas outside of the view\n        this._container.scrollTop = 0;\n        this._container.scrollLeft = 0;\n        return false;\n    };\n\n    /**\n     * Returns a Boolean indicating whether the map is fully loaded.\n     *\n     * Returns `false` if the style is not yet fully loaded,\n     * or if there has been a change to the sources or style that\n     * has not yet fully loaded.\n     *\n     * @returns A Boolean indicating whether the map is fully loaded.\n     */\n    loaded(): boolean {\n        return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();\n    }\n\n    /**\n     * @internal\n     * Update this map's style and sources, and re-render the map.\n     *\n     * @param updateStyle - mark the map's style for reprocessing as\n     * well as its sources\n     */\n    _update(updateStyle?: boolean): this {\n        if (!this.style?._loaded) return this;\n\n        this._styleDirty ||= updateStyle;\n        this._sourcesDirty = true;\n        this.triggerRepaint();\n\n        return this;\n    }\n\n    /**\n     * @internal\n     * Request that the given callback be executed during the next render\n     * frame.  Schedule a render frame if one is not already scheduled.\n     *\n     * @returns An id that can be used to cancel the callback\n     */\n    _requestRenderFrame(callback: () => void): TaskID {\n        this._update();\n        return this._renderTaskQueue.add(callback);\n    }\n\n    _cancelRenderFrame(id: TaskID): void {\n        this._renderTaskQueue.remove(id);\n    }\n\n    /**\n     * @internal\n     * Call when a (re-)render of the map is required:\n     *\n     * - The style has changed (`setPaintProperty()`, etc.)\n     * - Source data has changed (e.g. tiles have finished loading)\n     * - The map has is moving (or just finished moving)\n     * - A transition is in progress\n     *\n     * @param paintStartTimeStamp - The time when the animation frame began executing.\n     */\n    _render(paintStartTimeStamp: number): this {\n        const fadeDuration = this._idleTriggered ? this._fadeDuration : 0;\n\n        const isGlobeRendering = this.style.projection?.transitionState > 0;\n\n        // A custom layer may have used the context asynchronously. Mark the state as dirty.\n        this.painter.context.setDirty();\n        this.painter.setBaseState();\n\n        this._renderTaskQueue.run(paintStartTimeStamp);\n        // A task queue callback may have fired a user event which may have removed the map\n        if (this._removed) return;\n\n        let crossFading = false;\n\n        // If the style has changed, the map is being zoomed, or a transition or fade is in progress:\n        //  - Apply style changes (in a batch)\n        //  - Recalculate paint properties.\n        if (this.style && this._styleDirty) {\n            this._styleDirty = false;\n\n            const zoom = this._camera.transform.zoom;\n            const currentTime = now();\n            this.style.zoomHistory.update(zoom, currentTime);\n\n            const parameters = new EvaluationParameters(zoom, {\n                now: currentTime,\n                fadeDuration,\n                zoomHistory: this.style.zoomHistory,\n                transition: this.style.getTransition()\n            });\n\n            const factor = parameters.crossFadingFactor();\n            if (factor !== 1 || factor !== this._crossFadingFactor) {\n                crossFading = true;\n                this._crossFadingFactor = factor;\n            }\n\n            this.style.update(parameters);\n        }\n\n        const globeRenderingChanged = this.style.projection?.transitionState > 0 !== isGlobeRendering;\n        this._camera.prepareNextFrame(this.style.projection?.transitionState);\n\n        // If we are in _render for any reason other than an in-progress paint\n        // transition, update tile managers to check for and load any tiles we\n        // need for the current transform\n        if (this.style && (this._sourcesDirty || globeRenderingChanged)) {\n            this._sourcesDirty = false;\n            this.style._updateSources(this._camera.transform);\n        }\n\n        // update terrain stuff\n        if (this.terrain) {\n            const renderableTilesChanged = this.terrain.tileManager.update(this._camera.transform, this.terrain);\n            // The cached samplers and coverage index are only valid for the tile set they were built from.\n            if (renderableTilesChanged) {\n                this.terrain.resetElevationCache();\n            }\n        }\n        this._camera.clampCenterToGround(this.terrain);\n\n        this._placementDirty = this.style?._updatePlacement(this._camera.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions, globeRenderingChanged);\n\n        const projection = this.style.projection;\n        const projectionTransition = projection?.transitionState ?? 0;\n\n        // Actually draw\n        this.painter.render(this.style, this._camera.transform, {\n            showTileBoundaries: this.showTileBoundaries,\n            showOverdrawInspector: this._showOverdrawInspector,\n            rotating: this.isRotating(),\n            zooming: this.isZooming(),\n            moving: this.isMoving(),\n            fadeDuration,\n            symbolFadeChange: this.style.placement.symbolFadeChange(now()),\n            variableOffsets: this.style.placement.variableOffsets,\n            showPadding: this.showPadding,\n            anisotropicFilterPitch: this.getAnisotropicFilterPitch(),\n            projectionTransition,\n            isRenderingGlobe: projectionTransition > 0,\n            projectionShaderVariant: projection ? {name: projection.shaderVariantName, define: projection.shaderDefine, prelude: projection.shaderPreludeCode} : undefined,\n            useSubdivision: projection?.useSubdivision ?? false,\n            pixelRatio: this._clampedPixelRatio,\n            light: this.style.light?.getEvaluated(),\n            sky: this.style.sky?.getEvaluated(),\n        });\n\n        this.fire(new MapLibreEvent('render'));\n\n        if (this.loaded() && !this._loaded) {\n            this._loaded = true;\n            this.fire(new MapLibreEvent('load'));\n        }\n\n        if (this.style && (this.style.hasTransitions() || crossFading)) {\n            this._styleDirty = true;\n        }\n\n        if (this.style && !this._placementDirty) {\n            // Since no fade operations are in progress, we can release\n            // all tiles held for fading. If we didn't do this, the tiles\n            // would just sit in the TileManagers until the next render\n            this.style._releaseSymbolFadeTiles();\n        }\n\n        // Schedule another render frame if it's needed.\n        //\n        // Even though `_styleDirty` and `_sourcesDirty` are reset in this\n        // method, synchronous events fired during Style.update or\n        // Style._updateSources could have caused them to be set again.\n        const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty || this.painter.renderToTexture?.needsFollowUpFrame;\n        if (somethingDirty || this._repaint) {\n            this.triggerRepaint();\n        } else if (!this.isMoving() && this.loaded()) {\n            this.fire(new MapLibreEvent('idle'));\n        }\n\n        if (this._loaded && !this._fullyLoaded && !somethingDirty) {\n            this._fullyLoaded = true;\n        }\n\n        return this;\n    }\n\n    /**\n     * Force a synchronous redraw of the map.\n     * @example\n     * ```ts\n     * map.redraw();\n     * ```\n     */\n    redraw(): this {\n        if (this.style) {\n            // cancel the scheduled update\n            if (this._frameRequest) {\n                this._frameRequest.abort();\n                this._frameRequest = null;\n            }\n            this._render(0);\n        }\n        return this;\n    }\n\n    /**\n     * Clean up and release all internal resources associated with this map.\n     *\n     * This includes DOM elements, event bindings, web workers, and WebGL resources.\n     *\n     * Use this method when you are done using the map and wish to ensure that it no\n     * longer consumes browser resources. Afterwards, you must not call any other\n     * methods on the map.\n     */\n    remove(): void {\n        if (this._hash) this._hash.remove();\n\n        for (const control of this._controls) control.onRemove(this);\n        this._controls = [];\n\n        if (this._frameRequest) {\n            this._frameRequest.abort();\n            this._frameRequest = null;\n        }\n        this._renderTaskQueue.clear();\n        this._diffStyleRequest?.abort();\n        this.painter.destroy();\n        this._handlers.destroy();\n        getGlobalWorkerPool().off('restart', this._handleWorkersRestarted);\n        this.setStyle(null);\n        if (typeof window !== 'undefined') {\n            this._ownerWindow.removeEventListener('online', this._onWindowOnline, false);\n        }\n\n        ImageRequest.removeThrottleControl(this._imageQueueHandle);\n\n        this._resizeObserver?.disconnect();\n        const extension = this.painter.context.gl.getExtension('WEBGL_lose_context');\n        if (extension?.loseContext) extension.loseContext();\n        this._cleanupContainer();\n\n        this._removed = true;\n        this.fire(new MapLibreEvent('remove'));\n    }\n\n    /**\n     * Trigger the rendering of a single frame. Use this method with custom layers to\n     * repaint the map when the layer changes. Calling this multiple times before the\n     * next frame is rendered will still result in only a single frame being rendered.\n     * @example\n     * ```ts\n     * map.triggerRepaint();\n     * ```\n     * @see [Add 3D Tiles, 3D objects and models using Three.js](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-tiles-3d-objects-and-models-using-threejs/)\n     * @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-an-animated-icon-to-the-map/)\n     */\n    triggerRepaint(): void {\n        if (this.style && !this._frameRequest) {\n            this._frameRequest = new AbortController();\n            browser.frame(\n                this._frameRequest,\n                (paintStartTimeStamp) => {\n                    this._frameRequest = null;\n                    try {\n                        this._render(paintStartTimeStamp);\n                    } catch(error) {\n                        if (!isAbortError(error)) {\n                            throw error;\n                        }\n                    }\n                },\n                () => {},\n                this._ownerWindow\n            );\n        }\n    }\n\n    /**\n     * @internal\n     * A tile that fails to load fires an error event and no data event, so when it was the last tile loading,\n     * no frame would run to fire `load` and `idle`.\n     */\n    _onStyleError = (event: ErrorEvent & {tile?: unknown}): void => {\n        if (event.tile) this.triggerRepaint();\n    };\n\n    _onWindowOnline = (): void => {\n        this._update();\n    };\n\n    /**\n     * Gets and sets a Boolean indicating whether the map will render an outline\n     * around each tile and the tile ID. These tile boundaries are useful for\n     * debugging.\n     *\n     * The uncompressed file size of the first vector source is drawn in the top left\n     * corner of each tile, next to the tile ID.\n     *\n     * @example\n     * ```ts\n     * map.showTileBoundaries = true;\n     * ```\n     */\n    get showTileBoundaries(): boolean { return !!this._showTileBoundaries; }\n    set showTileBoundaries(value: boolean) {\n        if (this._showTileBoundaries === value) return;\n        this._showTileBoundaries = value;\n        this._update();\n    }\n\n    /**\n     * Gets and sets a Boolean indicating whether the map will visualize\n     * the padding offsets.\n     */\n    get showPadding(): boolean { return !!this._showPadding; }\n    set showPadding(value: boolean) {\n        if (this._showPadding === value) return;\n        this._showPadding = value;\n        this._update();\n    }\n\n    /**\n     * Gets and sets a Boolean indicating whether the map will render boxes\n     * around all symbols in the data source, revealing which symbols\n     * were rendered or which were hidden due to collisions.\n     * This information is useful for debugging.\n     */\n    get showCollisionBoxes(): boolean { return !!this._showCollisionBoxes; }\n    set showCollisionBoxes(value: boolean) {\n        if (this._showCollisionBoxes === value) return;\n        this._showCollisionBoxes = value;\n        if (value) {\n            // When we turn collision boxes on we have to generate them for existing tiles\n            // When we turn them off, there's no cost to leaving existing boxes in place\n            this.style._generateCollisionBoxes();\n        } else {\n            // Otherwise, call an update to remove collision boxes\n            this._update();\n        }\n    }\n\n    /**\n     * Gets and sets a Boolean indicating whether the map should color-code\n     * each fragment to show how many times it has been shaded.\n     * White fragments have been shaded 8 or more times.\n     * Black fragments have been shaded 0 times.\n     * This information is useful for debugging.\n     */\n    get showOverdrawInspector(): boolean { return !!this._showOverdrawInspector; }\n    set showOverdrawInspector(value: boolean) {\n        if (this._showOverdrawInspector === value) return;\n        this._showOverdrawInspector = value;\n        this._update();\n    }\n\n    /**\n     * Gets and sets a Boolean indicating whether the map will\n     * continuously repaint. This information is useful for analyzing performance.\n     */\n    get repaint(): boolean { return !!this._repaint; }\n    set repaint(value: boolean) {\n        if (this._repaint !== value) {\n            this._repaint = value;\n            this.triggerRepaint();\n        }\n    }\n    // show vertices\n    get vertices(): boolean { return !!this._vertices; }\n    set vertices(value: boolean) { this._vertices = value; this._update(); }\n\n    /**\n     * Returns the package version of the library\n     * @returns Package version of the library\n     */\n    get version(): string {\n        return version;\n    }\n\n    /**\n     * Returns the elevation for the point where the camera is looking.\n     * This value corresponds to:\n     * \"meters above sea level\" * \"exaggeration\"\n     * @returns The elevation.\n     */\n    getCameraTargetElevation(): number {\n        return this._camera.transform.elevation;\n    }\n\n    /**\n     * Gets the {@link ProjectionSpecification}.\n     * @returns the projection specification.\n     * @example\n     * ```ts\n     * let projection = map.getProjection();\n     * ```\n     */\n    getProjection(): ProjectionSpecification { return this.style.getProjection(); }\n\n    /**\n     * Sets the {@link ProjectionSpecification}.\n     * @param projection - the projection specification to set\n     * @returns\n     */\n    setProjection(projection: ProjectionSpecification): this {\n        this._lazyInitEmptyStyle();\n        this.style.setProjection(projection);\n        return this._update(true);\n    }\n}\n", "import Point from '@mapbox/point-geometry';\nimport {DOM} from '../../util/dom.ts';\nimport {degreesToRadians, extend, getAngleDelta} from '../../util/util.ts';\nimport {DragHandler, type DragMoveHandler, type DragRotateResult} from '../handler/drag_handler.ts';\nimport {MouseOrTouchMoveStateManager} from '../handler/drag_move_state_manager.ts';\n\nimport type {Map} from '../map.ts';\nimport type {IControl} from './control.ts';\n\n/**\n * The {@link NavigationControl} options object\n */\nexport type NavigationControlOptions = {\n    /**\n     * If `true` the compass button is included.\n     */\n    showCompass?: boolean;\n    /**\n     * If `true` the zoom-in and zoom-out buttons are included.\n     */\n    showZoom?: boolean;\n    /**\n     * If `true` the pitch is visualized by rotating X-axis of compass.\n     */\n    visualizePitch?: boolean;\n    /**\n     * If `true` the roll is visualized by rotating the compass.\n     */\n    visualizeRoll?: boolean;\n};\n\nconst defaultOptions: NavigationControlOptions = {\n    showCompass: true,\n    showZoom: true,\n    visualizePitch: false,\n    visualizeRoll: true\n};\n\n/**\n * A `NavigationControl` control contains zoom buttons and a compass.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let nav = new NavigationControl();\n * map.addControl(nav, 'top-left');\n * ```\n * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/display-map-navigation-controls/)\n */\nexport class NavigationControl implements IControl {\n    _map: Map;\n    options: NavigationControlOptions;\n    _container: HTMLElement;\n    _zoomInButton: HTMLButtonElement;\n    _zoomOutButton: HTMLButtonElement;\n    _compass: HTMLButtonElement;\n    _compassIcon: HTMLElement;\n    _handler: MouseRotateWrapper;\n\n    /**\n     * @param options - the control's options\n     */\n    constructor(options?: NavigationControlOptions) {\n        this.options = extend({}, defaultOptions, options);\n\n        this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n        this._container.addEventListener('contextmenu', (e) => e.preventDefault());\n\n        if (this.options.showZoom) {\n            this._zoomInButton = this._createButton('maplibregl-ctrl-zoom-in', (e) => this._map.zoomIn({}, {originalEvent: e}));\n            DOM.create('span', 'maplibregl-ctrl-icon', this._zoomInButton).setAttribute('aria-hidden', 'true');\n            this._zoomOutButton = this._createButton('maplibregl-ctrl-zoom-out', (e) => this._map.zoomOut({}, {originalEvent: e}));\n            DOM.create('span', 'maplibregl-ctrl-icon', this._zoomOutButton).setAttribute('aria-hidden', 'true');\n        }\n        if (this.options.showCompass) {\n            this._compass = this._createButton('maplibregl-ctrl-compass', (e) => {\n                if (this.options.visualizePitch) {\n                    this._map.resetNorthPitch({}, {originalEvent: e});\n                } else {\n                    this._map.resetNorth({}, {originalEvent: e});\n                }\n            });\n            this._compassIcon = DOM.create('span', 'maplibregl-ctrl-icon', this._compass);\n            this._compassIcon.setAttribute('aria-hidden', 'true');\n        }\n    }\n\n    _updateZoomButtons = (): void => {\n        const zoom = this._map.getZoom();\n        const isMax = zoom === this._map.getMaxZoom();\n        const isMin = zoom === this._map.getMinZoom(true);\n        this._zoomInButton.disabled = isMax;\n        this._zoomOutButton.disabled = isMin;\n        this._zoomInButton.setAttribute('aria-disabled', isMax.toString());\n        this._zoomOutButton.setAttribute('aria-disabled', isMin.toString());\n    };\n\n    _rotateCompassArrow = (): void => {\n        const pitch = this._map.getPitch();\n        const roll = this._map.getRoll();\n        const bearing = this._map.getBearing();\n        const pitchScale = 1 / Math.pow(Math.cos(degreesToRadians(pitch)), 0.5);\n        if (this.options.visualizePitch && this.options.visualizeRoll) {\n            this._compassIcon.style.transform = `scale(${pitchScale}) rotateZ(${-roll}deg) rotateX(${pitch}deg) rotateZ(${-bearing}deg)`;\n            return;\n        }\n        if (this.options.visualizePitch) {\n            this._compassIcon.style.transform = `scale(${pitchScale}) rotateX(${pitch}deg) rotateZ(${-bearing}deg)`;\n            return;\n        }\n        if (this.options.visualizeRoll) {\n            this._compassIcon.style.transform = `rotate(${-bearing - roll}deg)`;\n            return;\n        }\n        this._compassIcon.style.transform = `rotate(${-bearing}deg)`;\n    };\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        if (this.options.showZoom) {\n            this._setButtonTitle(this._zoomInButton, 'ZoomIn');\n            this._setButtonTitle(this._zoomOutButton, 'ZoomOut');\n            this._map.on('move', this._updateZoomButtons);\n            this._updateZoomButtons();\n        }\n        if (this.options.showCompass) {\n            this._setButtonTitle(this._compass, 'ResetBearing');\n            if (this.options.visualizePitch) {\n                this._map.on('pitch', this._rotateCompassArrow);\n            }\n            if (this.options.visualizeRoll) {\n                this._map.on('roll', this._rotateCompassArrow);\n            }\n            this._map.on('rotate', this._rotateCompassArrow);\n            this._rotateCompassArrow();\n            this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch);\n        }\n        return this._container;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        this._container.remove();\n        if (this.options.showZoom) {\n            this._map.off('move', this._updateZoomButtons);\n        }\n        if (this.options.showCompass) {\n            if (this.options.visualizePitch) {\n                this._map.off('pitch', this._rotateCompassArrow);\n            }\n            if (this.options.visualizeRoll) {\n                this._map.off('roll', this._rotateCompassArrow);\n            }\n            this._map.off('rotate', this._rotateCompassArrow);\n            this._handler.off();\n            delete this._handler;\n        }\n\n        delete this._map;\n    }\n\n    _createButton(className: string, fn: (e?: MouseEvent) => unknown): HTMLButtonElement {\n        const a = DOM.create('button', className, this._container);\n        a.type = 'button';\n        a.addEventListener('click', fn);\n        return a;\n    }\n\n    _setButtonTitle = (button: HTMLButtonElement, title: 'ZoomIn' | 'ZoomOut' | 'ResetBearing'): void => {\n        const str = this._map._getUIString(`NavigationControl.${title}`);\n        button.title = str;\n        button.setAttribute('aria-label', str);\n    };\n}\n\nclass MouseRotateWrapper {\n\n    map: Map;\n    _clickTolerance: number;\n    element: HTMLElement;\n    _rotatePitchHandler: DragMoveHandler<DragRotateResult, MouseEvent | TouchEvent>;\n    _startPos: Point;\n    _lastPos: Point;\n\n    constructor(map: Map, element: HTMLElement, pitch: boolean = false) {\n        this._clickTolerance = 10;\n        this.element = element;\n\n        const moveStateManager = new MouseOrTouchMoveStateManager();\n        this._rotatePitchHandler = new DragHandler<DragRotateResult, MouseEvent | TouchEvent>({\n            clickTolerance: 3,\n            move: (lastPoint: Point, currentPoint: Point) => {\n                const rect = element.getBoundingClientRect();\n                const center = new Point((rect.bottom - rect.top) / 2, (rect.right - rect.left) / 2);\n                const bearingDelta = getAngleDelta(new Point(lastPoint.x, currentPoint.y), currentPoint, center);\n                const pitchDelta = pitch ? (currentPoint.y - lastPoint.y) * -0.5 : undefined;\n                return {bearingDelta, pitchDelta};\n            },\n            moveStateManager,\n            enable: true,\n            assignEvents: () => {},\n        });\n        this.map = map;\n\n        element.addEventListener('mousedown', this.mousedown);\n        element.addEventListener('touchstart', this.touchstart, {passive: false});\n        element.addEventListener('touchcancel', this.reset);\n    }\n\n    startMove(e: MouseEvent | TouchEvent, point: Point): void {\n        this._rotatePitchHandler.dragStart(e, point);\n        DOM.disableDrag();\n    }\n\n    move(e: MouseEvent | TouchEvent, point: Point): void {\n        const map = this.map;\n        const {bearingDelta, pitchDelta} = this._rotatePitchHandler.dragMove(e, point) || {};\n        if (bearingDelta) map.setBearing(map.getBearing() + bearingDelta);\n        if (pitchDelta) map.setPitch(map.getPitch() + pitchDelta);\n    }\n\n    off(): void {\n        const element = this.element;\n        element.removeEventListener('mousedown', this.mousedown);\n        element.removeEventListener('touchstart', this.touchstart);\n        window.removeEventListener('touchmove', this.touchmove);\n        window.removeEventListener('touchend', this.touchend);\n        element.removeEventListener('touchcancel', this.reset);\n        this.offTemp();\n    }\n\n    offTemp(): void {\n        DOM.enableDrag();\n        window.removeEventListener('mousemove', this.mousemove);\n        window.removeEventListener('mouseup', this.mouseup);\n        window.removeEventListener('touchmove', this.touchmove);\n        window.removeEventListener('touchend', this.touchend);\n    }\n\n    mousedown = (e: MouseEvent): void => {\n        this.startMove(e, DOM.mousePos(this.element, e));\n        window.addEventListener('mousemove', this.mousemove);\n        window.addEventListener('mouseup', this.mouseup);\n    };\n\n    mousemove = (e: MouseEvent): void => {\n        this.move(e, DOM.mousePos(this.element, e));\n    };\n\n    mouseup = (e: MouseEvent): void => {\n        this._rotatePitchHandler.dragEnd(e);\n        this.offTemp();\n    };\n\n    touchstart = (e: TouchEvent): void => {\n        if (e.targetTouches.length !== 1) {\n            this.reset();\n        } else {\n            this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];\n            this.startMove(e, this._startPos);\n            window.addEventListener('touchmove', this.touchmove, {passive: false});\n            window.addEventListener('touchend', this.touchend);\n        }\n    };\n\n    touchmove = (e: TouchEvent): void => {\n        if (e.targetTouches.length !== 1) {\n            this.reset();\n        } else {\n            this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];\n            this.move(e, this._lastPos);\n        }\n    };\n\n    touchend = (e: TouchEvent): void => {\n        if (e.targetTouches.length === 0 &&\n            this._startPos &&\n            this._lastPos &&\n            this._startPos.dist(this._lastPos) < this._clickTolerance) {\n            this.element.click();\n        }\n        delete this._startPos;\n        delete this._lastPos;\n        this.offTemp();\n    };\n\n    reset = (): void => {\n        this._rotatePitchHandler.reset();\n        delete this._startPos;\n        delete this._lastPos;\n        this.offTemp();\n    };\n}\n", "let supportsGeolocation;\n\nexport async function checkGeolocationSupport(forceRecalculation = false): Promise<boolean> {\n    if (supportsGeolocation !== undefined && !forceRecalculation) {\n        return supportsGeolocation;\n    }\n    if (window.navigator.permissions === undefined) {\n        supportsGeolocation = !!window.navigator.geolocation;\n        return supportsGeolocation;\n    }\n    // navigator.permissions has incomplete browser support\n    // https://caniuse.com/#feat=permissions-api\n    // Test for the case where a browser disables Geolocation because of an\n    // insecure origin\n    try {\n        const permissions = await window.navigator.permissions.query({name: 'geolocation'});\n        supportsGeolocation = permissions.state !== 'denied';\n    } catch {\n        // Fix for iOS16 which rejects query but still supports geolocation\n        supportsGeolocation = !!window.navigator.geolocation;\n    }\n    return supportsGeolocation;\n}\n", "import {LngLat} from '../geo/lng_lat.ts';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {IReadonlyTransform} from '../geo/transform_interface.ts';\n\n/**\n * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted\n * n × 360° east or west for some n ≥ 0 such that:\n *\n * * the projected location of the result is on screen, if possible, and secondarily:\n * * the difference between the projected location of the result and the prior position\n *   is minimized.\n *\n * The object is to preserve perceived object constancy for Popups and Markers as much as\n * possible; they should avoid shifting large distances across the screen, even when the\n * map center changes by ±360° due to automatic wrapping, and when about to go off screen,\n * should wrap just enough to avoid doing so.\n */\nexport function smartWrap(lngLat: LngLat, priorPos: Point, transform: IReadonlyTransform, useNormalWrap: boolean = false): LngLat {\n    if (useNormalWrap || !transform.getCoveringTilesDetailsProvider().allowWorldCopies()) {\n        return lngLat?.wrap();\n    }\n    const originalLngLat = new LngLat(lngLat.lng, lngLat.lat);\n    lngLat = new LngLat(lngLat.lng, lngLat.lat);\n\n    // First, try shifting one world in either direction, and see if either is closer to the\n    // prior position. This preserves object constancy when the map center is auto-wrapped\n    // during animations.\n    if (priorPos) {\n        const left  = new LngLat(lngLat.lng - 360, lngLat.lat);\n        const right = new LngLat(lngLat.lng + 360, lngLat.lat);\n        const delta = transform.locationToScreenPoint(lngLat).distSqr(priorPos);\n        if (transform.locationToScreenPoint(left).distSqr(priorPos) < delta) {\n            lngLat = left;\n        } else if (transform.locationToScreenPoint(right).distSqr(priorPos) < delta) {\n            lngLat = right;\n        }\n    }\n\n    // Second, wrap toward the center until the new position is on screen, or we can't get\n    // any closer.\n    while (Math.abs(lngLat.lng - transform.center.lng) > 180) {\n        const pos = transform.locationToScreenPoint(lngLat);\n        if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) {\n            break;\n        }\n        if (lngLat.lng > transform.center.lng) {\n            lngLat.lng -= 360;\n        } else {\n            lngLat.lng += 360;\n        }\n    }\n\n    // Apply the change only if new coord is below horizon\n    if (lngLat.lng !== originalLngLat.lng && transform.isPointOnMapSurface(transform.locationToScreenPoint(lngLat))) {\n        return lngLat;\n    }\n\n    return originalLngLat;\n}\n", "/**\n * Where to position the anchor.\n * Used by a popup and a marker.\n */\nexport type PositionAnchor = 'center' | 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\nexport const anchorTranslate: {\n    [_ in PositionAnchor]: string;\n} = {\n    'center': 'translate(-50%,-50%)',\n    'top': 'translate(-50%,0)',\n    'top-left': 'translate(0,0)',\n    'top-right': 'translate(-100%,0)',\n    'bottom': 'translate(-50%,-100%)',\n    'bottom-left': 'translate(0,-100%)',\n    'bottom-right': 'translate(-100%,-100%)',\n    'left': 'translate(0,-50%)',\n    'right': 'translate(-100%,-50%)'\n};\n\nexport function applyAnchorClass(element: HTMLElement, anchor: PositionAnchor, prefix: string): void {\n    const classList = element.classList;\n    for (const key in anchorTranslate) {\n        classList.remove(`maplibregl-${prefix}-anchor-${key}`);\n    }\n    classList.add(`maplibregl-${prefix}-anchor-${anchor}`);\n}\n", "import {DOM} from '../util/dom.ts';\nimport {throttle} from '../util/throttle.ts';\nimport {LngLat} from '../geo/lng_lat.ts';\nimport {smartWrap} from '../util/smart_wrap.ts';\nimport {anchorTranslate, applyAnchorClass} from './anchor.ts';\nimport {Event, Evented} from '../util/evented.ts';\nimport Point from '@mapbox/point-geometry';\n\nimport type {PositionAnchor} from './anchor.ts';\nimport type {Map} from './map.ts';\nimport type {Popup, Offset} from './popup.ts';\nimport type {LngLatLike} from '../geo/lng_lat.ts';\nimport type {MapMouseEvent, MapTouchEvent} from './events.ts';\nimport type {PointLike} from './camera.ts';\nimport type {Terrain} from '../render/terrain.ts';\n\n/**\n * Alignment options of rotation and pitch\n */\nexport type Alignment = 'map' | 'viewport' | 'auto';\n\n/**\n * Screen-pixel deltas applied when a focused draggable marker is moved with the arrow keys.\n */\nconst ARROW_KEY_DELTAS: Partial<Record<KeyboardEvent['key'], [number, number]>> = {\n    ArrowLeft: [-1, 0],\n    ArrowRight: [1, 0],\n    ArrowUp: [0, -1],\n    ArrowDown: [0, 1]\n};\n\nconst KEYBOARD_DRAG_SMALL_STEP = 1;\nconst KEYBOARD_DRAG_LARGE_STEP = 10;\n\n/** Fill color of the default marker when {@link MarkerOptions.color} is not given. */\nconst DEFAULT_MARKER_COLOR = '#3FB1CE';\n/** Height in CSS pixels of the default marker SVG at scale 1. */\nconst DEFAULT_MARKER_HEIGHT = 41;\n/** Width in CSS pixels of the default marker SVG at scale 1. */\nconst DEFAULT_MARKER_WIDTH = 27;\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n\n/** Creates an SVG element with the given attributes, set in the order given, and children. */\nfunction svgElement(tag: string, attributes: Record<string, string>, children: Element[] = []): Element {\n    const element = DOM.createNS(SVG_NS, tag);\n    for (const name in attributes) element.setAttributeNS(null, name, attributes[name]);\n    for (const child of children) element.appendChild(child);\n    return element;\n}\n\n/** The default marker SVG at scale 1 in the default color, built on first use and cloned per marker. */\nlet defaultMarkerTemplate: Element;\n\n/**\n * Returns the shared default marker SVG, building it the first time it is asked for. Assembling\n * the pin takes about fifty DOM calls, so each default {@link Marker} deep-clones this template\n * and overrides only its size and its fill, see {@link defaultMarkerFillGroup}.\n */\nfunction getDefaultMarkerTemplate(): Element {\n    if (defaultMarkerTemplate) return defaultMarkerTemplate;\n\n    const shadowRadii = [\n        ['10.5', '5.25002273'],\n        ['10.5', '5.25002273'],\n        ['9.5', '4.77275007'],\n        ['8.5', '4.29549936'],\n        ['7.5', '3.81822308'],\n        ['6.5', '3.34094679'],\n        ['5.5', '2.86367051'],\n        ['4.5', '2.38636864']\n    ];\n    const shadow = svgElement('g', {transform: 'translate(3.0, 29.0)', fill: '#000000'},\n        shadowRadii.map(([rx, ry]) => svgElement('ellipse', {opacity: '0.04', cx: '10.5', cy: '5.80029008', rx, ry})));\n    const background = svgElement('g', {fill: DEFAULT_MARKER_COLOR}, [\n        svgElement('path', {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'})\n    ]);\n    const border = svgElement('g', {opacity: '0.25', fill: '#000000'}, [\n        svgElement('path', {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'})\n    ]);\n    const maki = svgElement('g', {transform: 'translate(6.0, 7.0)', fill: '#FFFFFF'});\n    const circles = svgElement('g', {transform: 'translate(8.0, 8.0)'}, [\n        svgElement('circle', {fill: '#000000', opacity: '0.25', cx: '5.5', cy: '5.5', r: '5.4999962'}),\n        svgElement('circle', {fill: '#FFFFFF', cx: '5.5', cy: '5.5', r: '5.4999962'})\n    ]);\n\n    defaultMarkerTemplate = svgElement('svg', {\n        display: 'block',\n        height: `${DEFAULT_MARKER_HEIGHT}px`,\n        width: `${DEFAULT_MARKER_WIDTH}px`,\n        viewBox: `0 0 ${DEFAULT_MARKER_WIDTH} ${DEFAULT_MARKER_HEIGHT}`\n    }, [svgElement('g', {'fill-rule': 'nonzero'}, [shadow, background, border, maki, circles])]);\n    return defaultMarkerTemplate;\n}\n\n/** The group of a default marker SVG that carries the pin's fill color: the second child of its single top-level group. */\nfunction defaultMarkerFillGroup(svg: Element): Element {\n    return svg.firstElementChild.children[1];\n}\n\n/**\n * The {@link Marker} options object\n */\nexport type MarkerOptions = {\n    /**\n     * DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.\n     */\n    element?: HTMLElement;\n    /**\n     * Space-separated CSS class names to add to marker element.\n     */\n    className?: string;\n    /**\n     * The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n     */\n    offset?: PointLike;\n    /**\n     * A string indicating the part of the Marker that should be positioned closest to the coordinate set via {@link Marker.setLngLat}.\n     * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`.\n     * @defaultValue 'center'\n     * */\n    anchor?: PositionAnchor;\n    /**\n     * The color to use for the default marker if options.element is not provided. The default is light blue.\n     * @defaultValue '#3FB1CE'\n     */\n    color?: string;\n    /**\n     * 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`.\n     * @defaultValue 1\n     */\n    scale?: number;\n    /**\n     * A boolean indicating whether or not a marker is able to be dragged to a new position on the map.\n     * A draggable default marker also becomes keyboard focusable and, while focused, moves by\n     * 1 screen pixel per arrow-key press (10 with Shift), firing the same `dragstart`/`drag`/`dragend`\n     * events as pointer dragging. Markers with a custom `element` keep their focusability and\n     * keyboard behavior application-owned.\n     * @defaultValue false\n     */\n    draggable?: boolean;\n    /**\n     * 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.\n     * @defaultValue 0\n     */\n    clickTolerance?: number;\n    /**\n     * The rotation angle of the marker in degrees, relative to its respective `rotationAlignment` setting. A positive value will rotate the marker clockwise.\n     * @defaultValue 0\n     */\n    rotation?: number;\n    /**\n     * `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`.\n     * @defaultValue 'auto'\n     */\n    rotationAlignment?: Alignment;\n    /**\n     * `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`.\n     * @defaultValue 'auto'\n     */\n    pitchAlignment?: Alignment;\n    /**\n     * Marker's opacity when it's in clear view (not behind 3d terrain)\n     * Accepts any valid CSS opacity value as a number or string.\n     * @defaultValue 1\n     */\n    opacity?: string | number;\n    /**\n     * Marker's opacity when it's behind 3d terrain\n     * Accepts any valid CSS opacity value as a number or string.\n     * @defaultValue 0.2\n     */\n    opacityWhenCovered?: string | number;\n    /**\n      * If `true`, rounding is disabled for placement of the marker, allowing for\n      * subpixel positioning and smoother movement when the marker is translated.\n      * @defaultValue false\n      */\n    subpixelPositioning?: boolean;\n};\n\n/**\n * The event class for marker drag events (`dragstart`, `drag` and `dragend`).\n *\n * @group Event Related\n */\nexport class MarkerDragEvent extends Event {\n    type: 'dragstart' | 'drag' | 'dragend';\n    /**\n     * The `Marker` object that fired the event.\n     */\n    target: Marker;\n}\n\n/**\n * The event class for the marker `click` event.\n *\n * @group Event Related\n */\nexport class MarkerClickEvent extends Event {\n    type: 'click';\n    /**\n     * The `Marker` object that fired the event.\n     */\n    target: Marker;\n    /**\n     * The DOM event which caused the marker click event.\n     */\n    originalEvent: MouseEvent;\n}\n\n/**\n * `MarkerEventType` - a mapping between the marker event name and the event value.\n * These events are used with the {@link Marker.on} method.\n *\n * @group Event Related\n */\nexport type MarkerEventType = {\n    /**\n     * Fired when dragging starts.\n     */\n    dragstart: MarkerDragEvent;\n    /**\n     * Fired while dragging.\n     */\n    drag: MarkerDragEvent;\n    /**\n     * Fired when the marker is finished being dragged.\n     */\n    dragend: MarkerDragEvent;\n    /**\n     * Fired when the marker is clicked.\n     */\n    click: MarkerClickEvent;\n};\n\n/**\n * Creates a marker component\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let marker = new Marker()\n *   .setLngLat([30.5, 50.5])\n *   .addTo(map);\n * ```\n *\n * @example\n * Set options\n * ```ts\n * let marker = new Marker({\n *     color: \"#FFFFFF\",\n *     draggable: true\n *   }).setLngLat([30.5, 50.5])\n *   .addTo(map);\n * ```\n * @see [Add a default marker](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-default-marker/)\n * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/add-custom-icons-with-markers/)\n * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)\n * @see [Animate a marker](https://maplibre.org/maplibre-gl-js/docs/examples/animate-a-marker/)\n * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)\n *\n * ## Events\n *\n * **Event** `dragstart` of type {@link MarkerDragEvent} will be fired when dragging starts.\n *\n * **Event** `drag` of type {@link MarkerDragEvent} will be fired while dragging.\n *\n * **Event** `dragend` of type {@link MarkerDragEvent} will be fired when the marker is finished being dragged.\n *\n * **Event** `click` of type {@link MarkerClickEvent} will be fired when the marker is clicked.\n *\n * ## CSS Classes\n *\n * **CSS class** `maplibregl-marker-covered` is toggled on the marker element when the marker\n * is hidden behind 3D terrain or on the back of a globe.\n * Use this class to apply custom styles to covered markers.\n *\n * @example\n * ```css\n * .maplibregl-marker-covered {\n *     pointer-events: none;\n *     cursor: default;\n * }\n * ```\n */\nexport class Marker extends Evented<MarkerEventType> {\n    _map: Map;\n    _anchor: PositionAnchor;\n    _offset: Point;\n    _element: HTMLElement;\n    _popup: Popup;\n    _lngLat: LngLat;\n    _pos: Point;\n    _flatPos: Point;\n    _color: string;\n    _scale: number;\n    _defaultMarker: boolean;\n    _draggable: boolean;\n    _clickTolerance: number;\n    _isDragging: boolean;\n    _state: 'inactive' | 'pending' | 'active'; // used for handling drag events\n    _positionDelta: Point;\n    _pointerdownPos: Point;\n    _rotation: number;\n    _pitchAlignment: Alignment;\n    _rotationAlignment: Alignment;\n    _opacity: string;\n    _opacityWhenCovered: string;\n    _subpixelPositioning: boolean;\n    _roleManaged: boolean;\n    _tabIndexManaged: boolean;\n    _keyboardDragActive: boolean;\n\n    /**\n     * @param options - the options\n     */\n    constructor(options?: MarkerOptions) {\n        super();\n\n        this._anchor = options?.anchor || 'center';\n        this._color = options?.color || DEFAULT_MARKER_COLOR;\n        this._scale = options?.scale || 1;\n        this._draggable = options?.draggable || false;\n        this._clickTolerance = options?.clickTolerance || 0;\n        this._subpixelPositioning = options?.subpixelPositioning || false;\n        this._isDragging = false;\n        this._roleManaged = false;\n        this._tabIndexManaged = false;\n        this._keyboardDragActive = false;\n        this._state = 'inactive';\n        this._rotation = options?.rotation || 0;\n        this._rotationAlignment = options?.rotationAlignment || 'auto';\n        this._pitchAlignment = options?.pitchAlignment && options.pitchAlignment !== 'auto' ?  options.pitchAlignment : this._rotationAlignment;\n        this.setOpacity(options?.opacity, options?.opacityWhenCovered);\n\n        if (!options?.element) {\n            this._defaultMarker = true;\n            this._element = DOM.create('div');\n\n            const svg = getDefaultMarkerTemplate().cloneNode(true) as Element;\n            svg.setAttributeNS(null, 'height', `${DEFAULT_MARKER_HEIGHT * this._scale}px`);\n            svg.setAttributeNS(null, 'width', `${DEFAULT_MARKER_WIDTH * this._scale}px`);\n            defaultMarkerFillGroup(svg).setAttributeNS(null, 'fill', this._color);\n\n            this._element.appendChild(svg);\n\n            // if no element and no offset option given apply an offset for the default marker\n            // the -14 as the y value of the default marker offset was determined as follows\n            //\n            // the marker tip is at the center of the shadow ellipse from the default svg\n            // 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)\"\n            // offset to the svg center \"height (41 / 2)\" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14\n            // negative is used to move the marker up from the center so the tip is at the Marker lngLat\n            this._offset = Point.convert(options?.offset || [0, -14]);\n        } else {\n            this._element = options.element;\n            this._offset = Point.convert(options?.offset || [0, 0]);\n        }\n\n        this._element.classList.add('maplibregl-marker');\n        this._element.addEventListener('dragstart', (e: DragEvent) => {\n            e.preventDefault();\n        });\n        this._element.addEventListener('mousedown', (e: MouseEvent) => {\n            // prevent focusing on click\n            e.preventDefault();\n        });\n        applyAnchorClass(this._element, this._anchor, 'marker');\n\n        if (options?.className) {\n            for (const name of options.className.split(' ')) {\n                this._element.classList.add(name);\n            }\n        }\n\n        this._popup = null;\n    }\n\n    /**\n     * Attaches the `Marker` to a `Map` object.\n     * @param map - The MapLibre GL JS map to add the marker to.\n     * @example\n     * ```ts\n     * let marker = new Marker()\n     *   .setLngLat([30.5, 50.5])\n     *   .addTo(map); // add the marker to the map\n     * ```\n     */\n    addTo(map: Map): this {\n        this.remove();\n        this._map = map;\n\n        if (this._defaultMarker && !this._element.hasAttribute('aria-label')) {\n            this._element.setAttribute('aria-label', map._getUIString('Marker.Title'));\n        }\n\n        this._updateAccessibilityRole();\n\n        map.getCanvasContainer().appendChild(this._element);\n        map.on('move', this._update);\n        map.on('moveend', this._update);\n        map.on('terrain', this._update);\n        map.on('projectiontransition', this._update);\n        map.on('idle', this._update);\n\n        this._element.addEventListener('click', this._onClick);\n        this.setDraggable(this._draggable);\n        this._update();\n\n        // If we attached the `click` listener to the marker element, the popup\n        // would close once the event propagated to `map` due to the\n        // `Popup._onClickClose` listener.\n        this._map.on('click', this._onMapClick);\n\n        return this;\n    }\n\n    /**\n     * Removes the marker from a map\n     * @example\n     * ```ts\n     * let marker = new Marker().addTo(map);\n     * marker.remove();\n     * ```\n     */\n    remove(): this {\n        if (this._map) {\n            this._map.off('click', this._onMapClick);\n            this._map.off('move', this._update);\n            this._map.off('moveend', this._update);\n            this._map.off('terrain', this._update);\n            this._map.off('projectiontransition', this._update);\n            this._map.off('idle', this._update);\n            this._map.off('mousedown', this._addDragHandler);\n            this._map.off('touchstart', this._addDragHandler);\n            this._map.off('mouseup', this._onUp);\n            this._map.off('touchend', this._onUp);\n            this._map.off('mousemove', this._onMove);\n            this._map.off('touchmove', this._onMove);\n            delete this._map;\n        }\n        this._element.removeEventListener('click', this._onClick);\n        this._element.removeEventListener('keydown', this._onKeyDown);\n        this._element.removeEventListener('keyup', this._onKeyUp);\n        this._element.removeEventListener('blur', this._onBlur);\n        this._element.removeEventListener('keypress', this._onKeyPress);\n        // Drop any in-flight keyboard drag silently, like a pointer drag interrupted by remove().\n        this._keyboardDragActive = false;\n        this._element.remove();\n        if (this._popup) this._popup.remove();\n        return this;\n    }\n\n    /**\n     * Get the marker's geographical location.\n     *\n     * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously\n     * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep\n     * the marker on screen.\n     *\n     * @returns A {@link LngLat} describing the marker's location.\n     * @example\n     * ```ts\n     * // Store the marker's longitude and latitude coordinates in a variable\n     * let lngLat = marker.getLngLat();\n     * // Print the marker's longitude and latitude values in the console\n     * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat )\n     * ```\n     * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)\n     */\n    getLngLat(): LngLat {\n        return this._lngLat;\n    }\n\n    /**\n     * Set the marker's geographical position and move it.\n     * @param lnglat - A {@link LngLat} describing where the marker should be located.\n     * @example\n     * Create a new marker, set the longitude and latitude, and add it to the map\n     * ```ts\n     * new Marker()\n     *   .setLngLat([-65.017, -16.457])\n     *   .addTo(map);\n     * ```\n     * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/add-custom-icons-with-markers/)\n     * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)\n     */\n    setLngLat(lnglat: LngLatLike): this {\n        this._lngLat = LngLat.convert(lnglat);\n        this._pos = null;\n        this._update();\n        if (this._popup) this._popup.setLngLat(this._lngLat);\n        return this;\n    }\n\n    /**\n     * Returns the `Marker`'s HTML element.\n     * @returns element\n     */\n    getElement(): HTMLElement {\n        return this._element;\n    }\n\n    /**\n     * Binds a {@link Popup} to the {@link Marker}.\n     * @param popup - An instance of the {@link Popup} class. If undefined or null, any popup\n     * set on this {@link Marker} instance is unset.\n     * @example\n     * ```ts\n     * let marker = new Marker()\n     *  .setLngLat([0, 0])\n     *  .setPopup(new Popup().setHTML(\"<h1>Hello World!</h1>\")) // add popup\n     *  .addTo(map);\n     * ```\n     * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)\n     */\n    setPopup(popup?: Popup | null): this {\n        if (this._popup) {\n            this._popup.remove();\n            this._popup = null;\n            this._element.removeEventListener('keypress', this._onKeyPress);\n        }\n\n        if (popup) {\n            if (!('offset' in popup.options)) {\n                const markerHeight = 41 - (5.8 / 2);\n                const markerRadius = 13.5;\n                const linearOffset = Math.abs(markerRadius) / Math.SQRT2;\n                popup.options.offset = this._defaultMarker ? {\n                    'top': [0, 0],\n                    'top-left': [0, 0],\n                    'top-right': [0, 0],\n                    'bottom': [0, -markerHeight],\n                    'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n                    'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n                    'left': [markerRadius, (markerHeight - markerRadius) * -1],\n                    'right': [-markerRadius, (markerHeight - markerRadius) * -1]\n                } as Offset : this._offset;\n            }\n            this._popup = popup;\n\n            this._element.addEventListener('keypress', this._onKeyPress);\n        }\n\n        this._updateTabIndex();\n        this._updateAccessibilityRole();\n        return this;\n    }\n\n    /**\n      * Set the option to allow subpixel positioning of the marker by passing a boolean\n      *\n      * @param value - when set to `true`, subpixel positioning is enabled for the marker.\n      *\n      * @example\n      * ```ts\n      * let marker = new Marker()\n      * marker.setSubpixelPositioning(true);\n      * ```\n      */\n    setSubpixelPositioning(value: boolean): this {\n        this._subpixelPositioning = value;\n        return this;\n    }\n\n    _onClick = (e: MouseEvent): void => {\n        this.fire(new MarkerClickEvent('click', {originalEvent: e}));\n    };\n\n    _onKeyPress = (e: KeyboardEvent): void => {\n        if (e.code === 'Space' || e.code === 'Enter') {\n            this.togglePopup();\n        }\n    };\n\n    /**\n     * Move a focused draggable default marker with the arrow keys\n     * (1 screen pixel per keydown; 10 with Shift).\n     * Mirrors the pointer drag gesture: the position updates before `dragstart`\n     * fires on the first movement, every movement fires `drag`, and releasing\n     * the arrow key (or losing focus) fires `dragend`. Holding a key down\n     * produces repeated `drag` events within a single gesture.\n     */\n    _onKeyDown = (e: KeyboardEvent): void => {\n        // Custom marker elements own their keyboard behavior (#7790).\n        if (!this._defaultMarker || !this._draggable || !this._map || !this._lngLat) return;\n        // Leave keys originating from elements nested inside the marker to the application.\n        if (e.composedPath()[0] !== this._element) return;\n        // Leave Alt/Ctrl/Meta shortcuts to the browser and the application.\n        if (e.altKey || e.ctrlKey || e.metaKey) return;\n\n        const delta = ARROW_KEY_DELTAS[e.key];\n        if (!delta) return;\n\n        e.preventDefault();\n        // The marker element lives in the canvas container, so without this the\n        // map's KeyboardHandler would also pan (or rotate/pitch with Shift) the camera.\n        e.stopPropagation();\n\n        const step = e.shiftKey ? KEYBOARD_DRAG_LARGE_STEP : KEYBOARD_DRAG_SMALL_STEP;\n        const pos = this._map.project(this._lngLat);\n        this.setLngLat(this._map.unproject(new Point(pos.x + delta[0] * step, pos.y + delta[1] * step)));\n\n        if (!this._keyboardDragActive) {\n            this._keyboardDragActive = true;\n            this.fire(new MarkerDragEvent('dragstart'));\n        }\n        this.fire(new MarkerDragEvent('drag'));\n    };\n\n    _onKeyUp = (e: KeyboardEvent): void => {\n        if (!ARROW_KEY_DELTAS[e.key]) return;\n        this._endKeyboardDrag();\n    };\n\n    _onBlur = (): void => {\n        this._endKeyboardDrag();\n    };\n\n    _endKeyboardDrag(): void {\n        if (this._keyboardDragActive) {\n            this._keyboardDragActive = false;\n            this.fire(new MarkerDragEvent('dragend'));\n        }\n    }\n\n    _onMapClick = (e: MapMouseEvent): void => {\n        const targetElement = e.originalEvent.target;\n        const element = this._element;\n\n        if (this._popup && (targetElement === element || element.contains(targetElement as any))) {\n            this.togglePopup();\n        }\n    };\n\n    /**\n     * Returns the {@link Popup} instance that is bound to the {@link Marker}.\n     * @returns popup\n     * @example\n     * ```ts\n     * let marker = new Marker()\n     *  .setLngLat([0, 0])\n     *  .setPopup(new Popup().setHTML(\"<h1>Hello World!</h1>\"))\n     *  .addTo(map);\n     *\n     * console.log(marker.getPopup()); // return the popup instance\n     * ```\n     */\n    getPopup(): Popup {\n        return this._popup;\n    }\n\n    /**\n     * Opens or closes the {@link Popup} instance that is bound to the {@link Marker}, depending on the current state of the {@link Popup}.\n     * @example\n     * ```ts\n     * let marker = new Marker()\n     *  .setLngLat([0, 0])\n     *  .setPopup(new Popup().setHTML(\"<h1>Hello World!</h1>\"))\n     *  .addTo(map);\n     *\n     * marker.togglePopup(); // toggle popup open or closed\n     * ```\n     */\n    togglePopup(): this {\n        const popup = this._popup;\n\n        if (this._element.style.opacity === this._opacityWhenCovered) return this;\n\n        if (!popup) return this;\n        else if (popup.isOpen()) popup.remove();\n        else {\n            popup.setLngLat(this._lngLat);\n            popup.addTo(this._map);\n        }\n        return this;\n    }\n\n    _updateOpacity(): void {\n        if (!this._isInViewport()) return;\n\n        const terrain = this._map?.terrain;\n        const occluded = this._map._camera.transform.isLocationOccluded(this._lngLat);\n        if (!terrain || occluded) {\n            const targetOpacity = occluded ? this._opacityWhenCovered : this._opacity;\n            if (this._element.style.opacity !== targetOpacity) {\n                this._element.style.opacity = targetOpacity;\n                this._element.classList.toggle('maplibregl-marker-covered', occluded);\n            }\n            return;\n        }\n        this._updateCovered();\n    }\n\n    /**\n     * @internal\n     * Whether the viewport shows the marker's position. There is nothing to compute for one it does not.\n     */\n    _isInViewport(): boolean {\n        const {width, height} = this._map._camera.transform;\n        return !!this._pos && this._pos.x >= 0 && this._pos.y >= 0 && this._pos.x <= width && this._pos.y <= height;\n    }\n\n    /**\n     * @internal\n     * Applies `opacityWhenCovered` and the covered class while the terrain covers the marker, closing its popup;\n     * `_updateCovered` runs it at most once per 100 ms. Nothing to do once the marker, the terrain or the viewport's\n     * view of the marker is gone.\n     */\n    _updateCoveredUnthrottled = (): void => {\n        const terrain = this._map?.terrain;\n        if (!terrain || !this._isInViewport()) return;\n        const covered = this._isCovered(terrain);\n        if (covered && this._popup?.isOpen()) this._popup.remove();\n        this._element.style.opacity = covered ? this._opacityWhenCovered : this._opacity;\n        this._element.classList.toggle('maplibregl-marker-covered', covered);\n    };\n\n    /**\n     * @internal\n     * The terrain check, at most once per 100 ms while the map moves; the last call in a window runs when the window closes.\n     */\n    _updateCovered: () => ReturnType<typeof setTimeout> = throttle(this._updateCoveredUnthrottled, 100);\n\n    /**\n     * @internal\n     * Whether the terrain covers the marker's center: the location raised by the height `offset` lifts the element\n     * above it on screen, or the location itself when the offset lowers the element.\n     */\n    _isCovered(terrain: Terrain): boolean {\n        const transform = this._map._camera.transform;\n        const elevation = terrain.getElevationForLngLat(this._lngLat, transform.tileZoom);\n        const metersToCenter = Math.max(0, -this._offset.y) / transform.pixelsPerMeter;\n        const elevationToCenter = Math.sin(this._map.getPitch() * Math.PI / 180) * metersToCenter;\n        return transform.isLocationOccluded(this._lngLat, terrain, elevation + elevationToCenter);\n    }\n\n    /**\n     * @internal\n     * Positions the marker and updates its opacity. As terrain tiles load, the map can adjust to the ground beneath\n     * its center without firing a `move` event. The `idle` event triggers a final marker update once the map has\n     * finished loading and rendering.\n     */\n    _update = (e?: { type: 'move' | 'moveend' | 'terrain' | 'projectiontransition' | 'idle' }): void => {\n        if (!this._map) return;\n\n        this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map._camera.transform);\n\n        this._flatPos = this._pos = this._map.project(this._lngLat)._add(this._offset);\n        if (this._map.terrain) {\n            // flat position is saved because smartWrap needs non-elevated points\n            this._flatPos = this._map._camera.transform.locationToScreenPoint(this._lngLat)._add(this._offset);\n        }\n\n        let rotation = '';\n        if (this._rotationAlignment === 'viewport' || this._rotationAlignment === 'auto') {\n            rotation = `rotateZ(${this._rotation}deg)`;\n        } else if (this._rotationAlignment === 'map') {\n            rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`;\n        }\n\n        let pitch = '';\n        if (this._pitchAlignment === 'viewport' || this._pitchAlignment === 'auto') {\n            pitch = 'rotateX(0deg)';\n        } else if (this._pitchAlignment === 'map') {\n            pitch = `rotateX(${this._map.getPitch()}deg)`;\n        }\n\n        // rounding the coordinates at every `move` event causes stuttered zooming,\n        // so the position is rounded only once the movement has stopped\n        if (!this._subpixelPositioning && e?.type !== 'move') {\n            this._pos = this._pos.round();\n        }\n\n        this._element.style.transform = `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`;\n\n        this._updateOpacity();\n    };\n\n    /**\n     * Get the marker's offset.\n     * @returns The marker's screen coordinates in pixels.\n     */\n    getOffset(): Point {\n        return this._offset;\n    }\n\n    /**\n     * Sets the offset of the marker\n     * @param offset - The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n     */\n    setOffset(offset: PointLike): this {\n        this._offset = Point.convert(offset);\n        this._update();\n        return this;\n    }\n\n    /**\n     * Adds a CSS class to the marker element.\n     *\n     * @param className - on-empty string with CSS class name to add to marker element\n     *\n     * @example\n     * ```\n     * let marker = new Marker()\n     * marker.addClassName('some-class')\n     * ```\n     */\n    addClassName(className: string): void {\n        this._element.classList.add(className);\n    }\n\n    /**\n     * Removes a CSS class from the marker element.\n     *\n     * @param className - Non-empty string with CSS class name to remove from marker element\n     *\n     * @example\n     * ```ts\n     * let marker = new Marker()\n     * marker.removeClassName('some-class')\n     * ```\n     */\n    removeClassName(className: string): void {\n        this._element.classList.remove(className);\n    }\n\n    /**\n     * Add or remove the given CSS class on the marker element, depending on whether the element currently has that class.\n     *\n     * @param className - Non-empty string with CSS class name to add/remove\n     *\n     * @returns if the class was removed return false, if class was added, then return true\n     *\n     * @example\n     * ```ts\n     * let marker = new Marker()\n     * marker.toggleClassName('toggleClass')\n     * ```\n     */\n    toggleClassName(className: string): boolean {\n        return this._element.classList.toggle(className);\n    }\n\n    _onMove = (e: MapMouseEvent | MapTouchEvent): void => {\n        if (!this._isDragging) {\n            const clickTolerance = this._clickTolerance || this._map._clickTolerance;\n            this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance;\n        }\n        if (!this._isDragging) return;\n\n        this._pos = e.point.sub(this._positionDelta);\n        this._lngLat = this._map.unproject(this._pos);\n        this.setLngLat(this._lngLat);\n        // suppress click event so that popups don't toggle on drag\n        this._element.style.pointerEvents = 'none';\n\n        // make sure dragstart only fires on the first move event after mousedown.\n        // this can't be on mousedown because that event doesn't necessarily\n        // imply that a drag is about to happen.\n        if (this._state === 'pending') {\n            this._state = 'active';\n            this.fire(new MarkerDragEvent('dragstart'));\n        }\n        this.fire(new MarkerDragEvent('drag'));\n    };\n\n    _onUp = (): void => {\n        // revert to normal pointer event handling\n        this._element.style.pointerEvents = 'auto';\n        this._positionDelta = null;\n        this._pointerdownPos = null;\n        this._isDragging = false;\n        this._map.off('mousemove', this._onMove);\n        this._map.off('touchmove', this._onMove);\n\n        // only fire dragend if it was preceded by at least one drag event\n        if (this._state === 'active') {\n            this.fire(new MarkerDragEvent('dragend'));\n        }\n\n        this._state = 'inactive';\n    };\n\n    _addDragHandler = (e: MapMouseEvent | MapTouchEvent): void => {\n        if (this._element.contains(e.originalEvent.target as any)) {\n            e.preventDefault();\n\n            // We need to calculate the pixel distance between the click point\n            // and the marker position, with the offset accounted for. Then we\n            // can subtract this distance from the mousemove event's position\n            // to calculate the new marker position.\n            // If we don't do this, the marker 'jumps' to the click position\n            // creating a jarring UX effect.\n            this._positionDelta = e.point.sub(this._pos).add(this._offset);\n\n            this._pointerdownPos = e.point;\n\n            this._state = 'pending';\n            this._map.on('mousemove', this._onMove);\n            this._map.on('touchmove', this._onMove);\n            this._map.once('mouseup', this._onUp);\n            this._map.once('touchend', this._onUp);\n        }\n    };\n\n    /**\n     * Sets the `draggable` property and functionality of the marker.\n     * A draggable default marker is also keyboard focusable and movable with the\n     * arrow keys (see {@link MarkerOptions.draggable}); custom marker elements keep\n     * their focusability and keyboard behavior application-owned.\n     * @param shouldBeDraggable - Turns drag functionality on/off\n     */\n    setDraggable(shouldBeDraggable?: boolean): this {\n        this._draggable = !!shouldBeDraggable; // convert possible undefined value to false\n        this._element.classList.toggle('maplibregl-marker-draggable', this._draggable);\n\n        // handle case where map may not exist yet\n        // e.g. when setDraggable is called before addTo\n        if (this._map) {\n            if (shouldBeDraggable) {\n                this._map.on('mousedown', this._addDragHandler);\n                this._map.on('touchstart', this._addDragHandler);\n            } else {\n                this._map.off('mousedown', this._addDragHandler);\n                this._map.off('touchstart', this._addDragHandler);\n            }\n        }\n\n        if (this._defaultMarker) {\n            if (this._draggable) {\n                this._element.addEventListener('keydown', this._onKeyDown);\n                this._element.addEventListener('keyup', this._onKeyUp);\n                this._element.addEventListener('blur', this._onBlur);\n            } else {\n                this._element.removeEventListener('keydown', this._onKeyDown);\n                this._element.removeEventListener('keyup', this._onKeyUp);\n                this._element.removeEventListener('blur', this._onBlur);\n                this._endKeyboardDrag();\n            }\n        }\n\n        this._updateTabIndex();\n        this._updateAccessibilityRole();\n        return this;\n    }\n\n    /**\n     * Returns true if the marker can be dragged\n     * @returns True if the marker is draggable.\n     */\n    isDraggable(): boolean {\n        return this._draggable;\n    }\n\n    /**\n     * Keep the marker element focusable while it has built-in keyboard behavior.\n     * A popup makes any marker element interactive; dragging only manages\n     * focusability for the default marker so custom elements stay\n     * application-owned (#7790). A tabindex supplied by the application is\n     * never added, changed, or removed here.\n     */\n    _updateTabIndex(): void {\n        const needsTabIndex = !!this._popup || (this._defaultMarker && this._draggable);\n        if (needsTabIndex) {\n            if (!this._element.hasAttribute('tabindex')) {\n                this._element.setAttribute('tabindex', '0');\n                this._tabIndexManaged = true;\n            }\n        } else if (this._tabIndexManaged) {\n            // Only remove the value we set; the application may have overridden it since.\n            if (this._element.getAttribute('tabindex') === '0') {\n                this._element.removeAttribute('tabindex');\n            }\n            this._tabIndexManaged = false;\n        }\n    }\n\n    /**\n     * Keep the default marker role aligned with interactivity.\n     * Default markers need a role because `aria-label` is set in {@link Marker.addTo}.\n     * Non-interactive markers use `role=img`; interactive ones (draggable or with a popup) use `role=button`.\n     * Click listeners are application-owned and do not automatically change the role.\n     * Custom marker elements are left alone so applications own their a11y tree.\n     * Explicit roles set by the application are preserved.\n     */\n    _updateAccessibilityRole(): void {\n        if (!this._defaultMarker) {\n            return;\n        }\n\n        // Preserve an explicit role chosen by the application unless we previously managed it.\n        if (this._element.hasAttribute('role') && !this._roleManaged) {\n            return;\n        }\n\n        const role = (this._draggable || !!this._popup) ? 'button' : 'img';\n        this._element.setAttribute('role', role);\n        this._roleManaged = true;\n    }\n\n    /**\n     * Sets the `rotation` property of the marker.\n     * @param rotation - The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker.setRotationAlignment} setting.\n     */\n    setRotation(rotation?: number): this {\n        this._rotation = rotation || 0;\n        this._update();\n        return this;\n    }\n\n    /**\n     * Returns the current rotation angle of the marker (in degrees).\n     * @returns The current rotation angle of the marker.\n     */\n    getRotation(): number {\n        return this._rotation;\n    }\n\n    /**\n     * Sets the `rotationAlignment` property of the marker.\n     * @param alignment - Sets the `rotationAlignment` property of the marker. defaults to 'auto'\n     */\n    setRotationAlignment(alignment?: Alignment): this {\n        this._rotationAlignment = alignment || 'auto';\n        this._update();\n        return this;\n    }\n\n    /**\n     * Returns the current `rotationAlignment` property of the marker.\n     * @returns The current rotational alignment of the marker.\n     */\n    getRotationAlignment(): Alignment {\n        return this._rotationAlignment;\n    }\n\n    /**\n     * Sets the `pitchAlignment` property of the marker.\n     * @param alignment - Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`.\n     */\n    setPitchAlignment(alignment?: Alignment): this {\n        this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment;\n        this._update();\n        return this;\n    }\n\n    /**\n     * Returns the current `pitchAlignment` property of the marker.\n     * @returns The current pitch alignment of the marker in degrees.\n     */\n    getPitchAlignment(): Alignment {\n        return this._pitchAlignment;\n    }\n\n    /**\n     * Sets the `opacity` and `opacityWhenCovered` properties of the marker.\n     * When called without arguments, resets opacity and opacityWhenCovered to defaults\n     * @param opacity - Sets the `opacity` property of the marker.\n     * @param opacityWhenCovered - Sets the `opacityWhenCovered` property of the marker.\n     */\n    setOpacity(opacity?: string | number, opacityWhenCovered?: string | number): this {\n        // Reset opacity when called without params or from constructor\n        if (this._opacity === undefined || (opacity === undefined && opacityWhenCovered === undefined)) {\n            this._opacity = '1';\n            this._opacityWhenCovered = '0.2';\n        }\n\n        if (opacity !== undefined) {\n            this._opacity = String(opacity);\n        }\n        if (opacityWhenCovered !== undefined) {\n            this._opacityWhenCovered = String(opacityWhenCovered);\n        }\n\n        if (this._map) {\n            this._updateOpacity();\n        }\n        return this;\n    }\n}\n", "import {Event, Evented} from '../../util/evented.ts';\nimport {DOM} from '../../util/dom.ts';\nimport {extend, warnOnce} from '../../util/util.ts';\nimport {checkGeolocationSupport} from '../../util/geolocation_support.ts';\nimport {LngLat} from '../../geo/lng_lat.ts';\nimport {Marker} from '../marker.ts';\nimport {LngLatBounds} from '../../geo/lng_lat_bounds.ts';\n\nimport type {Map} from '../map.ts';\nimport type {FitBoundsOptions} from '../camera.ts';\nimport type {IControl} from './control.ts';\n\n/**\n * The {@link GeolocateControl} options object\n */\nexport type GeolocateControlOptions = {\n    /**\n     * A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object.\n     * @defaultValue `{enableHighAccuracy: false, timeout: 6000}`\n     */\n    positionOptions?: PositionOptions;\n    /**\n     * A 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.\n     */\n    fitBoundsOptions?: FitBoundsOptions;\n    /**\n     * If `true` the `GeolocateControl` becomes a toggle button and when active the map will receive updates to the user's location as it changes.\n     * @defaultValue false\n     */\n    trackUserLocation?: boolean;\n    /**\n     * 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`.\n     * @defaultValue true\n     */\n    showAccuracyCircle?: boolean;\n    /**\n     * By default a dot will be shown on the map at the user's location. Set to `false` to disable.\n     * @defaultValue true\n     */\n    showUserLocation?: boolean;\n    /**\n     * If `true` then map updates from the user's location may also change the map zoom level based on the location update accuracy. If `false` then the map zoom level will not change.\n     * Has no effect when `trackUserLocation` is `false`.\n     * @defaultValue true\n     */\n    zoomToUserAccuracy?: boolean;\n};\n\nconst defaultOptions: GeolocateControlOptions = {\n    positionOptions: {\n        enableHighAccuracy: false,\n        maximumAge: 0,\n        timeout: 6000 /* 6 sec */\n    },\n    fitBoundsOptions: {\n        maxZoom: 15\n    },\n    trackUserLocation: false,\n    showAccuracyCircle: true,\n    showUserLocation: true,\n    zoomToUserAccuracy: true\n};\n\nlet numberOfWatches = 0;\nlet noTimeout = false;\n\n/**\n * The event class for geolocate control state events\n * (`trackuserlocationstart`, `trackuserlocationend`, `userlocationfocus` and `userlocationlostfocus`).\n *\n * @group Event Related\n */\nexport class GeolocateEvent extends Event {\n    type: 'trackuserlocationstart' | 'trackuserlocationend' | 'userlocationfocus' | 'userlocationlostfocus';\n    /**\n     * The `GeolocateControl` object that fired the event.\n     */\n    target: GeolocateControl;\n}\n\n/**\n * The event class for the geolocate control `geolocate` and `outofmaxbounds` events.\n * Carries the [Position](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition) returned by the Geolocation API.\n *\n * @group Event Related\n */\nexport class GeolocatePositionEvent extends Event {\n    type: 'geolocate' | 'outofmaxbounds';\n    /**\n     * The `GeolocateControl` object that fired the event.\n     */\n    target: GeolocateControl;\n    /**\n     * The geographic position returned by the Geolocation API.\n     */\n    coords: GeolocationCoordinates;\n    /**\n     * The time at which the position was acquired, in milliseconds since the Unix epoch.\n     */\n    timestamp: number;\n}\n\n/**\n * The event class for the geolocate control `error` event.\n * Carries the [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError) returned by the Geolocation API.\n *\n * @group Event Related\n */\nexport class GeolocateErrorEvent extends Event {\n    type: 'error';\n    /**\n     * The `GeolocateControl` object that fired the event.\n     */\n    target: GeolocateControl;\n    /**\n     * The error code returned by the Geolocation API.\n     */\n    code: number;\n    /**\n     * The error message returned by the Geolocation API.\n     */\n    message: string;\n}\n\n/**\n * `GeolocateControlEventType` - a mapping between the geolocate control event name and the event value.\n * These events are used with the {@link GeolocateControl.on} method.\n *\n * @group Event Related\n */\nexport type GeolocateControlEventType = {\n    /**\n     * Fired on each Geolocation API position update which returned as success.\n     */\n    geolocate: GeolocatePositionEvent;\n    /**\n     * Fired on each Geolocation API position update which returned as an error.\n     */\n    error: GeolocateErrorEvent;\n    /**\n     * Fired on each Geolocation API position update which returned as success but the user position is out of map `maxBounds`.\n     */\n    outofmaxbounds: GeolocatePositionEvent;\n    /**\n     * Fired when the geolocate control changes to the active lock state.\n     */\n    trackuserlocationstart: GeolocateEvent;\n    /**\n     * Fired when the geolocate control changes to the background state.\n     */\n    trackuserlocationend: GeolocateEvent;\n    /**\n     * Fired when the geolocate control's button is clicked in the active lock state.\n     */\n    userlocationfocus: GeolocateEvent;\n    /**\n     * Fired when the user changes the viewport while in the active lock state.\n     */\n    userlocationlostfocus: GeolocateEvent;\n};\n\n/**\n * A `GeolocateControl` control provides a button that uses the browser's geolocation\n * API to locate the user on the map.\n *\n * Not all browsers support geolocation,\n * and some users may disable the feature. Geolocation support for modern\n * browsers including Chrome requires sites to be served over HTTPS. If\n * geolocation support is not available, the `GeolocateControl` will show\n * as disabled.\n *\n * The zoom level applied will depend on the accuracy of the geolocation provided by the device.\n *\n * 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:\n * * 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.\n * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement.\n * * disabled - occurs if Geolocation is not available, disabled or denied.\n *\n * These interaction states can't be controlled programmatically, rather they are set based on user interactions.\n *\n * ## State Diagram\n * ![GeolocateControl state diagram](https://github.com/maplibre/maplibre-gl-js/assets/3269297/78e720e5-d781-4da8-9803-a7a0e6aaaa9f)\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * map.addControl(new GeolocateControl({\n *     positionOptions: {\n *         enableHighAccuracy: true\n *     },\n *     trackUserLocation: true\n * }));\n * ```\n * @see [Locate the user](https://maplibre.org/maplibre-gl-js/docs/examples/locate-the-user/)\n *\n * ## Events\n *\n * **Event** `trackuserlocationend` of type {@link Event} will be fired when the `GeolocateControl` 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.\n *\n * **Event** `trackuserlocationstart` of type {@link Event} will be fired when the `GeolocateControl` 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).\n *\n * **Event** `userlocationlostfocus` of type {@link Event} will be fired when the `GeolocateControl` 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.\n *\n * **Event** `userlocationfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens upon 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.\n *\n * **Event** `geolocate` of type {@link Event} will be fired on each Geolocation API position update which returned as success.\n * `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).\n *\n * **Event** `error` of type {@link Event} will be fired on each Geolocation API position update which returned as an error.\n * `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).\n *\n * **Event** `outofmaxbounds` of type {@link Event} will be fired on each Geolocation API position update which returned as success but user position is out of map `maxBounds`.\n * `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).\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n *   positionOptions: {\n *       enableHighAccuracy: true\n *   },\n *   trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a trackuserlocationend event occurs.\n * geolocate.on('trackuserlocationend', () => {\n *   console.log('A trackuserlocationend event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n *   positionOptions: {\n *       enableHighAccuracy: true\n *   },\n *   trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a trackuserlocationstart event occurs.\n * geolocate.on('trackuserlocationstart', () => {\n *   console.log('A trackuserlocationstart event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n *   positionOptions: {\n *       enableHighAccuracy: true\n *   },\n *   trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an userlocationlostfocus event occurs.\n * geolocate.on('userlocationlostfocus', function() {\n *   console.log('An userlocationlostfocus event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n *   positionOptions: {\n *       enableHighAccuracy: true\n *   },\n *   trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an userlocationfocus event occurs.\n * geolocate.on('userlocationfocus', function() {\n *   console.log('An userlocationfocus event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n *   positionOptions: {\n *       enableHighAccuracy: true\n *   },\n *   trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a geolocate event occurs.\n * geolocate.on('geolocate', () => {\n *   console.log('A geolocate event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n *   positionOptions: {\n *       enableHighAccuracy: true\n *   },\n *   trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an error event occurs.\n * geolocate.on('error', () => {\n *   console.log('An error event has occurred.')\n * });\n * ```\n *\n * @example\n * ```ts\n * // Initialize the geolocate control.\n * let geolocate = new GeolocateControl({\n *   positionOptions: {\n *       enableHighAccuracy: true\n *   },\n *   trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an outofmaxbounds event occurs.\n * geolocate.on('outofmaxbounds', () => {\n *   console.log('An outofmaxbounds event has occurred.')\n * });\n * ```\n */\nexport class GeolocateControl extends Evented<GeolocateControlEventType> implements IControl {\n    _map: Map;\n    options: GeolocateControlOptions;\n    _container: HTMLElement;\n    _dotElement: HTMLElement;\n    _circleElement: HTMLElement;\n    _geolocateButton: HTMLButtonElement;\n    _geolocationWatchID: number;\n    _timeoutId: ReturnType<typeof setTimeout>;\n    /* Geolocate Control Watch States\n     * This is the private state of the control.\n     *\n     * OFF\n     *    off/inactive\n     * WAITING_ACTIVE\n     *    Geolocate Control was clicked but still waiting for Geolocation API response with user location\n     * ACTIVE_LOCK\n     *    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.\n     * ACTIVE_ERROR\n     *    There was en error from the Geolocation API while trying to show and track the user location.\n     * BACKGROUND\n     *    Showing the user location as a dot but the camera doesn't follow their location as it changes.\n     * BACKGROUND_ERROR\n     *    There was an error from the Geolocation API while trying to show (but not track) the user location.\n     */\n    _watchState: 'OFF' | 'ACTIVE_LOCK' | 'WAITING_ACTIVE' | 'ACTIVE_ERROR' | 'BACKGROUND' | 'BACKGROUND_ERROR';\n    _lastKnownPosition: any;\n    _userLocationDotMarker: Marker;\n    _accuracyCircleMarker: Marker;\n    _accuracy: number;\n    _setup: boolean; // set to true once the control has been setup\n\n    /**\n     * @param options - the control's options\n     */\n    constructor(options: GeolocateControlOptions) {\n        super();\n        this.options = extend({}, defaultOptions, options);\n    }\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n        this._setupUI();\n        checkGeolocationSupport().then((supported) => this._finishSetupUI(supported));\n        return this._container;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        // clear the geolocation watch if exists\n        if (this._geolocationWatchID !== undefined) {\n            window.navigator.geolocation.clearWatch(this._geolocationWatchID);\n            this._geolocationWatchID = undefined;\n        }\n\n        // clear the markers from the map\n        if (this.options.showUserLocation && this._userLocationDotMarker) {\n            this._userLocationDotMarker.remove();\n        }\n        if (this.options.showAccuracyCircle && this._accuracyCircleMarker) {\n            this._accuracyCircleMarker.remove();\n        }\n\n        this._container.remove();\n        this._map.off('movestart', this._onMoveStart);\n        this._map.off('zoom', this._onUpdate);\n        this._map.off('move', this._onUpdate);\n        this._map.off('rotate', this._onUpdate);\n        this._map.off('pitch', this._onUpdate);\n        this._map = undefined;\n        numberOfWatches = 0;\n        noTimeout = false;\n    }\n\n    /**\n     * Check if the Geolocation API Position is outside the map's `maxBounds`.\n     *\n     * @param position - the Geolocation API Position\n     * @returns `true` if position is outside the map's `maxBounds`, otherwise returns `false`.\n     */\n    _isOutOfMapMaxBounds(position: GeolocationPosition): boolean {\n        const bounds = this._map.getMaxBounds();\n        const coordinates = position.coords;\n\n        return bounds && (\n            coordinates.longitude < bounds.getWest() ||\n            coordinates.longitude > bounds.getEast() ||\n            coordinates.latitude < bounds.getSouth() ||\n            coordinates.latitude > bounds.getNorth()\n        );\n    }\n\n    _setErrorState(): void {\n        switch (this._watchState) {\n            case 'WAITING_ACTIVE':\n                this._watchState = 'ACTIVE_ERROR';\n                this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n                this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error');\n                break;\n            case 'ACTIVE_LOCK':\n                this._watchState = 'ACTIVE_ERROR';\n                this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n                this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error');\n                this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n                // turn marker grey\n                break;\n            case 'BACKGROUND':\n                this._watchState = 'BACKGROUND_ERROR';\n                this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n                this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background-error');\n                this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n                // turn marker grey\n                break;\n            case 'ACTIVE_ERROR':\n            case 'BACKGROUND_ERROR':\n                // already in error state\n                break;\n            case 'OFF':\n            case undefined:\n                // when trackUserLocation is false, watchState is undefined\n                // when trackUserLocation is true but not activated, watchState is 'OFF'\n                // in both cases, no error state transition is needed\n                break;\n            default:\n                throw new Error(`Unexpected watchState ${this._watchState}`);\n        }\n    }\n\n    /**\n     * When the Geolocation API returns a new location, update the `GeolocateControl`.\n     *\n     * @param position - the Geolocation API Position\n     */\n    _onSuccess = (position: GeolocationPosition): void => {\n        if (!this._map) {\n            // control has since been removed\n            return;\n        }\n\n        if (this._isOutOfMapMaxBounds(position)) {\n            this._setErrorState();\n\n            this.fire(new GeolocatePositionEvent('outofmaxbounds', position));\n            this._updateMarker();\n            this._finish();\n\n            return;\n        }\n\n        if (this.options.trackUserLocation) {\n            // keep a record of the position so that if the state is BACKGROUND and the user\n            // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for\n            // watchPosition to trigger _onSuccess\n            this._lastKnownPosition = position;\n\n            switch (this._watchState) {\n                case 'WAITING_ACTIVE':\n                case 'ACTIVE_LOCK':\n                case 'ACTIVE_ERROR':\n                    this._watchState = 'ACTIVE_LOCK';\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error');\n                    this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active');\n                    break;\n                case 'BACKGROUND':\n                case 'BACKGROUND_ERROR':\n                    this._watchState = 'BACKGROUND';\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error');\n                    this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background');\n                    break;\n                default:\n                    throw new Error(`Unexpected watchState ${this._watchState}`);\n            }\n        }\n\n        // if showUserLocation and the watch state isn't off then update the marker location\n        if (this.options.showUserLocation && this._watchState !== 'OFF') {\n            this._updateMarker(position);\n        }\n\n        // if in normal mode (not watch mode), or if in watch mode and the state is active watch\n        // then update the camera\n        if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') {\n            this._updateCamera(position);\n        }\n\n        if (this.options.showUserLocation) {\n            this._dotElement.classList.remove('maplibregl-user-location-dot-stale');\n        }\n\n        this.fire(new GeolocatePositionEvent('geolocate', position));\n        this._finish();\n    };\n\n    /**\n     * Update the camera location to center on the current position.\n     * The camera change is tagged with `geolocateSource` so it does not switch the control to the background state.\n     *\n     * @param position - the Geolocation API Position\n     */\n    _updateCamera = (position: GeolocationPosition): void => {\n        const center = new LngLat(position.coords.longitude, position.coords.latitude);\n        const bearing = this._map.getBearing();\n        const eventData = {geolocateSource: true};\n\n        if (!this.options.zoomToUserAccuracy) {\n            const options = extend({}, this.options.fitBoundsOptions, {center, bearing, zoom: this._map.getZoom()});\n            if (options.linear) {\n                this._map.easeTo(options, eventData);\n            } else {\n                this._map.flyTo(options, eventData);\n            }\n            return;\n        }\n\n        const radius = position.coords.accuracy;\n        const options = extend({bearing}, this.options.fitBoundsOptions);\n        const newBounds = LngLatBounds.fromLngLat(center, radius);\n\n        this._map.fitBounds(newBounds, options, eventData);\n    };\n\n    /**\n     * Update the user location dot Marker to the current position\n     *\n     * @param position - the Geolocation API Position\n     */\n    _updateMarker = (position?: GeolocationPosition | null): void => {\n        if (position) {\n            const center = new LngLat(position.coords.longitude, position.coords.latitude);\n            this._accuracyCircleMarker.setLngLat(center).addTo(this._map);\n            this._userLocationDotMarker.setLngLat(center).addTo(this._map);\n            this._accuracy = position.coords.accuracy;\n            this._updateCircleRadiusIfNeeded();\n        } else {\n            this._userLocationDotMarker.remove();\n            this._accuracyCircleMarker.remove();\n        }\n    };\n\n    _updateCircleRadiusIfNeeded(): void {\n        const userLocation = this._userLocationDotMarker.getLngLat();\n        if (!this.options.showUserLocation || !this.options.showAccuracyCircle || !this._accuracy || !userLocation) {\n            return;\n        }\n        const screenPosition = this._map.project(userLocation);\n        const userLocationWith100Px = this._map.unproject([screenPosition.x + 100, screenPosition.y]);\n        const pixelsToMeters = userLocation.distanceTo(userLocationWith100Px) / 100;\n        const circleDiameter = 2 * this._accuracy / pixelsToMeters;\n        this._circleElement.style.width = `${circleDiameter.toFixed(2)}px`;\n        this._circleElement.style.height = `${circleDiameter.toFixed(2)}px`;\n    }\n\n    _onUpdate = (): void => {\n        this._updateCircleRadiusIfNeeded();\n    };\n\n    _onError = (error: GeolocationPositionError): void => {\n        if (!this._map) {\n            // control has since been removed\n            return;\n        }\n\n        if (error.code === 1) {\n            // PERMISSION_DENIED\n            this._watchState = 'OFF';\n            this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n            this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n            this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error');\n            this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n            this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error');\n            this._geolocateButton.disabled = true;\n            const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');\n            this._geolocateButton.title = title;\n            this._geolocateButton.setAttribute('aria-label', title);\n\n            if (this._geolocationWatchID !== undefined) {\n                this._clearWatch();\n            }\n        } else if (error.code === 3 && noTimeout) {\n            // this represents a forced error state\n            // this was triggered to force immediate geolocation when a watch is already present\n            // see https://github.com/mapbox/mapbox-gl-js/issues/8214\n            // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position\n            return;\n        } else {\n            this._setErrorState();\n        }\n\n        if (this._watchState !== 'OFF' && this.options.showUserLocation) {\n            this._dotElement.classList.add('maplibregl-user-location-dot-stale');\n        }\n\n        this.fire(new GeolocateErrorEvent('error', error));\n\n        this._finish();\n    };\n\n    _finish = (): void => {\n        if (this._timeoutId) { clearTimeout(this._timeoutId); }\n        this._timeoutId = undefined;\n    };\n\n    _onMoveStart = (event: any): void => {\n        if (!this._map) return;\n        const fromResize = event?.[0] instanceof ResizeObserverEntry;\n        if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize && !this._map.isZooming()) {\n            this._watchState = 'BACKGROUND';\n            this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background');\n            this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n\n            this.fire(new GeolocateEvent('trackuserlocationend'));\n            this.fire(new GeolocateEvent('userlocationlostfocus'));\n        }\n    };\n\n    _setupUI = (): void => {\n        // the control could have been removed before reaching here\n        if (!this._map) {\n            return;\n        }\n\n        this._container.addEventListener('contextmenu', (e: MouseEvent) => { e.preventDefault(); });\n        this._geolocateButton = DOM.create('button', 'maplibregl-ctrl-geolocate', this._container);\n        DOM.create('span', 'maplibregl-ctrl-icon', this._geolocateButton).setAttribute('aria-hidden', 'true');\n        this._geolocateButton.type = 'button';\n        this._geolocateButton.disabled = true;\n    };\n\n    _finishSetupUI = (supported: boolean): void => {\n        // this method is called asynchronously during onAdd\n        if (!this._map) {\n            // control has since been removed\n            return;\n        }\n\n        if (supported === false) {\n            warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.');\n            const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');\n            this._geolocateButton.disabled = true;\n            this._geolocateButton.title = title;\n            this._geolocateButton.setAttribute('aria-label', title);\n        } else {\n            const title = this._map._getUIString('GeolocateControl.FindMyLocation');\n            this._geolocateButton.disabled = false;\n            this._geolocateButton.title = title;\n            this._geolocateButton.setAttribute('aria-label', title);\n        }\n\n        if (this.options.trackUserLocation) {\n            this._geolocateButton.setAttribute('aria-pressed', 'false');\n            this._watchState = 'OFF';\n        }\n\n        // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map\n        if (this.options.showUserLocation) {\n            this._dotElement = DOM.create('div', 'maplibregl-user-location-dot');\n\n            this._userLocationDotMarker = new Marker({element: this._dotElement});\n\n            this._circleElement = DOM.create('div', 'maplibregl-user-location-accuracy-circle');\n            this._accuracyCircleMarker = new Marker({element: this._circleElement, pitchAlignment: 'map'});\n\n            if (this.options.trackUserLocation) this._watchState = 'OFF';\n\n            this._map.on('zoom', this._onUpdate);\n            this._map.on('move', this._onUpdate);\n            this._map.on('rotate', this._onUpdate);\n            this._map.on('pitch', this._onUpdate);\n        }\n\n        this._geolocateButton.addEventListener('click', () => this.trigger());\n\n        this._setup = true;\n\n        // when the camera is changed (and it's not as a result of the Geolocation Control) change\n        // the watch mode to background watch, so that the marker is updated but not the camera.\n        if (this.options.trackUserLocation) {\n            this._map.on('movestart', this._onMoveStart);\n        }\n    };\n\n    /**\n     * Programmatically request and move the map to the user's location.\n     *\n     * @returns `false` if called before control was added to a map, otherwise returns `true`.\n     * @example\n     * ```ts\n     * // Initialize the geolocate control.\n     * let geolocate = new GeolocateControl({\n     *  positionOptions: {\n     *    enableHighAccuracy: true\n     *  },\n     *  trackUserLocation: true\n     * });\n     * // Add the control to the map.\n     * map.addControl(geolocate);\n     * map.on('load', () => {\n     *   geolocate.trigger();\n     * });\n     * ```\n     */\n    trigger(): boolean {\n        if (!this._setup) {\n            warnOnce('Geolocate control triggered before added to a map');\n            return false;\n        }\n        if (this.options.trackUserLocation) {\n            // update watchState and do any outgoing state cleanup\n            switch (this._watchState) {\n                case 'OFF':\n                // turn on the Geolocate Control\n                    this._watchState = 'WAITING_ACTIVE';\n\n                    this.fire(new GeolocateEvent('trackuserlocationstart'));\n                    break;\n                case 'WAITING_ACTIVE':\n                case 'ACTIVE_LOCK':\n                case 'ACTIVE_ERROR':\n                case 'BACKGROUND_ERROR':\n                // turn off the Geolocate Control\n                    numberOfWatches--;\n                    noTimeout = false;\n                    this._watchState = 'OFF';\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error');\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error');\n\n                    this.fire(new GeolocateEvent('trackuserlocationend'));\n                    break;\n                case 'BACKGROUND':\n                    this._watchState = 'ACTIVE_LOCK';\n                    this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background');\n                    // set camera to last known location\n                    if (this._lastKnownPosition) this._updateCamera(this._lastKnownPosition);\n\n                    this.fire(new GeolocateEvent('trackuserlocationstart'));\n                    this.fire(new GeolocateEvent('userlocationfocus'));\n                    break;\n                default:\n                    throw new Error(`Unexpected watchState ${this._watchState}`);\n            }\n\n            // incoming state setup\n            switch (this._watchState) {\n                case 'WAITING_ACTIVE':\n                    this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n                    this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active');\n                    break;\n                case 'ACTIVE_LOCK':\n                    this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active');\n                    break;\n                case 'OFF':\n                    break;\n                default:\n                    throw new Error(`Unexpected watchState ${this._watchState}`);\n            }\n\n            // manage geolocation.watchPosition / geolocation.clearWatch\n            if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) {\n                // clear watchPosition as we've changed to an OFF state\n                this._clearWatch();\n            } else if (this._geolocationWatchID === undefined) {\n                // enable watchPosition since watchState is not OFF and there is no watchPosition already running\n\n                this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting');\n                this._geolocateButton.setAttribute('aria-pressed', 'true');\n\n                numberOfWatches++;\n                let positionOptions;\n                if (numberOfWatches > 1) {\n                    positionOptions = {maximumAge: 600000, timeout: 0};\n                    noTimeout = true;\n                } else {\n                    positionOptions = this.options.positionOptions;\n                    noTimeout = false;\n                }\n\n                this._geolocationWatchID = window.navigator.geolocation.watchPosition(\n                    this._onSuccess, this._onError, positionOptions);\n            }\n        } else {\n            window.navigator.geolocation.getCurrentPosition(\n                this._onSuccess, this._onError, this.options.positionOptions);\n\n            // This timeout ensures that we still call finish() even if\n            // the user declines to share their location in Firefox\n            this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */);\n        }\n\n        return true;\n    }\n\n    _clearWatch(): void {\n        window.navigator.geolocation.clearWatch(this._geolocationWatchID);\n\n        this._geolocationWatchID = undefined;\n        this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting');\n        this._geolocateButton.setAttribute('aria-pressed', 'false');\n\n        if (this.options.showUserLocation) {\n            this._updateMarker(null);\n        }\n    }\n}\n", "import {DOM} from '../../util/dom.ts';\n\nimport type {Map} from '../map.ts';\nimport type {ControlPosition, IControl} from './control.ts';\n\n/**\n * The unit type for length to use for the {@link ScaleControl}\n */\nexport type Unit = 'imperial' | 'metric' | 'nautical';\n\n/**\n * The {@link ScaleControl} options object\n */\nexport type ScaleControlOptions = {\n    /**\n     * The maximum length of the scale control in pixels.\n     * @defaultValue 100\n     */\n    maxWidth?: number;\n    /**\n     * Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).\n     * @defaultValue 'metric'\n     */\n    unit?: Unit;\n};\n\nconst defaultOptions: ScaleControlOptions = {\n    maxWidth: 100,\n    unit: 'metric'\n};\n\n/**\n * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let scale = new ScaleControl({\n *     maxWidth: 80,\n *     unit: 'imperial'\n * });\n * map.addControl(scale);\n *\n * scale.setUnit('metric');\n * ```\n */\nexport class ScaleControl implements IControl {\n    _map: Map;\n    _container: HTMLElement;\n    options: ScaleControlOptions;\n\n    /**\n     * @param options - the control's options\n     */\n    constructor(options?: ScaleControlOptions) {\n        this.options = {...defaultOptions, ...options};\n    }\n\n    getDefaultPosition(): ControlPosition {\n        return 'bottom-left';\n    }\n\n    _onMove = (): void => {\n        updateScale(this._map, this._container, this.options);\n    };\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-scale', map.getContainer());\n\n        this._map.on('move', this._onMove);\n        this._map.on('projectiontransition', this._onMove);\n        this._onMove();\n\n        return this._container;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        this._container.remove();\n        this._map.off('move', this._onMove);\n        this._map.off('projectiontransition', this._onMove);\n        this._map = undefined;\n    }\n\n    /**\n     * Set the scale's unit of the distance\n     *\n     * @param unit - Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).\n     */\n    setUnit = (unit: Unit): void => {\n        this.options.unit = unit;\n        if (!this._map) return;\n        updateScale(this._map, this._container, this.options);\n    };\n}\n\n/**\n * A horizontal scale is imagined to be present at center of the map\n * container with maximum length (Default) as 100px.\n * Using spherical law of cosines approximation, the real distance is\n * found between the two coordinates and is rounded off to near pretty number.\n * Minimum maxWidth is calculated for the scale box.\n * In case the center of the screen is not pointing at the map, the previous scale is used.\n * \n */\nfunction updateScale(map: Map, container: HTMLElement, options: ScaleControlOptions): void {\n    const optWidth = options?.maxWidth || 100;\n    const {width: containerWidth, height: containerHeight} = map._camera.transform;\n    const y = containerHeight / 2;\n    const x = containerWidth / 2;\n    const left = map.unproject([x - optWidth / 2, y]);\n    const right = map.unproject([x + optWidth / 2, y]);\n    if (!left || !right) return;\n\n    const globeWidth = Math.round(map.project(right).x - map.project(left).x);\n    const maxWidth = Math.min(optWidth, globeWidth, containerWidth);\n\n    const maxMeters = left.distanceTo(right);\n    if (options?.unit === 'imperial') {\n        const maxFeet = 3.2808 * maxMeters;\n        if (maxFeet > 5280) {\n            const maxMiles = maxFeet / 5280;\n            setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles'));\n        } else {\n            setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet'));\n        }\n    } else if (options?.unit === 'nautical') {\n        const maxNauticals = maxMeters / 1852;\n        setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles'));\n    } else if (maxMeters >= 1000) {\n        setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers'));\n    } else {\n        setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters'));\n    }\n}\n\nfunction setScale(container: HTMLElement, maxWidth: number, maxDistance: number, unit: string): void {\n    const distance = getRoundNum(maxDistance);\n    const ratio = distance / maxDistance;\n    container.style.width = `${maxWidth * ratio}px`;\n    const label = `${distance}\\u00a0${unit}`;\n    if (container.textContent !== label) container.textContent = label;\n}\n\nfunction getDecimalRoundNum(d) {\n    const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10));\n    return Math.round(d * multiplier) / multiplier;\n}\n\nfunction getRoundNum(num) {\n    const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1);\n    let d = num / pow10;\n\n    d = d >= 10 ? 10 :\n        d >= 5 ? 5 :\n            d >= 3 ? 3 :\n                d >= 2 ? 2 :\n                    d >= 1 ? 1 : getDecimalRoundNum(d);\n\n    return pow10 * d;\n}\n", "import {DOM} from '../../util/dom.ts';\nimport {warnOnce} from '../../util/util.ts';\nimport {Event, Evented} from '../../util/evented.ts';\n\nimport type {Map} from '../map.ts';\nimport type {IControl} from './control.ts';\n\n/**\n * The {@link FullscreenControl} options object\n */\nexport type FullscreenControlOptions = {\n    /**\n     * `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.\n     */\n    container?: HTMLElement;\n    /**\n     * If `true`, the fullscreen control will always use pseudo fullscreen mode (CSS-based, expanding to browser viewport) instead of native fullscreen API.\n     * This can be useful for faster transitions and to allow multiple maps to be \"fullscreen\" simultaneously in different browser windows.\n     * @defaultValue false\n     */\n    pseudo?: boolean;\n};\n\n/**\n * The event class for fullscreen control events (`fullscreenstart` and `fullscreenend`).\n *\n * @group Event Related\n */\nexport class FullscreenEvent extends Event {\n    type: 'fullscreenstart' | 'fullscreenend';\n    /**\n     * The `FullscreenControl` object that fired the event.\n     */\n    target: FullscreenControl;\n}\n\n/**\n * `FullscreenControlEventType` - a mapping between the fullscreen control event name and the event value.\n * These events are used with the {@link FullscreenControl.on} method.\n *\n * @group Event Related\n */\nexport type FullscreenControlEventType = {\n    /**\n     * Fired when fullscreen mode has started.\n     */\n    fullscreenstart: FullscreenEvent;\n    /**\n     * Fired when fullscreen mode has ended.\n     */\n    fullscreenend: FullscreenEvent;\n};\n\n/**\n * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode.\n * When [requestFullscreen](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) is not supported, fullscreen is handled via CSS properties.\n * The map's `cooperativeGestures` option is temporarily disabled while the map\n * is in fullscreen mode, and is restored when the map exist fullscreen mode.\n *\n * @group Markers and Controls\n * @param options - the full screen control options\n *\n * @example\n * ```ts\n * map.addControl(new FullscreenControl({container: document.querySelector('body')}));\n * ```\n * @see [View a fullscreen map](https://maplibre.org/maplibre-gl-js/docs/examples/view-a-fullscreen-map/)\n *\n * ## Events\n *\n * **Event** `fullscreenstart` of type {@link FullscreenEvent} will be fired when fullscreen mode has started.\n *\n * **Event** `fullscreenend` of type {@link FullscreenEvent} will be fired when fullscreen mode has ended.\n */\nexport class FullscreenControl extends Evented<FullscreenControlEventType> implements IControl {\n    _map: Map;\n    _controlContainer: HTMLElement;\n    _fullscreen: boolean;\n    _fullscreenchange: string;\n    _fullscreenButton: HTMLButtonElement;\n    _container: HTMLElement;\n    _prevCooperativeGesturesEnabled: boolean;\n    _pseudo: boolean;\n\n    /**\n     * @param options - the control's options\n     */\n    constructor(options: FullscreenControlOptions = {}) {\n        super();\n        this._fullscreen = false;\n        this._pseudo = options.pseudo ?? false;\n\n        if (options?.container) {\n            if (options.container instanceof HTMLElement) {\n                this._container = options.container;\n            } else {\n                warnOnce('Full screen control \\'container\\' must be a DOM element.');\n            }\n        }\n\n        if ('onfullscreenchange' in document) {\n            this._fullscreenchange = 'fullscreenchange';\n        } else if ('onmozfullscreenchange' in document) {\n            this._fullscreenchange = 'mozfullscreenchange';\n        } else if ('onwebkitfullscreenchange' in document) {\n            this._fullscreenchange = 'webkitfullscreenchange';\n        } else if ('onmsfullscreenchange' in document) {\n            this._fullscreenchange = 'MSFullscreenChange';\n        }\n    }\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        this._container ||= this._map.getContainer();\n        this._controlContainer = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n        this._setupUI();\n        return this._controlContainer;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        this._controlContainer.remove();\n        this._map = null;\n        window.document.removeEventListener(this._fullscreenchange, this._onFullscreenChange);\n    }\n\n    _setupUI(): void {\n        const button = this._fullscreenButton = DOM.create('button', (('maplibregl-ctrl-fullscreen')), this._controlContainer);\n        DOM.create('span', 'maplibregl-ctrl-icon', button).setAttribute('aria-hidden', 'true');\n        button.type = 'button';\n        this._updateTitle();\n        this._fullscreenButton.addEventListener('click', this._onClickFullscreen);\n        window.document.addEventListener(this._fullscreenchange, this._onFullscreenChange);\n    }\n\n    _updateTitle(): void {\n        const title = this._getTitle();\n        this._fullscreenButton.setAttribute('aria-label', title);\n        this._fullscreenButton.title = title;\n    }\n\n    _getTitle(): string {\n        return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter');\n    }\n\n    _isFullscreen(): boolean {\n        return this._fullscreen;\n    }\n\n    _onFullscreenChange = (): void => {\n        // WebKit due to https://caniuse.com/mdn-api_document_fullscreenelement\n        let fullscreenElement =\n            window.document.fullscreenElement ||\n            (window.document as any).webkitFullscreenElement;\n\n        while (fullscreenElement?.shadowRoot?.fullscreenElement) {\n            fullscreenElement = fullscreenElement.shadowRoot.fullscreenElement;\n        }\n\n        if ((fullscreenElement === this._container) !== this._fullscreen) {\n            this._handleFullscreenChange();\n        }\n    };\n\n    _handleFullscreenChange(): void {\n        this._fullscreen = !this._fullscreen;\n        this._fullscreenButton.classList.toggle('maplibregl-ctrl-shrink');\n        this._fullscreenButton.classList.toggle('maplibregl-ctrl-fullscreen');\n        this._updateTitle();\n\n        if (this._fullscreen) {\n            this.fire(new FullscreenEvent('fullscreenstart'));\n            this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled();\n            this._map.cooperativeGestures.disable();\n        } else {\n            this.fire(new FullscreenEvent('fullscreenend'));\n            if (this._prevCooperativeGesturesEnabled) {\n                this._map.cooperativeGestures.enable();\n            }\n        }\n    }\n\n    _onClickFullscreen = (): void => {\n        if (this._isFullscreen()) {\n            this._exitFullscreen();\n        } else {\n            this._requestFullscreen();\n        }\n    };\n\n    _exitFullscreen(): void {\n        if (this._pseudo) {\n            this._togglePseudoFullScreen();\n        } else if (window.document.exitFullscreen) {\n            (window.document as any).exitFullscreen();\n        } else if ((window.document as any).webkitCancelFullScreen) {\n            // due to https://caniuse.com/mdn-api_document_exitfullscreen\n            (window.document as any).webkitCancelFullScreen();\n        } else {\n            this._togglePseudoFullScreen();\n        }\n    }\n\n    _requestFullscreen(): void {\n        if (this._pseudo) {\n            this._togglePseudoFullScreen();\n        } else if (this._container.requestFullscreen) {\n            this._container.requestFullscreen();\n        } else if ((this._container as any).webkitRequestFullscreen) {\n            // due to https://caniuse.com/mdn-api_element_requestfullscreen\n            (this._container as any).webkitRequestFullscreen();\n        } else {\n            this._togglePseudoFullScreen();\n        }\n    }\n\n    _togglePseudoFullScreen(): void {\n        this._container.classList.toggle('maplibregl-pseudo-fullscreen');\n        this._handleFullscreenChange();\n        this._map.resize();\n    }\n}\n", "import {DOM} from '../../util/dom.ts';\n\nimport type {Map} from '../map.ts';\nimport type {IControl} from './control.ts';\nimport type {TerrainSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * A `TerrainControl` control contains a button for turning the terrain on and off.\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let map = new Map({TerrainControl: false})\n *     .addControl(new TerrainControl({\n *         source: \"terrain\"\n *     }));\n * ```\n * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/)\n * @see [Create a Heatmap layer on a globe with terrain elevation](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-heatmap-layer-on-a-globe-with-terrain-elevation/)\n * @see [Display a hybrid satellite map with terrain elevation](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-hybrid-satellite-map-with-terrain-elevation/)\n * @see [Sky, Fog, Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/sky-fog-terrain/)\n */\nexport class TerrainControl implements IControl {\n    options: TerrainSpecification;\n    _map: Map;\n    _container: HTMLElement;\n    _terrainButton: HTMLButtonElement;\n\n    /**\n     * @param options - the control's options\n     */\n    constructor(options: TerrainSpecification) {\n        this.options = options;\n    }\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n        this._terrainButton = DOM.create('button', 'maplibregl-ctrl-terrain', this._container);\n        DOM.create('span', 'maplibregl-ctrl-icon', this._terrainButton).setAttribute('aria-hidden', 'true');\n        this._terrainButton.type = 'button';\n        this._terrainButton.addEventListener('click', this._toggleTerrain);\n\n        this._updateTerrainIcon();\n        this._map.on('terrain', this._updateTerrainIcon);\n        return this._container;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        this._container.remove();\n        this._map.off('terrain', this._updateTerrainIcon);\n        this._map = undefined;\n    }\n\n    _toggleTerrain = (): void => {\n        if (this._map.getTerrain()) {\n            this._map.setTerrain(null);\n        } else {\n            this._map.setTerrain(this.options);\n        }\n        this._updateTerrainIcon();\n    };\n\n    _updateTerrainIcon = (): void => {\n        this._terrainButton.classList.remove('maplibregl-ctrl-terrain');\n        this._terrainButton.classList.remove('maplibregl-ctrl-terrain-enabled');\n        if (this._map.terrain) {\n            this._terrainButton.classList.add('maplibregl-ctrl-terrain-enabled');\n            this._terrainButton.title = this._map._getUIString('TerrainControl.Disable');\n        } else {\n            this._terrainButton.classList.add('maplibregl-ctrl-terrain');\n            this._terrainButton.title = this._map._getUIString('TerrainControl.Enable');\n        }\n    };\n}\n", "import {DOM} from '../../util/dom.ts';\n\nimport type {Map} from '../map.ts';\nimport type {IControl} from './control.ts';\n\n/**\n * A `GlobeControl` control contains a button for toggling the map projection between \"mercator\" and \"globe\".\n *\n * @group Markers and Controls\n *\n * @example\n * ```ts\n * let map = new Map()\n *     .addControl(new GlobeControl());\n * ```\n *\n * @see [Display a globe with a fill extrusion layer](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-globe-with-a-fill-extrusion-layer/)\n * @see [Sky, Fog, Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/sky-fog-terrain/)\n */\nexport class GlobeControl implements IControl {\n    _map: Map;\n    _container: HTMLElement;\n    _globeButton: HTMLButtonElement;\n\n    /** {@inheritDoc IControl.onAdd} */\n    onAdd(map: Map): HTMLElement {\n        this._map = map;\n        this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');\n        this._globeButton = DOM.create('button', 'maplibregl-ctrl-globe', this._container);\n        DOM.create('span', 'maplibregl-ctrl-icon', this._globeButton).setAttribute('aria-hidden', 'true');\n        this._globeButton.type = 'button';\n        this._globeButton.addEventListener('click', this._toggleProjection);\n\n        this._updateGlobeIcon();\n        this._map.on('styledata', this._updateGlobeIcon);\n        this._map.on('projectiontransition', this._updateGlobeIcon);\n        return this._container;\n    }\n\n    /** {@inheritDoc IControl.onRemove} */\n    onRemove(): void {\n        this._container.remove();\n        this._map.off('styledata', this._updateGlobeIcon);\n        this._map.off('projectiontransition', this._updateGlobeIcon);\n        this._globeButton.removeEventListener('click', this._toggleProjection);\n        this._map = undefined;\n    }\n\n    _toggleProjection = (): void => {\n        const currentProjection = this._map.getProjection()?.type;\n        if (currentProjection === 'mercator' || !currentProjection) {\n            this._map.setProjection({type: 'globe'});\n        } else {\n            this._map.setProjection({type: 'mercator'});\n        }\n        this._updateGlobeIcon();\n    };\n\n    _updateGlobeIcon = (): void => {\n        this._globeButton.classList.remove('maplibregl-ctrl-globe');\n        this._globeButton.classList.remove('maplibregl-ctrl-globe-enabled');\n        if (this._map.getProjection()?.type === 'globe') {\n            this._globeButton.classList.add('maplibregl-ctrl-globe-enabled');\n            this._globeButton.title = this._map._getUIString('GlobeControl.Disable');\n        } else {\n            this._globeButton.classList.add('maplibregl-ctrl-globe');\n            this._globeButton.title = this._map._getUIString('GlobeControl.Enable');\n        }\n    };\n}\n", "import {extend} from '../util/util.ts';\nimport {Event, Evented} from '../util/evented.ts';\nimport {DOM} from '../util/dom.ts';\nimport {LngLat} from '../geo/lng_lat.ts';\nimport {smartWrap} from '../util/smart_wrap.ts';\nimport {anchorTranslate, applyAnchorClass} from './anchor.ts';\nimport Point from '@mapbox/point-geometry';\n\nimport type {MapLibreEvent, MapMouseEvent} from './events.ts';\nimport type {PositionAnchor} from './anchor.ts';\nimport type {Map} from './map.ts';\nimport type {LngLatLike} from '../geo/lng_lat.ts';\nimport type {PointLike} from './camera.ts';\nimport type {PaddingOptions} from '../geo/edge_insets.ts';\n\nconst defaultOptions = {\n    closeButton: true,\n    closeOnClick: true,\n    focusAfterOpen: true,\n    className: '',\n    maxWidth: '240px',\n    subpixelPositioning: false,\n    locationOccludedOpacity: undefined,\n    padding: undefined,\n};\n\n/**\n * A pixel offset specified as:\n *\n * - A single number specifying a distance from the location\n * - A {@link PointLike} specifying a constant offset\n * - An object of {@link PointLike}s specifying an offset for each anchor position\n *\n * Negative offsets indicate left and up.\n */\nexport type Offset = number | PointLike | {\n    [_ in PositionAnchor]: PointLike;\n};\n\n/**\n * The {@link Popup} options object\n */\nexport type PopupOptions = {\n    /**\n     * If `true`, a close button will appear in the top right corner of the popup.\n     * @defaultValue true\n     */\n    closeButton?: boolean;\n    /**\n     * If `true`, the popup will closed when the map is clicked.\n     * @defaultValue true\n     */\n    closeOnClick?: boolean;\n    /**\n     * If `true`, the popup will closed when the map moves.\n     * @defaultValue false\n     */\n    closeOnMove?: boolean;\n    /**\n     * If `true`, the popup will try to focus the first focusable element inside the popup.\n     * @defaultValue true\n     */\n    focusAfterOpen?: boolean;\n    /**\n     * A string indicating the part of the Popup that should\n     * be positioned closest to the coordinate set via {@link Popup.setLngLat}.\n     * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`,\n     * `'top-right'`, `'bottom-left'`, and `'bottom-right'`. If unset the anchor will be\n     * dynamically set to ensure the popup falls within the map container with a preference\n     * for `'bottom'`.\n     */\n    anchor?: PositionAnchor;\n    /**\n     * A pixel offset applied to the popup's location\n     */\n    offset?: Offset;\n    /**\n     * Space-separated CSS class names to add to popup container\n     */\n    className?: string;\n    /**\n     * A string that sets the CSS property of the popup's maximum width, eg `'300px'`.\n     * To ensure the popup resizes to fit its content, set this property to `'none'`.\n     * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width\n     * @defaultValue '240px'\n     */\n    maxWidth?: string;\n    /**\n     * If `true`, rounding is disabled for placement of the popup, allowing for\n     * subpixel positioning and smoother movement when the popup is translated.\n     * @defaultValue false\n     */\n    subpixelPositioning?: boolean;\n    /**\n     * Optional opacity when the location is behind the globe.\n     * Note that if a number is provided, it will be converted to a string.\n     * @defaultValue undefined\n     */\n    locationOccludedOpacity?: number | string;\n    /**\n     * A pixel padding applied to the popup's positioning constraints.\n     * The popup will be positioned to avoid being placed within this padding area\n     * from the edges of the map container.\n     * @defaultValue undefined\n     */\n    padding?: PaddingOptions;\n};\n\nconst focusQuerySelector = [\n    'a[href]',\n    '[tabindex]:not([tabindex=\\'-1\\'])',\n    '[contenteditable]:not([contenteditable=\\'false\\'])',\n    'button:not([disabled])',\n    'input:not([disabled])',\n    'select:not([disabled])',\n    'textarea:not([disabled])',\n].join(', ');\n\n/**\n * The event class for popup events (`open` and `close`).\n *\n * @group Event Related\n */\nexport class PopupEvent extends Event {\n    type: keyof PopupEventType;\n    /**\n     * The `Popup` object that fired the event.\n     */\n    target: Popup;\n}\n\n/**\n * `PopupEventType` - a mapping between the popup event name and the event value.\n * These events are used with the {@link Popup.on} method.\n *\n * @group Event Related\n */\nexport type PopupEventType = {\n    /**\n     * Fired when the popup is opened manually or programmatically.\n     */\n    open: PopupEvent;\n    /**\n     * Fired when the popup is closed manually or programmatically.\n     */\n    close: PopupEvent;\n};\n\n/**\n * A popup component.\n *\n * @group Markers and Controls\n *\n *\n * @example\n * Create a popup\n * ```ts\n * let popup = new Popup();\n * // Set an event listener that will fire\n * // any time the popup is opened\n * popup.on('open', () => {\n *   console.log('popup was opened');\n * });\n * ```\n *\n * @example\n * Create a popup\n * ```ts\n * let popup = new Popup();\n * // Set an event listener that will fire\n * // any time the popup is closed\n * popup.on('close', () => {\n *   console.log('popup was closed');\n * });\n * ```\n *\n * @example\n * ```ts\n * let markerHeight = 50, markerRadius = 10, linearOffset = 25;\n * let popupOffsets = {\n *  'top': [0, 0],\n *  'top-left': [0,0],\n *  'top-right': [0,0],\n *  'bottom': [0, -markerHeight],\n *  'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n *  'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n *  'left': [markerRadius, (markerHeight - markerRadius) * -1],\n *  'right': [-markerRadius, (markerHeight - markerRadius) * -1]\n *  };\n * let popup = new Popup({offset: popupOffsets, className: 'my-class'})\n *   .setLngLat(e.lngLat)\n *   .setHTML(\"<h1>Hello World!</h1>\")\n *   .setMaxWidth(\"300px\")\n *   .addTo(map);\n * ```\n * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)\n * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)\n * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)\n * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/show-polygon-information-on-click/)\n *\n * ## Events\n *\n * **Event** `open` of type {@link PopupEvent} will be fired when the popup is opened manually or programmatically.\n *\n * **Event** `close` of type {@link PopupEvent} will be fired when the popup is closed manually or programmatically.\n */\nexport class Popup extends Evented<PopupEventType> {\n    _map: Map;\n    options: PopupOptions;\n    _content: HTMLElement;\n    _container: HTMLElement;\n    _closeButton: HTMLButtonElement;\n    _tip: HTMLElement;\n    _lngLat: LngLat;\n    _trackPointer: boolean;\n    _pos: Point;\n    _flatPos: Point;\n\n    /**\n     * @param options - the options\n     */\n    constructor(options?: PopupOptions) {\n        super();\n        this.options = extend(Object.create(defaultOptions), options);\n    }\n\n    /**\n     * Adds the popup to a map.\n     *\n     * @param map - The MapLibre GL JS map to add the popup to.\n     * @example\n     * ```ts\n     * new Popup()\n     *   .setLngLat([0, 0])\n     *   .setHTML(\"<h1>Null Island</h1>\")\n     *   .addTo(map);\n     * ```\n     * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)\n     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n     * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)\n     * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/show-polygon-information-on-click/)\n     */\n    addTo(map: Map): this {\n        if (this._map) this.remove();\n\n        this._map = map;\n        if (this.options.closeOnClick) {\n            this._map.on('click', this._onClose);\n        }\n\n        if (this.options.closeOnMove) {\n            this._map.on('move', this._onClose);\n        }\n\n        this._map.on('remove', this.remove);\n        this._map.on('terrain', this._update);\n        this._map.on('projectiontransition', this._update);\n        this._map.on('idle', this._update);\n        this._update();\n        this._focusFirstElement();\n\n        if (this._trackPointer) {\n            this._map.on('mousemove', this._update);\n            this._map.on('mouseup', this._update);\n            if (this._container) {\n                this._container.classList.add('maplibregl-popup-track-pointer');\n            }\n            this._map._canvasContainer.classList.add('maplibregl-track-pointer');\n        } else {\n            this._map.on('move', this._update);\n        }\n\n        this.fire(new PopupEvent('open'));\n\n        return this;\n    }\n\n    /**\n     * Add opacity to popup if in globe projection and location is behind view\n     */\n    _updateOpacity = (): void => {\n        if (this.options.locationOccludedOpacity === undefined) {\n            return;\n        }\n        if (this._map._camera.transform.isLocationOccluded(this.getLngLat())) {\n            this._container.style.opacity = `${this.options.locationOccludedOpacity}`;\n        } else {\n            this._container.style.opacity = '';\n        }\n    };\n\n    /**\n     * @returns `true` if the popup is open, `false` if it is closed.\n     */\n    isOpen(): boolean {\n        return !!this._map;\n    }\n\n    /**\n     * Removes the popup from the map it has been added to.\n     *\n     * @example\n     * ```ts\n     * let popup = new Popup().addTo(map);\n     * popup.remove();\n     * ```\n     */\n    remove = (): this => {\n        if (this._content) {\n            this._content.remove();\n        }\n\n        if (this._container) {\n            this._container.remove();\n            delete this._container;\n        }\n\n        if (this._map) {\n            this._map.off('move', this._update);\n            this._map.off('move', this._onClose);\n            this._map.off('click', this._onClose);\n            this._map.off('remove', this.remove);\n            this._map.off('terrain', this._update);\n            this._map.off('projectiontransition', this._update);\n            this._map.off('idle', this._update);\n            this._map.off('mousemove', this._update);\n            this._map.off('mouseup', this._update);\n            this._map.off('drag', this._update);\n            this._map._canvasContainer.classList.remove('maplibregl-track-pointer');\n            delete this._map;\n            this.fire(new PopupEvent('close'));\n        }\n\n        return this;\n    };\n\n    /**\n     * Returns the geographical location of the popup's anchor.\n     *\n     * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously\n     * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep\n     * the popup on screen.\n     *\n     * @returns The geographical location of the popup's anchor.\n     */\n    getLngLat(): LngLat {\n        return this._lngLat;\n    }\n\n    /**\n     * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior.\n     *\n     * @param lnglat - The geographical location to set as the popup's anchor.\n     */\n    setLngLat(lnglat: LngLatLike): this {\n        this._lngLat = LngLat.convert(lnglat);\n        this._pos = null;\n        this._flatPos = null;\n\n        this._trackPointer = false;\n\n        this._update();\n\n        if (this._map) {\n            this._map.on('move', this._update);\n            this._map.off('mousemove', this._update);\n            if (this._container) {\n                this._container.classList.remove('maplibregl-popup-track-pointer');\n            }\n            this._map._canvasContainer.classList.remove('maplibregl-track-pointer');\n        }\n\n        return this;\n    }\n\n    /**\n     * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior.\n     * For most use cases, set `closeOnClick` and `closeButton` to `false`.\n     * @example\n     * ```ts\n     * let popup = new Popup({ closeOnClick: false, closeButton: false })\n     *   .setHTML(\"<h1>Hello World!</h1>\")\n     *   .trackPointer()\n     *   .addTo(map);\n     * ```\n     */\n    trackPointer(): this {\n        this._trackPointer = true;\n        this._pos = null;\n        this._flatPos = null;\n        this._update();\n        if (this._map) {\n            this._map.off('move', this._update);\n            this._map.on('mousemove', this._update);\n            this._map.on('drag', this._update);\n            if (this._container) {\n                this._container.classList.add('maplibregl-popup-track-pointer');\n            }\n            this._map._canvasContainer.classList.add('maplibregl-track-pointer');\n        }\n\n        return this;\n\n    }\n\n    /**\n     * Returns the `Popup`'s HTML element.\n     * @example\n     * Change the `Popup` element's font size\n     * ```ts\n     * let popup = new Popup()\n     *   .setLngLat([-96, 37.8])\n     *   .setHTML(\"<p>Hello World!</p>\")\n     *   .addTo(map);\n     * let popupElem = popup.getElement();\n     * popupElem.style.fontSize = \"25px\";\n     * ```\n     * @returns element\n     */\n    getElement(): HTMLElement {\n        return this._container;\n    }\n\n    /**\n     * Sets the popup's content to a string of text.\n     *\n     * This function creates a [Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) node in the DOM,\n     * so it cannot insert raw HTML. Use this method for security against XSS\n     * if the popup content is user-provided.\n     *\n     * @param text - Textual content for the popup.\n     * @example\n     * ```ts\n     * let popup = new Popup()\n     *   .setLngLat(e.lngLat)\n     *   .setText('Hello, world!')\n     *   .addTo(map);\n     * ```\n     */\n    setText(text: string): this {\n        return this.setDOMContent(document.createTextNode(text));\n    }\n\n    /**\n     * Sets the popup's content to the HTML provided as a string.\n     *\n     * This method does not perform HTML filtering or sanitization, and must be\n     * used only with trusted content. Consider {@link Popup.setText} if\n     * the content is an untrusted text string.\n     *\n     * @param html - A string representing HTML content for the popup.\n     * @example\n     * ```ts\n     * let popup = new Popup()\n     *   .setLngLat(e.lngLat)\n     *   .setHTML(\"<h1>Hello World!</h1>\")\n     *   .addTo(map);\n     * ```\n     * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)\n     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)\n     * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)\n     * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)\n     */\n    setHTML(html: string): this {\n        const frag = document.createDocumentFragment();\n        const temp = document.createElement('body');\n        let child: ChildNode;\n        temp.innerHTML = html;\n        while (true) {\n            child = temp.firstChild;\n            if (!child) break;\n            frag.appendChild(child);\n        }\n\n        return this.setDOMContent(frag);\n    }\n\n    /**\n     * Returns the popup's maximum width.\n     *\n     * @returns The maximum width of the popup.\n     */\n    getMaxWidth(): string {\n        return this._container?.style.maxWidth;\n    }\n\n    /**\n     * Sets the popup's maximum width. This is setting the CSS property `max-width`.\n     * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width\n     *\n     * @param maxWidth - A string representing the value for the maximum width.\n     */\n    setMaxWidth(maxWidth: string): this {\n        this.options.maxWidth = maxWidth;\n        this._update();\n        return this;\n    }\n\n    /**\n     * Sets the popup's content to the element provided as a DOM node.\n     *\n     * @param htmlNode - A DOM node to be used as content for the popup.\n     * @example\n     * Create an element with the popup content\n     * ```ts\n     * let div = document.createElement('div');\n     * div.innerHTML = 'Hello, world!';\n     * let popup = new Popup()\n     *   .setLngLat(e.lngLat)\n     *   .setDOMContent(div)\n     *   .addTo(map);\n     * ```\n     */\n    setDOMContent(htmlNode: Node): this {\n        if (this._content) {\n            // Clear out children first.\n            while (this._content.hasChildNodes()) {\n                if (this._content.firstChild) {\n                    this._content.removeChild(this._content.firstChild);\n                }\n            }\n        } else {\n            this._content = DOM.create('div', 'maplibregl-popup-content', this._container);\n        }\n\n        // The close button should be the last tabbable element inside the popup for a good keyboard UX.\n        this._content.appendChild(htmlNode);\n        this._createCloseButton();\n        this._update();\n        this._focusFirstElement();\n        return this;\n    }\n\n    /**\n     * Adds a CSS class to the popup container element.\n     *\n     * @param className - Non-empty string with CSS class name to add to popup container\n     *\n     * @example\n     * ```ts\n     * let popup = new Popup()\n     * popup.addClassName('some-class')\n     * ```\n     */\n    addClassName(className: string): this {\n        if (this._container) {\n            this._container.classList.add(className);\n        }\n        return this;\n    }\n\n    /**\n     * Removes a CSS class from the popup container element.\n     *\n     * @param className - Non-empty string with CSS class name to remove from popup container\n     *\n     * @example\n     * ```ts\n     * let popup = new Popup()\n     * popup.removeClassName('some-class')\n     * ```\n     */\n    removeClassName(className: string): this {\n        if (this._container) {\n            this._container.classList.remove(className);\n        }\n        return this;\n    }\n\n    /**\n     * Sets the popup's offset.\n     *\n     * @param offset - Sets the popup's offset.\n     */\n    setOffset (offset?: Offset): this {\n        this.options.offset = offset;\n        this._update();\n        return this;\n    }\n\n    /**\n     * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.\n     *\n     * @param className - Non-empty string with CSS class name to add/remove\n     *\n     * @returns if the class was removed return false, if class was added, then return true, undefined if there is no container\n     *\n     * @example\n     * ```ts\n     * let popup = new Popup()\n     * popup.toggleClassName('toggleClass')\n     * ```\n     */\n    toggleClassName(className: string): boolean | undefined {\n        if (this._container) {\n            return this._container.classList.toggle(className);\n        }\n    }\n\n    /**\n     * Set the option to allow subpixel positioning of the popup by passing a boolean\n     *\n     * @param value - When boolean is true, subpixel positioning is enabled for the popup.\n     *\n     * @example\n     * ```ts\n     * let popup = new Popup()\n     * popup.setSubpixelPositioning(true);\n     * ```\n     */\n    setSubpixelPositioning(value: boolean): void {\n        this.options.subpixelPositioning = value;\n    }\n\n    /**\n     * Sets the popup's padding constraints for positioning.\n     *\n     * @param padding - The padding to apply as a {@link PaddingOptions} object.\n     * @example\n     * ```ts\n     * popup.setPadding({ top: 10, right: 20, bottom: 30, left: 40 });\n     * ```\n     */\n    setPadding(padding?: PaddingOptions): void {\n        this.options.padding = padding;\n        this._update();\n    }\n\n    _createCloseButton(): void {\n        if (this.options.closeButton) {\n            this._closeButton = DOM.create('button', 'maplibregl-popup-close-button', this._content);\n            this._closeButton.type = 'button';\n            this._closeButton.textContent = '\\xd7';\n            this._closeButton.addEventListener('click', this._onClose);\n        }\n    }\n\n    _update = (event?: MapLibreEvent | MapMouseEvent): void => {\n        const hasPosition = this._lngLat || this._trackPointer;\n\n        if (!this._map || !hasPosition || !this._content) { return; }\n\n        if (!this._container) {\n            this._container = DOM.create('div', 'maplibregl-popup', this._map.getContainer());\n            this._tip       = DOM.create('div', 'maplibregl-popup-tip', this._container);\n            this._container.appendChild(this._content);\n            if (this.options.className) {\n                for (const name of this.options.className.split(' ')) {\n                    this._container.classList.add(name);\n                }\n            }\n\n            if (this._closeButton) {\n                this._closeButton.setAttribute('aria-label', this._map._getUIString('Popup.Close'));\n            }\n\n            if (this._trackPointer) {\n                this._container.classList.add('maplibregl-popup-track-pointer');\n            }\n        }\n\n        if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) {\n            this._container.style.maxWidth = this.options.maxWidth;\n        }\n\n        this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map._camera.transform, this._trackPointer);\n\n        let cursor: Point;\n        if (event && 'point' in event && event.point) {\n            cursor = event.point;\n        }\n        if (this._trackPointer && !cursor) return;\n\n        const pos = this._flatPos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat);\n        if (this._map.terrain) {\n            // flat position is saved because smartWrap needs non-elevated points\n            this._flatPos = this._trackPointer && cursor ? cursor : this._map._camera.transform.locationToScreenPoint(this._lngLat);\n        }\n\n        let anchor = this.options.anchor;\n        const offset = normalizeOffset(this.options.offset);\n\n        if (!anchor) {\n            const width = this._container.offsetWidth;\n            const height = this._container.offsetHeight;\n            const padding = normalizePadding(this.options.padding);\n            let anchorComponents: string[];\n\n            if (pos.y + offset.bottom.y < height + padding.top) {\n                anchorComponents = ['top'];\n            } else if (pos.y > this._map._camera.transform.height - height - padding.bottom) {\n                anchorComponents = ['bottom'];\n            } else {\n                anchorComponents = [];\n            }\n\n            if (pos.x < width / 2 + padding.left) {\n                anchorComponents.push('left');\n            } else if (pos.x > this._map._camera.transform.width - width / 2 - padding.right) {\n                anchorComponents.push('right');\n            }\n\n            if (anchorComponents.length === 0) {\n                anchor = 'bottom';\n            } else {\n                anchor = (anchorComponents.join('-') as any);\n            }\n        }\n\n        let offsetedPos = pos.add(offset[anchor]);\n\n        if (!this.options.subpixelPositioning) {\n            offsetedPos = offsetedPos.round();\n        }\n\n        this._container.style.transform = `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`;\n        applyAnchorClass(this._container, anchor, 'popup');\n\n        this._updateOpacity();\n    };\n\n    _focusFirstElement(): void {\n        if (!this.options.focusAfterOpen || !this._container) return;\n\n        const firstFocusable = this._container.querySelector<HTMLElement>(focusQuerySelector);\n\n        if (firstFocusable) firstFocusable.focus();\n    }\n\n    _onClose = (): void => {\n        this.remove();\n    };\n}\n\nfunction normalizeOffset(offset?: Offset | null) {\n    if (!offset) {\n        return normalizeOffset(new Point(0, 0));\n\n    } else if (typeof offset === 'number') {\n        // input specifies a radius from which to calculate offsets at all positions\n        const cornerOffset = Math.round(Math.abs(offset) / Math.SQRT2);\n        return {\n            'center': new Point(0, 0),\n            'top': new Point(0, offset),\n            'top-left': new Point(cornerOffset, cornerOffset),\n            'top-right': new Point(-cornerOffset, cornerOffset),\n            'bottom': new Point(0, -offset),\n            'bottom-left': new Point(cornerOffset, -cornerOffset),\n            'bottom-right': new Point(-cornerOffset, -cornerOffset),\n            'left': new Point(offset, 0),\n            'right': new Point(-offset, 0)\n        };\n\n    } else if (offset instanceof Point || Array.isArray(offset)) {\n        // input specifies a single offset to be applied to all positions\n        const convertedOffset = Point.convert(offset);\n        return {\n            'center': convertedOffset,\n            'top': convertedOffset,\n            'top-left': convertedOffset,\n            'top-right': convertedOffset,\n            'bottom': convertedOffset,\n            'bottom-left': convertedOffset,\n            'bottom-right': convertedOffset,\n            'left': convertedOffset,\n            'right': convertedOffset\n        };\n\n    } else {\n        // input specifies an offset per position\n        return {\n            'center': Point.convert(offset['center'] || [0, 0]),\n            'top': Point.convert(offset['top'] || [0, 0]),\n            'top-left': Point.convert(offset['top-left'] || [0, 0]),\n            'top-right': Point.convert(offset['top-right'] || [0, 0]),\n            'bottom': Point.convert(offset['bottom'] || [0, 0]),\n            'bottom-left': Point.convert(offset['bottom-left'] || [0, 0]),\n            'bottom-right': Point.convert(offset['bottom-right'] || [0, 0]),\n            'left': Point.convert(offset['left'] || [0, 0]),\n            'right': Point.convert(offset['right'] || [0, 0])\n        };\n    }\n}\n\nfunction normalizePadding(padding?: PaddingOptions | null): {top: number; right: number; bottom: number; left: number} {\n    if (!padding) {\n        return {top: 0, right: 0, bottom: 0, left: 0};\n    }\n\n    return {\n        top: padding.top ?? 0,\n        right: padding.right ?? 0,\n        bottom: padding.bottom ?? 0,\n        left: padding.left ?? 0\n    };\n}\n", "import packageJSON from '../package.json' with {type: 'json'};\nimport {Map, type MapOptions, type MissingStyleImageResolver, type StyleImageSource, type WebGLContextAttributesWithType} from './ui/map.ts';\nimport {NavigationControl, type NavigationControlOptions} from './ui/control/navigation_control.ts';\nimport {GeolocateControl, GeolocateEvent, GeolocatePositionEvent, GeolocateErrorEvent, type GeolocateControlEventType, type GeolocateControlOptions} from './ui/control/geolocate_control.ts';\nimport {AttributionControl, type AttributionControlOptions} from './ui/control/attribution_control.ts';\nimport {LogoControl, type LogoControlOptions} from './ui/control/logo_control.ts';\nimport {ScaleControl, type ScaleControlOptions, type Unit} from './ui/control/scale_control.ts';\nimport {FullscreenControl, FullscreenEvent, type FullscreenControlEventType, type FullscreenControlOptions} from './ui/control/fullscreen_control.ts';\nimport {TerrainControl} from './ui/control/terrain_control.ts';\nimport {GlobeControl} from './ui/control/globe_control.ts';\nimport {type Offset, Popup, PopupEvent, type PopupEventType, type PopupOptions} from './ui/popup.ts';\nimport {type Alignment, Marker, MarkerDragEvent, MarkerClickEvent, type MarkerEventType, type MarkerOptions} from './ui/marker.ts';\nimport {type AddLayerObject, type FeatureIdentifier, Style, type StyleOptions, type StyleSetterOptions, type StyleSwapOptions, type TransformStyleFunction} from './style/style.ts';\nimport {LngLat, type LngLatLike} from './geo/lng_lat.ts';\nimport {LngLatBounds, type LngLatBoundsLike} from './geo/lng_lat_bounds.ts';\nimport Point from '@mapbox/point-geometry';\nimport {MercatorCoordinate} from './geo/mercator_coordinate.ts';\nimport {Evented, ErrorEvent, Event, type ErrorEventType, type EventedParentData, type EventTypeMap, type Listener} from './util/evented.ts';\nimport {type AddProtocolAction, type AddProtocolResponseData, config} from './util/config.ts';\nimport {rtlMainThreadPluginFactory} from './source/rtl_text_plugin_main_thread.ts';\nimport {now, setNow, restoreNow, isTimeFrozen} from './util/time_control.ts';\nimport {WorkerPool} from './util/worker_pool.ts';\nimport {prewarm, clearPrewarmedResources} from './util/global_worker_pool.ts';\nimport {AJAXError, type ExpiryData, type GetResourceResponse, type RequestParameters} from './util/ajax.ts';\nimport {GeoJSONSource, type GetClusterOptions, type SetClusterOptions} from './source/geojson_source.ts';\nimport {CanvasSource, type CanvasSourceSpecification} from './source/canvas_source.ts';\nimport {type CanonicalTileRange, type Coordinates, type ImageSourceImage, ImageSource, type ImageSourceWarp, type UpdateImageOptions} from './source/image_source.ts';\nimport {RasterDEMTileSource} from './source/raster_dem_tile_source.ts';\nimport {RasterTileSource} from './source/raster_tile_source.ts';\nimport {VectorTileSource, type LoadTileResult} from './source/vector_tile_source.ts';\nimport {VideoSource} from './source/video_source.ts';\nimport {type Source, type SourceClass, addSourceType} from './source/source.ts';\nimport {addProtocol, removeProtocol} from './source/protocol_crud.ts';\nimport {addProjection, removeProjection} from './geo/projection/projection_crud.ts';\nimport {type GlobalDispatcher, type GlobalDispatcherEventType, type CustomMessageHandler, getGlobalDispatcher} from './util/global_dispatcher.ts';\nimport {EdgeInsets, type PaddingOptions} from './geo/edge_insets.ts';\nimport {MapTerrainEvent, MapStyleImageMissingEvent, MapStyleDataEvent, MapStyleLoadEvent, MapSourceDataEvent, MapBoxZoomEvent, MapLibreEvent, MapMovementEvent, type MapLayerTouchEvent, type MapLayerMouseEvent, type MapLayerEventType, type MapEventType, MapContextEvent, MapWheelEvent, MapTouchEvent, MapMouseEvent, type MapSourceDataType, type SourceEventType, MapProjectionEvent} from './ui/events.ts';\nimport {BoxZoomHandler, type BoxZoomEndHandler, type BoxZoomHandlerOptions} from './ui/handler/box_zoom.ts';\nimport {DragRotateHandler, type DragRotateOptions} from './ui/handler/shim/drag_rotate.ts';\nimport {DragPanHandler, type DragPanOptions} from './ui/handler/shim/drag_pan.ts';\nimport {ScrollZoomHandler} from './ui/handler/scroll_zoom.ts';\nimport {TwoFingersTouchZoomRotateHandler} from './ui/handler/shim/two_fingers_touch.ts';\nimport {Hash} from './ui/hash.ts';\nimport {CooperativeGesturesHandler, type GestureOptions} from './ui/handler/cooperative_gestures.ts';\nimport {DoubleClickZoomHandler} from './ui/handler/shim/dblclick_zoom.ts';\nimport {KeyboardHandler} from './ui/handler/keyboard.ts';\nimport {TwoFingersTouchPitchHandler, TwoFingersTouchRotateHandler, TwoFingersTouchZoomHandler, type AroundCenterOptions} from './ui/handler/two_fingers_touch.ts';\nimport {createTileMesh, type CreateTileMeshOptions, type IndicesType, type TileMesh} from './util/create_tile_mesh.ts';\nimport {GPUInitializationError} from './util/gpu_initialization_error.ts';\nimport {EXTENT} from './data/extent.ts';\n\nimport type {Dispatcher} from './util/dispatcher.ts';\nimport type {MessageType, ActorMessage, RequestResponseMessageMap} from './util/actor_messages.ts';\nimport type {ControlPosition, IControl} from './ui/control/control.ts';\nimport type {CustomRenderMethod, CustomLayerInterface, CustomRenderMethodInput, CustomLayerProjectionDataParams, CustomTerrainRenderInput, UnwrappedTileIDLiteral} from './style/style_layer/custom_style_layer.ts';\nimport type {AnchoredCameraOptions, AnimationOptions, CameraForBoundsOptions, CameraOptions, CameraUpdateTransformFunction, CenterZoomBearing, EaseToOptions, FitBoundsOptions, FlyToOptions, JumpToOptions, PointLike} from './ui/camera.ts';\nimport type {DistributiveKeys, DistributiveOmit, GeoJSONFeature, MapGeoJSONFeature} from './util/vectortile_to_geojson.ts';\nimport type {Handler, HandlerResult} from './ui/handler_manager.ts';\nimport type {Complete, Mat4f32, Mat4f64, RequireAtLeastOne, Subscription} from './util/util.ts';\nimport type {CalculateTileZoomFunction, CoveringTilesOptions} from './geo/projection/covering_tiles.ts';\nimport type {TransformConstrainFunction} from './geo/transform_interface.ts';\nimport type {StyleImage, StyleImageData, StyleImageInterface, StyleImageMetadata, StyleImageWebGLData, StyleImageWebGLTarget, TextFit} from './style/style_image.ts';\nimport type {StyleLayer, PaintPropertyEntry} from './style/style_layer.ts';\nimport type {Tile} from './tile/tile.ts';\nimport type {GeoJSONFeatureDiff, GeoJSONFeatureId, GeoJSONSourceDiff} from './source/geojson_source_diff.ts';\nimport type {QueryRenderedFeaturesOptions, QuerySourceFeatureOptions} from './source/query_features.ts';\nimport type {RequestTransformFunction, ResourceType} from './util/request_manager.ts';\nimport type {OverscaledTileID} from './tile/tile_id.ts';\nimport type {PositionAnchor} from './ui/anchor.ts';\nimport type {CustomLayerProjectionData, ProjectionData, ProjectionDataParams, ProjectionMatrix, RendererProjectionData} from './geo/projection/projection_data.ts';\nimport type {CRS} from './geo/projection/crs.ts';\nimport type {TileMatrixSet} from './geo/projection/tile_matrix_set.ts';\nimport type {WorkerTileResult} from './source/worker_source.ts';\nimport type {Actor, IActor, MessageHandler} from './util/actor.ts';\nimport type {Bucket} from './data/bucket.ts';\nimport type {CollisionBoxArray} from './data/array_types.g.ts';\nimport type {AlphaImage} from './util/image.ts';\nimport type {GlyphPosition, GlyphPositions} from './render/glyph_atlas.ts';\nimport type {ImageAtlas} from './render/image_atlas.ts';\nimport type {GlyphMap, StyleGlyph} from './style/style_glyph.ts';\nimport type {FeatureIndex} from './data/feature_index.ts';\nimport type {DashEntry} from './render/line_atlas.ts';\nimport type {Painter} from './render/painter.ts';\nimport type {WorkerGlobalScopeInterface} from './util/web_worker.ts';\nimport type {TerrainHeightMapTarget} from './render/terrain.ts';\nconst version = packageJSON.version;\n\nexport type * from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text).\n *\n * @deprecated MapLibre shapes Arabic and reorders bidirectional text itself, so nothing has to be\n * loaded for right-to-left languages to be drawn correctly. A plugin set here still replaces the\n * built-in implementation, but this will be removed in a future release.\n * @param pluginURL - URL pointing to the Mapbox RTL text plugin source.\n * @param lazy - If set to `true`, maplibre will defer loading the plugin until rtl text is encountered,\n * rtl text will then be rendered only after the plugin finishes loading.\n * @example\n * ```ts\n * setRTLTextPlugin('https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.3.0/dist/mapbox-gl-rtl-text.js', false);\n * ```\n * @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/add-support-for-right-to-left-scripts/)\n * @see [Display and style rich text labels](https://maplibre.org/maplibre-gl-js/docs/examples/display-and-style-rich-text-labels/)\n */\nfunction setRTLTextPlugin(pluginURL: string, lazy: boolean): Promise<void> {\n    return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL, lazy);\n}\n/**\n * Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status.\n * The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`.\n * If the status is `loaded` and the plugin is requested again, an error will be thrown.\n *\n * @deprecated The status says nothing about whether right-to-left text can be drawn, which it always\n * can be. It reports only on a plugin set through the deprecated {@link setRTLTextPlugin}.\n * @example\n * ```ts\n * const pluginStatus = getRTLTextPluginStatus();\n * ```\n */\nfunction getRTLTextPluginStatus(): string {\n    return rtlMainThreadPluginFactory().getRTLTextPluginStatus();\n}\n/**\n * Returns the package version of the library\n * @returns Package version of the library\n */\nfunction getVersion(): string { return version; }\n/**\n * Gets the number of web workers instantiated on a page with GL JS maps.\n * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3).\n * Make sure to set this property before creating any map instances for it to have effect.\n *\n * @returns Number of workers currently configured.\n * @example\n * ```ts\n * const workerCount = getWorkerCount()\n * ```\n */\nfunction getWorkerCount(): number { return WorkerPool.workerCount; }\n/**\n * Sets the number of web workers instantiated on a page with GL JS maps.\n * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3).\n * Make sure to set this property before creating any map instances for it to have effect.\n *\n * @example\n * ```ts\n * setWorkerCount(2);\n * ```\n */\nfunction setWorkerCount(count: number): void { WorkerPool.workerCount = count; }\n/**\n * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel,\n * which affects performance in raster-heavy maps. 16 by default.\n *\n * @returns Number of parallel requests currently configured.\n * @example\n * ```ts\n * getMaxParallelImageRequests();\n * ```\n */\nfunction getMaxParallelImageRequests(): number { return config.MAX_PARALLEL_IMAGE_REQUESTS; }\n/**\n * Sets the maximum number of images (raster tiles, sprites, icons) to load in parallel,\n * which affects performance in raster-heavy maps. 16 by default.\n *\n * @example\n * ```ts\n * setMaxParallelImageRequests(10);\n * ```\n */\nfunction setMaxParallelImageRequests(numRequests: number): void { config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests; }\n/**\n * Gets the worker url\n * @returns The worker url\n */\nfunction getWorkerUrl(): string { return config.WORKER_URL; }\n/**\n * Sets the worker url\n */\nfunction setWorkerUrl(value: string): void { config.WORKER_URL = value; }\n/**\n * Allows loading javascript code in the worker thread.\n * *Note* that since this is using some very internal classes and flows it is considered experimental and can break at any point.\n *\n * It can be useful for the following examples:\n * 1. Using `self.addProtocol` in the worker thread - note that you might need to also register the protocol on the main thread.\n * 2. Using `self.registerWorkerSource(workerSource: WorkerSource)` to register a worker source, which should come with `addSourceType` usually.\n * 3. using `self.actor.registerMessageHandler` to override some internal worker operations\n *\n * Each url is imported once, and imported again automatically whenever the pooled workers are\n * recreated.\n * @param workerUrl - the worker url e.g. a url of a javascript file to load in the worker\n * @returns\n *\n * @example\n * ```ts\n * // below is an example of sending a js file to the worker to load the method there\n * // Note that you'll need to call the global function `addProtocol` in the worker to register the protocol there.\n * // add-protocol-worker.js\n * async function loadFn(params, abortController) {\n *     const t = await fetch(`https://${params.url.split(\"://\")[1]}`);\n *     if (t.status == 200) {\n *         const buffer = await t.arrayBuffer();\n *         return {data: buffer}\n *     } else {\n *         throw new Error(`Tile fetch error: ${t.statusText}`);\n *     }\n * }\n * self.addProtocol('custom', loadFn);\n *\n * // main.js\n * importScriptInWorkers('add-protocol-worker.js');\n * ```\n */\nasync function importScriptInWorkers(workerUrl: string): Promise<void> { await getGlobalDispatcher().importScript(workerUrl); }\n\nexport {\n    Map,\n    Map as MapLibreMap,\n    NavigationControl,\n    GeolocateControl,\n    GeolocateEvent,\n    GeolocatePositionEvent,\n    GeolocateErrorEvent,\n    AttributionControl,\n    LogoControl,\n    ScaleControl,\n    FullscreenControl,\n    FullscreenEvent,\n    TerrainControl,\n    GlobeControl,\n    Hash,\n    Popup,\n    PopupEvent,\n    Marker,\n    MarkerDragEvent,\n    MarkerClickEvent,\n    Style,\n    LngLat,\n    LngLatBounds,\n    Point,\n    MercatorCoordinate,\n    Evented,\n    Event,\n    AJAXError,\n    GPUInitializationError,\n    config,\n    CanvasSource,\n    GeoJSONSource,\n    ImageSource,\n    RasterDEMTileSource,\n    RasterTileSource,\n    VectorTileSource,\n    LoadTileResult,\n    VideoSource,\n    EdgeInsets,\n    BoxZoomHandler,\n    DragRotateHandler,\n    DragPanHandler,\n    ScrollZoomHandler,\n    TwoFingersTouchZoomRotateHandler,\n    CooperativeGesturesHandler,\n    DoubleClickZoomHandler,\n    KeyboardHandler,\n    TwoFingersTouchZoomHandler,\n    TwoFingersTouchRotateHandler,\n    TwoFingersTouchPitchHandler,\n    MapWheelEvent,\n    MapTouchEvent,\n    MapMouseEvent,\n    MapProjectionEvent,\n    MapTerrainEvent,\n    MapStyleImageMissingEvent,\n    MapStyleDataEvent,\n    MapStyleLoadEvent,\n    MapSourceDataEvent,\n    MapBoxZoomEvent,\n    MapLibreEvent,\n    MapMovementEvent,\n    MapContextEvent,\n    ErrorEvent,\n    type Handler,\n    type RequireAtLeastOne,\n    type CameraUpdateTransformFunction,\n    type TransformConstrainFunction,\n    type CustomRenderMethod,\n    type CalculateTileZoomFunction,\n    type MapSourceDataType,\n    type TileMesh,\n    type CreateTileMeshOptions,\n    type ControlPosition,\n    type Subscription,\n    type Complete,\n    type CameraOptions,\n    type AnchoredCameraOptions,\n    type CenterZoomBearing,\n    type StyleImage,\n    type StyleImageData,\n    type StyleImageMetadata,\n    type StyleLayer,\n    type PaintPropertyEntry,\n    type GetResourceResponse,\n    type MapGeoJSONFeature,\n    type Alignment,\n    type AddProtocolAction,\n    type AddProtocolResponseData,\n    type SourceClass,\n    type IndicesType,\n    type AttributionControlOptions,\n    type CanonicalTileRange,\n    type Tile,\n    type Listener,\n    type EventTypeMap,\n    type ErrorEventType,\n    type EventedParentData,\n    type Coordinates,\n    type ImageSourceWarp,\n    type ImageSourceImage,\n    type UpdateImageOptions,\n    type DragPanOptions,\n    type DragRotateOptions,\n    type FullscreenControlOptions,\n    type GetClusterOptions,\n    type SetClusterOptions,\n    type GeoJSONSourceDiff,\n    type GeolocateControlOptions,\n    type LogoControlOptions,\n    type StyleImageInterface,\n    type StyleImageWebGLData,\n    type StyleImageWebGLTarget,\n    type AddLayerObject,\n    type StyleSetterOptions,\n    type CameraForBoundsOptions,\n    type EaseToOptions,\n    type FitBoundsOptions,\n    type FlyToOptions,\n    type FeatureIdentifier,\n    type JumpToOptions,\n    type QueryRenderedFeaturesOptions,\n    type QuerySourceFeatureOptions,\n    type AnimationOptions,\n    type StyleSwapOptions,\n    type StyleOptions,\n    type RequestTransformFunction,\n    type MarkerOptions,\n    type NavigationControlOptions,\n    type PopupOptions,\n    type Offset,\n    type OverscaledTileID,\n    type ScaleControlOptions,\n    type Unit,\n    type AroundCenterOptions,\n    type BoxZoomEndHandler,\n    type BoxZoomHandlerOptions,\n    type HandlerResult,\n    type CustomRenderMethodInput,\n    type CustomTerrainRenderInput,\n    type ExpiryData,\n    type PositionAnchor,\n    type ProjectionData,\n    type ProjectionDataParams,\n    type CustomLayerProjectionData,\n    type Mat4f32,\n    type Mat4f64,\n    type ProjectionMatrix,\n    type RendererProjectionData,\n    type CRS,\n    type TileMatrixSet,\n    type GeoJSONFeatureId,\n    type GeoJSONFeatureDiff,\n    type TextFit,\n    type TransformStyleFunction,\n    type DistributiveOmit,\n    type DistributiveKeys,\n    type RequestParameters,\n    type RequestResponseMessageMap,\n    type WorkerTileResult,\n    type ResourceType,\n    type Dispatcher,\n    type GlobalDispatcher,\n    type GlobalDispatcherEventType,\n    type CustomMessageHandler,\n    type Actor,\n    type IActor,\n    type ActorMessage,\n    type MessageHandler,\n    type Bucket,\n    type CollisionBoxArray,\n    type FeatureIndex,\n    type AlphaImage,\n    type GlyphPositions,\n    type GlyphPosition,\n    type GlyphMap,\n    type ImageAtlas,\n    type MessageType,\n    type StyleGlyph,\n    type MapOptions,\n    type MissingStyleImageResolver,\n    type StyleImageSource,\n    type GestureOptions,\n    type WebGLContextAttributesWithType,\n    type IControl,\n    type CustomLayerInterface,\n    type CustomLayerProjectionDataParams,\n    type TerrainHeightMapTarget,\n    type UnwrappedTileIDLiteral,\n    type CanvasSourceSpecification,\n    type PaddingOptions,\n    type LngLatLike,\n    type PointLike,\n    type LngLatBoundsLike,\n    type Source,\n    type MapLayerTouchEvent,\n    type MapLayerMouseEvent,\n    type MapLayerEventType,\n    type MapEventType,\n    type SourceEventType,\n    type GeolocateControlEventType,\n    type FullscreenControlEventType,\n    type PopupEventType,\n    type MarkerEventType,\n    type GeoJSONFeature,\n    type CoveringTilesOptions,\n    type DashEntry,\n    type Painter,\n    type WorkerGlobalScopeInterface,\n    setRTLTextPlugin,\n    getRTLTextPluginStatus,\n    prewarm,\n    clearPrewarmedResources,\n    getVersion,\n    getWorkerCount,\n    setWorkerCount,\n    getMaxParallelImageRequests,\n    setMaxParallelImageRequests,\n    getWorkerUrl,\n    setWorkerUrl,\n    addProtocol,\n    removeProtocol,\n    addProjection,\n    removeProjection,\n    addSourceType,\n    importScriptInWorkers,\n    createTileMesh,\n    now,\n    setNow,\n    restoreNow,\n    isTimeFrozen,\n    getGlobalDispatcher,\n    EXTENT\n};\n", "// MapLibre, told where its worker is. Since v6, MapLibre finds its worker next to its own module\n// (import.meta.url), which esbuild's iife bundles leave empty: the worker is bundled on its own\n// (app/javascript/maplibre-gl-worker.js), and the layout gives its URL, digest included.\nimport * as maplibregl from \"maplibre-gl\";\n\nconst workerUrl = document.querySelector('meta[name=\"maplibre-worker-url\"]')?.content;\nif (workerUrl) maplibregl.setWorkerUrl(workerUrl);\n\nexport default maplibregl;\n", "import \"./quote_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./thumbnails_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./breadcrumbs_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"wicg-inert\";\nimport \"./bulletin_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static targets = [\"text\", \"image\", \"button\"];\n\n  connect() {\n    this.expanded = true;\n    const leeway = 50;\n\n    if (!this.hasImageTarget || this.textHeight <= (this.imageHeight + leeway)) return;\n\n    this.textTarget.inert = true;\n    this.expanded = false;\n    this.textTarget.setAttribute(\"aria-expanded\", \"false\");\n    this.buttonTarget.removeAttribute(\"hidden\");\n  }\n\n  toggle() {\n    this.textTarget.setAttribute(\"aria-expanded\", this.expanded ? \"false\" : \"true\");\n\n    const alternateText = this.buttonTarget.getAttribute(\"data-alternate-text\");\n    const currentText = this.buttonTarget.innerText;\n    this.buttonTarget.innerHTML = alternateText;\n    this.buttonTarget.setAttribute(\"data-alternate-text\", currentText);\n\n    this.textTarget.inert = this.expanded;\n    this.expanded = !this.expanded;\n  }\n\n  get imageHeight() {\n    return this.hasImageTarget ? parseFloat(getComputedStyle(this.imageTarget, null).height.replace(\"px\", \"\")) : 0;\n  }\n\n  get textHeight() {\n    return parseFloat(getComputedStyle(this.textTarget, null).height.replace(\"px\", \"\"));\n  }\n}\n", "var _createClass = 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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * This work is licensed under the W3C Software and Document License\n * (http://www.w3.org/Consortium/Legal/2015/copyright-software-and-document).\n */\n\n(function () {\n  // Return early if we're not running inside of the browser.\n  if (typeof window === 'undefined' || typeof Element === 'undefined') {\n    return;\n  }\n\n  // Convenience function for converting NodeLists.\n  /** @type {typeof Array.prototype.slice} */\n  var slice = Array.prototype.slice;\n\n  /**\n   * IE has a non-standard name for \"matches\".\n   * @type {typeof Element.prototype.matches}\n   */\n  var matches = Element.prototype.matches || Element.prototype.msMatchesSelector;\n\n  /** @type {string} */\n  var _focusableElementsString = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'details', 'summary', 'iframe', 'object', 'embed', 'video', '[contenteditable]'].join(',');\n\n  /**\n   * `InertRoot` manages a single inert subtree, i.e. a DOM subtree whose root element has an `inert`\n   * attribute.\n   *\n   * Its main functions are:\n   *\n   * - to create and maintain a set of managed `InertNode`s, including when mutations occur in the\n   *   subtree. The `makeSubtreeUnfocusable()` method handles collecting `InertNode`s via registering\n   *   each focusable node in the subtree with the singleton `InertManager` which manages all known\n   *   focusable nodes within inert subtrees. `InertManager` ensures that a single `InertNode`\n   *   instance exists for each focusable node which has at least one inert root as an ancestor.\n   *\n   * - to notify all managed `InertNode`s when this subtree stops being inert (i.e. when the `inert`\n   *   attribute is removed from the root node). This is handled in the destructor, which calls the\n   *   `deregister` method on `InertManager` for each managed inert node.\n   */\n\n  var InertRoot = function () {\n    /**\n     * @param {!HTMLElement} rootElement The HTMLElement at the root of the inert subtree.\n     * @param {!InertManager} inertManager The global singleton InertManager object.\n     */\n    function InertRoot(rootElement, inertManager) {\n      _classCallCheck(this, InertRoot);\n\n      /** @type {!InertManager} */\n      this._inertManager = inertManager;\n\n      /** @type {!HTMLElement} */\n      this._rootElement = rootElement;\n\n      /**\n       * @type {!Set<!InertNode>}\n       * All managed focusable nodes in this InertRoot's subtree.\n       */\n      this._managedNodes = new Set();\n\n      // Make the subtree hidden from assistive technology\n      if (this._rootElement.hasAttribute('aria-hidden')) {\n        /** @type {?string} */\n        this._savedAriaHidden = this._rootElement.getAttribute('aria-hidden');\n      } else {\n        this._savedAriaHidden = null;\n      }\n      this._rootElement.setAttribute('aria-hidden', 'true');\n\n      // Make all focusable elements in the subtree unfocusable and add them to _managedNodes\n      this._makeSubtreeUnfocusable(this._rootElement);\n\n      // Watch for:\n      // - any additions in the subtree: make them unfocusable too\n      // - any removals from the subtree: remove them from this inert root's managed nodes\n      // - attribute changes: if `tabindex` is added, or removed from an intrinsically focusable\n      //   element, make that node a managed node.\n      this._observer = new MutationObserver(this._onMutation.bind(this));\n      this._observer.observe(this._rootElement, { attributes: true, childList: true, subtree: true });\n    }\n\n    /**\n     * Call this whenever this object is about to become obsolete.  This unwinds all of the state\n     * stored in this object and updates the state of all of the managed nodes.\n     */\n\n\n    _createClass(InertRoot, [{\n      key: 'destructor',\n      value: function destructor() {\n        this._observer.disconnect();\n\n        if (this._rootElement) {\n          if (this._savedAriaHidden !== null) {\n            this._rootElement.setAttribute('aria-hidden', this._savedAriaHidden);\n          } else {\n            this._rootElement.removeAttribute('aria-hidden');\n          }\n        }\n\n        this._managedNodes.forEach(function (inertNode) {\n          this._unmanageNode(inertNode.node);\n        }, this);\n\n        // Note we cast the nulls to the ANY type here because:\n        // 1) We want the class properties to be declared as non-null, or else we\n        //    need even more casts throughout this code. All bets are off if an\n        //    instance has been destroyed and a method is called.\n        // 2) We don't want to cast \"this\", because we want type-aware optimizations\n        //    to know which properties we're setting.\n        this._observer = /** @type {?} */null;\n        this._rootElement = /** @type {?} */null;\n        this._managedNodes = /** @type {?} */null;\n        this._inertManager = /** @type {?} */null;\n      }\n\n      /**\n       * @return {!Set<!InertNode>} A copy of this InertRoot's managed nodes set.\n       */\n\n    }, {\n      key: '_makeSubtreeUnfocusable',\n\n\n      /**\n       * @param {!Node} startNode\n       */\n      value: function _makeSubtreeUnfocusable(startNode) {\n        var _this2 = this;\n\n        composedTreeWalk(startNode, function (node) {\n          return _this2._visitNode(node);\n        });\n\n        var activeElement = document.activeElement;\n\n        if (!document.body.contains(startNode)) {\n          // startNode may be in shadow DOM, so find its nearest shadowRoot to get the activeElement.\n          var node = startNode;\n          /** @type {!ShadowRoot|undefined} */\n          var root = undefined;\n          while (node) {\n            if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n              root = /** @type {!ShadowRoot} */node;\n              break;\n            }\n            node = node.parentNode;\n          }\n          if (root) {\n            activeElement = root.activeElement;\n          }\n        }\n        if (startNode.contains(activeElement)) {\n          activeElement.blur();\n          // In IE11, if an element is already focused, and then set to tabindex=-1\n          // calling blur() will not actually move the focus.\n          // To work around this we call focus() on the body instead.\n          if (activeElement === document.activeElement) {\n            document.body.focus();\n          }\n        }\n      }\n\n      /**\n       * @param {!Node} node\n       */\n\n    }, {\n      key: '_visitNode',\n      value: function _visitNode(node) {\n        if (node.nodeType !== Node.ELEMENT_NODE) {\n          return;\n        }\n        var element = /** @type {!HTMLElement} */node;\n\n        // If a descendant inert root becomes un-inert, its descendants will still be inert because of\n        // this inert root, so all of its managed nodes need to be adopted by this InertRoot.\n        if (element !== this._rootElement && element.hasAttribute('inert')) {\n          this._adoptInertRoot(element);\n        }\n\n        if (matches.call(element, _focusableElementsString) || element.hasAttribute('tabindex')) {\n          this._manageNode(element);\n        }\n      }\n\n      /**\n       * Register the given node with this InertRoot and with InertManager.\n       * @param {!Node} node\n       */\n\n    }, {\n      key: '_manageNode',\n      value: function _manageNode(node) {\n        var inertNode = this._inertManager.register(node, this);\n        this._managedNodes.add(inertNode);\n      }\n\n      /**\n       * Unregister the given node with this InertRoot and with InertManager.\n       * @param {!Node} node\n       */\n\n    }, {\n      key: '_unmanageNode',\n      value: function _unmanageNode(node) {\n        var inertNode = this._inertManager.deregister(node, this);\n        if (inertNode) {\n          this._managedNodes['delete'](inertNode);\n        }\n      }\n\n      /**\n       * Unregister the entire subtree starting at `startNode`.\n       * @param {!Node} startNode\n       */\n\n    }, {\n      key: '_unmanageSubtree',\n      value: function _unmanageSubtree(startNode) {\n        var _this3 = this;\n\n        composedTreeWalk(startNode, function (node) {\n          return _this3._unmanageNode(node);\n        });\n      }\n\n      /**\n       * If a descendant node is found with an `inert` attribute, adopt its managed nodes.\n       * @param {!HTMLElement} node\n       */\n\n    }, {\n      key: '_adoptInertRoot',\n      value: function _adoptInertRoot(node) {\n        var inertSubroot = this._inertManager.getInertRoot(node);\n\n        // During initialisation this inert root may not have been registered yet,\n        // so register it now if need be.\n        if (!inertSubroot) {\n          this._inertManager.setInert(node, true);\n          inertSubroot = this._inertManager.getInertRoot(node);\n        }\n\n        inertSubroot.managedNodes.forEach(function (savedInertNode) {\n          this._manageNode(savedInertNode.node);\n        }, this);\n      }\n\n      /**\n       * Callback used when mutation observer detects subtree additions, removals, or attribute changes.\n       * @param {!Array<!MutationRecord>} records\n       * @param {!MutationObserver} self\n       */\n\n    }, {\n      key: '_onMutation',\n      value: function _onMutation(records, self) {\n        records.forEach(function (record) {\n          var target = /** @type {!HTMLElement} */record.target;\n          if (record.type === 'childList') {\n            // Manage added nodes\n            slice.call(record.addedNodes).forEach(function (node) {\n              this._makeSubtreeUnfocusable(node);\n            }, this);\n\n            // Un-manage removed nodes\n            slice.call(record.removedNodes).forEach(function (node) {\n              this._unmanageSubtree(node);\n            }, this);\n          } else if (record.type === 'attributes') {\n            if (record.attributeName === 'tabindex') {\n              // Re-initialise inert node if tabindex changes\n              this._manageNode(target);\n            } else if (target !== this._rootElement && record.attributeName === 'inert' && target.hasAttribute('inert')) {\n              // If a new inert root is added, adopt its managed nodes and make sure it knows about the\n              // already managed nodes from this inert subroot.\n              this._adoptInertRoot(target);\n              var inertSubroot = this._inertManager.getInertRoot(target);\n              this._managedNodes.forEach(function (managedNode) {\n                if (target.contains(managedNode.node)) {\n                  inertSubroot._manageNode(managedNode.node);\n                }\n              });\n            }\n          }\n        }, this);\n      }\n    }, {\n      key: 'managedNodes',\n      get: function get() {\n        return new Set(this._managedNodes);\n      }\n\n      /** @return {boolean} */\n\n    }, {\n      key: 'hasSavedAriaHidden',\n      get: function get() {\n        return this._savedAriaHidden !== null;\n      }\n\n      /** @param {?string} ariaHidden */\n\n    }, {\n      key: 'savedAriaHidden',\n      set: function set(ariaHidden) {\n        this._savedAriaHidden = ariaHidden;\n      }\n\n      /** @return {?string} */\n      ,\n      get: function get() {\n        return this._savedAriaHidden;\n      }\n    }]);\n\n    return InertRoot;\n  }();\n\n  /**\n   * `InertNode` initialises and manages a single inert node.\n   * A node is inert if it is a descendant of one or more inert root elements.\n   *\n   * On construction, `InertNode` saves the existing `tabindex` value for the node, if any, and\n   * either removes the `tabindex` attribute or sets it to `-1`, depending on whether the element\n   * is intrinsically focusable or not.\n   *\n   * `InertNode` maintains a set of `InertRoot`s which are descendants of this `InertNode`. When an\n   * `InertRoot` is destroyed, and calls `InertManager.deregister()`, the `InertManager` notifies the\n   * `InertNode` via `removeInertRoot()`, which in turn destroys the `InertNode` if no `InertRoot`s\n   * remain in the set. On destruction, `InertNode` reinstates the stored `tabindex` if one exists,\n   * or removes the `tabindex` attribute if the element is intrinsically focusable.\n   */\n\n\n  var InertNode = function () {\n    /**\n     * @param {!Node} node A focusable element to be made inert.\n     * @param {!InertRoot} inertRoot The inert root element associated with this inert node.\n     */\n    function InertNode(node, inertRoot) {\n      _classCallCheck(this, InertNode);\n\n      /** @type {!Node} */\n      this._node = node;\n\n      /** @type {boolean} */\n      this._overrodeFocusMethod = false;\n\n      /**\n       * @type {!Set<!InertRoot>} The set of descendant inert roots.\n       *    If and only if this set becomes empty, this node is no longer inert.\n       */\n      this._inertRoots = new Set([inertRoot]);\n\n      /** @type {?number} */\n      this._savedTabIndex = null;\n\n      /** @type {boolean} */\n      this._destroyed = false;\n\n      // Save any prior tabindex info and make this node untabbable\n      this.ensureUntabbable();\n    }\n\n    /**\n     * Call this whenever this object is about to become obsolete.\n     * This makes the managed node focusable again and deletes all of the previously stored state.\n     */\n\n\n    _createClass(InertNode, [{\n      key: 'destructor',\n      value: function destructor() {\n        this._throwIfDestroyed();\n\n        if (this._node && this._node.nodeType === Node.ELEMENT_NODE) {\n          var element = /** @type {!HTMLElement} */this._node;\n          if (this._savedTabIndex !== null) {\n            element.setAttribute('tabindex', this._savedTabIndex);\n          } else {\n            element.removeAttribute('tabindex');\n          }\n\n          // Use `delete` to restore native focus method.\n          if (this._overrodeFocusMethod) {\n            delete element.focus;\n          }\n        }\n\n        // See note in InertRoot.destructor for why we cast these nulls to ANY.\n        this._node = /** @type {?} */null;\n        this._inertRoots = /** @type {?} */null;\n        this._destroyed = true;\n      }\n\n      /**\n       * @type {boolean} Whether this object is obsolete because the managed node is no longer inert.\n       * If the object has been destroyed, any attempt to access it will cause an exception.\n       */\n\n    }, {\n      key: '_throwIfDestroyed',\n\n\n      /**\n       * Throw if user tries to access destroyed InertNode.\n       */\n      value: function _throwIfDestroyed() {\n        if (this.destroyed) {\n          throw new Error('Trying to access destroyed InertNode');\n        }\n      }\n\n      /** @return {boolean} */\n\n    }, {\n      key: 'ensureUntabbable',\n\n\n      /** Save the existing tabindex value and make the node untabbable and unfocusable */\n      value: function ensureUntabbable() {\n        if (this.node.nodeType !== Node.ELEMENT_NODE) {\n          return;\n        }\n        var element = /** @type {!HTMLElement} */this.node;\n        if (matches.call(element, _focusableElementsString)) {\n          if ( /** @type {!HTMLElement} */element.tabIndex === -1 && this.hasSavedTabIndex) {\n            return;\n          }\n\n          if (element.hasAttribute('tabindex')) {\n            this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex;\n          }\n          element.setAttribute('tabindex', '-1');\n          if (element.nodeType === Node.ELEMENT_NODE) {\n            element.focus = function () {};\n            this._overrodeFocusMethod = true;\n          }\n        } else if (element.hasAttribute('tabindex')) {\n          this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex;\n          element.removeAttribute('tabindex');\n        }\n      }\n\n      /**\n       * Add another inert root to this inert node's set of managing inert roots.\n       * @param {!InertRoot} inertRoot\n       */\n\n    }, {\n      key: 'addInertRoot',\n      value: function addInertRoot(inertRoot) {\n        this._throwIfDestroyed();\n        this._inertRoots.add(inertRoot);\n      }\n\n      /**\n       * Remove the given inert root from this inert node's set of managing inert roots.\n       * If the set of managing inert roots becomes empty, this node is no longer inert,\n       * so the object should be destroyed.\n       * @param {!InertRoot} inertRoot\n       */\n\n    }, {\n      key: 'removeInertRoot',\n      value: function removeInertRoot(inertRoot) {\n        this._throwIfDestroyed();\n        this._inertRoots['delete'](inertRoot);\n        if (this._inertRoots.size === 0) {\n          this.destructor();\n        }\n      }\n    }, {\n      key: 'destroyed',\n      get: function get() {\n        return (/** @type {!InertNode} */this._destroyed\n        );\n      }\n    }, {\n      key: 'hasSavedTabIndex',\n      get: function get() {\n        return this._savedTabIndex !== null;\n      }\n\n      /** @return {!Node} */\n\n    }, {\n      key: 'node',\n      get: function get() {\n        this._throwIfDestroyed();\n        return this._node;\n      }\n\n      /** @param {?number} tabIndex */\n\n    }, {\n      key: 'savedTabIndex',\n      set: function set(tabIndex) {\n        this._throwIfDestroyed();\n        this._savedTabIndex = tabIndex;\n      }\n\n      /** @return {?number} */\n      ,\n      get: function get() {\n        this._throwIfDestroyed();\n        return this._savedTabIndex;\n      }\n    }]);\n\n    return InertNode;\n  }();\n\n  /**\n   * InertManager is a per-document singleton object which manages all inert roots and nodes.\n   *\n   * When an element becomes an inert root by having an `inert` attribute set and/or its `inert`\n   * property set to `true`, the `setInert` method creates an `InertRoot` object for the element.\n   * The `InertRoot` in turn registers itself as managing all of the element's focusable descendant\n   * nodes via the `register()` method. The `InertManager` ensures that a single `InertNode` instance\n   * is created for each such node, via the `_managedNodes` map.\n   */\n\n\n  var InertManager = function () {\n    /**\n     * @param {!Document} document\n     */\n    function InertManager(document) {\n      _classCallCheck(this, InertManager);\n\n      if (!document) {\n        throw new Error('Missing required argument; InertManager needs to wrap a document.');\n      }\n\n      /** @type {!Document} */\n      this._document = document;\n\n      /**\n       * All managed nodes known to this InertManager. In a map to allow looking up by Node.\n       * @type {!Map<!Node, !InertNode>}\n       */\n      this._managedNodes = new Map();\n\n      /**\n       * All inert roots known to this InertManager. In a map to allow looking up by Node.\n       * @type {!Map<!Node, !InertRoot>}\n       */\n      this._inertRoots = new Map();\n\n      /**\n       * Observer for mutations on `document.body`.\n       * @type {!MutationObserver}\n       */\n      this._observer = new MutationObserver(this._watchForInert.bind(this));\n\n      // Add inert style.\n      addInertStyle(document.head || document.body || document.documentElement);\n\n      // Wait for document to be loaded.\n      if (document.readyState === 'loading') {\n        document.addEventListener('DOMContentLoaded', this._onDocumentLoaded.bind(this));\n      } else {\n        this._onDocumentLoaded();\n      }\n    }\n\n    /**\n     * Set whether the given element should be an inert root or not.\n     * @param {!HTMLElement} root\n     * @param {boolean} inert\n     */\n\n\n    _createClass(InertManager, [{\n      key: 'setInert',\n      value: function setInert(root, inert) {\n        if (inert) {\n          if (this._inertRoots.has(root)) {\n            // element is already inert\n            return;\n          }\n\n          var inertRoot = new InertRoot(root, this);\n          root.setAttribute('inert', '');\n          this._inertRoots.set(root, inertRoot);\n          // If not contained in the document, it must be in a shadowRoot.\n          // Ensure inert styles are added there.\n          if (!this._document.body.contains(root)) {\n            var parent = root.parentNode;\n            while (parent) {\n              if (parent.nodeType === 11) {\n                addInertStyle(parent);\n              }\n              parent = parent.parentNode;\n            }\n          }\n        } else {\n          if (!this._inertRoots.has(root)) {\n            // element is already non-inert\n            return;\n          }\n\n          var _inertRoot = this._inertRoots.get(root);\n          _inertRoot.destructor();\n          this._inertRoots['delete'](root);\n          root.removeAttribute('inert');\n        }\n      }\n\n      /**\n       * Get the InertRoot object corresponding to the given inert root element, if any.\n       * @param {!Node} element\n       * @return {!InertRoot|undefined}\n       */\n\n    }, {\n      key: 'getInertRoot',\n      value: function getInertRoot(element) {\n        return this._inertRoots.get(element);\n      }\n\n      /**\n       * Register the given InertRoot as managing the given node.\n       * In the case where the node has a previously existing inert root, this inert root will\n       * be added to its set of inert roots.\n       * @param {!Node} node\n       * @param {!InertRoot} inertRoot\n       * @return {!InertNode} inertNode\n       */\n\n    }, {\n      key: 'register',\n      value: function register(node, inertRoot) {\n        var inertNode = this._managedNodes.get(node);\n        if (inertNode !== undefined) {\n          // node was already in an inert subtree\n          inertNode.addInertRoot(inertRoot);\n        } else {\n          inertNode = new InertNode(node, inertRoot);\n        }\n\n        this._managedNodes.set(node, inertNode);\n\n        return inertNode;\n      }\n\n      /**\n       * De-register the given InertRoot as managing the given inert node.\n       * Removes the inert root from the InertNode's set of managing inert roots, and remove the inert\n       * node from the InertManager's set of managed nodes if it is destroyed.\n       * If the node is not currently managed, this is essentially a no-op.\n       * @param {!Node} node\n       * @param {!InertRoot} inertRoot\n       * @return {?InertNode} The potentially destroyed InertNode associated with this node, if any.\n       */\n\n    }, {\n      key: 'deregister',\n      value: function deregister(node, inertRoot) {\n        var inertNode = this._managedNodes.get(node);\n        if (!inertNode) {\n          return null;\n        }\n\n        inertNode.removeInertRoot(inertRoot);\n        if (inertNode.destroyed) {\n          this._managedNodes['delete'](node);\n        }\n\n        return inertNode;\n      }\n\n      /**\n       * Callback used when document has finished loading.\n       */\n\n    }, {\n      key: '_onDocumentLoaded',\n      value: function _onDocumentLoaded() {\n        // Find all inert roots in document and make them actually inert.\n        var inertElements = slice.call(this._document.querySelectorAll('[inert]'));\n        inertElements.forEach(function (inertElement) {\n          this.setInert(inertElement, true);\n        }, this);\n\n        // Comment this out to use programmatic API only.\n        this._observer.observe(this._document.body || this._document.documentElement, { attributes: true, subtree: true, childList: true });\n      }\n\n      /**\n       * Callback used when mutation observer detects attribute changes.\n       * @param {!Array<!MutationRecord>} records\n       * @param {!MutationObserver} self\n       */\n\n    }, {\n      key: '_watchForInert',\n      value: function _watchForInert(records, self) {\n        var _this = this;\n        records.forEach(function (record) {\n          switch (record.type) {\n            case 'childList':\n              slice.call(record.addedNodes).forEach(function (node) {\n                if (node.nodeType !== Node.ELEMENT_NODE) {\n                  return;\n                }\n                var inertElements = slice.call(node.querySelectorAll('[inert]'));\n                if (matches.call(node, '[inert]')) {\n                  inertElements.unshift(node);\n                }\n                inertElements.forEach(function (inertElement) {\n                  this.setInert(inertElement, true);\n                }, _this);\n              }, _this);\n              break;\n            case 'attributes':\n              if (record.attributeName !== 'inert') {\n                return;\n              }\n              var target = /** @type {!HTMLElement} */record.target;\n              var inert = target.hasAttribute('inert');\n              _this.setInert(target, inert);\n              break;\n          }\n        }, this);\n      }\n    }]);\n\n    return InertManager;\n  }();\n\n  /**\n   * Recursively walk the composed tree from |node|.\n   * @param {!Node} node\n   * @param {(function (!HTMLElement))=} callback Callback to be called for each element traversed,\n   *     before descending into child nodes.\n   * @param {?ShadowRoot=} shadowRootAncestor The nearest ShadowRoot ancestor, if any.\n   */\n\n\n  function composedTreeWalk(node, callback, shadowRootAncestor) {\n    if (node.nodeType == Node.ELEMENT_NODE) {\n      var element = /** @type {!HTMLElement} */node;\n      if (callback) {\n        callback(element);\n      }\n\n      // Descend into node:\n      // If it has a ShadowRoot, ignore all child elements - these will be picked\n      // up by the <content> or <shadow> elements. Descend straight into the\n      // ShadowRoot.\n      var shadowRoot = /** @type {!HTMLElement} */element.shadowRoot;\n      if (shadowRoot) {\n        composedTreeWalk(shadowRoot, callback, shadowRoot);\n        return;\n      }\n\n      // If it is a <content> element, descend into distributed elements - these\n      // are elements from outside the shadow root which are rendered inside the\n      // shadow DOM.\n      if (element.localName == 'content') {\n        var content = /** @type {!HTMLContentElement} */element;\n        // Verifies if ShadowDom v0 is supported.\n        var distributedNodes = content.getDistributedNodes ? content.getDistributedNodes() : [];\n        for (var i = 0; i < distributedNodes.length; i++) {\n          composedTreeWalk(distributedNodes[i], callback, shadowRootAncestor);\n        }\n        return;\n      }\n\n      // If it is a <slot> element, descend into assigned nodes - these\n      // are elements from outside the shadow root which are rendered inside the\n      // shadow DOM.\n      if (element.localName == 'slot') {\n        var slot = /** @type {!HTMLSlotElement} */element;\n        // Verify if ShadowDom v1 is supported.\n        var _distributedNodes = slot.assignedNodes ? slot.assignedNodes({ flatten: true }) : [];\n        for (var _i = 0; _i < _distributedNodes.length; _i++) {\n          composedTreeWalk(_distributedNodes[_i], callback, shadowRootAncestor);\n        }\n        return;\n      }\n    }\n\n    // If it is neither the parent of a ShadowRoot, a <content> element, a <slot>\n    // element, nor a <shadow> element recurse normally.\n    var child = node.firstChild;\n    while (child != null) {\n      composedTreeWalk(child, callback, shadowRootAncestor);\n      child = child.nextSibling;\n    }\n  }\n\n  /**\n   * Adds a style element to the node containing the inert specific styles\n   * @param {!Node} node\n   */\n  function addInertStyle(node) {\n    if (node.querySelector('style#inert-style, link#inert-style')) {\n      return;\n    }\n    var style = document.createElement('style');\n    style.setAttribute('id', 'inert-style');\n    style.textContent = '\\n' + '[inert] {\\n' + '  pointer-events: none;\\n' + '  cursor: default;\\n' + '}\\n' + '\\n' + '[inert], [inert] * {\\n' + '  -webkit-user-select: none;\\n' + '  -moz-user-select: none;\\n' + '  -ms-user-select: none;\\n' + '  user-select: none;\\n' + '}\\n';\n    node.appendChild(style);\n  }\n\n  if (!HTMLElement.prototype.hasOwnProperty('inert')) {\n    /** @type {!InertManager} */\n    var inertManager = new InertManager(document);\n\n    Object.defineProperty(HTMLElement.prototype, 'inert', {\n      enumerable: true,\n      /** @this {!HTMLElement} */\n      get: function get() {\n        return this.hasAttribute('inert');\n      },\n      /** @this {!HTMLElement} */\n      set: function set(inert) {\n        inertManager.setInert(this, inert);\n      }\n    });\n  }\n})();\n", "import \"./button_component.css\";\n", "import \"./card_component.css\";\n", "import \"./details_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./footer_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./group_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./menu_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  remove() {\n    this.element.remove();\n  }\n}\n", "import \"./header_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static classes = [ \"current\" ];\n  static targets = [ \"titleTrigger\", \"togglableNavItem\" ];\n\n  connect() {\n    this.menuOpen = false;\n  }\n\n  // mobile menu\n  openMobileMenu() {\n    if (this.element.classList.contains(\"c-header-is-mobile-menu-closed\")) {\n      this.element.classList.remove(\"c-header-is-mobile-menu-closed\");\n      document.body.classList.add(\"no-scroll\");\n      this.titleTriggerTarget.innerText = \"Fermer\";\n    } else {\n      this.element.classList.add(\"c-header-is-mobile-menu-closed\");\n      document.body.classList.remove(\"no-scroll\");\n      this.titleTriggerTarget.innerText = \"Menu\";\n      this.removeMenuFrame();\n    }\n  }\n\n  // desktop submenu\n  toggleMenu(e) {\n    const target = e.target.closest(\"[data-header-target='togglableNavItem']\");\n    const src = target.dataset.menuSrc;\n    const current = target.classList.contains(this.currentClass);\n    const open = target.getAttribute(\"aria-expanded\") == \"true\";\n\n    this.disableAllNavItems();\n\n    if (src) {\n      e.preventDefault();\n\n      if (open) {\n        this.menuOpen = false;\n        this.removeMenuFrame();\n      } else {\n        this.menuOpen = true;\n        target.classList.add(this.currentClass);\n        target.setAttribute(\"aria-expanded\", \"true\");\n        this.menuFrame.setAttribute(\"src\", src);\n      }\n    } else {\n      this.menuOpen = false;\n      this.removeMenuFrame();\n      target.classList.add(this.currentClass);\n    }\n  }\n\n  closeMenu(e) {\n    if (!this.menuOpen) { return; }\n    if (e && e.target && e.target.closest(\".c-header-external-wrapper\")) { return; }\n\n    this.disableAllNavItems();\n    this.removeMenuFrame();\n  }\n\n  removeMenuFrame() {\n    while (this.menuFrame.firstChild) {\n      this.menuFrame.removeChild(this.menuFrame.firstChild);\n    }\n    this.menuFrame.removeAttribute(\"src\");\n  }\n\n  disableAllNavItems() {\n    this.currentNavItems.forEach(i => {\n      i.classList.remove(this.currentClass);\n    });\n    this.expandedNavItems.forEach(i => {\n      i.setAttribute(\"aria-expanded\", \"false\");\n    });\n  }\n\n  get menuFrame() {\n    return document.getElementById(\"header--menu\");\n  }\n\n  get currentNavItems() {\n    return this.togglableNavItemTargets.filter(i => i.classList.contains(this.currentClass));\n  }\n\n  get expandedNavItems() {\n    return this.togglableNavItemTargets.filter(i => i.getAttribute(\"aria-expanded\") == \"true\");\n  }\n}\n", "import \"./icon_card_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./icon_component.css\";\n", "import \"./link_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./activities_component.css\";\n", "import \"./bulletins_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./heading_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\nexport class Controller extends BaseController {\n  static targets = [\"time\"];\n\n  connect() {\n    if (this.hasTimeTarget) {\n      this.updateTime();\n      this.timeInterval = setInterval(() => this.updateTime(), 1000);\n    }\n  }\n\n  disconnect() {\n    if (this.timeInterval) {\n      clearInterval(this.timeInterval);\n    }\n  }\n\n  updateTime() {\n    this.timeTarget.innerHTML = this.currentTime;\n  }\n\n  remove() {\n    while (this.turboFrame.firstChild) {\n      this.turboFrame.removeChild(this.turboFrame.firstChild);\n    }\n    this.turboFrame.removeAttribute(\"src\");\n  }\n\n  get currentTime() {\n    const date = new Date();\n    const options = {\n      timeZone: \"Europe/Paris\",\n      hour: \"2-digit\",\n      minute: \"2-digit\",\n    };\n    const time = date.toLocaleTimeString(this.currentLocale, options);\n    return time.replace(\":\", \"<span>:</span>\");\n  }\n\n  get currentLocale() {\n    return document.documentElement.lang;\n  }\n\n  get turboFrame() {\n    return this.element.closest(\"turbo-frame\");\n  }\n}\n", "import \"./panel_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./road_conditions_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./snowfield_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./ticker_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static targets = [\"time\"];\n\n  connect() {\n    this.expanded = this.element.getAttribute(\"aria-expanded\") == \"true\";\n\n    this.connectTime();\n    this.connectScroll();\n  }\n\n  disconnect() {\n    this.disconnectTime();\n    this.disconnectScroll();\n  }\n\n  connectTime() {\n    if (!this.hasTimeTarget) return;\n\n    this.updateTime();\n    this.timeInterval = setInterval(() => this.updateTime(), 1000);\n  }\n\n  connectScroll() {\n    if (!this.expanded) return;\n\n    const viewportHeight = this.viewportHeight;\n    let lastScrollPos = 0;\n    let ticking = false;\n\n    this.scrollListener = (e) => {\n      lastScrollPos = window.scrollY;\n\n      if (!ticking) {\n        this.animationFrame = window.requestAnimationFrame(() => {\n          if (lastScrollPos > viewportHeight && this.expanded) {\n            this.toggle();\n            this.disconnectScroll();\n          }\n          ticking = false;\n        });\n      }\n\n      ticking = true;\n    };\n\n    window.addEventListener('scroll', this.scrollListener);\n  }\n\n  disconnectTime() {\n    if (this.timeInterval) {\n      clearInterval(this.timeInterval);\n      this.timeInterval = null;\n    }\n  }\n\n  disconnectScroll() {\n    if (this.scrollListener) {\n      window.removeEventListener('scroll', this.scrollListener);\n      this.scrollListener = null;\n    }\n\n    if (this.animationFrame) {\n      window.cancelAnimationFrame(this.animationFrame);\n      this.animationFrame = null;\n    }\n  }\n\n  updateTime() {\n    this.timeTarget.innerHTML = this.currentTime;\n  }\n\n  toggle() {\n    this.element.setAttribute(\"aria-expanded\", this.expanded ? \"false\" : \"true\");\n    this.expanded = !this.expanded;\n  }\n\n  remove() {\n    while (this.turboFrame.firstChild) {\n      this.turboFrame.removeChild(this.turboFrame.firstChild);\n    }\n    this.turboFrame.removeAttribute(\"src\");\n  }\n\n  get currentTime() {\n    const date = new Date();\n    const options = {\n      timeZone: \"Europe/Paris\",\n      hour: \"2-digit\",\n      minute: \"2-digit\",\n    };\n    const time = date.toLocaleTimeString(this.currentLocale, options);\n    return time.replace(\":\", \"<span>:</span>\");\n  }\n\n  get currentLocale() {\n    return document.documentElement.lang;\n  }\n\n  get turboFrame() {\n    return this.element.closest(\"turbo-frame\");\n  }\n\n  get viewportHeight() {\n    return Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n  }\n}\n", "import \"./weather_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./city_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\nimport maplibregl from \"../../../javascript/lib/maplibre\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\n\nexport class Controller extends BaseController {\n  static targets = [\"map\"];\n  static values = { center: { type: Array, default: [2.8094, 45.5750] } };\n\n  connect() {\n    this.map = new maplibregl.Map({\n      center: this.centerValue,\n      container: this.mapTarget,\n      locale: document.documentElement.lang,\n      style: 'https://api.maptiler.com/maps/da255326-71c7-42aa-ae18-2c472015e169/style.json?key=xJfyVrC29wRP9anAe2jn',\n      zoom: 15,\n    });\n\n    this.addNavControl();\n    this.enableZoomOnClick();\n  }\n\n  disconnect() {\n    this.map.remove();\n  }\n\n  addNavControl() {\n    this.map.addControl(new maplibregl.NavigationControl());\n  }\n\n  enableZoomOnClick() {\n    this.map.scrollZoom.disable();\n\n    this.map.on('click', (_) => {\n      this.map.scrollZoom.enable();\n    });\n  }\n}\n", "import L from \"leaflet\";\nimport RasterCoords from \"leaflet-rastercoords\";\nimport \"./station_component.css\";\nimport \"leaflet/dist/leaflet.css\";\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\n// Tile sets hosted on tiles.lemontdore.fr: the image size in pixels at full\n// resolution, and the URL template of its tiles. A new version of a map gets\n// its own directory, so cached tiles of the old one never mix with it.\nconst TILE_SETS = {\n  pistes: {\n    size: [10595, 7052],\n    url: \"https://{s}.tiles.lemontdore.fr/pistes-2026/{z}/{x}/{y}.webp\",\n  },\n  activities: {\n    size: [4988, 4761],\n    url: \"https://{s}.tiles.lemontdore.fr/activities/{z}/{x}/{y}.png\",\n  },\n};\n\nexport class Controller extends BaseController {\n  static targets = [\"map\"];\n\n  connect() {\n    const img = this.getImageDimensions();\n    const map = this.initializeMap();\n    const rc = new RasterCoords(map, img);\n    this.configureMap(map, rc, img);\n  }\n\n  disconnect() {}\n\n  getImageDimensions() {\n    return this.tileSet.size;\n  }\n\n  initializeMap() {\n    return L.map(this.mapTarget, {\n      attributionControl: false,\n      crs: L.CRS.Simple,\n      zoomControl: false,\n    });\n  }\n\n  configureMap(map, rc, img) {\n    map.setMaxZoom(rc.zoomLevel());\n    map.setMinZoom(2);\n\n    L.control.zoom({ position: \"topright\" }).addTo(map);\n    map.setView(rc.unproject([img[0] / 2, img[1] / 2]), this.defaultZoom);\n\n    L.tileLayer(this.tileSet.url, {\n      noWrap: true,\n      bounds: rc.getMaxBounds(),\n      maxNativeZoom: rc.zoomLevel(),\n    }).addTo(map);\n  }\n\n  get defaultZoom() {\n    const width = document.documentElement.clientWidth;\n    if (width > 2000) {\n      return 4;\n    } else if (width > 1000) {\n      return 3;\n    } else {\n      return 2;\n    }\n  }\n\n  get tilesValue() {\n    return this.element.getAttribute(\"data-tiles\");\n  }\n\n  get tileSet() {\n    return TILE_SETS[this.tilesValue];\n  }\n}\n", "import \"./details_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./contact_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./nav_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import './partners_component.css'\n", "import \"./notice_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./partners_component.css\"\n", "import \"./pill_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./activities_grid_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./agenda_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./carousel_component.css\";\nimport Flickity from \"flickity\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\n\nexport class Controller extends BaseController {\n  static targets = [\"gallery\"];\n\n  connect() {\n    this.flkty = new Flickity(this.galleryTarget, {\n      freeScroll: true,\n      contain: true,\n      groupCells: true,\n      pageDots: false,\n      prevNextButtons: false,\n    });\n  }\n\n  disconnect() {\n    this.flkty.destroy();\n  }\n\n  previous() {\n    this.flkty.previous();\n  }\n\n  next() {\n    this.flkty.next();\n  }\n}\n", "import \"./features_grid_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./grid_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./hero_component.css\";\n\nimport { Controller as BaseController } from \"@hotwired/stimulus\";\nimport { decodeBlurHash } from \"fast-blurhash\";\n\nexport class Controller extends BaseController {\n  static values = { blurhash: String };\n\n  connect() {\n    if (this.hasBlurhashValue) {\n      this.renderBlurhash();\n    }\n  }\n\n  renderBlurhash() {\n    const pixels = decodeBlurHash(this.blurhashValue, this.dimensions.width, this.dimensions.height);\n    const canvas = document.createElement('canvas');\n    canvas.setAttribute(\"width\", this.dimensions.width);\n    canvas.setAttribute(\"height\", this.dimensions.height);\n    canvas.classList.add(`c-${this.identifier}-canvas`)\n    const ctx = canvas.getContext('2d');\n    const imageData = ctx.createImageData(this.dimensions.width, this.dimensions.height);\n    imageData.data.set(pixels);\n    ctx.putImageData(imageData, 0, 0);\n    this.element.prepend(canvas);\n  }\n\n  scroll(e) {\n    const target = e.target.closest(\".c-button-root\");\n    const scrollTarget = document.querySelector(target.dataset.scrollTarget);\n    scrollTarget.scrollIntoView({\n      behavior: \"smooth\",\n      block: \"start\",\n      inline: \"nearest\"\n    });\n  }\n\n  get dimensions() {\n    return {\n      height: 32,\n      width: 32,\n    }\n  }\n}\n", "import \"./lambda_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./slate_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./slate_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./switcher_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./thumbnail_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "import \"./toc_component.css\";\n\n// Add a Stimulus controller for this component.\n// It will automatically registered and its name will be available\n// via #component_name in the component class.\n//\n// import { Controller as BaseController } from \"@hotwired/stimulus\";\n//\n// export class Controller extends BaseController {\n//   connect() {\n//   }\n//\n//   disconnect() {\n//   }\n// }\n", "\n        import * as module0 from './activities/filters_component/filters_component.js';import * as module1 from './admin/brand_component/brand_component.js';import * as module2 from './admin/button_component/button_component.js';import * as module3 from './admin/button_group_component/button_group_component.js';import * as module4 from './admin/dashboard/section_component/section_component.js';import * as module5 from './admin/dashboard/tile_component/tile_component.js';import * as module6 from './admin/form/actions_component/actions_component.js';import * as module7 from './admin/form/content_editor_component/content_editor_component.js';import * as module8 from './admin/form/fieldset_component/fieldset_component.js';import * as module9 from './admin/form/group_component/group_component.js';import * as module10 from './admin/form/grouped_collection_select_component/grouped_collection_select_component.js';import * as module11 from './admin/form/image_field_component/image_field_component.js';import * as module12 from './admin/form/link_select_component/link_select_component.js';import * as module13 from './admin/form/switch_box_component/switch_box_component.js';import * as module14 from './admin/form/text_field_component/text_field_component.js';import * as module15 from './admin/gate_component/gate_component.js';import * as module16 from './admin/header_component/header_component.js';import * as module17 from './admin/heading_component/heading_component.js';import * as module18 from './admin/layout_component/layout_component.js';import * as module19 from './admin/list/item_component/item_component.js';import * as module20 from './admin/list/tree/item_component/item_component.js';import * as module21 from './admin/list/tree_component/tree_component.js';import * as module22 from './admin/list_component/list_component.js';import * as module23 from './admin/menu_component/menu_component.js';import * as module24 from './admin/sections/activities_grid_component/activities_grid_component.js';import * as module25 from './admin/sections/agenda_component/agenda_component.js';import * as module26 from './admin/sections/features_grid_component/features_grid_component.js';import * as module27 from './admin/sections/hero_component/hero_component.js';import * as module28 from './admin/sections/slate_component/slate_component.js';import * as module29 from './admin/tabs_component/tabs_component.js';import * as module30 from './admin/toaster/toast_component/toast_component.js';import * as module31 from './admin/toaster_component/toaster_component.js';import * as module32 from './article_component/article_component.js';import * as module33 from './blocks/button_component/button_component.js';import * as module34 from './blocks/figure_component/figure_component.js';import * as module35 from './blocks/gallery_component/gallery_component.js';import * as module36 from './blocks/map_component/map_component.js';import * as module37 from './blocks/quote_component/quote_component.js';import * as module38 from './blocks/thumbnails_component/thumbnails_component.js';import * as module39 from './breadcrumbs_component/breadcrumbs_component.js';import * as module40 from './bulletin_component/bulletin_component.js';import * as module41 from './button_component/button_component.js';import * as module42 from './card_component/card_component.js';import * as module43 from './details_component/details_component.js';import * as module44 from './footer_component/footer_component.js';import * as module45 from './form/group_component/group_component.js';import * as module46 from './header/menu_component/menu_component.js';import * as module47 from './header_component/header_component.js';import * as module48 from './icon_card_component/icon_card_component.js';import * as module49 from './icon_component/icon_component.js';import * as module50 from './link_component/link_component.js';import * as module51 from './live/activities_component/activities_component.js';import * as module52 from './live/bulletins_component/bulletins_component.js';import * as module53 from './live/heading_component/heading_component.js';import * as module54 from './live/panel_component/panel_component.js';import * as module55 from './live/road_conditions_component/road_conditions_component.js';import * as module56 from './live/snowfield_component/snowfield_component.js';import * as module57 from './live/ticker_component/ticker_component.js';import * as module58 from './live/weather_component/weather_component.js';import * as module59 from './maps/city_component/city_component.js';import * as module60 from './maps/station_component/station_component.js';import * as module61 from './mda/details_component/details_component.js';import * as module62 from './mda/forms/contact_component/contact_component.js';import * as module63 from './mda/nav_component/nav_component.js';import * as module64 from './mda/partners_component/partners_component.js';import * as module65 from './notice_component/notice_component.js';import * as module66 from './partners_component/partners_component.js';import * as module67 from './pill_component/pill_component.js';import * as module68 from './sections/activities_grid_component/activities_grid_component.js';import * as module69 from './sections/agenda_component/agenda_component.js';import * as module70 from './sections/carousel_component/carousel_component.js';import * as module71 from './sections/features_grid_component/features_grid_component.js';import * as module72 from './sections/grid_component/grid_component.js';import * as module73 from './sections/hero_component/hero_component.js';import * as module74 from './sections/lambda_component/lambda_component.js';import * as module75 from './sections/slate_component/slate_component.js';import * as module76 from './slate_component/slate_component.js';import * as module77 from './switcher_component/switcher_component.js';import * as module78 from './thumbnail_component/thumbnail_component.js';import * as module79 from './toc_component/toc_component.js'\n        const modules = [{name: 'activities--filters-component--filters-component.js', module: module0, filename: 'activities/filters_component/filters_component.js'},{name: 'admin--brand-component--brand-component.js', module: module1, filename: 'admin/brand_component/brand_component.js'},{name: 'admin--button-component--button-component.js', module: module2, filename: 'admin/button_component/button_component.js'},{name: 'admin--button-group-component--button-group-component.js', module: module3, filename: 'admin/button_group_component/button_group_component.js'},{name: 'admin--dashboard--section-component--section-component.js', module: module4, filename: 'admin/dashboard/section_component/section_component.js'},{name: 'admin--dashboard--tile-component--tile-component.js', module: module5, filename: 'admin/dashboard/tile_component/tile_component.js'},{name: 'admin--form--actions-component--actions-component.js', module: module6, filename: 'admin/form/actions_component/actions_component.js'},{name: 'admin--form--content-editor-component--content-editor-component.js', module: module7, filename: 'admin/form/content_editor_component/content_editor_component.js'},{name: 'admin--form--fieldset-component--fieldset-component.js', module: module8, filename: 'admin/form/fieldset_component/fieldset_component.js'},{name: 'admin--form--group-component--group-component.js', module: module9, filename: 'admin/form/group_component/group_component.js'},{name: 'admin--form--grouped-collection-select-component--grouped-collection-select-component.js', module: module10, filename: 'admin/form/grouped_collection_select_component/grouped_collection_select_component.js'},{name: 'admin--form--image-field-component--image-field-component.js', module: module11, filename: 'admin/form/image_field_component/image_field_component.js'},{name: 'admin--form--link-select-component--link-select-component.js', module: module12, filename: 'admin/form/link_select_component/link_select_component.js'},{name: 'admin--form--switch-box-component--switch-box-component.js', module: module13, filename: 'admin/form/switch_box_component/switch_box_component.js'},{name: 'admin--form--text-field-component--text-field-component.js', module: module14, filename: 'admin/form/text_field_component/text_field_component.js'},{name: 'admin--gate-component--gate-component.js', module: module15, filename: 'admin/gate_component/gate_component.js'},{name: 'admin--header-component--header-component.js', module: module16, filename: 'admin/header_component/header_component.js'},{name: 'admin--heading-component--heading-component.js', module: module17, filename: 'admin/heading_component/heading_component.js'},{name: 'admin--layout-component--layout-component.js', module: module18, filename: 'admin/layout_component/layout_component.js'},{name: 'admin--list--item-component--item-component.js', module: module19, filename: 'admin/list/item_component/item_component.js'},{name: 'admin--list--tree--item-component--item-component.js', module: module20, filename: 'admin/list/tree/item_component/item_component.js'},{name: 'admin--list--tree-component--tree-component.js', module: module21, filename: 'admin/list/tree_component/tree_component.js'},{name: 'admin--list-component--list-component.js', module: module22, filename: 'admin/list_component/list_component.js'},{name: 'admin--menu-component--menu-component.js', module: module23, filename: 'admin/menu_component/menu_component.js'},{name: 'admin--sections--activities-grid-component--activities-grid-component.js', module: module24, filename: 'admin/sections/activities_grid_component/activities_grid_component.js'},{name: 'admin--sections--agenda-component--agenda-component.js', module: module25, filename: 'admin/sections/agenda_component/agenda_component.js'},{name: 'admin--sections--features-grid-component--features-grid-component.js', module: module26, filename: 'admin/sections/features_grid_component/features_grid_component.js'},{name: 'admin--sections--hero-component--hero-component.js', module: module27, filename: 'admin/sections/hero_component/hero_component.js'},{name: 'admin--sections--slate-component--slate-component.js', module: module28, filename: 'admin/sections/slate_component/slate_component.js'},{name: 'admin--tabs-component--tabs-component.js', module: module29, filename: 'admin/tabs_component/tabs_component.js'},{name: 'admin--toaster--toast-component--toast-component.js', module: module30, filename: 'admin/toaster/toast_component/toast_component.js'},{name: 'admin--toaster-component--toaster-component.js', module: module31, filename: 'admin/toaster_component/toaster_component.js'},{name: 'article-component--article-component.js', module: module32, filename: 'article_component/article_component.js'},{name: 'blocks--button-component--button-component.js', module: module33, filename: 'blocks/button_component/button_component.js'},{name: 'blocks--figure-component--figure-component.js', module: module34, filename: 'blocks/figure_component/figure_component.js'},{name: 'blocks--gallery-component--gallery-component.js', module: module35, filename: 'blocks/gallery_component/gallery_component.js'},{name: 'blocks--map-component--map-component.js', module: module36, filename: 'blocks/map_component/map_component.js'},{name: 'blocks--quote-component--quote-component.js', module: module37, filename: 'blocks/quote_component/quote_component.js'},{name: 'blocks--thumbnails-component--thumbnails-component.js', module: module38, filename: 'blocks/thumbnails_component/thumbnails_component.js'},{name: 'breadcrumbs-component--breadcrumbs-component.js', module: module39, filename: 'breadcrumbs_component/breadcrumbs_component.js'},{name: 'bulletin-component--bulletin-component.js', module: module40, filename: 'bulletin_component/bulletin_component.js'},{name: 'button-component--button-component.js', module: module41, filename: 'button_component/button_component.js'},{name: 'card-component--card-component.js', module: module42, filename: 'card_component/card_component.js'},{name: 'details-component--details-component.js', module: module43, filename: 'details_component/details_component.js'},{name: 'footer-component--footer-component.js', module: module44, filename: 'footer_component/footer_component.js'},{name: 'form--group-component--group-component.js', module: module45, filename: 'form/group_component/group_component.js'},{name: 'header--menu-component--menu-component.js', module: module46, filename: 'header/menu_component/menu_component.js'},{name: 'header-component--header-component.js', module: module47, filename: 'header_component/header_component.js'},{name: 'icon-card-component--icon-card-component.js', module: module48, filename: 'icon_card_component/icon_card_component.js'},{name: 'icon-component--icon-component.js', module: module49, filename: 'icon_component/icon_component.js'},{name: 'link-component--link-component.js', module: module50, filename: 'link_component/link_component.js'},{name: 'live--activities-component--activities-component.js', module: module51, filename: 'live/activities_component/activities_component.js'},{name: 'live--bulletins-component--bulletins-component.js', module: module52, filename: 'live/bulletins_component/bulletins_component.js'},{name: 'live--heading-component--heading-component.js', module: module53, filename: 'live/heading_component/heading_component.js'},{name: 'live--panel-component--panel-component.js', module: module54, filename: 'live/panel_component/panel_component.js'},{name: 'live--road-conditions-component--road-conditions-component.js', module: module55, filename: 'live/road_conditions_component/road_conditions_component.js'},{name: 'live--snowfield-component--snowfield-component.js', module: module56, filename: 'live/snowfield_component/snowfield_component.js'},{name: 'live--ticker-component--ticker-component.js', module: module57, filename: 'live/ticker_component/ticker_component.js'},{name: 'live--weather-component--weather-component.js', module: module58, filename: 'live/weather_component/weather_component.js'},{name: 'maps--city-component--city-component.js', module: module59, filename: 'maps/city_component/city_component.js'},{name: 'maps--station-component--station-component.js', module: module60, filename: 'maps/station_component/station_component.js'},{name: 'mda--details-component--details-component.js', module: module61, filename: 'mda/details_component/details_component.js'},{name: 'mda--forms--contact-component--contact-component.js', module: module62, filename: 'mda/forms/contact_component/contact_component.js'},{name: 'mda--nav-component--nav-component.js', module: module63, filename: 'mda/nav_component/nav_component.js'},{name: 'mda--partners-component--partners-component.js', module: module64, filename: 'mda/partners_component/partners_component.js'},{name: 'notice-component--notice-component.js', module: module65, filename: 'notice_component/notice_component.js'},{name: 'partners-component--partners-component.js', module: module66, filename: 'partners_component/partners_component.js'},{name: 'pill-component--pill-component.js', module: module67, filename: 'pill_component/pill_component.js'},{name: 'sections--activities-grid-component--activities-grid-component.js', module: module68, filename: 'sections/activities_grid_component/activities_grid_component.js'},{name: 'sections--agenda-component--agenda-component.js', module: module69, filename: 'sections/agenda_component/agenda_component.js'},{name: 'sections--carousel-component--carousel-component.js', module: module70, filename: 'sections/carousel_component/carousel_component.js'},{name: 'sections--features-grid-component--features-grid-component.js', module: module71, filename: 'sections/features_grid_component/features_grid_component.js'},{name: 'sections--grid-component--grid-component.js', module: module72, filename: 'sections/grid_component/grid_component.js'},{name: 'sections--hero-component--hero-component.js', module: module73, filename: 'sections/hero_component/hero_component.js'},{name: 'sections--lambda-component--lambda-component.js', module: module74, filename: 'sections/lambda_component/lambda_component.js'},{name: 'sections--slate-component--slate-component.js', module: module75, filename: 'sections/slate_component/slate_component.js'},{name: 'slate-component--slate-component.js', module: module76, filename: 'slate_component/slate_component.js'},{name: 'switcher-component--switcher-component.js', module: module77, filename: 'switcher_component/switcher_component.js'},{name: 'thumbnail-component--thumbnail-component.js', module: module78, filename: 'thumbnail_component/thumbnail_component.js'},{name: 'toc-component--toc-component.js', module: module79, filename: 'toc_component/toc_component.js'}]\n        export default modules;\n      ", "import { application } from \"../javascript/controllers/application\";\nimport components from './**/*_component.js';\n\ncomponents.forEach((component) => {\n  const path = component.filename;\n\n  // Check whether a module has the Controller export defined\n  if (!component.module.Controller) return;\n\n  // Convert path into a controller identifier:\n  //   example_component/example_component.js -> example\n  //   nav/user_info_component/user_info_component.js -> nav--user-info\n  const identifier = /^(.+)_component\\//.exec(path)[1]\n    .replace(/^\\.\\//, '')\n    .replace(/_/g, '-')\n    .replace(/\\//g, '--');\n\n  application.register(identifier, component.module.Controller)\n})\n"],
  "mappings": "grBAAA,IAAOA,GAAPC,GAAAC,GAAA,KAAOF,GAAQ,CACb,OAAQ,OAAO,QAAY,IAAc,QAAU,OACnD,UAAW,OAAO,UAAc,IAAc,UAAY,MAC5D,ICHA,IAcOG,GAdPC,GAAAC,GAAA,KAAA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CACrBtF,KAAQ,OACRC,OAAU,CACTiG,IAAO,CAAC,EACRC,SAAY,CAAC,CACd,EACAzF,QAAW,MACX0E,WAAc,CACbC,aAAgB,GAChBC,WAAc,CAAC,MAAM,CACtB,EACA,gBAAiB,eAClB,EACA,yBAA0B,CACzBtF,KAAQ,OACRC,OAAU,CACTiG,IAAO,CAAC,EACRC,SAAY,CAAC,CACd,EACAzF,QAAW,WACX0E,WAAc,CACbC,aAAgB,GAChBC,WAAc,CAAC,MAAM,CACtB,EACA,gBAAiB,eAClB,EACA,sBAAuB,CACtBtF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXjC,WAAc,GACdX,MAAS,SACTwE,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,sBAAuB,CACtBtF,KAAQ,QACRU,QAAW,UACXa,WAAc,GACd6D,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,wBAAyB,CACxBtF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXD,QAAW,EACXhC,WAAc,GACd6D,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,CACD,EACA,cAAe,CACd,iBAAkB,CACjBtF,KAAQ,SACRU,QAAW,GACX8C,QAAW,EACXjC,WAAc,GACdX,MAAS,SACTwE,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,iBAAkB,CACjBtF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXjC,WAAc,GACd6D,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,oBAAqB,CACpBtF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXjC,WAAc,GACd6D,WAAc,CACbC,aAAgB,GAChBC,WAAc,CAAC,MAAM,CACtB,EACA,gBAAiB,eAClB,EACA,gBAAiB,CAChBtF,KAAQ,QACRU,QAAW,CACV,cACA,CAAC,QAAQ,EACT,CAAC,iBAAiB,EAClB,EACA,qBACA,GACA,YACA,GACA,OACA,GACA,OACA,GACA,SACA,EACA,KACD,EACAa,WAAc,GACd6D,WAAc,CACbC,aAAgB,GAChBC,WAAc,CAAC,iBAAiB,CACjC,EACA,gBAAiB,YAClB,EACA,kBAAmB,CAClBtF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXD,QAAW,EACXhC,WAAc,GACd6D,WAAc,CACbC,aAAgB,GAChBC,WAAc,CAAC,MAAM,CACtB,EACA,gBAAiB,eAClB,CACD,EACA,aAAc,CACb,eAAgB,CACftF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXD,QAAW,EACXhC,WAAc,GACdqE,SAAY,CAAC,YAAY,EACzBR,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,aAAc,CACbtF,KAAQ,QACRU,QAAW,UACXa,WAAc,GACdqE,SAAY,CAAC,YAAY,EACzBR,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,kBAAmB,CAClBtF,KAAQ,QACRU,QAAW,mBACXa,WAAc,GACdqE,SAAY,CAAC,YAAY,EACzBR,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,kBAAmB,CAClBtF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXjC,WAAc,GACdX,MAAS,SACTgF,SAAY,CAAC,YAAY,EACzBR,WAAc,CACbC,aAAgB,GAChBC,WAAc,CACb,OACA,UACA,eACD,CACD,EACA,gBAAiB,aAClB,EACA,iBAAkB,CACjBtF,KAAQ,SACRU,QAAW,EACX8C,QAAW,EACXjC,WAAc,GACdX,MAAS,SACTgF,SAAY,C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ACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,MAAO,CACN,IACA,IACA,GACD,EACA,MAAO,CACN,IACA,IACA,GACD,EACA,OAAQ,CACP,IACA,IACA,GACD,EACA,MAAO,CACN,EACA,EACA,CACD,EACA,eAAgB,CACf,IACA,IACA,GACD,EACA,KAAM,CACL,EACA,EACA,GACD,EACA,WAAY,CACX,IACA,GACA,GACD,EACA,MAAO,CACN,IACA,GACA,EACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,UAAW,CACV,GACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,CACD,EACA,UAAW,CACV,IACA,IACA,EACD,EACA,MAAO,CACN,IACA,IACA,EACD,EACA,eAAgB,CACf,IACA,IACA,GACD,EACA,SAAU,CACT,IACA,IACA,GACD,EACA,QAAS,CACR,IACA,GACA,EACD,EACA,KAAM,CACL,EACA,IACA,GACD,EACA,SAAU,CACT,EACA,EACA,GACD,EACA,SAAU,CACT,EACA,IACA,GACD,EACA,cAAe,CACd,IACA,IACA,EACD,EACA,SAAU,CACT,IACA,IACA,GACD,EACA,UAAW,CACV,EACA,IACA,CACD,EACA,SAAU,CACT,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,YAAa,CACZ,IACA,EACA,GACD,EACA,eAAgB,CACf,GACA,IACA,EACD,EACA,WAAY,CACX,IACA,IACA,CACD,EACA,WAAY,CACX,IACA,GACA,GACD,EACA,QAAS,CACR,IACA,EACA,CACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,aAAc,CACb,IACA,IACA,GACD,EACA,cAAe,CACd,GACA,GACA,GACD,EACA,cAAe,CACd,GACA,GACA,EACD,EACA,cAAe,CACd,GACA,GACA,EACD,EACA,cAAe,CACd,EACA,IACA,GACD,EACA,WAAY,CACX,IACA,EACA,GACD,EACA,SAAU,CACT,IACA,GACA,GACD,EACA,YAAa,CACZ,EACA,IACA,GACD,EACA,QAAS,CACR,IACA,IACA,GACD,EACA,QAAS,CACR,IACA,IACA,GACD,EACA,WAAY,CACX,GACA,IACA,GACD,EACA,UAAW,CACV,IACA,GACA,EACD,EACA,YAAa,CACZ,IACA,IACA,GACD,EACA,YAAa,CACZ,GACA,IACA,EACD,EACA,QAAS,CACR,IACA,EACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,KAAM,CACL,IACA,IACA,CACD,EACA,UAAW,CACV,IACA,IACA,EACD,EACA,KAAM,CACL,IACA,IACA,GACD,EACA,MAAO,CACN,EACA,IACA,CACD,EACA,YAAa,CACZ,IACA,IACA,EACD,EACA,KAAM,CACL,IACA,IACA,GACD,EACA,SAAU,CACT,IACA,IACA,GACD,EACA,QAAS,CACR,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,GACA,EACD,EACA,OAAQ,CACP,GACA,EACA,GACD,EACA,MAAO,CACN,IACA,IACA,GACD,EACA,MAAO,CACN,IACA,IACA,GACD,EACA,SAAU,CACT,IACA,IACA,GACD,EACA,cAAe,CACd,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,CACD,EACA,aAAc,CACb,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,qBAAsB,CACrB,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,YAAa,CACZ,IACA,IACA,GACD,EACA,cAAe,CACd,GACA,IACA,GACD,EACA,aAAc,CACb,IACA,IACA,GACD,EACA,eAAgB,CACf,IACA,IACA,GACD,EACA,eAAgB,CACf,IACA,IACA,GACD,EACA,eAAgB,CACf,IACA,IACA,GACD,EACA,YAAa,CACZ,IACA,IACA,GACD,EACA,KAAM,CACL,EACA,IACA,CACD,EACA,UAAW,CACV,GACA,IACA,EACD,EACA,MAAO,CACN,IACA,IACA,GACD,EACA,QAAS,CACR,IACA,EACA,GACD,EACA,OAAQ,CACP,IACA,EACA,CACD,EACA,iBAAkB,CACjB,IACA,IACA,GACD,EACA,WAAY,CACX,EACA,EACA,GACD,EACA,aAAc,CACb,IACA,GACA,GACD,EACA,aAAc,CACb,IACA,IACA,GACD,EACA,eAAgB,CACf,GACA,IACA,GACD,EACA,gBAAiB,CAChB,IACA,IACA,GACD,EACA,kBAAmB,CAClB,EACA,IACA,GACD,EACA,gBAAiB,CAChB,GACA,IACA,GACD,EACA,gBAAiB,CAChB,IACA,GACA,GACD,EACA,aAAc,CACb,GACA,GACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,SAAU,CACT,IACA,IACA,GACD,EACA,YAAa,CACZ,IACA,IACA,GACD,EACA,KAAM,CACL,EACA,EACA,GACD,EACA,QAAS,CACR,IACA,IACA,GACD,EACA,MAAO,CACN,IACA,IACA,CACD,EACA,UAAW,CACV,IACA,IACA,EACD,EACA,OAAQ,CACP,IACA,IACA,CACD,EACA,UAAW,CACV,IACA,GACA,CACD,EACA,OAAQ,CACP,IACA,IACA,GACD,EACA,cAAe,CACd,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,cAAe,CACd,IACA,IACA,GACD,EACA,cAAe,CACd,IACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,KAAM,CACL,IACA,IACA,EACD,EACA,KAAM,CACL,IACA,IACA,GACD,EACA,KAAM,CACL,IACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,OAAQ,CACP,IACA,EACA,GACD,EACA,cAAe,CACd,IACA,GACA,GACD,EACA,IAAK,CACJ,IACA,EACA,CACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,UAAW,CACV,GACA,IACA,GACD,EACA,YAAa,CACZ,IACA,GACA,EACD,EACA,OAAQ,CACP,IACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,EACD,EACA,SAAU,CACT,GACA,IACA,EACD,EACA,SAAU,CACT,IACA,IACA,GACD,EACA,OAAQ,CACP,IACA,GACA,EACD,EACA,OAAQ,CACP,IACA,IACA,GACD,EACA,QAAS,CACR,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,GACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,UAAW,CACV,IACA,IACA,GACD,EACA,KAAM,CACL,IACA,IACA,GACD,EACA,YAAa,CACZ,EACA,IACA,GACD,EACA,UAAW,CACV,GACA,IACA,GACD,EACA,IAAK,CACJ,IACA,IACA,GACD,EACA,KAAM,CACL,EACA,IACA,GACD,EACA,QAAS,CACR,IACA,IACA,GACD,EACA,OAAQ,CACP,IACA,GACA,EACD,EACA,UAAW,CACV,GACA,IACA,GACD,EACA,OAAQ,CACP,IACA,IACA,GACD,EACA,MAAO,CACN,IACA,IACA,GACD,EACA,MAAO,CACN,IACA,IACA,GACD,EACA,WAAY,CACX,IACA,IACA,GACD,EACA,OAAQ,CACP,IACA,IACA,CACD,EACA,YAAa,CACZ,IACA,IACA,EACD,CACD,EC72BA,SAASqB,GAAkBt0B,EAAMC,EAAIgB,EAAG,CACvC,OAAOszB,EAAOt0B,GAAKu0B,EAAKD,EACzB,CACA,SAASE,GAAiBz0B,EAAMC,EAAIgB,EAAG,CACtC,OAAOszB,EAAK,IAAA,CAAKv0B,EAAG6B,IACZyyB,GAAkBltB,EAAGotB,EAAG5yB,CAAAA,EAAI3B,CAAC,CACpC,CACF,CCGA,SAASy0B,IAAmC10B,EAAY,CACvD,OAAO20B,IAAe,OAASA,IAAe,OAASA,IAAe,KACvE,CAMA,IAAIC,GAAQ,MAAMA,EAAM,CAUvB,YAAY,EAAG30B,EAAGgB,EAAGY,EAAQ,EAAGD,EAAgB,GAAM,CACrD,KAAK,EAAIC,EACT,KAAK,EAAIyF,EACT,KAAK,EAAI1G,E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ICAvBmE,IAAW,QAASC,GAAc,CAChC,IAAMC,EAAOD,EAAU,SAGvB,GAAI,CAACA,EAAU,OAAO,WAAY,OAKlC,IAAME,EAAa,oBAAoB,KAAKD,CAAI,EAAE,CAAC,EAChD,QAAQ,QAAS,EAAE,EACnB,QAAQ,KAAM,GAAG,EACjB,QAAQ,MAAO,IAAI,EAEtBE,GAAY,SAASD,EAAYF,EAAU,OAAO,UAAU,CAC9D,CAAC",
  "names": ["adapters_default", "init_adapters", "__esmMin", "logger_default", "init_logger", "__esmMin", "init_adapters", "messages", "adapters_default", "now", "secondsSince", "ConnectionMonitor", "connection_monitor_default", "init_connection_monitor", "__esmMin", "init_logger", "time", "connection", "logger_default", "staleThreshold", "reconnectionBackoffRate", "backoff", "jitter", "internal_default", "init_internal", "__esmMin", "message_types", "protocols", "supportedProtocols", "indexOf", "Connection", "connection_default", "init_connection", "__esmMin", "init_adapters", "init_connection_monitor", "init_internal", "init_logger", "internal_default", "consumer", "connection_monitor_default", "data", "logger_default", "socketProtocols", "adapters_default", "allowReconnect", "error", "states", "state", "eventName", "handler", "event", "identifier", "message", "reason", "reconnect", "type", "extend", "Subscription", "init_subscription", "__esmMin", "object", "properties", "key", "value", "consumer", "params", "mixin", "action", "data", "SubscriptionGuarantor", "subscription_guarantor_default", "init_subscription_guarantor", "__esmMin", "init_logger", "subscriptions", "subscription", "logger_default", "s", "Subscriptions", "init_subscriptions", "__esmMin", "init_subscription", "init_subscription_guarantor", "init_logger", "consumer", "subscription_guarantor_default", "channelName", "mixin", "channel", "params", "subscription", "Subscription", "identifier", "s", "callbackName", "args", "subscriptions", "logger_default", "command", "createWebSocketURL", "url", "a", "Consumer", "init_consumer", "__esmMin", "init_connection", "init_subscriptions", "Subscriptions", "connection_default", "data", "subprotocol", "src_exports", "__export", "connection_default", "connection_monitor_default", "Consumer", "internal_default", "Subscription", "subscription_guarantor_default", "Subscriptions", "adapters_default", "createConsumer", "createWebSocketURL", "getConfig", "logger_default", "url", "name", "element", "init_src", "__esmMin", "init_connection", "init_connection_monitor", "init_consumer", "init_internal", "init_subscription", "init_subscriptions", "init_subscription_guarantor", "init_adapters", "init_logger", "require_slugify", "__commonJSMin", "exports", "module", "name", "root", "factory", "charMap", "locales", "replace", "string", "options", "locale", "replacement", "trim", "slug", "result", "ch", "appendChar", "customMap", "require_getTimeStamp", "__commonJSMin", "exports", "module", "pad", "number", "getTimeStamp", "date", "hours", "minutes", "seconds", "require_loggers", "__commonJSMin", "exports", "getTimeStamp", "justErrorsLogger", "_len", "args", "_key", "debugLogger", "_len2", "_key2", "_len3", "_key3", "_len4", "_key4", "require_non_secure", "__commonJSMin", "exports", "module", "urlAlphabet", "customAlphabet", "alphabet", "defaultSize", "size", "id", "i", "nanoid", "require_prettierBytes", "__commonJSMin", "exports", "module", "num", "neg", "units", "exponent", "unit", "require_wildcard", "__commonJSMin", "exports", "module", "WildcardMatcher", "text", "separator", "input", "matches", "parts", "ii", "partsCount", "testParts", "key", "test", "matcher", "require_mime_match", "__commonJSMin", "exports", "module", "wildcard", "reMimePartSplit", "target", "pattern", "test", "result", "require_Restricter", "__commonJSMin", "exports", "prettierBytes", "match", "defaultOptions", "RestrictionError", "errors", "message", "Restricter", "getOpts", "i18n", "opts", "file", "files", "maxFileSize", "minFileSize", "maxTotalFileSize", "maxNumberOfFiles", "allowedFileTypes", "f", "type", "allowedFileTypesString", "total", "minNumberOfFiles", "error", "requiredMetaFields", "own", "missingFields", "field", "require_hasProperty", "__commonJSMin", "exports", "module", "has", "object", "key", "require_Translator", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "has", "insertReplacement", "source", "rx", "replacement", "newParts", "chunk", "raw", "i", "list", "interpolate", "phrase", "options", "dollarRegex", "dollarBillsYall", "interpolated", "arg", "_apply", "Translator", "locales", "_apply2", "n", "key", "string", "plural", "locale", "prevLocale", "require_namespace_emitter", "__commonJSMin", "exports", "module", "emitter", "_fns", "event", "arg1", "arg2", "arg3", "arg4", "arg5", "arg6", "toEmit", "getListeners", "emitAll", "fn", "one", "keep", "fns", "i", "l", "e", "out", "idx", "args", "keys", "key", "require_lodash", "__commonJSMin", "exports", "module", "FUNC_ERROR_TEXT", "NAN", "symbolTag", "reTrim", "reIsBadHex", "reIsBinary", "reIsOctal", "freeParseInt", "freeGlobal", "freeSelf", "root", "objectProto", "objectToString", "nativeMax", "nativeMin", "now", "debounce", "func", "wait", "options", "lastArgs", "lastThis", "maxWait", "result", "timerId", "lastCallTime", "lastInvokeTime", "leading", "maxing", "trailing", "toNumber", "isObject", "invokeFunc", "time", "args", "thisArg", "leadingEdge", "timerExpired", "remainingWait", "timeSinceLastCall", "timeSinceLastInvoke", "shouldInvoke", "trailingEdge", "cancel", "flush", "debounced", "isInvoking", "throttle", "value", "type", "isObjectLike", "isSymbol", "other", "isBinary", "require_lib", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "packageJson", "_publish", "DefaultStore", "_publish2", "patch", "prevState", "nextState", "listener", "_len", "args", "_key", "defaultStore", "require_getFileNameAndExtension", "__commonJSMin", "exports", "module", "getFileNameAndExtension", "fullFileName", "lastDot", "require_mimeTypes", "__commonJSMin", "exports", "module", "require_getFileType", "__commonJSMin", "exports", "module", "getFileNameAndExtension", "mimeTypes", "getFileType", "file", "_getFileNameAndExtens", "fileExtension", "require_generateFileID", "__commonJSMin", "exports", "module", "encodeCharacter", "character", "encodeFilename", "name", "suffix", "generateFileID", "file", "id", "require_supportsUploadProgress", "__commonJSMin", "exports", "module", "supportsUploadProgress", "userAgent", "m", "edgeVersion", "major", "minor", "require_getFileName", "__commonJSMin", "exports", "module", "getFileName", "fileType", "fileDescriptor", "require_locale", "__commonJSMin", "exports", "module", "require_Uppy", "__commonJSMin", "exports", "module", "_nonSecure", "_loggers", "_Restricter", "_Symbol$for", "_Symbol$for2", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "Translator", "ee", "throttle", "DefaultStore", "getFileType", "getFileNameAndExtension", "generateFileID", "supportsUploadProgress", "getFileName", "packageJson", "locale", "_plugins", "_restricter", "_storeUnsubscribe", "_emitter", "_preProcessors", "_uploaders", "_postProcessors", "_informAndEmit", "_checkRequiredMetaFieldsOnFile", "_checkRequiredMetaFields", "_assertNewUploadAllowed", "_checkAndCreateFileStateObject", "_startIfAutoProceed", "_addListeners", "_updateOnlineStatus", "_createUpload", "_getUpload", "_removeUpload", "_runUpload", "Uppy", "_opts", "_runUpload2", "_removeUpload2", "_getUpload2", "_createUpload2", "_addListeners2", "_startIfAutoProceed2", "_checkAndCreateFileStateObject2", "_assertNewUploadAllowed2", "_checkRequiredMetaFields2", "_checkRequiredMetaFieldsOnFile2", "_informAndEmit2", "defaultOptions", "currentFile", "files", "prevState", "nextState", "patch", "event", "_len", "args", "_key", "callback", "state", "plugin", "fileID", "translator", "newOpts", "defaultProgress", "updatedFiles", "updatedFile", "fn", "data", "updatedMeta", "newMeta", "filesObject", "totalProgress", "error", "inProgressFiles", "_ref", "progress", "newFiles", "file", "startedFiles", "uploadStartedFiles", "pausedFiles", "completeFiles", "erroredFiles", "inProgressNotPausedFiles", "processingFiles", "err", "newFile", "fileDescriptors", "errors", "i", "message", "subError", "fileIDs", "reason", "currentUploads", "updatedUploads", "removedFiles", "fileIsNotRemoved", "uploadFileID", "uploadID", "newFileIDs", "capabilities", "stateUpdate", "removedFileIDs", "isPaused", "filesToRetry", "_temp", "canHavePercentage", "inProgress", "sizedFiles", "unsizedFiles", "progressMax", "currentProgress", "acc", "totalSize", "averageSize", "uploadedSize", "Plugin", "opts", "msg", "pluginId", "existsPluginAlready", "plugins", "foundPlugin", "type", "method", "instance", "list", "index", "item", "updatedState", "_temp2", "info", "duration", "isComplexMessage", "logger", "currentUpload", "_classPrivateFieldLoo", "onBeforeUploadResult", "currentlyUploadingFiles", "curr", "waitingFileIDs", "details", "missingFields", "success", "allowNewUpload", "fileDescriptor", "fileType", "fileName", "fileExtension", "isRemote", "meta", "size", "onBeforeFileAddedResult", "filesArray", "errorHandler", "response", "errorMsg", "newError", "uploadResp", "forceAllowNewUpload", "restoreStep", "steps", "step", "updatedUpload", "successful", "failed", "result", "preact_module_exports", "__export", "C", "S", "W", "X", "k", "M", "U", "t", "l", "R", "F", "assign", "obj", "props", "i", "removeNode", "node", "parentNode", "removeChild", "createElement", "type", "children", "key", "ref", "normalizedProps", "arguments", "length", "slice", "call", "defaultProps", "createVNode", "original", "vnode", "__k", "__", "__b", "__e", "__c", "constructor", "__v", "vnodeId", "__i", "__u", "options", "createRef", "current", "Fragment", "BaseComponent", "context", "this", "getDomSibling", "childIndex", "sibling", "renderComponent", "component", "__P", "__d", "oldVNode", "oldDom", "commitQueue", "refQueue", "newVNode", "diff", "__n", "namespaceURI", "commitRoot", "updateParentDomPointers", "base", "some", "child", "enqueueRender", "c", "rerenderQueue", "push", "process", "__r", "prevDebounce", "debounceRendering", "defer", "sort", "depthSort", "shift", "diffChildren", "parentDom", "renderResult", "newParentVNode", "oldParentVNode", "globalContext", "namespace", "excessDomChildren", "isHydrating", "childVNode", "newDom", "firstChildDom", "result", "oldChildren", "EMPTY_ARR", "newChildrenLength", "constructNewChildrenArray", "EMPTY_OBJ", "applyRef", "insert", "nextSibling", "skewedIndex", "matchingIndex", "oldChildrenLength", "remainingOldChildren", "skew", "Array", "String", "isArray", "findMatchingIndex", "unmount", "parentVNode", "insertBefore", "nodeType", "toChildArray", "out", "x", "y", "matched", "setStyle", "style", "value", "setProperty", "IS_NON_DIMENSIONAL", "test", "dom", "name", "oldValue", "useCapture", "lowerCaseName", "o", "cssText", "replace", "CAPTURE_REGEX", "toLowerCase", "EVENT_ATTACHED", "eventClock", "addEventListener", "eventProxyCapture", "eventProxy", "removeEventListener", "e", "removeAttribute", "setAttribute", "createEventProxy", "eventHandler", "EVENT_DISPATCHED", "event", "tmp", "oldCommitQueueLength", "isNew", "oldProps", "oldState", "snapshot", "clearProcessingException", "newProps", "isClassComponent", "provider", "componentContext", "renderHook", "count", "newType", "outer", "prototype", "render", "contextType", "__E", "doRender", "sub", "state", "__h", "_sb", "__s", "getDerivedStateFromProps", "componentWillMount", "componentDidMount", "componentWillReceiveProps", "shouldComponentUpdate", "apply", "componentWillUpdate", "componentDidUpdate", "getChildContext", "getSnapshotBeforeUpdate", "cloneNode", "then", "MODE_HYDRATE", "indexOf", "markAsForce", "diffElementNodes", "diffed", "root", "cb", "map", "newHtml", "oldHtml", "newChildren", "inputValue", "checked", "localName", "document", "createTextNode", "createElementNS", "is", "__m", "data", "defaultValue", "childNodes", "attributes", "__html", "innerHTML", "content", "undefined", "hasRefUnmount", "skipRemove", "r", "componentWillUnmount", "replaceNode", "documentElement", "firstChild", "hydrate", "cloneElement", "createContext", "Context", "subs", "ctx", "Set", "_props", "forEach", "add", "old", "delete", "Provider", "__l", "Consumer", "contextValue", "isValidElement", "_id", "init_preact_module", "__esmMin", "error", "errorInfo", "ctor", "handled", "getDerivedStateFromError", "setState", "componentDidCatch", "update", "callback", "s", "forceUpdate", "Promise", "bind", "resolve", "setTimeout", "a", "b", "Math", "random", "toString", "require_isDOMElement", "__commonJSMin", "exports", "module", "isDOMElement", "obj", "require_findDOMElement", "__commonJSMin", "exports", "module", "isDOMElement", "findDOMElement", "element", "context", "require_getTextDirection", "__commonJSMin", "exports", "module", "getTextDirection", "element", "_element", "require_BasePlugin", "__commonJSMin", "exports", "module", "Translator", "BasePlugin", "uppy", "opts", "plugins", "update", "newOpts", "translator", "require_UIPlugin", "__commonJSMin", "exports", "module", "_preact", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "findDOMElement", "getTextDirection", "BasePlugin", "debounce", "fn", "calling", "latestArgs", "_len", "args", "_key", "_updateUI", "UIPlugin", "_UIPlugin", "target", "plugin", "callerPluginName", "targetElement", "uppyRootElement", "state", "targetPlugin", "Target", "p", "message", "_classPrivateFieldLoo", "_classPrivateFieldLoo2", "_this$el", "require_lib", "__commonJSMin", "exports", "module", "_loggers", "_0", "_1", "Uppy", "UIPlugin", "BasePlugin", "require_NetworkError", "__commonJSMin", "exports", "module", "NetworkError", "error", "xhr", "require_fetchWithNetworkError", "__commonJSMin", "exports", "module", "NetworkError", "fetchWithNetworkError", "err", "require_ErrorWithCause", "__commonJSMin", "exports", "module", "hasProperty", "ErrorWithCause", "message", "options", "require_AuthError", "__commonJSMin", "exports", "module", "AuthError", "require_RequestClient", "__commonJSMin", "exports", "module", "_Symbol$for", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "fetchWithNetworkError", "ErrorWithCause", "AuthError", "packageJson", "stripSlash", "url", "handleJSONResponse", "res", "jsonPromise", "errMsg", "errData", "_companionHeaders", "_getPostResponseFunc", "_getUrl", "_errorHandler", "RequestClient", "_RequestClient", "uppy", "opts", "_errorHandler2", "_getUrl2", "skip", "response", "headers", "companion", "host", "path", "headerName", "err", "_ref", "allowedHeaders", "header", "skipPostResponse", "data", "method", "_err", "require_tokenStorage", "__commonJSMin", "exports", "getItem", "removeItem", "setItem", "key", "value", "resolve", "require_Provider", "__commonJSMin", "exports", "module", "tokenStorage", "RequestClient", "getName", "id", "s", "Provider", "uppy", "opts", "_ref", "headers", "token", "authHeaders", "response", "plugin", "authenticated", "queries", "params", "res", "err", "directory", "_ref2", "defaultOpts", "pattern", "require_SearchProvider", "__commonJSMin", "exports", "module", "RequestClient", "getName", "id", "s", "SearchProvider", "uppy", "opts", "text", "queries", "require_Socket", "__commonJSMin", "exports", "module", "_Symbol$for", "_Symbol$for2", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "ee", "_queued", "_emitter", "_isOpen", "_socket", "_handleMessage", "UppySocket", "opts", "e", "message", "err", "first", "_classPrivateFieldLoo", "action", "payload", "handler", "require_lib", "__commonJSMin", "exports", "_0", "_1", "_2", "_3", "require_AuthView", "__commonJSMin", "exports", "module", "_preact", "GoogleIcon", "AuthView", "props", "pluginName", "pluginIcon", "i18nArray", "handleAuth", "isGoogleDrive", "pluginNameComponent", "require_User", "__commonJSMin", "exports", "module", "_preact", "_ref", "i18n", "logout", "username", "require_Breadcrumbs", "__commonJSMin", "exports", "module", "_preact", "Breadcrumb", "props", "getFolder", "title", "isLast", "breadcrumbsIcon", "directories", "directory", "i", "require_Header", "__commonJSMin", "exports", "module", "User", "Breadcrumbs", "props", "components", "require_classnames", "__commonJSMin", "exports", "module", "hasOwn", "classNames", "classes", "i", "arg", "appendClass", "parseValue", "key", "value", "newClass", "require_remoteFileObjToLocal", "__commonJSMin", "exports", "module", "getFileNameAndExtension", "remoteFileObjToLocal", "file", "require_Filter", "__commonJSMin", "exports", "module", "_preact", "Filter", "props", "ev", "i18n", "filterInput", "filterQuery", "e", "require_FooterActions", "__commonJSMin", "exports", "module", "_preact", "_ref", "cancel", "done", "i18n", "selected", "require_ItemIcon", "__commonJSMin", "exports", "module", "_preact", "FileIcon", "FolderIcon", "VideoIcon", "props", "itemIconString", "alt", "require_GridLi", "__commonJSMin", "exports", "module", "_preact", "GridListItem", "props", "className", "isDisabled", "restrictionReason", "isChecked", "title", "itemIconEl", "showTitles", "toggleCheckbox", "recordShiftKeyPress", "id", "children", "require_ListLi", "__commonJSMin", "exports", "module", "_preact", "ListItem", "props", "className", "isDisabled", "restrictionReason", "isCheckboxDisabled", "isChecked", "toggleCheckbox", "recordShiftKeyPress", "type", "id", "itemIconEl", "title", "handleFolderClick", "showTitles", "i18n", "require_Item", "__commonJSMin", "exports", "module", "_preact", "_extends", "target", "i", "source", "key", "classNames", "ItemIcon", "GridListItem", "ListItem", "props", "author", "getItemIcon", "isChecked", "isDisabled", "viewType", "itemIconString", "className", "itemIconEl", "require_Browser", "__commonJSMin", "exports", "module", "_preact", "classNames", "remoteFileObjToLocal", "Filter", "FooterActions", "Item", "VIRTUAL_SHARED_DIR", "Browser", "props", "currentSelection", "folders", "files", "uppyFiles", "viewType", "headerComponent", "showBreadcrumbs", "isChecked", "toggleCheckbox", "recordShiftKeyPress", "handleScroll", "showTitles", "i18n", "validateRestrictions", "showFilter", "filterQuery", "filterInput", "getNextFolder", "cancel", "done", "columns", "selected", "folder", "_isChecked", "event", "file", "validated", "require_Loader", "__commonJSMin", "exports", "module", "_preact", "_ref", "i18n", "require_CloseWrapper", "__commonJSMin", "exports", "module", "_preact", "CloseWrapper", "onUnmount", "children", "require_isPreviewSupported", "__commonJSMin", "exports", "module", "isPreviewSupported", "fileType", "require_SharedHandler", "__commonJSMin", "exports", "module", "remoteFileObjToLocal", "SharedHandler", "plugin", "items", "state", "folder", "file", "folders", "files", "prevIndex", "currentIndex", "currentSelection", "reducedCurrentSelection", "item", "uppy", "validatedRestrictions", "promise", "then", "catch_", "result", "err", "require_View", "__commonJSMin", "exports", "module", "getFileType", "isPreviewSupported", "generateFileID", "SharedHandler", "View", "plugin", "opts", "file", "event", "scrollHeight", "scrollTop", "offsetHeight", "dashboard", "error", "uppy", "message", "tagFile", "fileType", "err", "require_ProviderView", "__commonJSMin", "exports", "module", "_preact", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "AuthView", "Header", "Browser", "LoaderView", "CloseWrapper", "View", "packageJson", "getOrigin", "getRegex", "value", "isOriginAllowed", "origin", "allowedOrigin", "pattern", "_updateFilesAndFolders", "ProviderView", "_ProviderView", "plugin", "opts", "_updateFilesAndFolders2", "defaultOptions", "res", "folders", "files", "updatedDirectories", "state", "index", "dir", "folder", "message", "newState", "folderId", "count", "file", "ids", "e", "selectedFolders", "authState", "clientVersion", "link", "authWindow", "handleToken", "data", "uppy", "event", "path", "response", "error", "item", "moreFiles", "currentSelection", "promises", "viewOptions", "_this", "authenticated", "didFirstRender", "targetViewOptions", "filterInput", "loading", "isChecked", "toggleCheckbox", "recordShiftKeyPress", "filterItems", "hasInput", "headerProps", "browserProps", "require_ProviderView", "__commonJSMin", "exports", "module", "require_InputView", "__commonJSMin", "exports", "module", "_preact", "_ref", "i18n", "search", "input", "validateAndSearch", "handleKeyPress", "ev", "input_", "require_Header", "__commonJSMin", "exports", "module", "_preact", "SUBMIT_KEY", "props", "searchTerm", "i18n", "search", "handleKeyPress", "ev", "require_SearchProviderView", "__commonJSMin", "exports", "module", "_preact", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "SearchInput", "Browser", "LoaderView", "Header", "CloseWrapper", "View", "packageJson", "_updateFilesAndInputMode", "SearchProviderView", "plugin", "opts", "_updateFilesAndInputMode2", "defaultOptions", "query", "searchTerm", "res", "event", "files", "response", "error", "currentSelection", "promises", "file", "state", "viewOptions", "_this", "didFirstRender", "isInputMode", "targetViewOptions", "folders", "filterInput", "loading", "isChecked", "toggleCheckbox", "filterItems", "hasInput", "browserProps", "item", "require_SearchProviderView", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "_0", "_1", "require_lib", "__commonJSMin", "exports", "module", "middleware", "reducer", "_nonSecure", "_Symbol$for", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "packageJson", "STATE_UPDATE", "defaultSelector", "state", "getPatch", "prev", "next", "nextKeys", "patch", "k", "_id", "_selector", "_store", "ReduxStore", "opts", "cb", "prevState", "nextState", "action", "newState", "require_toArray", "__commonJSMin", "exports", "module", "require_FOCUSABLE_ELEMENTS", "__commonJSMin", "exports", "module", "require_getActiveOverlayEl", "__commonJSMin", "exports", "module", "getActiveOverlayEl", "dashboardEl", "activeOverlayType", "overlayEl", "require_trapFocus", "__commonJSMin", "exports", "forInline", "trapFocus", "toArray", "FOCUSABLE_ELEMENTS", "getActiveOverlayEl", "focusOnFirstNode", "event", "nodes", "node", "focusOnLastNode", "isFocusInOverlay", "activeOverlayEl", "activeOverlayType", "dashboardEl", "focusableNodes", "focusedItemIndex", "require_getSpeed", "__commonJSMin", "exports", "module", "getSpeed", "fileProgress", "timeElapsed", "require_getBytesRemaining", "__commonJSMin", "exports", "module", "getBytesRemaining", "fileProgress", "require_StatusBarStates", "__commonJSMin", "exports", "module", "require_secondsToTime", "__commonJSMin", "exports", "module", "secondsToTime", "rawSeconds", "hours", "minutes", "seconds", "require_prettyETA", "__commonJSMin", "exports", "module", "secondsToTime", "prettyETA", "seconds", "time", "hoursStr", "minutesStr", "secondsStr", "require_Components", "__commonJSMin", "exports", "CancelBtn", "DoneBtn", "LoadingSpinner", "PauseResumeButton", "ProgressBarComplete", "ProgressBarError", "ProgressBarProcessing", "ProgressBarUploading", "ProgressDetails", "RetryBtn", "UploadBtn", "_preact", "classNames", "throttle", "prettierBytes", "prettyETA", "statusBarStates", "DOT", "renderDot", "props", "newFiles", "isUploadStarted", "recoveredState", "i18n", "uploadState", "isSomeGhost", "startUpload", "uploadBtnClassNames", "uploadBtnText", "uppy", "isAllPaused", "isAllComplete", "resumableUploads", "title", "togglePauseResume", "doneButtonHandler", "progress", "value", "mode", "message", "roundedValue", "numUploads", "complete", "totalUploadedSize", "totalSize", "totalETA", "ifShowFilesUploadedOfTotal", "FileUploadCount", "UploadNewlyAddedFiles", "ThrottledProgressDetails", "supportsUploadProgress", "totalProgress", "showProgressDetails", "showUploadNewlyAddedFiles", "renderProgressDetails", "error", "displayErrorAlert", "errorMessage", "require_calculateProcessingProgress", "__commonJSMin", "exports", "module", "calculateProcessingProgress", "files", "values", "mode", "message", "progress", "preprocess", "postprocess", "value", "total", "progressValue", "require_StatusBar", "__commonJSMin", "exports", "module", "_preact", "_Components", "classNames", "statusBarStates", "calculateProcessingProgress", "STATE_ERROR", "STATE_WAITING", "STATE_PREPROCESSING", "STATE_UPLOADING", "STATE_POSTPROCESSING", "STATE_COMPLETE", "StatusBar", "props", "newFiles", "allowNewUpload", "isUploadInProgress", "isAllPaused", "resumableUploads", "error", "hideUploadButton", "hidePauseResumeButton", "hideCancelButton", "hideRetryButton", "recoveredState", "uploadState", "totalProgress", "files", "supportsUploadProgress", "hideAfterFinish", "isSomeGhost", "doneButtonHandler", "isUploadStarted", "i18n", "startUpload", "uppy", "isAllComplete", "showProgressDetails", "numUploads", "complete", "totalSize", "totalETA", "totalUploadedSize", "getProgressValue", "progress", "getIsIndeterminate", "mode", "getIsHidden", "progressValue", "isHidden", "width", "showUploadBtn", "showCancelBtn", "showPauseResumeBtn", "showRetryBtn", "showDoneBtn", "progressClassNames", "statusBarClassNames", "require_locale", "__commonJSMin", "exports", "module", "require_StatusBar", "__commonJSMin", "exports", "module", "_core", "getSpeed", "getBytesRemaining", "getTextDirection", "statusBarStates", "StatusBarUI", "packageJson", "locale", "getTotalSpeed", "files", "totalSpeed", "file", "getTotalETA", "totalBytesRemaining", "total", "getUploadingState", "error", "isAllComplete", "recoveredState", "state", "fileIDs", "i", "progress", "StatusBar", "uppy", "opts", "defaultOptions", "capabilities", "allowNewUpload", "totalProgress", "newFiles", "startedFiles", "completeFiles", "inProgressNotPausedFiles", "isUploadStarted", "isAllErrored", "isAllPaused", "isUploadInProgress", "isSomeGhost", "newFilesOrRecovered", "totalETA", "resumableUploads", "supportsUploadProgress", "totalSize", "totalUploadedSize", "element", "target", "require_lib", "__commonJSMin", "exports", "module", "require_FadeIn", "__commonJSMin", "exports", "module", "_preact", "TRANSITION_MS", "FadeIn", "callback", "children", "require_TransitionGroup", "__commonJSMin", "exports", "module", "_preact", "assign", "obj", "props", "getKey", "vnode", "fallback", "_vnode$key", "linkRef", "component", "name", "cache", "c", "getChildMapping", "children", "out", "key", "mergeChildMappings", "prev", "next", "getValueForKey", "nextKeysPending", "pendingKeys", "prevKey", "childMapping", "nextKey", "i", "pendingNextKey", "identity", "TransitionGroup", "context", "initialChildMapping", "nextProps", "nextChildMapping", "prevChildMapping", "prevState", "hasPrev", "hasNext", "keysToEnter", "keysToLeave", "idx", "currentChildMapping", "_ref", "_ref2", "childFactory", "transitionLeave", "transitionName", "transitionAppear", "transitionEnter", "transitionLeaveTimeout", "transitionEnterTimeout", "transitionAppearTimeout", "childrenToRender", "child", "ref", "el", "require_Informer", "__commonJSMin", "exports", "module", "_preact", "_core", "FadeIn", "TransitionGroup", "packageJson", "Informer", "uppy", "opts", "state", "info", "defaultOptions", "target", "require_lib", "__commonJSMin", "exports", "module", "require_mini_umd", "__commonJSMin", "exports", "module", "e", "t", "s", "i", "r", "a", "h", "f", "l", "o", "u", "d", "c", "p", "g", "m", "y", "b", "w", "k", "O", "v", "A", "S", "U", "x", "C", "B", "V", "n", "I", "L", "T", "P", "z", "F", "j", "E", "_", "D", "M", "N", "R", "$", "K", "W", "X", "H", "Y", "G", "te", "J", "q", "Q", "ee", "Z", "se", "ie", "ne", "re", "ae", "he", "fe", "le", "oe", "ue", "de", "ce", "pe", "ge", "me", "ye", "be", "we", "ke", "Oe", "ve", "Se", "Ae", "require_dataURItoBlob", "__commonJSMin", "exports", "module", "DATA_URL_PATTERN", "dataURItoBlob", "dataURI", "opts", "toFile", "_ref", "_opts$mimeType", "dataURIData", "mimeType", "data", "binary", "bytes", "i", "require_isObjectURL", "__commonJSMin", "exports", "module", "isObjectURL", "url", "require_locale", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "module", "_core", "_miniUmd", "dataURItoBlob", "isObjectURL", "isPreviewSupported", "locale", "packageJson", "canvasToBlob", "canvas", "type", "quality", "err", "resolve", "blob", "rotateImage", "image", "translate", "w", "h", "context", "protect", "ratio", "maxSquare", "maxSize", "maxW", "maxH", "ThumbnailGenerator", "uppy", "opts", "file", "index", "fileIDs", "fileID", "emitPreprocessCompleteForAll", "defaultOptions", "targetWidth", "targetHeight", "originalUrl", "onload", "reject", "event", "orientationPromise", "_ref", "orientation", "dimensions", "rotatedImage", "resizedImage", "img", "width", "height", "rotation", "aspect", "steps", "sW", "sH", "x", "preview", "item", "current", "require_findAllDOMElements", "__commonJSMin", "exports", "module", "isDOMElement", "findAllDOMElements", "element", "elements", "require_getFilesAndDirectoriesFromDirectory", "__commonJSMin", "exports", "module", "getFilesAndDirectoriesFromDirectory", "directoryReader", "oldEntries", "logDropError", "_ref", "onSuccess", "entries", "newEntries", "error", "require_webkitGetAsEntryApi", "__commonJSMin", "exports", "module", "getFilesAndDirectoriesFromDirectory", "getAsFileSystemHandleFromEntry", "entry", "logDropError", "resolve", "reject", "directoryReader", "dirEntries", "file", "createPromiseToAddFileOrParseDirectory", "relativePath", "handle", "getFilesFromDataTransfer", "dataTransfer", "entries", "item", "_await$item$getAsFile", "lastResortFile", "err", "require_fallbackApi", "__commonJSMin", "exports", "module", "toArray", "fallbackApi", "dataTransfer", "files", "require_getDroppedFiles", "__commonJSMin", "exports", "module", "webkitGetAsEntryApi", "fallbackApi", "getDroppedFiles", "dataTransfer", "_temp", "logDropError", "accumulator", "file", "require_memoize_one_cjs", "__commonJSMin", "exports", "module", "safeIsNaN", "value", "isEqual", "first", "second", "areInputsEqual", "newInputs", "lastInputs", "memoizeOne", "resultFn", "lastThis", "lastArgs", "lastResult", "calledOnce", "memoized", "newArgs", "_i", "require_lodash", "__commonJSMin", "exports", "module", "FUNC_ERROR_TEXT", "NAN", "symbolTag", "reTrim", "reIsBadHex", "reIsBinary", "reIsOctal", "freeParseInt", "freeGlobal", "freeSelf", "root", "objectProto", "objectToString", "nativeMax", "nativeMin", "now", "debounce", "func", "wait", "options", "lastArgs", "lastThis", "maxWait", "result", "timerId", "lastCallTime", "lastInvokeTime", "leading", "maxing", "trailing", "toNumber", "isObject", "invokeFunc", "time", "args", "thisArg", "leadingEdge", "timerExpired", "remainingWait", "timeSinceLastCall", "timeSinceLastInvoke", "shouldInvoke", "trailingEdge", "cancel", "flush", "debounced", "isInvoking", "value", "type", "isObjectLike", "isSymbol", "other", "isBinary", "require_createSuperFocus", "__commonJSMin", "exports", "module", "debounce", "FOCUSABLE_ELEMENTS", "getActiveOverlayEl", "createSuperFocus", "lastFocusWasOnSuperFocusableEl", "dashboardEl", "activeOverlayType", "overlayEl", "isFocusInOverlay", "superFocusableEl", "firstEl", "require_isDragDropSupported", "__commonJSMin", "exports", "module", "isDragDropSupported", "div", "require_is_shallow_equal", "__commonJSMin", "exports", "module", "a", "b", "i", "require_getFileTypeIcon", "__commonJSMin", "exports", "module", "_preact", "iconImage", "iconAudio", "iconVideo", "iconPDF", "iconArchive", "iconFile", "iconText", "getIconByMime", "fileType", "defaultChoice", "fileTypeGeneral", "fileTypeSpecific", "require_FilePreview", "__commonJSMin", "exports", "module", "_preact", "getFileTypeIcon", "FilePreview", "props", "file", "color", "icon", "require_MetaErrorMessage", "__commonJSMin", "exports", "module", "_preact", "metaFieldIdToName", "metaFieldId", "metaFields", "f", "renderMissingMetaFieldsError", "props", "file", "toggleFileCard", "i18n", "missingRequiredMetaFields", "metaFieldsString", "missingMetaField", "require_FilePreviewAndLink", "__commonJSMin", "exports", "module", "_preact", "FilePreview", "MetaErrorMessage", "getFileTypeIcon", "FilePreviewAndLink", "props", "require_FileProgress", "__commonJSMin", "exports", "module", "_preact", "onPauseResumeCancelRetry", "props", "progressIndicatorTitle", "ProgressIndicatorButton", "ProgressCircleContainer", "_ref", "children", "ProgressCircle", "_ref2", "progress", "circleLength", "FileProgress", "require_truncateString", "__commonJSMin", "exports", "module", "truncateString", "string", "maxLength", "charsToShow", "frontChars", "backChars", "require_FileInfo", "__commonJSMin", "exports", "module", "_preact", "prettierBytes", "truncateString", "MetaErrorMessage", "renderFileName", "props", "author", "name", "getMaxNameLength", "renderAuthor", "providerName", "dot", "renderFileSize", "ReSelectButton", "ErrorButton", "_ref", "file", "onClick", "FileInfo", "require_copyToClipboard", "__commonJSMin", "exports", "module", "copyToClipboard", "textToCopy", "fallbackString", "resolve", "textArea", "magicCopyFailed", "err", "require_Buttons", "__commonJSMin", "exports", "module", "_preact", "copyToClipboard", "EditButton", "_ref", "file", "uploadInProgressOrComplete", "metaFields", "canEditFile", "i18n", "onClick", "RemoveButton", "_ref2", "copyLinkToClipboard", "event", "props", "CopyLinkButton", "Buttons", "uppy", "showLinkToFileUploadResult", "showRemoveButton", "toggleFileCard", "openFileEditor", "editAction", "require_FileItem", "__commonJSMin", "exports", "module", "_preact", "classNames", "shallowEqual", "FilePreviewAndLink", "FileProgress", "FileInfo", "Buttons", "FileItem", "file", "nextProps", "isProcessing", "isUploaded", "uploadInProgressOrComplete", "uploadInProgress", "error", "isGhost", "showRemoveButton", "dashboardItemClass", "require_VirtualList", "__commonJSMin", "exports", "module", "_preact", "_extends", "target", "i", "source", "key", "STYLE_INNER", "STYLE_CONTENT", "VirtualList", "props", "height", "_ref", "data", "rowHeight", "renderRow", "overscanCount", "offset", "start", "visibleRowCount", "end", "selection", "styleInner", "styleContent", "require_FileList", "__commonJSMin", "exports", "module", "_preact", "_extends", "target", "i", "source", "key", "classNames", "FileItem", "VirtualList", "chunks", "list", "size", "chunked", "currentChunk", "item", "props", "noFiles", "dashboardFilesClass", "rowHeight", "fileProps", "sortByGhostComesFirst", "file1", "file2", "files", "rows", "renderRow", "row", "fileID", "require_AddFiles", "__commonJSMin", "exports", "module", "_preact", "_Symbol$for", "AddFiles", "event", "isFolder", "refCallback", "text", "onClickFn", "numberOfAcquirers", "browseFiles", "browseFolders", "lowerFMSelectionType", "camelFMSelectionType", "acquirer", "acquirers", "disableLocalFiles", "acquirersWithoutLastTwo", "lastTwoAcquirers", "i18nArray", "uppyBranding", "linkText", "ref", "require_AddFilesPanel", "__commonJSMin", "exports", "module", "_preact", "classNames", "AddFiles", "AddFilesPanel", "props", "require_ignoreEvent", "__commonJSMin", "exports", "module", "ignoreEvent", "ev", "tagName", "require_PickerPanelContent", "__commonJSMin", "exports", "module", "_preact", "classNames", "ignoreEvent", "PickerPanelContent", "_ref", "activePickerPanel", "className", "hideAllPanels", "i18n", "state", "uppy", "require_EditorPanel", "__commonJSMin", "exports", "module", "_preact", "classNames", "EditorPanel", "props", "file", "target", "require_PickerPanelTopBar", "__commonJSMin", "exports", "module", "_preact", "uploadStates", "getUploadingState", "isAllErrored", "isAllComplete", "isAllPaused", "files", "state", "fileIDs", "i", "progress", "UploadStatus", "_ref", "i18n", "inProgressNotPausedFiles", "newFiles", "processingFiles", "PanelTopBar", "props", "hideCancelButton", "maxNumberOfFiles", "toggleAddFilesPanel", "uppy", "allowNewUpload", "require_FileCard", "__commonJSMin", "exports", "module", "_preact", "_nonSecure", "classNames", "getFileTypeIcon", "ignoreEvent", "FilePreview", "FileCard", "props", "newVal", "name", "_ref", "formState", "e", "fileID", "file", "ev", "metaFields", "fieldCSSClasses", "field", "id", "required", "_file", "_metaFields", "storedMetaData", "showEditButton", "event", "require_Slide", "__commonJSMin", "exports", "module", "_preact", "classNames", "transitionName", "duration", "Slide", "props", "nextProps", "cachedChildren", "child", "patch", "className", "require_Dashboard", "__commonJSMin", "exports", "module", "_preact", "_extends", "target", "i", "source", "key", "classNames", "isDragDropSupported", "FileList", "AddFiles", "AddFilesPanel", "PickerPanelContent", "EditorPanel", "PanelTopBar", "FileCard", "Slide", "WIDTH_XL", "WIDTH_LG", "WIDTH_MD", "HEIGHT_MD", "Dashboard", "props", "noFiles", "isSizeMD", "dashboardClassName", "itemsPerRow", "showFileList", "numberOfFilesForRecovery", "numberOfGhosts", "fileID", "renderRestoredText", "require_locale", "__commonJSMin", "exports", "module", "require_Dashboard", "__commonJSMin", "exports", "module", "_preact", "_core", "_nonSecure", "trapFocus", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "StatusBar", "Informer", "ThumbnailGenerator", "findAllDOMElements", "toArray", "getDroppedFiles", "memoizeOne", "FOCUSABLE_ELEMENTS", "createSuperFocus", "DashboardUI", "packageJson", "locale", "memoize", "TAB_KEY", "ESC_KEY", "createPromise", "o", "resolve", "reject", "defaultPickerIcon", "_openFileEditorWhenFilesAdded", "_attachRenderFunctionToTarget", "_isTargetSupported", "_getAcquirers", "_getProgressIndicators", "_getEditors", "Dashboard", "uppy", "_opts", "_this", "plugin", "newTargets", "target", "callerPluginId", "callerPluginName", "callerPluginType", "state", "update", "targets", "activePickerPanel", "file", "editors", "editor", "promise", "handler", "opts", "manualClose", "isHidden", "isClosing", "_history$state", "isDarkModeOn", "capabilities", "event", "isDarkModeOnNow", "show", "fileID", "files", "descriptors", "err", "entries", "uppyDashboardInnerEl", "width", "height", "pluginState", "isModalAndClosed", "disable", "focusableNodes", "node", "currentTabIndex", "_history$state2", "_event$state", "_this$opts$onDragOver", "_this$opts", "canSomePluginHandleRootDrop", "somePluginCanHandleRootDrop", "doesEventHaveFiles", "types", "type", "hasFiles", "_this$opts$onDragLeav", "_this$opts2", "_this$opts$onDrop", "_this$opts3", "executedDropErrorOnce", "logDropError", "error", "_ref", "failed", "firstFile", "showModalTrigger", "trigger", "isFocusInUppy", "isFocusNowhere", "isInformerHidden", "isModal", "meta", "allowNewUpload", "newFiles", "uploadStartedFiles", "completeFiles", "erroredFiles", "inProgressFiles", "inProgressNotPausedFiles", "processingFiles", "isUploadStarted", "isAllComplete", "isAllErrored", "isAllPaused", "acquirers", "progressindicators", "theme", "inline", "closeAfterFinish", "allowMultipleUploads", "allowMultipleUploadBatches", "pluginID", "isDarkModeOnFromTheStart", "informer", "statusBar", "thumbnail", "defaultOptions", "require_lib", "__commonJSMin", "exports", "module", "require_locale", "__commonJSMin", "exports", "module", "require_DragDrop", "__commonJSMin", "exports", "module", "_core", "_preact", "toArray", "isDragDropSupported", "getDroppedFiles", "packageJson", "locale", "DragDrop", "_DragDrop", "uppy", "opts", "event", "_this$opts$onDrop", "_this$opts", "logDropError", "error", "files", "defaultOpts", "descriptors", "file", "err", "_this$opts$onDragOver", "_this$opts2", "types", "hasFiles", "type", "allowNewUpload", "_this$opts$onDragLeav", "_this$opts3", "restrictions", "ref", "dragDropClass", "dragDropStyle", "target", "require_lib", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "module", "BasePlugin", "getDroppedFiles", "toArray", "packageJson", "isFileTransfer", "event", "_event$dataTransfer$t", "_event$dataTransfer$t2", "type", "DropTarget", "uppy", "opts", "files", "descriptors", "file", "err", "_this$opts$onDrop", "_this$opts", "plugin", "executedDropErrorOnce", "logDropError", "error", "_this$opts$onDragOver", "_this$opts2", "_this$opts$onDragLeav", "_this$opts3", "currentTarget", "target", "node", "defaultOpts", "require_locale", "__commonJSMin", "exports", "module", "require_FileInput", "__commonJSMin", "exports", "module", "_core", "_preact", "toArray", "packageJson", "locale", "FileInput", "uppy", "opts", "defaultOptions", "files", "descriptors", "file", "err", "event", "hiddenInputStyle", "restrictions", "accept", "input", "target", "require_lib", "__commonJSMin", "exports", "module", "require_cropper", "__commonJSMin", "exports", "module", "global", "factory", "_typeof", "obj", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "i", "descriptor", "_createClass", "protoProps", "staticProps", "_defineProperty", "key", "value", "ownKeys", "object", "enumerableOnly", "keys", "symbols", "sym", "_objectSpread2", "source", "_toConsumableArray", "arr", "_arrayWithoutHoles", "_iterableToArray", "_unsupportedIterableToArray", "_nonIterableSpread", "_arrayLikeToArray", "iter", "o", "minLen", "n", "len", "arr2", "IS_BROWSER", "WINDOW", "IS_TOUCH_DEVICE", "HAS_POINTER_EVENT", "NAMESPACE", "ACTION_ALL", "ACTION_CROP", "ACTION_MOVE", "ACTION_ZOOM", "ACTION_EAST", "ACTION_WEST", "ACTION_SOUTH", "ACTION_NORTH", "ACTION_NORTH_EAST", "ACTION_NORTH_WEST", "ACTION_SOUTH_EAST", "ACTION_SOUTH_WEST", "CLASS_CROP", "CLASS_DISABLED", "CLASS_HIDDEN", "CLASS_HIDE", "CLASS_INVISIBLE", "CLASS_MODAL", "CLASS_MOVE", "DATA_ACTION", "DATA_PREVIEW", "DRAG_MODE_CROP", "DRAG_MODE_MOVE", "DRAG_MODE_NONE", "EVENT_CROP", "EVENT_CROP_END", "EVENT_CROP_MOVE", "EVENT_CROP_START", "EVENT_DBLCLICK", "EVENT_TOUCH_START", "EVENT_TOUCH_MOVE", "EVENT_TOUCH_END", "EVENT_POINTER_DOWN", "EVENT_POINTER_MOVE", "EVENT_POINTER_UP", "EVENT_READY", "EVENT_RESIZE", "EVENT_WHEEL", "EVENT_ZOOM", "MIME_TYPE_JPEG", "REGEXP_ACTIONS", "REGEXP_DATA_URL", "REGEXP_DATA_URL_JPEG", "REGEXP_TAG_NAME", "DEFAULTS", "TEMPLATE", "isNaN", "isNumber", "isPositiveNumber", "isUndefined", "isObject", "hasOwnProperty", "isPlainObject", "_constructor", "prototype", "isFunction", "slice", "toArray", "forEach", "data", "callback", "assign", "_len", "args", "_key", "arg", "REGEXP_DECIMALS", "normalizeDecimalNumber", "times", "REGEXP_SUFFIX", "setStyle", "element", "styles", "style", "property", "hasClass", "addClass", "elem", "className", "removeClass", "toggleClass", "added", "REGEXP_CAMEL_CASE", "toParamCase", "getData", "name", "setData", "removeData", "REGEXP_SPACES", "onceSupported", "supported", "once", "listener", "options", "removeListener", "type", "handler", "event", "listeners", "addListener", "_handler", "_element$listeners", "_len2", "_key2", "dispatchEvent", "getOffset", "box", "location", "REGEXP_ORIGINS", "isCrossOriginURL", "url", "parts", "addTimestamp", "timestamp", "getTransforms", "_ref", "rotate", "scaleX", "scaleY", "translateX", "translateY", "values", "transform", "getMaxZoomRatio", "pointers", "pointers2", "ratios", "pointer", "pointerId", "pointer2", "x1", "y1", "x2", "y2", "z1", "z2", "ratio", "a", "b", "getPointer", "_ref2", "endOnly", "pageX", "pageY", "end", "getPointersCenter", "count", "_ref3", "startX", "startY", "getAdjustedSizes", "_ref4", "aspectRatio", "height", "width", "isValidWidth", "isValidHeight", "adjustedWidth", "getRotatedSizes", "_ref5", "degree", "arc", "sinArc", "cosArc", "newWidth", "newHeight", "getSourceCanvas", "image", "_ref6", "_ref7", "_ref8", "imageAspectRatio", "imageNaturalWidth", "imageNaturalHeight", "_ref6$rotate", "_ref6$scaleX", "_ref6$scaleY", "naturalWidth", "naturalHeight", "_ref8$fillColor", "fillColor", "_ref8$imageSmoothingE", "imageSmoothingEnabled", "_ref8$imageSmoothingQ", "imageSmoothingQuality", "_ref8$maxWidth", "maxWidth", "_ref8$maxHeight", "maxHeight", "_ref8$minWidth", "minWidth", "_ref8$minHeight", "minHeight", "canvas", "context", "maxSizes", "minSizes", "destMaxSizes", "destMinSizes", "destWidth", "destHeight", "params", "param", "fromCharCode", "getStringFromCharCode", "dataView", "start", "length", "str", "REGEXP_DATA_URL_HEAD", "dataURLToArrayBuffer", "dataURL", "base64", "binary", "arrayBuffer", "uint8", "arrayBufferToDataURL", "mimeType", "chunks", "chunkSize", "resetAndGetOrientation", "orientation", "littleEndian", "app1Start", "ifdStart", "offset", "exifIDCode", "tiffOffset", "endianness", "firstIFDOffset", "_length", "_offset", "parseOrientation", "render", "container", "cropper", "containerData", "imageData", "viewMode", "rotated", "canvasWidth", "canvasHeight", "canvasData", "sizeLimited", "positionLimited", "cropBoxData", "cropped", "minCanvasWidth", "minCanvasHeight", "_getAdjustedSizes", "newCanvasLeft", "newCanvasTop", "changed", "transformed", "_getRotatedSizes", "autoCropArea", "limited", "minCropBoxWidth", "minCropBoxHeight", "maxCropBoxWidth", "maxCropBoxHeight", "preview", "crossOrigin", "alt", "previews", "el", "img", "cropBoxWidth", "cropBoxHeight", "left", "top", "originalWidth", "originalHeight", "events", "handlers", "_this", "delta", "buttons", "button", "action", "touch", "change", "right", "bottom", "minLeft", "minTop", "renderable", "range", "check", "side", "p", "methods", "hasSameSize", "offsetX", "offsetY", "_this$canvasData", "x", "y", "_originalEvent", "pivot", "center", "_scaleX", "_scaleY", "rounded", "widthChanged", "heightChanged", "_this$getData", "initialX", "initialY", "initialWidth", "initialHeight", "_options$imageSmoothi", "sourceWidth", "sourceHeight", "srcX", "srcY", "srcWidth", "srcHeight", "dstX", "dstY", "dstWidth", "dstHeight", "scale", "mode", "dragBox", "face", "croppable", "movable", "AnotherCropper", "Cropper", "tagName", "xhr", "clone", "_parseOrientation", "crossOriginUrl", "_this2", "isIOSWebKit", "done", "sizingImage", "body", "template", "cropBox", "require_Editor", "__commonJSMin", "exports", "module", "_preact", "Cropper", "Editor", "props", "ev", "rotationAngle", "rotationDelta", "pendingRotationDelta", "pendingRotationAngle", "opts", "storeCropperInstance", "i18n", "currentImage", "actions", "imageURL", "ref", "require_locale", "__commonJSMin", "exports", "module", "require_ImageEditor", "__commonJSMin", "exports", "module", "_core", "_preact", "Editor", "packageJson", "locale", "ImageEditor", "uppy", "opts", "saveBlobCallback", "blob", "currentImage", "updatedFile", "cropper", "file", "defaultCropperOptions", "defaultActions", "defaultOptions", "fileTypeSpecific", "target", "require_lib", "__commonJSMin", "exports", "module", "require_ProgressBar", "__commonJSMin", "exports", "module", "_preact", "_core", "packageJson", "ProgressBar", "uppy", "opts", "defaultOptions", "state", "progress", "isHidden", "target", "require_lib", "__commonJSMin", "exports", "module", "require_getFileTypeExtension", "__commonJSMin", "exports", "module", "mimeToExtensions", "getFileTypeExtension", "mimeType", "require_supportsMediaRecorder", "__commonJSMin", "exports", "module", "supportsMediaRecorder", "_MediaRecorder$protot", "getHookState", "index", "type", "options", "__h", "currentComponent", "currentHook", "hooks", "__H", "__", "length", "push", "useState", "initialState", "useReducer", "invokeOrReturn", "reducer", "init", "hookState", "currentIndex", "_reducer", "__c", "action", "currentValue", "__N", "nextValue", "setState", "__f", "updateHookState", "p", "s", "c", "updatedHook", "shouldUpdate", "props", "some", "hookItem", "prevScu", "result", "call", "this", "shouldComponentUpdate", "prevCWU", "componentWillUpdate", "__e", "tmp", "useEffect", "callback", "args", "state", "__s", "argsChanged", "_pendingArgs", "useLayoutEffect", "useRef", "initialValue", "useMemo", "current", "useImperativeHandle", "ref", "createHandle", "concat", "factory", "useCallback", "useContext", "context", "provider", "sub", "value", "useDebugValue", "formatter", "n", "useErrorBoundary", "cb", "errState", "componentDidCatch", "err", "errorInfo", "undefined", "useId", "root", "__v", "__m", "mask", "flushAfterPaintEffects", "component", "afterPaintEffects", "shift", "__P", "invokeCleanup", "invokeEffect", "e", "afterNextFrame", "raf", "done", "clearTimeout", "timeout", "HAS_RAF", "cancelAnimationFrame", "setTimeout", "requestAnimationFrame", "hook", "comp", "cleanup", "oldArgs", "newArgs", "arg", "f", "previousComponent", "prevRaf", "oldBeforeDiff", "oldBeforeRender", "oldAfterDiff", "oldCommit", "oldBeforeUnmount", "oldRoot", "_options", "__b", "__r", "diffed", "unmount", "vnode", "parentDom", "__k", "commitQueue", "filter", "hasErrored", "require_RecordButton", "__commonJSMin", "exports", "module", "_preact", "RecordButton", "_ref", "recording", "onStartRecording", "onStopRecording", "i18n", "require_formatSeconds", "__commonJSMin", "exports", "module", "formatSeconds", "seconds", "require_RecordingLength", "__commonJSMin", "exports", "module", "_preact", "formatSeconds", "RecordingLength", "_ref", "recordingLengthSeconds", "i18n", "formattedRecordingLengthSeconds", "require_AudioSourceSelect", "__commonJSMin", "exports", "module", "_preact", "_ref", "currentDeviceId", "audioSources", "onChangeSource", "event", "audioSource", "require_audio_oscilloscope", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "isFunction", "v", "result", "_draw", "AudioOscilloscope", "canvas", "options", "canvasOptions", "canvasContextOptions", "streamSource", "analyser", "dataArray", "bufferLength", "ctx", "w", "h", "sliceWidth", "x", "i", "y", "require_SubmitButton", "__commonJSMin", "exports", "module", "_preact", "SubmitButton", "_ref", "onSubmit", "i18n", "require_DiscardButton", "__commonJSMin", "exports", "module", "_preact", "DiscardButton", "_ref", "onDiscard", "i18n", "require_RecordingScreen", "__commonJSMin", "exports", "module", "_preact", "_hooks", "RecordButton", "RecordingLength", "AudioSourceSelect", "AudioOscilloscope", "SubmitButton", "DiscardButton", "RecordingScreen", "props", "stream", "recordedAudio", "onStop", "recording", "supportsRecording", "audioSources", "showAudioSourceDropdown", "onSubmit", "i18n", "onStartRecording", "onStopRecording", "onDiscardRecordedAudio", "recordingLengthSeconds", "canvasEl", "oscilloscope", "source", "hasRecordedAudio", "shouldShowRecordButton", "shouldShowAudioSourceDropdown", "require_PermissionsScreen", "__commonJSMin", "exports", "module", "_preact", "props", "icon", "hasAudio", "i18n", "require_locale", "__commonJSMin", "exports", "module", "require_Audio", "__commonJSMin", "exports", "module", "_preact", "_core", "_extends", "target", "i", "source", "key", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "getFileTypeExtension", "supportsMediaRecorder", "RecordingScreen", "PermissionsScreen", "locale", "packageJson", "_stream", "_audioActive", "_recordingChunks", "_recorder", "_capturedMediaFile", "_mediaDevices", "_supportsUserMedia", "_hasAudioCheck", "_start", "_startRecording", "_stopRecording", "_discardRecordedAudio", "_submit", "_stop", "_getAudio", "_changeSource", "_updateSources", "Audio", "uppy", "opts", "_this", "_getAudio2", "_hasAudioCheck2", "options", "hasAudio", "stream", "currentDeviceId", "tracks", "track", "err", "stoppingBecauseOfMaxSize", "event", "restrictions", "totalSize", "acc", "chunk", "expectedEndChunkSize", "maxSize", "currentRecordingLength", "resolve", "file", "error", "deviceId", "devices", "device", "audioState", "restartStream", "audioSources", "audioSource", "mimeType", "blob", "_blob$type", "fileExtension", "require_lib", "__commonJSMin", "exports", "module", "require_locale", "__commonJSMin", "exports", "module", "require_Box", "__commonJSMin", "exports", "module", "_core", "_companionClient", "_providerViews", "_preact", "locale", "packageJson", "Box", "uppy", "opts", "target", "state", "require_lib", "__commonJSMin", "exports", "module", "require_locale", "__commonJSMin", "exports", "module", "require_Dropbox", "__commonJSMin", "exports", "module", "_core", "_companionClient", "_providerViews", "_preact", "packageJson", "locale", "Dropbox", "uppy", "opts", "target", "state", "require_lib", "__commonJSMin", "exports", "module", "require_locale", "__commonJSMin", "exports", "module", "require_Facebook", "__commonJSMin", "exports", "module", "_core", "_companionClient", "_providerViews", "_preact", "packageJson", "locale", "Facebook", "uppy", "opts", "target", "state", "viewOptions", "require_lib", "__commonJSMin", "exports", "module", "require_DriveProviderViews", "__commonJSMin", "exports", "module", "_providerViews", "DriveProviderViews", "file", "require_locale", "__commonJSMin", "exports", "module", "require_GoogleDrive", "__commonJSMin", "exports", "module", "_core", "_companionClient", "_preact", "packageJson", "DriveProviderViews", "locale", "GoogleDrive", "uppy", "opts", "target", "state", "require_lib", "__commonJSMin", "exports", "module", "require_locale", "__commonJSMin", "exports", "module", "require_Instagram", "__commonJSMin", "exports", "module", "_preact", "_core", "_companionClient", "_providerViews", "packageJson", "locale", "Instagram", "uppy", "opts", "target", "state", "require_lib", "__commonJSMin", "exports", "module", "require_locale", "__commonJSMin", "exports", "module", "require_OneDrive", "__commonJSMin", "exports", "module", "_preact", "_core", "_companionClient", "_providerViews", "packageJson", "locale", "OneDrive", "uppy", "opts", "target", "state", "require_lib", "__commonJSMin", "exports", "module", "require_Unsplash", "__commonJSMin", "exports", "module", "_preact", "_core", "_companionClient", "_providerViews", "packageJson", "Unsplash", "uppy", "opts", "target", "state", "require_lib", "__commonJSMin", "exports", "module", "require_UrlUI", "__commonJSMin", "exports", "module", "_preact", "UrlUI", "props", "ev", "addFile", "i18n", "input", "require_forEachDroppedOrPastedUrl", "__commonJSMin", "exports", "module", "toArray", "forEachDroppedOrPastedUrl", "dataTransfer", "isDropOrPaste", "callback", "items", "urlItems", "item", "urlString", "require_locale", "__commonJSMin", "exports", "module", "require_Url", "__commonJSMin", "exports", "module", "_preact", "_core", "_companionClient", "toArray", "UrlUI", "forEachDroppedOrPastedUrl", "packageJson", "locale", "UrlIcon", "addProtocolToURL", "url", "protocolRegex", "defaultProtocol", "canHandleRootDrop", "e", "item", "checkIfCorrectURL", "protocol", "getFileNameFromUrl", "pathname", "Url", "uppy", "opts", "defaultOptions", "res", "protocollessUrl", "optionalMeta", "meta", "tagFile", "err", "target", "require_lib", "__commonJSMin", "exports", "module", "require_locale", "__commonJSMin", "exports", "module", "require_Zoom", "__commonJSMin", "exports", "module", "_preact", "_core", "_companionClient", "_providerViews", "packageJson", "locale", "Zoom", "uppy", "opts", "target", "state", "require_lib", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "module", "_core", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "Dashboard", "Dropbox", "GoogleDrive", "Instagram", "Facebook", "OneDrive", "Box", "Unsplash", "Url", "Zoom", "packageJson", "availablePlugins", "_installedPlugins", "RemoteSources", "uppy", "opts", "defaultOptions", "newOpts", "pluginId", "optsForRemoteSourcePlugin", "plugin", "p", "pluginNames", "formatter", "require_ScreenRecIcon", "__commonJSMin", "exports", "module", "_preact", "require_RecordButton", "__commonJSMin", "exports", "module", "_preact", "RecordButton", "_ref", "recording", "onStartRecording", "onStopRecording", "i18n", "require_SubmitButton", "__commonJSMin", "exports", "module", "_preact", "SubmitButton", "_ref", "recording", "recordedVideo", "onSubmit", "i18n", "require_StopWatch", "__commonJSMin", "exports", "module", "_preact", "Stopwatch", "props", "state", "s", "recording", "i18n", "elapsedTime", "minAndSec", "require_StreamStatus", "__commonJSMin", "exports", "module", "_preact", "_ref", "streamActive", "i18n", "require_CaptureScreen", "__commonJSMin", "exports", "module", "_preact", "_extends", "target", "i", "source", "key", "RecordButton", "SubmitButton", "StopWatch", "StreamStatus", "RecorderScreen", "onStop", "recording", "videoStream", "recordedVideo", "videoProps", "videoElement", "require_locale", "__commonJSMin", "exports", "module", "require_ScreenCapture", "__commonJSMin", "exports", "module", "_preact", "_core", "_extends", "target", "i", "source", "key", "getFileTypeExtension", "ScreenRecIcon", "CaptureScreen", "packageJson", "locale", "isScreenRecordingSupported", "_navigator$mediaDevic", "getMediaDevices", "ScreenCapture", "uppy", "opts", "defaultOptions", "res", "resolve", "videoStream", "err", "audioStream", "options", "preferredVideoMimeType", "tracks", "event", "recordedVideo", "recording", "file", "error", "track", "mimeType", "fileExtension", "name", "blob", "recorderState", "require_lib", "__commonJSMin", "exports", "module", "require_canvasToBlob", "__commonJSMin", "exports", "module", "canvasToBlob", "canvas", "type", "quality", "resolve", "require_supportsMediaRecorder", "__commonJSMin", "exports", "module", "supportsMediaRecorder", "require_CameraIcon", "__commonJSMin", "exports", "module", "_preact", "require_SnapshotButton", "__commonJSMin", "exports", "module", "_preact", "CameraIcon", "_ref", "onSnapshot", "i18n", "require_RecordButton", "__commonJSMin", "exports", "module", "_preact", "RecordButton", "_ref", "recording", "onStartRecording", "onStopRecording", "i18n", "require_formatSeconds", "__commonJSMin", "exports", "module", "formatSeconds", "seconds", "require_RecordingLength", "__commonJSMin", "exports", "module", "_preact", "formatSeconds", "RecordingLength", "_ref", "recordingLengthSeconds", "i18n", "formattedRecordingLengthSeconds", "require_VideoSourceSelect", "__commonJSMin", "exports", "module", "_preact", "_ref", "currentDeviceId", "videoSources", "onChangeVideoSource", "event", "videoSource", "require_SubmitButton", "__commonJSMin", "exports", "module", "_preact", "SubmitButton", "_ref", "onSubmit", "i18n", "require_DiscardButton", "__commonJSMin", "exports", "module", "_preact", "DiscardButton", "_ref", "onDiscard", "i18n", "require_CameraScreen", "__commonJSMin", "exports", "module", "_preact", "_extends", "target", "i", "source", "key", "SnapshotButton", "RecordButton", "RecordingLength", "VideoSourceSelect", "SubmitButton", "DiscardButton", "isModeAvailable", "modes", "mode", "CameraScreen", "onFocus", "onStop", "src", "recordedVideo", "recording", "supportsRecording", "videoSources", "showVideoSourceDropdown", "showRecordingLength", "onSubmit", "i18n", "mirror", "onSnapshot", "onStartRecording", "onStopRecording", "onDiscardRecordedVideo", "recordingLengthSeconds", "hasRecordedVideo", "shouldShowRecordButton", "shouldShowSnapshotButton", "shouldShowRecordingLength", "shouldShowVideoSourceDropdown", "videoProps", "videoElement", "require_PermissionsScreen", "__commonJSMin", "exports", "module", "_preact", "_ref", "icon", "i18n", "hasCamera", "require_locale", "__commonJSMin", "exports", "module", "require_Webcam", "__commonJSMin", "exports", "module", "_preact", "_core", "_extends", "target", "i", "source", "key", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "getFileTypeExtension", "mimeTypes", "canvasToBlob", "supportsMediaRecorder", "CameraIcon", "CameraScreen", "PermissionsScreen", "packageJson", "locale", "toMimeType", "fileType", "isVideoMimeType", "mimeType", "isImageMimeType", "getMediaDevices", "_enableMirror", "Webcam", "uppy", "opts", "defaultOptions", "newOpts", "devices", "device", "deviceId", "acceptsAudio", "acceptsVideo", "videoConstraints", "options", "constraints", "hasCamera", "stream", "currentDeviceId", "tracks", "track", "err", "restrictions", "preferredVideoMimeTypes", "filterSupportedTypes", "candidateType", "acceptableMimeTypes", "stoppingBecauseOfMaxSize", "event", "totalSize", "acc", "chunk", "expectedEndChunkSize", "maxSize", "currentRecordingLength", "resolve", "file", "error", "audioTracks", "videoTracks", "reject", "count", "countDown", "message", "tagFile", "video", "width", "height", "canvas", "preferredImageMimeTypes", "ext", "blob", "_blob$type", "fileExtension", "webcamState", "restartStream", "videoSources", "videoSource", "require_lib", "__commonJSMin", "exports", "module", "require_RateLimitedQueue", "__commonJSMin", "exports", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "createCancelError", "_activeRequests", "_queuedHandlers", "_paused", "_pauseTimer", "_downLimit", "_upperLimit", "_rateLimitingTimer", "_call", "_queueNext", "_next", "_queue", "_dequeue", "_resume", "_increaseLimit", "RateLimitedQueue", "limit", "_dequeue2", "_queue2", "_next2", "_queueNext2", "_call2", "fn", "queueOptions", "_this", "_len", "args", "_key", "queuedRequest", "outerPromise", "resolve", "reject", "cancelError", "innerPromise", "err", "result", "i", "duration", "done", "cancelActive", "next", "handler", "options", "index", "other", "internalRateLimitedQueue", "require_emitSocketProgress", "__commonJSMin", "exports", "module", "throttle", "emitSocketProgress", "uploader", "progressData", "file", "progress", "bytesUploaded", "bytesTotal", "require_getSocketHost", "__commonJSMin", "exports", "module", "getSocketHost", "url", "host", "require_EventTracker", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "_emitter", "_events", "EventTracker", "emitter", "event", "fn", "require_ProgressTimeout", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "_aliveTimer", "_isDone", "_onTimedOut", "_timeout", "ProgressTimeout", "timeout", "timeoutHandler", "require_isNetworkError", "__commonJSMin", "exports", "module", "isNetworkError", "xhr", "require_MiniXHRUpload", "__commonJSMin", "exports", "module", "_nonSecure", "_companionClient", "_RateLimitedQueue", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "emitSocketProgress", "getSocketHost", "EventTracker", "ProgressTimeout", "ErrorWithCause", "NetworkError", "isNetworkError", "buildResponseError", "xhr", "error", "err", "setTypeInBlob", "file", "addMetadata", "formData", "meta", "opts", "item", "createFormDataUpload", "formPost", "dataWithUpdatedType", "createBareUpload", "_queueRequestSocketToken", "_getOptions", "_addEventHandlerForFile", "_addEventHandlerIfFileStillExists", "_uploadLocalFile", "_requestSocketToken", "_uploadRemoteFile", "MiniXHRUpload", "_uppy", "_opts", "_uploadRemoteFile2", "_uploadLocalFile2", "_addEventHandlerIfFileStillExists2", "_addEventHandlerForFile2", "_getOptions2", "Client", "client", "metaFields", "status", "current", "total", "resolve", "reject", "token", "host", "socket", "createSocket", "progressData", "data", "body", "uploadURL", "uploadResp", "queuedRequest", "errData", "resp", "_socket", "_socket2", "_temp", "reason", "_socket3", "onRetryRequest", "_file$xhrUpload", "uppy", "overrides", "eventName", "fileID", "eventHandler", "targetFileID", "_this", "timer", "ev", "response", "header", "_temp2", "serverToken", "require_isXml", "__commonJSMin", "exports", "module", "removeMimeParameters", "mimeType", "isXml", "content", "xhr", "rawContentType", "contentType", "require_locale", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "module", "_RateLimitedQueue", "_companionClient", "_Symbol$for", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "BasePlugin", "packageJson", "MiniXHRUpload", "isXml", "locale", "resolveUrl", "origin", "link", "getXmlValue", "source", "tagName", "start", "end", "assertServerError", "res", "error", "validateParameters", "file", "params", "defaultGetResponseError", "content", "xhr", "warnedSuccessActionStatus", "_client", "_requests", "_uploader", "_handleUpload", "_setCompanionHeaders", "AwsS3", "uppy", "opts", "fileIDs", "paramsPromises", "onremove", "_paramsPromises$id", "getUploadParameters", "numberOfFiles", "index", "method", "url", "fields", "headers", "xhrOpts", "defaultOptions", "client", "filename", "type", "metadata", "key", "query", "defaultGetResponseData", "xhrOptions", "require_AbortController", "__commonJSMin", "exports", "AbortController", "AbortSignal", "createAbortError", "message", "require_delay", "__commonJSMin", "exports", "module", "_AbortController", "delay", "ms", "opts", "resolve", "reject", "_opts$signal", "_opts$signal2", "timeout", "cleanup", "onabort", "_opts$signal3", "require_MultipartUploader", "__commonJSMin", "exports", "module", "_AbortController", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "delay", "MB", "defaultOptions", "file", "err", "ensureInt", "value", "_aborted", "_initChunks", "_createUpload", "_resumeUpload", "_uploadParts", "_retryable", "_prepareUploadParts", "_uploadPartRetryable", "_uploadPart", "_onPartProgress", "_onPartComplete", "_uploadPartBytes", "_completeUpload", "_abortUpload", "_onError", "MultipartUploader", "options", "_onError2", "_abortUpload2", "_completeUpload2", "_uploadPartBytes2", "_onPartComplete2", "_onPartProgress2", "_uploadPart2", "_uploadPartRetryable2", "_prepareUploadParts2", "_retryable2", "_uploadParts2", "_resumeUpload2", "_createUpload2", "_initChunks2", "_aborted2", "opts", "_opts", "chunks", "desiredChunkSize", "minChunkSize", "chunkSize", "i", "end", "result", "parts", "part", "p", "state", "need", "completeChunks", "remainingChunks", "minNeeded", "candidates", "index", "partNumber", "prePreparedPart", "_ref", "before", "attempt", "after", "retryDelays", "signal", "shouldRetry", "status", "doAttempt", "retryAttempt", "candidate", "url", "headers", "sent", "totalUploaded", "n", "c", "etag", "body", "defer", "promise", "resolve", "reject", "xhr", "key", "cleanup", "onabort", "ev", "error", "a", "b", "require_lib", "__commonJSMin", "exports", "module", "_companionClient", "_RateLimitedQueue", "_Symbol$for", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "BasePlugin", "EventTracker", "emitSocketProgress", "getSocketHost", "packageJson", "MultipartUploader", "assertServerError", "res", "error", "_queueRequestSocketToken", "_client", "_requestSocketToken", "_setCompanionHeaders", "AwsS3Multipart", "uppy", "_opts", "file", "Client", "client", "opts", "defaultOptions", "fileID", "method", "metadata", "key", "_ref", "uploadId", "filename", "_ref2", "partNumbers", "_ref3", "parts", "uploadIdEnc", "_ref4", "_this", "resolve", "reject", "queuedRequest", "onStart", "data", "cFile", "onProgress", "bytesUploaded", "bytesTotal", "onError", "err", "onSuccess", "result", "uploadObject", "upload", "uploadResp", "onPartComplete", "part", "removed", "_temp", "reason", "isPaused", "serverToken", "_this2", "token", "host", "socket", "_temp2", "progressData", "errData", "fileIDs", "promises", "cb", "targetFileID", "eventHandler", "_this3", "capabilities", "require_base64", "__commonJSMin", "exports", "module", "global", "factory", "_Base64", "version", "b64chars", "b64tab", "bin", "t", "i", "l", "fromCharCode", "cb_utob", "c", "cc", "re_utob", "utob", "u", "cb_encode", "ccc", "padlen", "ord", "chars", "btoa", "b", "_encode", "mkUriSafe", "b64", "m0", "encode", "urisafe", "encodeURI", "fromUint8Array", "a", "a0", "a1", "a2", "re_btou", "cb_btou", "cccc", "cp", "offset", "btou", "cb_decode", "len", "n", "_atob", "atob", "_decode", "_fromURI", "decode", "toUint8Array", "noConflict", "Base64", "noEnum", "v", "require_requires_port", "__commonJSMin", "exports", "module", "port", "protocol", "require_querystringify", "__commonJSMin", "exports", "has", "undef", "decode", "input", "encode", "querystring", "query", "parser", "result", "part", "key", "value", "querystringify", "obj", "prefix", "pairs", "require_url_parse", "__commonJSMin", "exports", "module", "required", "qs", "controlOrWhitespace", "CRHTLF", "slashes", "port", "protocolre", "windowsDriveLetter", "trimLeft", "str", "rules", "address", "url", "isSpecial", "ignore", "lolcation", "loc", "globalVar", "location", "finaldestination", "type", "key", "Url", "scheme", "extractProtocol", "match", "protocol", "forwardSlashes", "otherSlashes", "slashesCount", "rest", "resolve", "relative", "base", "path", "i", "last", "unshift", "up", "parser", "extracted", "parse", "instruction", "index", "instructions", "set", "part", "value", "fn", "char", "ins", "toString", "stringify", "query", "host", "result", "require_error", "__commonJSMin", "exports", "_typeof", "obj", "_defineProperties", "target", "props", "descriptor", "_createClass", "Constructor", "protoProps", "staticProps", "_classCallCheck", "instance", "_inherits", "subClass", "superClass", "_setPrototypeOf", "_createSuper", "Derived", "hasNativeReflectConstruct", "_isNativeReflectConstruct", "Super", "_getPrototypeOf", "result", "NewTarget", "_possibleConstructorReturn", "self", "call", "_assertThisInitialized", "_wrapNativeSuper", "Class", "_cache", "_isNativeFunction", "Wrapper", "_construct", "Parent", "args", "fn", "o", "p", "DetailedError", "_Error", "_super", "message", "_this", "causingErr", "req", "res", "requestId", "method", "url", "status", "body", "_default", "require_logger", "__commonJSMin", "exports", "enableDebugLog", "log", "isEnabled", "msg", "require_uuid", "__commonJSMin", "exports", "uuid", "c", "r", "v", "require_upload", "__commonJSMin", "exports", "_jsBase", "_urlParse", "_interopRequireDefault", "_error", "_logger", "_uuid", "obj", "ownKeys", "object", "enumerableOnly", "keys", "symbols", "sym", "_objectSpread", "target", "i", "source", "key", "_defineProperty", "value", "_classCallCheck", "instance", "Constructor", "_defineProperties", "props", "descriptor", "_createClass", "protoProps", "staticProps", "defaultOptions", "BaseUpload", "file", "options", "_this", "fingerprint", "previousUpload", "_this2", "retryDelays", "optionName", "err", "_this3", "totalSize", "totalProgress", "partCount", "parts", "splitSizeIntoParts", "uploads", "part", "index", "lastPartProgress", "_ref", "resolve", "reject", "newPartProgress", "upload", "u", "req", "metadata", "encodeMetadata", "res", "inStatusCategory", "location", "resolveUrl", "shouldTerminate", "_this4", "message", "causingErr", "_this5", "shouldResetDelays", "shouldRetry", "delay", "bytesSent", "bytesTotal", "chunkSize", "bytesAccepted", "_this6", "promise", "_this7", "status", "offset", "length", "_this8", "_this9", "start", "end", "_ref2", "done", "method", "url", "openRequest", "_this10", "_this11", "storedUpload", "urlStorageKey", "body", "sendRequest", "remainingDelays", "newOptions", "encoded", "category", "headers", "name", "requestId", "onBeforeRequestPromise", "onAfterResponsePromise", "isOnline", "online", "retryAttempt", "origin", "link", "previousUrls", "partSize", "_default", "require_noopUrlStorage", "__commonJSMin", "exports", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "descriptor", "_createClass", "protoProps", "staticProps", "NoopUrlStorage", "fingerprint", "urlStorageKey", "upload", "require_urlStorage", "__commonJSMin", "exports", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "descriptor", "_createClass", "protoProps", "staticProps", "hasStorage", "key", "e", "canStoreURLs", "WebStorageUrlStorage", "results", "fingerprint", "urlStorageKey", "upload", "id", "prefix", "i", "_key", "require_httpStack", "__commonJSMin", "exports", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "descriptor", "_createClass", "protoProps", "staticProps", "XHRHttpStack", "method", "url", "Request", "header", "value", "progressHandler", "e", "_this", "body", "resolve", "reject", "Response", "err", "xhr", "require_isReactNative", "__commonJSMin", "exports", "isReactNative", "_default", "require_uriToBlob", "__commonJSMin", "exports", "uriToBlob", "uri", "resolve", "reject", "xhr", "blob", "err", "require_isCordova", "__commonJSMin", "exports", "isCordova", "_default", "require_readAsByteArray", "__commonJSMin", "exports", "readAsByteArray", "chunk", "resolve", "reject", "reader", "value", "err", "require_FileSource", "__commonJSMin", "exports", "_isCordova", "_interopRequireDefault", "_readAsByteArray", "obj", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "descriptor", "_createClass", "protoProps", "staticProps", "FileSource", "file", "start", "end", "value", "require_StreamSource", "__commonJSMin", "exports", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "descriptor", "_createClass", "protoProps", "staticProps", "len", "blobOrArray", "concat", "a", "b", "c", "StreamSource", "reader", "chunkSize", "start", "end", "_this", "hasEnoughData", "value", "done", "_ref", "hasAllDataBeenRead", "require_fileReader", "__commonJSMin", "exports", "_isReactNative", "_interopRequireDefault", "_uriToBlob", "_FileSource", "_StreamSource", "obj", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "descriptor", "_createClass", "protoProps", "staticProps", "FileReader", "input", "chunkSize", "blob", "err", "require_fingerprint", "__commonJSMin", "exports", "fingerprint", "_isReactNative", "_interopRequireDefault", "obj", "file", "options", "reactNativeFingerprint", "exifHash", "hashCode", "str", "hash", "_char", "require_browser", "__commonJSMin", "exports", "_error", "_httpStack", "_urlStorage", "_logger", "_upload", "_interopRequireDefault", "_noopUrlStorage", "_fileReader", "_fingerprint", "obj", "_typeof", "_classCallCheck", "instance", "Constructor", "_defineProperties", "target", "props", "descriptor", "_createClass", "protoProps", "staticProps", "_inherits", "subClass", "superClass", "_setPrototypeOf", "o", "p", "_createSuper", "Derived", "hasNativeReflectConstruct", "_isNativeReflectConstruct", "Super", "_getPrototypeOf", "result", "NewTarget", "_possibleConstructorReturn", "self", "call", "_assertThisInitialized", "ownKeys", "object", "enumerableOnly", "keys", "symbols", "sym", "_objectSpread", "i", "source", "key", "_defineProperty", "value", "defaultOptions", "Upload", "_BaseUpload", "_super", "file", "options", "url", "cb", "_window", "XMLHttpRequest", "Blob", "isSupported", "require_settle", "__commonJSMin", "exports", "module", "settle", "promises", "resolutions", "rejections", "resolved", "value", "rejected", "error", "promise", "require_getFingerprint", "__commonJSMin", "exports", "module", "tus", "isCordova", "isReactNative", "getFingerprint", "uppyFileObj", "file", "options", "uppyFingerprint", "require_lib", "__commonJSMin", "exports", "module", "tus", "_companionClient", "_RateLimitedQueue", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "BasePlugin", "emitSocketProgress", "getSocketHost", "settle", "EventTracker", "NetworkError", "isNetworkError", "hasProperty", "getFingerprint", "packageJson", "tusDefaultOptions", "_retryDelayIterator", "_queueRequestSocketToken", "_requestSocketToken", "Tus", "uppy", "_opts", "_this$opts$rateLimite", "_this$opts$retryDelay", "file", "Client", "client", "opts", "defaultOptions", "files", "fileID", "tusState", "uploader", "_this", "resolve", "reject", "queuedRequest", "qRequest", "upload", "uploadOptions", "req", "xhr", "userProvidedPromise", "done", "p", "res", "err", "_queuedRequest", "bytesUploaded", "bytesTotal", "uploadResp", "defaultOnShouldRetry", "_err$originalResponse", "status", "_classPrivateFieldLoo", "next", "_len", "args", "_key", "copyProp", "obj", "srcProp", "destProp", "meta", "item", "previousUploads", "previousUpload", "targetFileID", "isPaused", "_temp", "reason", "serverToken", "_this2", "token", "host", "socket", "_temp2", "progressData", "errData", "message", "error", "data", "uploadURL", "currentFile", "cb", "eventHandler", "_this3", "promises", "i", "current", "total", "fileIDs", "filesToUpload", "require_component_emitter", "__commonJSMin", "exports", "module", "Emitter", "obj", "mixin", "key", "event", "fn", "on", "callbacks", "cb", "i", "args", "len", "require_parseUrl", "__commonJSMin", "exports", "module", "parseUrl", "url", "scheme", "slashIndex", "require_commons", "__commonJSMin", "exports", "PACKET_TYPES", "PACKET_TYPES_REVERSE", "key", "ERROR_PACKET", "require_encodePacket_browser", "__commonJSMin", "exports", "encodePacketToBinary", "commons_js_1", "withNativeBlob", "withNativeArrayBuffer", "isView", "obj", "encodePacket", "type", "data", "supportsBinary", "callback", "encodeBlobAsBase64", "fileReader", "content", "toArray", "TEXT_ENCODER", "packet", "encoded", "require_base64_arraybuffer", "__commonJSMin", "exports", "chars", "lookup", "i", "encode", "arraybuffer", "bytes", "len", "base64", "decode", "bufferLength", "p", "encoded1", "encoded2", "encoded3", "encoded4", "require_decodePacket_browser", "__commonJSMin", "exports", "commons_js_1", "base64_arraybuffer_js_1", "withNativeArrayBuffer", "decodePacket", "encodedPacket", "binaryType", "mapBinary", "type", "decodeBase64Packet", "data", "decoded", "require_cjs", "__commonJSMin", "exports", "createPacketEncoderStream", "createPacketDecoderStream", "encodePacket_js_1", "decodePacket_js_1", "commons_js_1", "SEPARATOR", "encodePayload", "packets", "callback", "length", "encodedPackets", "count", "packet", "i", "encodedPacket", "decodePayload", "encodedPayload", "binaryType", "decodedPacket", "controller", "payloadLength", "header", "view", "TEXT_DECODER", "totalLength", "chunks", "acc", "chunk", "concatChunks", "size", "buffer", "j", "maxPayload", "state", "expectedLength", "isBinary", "headerArray", "n", "data", "require_cjs", "__commonJSMin", "exports", "Emitter", "obj", "mixin", "key", "event", "fn", "on", "callbacks", "cb", "i", "args", "len", "require_globals", "__commonJSMin", "exports", "createCookieJar", "cb", "setTimeoutFn", "require_util", "__commonJSMin", "exports", "pick", "installTimerFunctions", "byteLength", "randomString", "globals_node_js_1", "obj", "attr", "acc", "k", "NATIVE_SET_TIMEOUT", "NATIVE_CLEAR_TIMEOUT", "opts", "BASE64_OVERHEAD", "utf8Length", "str", "c", "length", "i", "l", "require_parseqs", "__commonJSMin", "exports", "encode", "decode", "obj", "str", "qs", "qry", "pairs", "i", "l", "pair", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "ns", "matchesTemplate", "search", "template", "searchIndex", "templateIndex", "starIndex", "matchIndex", "name", "skip", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "m", "args", "c", "index", "lastC", "match", "namespaces", "r", "formatters", "v", "error", "require_transport", "__commonJSMin", "exports", "__importDefault", "mod", "engine_io_parser_1", "component_emitter_1", "util_js_1", "parseqs_js_1", "debug_1", "debug", "TransportError", "reason", "description", "context", "Transport", "opts", "packets", "data", "packet", "details", "onPause", "schema", "query", "hostname", "encodedQuery", "require_polling", "__commonJSMin", "exports", "__importDefault", "mod", "transport_js_1", "util_js_1", "engine_io_parser_1", "debug_1", "debug", "Polling", "onPause", "pause", "total", "data", "callback", "packet", "close", "packets", "schema", "query", "require_has_cors", "__commonJSMin", "exports", "value", "require_polling_xhr", "__commonJSMin", "exports", "__importDefault", "mod", "polling_js_1", "component_emitter_1", "util_js_1", "globals_node_js_1", "has_cors_js_1", "debug_1", "debug", "empty", "BaseXHR", "opts", "isSSL", "port", "data", "fn", "req", "xhrStatus", "context", "Request", "_Request", "createRequest", "uri", "_a", "xhr", "i", "e", "err", "fromError", "unloadHandler", "terminationEvent", "hasXHR2", "newRequest", "XHR", "forceBase64", "xdomain", "require_websocket", "__commonJSMin", "exports", "__importDefault", "mod", "transport_js_1", "util_js_1", "engine_io_parser_1", "globals_node_js_1", "debug_1", "debug", "isReactNative", "BaseWS", "uri", "protocols", "opts", "err", "closeEvent", "ev", "packets", "packet", "lastPacket", "data", "schema", "query", "WebSocketCtor", "WS", "_packet", "require_webtransport", "__commonJSMin", "exports", "__importDefault", "mod", "transport_js_1", "globals_node_js_1", "engine_io_parser_1", "debug_1", "debug", "WT", "err", "stream", "decoderStream", "reader", "encoderStream", "read", "done", "value", "packet", "packets", "lastPacket", "_a", "require_transports", "__commonJSMin", "exports", "polling_xhr_node_js_1", "websocket_node_js_1", "webtransport_js_1", "require_parseuri", "__commonJSMin", "exports", "parse", "re", "parts", "str", "src", "b", "e", "m", "uri", "i", "pathNames", "queryKey", "obj", "path", "regx", "names", "query", "data", "$0", "$1", "$2", "require_socket", "__commonJSMin", "exports", "__importDefault", "mod", "index_js_1", "util_js_1", "parseqs_js_1", "parseuri_js_1", "component_emitter_1", "engine_io_parser_1", "globals_node_js_1", "debug_1", "debug", "withEventListeners", "OFFLINE_EVENT_LISTENERS", "listener", "Socket", "_Socket", "uri", "opts", "_a", "_b", "parsedUri", "t", "transportName", "name", "query", "transport", "reason", "failed", "onTransportOpen", "msg", "cleanup", "err", "freezeTransport", "onerror", "error", "onTransportClose", "onclose", "onupgrade", "to", "i", "packet", "data", "delay", "packets", "payloadSize", "hasExpired", "options", "fn", "type", "close", "cleanupAndClose", "waitForUpgrade", "description", "upgrades", "filteredUpgrades", "require_polling_fetch", "__commonJSMin", "exports", "polling_js_1", "Fetch", "res", "data", "err", "callback", "_a", "isPost", "headers", "require_cjs", "__commonJSMin", "exports", "socket_js_1", "transport_js_1", "index_js_1", "util_js_1", "parseuri_js_1", "globals_node_js_1", "polling_fetch_js_1", "polling_xhr_node_js_1", "polling_xhr_js_1", "websocket_node_js_1", "websocket_js_1", "webtransport_js_1", "require_url", "__commonJSMin", "exports", "__importDefault", "mod", "url", "engine_io_client_1", "debug_1", "debug", "uri", "path", "loc", "obj", "host", "require_is_binary", "__commonJSMin", "exports", "isBinary", "hasBinary", "withNativeArrayBuffer", "isView", "obj", "toString", "withNativeBlob", "withNativeFile", "toJSON", "l", "key", "require_binary", "__commonJSMin", "exports", "deconstructPacket", "reconstructPacket", "is_binary_js_1", "packet", "buffers", "packetData", "pack", "_deconstructPacket", "data", "toJSON", "placeholder", "newData", "i", "key", "_reconstructPacket", "require_cjs", "__commonJSMin", "exports", "__importDefault", "mod", "isPacketValid", "component_emitter_1", "binary_js_1", "is_binary_js_1", "debug_1", "debug", "RESERVED_EVENTS", "PacketType", "Encoder", "replacer", "obj", "str", "deconstruction", "pack", "buffers", "Decoder", "_Decoder", "opts", "packet", "isBinaryEvent", "BinaryReconstructor", "p", "start", "buf", "n", "isInteger", "next", "c", "payload", "type", "isObject", "binData", "isNamespaceValid", "nsp", "value", "isAckIdValid", "id", "isDataValid", "require_on", "__commonJSMin", "exports", "on", "obj", "ev", "fn", "require_socket", "__commonJSMin", "exports", "__importDefault", "mod", "socket_io_parser_1", "on_js_1", "component_emitter_1", "debug_1", "debug", "RESERVED_EVENTS", "Socket", "io", "nsp", "opts", "args", "ev", "_a", "_b", "_c", "packet", "id", "ack", "isTransportWritable", "isConnected", "timeout", "timer", "i", "fn", "resolve", "reject", "arg1", "arg2", "err", "responseArgs", "force", "data", "reason", "description", "listeners", "listener", "self", "sent", "pid", "subDestroy", "compress", "require_backo2", "__commonJSMin", "exports", "Backoff", "opts", "ms", "rand", "deviation", "min", "max", "jitter", "require_manager", "__commonJSMin", "exports", "__createBinding", "o", "m", "k", "k2", "desc", "__setModuleDefault", "v", "__importStar", "ownKeys", "ar", "mod", "result", "i", "__importDefault", "engine_io_client_1", "socket_js_1", "parser", "on_js_1", "backo2_js_1", "component_emitter_1", "debug_1", "debug", "Manager", "uri", "opts", "_a", "_parser", "fn", "socket", "self", "openSubDestroy", "onError", "err", "errorSub", "timeout", "timer", "data", "e", "packet", "nsp", "nsps", "encodedPackets", "subDestroy", "reason", "description", "delay", "attempt", "require_cjs", "__commonJSMin", "exports", "module", "__importDefault", "mod", "lookup", "url_js_1", "manager_js_1", "socket_js_1", "debug_1", "debug", "cache", "uri", "opts", "parsed", "source", "id", "path", "sameNamespace", "newConnection", "io", "socket_io_parser_1", "engine_io_client_1", "require_Assembly", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "Emitter", "has", "NetworkError", "fetchWithNetworkError", "parseUrl", "socketIo", "requireSocketIo", "_socketIo", "ASSEMBLY_UPLOADING", "ASSEMBLY_EXECUTING", "ASSEMBLY_COMPLETED", "statusOrder", "isStatus", "status", "test", "_rateLimitedQueue", "_fetchWithNetworkError", "_previousFetchStatusStillPending", "_onFinished", "_connectSocket", "_onError", "_beginPolling", "_fetchStatus", "_diffStatus", "TransloaditAssembly", "assembly", "rateLimitedQueue", "_diffStatus2", "_fetchStatus2", "_beginPolling2", "_onError2", "_connectSocket2", "_onFinished2", "next", "parsed", "socket", "file", "stepName", "result", "err", "_temp", "diff", "response", "prev", "prevStatus", "nextStatus", "nowExecuting", "upload", "nextResults", "prevResults", "n", "p", "require_Client", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "fetchWithNetworkError", "ASSEMBLIES_ENDPOINT", "_headers", "_fetchWithNetworkError", "_fetchJSON", "_reportError", "Client", "_opts", "_fetchJSON2", "err", "params", "opts", "_ref", "fields", "signature", "expectedFiles", "data", "key", "url", "assembly", "file", "size", "uploadUrl", "filename", "qs", "num_expected_upload_files", "body", "_temp", "endpoint", "instance", "message", "_len", "args", "_key", "response", "serverError", "error", "require_AssemblyOptions", "__commonJSMin", "exports", "module", "validateParams", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "ErrorWithCause", "params", "err", "dedupe", "list", "dedupeMap", "fileIDs", "options", "_ref", "fileIDArrays", "_getAssemblyOptions", "AssemblyOptions", "files", "opts", "_getAssemblyOptions2", "file", "assemblyOptions", "fieldName", "require_AssemblyWatcher", "__commonJSMin", "exports", "module", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "Emitter", "_assemblyIDs", "_reject", "_remaining", "_resolve", "_uppy", "_watching", "_onAssemblyComplete", "_onAssemblyCancel", "_onAssemblyError", "_onImportError", "_checkAllComplete", "_removeListeners", "_addListeners", "TransloaditAssemblyWatcher", "uppy", "assemblyIDs", "_addListeners2", "_removeListeners2", "_checkAllComplete2", "_watching2", "assembly", "error", "fileID", "resolve", "reject", "require_locale", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "module", "_RateLimitedQueue", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "hasProperty", "ErrorWithCause", "BasePlugin", "Tus", "Assembly", "Client", "AssemblyOptions", "validateParams", "AssemblyWatcher", "locale", "packageJson", "defaultGetAssemblyOptions", "file", "options", "sendErrorToConsole", "originalErr", "err", "error", "COMPANION", "ALLOWED_COMPANION_PATTERN", "TL_COMPANION", "_rateLimitedQueue", "_getClientVersion", "_attachAssemblyMetadata", "_createAssembly", "_createAssemblyWatcher", "_shouldWaitAfterUpload", "_reserveFiles", "_onFileUploadURLAvailable", "_findFile", "_onFileUploadComplete", "_onResult", "_onAssemblyFinished", "_cancelAssembly", "_onCancelAll", "_getPersistentData", "_onRestored", "_connectAssembly", "_prepareUpload", "_afterUpload", "_closeAssemblyIfExists", "_onError", "_onTusError", "Transloadit", "uppy", "opts", "_this", "_connectAssembly2", "_cancelAssembly2", "_onAssemblyFinished2", "_onResult2", "_onFileUploadComplete2", "_findFile2", "_reserveFiles2", "_shouldWaitAfterUpload2", "_createAssemblyWatcher2", "_createAssembly2", "_attachAssemblyMetadata2", "_getClientVersion2", "rawFile", "_file$transloadit", "assemblies", "assembly", "_temp", "reason", "uploadsAssemblies", "assemblyID", "setData", "pluginData", "savedState", "previousAssemblies", "restoreState", "files", "results", "status", "uploadedFile", "state", "stepName", "result", "restoreAssemblies", "uploadID", "assemblyIDs", "updateAssemblies", "fileIDs", "filesWithoutErrors", "createAssembly", "_ref", "fileID", "maybeCreatedAssemblies", "createdAssemblies", "filteredFileIDs", "closeSocketConnections", "_this$activeAssemblie", "_file$transloadit2", "_err$message", "_err$originalRequest", "_err$originalRequest$", "endpoint", "defaultOptions", "hasCustomAssemblyOptions", "capabilities", "_file$transloadit3", "list", "addPluginVersion", "pluginName", "versionName", "plugin", "meta", "tus", "remote", "newHost", "path", "newFile", "newAssembly", "_ref2", "updatedFiles", "fileRemovedHandler", "fileRemoved", "nbOfRemainingFiles", "wrapped", "watcher", "assemblyId", "entry", "url", "finalStatus", "newStatus", "require_locale", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "module", "_nonSecure", "_companionClient", "_RateLimitedQueue", "BasePlugin", "emitSocketProgress", "getSocketHost", "settle", "EventTracker", "ProgressTimeout", "NetworkError", "isNetworkError", "packageJson", "locale", "buildResponseError", "xhr", "err", "error", "setTypeInBlob", "file", "XHRUpload", "uppy", "opts", "defaultOptions", "responseText", "parsedResponse", "_", "response", "status", "overrides", "headers", "formData", "meta", "item", "formPost", "dataWithUpdatedType", "files", "options", "current", "total", "resolve", "reject", "data", "queuedRequest", "timer", "id", "ev", "body", "uploadURL", "uploadResp", "currentOpts", "header", "_ref", "reason", "fields", "name", "Client", "res", "token", "host", "socket", "_temp", "progressData", "errData", "resp", "endpoint", "method", "optsFromState", "emitError", "_temp2", "promises", "i", "fileID", "cb", "targetFileID", "eventHandler", "_this", "fileIDs", "capabilities", "require_prettierBytes", "__commonJSMin", "exports", "module", "num", "neg", "units", "exponent", "unit", "require_compressor_common", "__commonJSMin", "exports", "module", "_classCallCheck", "a", "n", "_defineProperties", "e", "r", "t", "o", "_toPropertyKey", "_createClass", "_defineProperty", "_extends", "ownKeys", "_objectSpread2", "_toPrimitive", "i", "getDefaultExportFromCjs", "x", "canvasToBlob", "window", "CanvasPrototype", "hasBlobConstructor", "hasArrayBufferViewSupport", "BlobBuilder", "dataURIPattern", "dataURLtoBlob", "dataURI", "matches", "mediaType", "isBase64", "dataString", "byteString", "arrayBuffer", "intArray", "bb", "callback", "type", "quality", "self", "canvasToBlobExports", "toBlob", "isBlob", "value", "isBlob$1", "DEFAULTS", "IS_BROWSER", "WINDOW", "isPositiveNumber", "slice", "toArray", "REGEXP_IMAGE_TYPE", "isImageType", "imageTypeToExtension", "extension", "fromCharCode", "getStringFromCharCode", "dataView", "start", "length", "str", "isCanvasAvailable", "canvas", "context", "imageData", "readBack", "expected", "index", "btoa", "arrayBufferToDataURL", "mimeType", "chunks", "chunkSize", "uint8", "resetAndGetOrientation", "orientation", "littleEndian", "app1Start", "ifdStart", "offset", "exifIDCode", "tiffOffset", "endianness", "firstIFDOffset", "_length", "_offset", "parseOrientation", "rotate", "scaleX", "scaleY", "REGEXP_DECIMALS", "normalizeDecimalNumber", "times", "getAdjustedSizes", "_ref", "aspectRatio", "height", "width", "isValidWidth", "isValidHeight", "adjustedWidth", "getExif", "array", "segments", "next", "end", "segment", "exifArray", "current", "insertExif", "app0Length", "newArrayBuffer", "ArrayBuffer$1", "FileReader", "URL", "REGEXP_EXTENSION", "AnotherCompressor", "Compressor", "file", "options", "_this", "isJPEGImage", "checkOrientation", "retainExif", "reader", "target", "result", "data", "_this2", "image", "_ref2", "_this3", "naturalWidth", "naturalHeight", "_ref2$rotate", "_ref2$scaleX", "_ref2$scaleY", "is90DegreesRotated", "resizable", "maxWidth", "maxHeight", "minWidth", "minHeight", "_ref3", "_ref4", "_ref5", "_getAdjustedSizes", "_getAdjustedSizes2", "_getAdjustedSizes3", "_getAdjustedSizes4", "_getAdjustedSizes4$wi", "_getAdjustedSizes4$he", "destX", "destY", "destWidth", "destHeight", "params", "srcX", "srcY", "srcWidth", "srcHeight", "_getAdjustedSizes5", "_ref6", "fillStyle", "blob", "done", "_ref7", "_ref8", "fileName", "date", "err", "require_locale", "__commonJSMin", "exports", "module", "require_lib", "__commonJSMin", "exports", "module", "_core", "_RateLimitedQueue2", "_classPrivateFieldLooseBase", "receiver", "privateKey", "id", "_classPrivateFieldLooseKey", "name", "getFileNameAndExtension", "prettierBytes", "CompressorJS", "locale", "_RateLimitedQueue", "Compressor", "uppy", "opts", "defaultOptions", "blob", "resolve", "reject", "fileIDs", "totalCompressedSize", "compressedFiles", "compressAndApplyResult", "file", "compressedBlob", "compressedSavingsSize", "type", "size", "extension", "err", "promises", "fileID", "require_lib", "__commonJSMin", "exports", "getFormData", "getFieldData", "NODE_LIST_CLASSES", "IGNORED_ELEMENT_TYPES", "CHECKED_INPUT_TYPES", "TRIM_RE", "slice", "toString", "form", "options", "data", "elementName", "elementNames", "elementNameLookup", "i", "l", "element", "_i", "_l", "value", "fieldName", "getFormElementValue", "allRadios", "trim", "type", "require_lib", "__commonJSMin", "exports", "module", "BasePlugin", "findDOMElement", "toArray", "getFormData", "packageJson", "Form", "uppy", "opts", "defaultOptions", "result", "ev", "elements", "disabledByUppy", "el", "button", "err", "resultInput", "updatedResult", "formMeta", "require_ServiceWorkerStore", "__commonJSMin", "exports", "module", "isSupported", "waitForServiceWorker", "resolve", "reject", "ServiceWorkerStore", "opts", "defer", "promise", "onMessage", "event", "file", "fileID", "require_IndexedDBStore", "__commonJSMin", "exports", "module", "indexedDB", "isSupported", "DB_NAME", "STORE_NAME", "DEFAULT_EXPIRY", "DB_VERSION", "migrateExpiration", "store", "request", "event", "cursor", "entry", "connect", "dbName", "resolve", "reject", "db", "transaction", "waitForRequest", "cleanedUp", "IndexedDBStore", "_IndexedDBStore", "opts", "createConnection", "fileID", "files", "result", "file", "size", "require_MetaDataStore", "__commonJSMin", "exports", "module", "findUppyInstances", "instances", "i", "key", "maybeParse", "str", "cleanedUp", "MetaDataStore", "_MetaDataStore", "opts", "savedState", "data", "metadata", "expires", "state", "instanceID", "instanceIDs", "now", "id", "obj", "require_lib", "__commonJSMin", "exports", "module", "throttle", "BasePlugin", "ServiceWorkerStore", "IndexedDBStore", "MetaDataStore", "packageJson", "GoldenRetriever", "uppy", "opts", "file", "err", "currentUploads", "uploadId", "fileIDs", "_ref", "successful", "resultingArrayOfObjects", "blobs", "defaultOptions", "savedState", "waitingFiles", "uploadingFiles", "uploadID", "fileID", "filesToSave", "filesToSaveWithoutData", "pluginData", "data", "localFilesOnly", "numberOfFilesRecovered", "numberOfFilesTryingToRecover", "obsoleteBlobs", "updatedFiles", "originalFile", "updatedFileData", "promises", "id", "require_lib", "__commonJSMin", "exports", "module", "_core", "packageJson", "ReduxDevTools", "uppy", "opts", "defaultOptions", "prevState", "nextState", "message", "computedStates", "require_fr_FR", "__commonJSMin", "exports", "module", "fr_FR", "n", "extend", "dest", "i", "j", "len", "src", "create", "F", "proto", "bind", "fn", "obj", "slice", "args", "lastId", "stamp", "throttle", "time", "context", "lock", "wrapperFn", "later", "wrapNum", "x", "range", "includeMax", "max", "min", "d", "falseFn", "formatNum", "num", "precision", "pow", "trim", "str", "splitWords", "setOptions", "options", "getParamString", "existingUrl", "uppercase", "params", "templateRe", "template", "data", "key", "value", "isArray", "indexOf", "array", "el", "emptyImageUrl", "getPrefixed", "name", "lastTime", "timeoutDefer", "timeToCall", "requestFn", "cancelFn", "id", "requestAnimFrame", "immediate", "cancelAnimFrame", "Class", "props", "NewClass", "Util.setOptions", "parentProto", "Util.create", "Util.extend", "checkDeprecatedMixinEvents", "parentOptions", "init", "includes", "Util.isArray", "Events", "types", "type", "Util.splitWords", "removeAll", "_once", "newListener", "listeners", "Util.falseFn", "index", "listener", "propagate", "event", "l", "_fn", "Util.stamp", "e", "Evented", "Point", "y", "round", "trunc", "v", "point", "toPoint", "Bounds", "a", "b", "points", "min2", "max2", "toBounds", "bounds", "xIntersects", "yIntersects", "xOverlaps", "yOverlaps", "bufferRatio", "heightBuffer", "widthBuffer", "LatLngBounds", "corner1", "corner2", "latlngs", "sw", "ne", "sw2", "ne2", "LatLng", "toLatLng", "toLatLngBounds", "latIntersects", "lngIntersects", "latOverlaps", "lngOverlaps", "maxMargin", "lat", "lng", "alt", "margin", "Util.formatNum", "other", "Earth", "sizeInMeters", "latAccuracy", "lngAccuracy", "c", "CRS", "latlng", "zoom", "projectedPoint", "scale", "untransformedPoint", "s", "Util.wrapNum", "center", "newCenter", "latShift", "lngShift", "newSw", "newNe", "latlng1", "latlng2", "rad", "lat1", "lat2", "sinDLat", "sinDLon", "earthRadius", "SphericalMercator", "sin", "Transformation", "toTransformation", "EPSG3857", "EPSG900913", "svgCreate", "pointsToPath", "rings", "closed", "len2", "p", "Browser", "style", "ie", "ielt9", "edge", "webkit", "userAgentContains", "android", "android23", "webkitVer", "androidStock", "opera", "chrome", "gecko", "safari", "phantom", "opera12", "win", "ie3d", "webkit3d", "gecko3d", "any3d", "mobile", "mobileWebkit", "mobileWebkit3d", "msPointer", "pointer", "touchNative", "touch", "mobileOpera", "mobileGecko", "retina", "passiveEvents", "supportsPassiveOption", "opts", "canvas", "svg", "inlineSvg", "div", "vml", "shape", "mac", "linux", "POINTER_DOWN", "POINTER_MOVE", "POINTER_UP", "POINTER_CANCEL", "pEvent", "handle", "_onPointerStart", "_handlePointer", "_pointers", "_pointerDocListener", "addPointerListener", "handler", "_addPointerDocListener", "removePointerListener", "_globalPointerDown", "_globalPointerMove", "_globalPointerUp", "DomEvent.preventDefault", "makeDblclick", "newEvent", "prop", "delay", "addDoubleTapListener", "last", "detail", "simDblclick", "path", "DomEvent.getPropagationPath", "now", "removeDoubleTapListener", "handlers", "TRANSFORM", "testProp", "TRANSITION", "TRANSITION_END", "get", "getStyle", "css", "tagName", "className", "container", "remove", "parent", "empty", "toFront", "toBack", "hasClass", "getClass", "addClass", "classes", "setClass", "removeClass", "Util.trim", "setOpacity", "_setOpacityIE", "filter", "filterName", "setTransform", "offset", "pos", "setPosition", "getPosition", "disableTextSelection", "enableTextSelection", "_userSelect", "DomEvent.on", "DomEvent.off", "userSelectProperty", "disableImageDrag", "enableImageDrag", "_outlineElement", "_outlineStyle", "preventOutline", "element", "restoreOutline", "getSizedParentNode", "getScale", "rect", "on", "addOne", "eventsKey", "off", "batchRemove", "removeOne", "Util.indexOf", "filterFn", "mouseSubst", "originalHandler", "isExternalTarget", "stopPropagation", "disableScrollPropagation", "disableClickPropagation", "preventDefault", "stop", "getPropagationPath", "ev", "getMousePosition", "wheelPxFactor", "getWheelDelta", "related", "PosAnimation", "newPos", "duration", "easeLinearity", "DomUtil.getPosition", "Util.requestAnimFrame", "elapsed", "progress", "DomUtil.setPosition", "Util.cancelAnimFrame", "t", "Map", "Util.bind", "DomUtil.TRANSITION", "DomUtil.TRANSITION_END", "moved", "delta", "viewHalf", "containerPoint", "centerOffset", "paddingTL", "paddingBR", "paddingOffset", "swPoint", "nePoint", "target", "DomUtil.addClass", "targetCenter", "targetZoom", "from", "to", "size", "startZoom", "w0", "w1", "u1", "rho", "rho2", "r", "s1", "s2", "t1", "b1", "sq", "log", "sinh", "n", "cosh", "tanh", "r0", "w", "u", "easeOut", "start", "S", "frame", "oldZoom", "pixelCenter", "pixelPoint", "pixelBounds", "paddedBounds", "paddedSize", "oldSize", "newSize", "oldCenter", "onResponse", "onError", "error", "message", "HandlerClass", "DomUtil.remove", "pane", "DomUtil.create", "inside", "padding", "nw", "se", "boundsSize", "snap", "scalex", "scaley", "topLeftPoint", "toZoom", "fromZoom", "crs", "layerPoint", "DomEvent.getMousePosition", "DomUtil.get", "position", "DomUtil.getStyle", "panes", "noMoveStart", "loading", "zoomChanged", "supressEvent", "onOff", "targets", "isHover", "dragging", "DomEvent.isExternalTarget", "DomUtil.preventOutline", "canvasTargets", "synth", "filtered", "isMarker", "callback", "pixelOrigin", "topLeft", "latLngBounds", "centerPoint", "viewBounds", "newBounds", "pxBounds", "maxBounds", "projectedMaxBounds", "minOffset", "maxOffset", "dx", "dy", "left", "right", "DomUtil.removeClass", "proxy", "DomUtil.TRANSFORM", "transform", "DomUtil.setTransform", "z", "startAnim", "noUpdate", "createMap", "Control", "map", "corner", "control", "corners", "createCorner", "vSide", "hSide", "Layers", "layerA", "layerB", "nameA", "nameB", "baseLayers", "overlays", "layer", "acceptableHeight", "collapsed", "DomEvent.disableClickPropagation", "DomEvent.disableScrollPropagation", "section", "link", "overlay", "DomUtil.empty", "baseLayersPresent", "overlaysPresent", "baseLayersCount", "checked", "radioHtml", "radioFragment", "label", "input", "holder", "inputs", "addedLayers", "removedLayers", "that", "layers", "Zoom", "zoomName", "html", "title", "DomEvent.stop", "Scale", "maxMeters", "meters", "maxFeet", "maxMiles", "miles", "feet", "text", "ratio", "pow10", "ukrainianFlag", "Attribution", "prefix", "attribs", "prefixAndAttribs", "attribution", "Handler", "Mixin", "START", "Draggable", "dragStartTarget", "DomUtil.hasClass", "DomUtil.disableImageDrag", "DomUtil.disableTextSelection", "first", "sizedParent", "DomUtil.getSizedParentNode", "DomUtil.getScale", "mouseevent", "noInertia", "DomUtil.enableImageDrag", "DomUtil.enableTextSelection", "fireDragend", "clipPolygon", "clippedPoints", "edges", "k", "LineUtil._getBitCode", "LineUtil._getEdgeIntersection", "polygonCenter", "p1", "p2", "f", "area", "LineUtil.isFlat", "centroidLatLng", "areaBounds", "centroid", "latlngCenter", "coords", "latSum", "lngSum", "simplify", "tolerance", "sqTolerance", "_reducePoints", "_simplifyDP", "pointToSegmentDistance", "_sqClosestPointOnSegment", "closestPointOnSegment", "ArrayConstructor", "markers", "_simplifyDPStep", "newPoints", "maxSqDist", "sqDist", "reducedPoints", "prev", "_sqDist", "_lastCode", "clipSegment", "useLastCode", "codeA", "_getBitCode", "codeB", "codeOut", "newCode", "_getEdgeIntersection", "code", "dot", "isFlat", "_flat", "polylineCenter", "halfDist", "segDist", "dist", "LonLat", "Mercator", "tmp", "con", "ts", "phi", "dphi", "EPSG3395", "EPSG4326", "Simple", "Layer", "targetEl", "events", "method", "minZoom", "maxZoom", "oldZoomSpan", "LayerGroup", "layerId", "methodName", "zIndex", "layerGroup", "FeatureGroup", "featureGroup", "Icon", "oldIcon", "img", "sizeOption", "anchor", "icon", "IconDefault", "strip", "re", "idx", "match", "MarkerDrag", "marker", "speed", "iconPos", "origin", "panBounds", "movement", "shadow", "Marker", "latLng", "oldLatLng", "classToAdd", "addIcon", "newShadow", "addShadow", "opt", "draggable", "opacity", "DomUtil.setOpacity", "iconOpts", "Path", "CircleMarker", "radius", "r2", "circleMarker", "Circle", "legacyOptions", "half", "latR", "top", "bottom", "lngR", "circle", "Polyline", "minDistance", "minPoint", "closest", "LineUtil._sqClosestPointOnSegment", "jLen", "LineUtil.polylineCenter", "result", "flat", "projectedBounds", "ring", "parts", "segment", "LineUtil.clipSegment", "LineUtil.simplify", "part", "LineUtil.pointToSegmentDistance", "polyline", "LineUtil._flat", "Polygon", "PolyUtil.polygonCenter", "clipped", "PolyUtil.clipPolygon", "polygon", "GeoJSON", "geojson", "features", "feature", "geometryToLayer", "asFeature", "geometry", "pointToLayer", "_coordsToLatLng", "coordsToLatLng", "_pointToLayer", "coordsToLatLngs", "geoLayer", "featureLayer", "pointToLayerFn", "levelsDeep", "latLngToCoords", "latLngsToCoords", "getFeature", "newGeometry", "PointToGeoJSON", "multi", "holes", "isGeometryCollection", "jsons", "json", "geoJSON", "geoJson", "ImageOverlay", "url", "styleOpts", "DomUtil.toFront", "DomUtil.toBack", "wasElementSupplied", "image", "errorUrl", "imageOverlay", "VideoOverlay", "vid", "sourceElements", "sources", "source", "videoOverlay", "video", "SVGOverlay", "svgOverlay", "DivOverlay", "content", "node", "OverlayClass", "old", "Popup", "DomEvent.stopPropagation", "wrapper", "closeButton", "width", "height", "maxHeight", "scrolledClass", "marginBottom", "containerHeight", "containerWidth", "layerPos", "containerPos", "popup", "Tooltip", "subX", "subY", "tooltipPoint", "direction", "tooltipWidth", "tooltipHeight", "tooltip", "DivIcon", "bgPos", "divIcon", "GridLayer", "tileZoom", "Util.throttle", "compare", "edgeZIndex", "nextFrame", "willPrune", "tile", "fade", "level", "x2", "y2", "z2", "coords2", "animating", "noPrune", "tileZoomChanged", "translate", "tileSize", "mapZoom", "halfSize", "tileRange", "tileCenter", "queue", "noPruneRange", "fragment", "tileBounds", "nwPoint", "sePoint", "bp", "tilePos", "err", "newCoords", "gridLayer", "TileLayer", "noRedraw", "done", "invertedY", "Util.template", "zoomReverse", "zoomOffset", "tilePoint", "Util.emptyImageUrl", "tileLayer", "TileLayerWMS", "wmsParams", "realRetina", "projectionKey", "bbox", "tileLayerWMS", "Renderer", "currentCenterPoint", "topLeftOffset", "Canvas", "m", "order", "next", "dashArray", "dashValue", "ctx", "clickedLayer", "candidateHoveredLayer", "vmlCreate", "vmlMixin", "stroke", "fill", "SVG", "arc", "renderer", "Rectangle", "rectangle", "BoxZoom", "DoubleClickZoom", "Drag", "pxCenter", "pxWorldCenter", "threshold", "limit", "worldWidth", "halfWidth", "newX1", "newX2", "newX", "ease", "speedVector", "limitedSpeed", "limitedSpeedVector", "decelerationDuration", "Keyboard", "body", "docEl", "panDelta", "keys", "codes", "zoomDelta", "newLatLng", "ScrollWheelZoom", "DomEvent.getWheelDelta", "debounce", "d2", "d3", "d4", "tapHoldDelay", "TapHold", "cancelClickPrevent", "simulatedEvent", "TouchZoom", "moveFn", "require_rastercoords", "__commonJSMin", "exports", "module", "factory", "L", "map", "imgsize", "tilesize", "setmaxbounds", "coords", "southWest", "northEast", "bounds", "require_ev_emitter", "__commonJSMin", "exports", "module", "global", "factory", "EvEmitter", "proto", "eventName", "listener", "events", "listeners", "onceEvents", "onceListeners", "index", "args", "i", "isOnce", "require_get_size", "__commonJSMin", "exports", "module", "window", "factory", "getStyleSize", "value", "num", "isValid", "noop", "logError", "message", "measurements", "measurementsLength", "getZeroSize", "size", "i", "measurement", "getStyle", "elem", "style", "isSetup", "isBoxSizeOuter", "setup", "div", "body", "getSize", "isBorderBox", "paddingWidth", "paddingHeight", "marginWidth", "marginHeight", "borderWidth", "borderHeight", "isBorderBoxSizeOuter", "styleWidth", "styleHeight", "require_matches_selector", "__commonJSMin", "exports", "module", "window", "factory", "matchesMethod", "ElemProto", "prefixes", "i", "prefix", "method", "elem", "selector", "require_utils", "__commonJSMin", "exports", "module", "window", "factory", "matchesSelector", "utils", "a", "b", "prop", "num", "div", "arraySlice", "obj", "isArrayLike", "ary", "index", "elem", "selector", "event", "method", "elems", "ffElems", "childElems", "i", "_class", "methodName", "threshold", "timeoutName", "timeout", "args", "_this", "callback", "readyState", "str", "match", "$1", "$2", "console", "WidgetClass", "namespace", "dashedNamespace", "dataAttr", "dataAttrElems", "jsDashElems", "dataOptionsAttr", "jQuery", "attr", "options", "error", "instance", "require_cell", "__commonJSMin", "exports", "module", "window", "factory", "getSize", "Cell", "elem", "parent", "proto", "side", "x", "marginProperty", "sideOffset", "adjustedX", "shift", "require_slide", "__commonJSMin", "exports", "module", "window", "factory", "Slide", "parent", "proto", "cell", "beginMargin", "endMargin", "lastCell", "lastMargin", "slideWidth", "require_animate", "__commonJSMin", "exports", "module", "window", "factory", "utils", "proto", "previousX", "_this", "x", "is3d", "translateX", "firstSlide", "positionX", "progress", "position", "isResting", "beforeGap", "afterGap", "cells", "gap", "shift", "i", "cell", "cellShift", "force", "dragVelocity", "dragForce", "dragDown", "distance", "require_flickity", "__commonJSMin", "exports", "module", "window", "factory", "EvEmitter", "getSize", "utils", "Cell", "Slide", "animatePrototype", "_Flickity", "jQuery", "getComputedStyle", "console", "moveElements", "elems", "toElem", "GUID", "instances", "Flickity", "element", "options", "queryElement", "instance", "proto", "id", "eventName", "listener", "method", "opts", "cellElems", "slider", "cells", "cellElem", "index", "cellX", "startCell", "len", "i", "cell", "slide", "isOriginLeft", "nextMargin", "canCellFit", "slideWidth", "groupCells", "number", "percentMatch", "percent", "cellAlignShorthands", "shorthand", "height", "gapX", "cellIndex", "increment", "isRightToLeft", "beginMargin", "endMargin", "contentWidth", "isContentSmaller", "beginBound", "endBound", "type", "event", "args", "emitArgs", "$event", "jQEvent", "isWrap", "isInstant", "prevIndex", "isWrapping", "wrapIndex", "delta", "backWrapDelta", "forewardWrapDelta", "initialIndex", "value", "elem", "adjCount", "slideIndex", "selector", "selectedElement", "watchOption", "afterContent", "isNotFocused", "handler", "leftMethod", "rightMethod", "prevScrollY", "jq", "require_unipointer", "__commonJSMin", "exports", "module", "window", "factory", "EvEmitter", "noop", "Unipointer", "proto", "elem", "isAdd", "bindMethod", "startEvent", "event", "method", "touches", "i", "touch", "button", "pointer", "postStartEvents", "events", "eventName", "require_unidragger", "__commonJSMin", "exports", "module", "window", "factory", "Unipointer", "Unidragger", "proto", "isAdd", "bindMethod", "touchAction", "i", "handle", "event", "pointer", "isOkay", "cursorNodes", "clickTypes", "isCursorNode", "isClickType", "focused", "canBlur", "moveVector", "require_drag", "__commonJSMin", "exports", "module", "window", "factory", "Flickity", "Unidragger", "utils", "proto", "event", "pointer", "isOkay", "getScrollPosition", "focusNodes", "isFocusNode", "isTouchStart", "isTouchPointer", "moveVector", "direction", "dragX", "originBound", "endBound", "index", "restingX", "distance", "positiveResting", "negativeResting", "increment", "minDistance", "condition", "dist", "minDist", "x", "len", "isWrapAround", "slideIndex", "slide", "wrap", "delta", "clickedCell", "cellElem", "cellIndex", "scroll", "scrollMoveX", "scrollMoveY", "require_prev_next_button", "__commonJSMin", "exports", "module", "window", "factory", "Flickity", "Unipointer", "utils", "svgURI", "PrevNextButton", "direction", "parent", "leftDirection", "element", "svg", "path", "pathMovements", "getArrowMovements", "shape", "method", "slides", "lastIndex", "boundIndex", "proto", "require_page_dots", "__commonJSMin", "exports", "module", "window", "factory", "Flickity", "Unipointer", "utils", "PageDots", "parent", "delta", "count", "fragment", "newDots", "length", "max", "i", "dot", "removeDots", "event", "target", "index", "proto", "require_player", "__commonJSMin", "exports", "module", "window", "factory", "EvEmitter", "utils", "Flickity", "Player", "parent", "isPageHidden", "time", "_this", "proto", "require_add_remove_cell", "__commonJSMin", "exports", "module", "window", "factory", "Flickity", "utils", "getCellsFragment", "cells", "fragment", "cell", "proto", "elems", "index", "len", "isAppend", "insertCellElement", "endCells", "minCellIndex", "elem", "changedCellIndex", "isPositioningSlider", "prevSelectedElem", "require_lazyload", "__commonJSMin", "exports", "module", "window", "factory", "Flickity", "utils", "proto", "lazyLoad", "adjCount", "cellElems", "lazyImages", "cellElem", "lazyCellImages", "getCellLazyImages", "img", "LazyLoader", "lazyloadAttr", "srcAttr", "srcsetAttr", "lazySelector", "imgs", "flickity", "src", "srcset", "event", "className", "cell", "require_js", "__commonJSMin", "exports", "module", "window", "factory", "Flickity", "BuiltInHTMLElement", "wrapperForTheName", "prototype", "submitter", "validateSubmitter", "form", "raise", "errorConstructor", "message", "name", "submittersByForm", "findSubmitterFromClickTarget", "target", "element", "candidate", "clickCaptured", "event", "FrameLoadingStyle", "FrameElement", "_FrameElement", "value", "frameLoadingStyleFromString", "_a", "_b", "style", "expandURL", "locatable", "getAnchor", "url", "anchorMatch", "getAction", "action", "getExtension", "getLastPathComponent", "isHTML", "isPrefixedBy", "baseURL", "prefix", "getPrefix", "locationIsVisitable", "location", "rootLocation", "getRequestURL", "anchor", "toCacheKey", "urlsAreEqual", "left", "right", "getPathComponents", "addTrailingSlash", "FetchResponse", "response", "activateScriptElement", "createdScriptElement", "cspNonce", "getMetaContent", "copyElementAttributes", "destinationElement", "sourceElement", "createDocumentFragment", "html", "template", "dispatch", "eventName", "cancelable", "detail", "nextAnimationFrame", "resolve", "nextEventLoopTick", "nextMicrotask", "parseHTMLDocument", "unindent", "strings", "values", "lines", "interpolate", "match", "indent", "line", "result", "string", "i", "uuid", "_", "getAttribute", "attributeName", "elements", "hasAttribute", "markAsBusy", "clearBusyState", "waitForLoad", "timeoutInMilliseconds", "onComplete", "getHistoryMethodForAction", "isAction", "getVisitAction", "getMetaElement", "setMetaContent", "content", "findClosestRecursively", "selector", "FetchMethod", "fetchMethodFromString", "method", "FetchRequest", "delegate", "body", "_value", "fetchOptions", "error", "fetchResponse", "mimeType", "requestInterception", "AppearanceObserver", "entries", "lastEntry", "StreamMessage", "fragment", "importStreamElements", "streamElement", "inertScriptElement", "FormSubmissionState", "FormEnctype", "formEnctypeFromString", "encoding", "FormSubmission", "_FormSubmission", "_element", "_submitter", "formElement", "mustRedirect", "buildFormData", "mergeFormDataEntries", "formElementAction", "initialized", "requesting", "confirmationMessage", "stopping", "stopped", "request", "token", "getCookieValue", "_request", "responseSucceededWithoutRedirect", "input", "formData", "cookieName", "cookie", "searchParams", "Snapshot", "inertDisabledOrHidden", "queryPermanentElementsAll", "id", "getPermanentElementById", "snapshot", "permanentElementMap", "currentPermanentElement", "newPermanentElement", "node", "FormSubmitObserver", "eventTarget", "submissionDoesNotDismissDialog", "submissionDoesNotTargetIFrame", "View", "x", "y", "renderer", "isPreview", "shouldRender", "renderInterception", "options", "reason", "FrameView", "LinkInterceptor", "_event", "LinkClickObserver", "link", "doesNotTargetIFrame", "FormLinkClickObserver", "originalEvent", "type", "turboFrame", "turboAction", "turboConfirm", "Bardo", "callback", "bardo", "permanentElement", "placeholder", "createPlaceholderForPermanentElement", "clone", "Renderer", "currentSnapshot", "newSnapshot", "renderElement", "willRender", "reject", "elementIsFocusable", "FrameRenderer", "currentElement", "newElement", "destinationRange", "frameElement", "sourceRange", "block", "readScrollLogicalPosition", "behavior", "readScrollBehavior", "activatedScriptElement", "defaultValue", "ProgressBar", "_ProgressBar", "HeadSnapshot", "elementIsNoscript", "elementWithoutNonce", "outerHTML", "details", "elementType", "elementIsTracked", "matchedType", "tracked", "elementIsMetaElementWithName", "elementIsScript", "elementIsStylesheet", "tagName", "PageSnapshot", "_PageSnapshot", "head", "headSnapshot", "clonedElement", "selectElements", "clonedSelectElements", "index", "source", "option", "clonedPasswordInput", "root", "TimingMetric", "VisitState", "defaultOptions", "SystemStatusCode", "Visit", "restorationIdentifier", "historyChanged", "referrer", "snapshotHTML", "visitCachedSnapshot", "updateHistory", "shouldCacheSnapshot", "acceptsStreamResponse", "actionForHistory", "statusCode", "isSuccessful", "responseHTML", "_response", "redirected", "_error", "scrollPosition", "metric", "BrowserAdapter", "session", "visit", "_visit", "_formSubmission", "CacheObserver", "FrameRedirector", "_location", "frame", "meta", "History", "turbo", "state", "additionalData", "restorationData", "Navigator", "formSubmission", "visitOptions", "currentAnchor", "isRestorationToTop", "oldURL", "newURL", "PageStage", "PageObserver", "readyState", "ScrollObserver", "position", "StreamMessageRenderer", "getPermanentElementMapForFragment", "permanentElementsInDocument", "permanentElementInDocument", "elementInStream", "StreamObserver", "fetchResponseFromEvent", "fetchResponseIsStream", "ErrorRenderer", "documentElement", "replaceableElement", "parentNode", "PageRenderer", "mergedHeadElements", "newStylesheetElements", "loadingElements", "newHeadElements", "elementList", "SnapshotCache", "size", "key", "PageView", "cachedSnapshot", "Preloader", "responseText", "Session", "adapter", "delay", "mode", "extendURLWithDeprecatedProperties", "defaultPrevented", "render", "_snapshot", "_isPreview", "ev", "newBody", "timing", "submitterIsNavigatable", "container", "withinFrame", "deprecatedLocationPropertyDescriptors", "Cache", "StreamActions", "e", "targetElement", "cache", "navigator$1", "start", "registerAdapter", "connectStreamSource", "disconnectStreamSource", "renderStreamMessage", "clearCache", "setProgressBarDelay", "setConfirmMethod", "confirmMethod", "setFormMode", "Turbo", "TurboFrameMissingError", "FrameController", "_fetchResponse", "src", "document", "fetchRequest", "newFrame", "_newElement", "newFrameElement", "pageSnapshot", "wrapped", "getFrameElementById", "activateElement", "sourceURL", "currentURL", "StreamElement", "_StreamElement", "c", "existingChildren", "newChildrenIds", "actionFunction", "StreamSourceElement", "consumer", "getConsumer", "setConsumer", "createConsumer", "newConsumer", "subscribeTo", "channel", "mixin", "subscriptions", "walk", "obj", "acc", "key", "camel", "m", "x", "TurboCableStreamSourceElement", "connectStreamSource", "subscribeTo", "disconnectStreamSource", "data", "event", "channel", "signed_stream_name", "walk", "encodeMethodIntoRequestBody", "event", "form", "fetchOptions", "submitter", "body", "isBodyInit", "method", "determineFetchMethod", "formMethod", "determineFormMethod", "overrideMethod", "encodeMethodIntoRequestBody", "EventListener", "eventTarget", "eventName", "eventOptions", "binding", "event", "extendedEvent", "extendEvent", "left", "right", "leftIndex", "rightIndex", "stopImmediatePropagation", "Dispatcher", "application", "eventListener", "listeners", "map", "clearEventListeners", "error", "message", "detail", "eventListenerMap", "cacheKey", "parts", "key", "defaultActionDescriptorFilters", "value", "element", "descriptorPattern", "parseActionDescriptorString", "descriptorString", "matches", "keyFilter", "parseEventTarget", "parseEventOptions", "eventTargetName", "options", "token", "stringifyEventTarget", "camelize", "_", "char", "namespaceCamelize", "capitalize", "dasherize", "tokenize", "isSomething", "object", "hasProperty", "property", "allModifiers", "Action", "index", "descriptor", "schema", "getDefaultEventNameForElement", "eventFilter", "filters", "standardFilter", "params", "pattern", "name", "match", "typecast", "meta", "ctrl", "alt", "shift", "modifier", "defaultEventNames", "e", "tagName", "Binding", "context", "action", "actionEvent", "method", "actionDescriptorFilters", "controller", "passes", "filter", "target", "currentTarget", "identifier", "ElementObserver", "delegate", "mutations", "callback", "mutation", "attributeName", "nodes", "node", "tree", "processor", "AttributeObserver", "add", "fetch", "del", "prune", "values", "Multimap", "set", "size", "_key", "_values", "SelectorObserver", "element", "selector", "delegate", "details", "ElementObserver", "Multimap", "callback", "matches", "tree", "match", "selectors", "_attributeName", "matchedBefore", "StringMapObserver", "mutations", "attributeName", "mutation", "oldValue", "key", "value", "attribute", "TokenListObserver", "AttributeObserver", "unmatchedTokens", "matchedTokens", "tokens", "token", "previousTokens", "currentTokens", "firstDifferingIndex", "zip", "previousToken", "currentToken", "tokensAreEqual", "tokenString", "parseTokenString", "content", "index", "left", "right", "length", "_", "ValueListObserver", "parseResult", "valuesByToken", "error", "BindingObserver", "context", "action", "binding", "Binding", "Action", "ValueObserver", "receiver", "descriptor", "name", "defaultValue", "writer", "rawValue", "rawOldValue", "changedMethodName", "changedMethod", "valueDescriptorMap", "descriptors", "hasMethodName", "capitalize", "TargetObserver", "_a", "readInheritableStaticArrayValues", "constructor", "propertyName", "ancestors", "getAncestorsForConstructor", "values", "getOwnStaticArrayValues", "readInheritableStaticObjectPairs", "pairs", "getOwnStaticObjectPairs", "definition", "OutletObserver", "outletName", "observer", "_selector", "outlet", "hasOutlet", "hasOutletController", "_element", "selectorObserver", "attributeObserver", "dependencies", "module", "identifiers", "Context", "scope", "functionName", "detail", "identifier", "controller", "message", "namespaceCamelize", "methodName", "args", "bless", "shadow", "getBlessedProperties", "properties", "shadowConstructor", "extend", "shadowProperties", "getShadowProperties", "blessedProperties", "blessing", "prototype", "getOwnKeys", "getShadowedDescriptor", "shadowingDescriptor", "object", "extendWithReflect", "extended", "testReflectExtension", "b", "blessDefinition", "Module", "application", "ClassMap", "tokenize", "DataMap", "dasherize", "Guide", "logger", "warnedKeys", "attributeValueContainsToken", "TargetSet", "targetName", "targetNames", "target", "targets", "targetDescriptor", "revisedAttributeName", "OutletSet", "controllerElement", "outletNames", "outlets", "controllerAttribute", "Scope", "_Scope", "schema", "ScopeObserver", "scopesByIdentifier", "referenceCount", "Router", "contexts", "afterLoad", "defaultSchema", "objectFromEntries", "c", "n", "array", "memo", "k", "v", "Application", "Dispatcher", "defaultActionDescriptorFilters", "domReady", "controllerConstructor", "filter", "head", "rest", "resolve", "ClassPropertiesBlessing", "classDefinition", "propertiesForClassDefinition", "classes", "OutletPropertiesBlessing", "outletDefinition", "propertiesForOutletDefinition", "getOutletController", "getControllerAndEnsureConnectedScope", "outletController", "camelizedName", "outletElement", "TargetPropertiesBlessing", "targetDefinition", "propertiesForTargetDefinition", "ValuePropertiesBlessing", "valueDefinitionPairs", "propertyDescriptorMap", "result", "valueDefinitionPair", "valueDescriptor", "parseValueDefinitionPair", "propertiesForValueDefinitionPair", "read", "write", "typeDefinition", "valueDescriptorForTokenAndTypeDefinition", "parseValueTypeConstant", "constant", "parseValueTypeDefault", "parseValueTypeObject", "payload", "typeObject", "hasType", "isSomething", "hasDefault", "fullObject", "onlyType", "onlyDefault", "typeFromObject", "typeFromDefaultValue", "propertyPath", "parseValueTypeDefinition", "typeFromConstant", "type", "defaultValueForDefinition", "defaultValuesByType", "hasProperty", "constantFromType", "camelize", "readers", "writers", "writeString", "writeJSON", "Controller", "_identifier", "_application", "eventName", "prefix", "bubbles", "cancelable", "event", "application", "Application", "chars", "decode83", "str", "start", "end", "value", "pow", "PI", "d", "e", "sRGBToLinear", "linearTosRGB", "v", "LUT_SIZE", "sRGBLookup", "i", "fastLinearTosRGB", "signSqr", "x", "fastCos", "cos", "getBlurHashAverageColor", "blurHash", "val", "decodeBlurHash", "width", "height", "punch", "sizeFlag", "numX", "numY", "size", "j", "y", "r", "g", "b", "basis", "basisY", "colorIndex", "pixelIndex", "maximumValue", "colors", "averageColor", "cosinesY", "cosinesX", "bytesPerRow", "pixels", "u", "lightness_controller_default", "Controller", "bottom", "decodeBlurHash", "r", "g", "b", "a", "application", "lightness_controller_default", "filters_component_exports", "brand_component_exports", "button_component_exports", "button_group_component_exports", "section_component_exports", "tile_component_exports", "actions_component_exports", "content_editor_component_exports", "__export", "Controller", "OrderedMap", "content", "key", "i", "found", "value", "newKey", "self", "place", "without", "f", "map", "result", "prop", "dist_default", "findDiffStart", "a", "b", "pos", "i", "childA", "childB", "tA", "tB", "j", "surrogateHigh", "surrogateLow", "inner", "findDiffEnd", "posA", "posB", "iA", "iB", "size", "ch", "Fragment", "_Fragment", "content", "from", "to", "f", "nodeStart", "parent", "child", "end", "start", "blockSeparator", "leafText", "text", "first", "node", "nodeText", "other", "last", "result", "index", "current", "copy", "found", "p", "otherPos", "retIndex", "curPos", "cur", "n", "schema", "value", "array", "joined", "nodes", "offset", "compareDeep", "Mark", "_Mark", "type", "attrs", "set", "placed", "obj", "_", "json", "marks", "ReplaceError", "Slice", "_Slice", "openStart", "openEnd", "fragment", "insertInto", "removeRange", "openIsolating", "indexTo", "offsetTo", "dist", "insert", "replace", "$from", "$to", "slice", "replaceOuter", "depth", "close", "prepareSliceForReplace", "replaceThreeWay", "replaceTwoWay", "checkJoin", "main", "sub", "joinable", "$before", "$after", "addNode", "target", "addRange", "$start", "$end", "startIndex", "endIndex", "$along", "extra", "ResolvedPos", "_ResolvedPos", "path", "parentOffset", "val", "dOff", "tmp", "after", "next", "pred", "d", "NodeRange", "str", "doc", "rem", "cache", "resolveCache", "elt", "ResolveCache", "resolveCacheSize", "emptyAttrs", "Node", "_Node", "startPos", "includeParents", "name", "wrapMarks", "match", "replacement", "one", "two", "checkAttrs", "mark", "m", "v8InternHack", "stack", "s", "TextNode", "_TextNode", "base", "values", "attr", "ContentMatch", "_ContentMatch", "validEnd", "string", "nodeTypes", "stream", "TokenStream", "expr", "parseExpr", "dfa", "nfa", "checkForDeadEnds", "frag", "toEnd", "seen", "search", "types", "finished", "tp", "computed", "active", "scan", "out", "tok", "exprs", "parseExprSeq", "parseExprSubscript", "parseExprAtom", "parseExprRange", "parseNum", "min", "max", "resolveName", "typeName", "connect", "compile", "edge", "term", "edges", "loop", "cmp", "nullFrom", "labeled", "explore", "states", "state", "work", "dead", "defaultAttrs", "defaults", "attrName", "computeAttrs", "built", "given", "initAttrs", "Attribute", "NodeType", "_NodeType", "spec", "group", "before", "matched", "markType", "topType", "validateType", "options", "MarkType", "_MarkType", "rank", "Schema", "instanceSpec", "prop", "dist_default", "contentExprCache", "contentExpr", "markExpr", "gatherMarks", "excl", "ok", "isTagRule", "rule", "isStyleRule", "DOMParser", "_DOMParser", "rules", "matchedStyles", "r", "dom", "context", "ParseContext", "matches", "style", "priority", "blockTags", "ignoreTags", "listTags", "OPT_PRESERVE_WS", "OPT_PRESERVE_WS_FULL", "OPT_OPEN_LEFT", "wsOptionsFor", "preserveWhitespace", "NodeContext", "solid", "fill", "wrap", "parser", "isOpen", "topNode", "topContext", "topOptions", "top", "preserveWS", "lines", "nodeBefore", "domNodeBefore", "matchAfter", "outerWS", "ruleID", "normalizeList", "sync", "oldNeedsBlock", "innerMarks", "styles", "continueAfter", "nodeType", "startIn", "contentDOM", "cautious", "route", "penalty", "cx", "block", "nodeMarks", "markMayApply", "applyMarks", "textNode", "parts", "option", "useRoot", "minDepth", "part", "$context", "deflt", "prevItem", "selector", "DOMSerializer", "_DOMSerializer", "keep", "rendered", "add", "markDOM", "renderSpec", "inline", "toDOM", "structure", "xmlNS", "blockArraysIn", "gatherToDOM", "suspiciousAttributeCache", "suspiciousAttributes", "suspiciousAttributesInner", "tagName", "suspicious", "space", "innerContent", "lower16", "factor16", "makeRecover", "index", "offset", "recoverIndex", "value", "recoverOffset", "DEL_BEFORE", "DEL_AFTER", "DEL_ACROSS", "DEL_SIDE", "MapResult", "pos", "delInfo", "recover", "StepMap", "_StepMap", "ranges", "inverted", "diff", "i", "assoc", "simple", "oldIndex", "newIndex", "start", "oldSize", "newSize", "end", "side", "result", "del", "f", "oldStart", "newStart", "n", "Mapping", "_Mapping", "maps", "mirror", "from", "to", "map", "mirrors", "mapping", "startSize", "mirr", "m", "totalSize", "inverse", "corr", "stepsByID", "Step", "other", "schema", "json", "type", "id", "stepClass", "StepResult", "_StepResult", "doc", "failed", "message", "slice", "e", "ReplaceError", "mapFragment", "fragment", "parent", "mapped", "child", "Fragment", "AddMarkStep", "_AddMarkStep", "mark", "oldSlice", "$from", "Slice", "node", "steps", "added", "Mark", "pushMarkStep", "RemoveMarkStep", "MarkSetStep", "_RemoveMarkStep", "cls", "target", "last", "_MarkSetStep", "step", "s", "AddNodeMarkStep", "_AddNodeMarkStep", "updated", "newSet", "RemoveNodeMarkStep", "_RemoveNodeMarkStep", "ReplaceStep", "_ReplaceStep", "structure", "contentBetween", "ReplaceAroundStep", "_ReplaceAroundStep", "gapFrom", "gapTo", "insert", "gap", "inserted", "dist", "depth", "next", "addMark", "tr", "marks", "removeMark", "matched", "toRemove", "MarkType", "set", "found", "style", "j", "clearIncompatible", "parentType", "match", "clearNewlines", "replSteps", "cur", "allowed", "newline", "fill", "canCut", "liftTarget", "range", "content", "contentBefore", "contentAfter", "endIndex", "lift", "$to", "gapStart", "gapEnd", "before", "openStart", "d", "splitting", "after", "openEnd", "findWrapping", "nodeType", "attrs", "innerRange", "around", "findWrappingOutside", "inner", "findWrappingInside", "withAttrs", "startIndex", "outer", "inside", "innerMatch", "wrap", "wrappers", "setBlockType", "mapFrom", "attrsHere", "canChangeType", "convertNewlines", "pre", "supportLinebreak", "replaceLinebreaks", "startM", "endM", "replaceNewlines", "$pos", "setNodeMarkup", "newNode", "canSplit", "typesAfter", "base", "innerType", "rest", "overrideChild", "baseType", "split", "typeAfter", "canJoin", "joinable", "canAppendWithSubstitutedLinebreaks", "a", "b", "linebreakReplacement", "joinPoint", "dir", "join", "$before", "beforeType", "$after", "$full", "insertPoint", "dropPoint", "pass", "bias", "insertPos", "fits", "wrapping", "replaceStep", "fitsTrivially", "Fitter", "unplaced", "fit", "moveInline", "placedSize", "startDepth", "sliceDepth", "contentAt", "first", "frontierDepth", "inject", "maxOpen", "openAtEnd", "dropFromFragment", "taken", "add", "openEndCount", "matches", "closeNodeStart", "toEnd", "addToFragment", "top", "level", "contentAfterFits", "scan", "dropInner", "close", "count", "frag", "open", "invalidMarks", "definesContent", "ch", "replaceRange", "targetDepths", "coveredDepths", "preferredTarget", "spec", "preferredTargetIndex", "leftNodes", "preferredDepth", "leftNode", "def", "openDepth", "targetDepth", "expand", "closeFragment", "startSteps", "oldOpen", "newOpen", "replaceRangeWith", "point", "deleteRange", "shared", "isolated", "covered", "minDepth", "AttrStep", "_AttrStep", "attr", "name", "DocAttrStep", "_DocAttrStep", "TransformError", "err", "Transform", "_f", "_t", "fromB", "toB", "classesById", "Selection", "$anchor", "$head", "ranges", "SelectionRange", "tr", "content", "Slice", "lastNode", "lastParent", "i", "mapFrom", "$from", "$to", "mapping", "selectionToInsertionEnd", "node", "from", "to", "$pos", "dir", "textOnly", "inner", "TextSelection", "findSelectionIn", "depth", "found", "bias", "AllSelection", "doc", "json", "cls", "id", "selectionClass", "warnedAboutTextSelection", "checkTextSelection", "_TextSelection", "marks", "other", "TextBookmark", "anchor", "head", "dPos", "_TextBookmark", "NodeSelection", "_NodeSelection", "$end", "deleted", "pos", "Fragment", "NodeBookmark", "_NodeBookmark", "_AllSelection", "sel", "AllBookmark", "index", "text", "child", "startLen", "last", "step", "ReplaceStep", "ReplaceAroundStep", "map", "end", "_from", "_to", "_newFrom", "newTo", "UPDATED_SEL", "UPDATED_MARKS", "UPDATED_SCROLL", "Transaction", "Transform", "state", "selection", "Mark", "mark", "time", "slice", "inheritMarks", "schema", "key", "value", "_", "bind", "f", "self", "FieldDesc", "name", "desc", "baseFields", "config", "instance", "_marks", "_old", "prev", "Configuration", "plugins", "plugin", "EditorState", "_EditorState", "ignore", "rootTr", "trs", "newState", "seen", "haveNew", "n", "oldState", "j", "newInstance", "fields", "field", "$config", "pluginFields", "result", "m", "prop", "Node", "bindProps", "obj", "target", "val", "Plugin", "spec", "createKey", "keys", "PluginKey", "domIndex", "node", "index", "parentNode", "parent", "reusedRange", "textRange", "from", "to", "range", "clearReusedRange", "isEquivalentPosition", "off", "targetNode", "targetOff", "scanFor", "atomElements", "dir", "_a", "nodeSize", "isElt", "hasBlockDesc", "child", "isText", "contains", "textNodeBefore$1", "offset", "textNodeAfter$1", "isOnEdge", "atStart", "atEnd", "dom", "desc", "cur", "selectionCollapsed", "domSel", "keyEvent", "keyCode", "key", "event", "deepActiveElement", "doc", "elt", "caretFromPoint", "x", "y", "pos", "nav", "agent", "ie_edge", "ie_upto10", "ie_11up", "ie", "ie_version", "gecko", "_chrome", "chrome", "chrome_version", "safari", "ios", "mac", "windows", "android", "webkit", "webkit_version", "windowRect", "vp", "getSide", "value", "side", "clientRect", "rect", "scaleX", "scaleY", "scrollRectIntoView", "view", "startDOM", "nonZero", "scrollThreshold", "scrollMargin", "atTop", "bounding", "moveX", "moveY", "startX", "startY", "dX", "dY", "storeScrollPos", "refDOM", "refTop", "localRect", "scrollStack", "stack", "resetScrollPos", "newRefTop", "restoreScrollStack", "dTop", "top", "left", "preventScrollSupported", "focusPreventScroll", "stored", "findOffsetInNode", "coords", "closest", "dxClosest", "coordsClosest", "rowBot", "rowTop", "firstBelow", "coordsBelow", "childIndex", "rects", "i", "dx", "findOffsetInText", "len", "result", "singleRect", "inRect", "targetKludge", "posFromElement", "bias", "posFromCaret", "outsideBlock", "sawBlock", "elementFromPoint", "element", "box", "startI", "j", "posAtCoords", "caret", "p", "next", "prev", "target", "first", "BIDI", "coordsAtPos", "atom", "supportEmptyRange", "rectBefore", "rectAfter", "flattenV", "takeSide", "before", "flattenH", "after", "withFlushedState", "state", "f", "viewState", "active", "endOfTextblockVertical", "sel", "$pos", "nearest", "boxes", "maybeRTL", "endOfTextblockHorizontal", "$head", "oldNode", "oldOff", "anchorNode", "anchorOffset", "oldBidiLevel", "parentDOM", "newNode", "newOff", "cachedState", "cachedDir", "cachedResult", "endOfTextblock", "NOT_DIRTY", "CHILD_DIRTY", "CONTENT_DIRTY", "NODE_DIRTY", "ViewDesc", "children", "contentDOM", "widget", "mark", "outerDeco", "innerDeco", "nodeName", "addedNodes", "size", "domBefore", "domAfter", "rel", "n", "search", "onlyNodes", "nodeDOM", "scan", "end", "inner", "curPos", "BufferHackViewDesc", "WidgetViewDesc", "enter", "base", "fromOffset", "toOffset", "childBase", "anchor", "head", "force", "anchorDOM", "headDOM", "selRange", "brKludge", "domSelExtended", "tmp", "mutation", "startInside", "endInside", "level", "dirty", "text", "self", "stop", "CompositionViewDesc", "textDOM", "mut", "MarkViewDesc", "_MarkViewDesc", "spec", "inline", "custom", "DOMSerializer", "copy", "nodes", "replaceNodes", "NodeViewDesc", "_NodeViewDesc", "descObj", "applyOuterDeco", "CustomNodeViewDesc", "TextViewDesc", "rule", "found", "Fragment", "sameOuterDeco", "composition", "localComposition", "compositionInChild", "updater", "ViewTreeUpdater", "addBuffers", "atBufferPos", "iterDeco", "insideNode", "Mark", "compIndex", "renderDescs", "iosHacks", "TextSelection", "textNode", "textPos", "findTextInFragment", "topNode", "needsWrap", "oldDOM", "patchOuterDeco", "computeOuterDeco", "docViewDesc", "docView", "_TextViewDesc", "skip", "_view", "descs", "written", "childDOM", "rm", "OuterDecoLevel", "noDeco", "attrs", "name", "val", "outerDOM", "prevComputed", "curComputed", "curDOM", "deco", "patchAttributes", "prevList", "curList", "prop", "m", "a", "b", "lock", "preMatch", "start", "marks", "parentIndex", "keep", "depth", "maxKeep", "scanTo", "markDesc", "targetDesc", "e", "domNode", "nextDOM", "updated", "locked", "wrapper", "ch", "lastChild", "hack", "frag", "parentDesc", "curDesc", "descI", "fI", "matched", "matches", "outer", "compareSide", "onWidget", "onNode", "locals", "decoIndex", "restNode", "widgets", "cutAt", "d", "oldCSS", "childStart", "str", "replacement", "selectionFromDOM", "origin", "nearestDesc", "inWidget", "selection", "NodeSelection", "Selection", "min", "max", "$anchor", "selectionBetween", "editorOwnsSelection", "hasSelection", "selectionToDOM", "syncNodeSelection", "mouseDown", "curSel", "selectCursorWrapper", "resetEditableFrom", "resetEditableTo", "brokenSelectBetweenUneditable", "temporarilyEditableNear", "resetEditable", "removeClassOnSelectionChange", "setEditable", "img", "clearNodeSelection", "hasFocusAndSelection", "anchorInRightPlace", "moveSelectionBlock", "$side", "$start", "apply", "selectHorizontally", "mods", "$newHead", "nodePos", "isIgnorable", "skipIgnoredNodes", "skipIgnoredNodesBefore", "skipIgnoredNodesAfter", "moveNode", "moveOffset", "isBlockNode", "setSelFocus", "textNodeAfter", "textNodeBefore", "findDirection", "mid", "block", "selectVertically", "$from", "$to", "beyond", "AllSelection", "stopNativeHorizontalDelete", "empty", "nextNode", "tr", "switchEditable", "safariDownArrowBug", "focusNode", "focusOffset", "getMods", "captureKeyDown", "code", "serializeForClipboard", "slice", "context", "content", "openStart", "openEnd", "serializer", "detachedDoc", "wrap", "firstChild", "wrappers", "wrapMap", "parseFromClipboard", "html", "plainText", "$context", "inCode", "asText", "Slice", "parsed", "schema", "readHTML", "restoreReplacedSpaces", "contextNode", "sliceData", "DOMParser", "inlineParents", "addContext", "closeSlice", "normalizeSiblings", "fragment", "match", "lastWrap", "inLast", "addToSibling", "closeRight", "wrapped", "withWrappers", "sibling", "fill", "closeRange", "_policy", "maybeWrapTrusted", "trustedTypes", "s", "metas", "firstTag", "style", "k", "array", "type", "handlers", "editHandlers", "passiveHandlers", "InputState", "initInput", "handler", "eventBelongsToView", "runCustomHandler", "ensureListeners", "setSelectionOrigin", "destroyInput", "currentHandlers", "dispatchEvent", "dispatchKey", "input", "_event", "inOrNearComposition", "now", "deflt", "eventCoords", "isNear", "click", "dy", "runHandlerOnContext", "propName", "inside", "updateSelection", "selectClickedLeaf", "selectClickedNode", "selectedNode", "selectAt", "handleSingleClick", "selectNode", "handleDoubleClick", "handleTripleClick", "defaultTripleClick", "selectionForTripleClick", "TripleClickDrag", "selectNodes", "forceDOMFlush", "endComposition", "selectNodeModifier", "flushed", "LeftMouseDown", "MouseDown", "targetPos", "startSelection", "timeoutComposition", "selectionBeforeUneditable", "scheduleComposeEnd", "delay", "clearComposition", "findCompositionNode", "textBefore", "textAfter", "descAfter", "lastChanged", "descBefore", "restarting", "captureCopy", "brokenClipboardAPI", "cut", "data", "sliceSingleNode", "capturePaste", "plain", "doPaste", "preferPlain", "singleNode", "getText", "clipboardData", "uris", "Dragging", "move", "dragCopyModifier", "dragMoves", "test", "draggedSlice", "dragging", "_", "handleDrop", "eventPos", "$mouse", "insertPos", "dropPoint", "isNode", "beforeInsert", "_from", "_to", "_newFrom", "newTo", "startSel", "newSel", "domChangeCount", "$cursor", "compareObjs", "FragmentCursor", "WidgetType", "_WidgetType", "toDOM", "noSpec", "mapping", "span", "oldOffset", "deleted", "Decoration", "other", "InlineType", "_InlineType", "NodeType", "_NodeType", "cursor", "_Decoration", "none", "DecorationSet", "_DecorationSet", "local", "decorations", "buildTree", "predicate", "childOff", "options", "newLocal", "mapped", "mapChildren", "byPos", "childNode", "childOffset", "baseOffset", "takeSpansForNode", "moveSpans", "withoutNulls", "removed", "dec", "localSet", "DecorationGroup", "removeOverlap", "_DecorationGroup", "members", "mappedDecos", "member", "sorted", "r", "oldChildren", "moved", "oldStart", "oldEnd", "newStart", "newEnd", "dSize", "mustRebuild", "fromLocal", "toLocal", "mapAndGatherRemainingDecorations", "built", "spans", "gather", "set", "hasNulls", "localStart", "subtree", "working", "insertAhead", "viewDecorations", "observeOptions", "useCharData", "SelectionState", "DOMObserver", "handleDOMChange", "mutations", "take", "ancestors", "container", "typeOver", "added", "brs", "br", "blockParent", "readSel", "checkCSS", "fixUpBadSafariComposition", "previousSibling", "nextSibling", "cssChecked", "cssCheckWarned", "rangeToSelectionRange", "currentAnchor", "safariShadowSelectionRange", "read", "nextCell", "parseBetween", "from_", "to_", "find", "startDoc", "parser", "ruleFromNode", "isInline", "readDOMChange", "compositionID", "$before", "shared", "parse", "compare", "preferredPos", "preferredSide", "change", "findDiff", "resolveSelection", "$fromA", "inlineChange", "looksLikeEnter", "looksLikeBlockJoin", "chFrom", "chTo", "mkTr", "markChange", "isMarkChange", "parsedSel", "curMarks", "prevMarks", "update", "old", "$newStart", "$newEnd", "skipClosingAndOpening", "$next", "newTextlines", "newLeaves", "fromEnd", "mayOpen", "lenA", "lenB", "endA", "endB", "adjust", "EditorView", "place", "props", "InputState", "checkStateComponent", "getEditable", "updateCursorWrapper", "buildNodeViews", "docViewDesc", "computeDocDeco", "viewDecorations", "DOMObserver", "from", "to", "typeOver", "added", "readDOMChange", "initInput", "prev", "name", "ensureListeners", "prevProps", "updated", "state", "_a", "redraw", "updateSel", "clearComposition", "pluginsChanged", "nodeViews", "changedNodeViews", "innerDeco", "outerDeco", "scroll", "updateDoc", "oldScrollPos", "storeScrollPos", "forceSelUpdate", "ie", "chrome", "selectionContextChanged", "chromeKludge", "findCompositionNode", "mouseDown", "anchorInRightPlace", "selectionToDOM", "syncNodeSelection", "resetScrollPos", "startDOM", "contains", "f", "NodeSelection", "target", "isElt", "scrollRectIntoView", "view", "prevState", "plugin", "pluginView", "dragging", "sel", "found", "movedPos", "Dragging", "propName", "prop", "value", "i", "plugins", "node", "focusPreventScroll", "cached", "search", "coords", "posAtCoords", "pos", "side", "coordsAtPos", "desc", "offset", "bias", "dir", "endOfTextblock", "html", "event", "doPaste", "text", "slice", "serializeForClipboard", "destroyInput", "clearReusedRange", "dispatchEvent", "safari", "deepActiveElement", "safariShadowSelectionRange", "tr", "dispatchTransaction", "attrs", "attr", "Decoration", "dom", "sel1", "sel2", "depth", "result", "add", "obj", "a", "b", "nA", "nB", "_", "base", "shift", "mac", "ie", "i", "code", "keyName", "event", "ignoreKey", "name", "mac", "windows", "normalizeKeyName", "name", "parts", "result", "alt", "ctrl", "shift", "meta", "i", "mod", "normalize", "map", "copy", "prop", "modifiers", "event", "keymap", "bindings", "Plugin", "keydownHandler", "view", "keyName", "baseName", "direct", "noShift", "base", "fromCode", "deleteSelection", "state", "dispatch", "atBlockStart", "view", "$cursor", "joinBackward", "$cut", "findCutBefore", "range", "target", "liftTarget", "before", "deleteBarrier", "textblockAt", "NodeSelection", "depth", "delStep", "replaceStep", "Slice", "tr", "Selection", "joinTextblockBackward", "joinTextblocksAround", "joinTextblockForward", "atBlockEnd", "findCutAfter", "beforeText", "beforePos", "child", "after", "afterText", "afterPos", "step", "ReplaceStep", "TextSelection", "node", "side", "only", "scan", "selectNodeBackward", "$head", "empty", "$pos", "i", "joinForward", "selectNodeForward", "parent", "joinUp", "sel", "nodeSel", "point", "canJoin", "joinPoint", "joinDown", "lift", "$from", "$to", "newlineInCode", "$anchor", "defaultBlockAt", "match", "type", "exitCode", "above", "pos", "createParagraphNear", "AllSelection", "liftEmptyBlock", "canSplit", "splitBlockAs", "splitNode", "mapFrom", "types", "splitDepth", "deflt", "atEnd", "atStart", "d", "splitType", "splitPos", "can", "mapping", "first", "$first", "splitBlock", "selectParentNode", "state", "dispatch", "$from", "to", "pos", "same", "NodeSelection", "selectAll", "AllSelection", "joinMaybeClear", "$pos", "before", "after", "index", "canJoin", "deleteBarrier", "$cut", "dir", "conn", "match", "isolated", "canDelAfter", "end", "wrap", "Fragment", "i", "tr", "ReplaceAroundStep", "Slice", "$joinAt", "selAfter", "Selection", "range", "target", "liftTarget", "textblockAt", "at", "afterText", "afterDepth", "selectTextblockSide", "side", "sel", "depth", "TextSelection", "selectTextblockStart", "selectTextblockEnd", "wrapIn", "nodeType", "attrs", "$to", "wrapping", "findWrapping", "setBlockType", "applicable", "from", "node", "chainCommands", "commands", "state", "dispatch", "view", "i", "backspace", "deleteSelection", "joinBackward", "selectNodeBackward", "del", "joinForward", "selectNodeForward", "pcBaseKeymap", "newlineInCode", "createParagraphNear", "liftEmptyBlock", "splitBlock", "exitCode", "selectAll", "macBaseKeymap", "selectTextblockStart", "selectTextblockEnd", "key", "mac", "wrapInList", "listType", "attrs", "state", "dispatch", "$from", "$to", "range", "tr", "wrapRangeInList", "doJoin", "outerRange", "doc", "$insert", "NodeRange", "wrap", "findWrapping", "doWrapInList", "wrappers", "joinBefore", "content", "Fragment", "i", "ReplaceAroundStep", "Slice", "found", "splitDepth", "splitPos", "parent", "e", "first", "canSplit", "isItem", "itemType", "type", "NodeType", "liftListItem", "itemType", "state", "dispatch", "$from", "$to", "range", "node", "isItem", "liftToOuterList", "liftOutOfList", "tr", "end", "endOfList", "ReplaceAroundStep", "Slice", "Fragment", "NodeRange", "target", "liftTarget", "$after", "canJoin", "list", "pos", "i", "e", "$start", "item", "atStart", "atEnd", "parent", "indexBefore", "start", "sinkListItem", "startIndex", "nodeBefore", "nestedBefore", "inner", "slice", "before", "after", "createChainableState", "config", "state", "transaction", "selection", "doc", "storedMarks", "CommandManager", "props", "rawCommands", "editor", "view", "tr", "name", "command", "args", "callback", "startTr", "shouldDispatch", "callbacks", "hasStartTransaction", "run", "chain", "dispatch", "EventEmitter", "event", "fn", "onceFn", "getExtensionField", "extension", "field", "context", "splitExtensions", "extensions", "baseExtensions", "nodeExtensions", "markExtensions", "getAttributesFromExtensions", "extensionAttributes", "nodeAndMarkExtensions", "defaultAttribute", "addGlobalAttributes", "globalAttribute", "type", "attribute", "addAttributes", "attributes", "mergedAttr", "getNodeType", "nameOrType", "schema", "mergeAttributes", "objects", "item", "items", "mergedAttributes", "key", "value", "valueClasses", "existingClasses", "insertClasses", "valueClass", "newStyles", "style", "existingStyles", "styleMap", "property", "val", "part", "getRenderedAttributes", "nodeOrMark", "isFunction", "callOrReturn", "isEmptyObject", "fromString", "injectExtensionAttributesToParseRule", "parseRule", "node", "oldAttributes", "newAttributes", "cleanUpSchemaItem", "data", "getSchemaByResolvedExtensions", "allAttributes", "topNode", "_a", "nodes", "extraNodeFields", "fields", "e", "extendNodeSchema", "extensionAttribute", "parseHTML", "renderHTML", "renderText", "marks", "extraMarkFields", "extendMarkSchema", "mark", "Schema", "getSchemaTypeByName", "isExtensionRulesEnabled", "enabled", "enabledExtension", "getHTMLFromFragment", "fragment", "documentFragment", "DOMSerializer", "container", "getTextContentFromNodes", "$from", "maxMatch", "textBefore", "sliceEndPos", "pos", "parent", "index", "chunk", "_b", "isRegExp", "InputRule", "inputRuleMatcherHandler", "text", "find", "inputRuleMatch", "result", "from", "to", "rules", "plugin", "matched", "rule", "match", "range", "commands", "can", "inputRulesPlugin", "Plugin", "prev", "stored", "simulatedInputMeta", "Fragment", "$cursor", "getType", "isPlainObject", "mergeDeep", "target", "source", "output", "Mark", "_Mark", "options", "extendedConfig", "currentPos", "currentMarks", "m", "removeMark", "isNumber", "PasteRule", "pasteRuleMatcherHandler", "matches", "pasteRuleMatch", "pasteEvent", "dropEvent", "handlers", "resolvedFrom", "resolvedTo", "textToMatch", "start", "end", "handler", "tiptapDragFromOtherEditor", "createClipboardPasteEvent", "pasteRulesPlugin", "dragSourceElement", "isPastedFromProseMirror", "isDroppedFromProseMirror", "processEvent", "pasteEvt", "chainableState", "handleDragstart", "handleDragend", "dragFromOtherEditor", "_view", "html", "transactions", "oldState", "isPaste", "isDrop", "simulatedPasteMeta", "isSimulatedPaste", "findDuplicates", "filtered", "el", "ExtensionManager", "_ExtensionManager", "resolvedExtensions", "duplicatedNames", "addExtensions", "a", "b", "priorityA", "priorityB", "addCommands", "inputRules", "pasteRules", "allPlugins", "plugins", "addKeyboardShortcuts", "defaultBindings", "bindings", "shortcut", "method", "keyMapPlugin", "keymap", "addInputRules", "addPasteRules", "addProseMirrorPlugins", "proseMirrorPlugins", "addNodeView", "nodeview", "getPos", "decorations", "innerDecorations", "HTMLAttributes", "onBeforeCreate", "onCreate", "onUpdate", "onSelectionUpdate", "onTransaction", "onFocus", "onBlur", "onDestroy", "Extension", "_Extension", "getTextBetween", "startNode", "blockSeparator", "textSerializers", "textSerializer", "getTextSerializersFromSchema", "ClipboardTextSerializer", "PluginKey", "ranges", "blur", "clearContent", "emitUpdate", "clearNodes", "$to", "mapping", "$mappedFrom", "$mappedTo", "nodeRange", "targetLiftDepth", "liftTarget", "defaultType", "createParagraphNear", "originalCreateParagraphNear", "cut", "originRange", "targetPos", "contentSlice", "newPos", "TextSelection", "deleteCurrentNode", "currentNode", "$pos", "depth", "deleteNode", "typeOrName", "deleteRange", "deleteSelection", "originalDeleteSelection", "enter", "exitCode", "originalExitCode", "objectIncludes", "object1", "object2", "keys", "findMarkInSet", "k", "isMarkInSet", "getMarkRange", "startIndex", "startPos", "endIndex", "endPos", "getMarkType", "extendMarkRange", "newSelection", "first", "i", "isTextSelection", "minMax", "min", "max", "resolveFocusPosition", "position", "selectionAtStart", "Selection", "selectionAtEnd", "minPos", "maxPos", "isAndroid", "isiOS", "isSafari", "focus", "delayedFocus", "isSameSelection", "forEach", "insertContent", "removeWhitespaces", "children", "child", "elementFromString", "wrappedValue", "createNodeFromContent", "content", "ProseMirrorNode", "isJSONContent", "isTextContent", "error", "hasInvalidContent", "invalidContent", "contentCheckSchema", "DOMParser", "parser", "selectionToInsertionEnd", "startLen", "bias", "last", "step", "ReplaceStep", "ReplaceAroundStep", "map", "_from", "_to", "_newFrom", "newTo", "isFragment", "nodeOrFragment", "insertContentAt", "emitContentError", "parseOptions", "isOnlyTextContent", "isOnlyBlockContent", "newContent", "v", "joinUp", "originalJoinUp", "joinDown", "originalJoinDown", "joinBackward", "originalJoinBackward", "joinForward", "originalJoinForward", "joinItemBackward", "point", "joinPoint", "joinItemForward", "joinTextblockBackward", "originalCommand", "joinTextblockForward", "isMacOS", "normalizeKeyName", "parts", "alt", "ctrl", "shift", "meta", "mod", "keyboardShortcut", "capturedTransaction", "f", "newStep", "isNodeActive", "empty", "nodeRanges", "relativeFrom", "relativeTo", "selectionRange", "matchedNodeRanges", "sum", "lift", "originalLift", "liftEmptyBlock", "originalLiftEmptyBlock", "liftListItem", "originalLiftListItem", "newlineInCode", "originalNewlineInCode", "getSchemaTypeNameByName", "deleteProps", "obj", "propOrProps", "newObj", "prop", "resetAttributes", "nodeType", "markType", "schemaType", "scrollIntoView", "selectAll", "AllSelection", "selectNodeBackward", "originalSelectNodeBackward", "selectNodeForward", "originalSelectNodeForward", "selectParentNode", "originalSelectParentNode", "selectTextblockEnd", "originalSelectTextblockEnd", "selectTextblockStart", "originalSelectTextblockStart", "createDocument", "setContent", "document", "getMarkAttributes", "markItem", "combineTransactionSteps", "oldDoc", "transform", "Transform", "defaultBlockAt", "findChildrenInRange", "node", "range", "predicate", "nodesWithPos", "child", "pos", "findParentNodeClosestToPos", "$pos", "findParentNode", "selection", "getText", "node", "options", "range", "getTextBetween", "getNodeAttributes", "state", "typeOrName", "type", "getNodeType", "from", "to", "nodes", "node", "nodeItem", "getAttributes", "schemaType", "getSchemaTypeNameByName", "getMarkAttributes", "removeDuplicates", "array", "by", "seen", "item", "key", "simplifyChangedRanges", "changes", "uniqueChanges", "change", "index", "_", "i", "otherChange", "getChangedRanges", "transform", "mapping", "steps", "stepMap", "ranges", "newStart", "newEnd", "oldStart", "oldEnd", "getMarksBetween", "from", "to", "doc", "marks", "mark", "$pos", "range", "getMarkRange", "node", "pos", "getSplittedAttributes", "extensionAttributes", "typeName", "attributes", "name", "extensionAttribute", "item", "isMarkActive", "state", "typeOrName", "empty", "ranges", "type", "getMarkType", "mark", "objectIncludes", "selectionRange", "markRanges", "$from", "$to", "from", "to", "node", "pos", "relativeFrom", "relativeTo", "range", "matchedRange", "markRange", "sum", "excludedRange", "isActive", "isNodeActive", "schemaType", "getSchemaTypeNameByName", "isList", "name", "extensions", "nodeExtensions", "splitExtensions", "extension", "item", "context", "group", "callOrReturn", "getExtensionField", "isNodeEmpty", "node", "checkChildren", "ignoreWhitespace", "_a", "isContentEmpty", "childNode", "isNodeSelection", "value", "NodeSelection", "posToDOMRect", "view", "from", "to", "maxPos", "resolvedFrom", "minMax", "resolvedEnd", "start", "end", "top", "bottom", "left", "right", "width", "height", "data", "canSetMark", "state", "tr", "newMarkType", "selection", "cursor", "isTextSelection", "currentMarks", "_a", "mark", "ranges", "$from", "$to", "someNodeSupportsMark", "node", "_pos", "parent", "parentAllowsMarkType", "currentMarksAllowMarkType", "otherMark", "setMark", "typeOrName", "attributes", "dispatch", "empty", "type", "getMarkType", "oldAttributes", "getMarkAttributes", "range", "from", "to", "pos", "trimmedFrom", "trimmedTo", "setMeta", "key", "value", "setNode", "chain", "getNodeType", "attributesToCopy", "commands", "setBlockType", "updatedState", "setNodeSelection", "position", "doc", "minMax", "NodeSelection", "setTextSelection", "minPos", "TextSelection", "maxPos", "resolvedFrom", "resolvedEnd", "sinkListItem", "originalSinkListItem", "ensureMarks", "splittableMarks", "marks", "filteredMarks", "splitBlock", "keepMarks", "editor", "extensionAttributes", "newAttributes", "getSplittedAttributes", "canSplit", "atEnd", "deflt", "defaultBlockAt", "types", "can", "first", "$first", "splitListItem", "overrideAttrs", "grandParent", "wrap", "Fragment", "depthBefore", "d", "depthAfter", "newNextTypeAttributes", "nextType", "start", "Slice", "sel", "n", "newTypeAttributes", "storedMarks", "joinListBackwards", "listType", "list", "findParentNode", "before", "nodeBefore", "canJoin", "joinListForwards", "after", "nodeAfter", "toggleList", "listTypeOrName", "itemTypeOrName", "extensions", "itemType", "parentList", "isList", "canWrapInList", "toggleMark", "options", "extendEmptyMarkRange", "isMarkActive", "toggleNode", "toggleTypeOrName", "toggleType", "isActive", "isNodeActive", "toggleWrap", "undoInputRule", "plugins", "i", "plugin", "undoable", "toUndo", "j", "unsetAllMarks", "unsetMark", "attrs", "getMarkRange", "updateAttributes", "nodeType", "markType", "schemaType", "getSchemaTypeNameByName", "lastPos", "lastNode", "trimmedFrom2", "trimmedTo2", "wrapIn", "originalWrapIn", "wrapInList", "originalWrapInList", "Commands", "Extension", "Drop", "Plugin", "PluginKey", "_", "slice", "moved", "Editable", "focusEventsPluginKey", "FocusEvents", "view", "event", "transaction", "Keymap", "handleBackspace", "$anchor", "$parentPos", "parentIsIsolating", "parentPos", "isAtStart", "Selection", "handleDelete", "baseKeymap", "pcKeymap", "macKeymap", "isiOS", "isMacOS", "transactions", "oldState", "newState", "docChanges", "ignoreTr", "allFrom", "allEnd", "isNodeEmpty", "createChainableState", "CommandManager", "Paste", "_view", "Tabindex", "NodePos", "_NodePos", "pos", "editor", "isBlock", "node", "_a", "content", "from", "to", "parentPos", "$pos", "children", "offset", "isNonTextAtom", "targetPos", "childNodePos", "selector", "attributes", "currentNode", "nodeAttributes", "attrKeys", "index", "key", "firstItemOnly", "nodes", "childPos", "tr", "style", "createStyleTag", "nonce", "suffix", "tiptapStyleTag", "styleNode", "Editor", "EventEmitter", "options", "error", "event", "slice", "moved", "editable", "emitUpdate", "plugin", "handlePlugins", "plugins", "isFunction", "state", "nameOrPluginKeyToRemove", "prevPlugins", "nameOrPluginKey", "name", "allExtensions", "Editable", "ClipboardTextSerializer", "_b", "Commands", "FocusEvents", "Keymap", "Tabindex", "Drop", "Paste", "ext", "extension", "ExtensionManager", "CommandManager", "doc", "createDocument", "e", "selection", "resolveFocusPosition", "EditorView", "EditorState", "newState", "dom", "fn", "transaction", "step", "selectionHasChanged", "focus", "blur", "nameOrType", "getAttributes", "nameOrAttributes", "attributesOrUndefined", "isActive", "getHTMLFromFragment", "blockSeparator", "textSerializers", "getText", "getTextSerializersFromSchema", "isNodeEmpty", "markInputRule", "config", "InputRule", "range", "match", "callOrReturn", "captureGroup", "fullMatch", "startSpaces", "textStart", "textEnd", "getMarksBetween", "item", "type", "markEnd", "nodeInputRule", "start", "end", "newNode", "matchStart", "lastChar", "insertionStart", "textblockTypeInputRule", "$start", "wrappingInputRule", "config", "InputRule", "state", "range", "match", "chain", "attributes", "callOrReturn", "tr", "blockRange", "wrapping", "findWrapping", "selection", "storedMarks", "splittableMarks", "marks", "filteredMarks", "mark", "nodeType", "before", "canJoin", "Node", "_Node", "getExtensionField", "options", "extension", "mergeDeep", "extendedConfig", "markPasteRule", "config", "PasteRule", "state", "range", "match", "pasteEvent", "attributes", "callOrReturn", "tr", "captureGroup", "fullMatch", "markEnd", "startSpaces", "textStart", "textEnd", "getMarksBetween", "item", "type", "canInsertNode", "nodeType", "selection", "$from", "NodeSelection", "index", "depth", "top", "bottom", "right", "left", "auto", "basePlacements", "start", "end", "clippingParents", "viewport", "popper", "reference", "variationPlacements", "acc", "placement", "placements", "beforeRead", "read", "afterRead", "beforeMain", "main", "afterMain", "beforeWrite", "write", "afterWrite", "modifierPhases", "getNodeName", "element", "getWindow", "node", "ownerDocument", "isElement", "node", "OwnElement", "getWindow", "isHTMLElement", "isShadowRoot", "applyStyles", "_ref", "state", "name", "style", "attributes", "element", "isHTMLElement", "getNodeName", "value", "effect", "_ref2", "initialStyles", "styleProperties", "property", "attribute", "applyStyles_default", "getBasePlacement", "placement", "max", "min", "round", "getUAString", "uaData", "item", "isLayoutViewport", "getUAString", "getBoundingClientRect", "element", "includeScale", "isFixedStrategy", "clientRect", "scaleX", "scaleY", "isHTMLElement", "round", "_ref", "isElement", "getWindow", "visualViewport", "addVisualOffsets", "isLayoutViewport", "x", "y", "width", "height", "getLayoutRect", "element", "clientRect", "getBoundingClientRect", "width", "height", "contains", "parent", "child", "rootNode", "isShadowRoot", "next", "getComputedStyle", "element", "getWindow", "isTableElement", "element", "getNodeName", "getDocumentElement", "element", "isElement", "getParentNode", "element", "getNodeName", "isShadowRoot", "getDocumentElement", "getTrueOffsetParent", "element", "isHTMLElement", "getComputedStyle", "getContainingBlock", "isFirefox", "getUAString", "isIE", "elementCss", "currentNode", "getParentNode", "isShadowRoot", "getNodeName", "css", "getOffsetParent", "window", "getWindow", "offsetParent", "isTableElement", "getMainAxisFromPlacement", "placement", "within", "min", "value", "max", "withinMaxClamp", "v", "getFreshSideObject", "mergePaddingObject", "paddingObject", "getFreshSideObject", "expandToHashMap", "value", "keys", "hashMap", "key", "toPaddingObject", "padding", "state", "mergePaddingObject", "expandToHashMap", "basePlacements", "arrow", "_ref", "_state$modifiersData$", "name", "options", "arrowElement", "popperOffsets", "basePlacement", "getBasePlacement", "axis", "getMainAxisFromPlacement", "isVertical", "left", "right", "len", "paddingObject", "arrowRect", "getLayoutRect", "minProp", "top", "maxProp", "bottom", "endDiff", "startDiff", "arrowOffsetParent", "getOffsetParent", "clientSize", "centerToReference", "min", "max", "center", "offset", "within", "axisProp", "effect", "_ref2", "_options$element", "contains", "arrow_default", "getVariation", "placement", "unsetSides", "roundOffsetsByDPR", "_ref", "win", "x", "y", "dpr", "round", "mapToStyles", "_ref2", "_Object$assign2", "popper", "popperRect", "placement", "variation", "offsets", "position", "gpuAcceleration", "adaptive", "roundOffsets", "isFixed", "_offsets$x", "_offsets$y", "_ref3", "hasX", "hasY", "sideX", "left", "sideY", "top", "offsetParent", "getOffsetParent", "heightProp", "widthProp", "getWindow", "getDocumentElement", "getComputedStyle", "right", "end", "bottom", "offsetY", "offsetX", "commonStyles", "_ref4", "_Object$assign", "computeStyles", "_ref5", "state", "options", "_options$gpuAccelerat", "_options$adaptive", "_options$roundOffsets", "getBasePlacement", "getVariation", "computeStyles_default", "passive", "effect", "_ref", "state", "instance", "options", "_options$scroll", "scroll", "_options$resize", "resize", "window", "getWindow", "scrollParents", "scrollParent", "eventListeners_default", "hash", "getOppositePlacement", "placement", "matched", "hash", "getOppositeVariationPlacement", "placement", "matched", "getWindowScroll", "node", "win", "getWindow", "scrollLeft", "scrollTop", "getWindowScrollBarX", "element", "getBoundingClientRect", "getDocumentElement", "getWindowScroll", "getViewportRect", "element", "strategy", "win", "getWindow", "html", "getDocumentElement", "visualViewport", "width", "height", "x", "y", "layoutViewport", "isLayoutViewport", "getWindowScrollBarX", "getDocumentRect", "element", "_element$ownerDocumen", "html", "getDocumentElement", "winScroll", "getWindowScroll", "body", "width", "max", "height", "x", "getWindowScrollBarX", "y", "getComputedStyle", "isScrollParent", "element", "_getComputedStyle", "getComputedStyle", "overflow", "overflowX", "overflowY", "getScrollParent", "node", "getNodeName", "isHTMLElement", "isScrollParent", "getParentNode", "listScrollParents", "element", "list", "_element$ownerDocumen", "scrollParent", "getScrollParent", "isBody", "win", "getWindow", "target", "isScrollParent", "updatedList", "getParentNode", "rectToClientRect", "rect", "getInnerBoundingClientRect", "element", "strategy", "rect", "getBoundingClientRect", "getClientRectFromMixedType", "clippingParent", "viewport", "rectToClientRect", "getViewportRect", "isElement", "getDocumentRect", "getDocumentElement", "getClippingParents", "clippingParents", "listScrollParents", "getParentNode", "canEscapeClipping", "getComputedStyle", "clipperElement", "isHTMLElement", "getOffsetParent", "contains", "getNodeName", "getClippingRect", "boundary", "rootBoundary", "mainClippingParents", "firstClippingParent", "clippingRect", "accRect", "max", "min", "computeOffsets", "_ref", "reference", "element", "placement", "basePlacement", "getBasePlacement", "variation", "getVariation", "commonX", "commonY", "offsets", "top", "bottom", "right", "left", "mainAxis", "getMainAxisFromPlacement", "len", "start", "end", "detectOverflow", "state", "options", "_options", "_options$placement", "placement", "_options$strategy", "strategy", "_options$boundary", "boundary", "clippingParents", "_options$rootBoundary", "rootBoundary", "viewport", "_options$elementConte", "elementContext", "popper", "_options$altBoundary", "altBoundary", "_options$padding", "padding", "paddingObject", "mergePaddingObject", "expandToHashMap", "basePlacements", "altContext", "reference", "popperRect", "element", "clippingClientRect", "getClippingRect", "isElement", "getDocumentElement", "referenceClientRect", "getBoundingClientRect", "popperOffsets", "computeOffsets", "popperClientRect", "rectToClientRect", "elementClientRect", "overflowOffsets", "offsetData", "offset", "key", "multiply", "right", "bottom", "axis", "top", "computeAutoPlacement", "state", "options", "_options", "placement", "boundary", "rootBoundary", "padding", "flipVariations", "_options$allowedAutoP", "allowedAutoPlacements", "placements", "variation", "getVariation", "variationPlacements", "basePlacements", "allowedPlacements", "overflows", "acc", "detectOverflow", "getBasePlacement", "a", "b", "getExpandedFallbackPlacements", "placement", "getBasePlacement", "auto", "oppositePlacement", "getOppositePlacement", "getOppositeVariationPlacement", "flip", "_ref", "state", "options", "name", "_options$mainAxis", "checkMainAxis", "_options$altAxis", "checkAltAxis", "specifiedFallbackPlacements", "padding", "boundary", "rootBoundary", "altBoundary", "_options$flipVariatio", "flipVariations", "allowedAutoPlacements", "preferredPlacement", "basePlacement", "isBasePlacement", "fallbackPlacements", "placements", "acc", "computeAutoPlacement", "referenceRect", "popperRect", "checksMap", "makeFallbackChecks", "firstFittingPlacement", "i", "_basePlacement", "isStartVariation", "getVariation", "start", "isVertical", "top", "bottom", "len", "overflow", "detectOverflow", "mainVariationSide", "right", "left", "altVariationSide", "checks", "check", "numberOfChecks", "_loop", "_i", "fittingPlacement", "_ret", "flip_default", "getSideOffsets", "overflow", "rect", "preventedOffsets", "isAnySideFullyClipped", "top", "right", "bottom", "left", "side", "hide", "_ref", "state", "name", "referenceRect", "popperRect", "referenceOverflow", "detectOverflow", "popperAltOverflow", "referenceClippingOffsets", "popperEscapeOffsets", "isReferenceHidden", "hasPopperEscaped", "hide_default", "distanceAndSkiddingToXY", "placement", "rects", "offset", "basePlacement", "getBasePlacement", "invertDistance", "left", "top", "_ref", "skidding", "distance", "right", "_ref2", "state", "options", "name", "_options$offset", "data", "placements", "acc", "_data$state$placement", "x", "y", "offset_default", "popperOffsets", "_ref", "state", "name", "computeOffsets", "popperOffsets_default", "getAltAxis", "axis", "preventOverflow", "_ref", "state", "options", "name", "_options$mainAxis", "checkMainAxis", "_options$altAxis", "checkAltAxis", "boundary", "rootBoundary", "altBoundary", "padding", "_options$tether", "tether", "_options$tetherOffset", "tetherOffset", "overflow", "detectOverflow", "basePlacement", "getBasePlacement", "variation", "getVariation", "isBasePlacement", "mainAxis", "getMainAxisFromPlacement", "altAxis", "getAltAxis", "popperOffsets", "referenceRect", "popperRect", "tetherOffsetValue", "normalizedTetherOffsetValue", "offsetModifierState", "data", "_offsetModifierState$", "mainSide", "top", "left", "altSide", "bottom", "right", "len", "offset", "min", "max", "additive", "minLen", "start", "maxLen", "arrowElement", "arrowRect", "getLayoutRect", "arrowPaddingObject", "getFreshSideObject", "arrowPaddingMin", "arrowPaddingMax", "arrowLen", "within", "minOffset", "maxOffset", "arrowOffsetParent", "getOffsetParent", "clientOffset", "offsetModifierValue", "tetherMin", "tetherMax", "preventedOffset", "_offsetModifierState$2", "_mainSide", "_altSide", "_offset", "_len", "_min", "_max", "isOriginSide", "_offsetModifierValue", "_tetherMin", "_tetherMax", "_preventedOffset", "withinMaxClamp", "preventOverflow_default", "getHTMLElementScroll", "element", "getNodeScroll", "node", "getWindow", "isHTMLElement", "getWindowScroll", "getHTMLElementScroll", "isElementScaled", "element", "rect", "scaleX", "round", "scaleY", "getCompositeRect", "elementOrVirtualElement", "offsetParent", "isFixed", "isOffsetParentAnElement", "isHTMLElement", "offsetParentIsScaled", "documentElement", "getDocumentElement", "getBoundingClientRect", "scroll", "offsets", "getNodeName", "isScrollParent", "getNodeScroll", "getWindowScrollBarX", "order", "modifiers", "map", "visited", "result", "modifier", "sort", "requires", "dep", "depModifier", "orderModifiers", "orderedModifiers", "modifierPhases", "acc", "phase", "debounce", "fn", "pending", "resolve", "mergeByName", "modifiers", "merged", "current", "existing", "key", "DEFAULT_OPTIONS", "areValidElements", "_len", "args", "_key", "element", "popperGenerator", "generatorOptions", "_generatorOptions", "_generatorOptions$def", "defaultModifiers", "_generatorOptions$def2", "defaultOptions", "reference", "popper", "options", "state", "effectCleanupFns", "isDestroyed", "instance", "setOptionsAction", "cleanupModifierEffects", "isElement", "listScrollParents", "orderedModifiers", "orderModifiers", "mergeByName", "m", "runModifierEffects", "_state$elements", "getCompositeRect", "getOffsetParent", "getLayoutRect", "modifier", "index", "_state$orderedModifie", "fn", "_state$orderedModifie2", "_options", "name", "debounce", "resolve", "_ref", "_ref$options", "effect", "cleanupFn", "noopFn", "defaultModifiers", "eventListeners_default", "popperOffsets_default", "computeStyles_default", "applyStyles_default", "offset_default", "flip_default", "preventOverflow_default", "arrow_default", "hide_default", "createPopper", "popperGenerator", "BOX_CLASS", "CONTENT_CLASS", "BACKDROP_CLASS", "ARROW_CLASS", "SVG_ARROW_CLASS", "TOUCH_OPTIONS", "passive", "capture", "TIPPY_DEFAULT_APPEND_TO", "document", "body", "getValueAtIndexOrReturn", "value", "index", "defaultValue", "Array", "isArray", "v", "isType", "type", "str", "toString", "call", "indexOf", "invokeWithArgsOrReturn", "args", "debounce", "fn", "ms", "timeout", "arg", "clearTimeout", "setTimeout", "splitBySpaces", "value", "split", "filter", "Boolean", "normalizeToArray", "concat", "pushIfUnique", "arr", "indexOf", "push", "unique", "item", "index", "getBasePlacement", "placement", "arrayFrom", "slice", "call", "removeUndefinedProps", "obj", "Object", "keys", "reduce", "acc", "key", "undefined", "div", "document", "createElement", "isElement", "some", "type", "isType", "isNodeList", "isMouseEvent", "isReferenceElement", "_tippy", "reference", "getArrayOfElements", "Array", "isArray", "querySelectorAll", "setTransitionDuration", "els", "forEach", "el", "style", "transitionDuration", "setVisibilityState", "state", "setAttribute", "getOwnerDocument", "elementOrElements", "_element$ownerDocumen", "_normalizeToArray", "element", "ownerDocument", "body", "isCursorOutsideInteractiveBorder", "popperTreeData", "event", "clientX", "clientY", "every", "_ref", "popperRect", "popperState", "props", "interactiveBorder", "basePlacement", "offsetData", "modifiersData", "offset", "topDistance", "top", "y", "bottomDistance", "bottom", "leftDistance", "left", "x", "rightDistance", "right", "exceedsTop", "exceedsBottom", "exceedsLeft", "exceedsRight", "updateTransitionEndListener", "box", "action", "listener", "method", "actualContains", "parent", "child", "target", "_target$getRootNode", "contains", "getRootNode", "host", "currentInput", "isTouch", "lastMouseMoveTime", "onDocumentTouchStart", "window", "performance", "addEventListener", "onDocumentMouseMove", "now", "removeEventListener", "onWindowBlur", "activeElement", "instance", "blur", "isVisible", "bindGlobalEventListeners", "TOUCH_OPTIONS", "isBrowser", "isIE11", "msCrypto", "pluginProps", "animateFill", "followCursor", "inlinePositioning", "sticky", "renderProps", "allowHTML", "animation", "arrow", "content", "inertia", "maxWidth", "role", "theme", "zIndex", "defaultProps", "appendTo", "TIPPY_DEFAULT_APPEND_TO", "aria", "expanded", "delay", "duration", "getReferenceClientRect", "hideOnClick", "ignoreAttributes", "interactive", "interactiveBorder", "interactiveDebounce", "moveTransition", "offset", "onAfterUpdate", "onBeforeUpdate", "onCreate", "onDestroy", "onHidden", "onHide", "onMount", "onShow", "onShown", "onTrigger", "onUntrigger", "onClickOutside", "placement", "plugins", "popperOptions", "render", "showOnCreate", "touch", "trigger", "triggerTarget", "defaultKeys", "Object", "keys", "setDefaultProps", "partialProps", "forEach", "key", "getExtendedPassedProps", "passedProps", "reduce", "acc", "plugin", "name", "defaultValue", "_name", "undefined", "getDataAttributeProps", "reference", "propKeys", "props", "valueAsString", "getAttribute", "trim", "JSON", "parse", "evaluateProps", "out", "invokeWithArgsOrReturn", "innerHTML", "dangerouslySetInnerHTML", "element", "html", "createArrowElement", "value", "arrow", "div", "className", "ARROW_CLASS", "SVG_ARROW_CLASS", "isElement", "appendChild", "setContent", "content", "props", "allowHTML", "textContent", "getChildren", "popper", "box", "firstElementChild", "boxChildren", "arrayFrom", "children", "find", "node", "classList", "contains", "CONTENT_CLASS", "backdrop", "BACKDROP_CLASS", "render", "instance", "BOX_CLASS", "setAttribute", "onUpdate", "prevProps", "nextProps", "_getChildren", "theme", "removeAttribute", "animation", "inertia", "style", "maxWidth", "role", "removeChild", "$$tippy", "idCounter", "mouseMoveListeners", "mountedInstances", "createTippy", "reference", "passedProps", "evaluateProps", "defaultProps", "getExtendedPassedProps", "removeUndefinedProps", "showTimeout", "hideTimeout", "scheduleHideAnimationFrame", "isVisibleFromClick", "didHideDueToDocumentMouseDown", "didTouchMove", "ignoreOnFirstUpdate", "lastTriggerEvent", "currentTransitionEndListener", "onFirstUpdate", "listeners", "debouncedOnMouseMove", "debounce", "onMouseMove", "interactiveDebounce", "currentTarget", "id", "popperInstance", "plugins", "unique", "state", "isEnabled", "isVisible", "isDestroyed", "isMounted", "isShown", "clearDelayTimeouts", "setProps", "show", "hide", "hideWithInteractivity", "enable", "disable", "unmount", "destroy", "_props$render", "_tippy", "pluginsHooks", "map", "plugin", "fn", "hasAriaExpanded", "hasAttribute", "addListeners", "handleAriaExpandedAttribute", "handleStyles", "invokeHook", "showOnCreate", "scheduleShow", "addEventListener", "interactive", "trigger", "indexOf", "getDocument", "getNormalizedTouchSettings", "touch", "Array", "isArray", "getIsCustomTouchBehavior", "getIsDefaultRenderFn", "_instance$props$rende", "getCurrentTarget", "parent", "parentNode", "getOwnerDocument", "document", "getDefaultTemplateChildren", "getDelay", "isShow", "currentInput", "isTouch", "type", "getValueAtIndexOrReturn", "delay", "fromHide", "pointerEvents", "zIndex", "hook", "args", "shouldInvokePropsHook", "forEach", "pluginHooks", "_instance$props", "handleAriaContentAttribute", "aria", "attr", "nodes", "normalizeToArray", "triggerTarget", "currentValue", "getAttribute", "nextValue", "replace", "trim", "expanded", "cleanupInteractiveMouseListeners", "removeEventListener", "filter", "listener", "onDocumentPress", "event", "actualTarget", "composedPath", "target", "actualContains", "some", "el", "hideOnClick", "setTimeout", "removeDocumentPress", "onTouchMove", "onTouchStart", "addDocumentPress", "doc", "TOUCH_OPTIONS", "onTransitionedOut", "duration", "callback", "onTransitionEnd", "onTransitionedIn", "updateTransitionEndListener", "on", "eventType", "handler", "options", "push", "onTrigger", "passive", "onMouseLeave", "splitBySpaces", "isIE11", "onBlurOrFocusOut", "removeListeners", "_ref", "_lastTriggerEvent", "shouldScheduleClickHide", "isEventListenerStopped", "wasFocused", "isMouseEvent", "scheduleHide", "isCursorOverReferenceOrPopper", "popperTreeData", "getNestedPopperTree", "concat", "_instance$popperInsta", "popperRect", "getBoundingClientRect", "popperState", "Boolean", "isCursorOutsideInteractiveBorder", "shouldBail", "relatedTarget", "createPopperInstance", "destroyPopperInstance", "_instance$props2", "popperOptions", "placement", "offset", "getReferenceClientRect", "moveTransition", "computedReference", "contextElement", "tippyModifier", "name", "enabled", "phase", "requires", "_ref2", "_getDefaultTemplateCh", "attributes", "modifiers", "padding", "top", "bottom", "left", "right", "adaptive", "createPopper", "mount", "appendTo", "TIPPY_DEFAULT_APPEND_TO", "invokeWithArgsOrReturn", "querySelectorAll", "_getNormalizedTouchSe", "touchValue", "touchDelay", "requestAnimationFrame", "clearTimeout", "cancelAnimationFrame", "partialProps", "ignoreAttributes", "nestedPopper", "forceUpdate", "isAlreadyVisible", "isDisabled", "isTouchAndTouchDisabled", "onShow", "visibility", "transition", "_getDefaultTemplateCh2", "setTransitionDuration", "_instance$popperInsta2", "offsetHeight", "_getDefaultTemplateCh3", "setVisibilityState", "pushIfUnique", "isAlreadyHidden", "onHide", "_getDefaultTemplateCh4", "i", "tippy", "targets", "optionalProps", "bindGlobalEventListeners", "elements", "getArrayOfElements", "isSingleContentElement", "isMoreThanOneReferenceElement", "instances", "reduce", "acc", "setDefaultProps", "applyStylesModifier", "applyStyles", "effect", "_ref", "state", "initialStyles", "popper", "position", "options", "strategy", "left", "top", "margin", "arrow", "reference", "Object", "assign", "elements", "style", "styles", "tippy", "setDefaultProps", "render", "FloatingMenuView", "node", "getText", "getTextSerializersFromSchema", "editor", "element", "view", "tippyOptions", "shouldShow", "state", "selection", "$anchor", "empty", "isRootDepth", "isEmptyTextBlock", "event", "_a", "editorElement", "editorIsAttached", "tippy_esm_default", "oldState", "doc", "from", "to", "_b", "_c", "posToDOMRect", "FloatingMenuPlugin", "options", "Plugin", "PluginKey", "FloatingMenu", "Extension", "encodedTlds", "encodedUtlds", "numeric", "ascii", "alpha", "asciinumeric", "alphanumeric", "domain", "emoji", "scheme", "slashscheme", "whitespace", "registerGroup", "name", "groups", "addToGroups", "flags", "k", "group", "flagsForToken", "result", "c", "State", "token", "input", "state", "nextState", "i", "regex", "exactOnly", "inputs", "next", "regexp", "len", "t", "templateState", "allFlags", "ta", "tr", "ts", "tt", "WORD", "UWORD", "ASCIINUMERICAL", "ALPHANUMERICAL", "LOCALHOST", "TLD", "UTLD", "SCHEME", "SLASH_SCHEME", "NUM", "WS", "NL", "OPENBRACE", "CLOSEBRACE", "OPENBRACKET", "CLOSEBRACKET", "OPENPAREN", "CLOSEPAREN", "OPENANGLEBRACKET", "CLOSEANGLEBRACKET", "FULLWIDTHLEFTPAREN", "FULLWIDTHRIGHTPAREN", "LEFTCORNERBRACKET", "RIGHTCORNERBRACKET", "LEFTWHITECORNERBRACKET", "RIGHTWHITECORNERBRACKET", "FULLWIDTHLESSTHAN", "FULLWIDTHGREATERTHAN", "AMPERSAND", "APOSTROPHE", "ASTERISK", "AT", "BACKSLASH", "BACKTICK", "CARET", "COLON", "COMMA", "DOLLAR", "DOT", "EQUALS", "EXCLAMATION", "HYPHEN", "PERCENT", "PIPE", "PLUS", "POUND", "QUERY", "QUOTE", "FULLWIDTHMIDDLEDOT", "SEMI", "SLASH", "TILDE", "UNDERSCORE", "EMOJI$1", "SYM", "tk", "ASCII_LETTER", "LETTER", "EMOJI", "DIGIT", "SPACE", "CR", "LF", "EMOJI_VARIATION", "EMOJI_JOINER", "OBJECT_REPLACEMENT", "tlds", "utlds", "init$2", "customSchemes", "groups", "State", "Start", "decodeTlds", "encodedTlds", "encodedUtlds", "tt", "APOSTROPHE", "OPENBRACE", "CLOSEBRACE", "OPENBRACKET", "CLOSEBRACKET", "OPENPAREN", "CLOSEPAREN", "OPENANGLEBRACKET", "CLOSEANGLEBRACKET", "FULLWIDTHLEFTPAREN", "FULLWIDTHRIGHTPAREN", "LEFTCORNERBRACKET", "RIGHTCORNERBRACKET", "LEFTWHITECORNERBRACKET", "RIGHTWHITECORNERBRACKET", "FULLWIDTHLESSTHAN", "FULLWIDTHGREATERTHAN", "AMPERSAND", "ASTERISK", "AT", "BACKTICK", "CARET", "COLON", "COMMA", "DOLLAR", "DOT", "EQUALS", "EXCLAMATION", "HYPHEN", "PERCENT", "PIPE", "PLUS", "POUND", "QUERY", "QUOTE", "SLASH", "SEMI", "TILDE", "UNDERSCORE", "BACKSLASH", "FULLWIDTHMIDDLEDOT", "Num", "tr", "DIGIT", "NUM", "numeric", "Asciinumeric", "ASCII_LETTER", "ASCIINUMERICAL", "asciinumeric", "Alphanumeric", "LETTER", "ALPHANUMERICAL", "alphanumeric", "Word", "WORD", "ascii", "UWord", "UWORD", "alpha", "Nl", "NL", "whitespace", "Cr", "WS", "Ws", "SPACE", "Emoji", "EMOJI", "EMOJI$1", "emoji", "EmojiJoiner", "wordjr", "uwordjr", "i", "fastts", "TLD", "UTLD", "addToGroups", "SCHEME", "SLASH_SCHEME", "a", "sch", "flags", "scheme", "slashscheme", "domain", "ts", "LOCALHOST", "SYM", "tk", "run$1", "start", "str", "iterable", "stringToArray", "c", "charCount", "tokens", "cursor", "charCursor", "state", "nextState", "tokenLength", "latestAccepting", "sinceAccepts", "charsSinceAccepts", "result", "len", "index", "first", "second", "char", "input", "t", "defaultt", "jr", "next", "encoded", "words", "stack", "digits", "popDigitCount", "popCount", "defaults", "noop", "Options", "opts", "defaultRender", "o", "ignoredTags", "uppercaseIgnoredTags", "classNames", "classes", "ir", "token", "key", "operator", "isCallable", "option", "obj", "val", "MultiToken", "value", "tokens", "scheme", "options", "val", "truncate", "formatted", "protocol", "defaults", "token", "href", "formattedHref", "tagName", "content", "attributes", "className", "target", "rel", "attrs", "eventListeners", "createTokenClass", "type", "props", "Token", "p", "Email", "Text", "Nl", "Url", "LOCALHOST", "COLON", "makeState", "arg", "State", "init$1", "groups", "qsAccepting", "AMPERSAND", "ASTERISK", "AT", "BACKSLASH", "BACKTICK", "CARET", "DOLLAR", "EQUALS", "HYPHEN", "NUM", "PERCENT", "PIPE", "PLUS", "POUND", "SLASH", "SYM", "TILDE", "UNDERSCORE", "qsNonAccepting", "APOSTROPHE", "COLON", "COMMA", "DOT", "EXCLAMATION", "QUERY", "QUOTE", "SEMI", "OPENANGLEBRACKET", "CLOSEANGLEBRACKET", "OPENBRACE", "CLOSEBRACE", "CLOSEBRACKET", "OPENBRACKET", "OPENPAREN", "CLOSEPAREN", "FULLWIDTHLEFTPAREN", "FULLWIDTHRIGHTPAREN", "LEFTCORNERBRACKET", "RIGHTCORNERBRACKET", "LEFTWHITECORNERBRACKET", "RIGHTWHITECORNERBRACKET", "FULLWIDTHLESSTHAN", "FULLWIDTHGREATERTHAN", "localpartAccepting", "Start", "Localpart", "tt", "ta", "Domain", "Scheme", "SlashScheme", "LocalpartAt", "LocalpartDot", "EmailDomain", "EmailDomainDot", "Email$1", "Email", "LOCALHOST", "EmailDomainHyphen", "DomainHyphen", "DomainDot", "DomainDotTld", "Url", "DomainDotTldColon", "DomainDotTldColonPort", "Url$1", "UrlNonaccept", "SchemeColon", "SlashSchemeColon", "SlashSchemeColonSlash", "UriPrefix", "bracketPairs", "i", "OPEN", "CLOSE", "UrlOpen", "UrlOpenQ", "UrlOpenSyms", "NL", "Nl", "tk", "run", "start", "input", "tokens", "len", "cursor", "multis", "textTokens", "dead", "state", "secondState", "nextState", "multiLength", "latestAccepting", "sinceAccepts", "visited", "k", "pos", "initMultiToken", "Text", "Multi", "subtokens", "startIdx", "endIdx", "value", "warn", "warnAdvice", "INIT", "reset", "registerCustomProtocol", "scheme", "optionalSlashSlash", "INIT", "warn", "warnAdvice", "init", "init$2", "i", "init$1", "tokenize", "str", "run", "run$1", "find", "type", "opts", "options", "Options", "tokens", "filtered", "token", "UNICODE_WHITESPACE_PATTERN", "UNICODE_WHITESPACE_REGEX", "UNICODE_WHITESPACE_REGEX_END", "UNICODE_WHITESPACE_REGEX_GLOBAL", "isValidLinkStructure", "tokens", "autolink", "options", "Plugin", "PluginKey", "transactions", "oldState", "newState", "docChanges", "transaction", "preventAutolink", "tr", "transform", "combineTransactionSteps", "getChangedRanges", "newRange", "nodesInChangedRanges", "findChildrenInRange", "node", "textBlock", "textBeforeWhitespace", "endText", "wordsBeforeWhitespace", "lastWordBeforeSpace", "lastWordAndBlockOffset", "linksBeforeSpace", "tokenize", "t", "link", "getMarksBetween", "item", "clickHandler", "view", "pos", "event", "a", "els", "value", "attrs", "getAttributes", "href", "_a", "target", "_b", "pasteHandler", "slice", "state", "selection", "empty", "textContent", "find", "isAllowedUri", "uri", "protocols", "allowedProtocols", "protocol", "nextProtocol", "UNICODE_WHITESPACE_REGEX_GLOBAL", "Link", "Mark", "registerCustomProtocol", "reset", "url", "ctx", "element", "dom", "href", "HTMLAttributes", "mergeAttributes", "attributes", "chain", "markPasteRule", "text", "foundLinks", "defaultProtocol", "links", "find", "item", "link", "match", "_a", "plugins", "autolink", "clickHandler", "pasteHandler", "inputRegex", "Blockquote", "Node", "HTMLAttributes", "mergeAttributes", "commands", "wrappingInputRule", "starInputRegex", "starPasteRegex", "underscoreInputRegex", "underscorePasteRegex", "Bold", "Mark", "node", "mark", "value", "HTMLAttributes", "mergeAttributes", "commands", "markInputRule", "markPasteRule", "ListItemName", "TextStyleName", "inputRegex", "BulletList", "Node", "HTMLAttributes", "mergeAttributes", "commands", "chain", "inputRule", "wrappingInputRule", "inputRegex", "pasteRegex", "Code", "Mark", "HTMLAttributes", "mergeAttributes", "commands", "markInputRule", "markPasteRule", "backtickInputRegex", "tildeInputRegex", "CodeBlock", "Node", "element", "languageClassPrefix", "language", "_a", "className", "node", "HTMLAttributes", "mergeAttributes", "attributes", "commands", "empty", "$anchor", "isAtStart", "editor", "state", "selection", "$from", "isAtEnd", "endsWithDoubleNewline", "tr", "doc", "after", "Selection", "textblockTypeInputRule", "match", "Plugin", "PluginKey", "view", "event", "text", "vscode", "vscodeData", "schema", "textNode", "TextSelection", "Document", "Node", "dropCursor", "options", "Plugin", "editorView", "DropCursorView", "_a", "name", "handler", "e", "prevState", "target", "pos", "$pos", "isBlock", "rect", "editorDOM", "editorRect", "scaleX", "scaleY", "before", "after", "node", "nodeRect", "top", "halfWidth", "coords", "parent", "parentLeft", "parentTop", "parentScaleX", "parentScaleY", "timeout", "event", "disableDropCursor", "disabled", "point", "dropPoint", "Dropcursor", "Extension", "dropCursor", "GapCursor", "_GapCursor", "Selection", "$pos", "doc", "mapping", "Slice", "other", "json", "GapBookmark", "parent", "closedBefore", "closedAfter", "override", "deflt", "dir", "mustMove", "search", "pos", "next", "d", "$cur", "inside", "NodeSelection", "_GapBookmark", "needsGap", "type", "index", "before", "after", "gapCursor", "Plugin", "drawGapCursor", "_view", "$anchor", "$head", "handleClick", "handleKeyDown", "beforeinput", "keydownHandler", "arrow", "axis", "dirStr", "state", "dispatch", "view", "sel", "$start", "TextSelection", "$found", "event", "clickPos", "$from", "insert", "frag", "Fragment", "i", "tr", "node", "DecorationSet", "Decoration", "Gapcursor", "Extension", "gapCursor", "extension", "context", "_a", "callOrReturn", "getExtensionField", "HardBreak", "Node", "HTMLAttributes", "mergeAttributes", "commands", "chain", "state", "editor", "selection", "storedMarks", "keepMarks", "splittableMarks", "marks", "tr", "dispatch", "filteredMarks", "mark", "Heading", "Node", "level", "node", "HTMLAttributes", "mergeAttributes", "attributes", "commands", "items", "textblockTypeInputRule", "GOOD_LEAF_SIZE", "RopeSequence", "other", "Append", "from", "to", "i", "f", "result", "elt", "values", "Leaf", "prototypeAccessors", "start", "left", "right", "leftLen", "inner", "dist_default", "max_empty_items", "Branch", "_Branch", "items", "eventCount", "state", "preserveItems", "end", "remap", "mapFrom", "transform", "selection", "remaining", "addAfter", "addBefore", "item", "i", "Item", "step", "map", "histOptions", "newItems", "oldItems", "lastItem", "merged", "overflow", "DEPTH_OVERFLOW", "cutOffEvents", "from", "to", "maps", "Mapping", "mirrorPos", "array", "rebasedTransform", "rebasedCount", "rebasedItems", "start", "mapping", "newUntil", "iRebased", "pos", "newMaps", "branch", "count", "upto", "events", "newItem", "last", "dist_default", "n", "cutPoint", "_Item", "mirrorOffset", "other", "HistoryState", "done", "undone", "prevRanges", "prevTime", "prevComposition", "applyTransaction", "history", "tr", "options", "historyTr", "historyKey", "rebased", "closeHistoryKey", "appended", "mustPreserveItems", "rangesFor", "composition", "newGroup", "isAdjacentTo", "mapRanges", "adjacent", "result", "_from", "_to", "ranges", "histTransaction", "redo", "pop", "added", "newHist", "cachedPreserveItems", "cachedPreserveItemsPlugins", "plugins", "historyKey", "PluginKey", "closeHistoryKey", "history", "config", "Plugin", "HistoryState", "Branch", "tr", "hist", "state", "applyTransaction", "view", "e", "inputType", "command", "undo", "redo", "buildCommand", "scroll", "dispatch", "histTransaction", "undoNoScroll", "redoNoScroll", "History", "Extension", "state", "dispatch", "undo", "redo", "history", "HorizontalRule", "Node", "HTMLAttributes", "mergeAttributes", "chain", "state", "canInsertNode", "selection", "$originFrom", "$originTo", "currentChain", "isNodeSelection", "tr", "dispatch", "$to", "posAfter", "TextSelection", "NodeSelection", "node", "_a", "nodeInputRule", "starInputRegex", "starPasteRegex", "underscoreInputRegex", "underscorePasteRegex", "Italic", "Mark", "node", "mark", "HTMLAttributes", "mergeAttributes", "commands", "markInputRule", "markPasteRule", "ListItem", "Node", "HTMLAttributes", "mergeAttributes", "ListItemName", "TextStyleName", "inputRegex", "OrderedList", "Node", "element", "HTMLAttributes", "start", "attributesWithoutStart", "mergeAttributes", "commands", "chain", "inputRule", "wrappingInputRule", "match", "node", "Paragraph", "Node", "HTMLAttributes", "mergeAttributes", "commands", "inputRegex", "pasteRegex", "Strike", "Mark", "style", "HTMLAttributes", "mergeAttributes", "commands", "markInputRule", "markPasteRule", "Text", "Node", "StarterKit", "Extension", "extensions", "Bold", "Blockquote", "BulletList", "Code", "CodeBlock", "Document", "Dropcursor", "Gapcursor", "HardBreak", "Heading", "History", "HorizontalRule", "Italic", "ListItem", "OrderedList", "Paragraph", "Strike", "Text", "import_slugify", "isTargetNodeOfType", "node", "type", "pluginKey", "PluginKey", "TableOfContents", "Extension", "attributes", "element", "Plugin", "transactions", "_prevState", "nextState", "tr", "modified", "transaction", "pos", "heading", "attrs", "slug", "slugify", "attributesToParams", "attributes", "params", "k", "v", "prompts_block_default", "Node", "HTMLAttributes", "mergeAttributes", "editor", "node", "getPos", "decorations", "extension", "dom", "attributesToParams", "attributes", "params", "k", "v", "image_block_default", "Node", "HTMLAttributes", "mergeAttributes", "editor", "node", "getPos", "decorations", "extension", "dom", "Controller", "Editor", "StarterKit", "Link", "TableOfContents", "FloatingMenu", "image_block_default", "prompts_block_default", "b", "button", "active", "attributes", "url", "linkAttributes", "k", "v", "state", "t", "params", "level", "content", "value", "fieldset_component_exports", "group_component_exports", "grouped_collection_select_component_exports", "__export", "Controller", "forEvents", "events", "callback", "event", "MicroEvent", "fct", "event_array", "n", "args", "self", "MicroPlugin", "Interface", "name", "fn", "plugins", "key", "self", "queue", "plugin", "arrayToPattern", "chars", "maxValueLength", "sequencePattern", "array", "hasDuplicates", "pattern", "prev_char_count", "prev_pattern", "char", "i", "setToPattern", "escape_regex", "str", "longest", "value", "unicodeLength", "allSubstrings", "input", "result", "start", "subresult", "tmp", "folding_code_points", "accent_pat", "unicode_map", "multi_char_reg", "max_char_length", "latin_convert", "latin_condensed", "latin", "unicode", "char", "convert_pat", "initialize", "_code_points", "generateMap", "normalize", "str", "form", "asciifold", "result", "_asciifold", "generator", "code_points", "code_point_min", "code_point_max", "i", "composed", "folded", "generateSets", "unicode_sets", "addMatching", "to_add", "folded_set", "patt", "setToPattern", "escape_regex", "value", "multi_char", "set", "a", "b", "multi_char_patt", "arrayToPattern", "mapSequence", "strings", "min_replacement", "chars_replaced", "sequencePattern", "substringsToPattern", "allSubstrings", "sub_pat", "sequencesToPattern", "sequences", "all", "sequence", "seq", "len", "j", "inSequences", "needle_seq", "needle_parts", "filter", "part", "needle_part", "Sequence", "_Sequence", "position", "last_piece", "clone", "parts", "last_part", "last_substr", "clone_last_len", "getPattern", "pattern", "match", "match_str", "overlapping", "added_types", "new_seq", "old_seq", "getAttr", "obj", "name", "getAttrNesting", "part", "names", "scoreValue", "value", "token", "weight", "score", "pos", "propToArray", "key", "iterate", "object", "callback", "cmp", "a", "b", "asciifold", "Sifter", "items", "settings", "query", "respect_word_boundaries", "weights", "tokens", "words", "field_regex", "escape_regex", "word", "field_match", "field", "regex", "getPattern", "options", "search", "token_count", "fields", "field_count", "getAttrFn", "scoreObject", "token", "data", "scoreValue", "sum", "value", "iterate", "weight", "score", "implicit_score", "sort_flds", "self", "sort", "get_field", "name", "result", "s", "fld", "a", "b", "sort_fld", "cmp", "optsUser", "propToArray", "getAttrNesting", "getAttr", "fn_score", "item", "id", "_", "fn_sort", "hash_key", "value", "get_hash", "escape_html", "str", "timeout", "fn", "loadDebounce", "delay", "callback", "self", "debounce_events", "types", "type", "trigger", "event_args", "getSelection", "input", "preventDefault", "evt", "stop", "addEvent", "target", "options", "isKeyDown", "key_name", "count", "getId", "el", "id", "existing_id", "addSlashes", "append", "parent", "node", "iterate", "object", "key", "getDom", "query", "isHtmlString", "tpl", "arg", "escapeQuery", "triggerEvent", "dom_el", "event_name", "event", "applyCSS", "css", "addClasses", "elmts", "classes", "norm_classes", "classesArray", "castAsArray", "el", "cls", "removeClasses", "args", "iterate", "_classes", "parentMatch", "target", "selector", "wrapper", "getTail", "list", "direction", "isEmptyObject", "obj", "nodeIndex", "amongst", "setAttr", "attrs", "val", "attr", "replaceNode", "existing", "replacement", "highlight", "element", "regex", "highlightText", "node", "match", "spannode", "middlebit", "middleclone", "replaceNode", "highlightChildren", "highlightRecursive", "removeHighlight", "el", "elements", "parent", "IS_MAC", "KEY_SHORTCUT", "defaults_default", "query", "getSettings", "input", "settings_user", "settings", "defaults_default", "attr_data", "field_label", "field_value", "field_disabled", "field_optgroup", "field_optgroup_label", "field_optgroup_value", "tag_name", "placeholder", "option", "settings_element", "init_select", "tagName", "options", "optionsMap", "group_count", "$order", "readData", "el", "data", "json", "addOption", "group", "value", "hash_key", "arr", "option_data", "addGroup", "optgroup", "id", "optgroup_data", "iterate", "child", "init_textbox", "data_raw", "opt", "_b", "_a", "values", "instance_i", "TomSelect", "MicroPlugin", "MicroEvent", "input_arg", "user_settings", "dir", "input", "getDom", "computedStyle", "settings", "getSettings", "getId", "Sifter", "filter", "value", "wrapper", "control", "dropdown", "dropdown_content", "classes", "inputMode", "control_input", "addClasses", "append", "isHtmlString", "attrs", "iterate", "attr", "setAttr", "self", "focus_node", "passive_event", "listboxId", "control_id", "query", "escapeQuery", "label", "label_click", "addEvent", "label_id", "classes_plugins", "escape_regex", "loadDebounce", "e", "target_match", "parentMatch", "evt", "option", "preventDefault", "doc_mousedown", "target", "win_scroll", "input_invalid", "options", "optgroups", "optgroup", "field_label", "field_optgroup", "templates", "data", "escape", "key", "fn", "callbacks", "get_settings", "triggerEvent", "pastedText", "splitInput", "piece", "hash_key", "character", "isKeyDown", "KEY_SHORTCUT", "next", "prev", "timeout", "wasFocused", "deactivate", "item", "callback", "removeClasses", "classList", "changed", "silent", "events", "debounce_events", "eventName", "i", "begin", "end", "swap", "last", "last_active", "idx", "scroll", "behavior", "content", "height_menu", "scrollTop", "height_item", "y", "activeItems", "focusTarget", "fields", "sort", "result", "calculateScore", "hashed", "triggerDropdown", "j", "k", "n", "html", "has_create_option", "active_group", "create", "groups", "groups_order", "same_query", "results", "active_option", "show_dropdown", "getGroupFragment", "order", "group_order_i", "order_group", "group_fragment", "opt_value", "opt_hash", "get_hash", "option_el", "self_optgroup", "regGroup", "a", "b", "group_order", "group_heading", "group_options", "header", "group_html", "removeHighlight", "tok", "highlight", "add_template", "template", "active_index", "user_created", "dat", "id", "hashed_id", "item_new", "index_item", "value_old", "value_new", "data_old", "option_new", "replaceNode", "boundFilter", "selected", "direction", "type", "all", "addSlashes", "values", "items", "x", "last_item", "wasFull", "nodeIndex", "caret", "output", "created", "isFull", "isLocked", "wrap_classList", "isEmptyObject", "opts", "empty_option", "AddSelected", "escape_html", "has_selected", "reuse_opt", "applyCSS", "setTextboxValue", "trigger", "context", "rect", "top", "left", "el", "selection", "tail", "getSelection", "rm_items", "getTail", "rm_item", "adjacent", "new_pos", "lock", "disabled", "isReadOnly", "revertSettings", "templateName", "when", "method", "new_fn", "orig_method", "result_new", "addEvent", "target", "type", "callback", "options", "addEventListener", "plugin", "input", "sync", "hash_key", "value", "get_hash", "preventDefault", "evt", "stop", "stopPropagation", "getDom", "query", "jquery", "HTMLElement", "isHtmlString", "tpl", "document", "createElement", "innerHTML", "trim", "content", "firstChild", "querySelector", "arg", "indexOf", "plugin", "userOptions", "self", "orig_onOptionSelect", "onOptionSelect", "settings", "hideSelected", "cbOptions", "Object", "assign", "className", "checkedClassNames", "undefined", "uncheckedClassNames", "UpdateChecked", "checkbox", "toCheck", "checked", "classList", "remove", "add", "UpdateCheckbox", "option", "setTimeout", "HTMLInputElement", "contains", "hook", "orig_render_option", "render", "data", "escape_html", "rendered", "call", "addEventListener", "type", "hashed", "valueField", "items", "prepend", "on", "getOption", "removeItem", "dataset", "refreshOptions", "getDom", "query", "jquery", "HTMLElement", "isHtmlString", "tpl", "document", "createElement", "innerHTML", "trim", "content", "firstChild", "querySelector", "arg", "indexOf", "plugin", "userOptions", "self", "options", "Object", "assign", "className", "title", "role", "tabindex", "html", "data", "on", "button", "addEventListener", "evt", "isLocked", "clear", "settings", "mode", "allowEmptyOption", "addItem", "refreshOptions", "preventDefault", "stopPropagation", "control", "appendChild", "preventDefault", "evt", "stop", "stopPropagation", "addEvent", "target", "type", "callback", "options", "addEventListener", "iterate", "object", "Array", "isArray", "forEach", "key", "hasOwnProperty", "getDom", "query", "jquery", "HTMLElement", "isHtmlString", "tpl", "document", "createElement", "innerHTML", "trim", "content", "firstChild", "querySelector", "arg", "indexOf", "setAttr", "el", "attrs", "val", "attr", "removeAttribute", "setAttribute", "insertAfter", "referenceNode", "newNode", "_referenceNode$parent", "parentNode", "insertBefore", "nextSibling", "_referenceNode$parent2", "isBefore", "_newNode", "previousElementSibling", "plugin", "self", "settings", "mode", "orig_lock", "lock", "orig_unlock", "unlock", "sortable", "drag_item", "hook", "orig_render_item", "render", "item", "data", "escape", "call", "mousedown", "dragStart", "setTimeout", "classList", "add", "dragOver", "moveitem", "dragLeave", "remove", "targetitem", "dragitem", "undefined", "dragend", "_drag_item", "querySelectorAll", "values", "control", "dataset", "value", "push", "setValue", "preventDefault", "evt", "stop", "stopPropagation", "getDom", "query", "jquery", "HTMLElement", "isHtmlString", "tpl", "document", "createElement", "innerHTML", "trim", "content", "firstChild", "querySelector", "arg", "indexOf", "plugin", "userOptions", "self", "options", "Object", "assign", "title", "headerClass", "titleRowClass", "labelClass", "closeClass", "html", "data", "on", "header", "close_link", "addEventListener", "close", "dropdown", "insertBefore", "iterate", "object", "callback", "Array", "isArray", "forEach", "key", "hasOwnProperty", "removeClasses", "elmts", "classes", "norm_classes", "classesArray", "castAsArray", "map", "el", "cls", "classList", "remove", "args", "_classes", "trim", "split", "concat", "filter", "Boolean", "arg", "nodeIndex", "amongst", "nodeName", "i", "previousElementSibling", "matches", "plugin", "self", "hook", "new_pos", "settings", "mode", "control", "contains", "control_input", "items", "length", "Math", "max", "min", "caretPos", "isPending", "controlChildren", "child", "j", "insertAdjacentElement", "appendChild", "direction", "isFocused", "last_active", "getLastActive", "idx", "setCaret", "setActiveItem", "preventDefault", "evt", "stop", "stopPropagation", "addEvent", "target", "type", "callback", "options", "addEventListener", "iterate", "object", "Array", "isArray", "forEach", "key", "hasOwnProperty", "getDom", "query", "jquery", "HTMLElement", "isHtmlString", "tpl", "document", "createElement", "innerHTML", "trim", "content", "firstChild", "querySelector", "arg", "indexOf", "addClasses", "elmts", "classes", "norm_classes", "classesArray", "castAsArray", "map", "el", "cls", "classList", "add", "args", "_classes", "split", "concat", "filter", "Boolean", "plugin", "self", "settings", "shouldOpen", "hook", "_self$input", "focus_node", "control", "control_input", "div", "append", "dropdown", "insertBefore", "placeholder", "label", "input", "getAttribute", "setAttribute", "on", "keyCode", "constants", "isOpen", "close", "clearActiveItems", "tabIndex", "onKeyDown", "call", "isDisabled", "focus", "orig_onBlur", "onBlur", "relatedTarget", "preventScroll", "addEvent", "target", "type", "callback", "options", "addEventListener", "plugin", "self", "on", "test_input", "document", "createElement", "control", "control_input", "style", "cssText", "wrapper", "appendChild", "transfer_styles", "style_name", "resize", "textContent", "value", "width", "clientWidth", "plugin", "self", "orig_deleteSelection", "deleteSelection", "hook", "evt", "activeItems", "length", "call", "plugin", "hook", "parentMatch", "target", "selector", "wrapper", "matches", "parentNode", "nodeIndex", "el", "amongst", "nodeName", "i", "previousElementSibling", "plugin", "self", "orig_keydown", "onKeyDown", "hook", "evt", "index", "option", "options", "optgroup", "isOpen", "keyCode", "constants", "call", "ignoreHover", "activeOption", "previousSibling", "nextSibling", "querySelectorAll", "Math", "min", "length", "setActiveOption", "preventDefault", "evt", "stop", "stopPropagation", "addEvent", "target", "type", "callback", "options", "addEventListener", "getDom", "query", "jquery", "HTMLElement", "isHtmlString", "tpl", "document", "createElement", "innerHTML", "trim", "content", "firstChild", "querySelector", "arg", "indexOf", "plugin", "userOptions", "self", "Object", "assign", "label", "title", "className", "tabindex", "role", "html", "data", "_data$tabindex", "el", "setAttribute", "tabIndex", "textContent", "hook", "orig_render_item", "settings", "render", "item", "escape", "call", "close_button", "appendChild", "isLocked", "shouldDelete", "removeItem", "refreshOptions", "inputState", "plugin", "userOptions", "self", "options", "Object", "assign", "text", "option", "settings", "labelField", "on", "value", "isFocused", "control_input", "trim", "setTextboxValue", "call", "iterate", "object", "callback", "Array", "isArray", "forEach", "key", "hasOwnProperty", "addClasses", "elmts", "classes", "norm_classes", "classesArray", "castAsArray", "map", "el", "cls", "classList", "add", "removeClasses", "remove", "args", "_classes", "trim", "split", "concat", "filter", "Boolean", "arg", "plugin", "self", "orig_canLoad", "canLoad", "orig_clearActiveOption", "clearActiveOption", "orig_loadCallback", "loadCallback", "orig_load", "load", "pagination", "dropdown_content", "loading_more", "load_more_opt", "default_values", "default_values_loaded", "default_pagination", "default_options", "html_values", "preload_requested", "settings", "shouldLoadMore", "clientHeight", "scrollHeight", "scrollTop", "activeOption", "selectable", "index", "from", "indexOf", "length", "firstUrl", "sortField", "field", "canLoadMore", "query", "maxOptions", "children", "clearFilter", "option", "value", "items", "setNextUrl", "next_url", "getUrl", "clearPagination", "call", "hook", "loadCallbackForQuery", "was_loading_more", "options", "optgroups", "lastValue", "loading", "Math", "max", "wrapper", "loadingClass", "first_option", "undefined", "dataset", "valueField", "activeFilter", "_option", "clearOptions", "Object", "keys", "values", "isOpen", "loadMoreIfNeeded", "outer_callback", "getAttribute", "setActiveOption", "previousElementSibling", "render", "setAttribute", "querySelector", "optionClass", "append", "restoreDefaults", "contains", "isFocused", "preload", "addOptions", "on", "refreshOptions", "assign", "no_more_results", "addEventListener", "TomSelect", "plugin", "tom_select_complete_default", "Controller", "config", "tom_select_complete_default", "image_field_component_exports", "__export", "Controller", "import_core", "import_companion_client", "import_provider_views", "import_store_default", "import_store_redux", "import_dashboard", "import_drag_drop", "import_drop_target", "import_file_input", "import_image_editor", "import_informer", "import_progress_bar", "import_status_bar", "import_audio", "import_box", "import_dropbox", "import_facebook", "import_google_drive", "import_instagram", "import_onedrive", "import_remote_sources", "import_screen_capture", "import_unsplash", "import_url", "import_webcam", "import_zoom", "import_aws_s3", "import_aws_s3_multipart", "import_transloadit", "import_tus", "import_xhr_upload", "import_compressor", "import_form", "import_golden_retriever", "import_redux_dev_tools", "import_thumbnail_generator", "import_fr_FR", "Controller", "French", "file", "preview", "previewImage", "response", "uploadedFileData", "event", "files", "err", "link_select_component_exports", "__export", "Controller", "Controller", "config", "tom_select_complete_default", "switch_box_component_exports", "__export", "Controller", "Controller", "selector", "text_field_component_exports", "gate_component_exports", "header_component_exports", "__export", "Controller", "Controller", "dark", "heading_component_exports", "layout_component_exports", "__export", "Controller", "isff", "addEvent", "object", "event", "method", "useCapture", "removeEvent", "getMods", "modifier", "key", "modsKeys", "modsCodes", "i", "getKeys", "keys", "index", "compareArray", "a1", "a2", "arr1", "arr2", "isIndex", "getLayoutIndependentKeyCode", "keyMap", "modifierMap", "eventKey", "_keyMap", "_modifier", "_mods", "_handlers", "k", "_downKeys", "winListendFocus", "winListendFullscreen", "winListendPrint", "_scope", "elementEventMap", "code", "x", "getKey", "getModifier", "setScope", "scope", "getScope", "getPressedKeyCodes", "getPressedKeyString", "c", "getAllKeyCodes", "result", "mods", "shortcut", "splitKey", "v", "filter", "target", "tagName", "flag", "isInput", "isPressed", "keyCode", "deleteScope", "newScope", "handlers", "element", "removeKeyEvent", "clearModifier", "hotkeys", "unbind", "keysInfo", "args", "info", "eachUnbind", "originKey", "unbindKeys", "len", "lastKey", "keyCodes", "unbindElements", "record", "isUnbind", "eventHandler", "handler", "modifiersMatch", "y", "dispatch", "asterisk", "keyName", "keyNum", "e", "handlerKey", "keyLen", "keyShortcut", "_downKeysCurrent", "a", "option", "keyup", "keydown", "capture", "single", "opts", "currentKey", "finalKey", "keydownListener", "keyupListenr", "listener", "onFullscreenChange", "fullscreenListener", "webkitListener", "trigger", "item", "data", "values", "findindex", "el", "_api", "_hotkeys", "deep", "composeEventName", "name", "controller", "eventPrefix", "composedName", "extendedEvent", "type", "event", "detail", "bubbles", "cancelable", "composed", "isElementInViewport", "el", "rect", "windowHeight", "windowWidth", "vertInView", "horInView", "defaultOptions$5", "useClickOutside", "controller", "options", "onlyVisible", "dispatchEvent", "events", "eventPrefix", "onEvent", "event", "targetElement", "isElementInViewport", "eventName", "composeEventName", "clickOutsideEvent", "extendedEvent", "observe", "unobserve", "controllerDisconnect", "DebounceController", "Controller", "ThrottleController", "Controller", "Controller", "useClickOutside", "item_component_exports", "item_component_exports", "tree_component_exports", "__export", "Controller", "_defineProperty", "e", "r", "t", "_toPropertyKey", "_extends", "n", "ownKeys", "e", "r", "t", "o", "_objectSpread2", "_defineProperty", "_objectWithoutProperties", "i", "_objectWithoutPropertiesLoose", "n", "_toPrimitive", "r", "e", "i", "_toPropertyKey", "_typeof", "o", "version", "userAgent", "pattern", "IE11OrLess", "Edge", "FireFox", "Safari", "IOS", "ChromeForAndroid", "captureMode", "on", "el", "event", "fn", "off", "matches", "selector", "getParentOrHost", "closest", "ctx", "includeCTX", "R_SPACE", "toggleClass", "name", "state", "className", "css", "prop", "val", "style", "matrix", "selfOnly", "appliedTransforms", "transform", "matrixFn", "find", "tagName", "iterator", "list", "i", "n", "getWindowScrollingElement", "scrollingElement", "getRect", "relativeToContainingBlock", "relativeToNonStaticParent", "undoScale", "container", "elRect", "top", "left", "bottom", "right", "height", "width", "containerRect", "elMatrix", "scaleX", "scaleY", "isScrolledPast", "elSide", "parentSide", "parent", "getParentAutoScrollElement", "elSideVal", "parentSideVal", "visible", "getChild", "childNum", "options", "includeDragEl", "currentChild", "children", "Sortable", "lastChild", "last", "index", "getRelativeScrollOffset", "offsetLeft", "offsetTop", "winScroller", "indexOfObject", "arr", "obj", "key", "includeSelf", "elem", "gotSelf", "elemCSS", "extend", "dst", "src", "isRectEqual", "rect1", "rect2", "_throttleTimeout", "throttle", "callback", "ms", "args", "_this", "cancelThrottle", "scrollBy", "x", "y", "clone", "Polymer", "$", "getChildContainingRectFromElement", "container", "options", "ghostEl", "rect", "child", "_rect$left", "_rect$top", "_rect$right", "_rect$bottom", "closest", "childRect", "getRect", "expando", "AnimationStateManager", "animationStates", "animationCallbackId", "children", "css", "Sortable", "fromRect", "_objectSpread2", "childMatrix", "matrix", "state", "target", "indexOfObject", "callback", "_this", "animating", "animationTime", "time", "toRect", "prevFromRect", "prevToRect", "animatingRect", "targetMatrix", "isRectEqual", "calculateRealTime", "currentRect", "duration", "elMatrix", "scaleX", "scaleY", "translateX", "translateY", "repaint", "plugins", "defaults", "PluginManager", "plugin", "option", "p", "eventName", "sortable", "evt", "eventNameGlobal", "el", "pluginName", "initialized", "_extends", "modified", "name", "eventProperties", "value", "modifiedValue", "dispatchEvent", "_ref", "rootEl", "targetEl", "cloneEl", "toEl", "fromEl", "oldIndex", "newIndex", "oldDraggableIndex", "newDraggableIndex", "originalEvent", "putSortable", "extraEventProperties", "onName", "IE11OrLess", "Edge", "allEventProperties", "_excluded", "pluginEvent", "data", "_objectWithoutProperties", "dragEl", "parentEl", "nextEl", "lastDownEl", "cloneHidden", "moved", "_hideGhostForTarget", "_unhideGhostForTarget", "_dispatchEvent", "info", "activeGroup", "awaitingDragStarted", "ignoreNextClick", "sortables", "tapEvt", "touchEvt", "lastDx", "lastDy", "tapDistanceLeft", "tapDistanceTop", "lastTarget", "lastDirection", "pastFirstInvertThresh", "isCircumstantialInvert", "targetMoveDistance", "ghostRelativeParent", "ghostRelativeParentInitialScroll", "_silent", "savedInputChecked", "documentExists", "PositionGhostAbsolutely", "IOS", "CSSFloatProperty", "supportDraggable", "ChromeForAndroid", "supportCssPointerEvents", "_detectDirection", "elCSS", "elWidth", "child1", "getChild", "child2", "firstChildCSS", "secondChildCSS", "firstChildWidth", "secondChildWidth", "touchingSideChild2", "_dragElInRowColumn", "dragRect", "targetRect", "vertical", "dragElS1Opp", "dragElS2Opp", "dragElOppLength", "targetS1Opp", "targetS2Opp", "targetOppLength", "_detectNearestEmptySortable", "x", "y", "ret", "threshold", "lastChild", "insideHorizontally", "insideVertically", "_prepareGroup", "toFn", "pull", "to", "from", "sameGroup", "otherGroup", "group", "originalGroup", "_typeof", "nearestEmptyInsertDetectEvent", "nearest", "event", "i", "_checkOutsideTargetEl", "dataTransfer", "Safari", "fn", "on", "preventOnFilter", "type", "touch", "originalTarget", "filter", "_saveInputCheckedState", "index", "criteria", "ownerDocument", "dragStartFn", "FireFox", "toggleClass", "find", "_disableDraggable", "off", "_nextTick", "fallback", "parent", "inserted", "getParentOrHost", "fallbackTolerance", "fallbackOffset", "ghostMatrix", "relativeScrollOffset", "getRelativeScrollOffset", "dx", "dy", "cssMatrix", "getWindowScrollingElement", "clone", "revert", "activeSortable", "isOwner", "canSort", "fromSortable", "completedFired", "dragOverEvent", "extra", "completed", "after", "_onMove", "changed", "capture", "insertion", "elLastChild", "_ghostIsLast", "_ghostIsFirst", "firstChild", "direction", "targetBeforeFirstSwap", "differentLevel", "differentRowCol", "side1", "scrolledPastTop", "isScrolledPast", "scrollBefore", "_getSwapDirection", "sibling", "dragIndex", "nextSibling", "moveVector", "_unsilent", "scrollBy", "_cancelNextTick", "checkEl", "_globalDragOver", "order", "n", "_generateId", "useAnimation", "items", "id", "store", "selector", "willInsertAfter", "onMoveFn", "retVal", "firstElRect", "childContainingRect", "spacer", "lastElRect", "swapThreshold", "invertedSwapThreshold", "invertSwap", "isLastTarget", "mouseOnAxis", "targetLength", "targetS1", "targetS2", "invert", "_getInsertDirection", "str", "sum", "root", "inputs", "idx", "extend", "throttle", "element", "_len", "_key", "version", "autoScrolls", "scrollEl", "scrollRootEl", "scrolling", "lastAutoScrollX", "lastAutoScrollY", "touchEvt$1", "pointerElemChangedInterval", "AutoScrollPlugin", "AutoScroll", "_ref2", "clearPointerElemChangedInterval", "clearAutoScrolls", "cancelThrottle", "elem", "autoScroll", "ogElemScroller", "getParentAutoScrollElement", "newElem", "isFallback", "sens", "speed", "winScroller", "scrollThisInstance", "scrollCustomFn", "layersOut", "currentParent", "top", "bottom", "left", "right", "width", "height", "canScrollX", "canScrollY", "scrollWidth", "scrollHeight", "scrollPosX", "scrollPosY", "vx", "vy", "scrollOffsetY", "scrollOffsetX", "drop", "dispatchSortableEvent", "hideGhostForTarget", "unhideGhostForTarget", "toSortable", "Revert", "_ref3", "Remove", "_ref4", "parentSortable", "Sortable", "AutoScrollPlugin", "Remove", "Revert", "sortable_esm_default", "Controller", "subtree", "sortable_esm_default", "e", "list_component_exports", "__export", "Controller", "Controller", "sortable_esm_default", "sortable", "orderHash", "hash", "id", "index", "menu_component_exports", "activities_grid_component_exports", "agenda_component_exports", "features_grid_component_exports", "hero_component_exports", "slate_component_exports", "tabs_component_exports", "__export", "Controller", "Controller", "tab", "move", "index", "next", "toast_component_exports", "__export", "Controller", "Controller", "toaster_component_exports", "article_component_exports", "button_component_exports", "figure_component_exports", "gallery_component_exports", "map_component_exports", "__export", "Controller", "Point", "e", "t", "x", "y", "u", "p", "k", "a", "m", "other", "dx", "dy", "b", "cos", "angle", "sin", "unitBezier", "n", "cx", "p1x", "bx", "p2x", "ax", "cy", "p1y", "by", "p2y", "ay", "i", "r", "x2", "epsilon", "d2", "t0", "t1", "s", "supportsOffscreenCanvas", "offscreenCanvasSupported", "f", "offscreenCanvasDistorted", "isOffscreenCanvasDistorted", "context", "base", "data", "ARRAY_TYPE", "create", "out", "glMatrix.ARRAY_TYPE", "invert", "a0", "a1", "a2", "a3", "det", "o", "determinant", "rotate", "rad", "c", "a00", "a01", "a02", "a10", "a11", "a12", "a20", "a21", "a22", "fromRotation", "fromQuat", "q", "z", "w", "y2", "z2", "xx", "yx", "yy", "zx", "zy", "zz", "wx", "wy", "wz", "clone", "copy", "identity", "a03", "a13", "a23", "a30", "a31", "a32", "a33", "b00", "b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "A", "multiply", "b0", "b1", "b2", "b3", "S", "translate", "v", "l", "d", "h", "g", "_", "scale", "rotateX", "rotateY", "rotateZ", "fromScaling", "perspectiveNO", "fovy", "aspect", "far", "nf", "near", "perspective", "orthoNO", "lr", "left", "right", "bt", "bottom", "top", "ortho", "exactEquals", "equals", "a4", "a5", "a6", "a7", "a8", "a9", "a14", "a15", "b4", "b5", "b6", "b7", "b8", "b9", "b12", "b13", "b14", "b15", "length", "fromValues", "add", "subtract", "scaleAndAdd", "distance", "negate", "normalize", "len", "dot", "cross", "az", "bz", "lerp", "transformMat4", "transformMat3", "transformQuat", "qx", "qy", "qz", "qw", "vx", "vy", "vz", "tx", "ty", "tz", "zero", "sub", "vec", "stride", "offset", "count", "fn", "arg", "set", "mul", "setAxisAngle", "axis", "aw", "bw", "slerp", "omega", "cosom", "sinom", "scale0", "scale1", "fromMat3", "fTrace", "fRoot", "j", "fromEuler", "order", "halfToRad", "sx", "sy", "sz", "cz", "vec4.set", "vec4.normalize", "tmpvec3", "vec3.create", "xUnitVec3", "vec3.fromValues", "yUnitVec3", "vec3.dot", "vec3.len", "normalize$2", "temp1", "temp2", "matr", "mat3.create", "up", "view", "squaredLength", "sqrLen", "EXTENT", "pixelsToTileUnits", "pixelValue", "tile", "ensureError", "createVec4f64", "createVec3f64", "createMat4f64", "createIdentityMat4f64", "identity$1", "createIdentityMat4f32", "translatePosition", "inViewportPixelUnitsUnits", "translateAnchor", "transform", "sinA", "cosA", "pointPlaneSignedDistance", "plane", "point", "threePlaneIntersection", "mat3.determinant", "plane0", "plane1", "plane2", "cross12", "vec3.cross", "cross20", "cross01", "sum", "vec3.scale", "scale$2", "rayPlaneIntersection", "dotOriginPlane", "origin", "dotDirectionPlane", "direction", "angleToRotateBetweenVectors2D", "length1", "vec1x", "vec1y", "length2", "vec2x", "vec2y", "differenceOfAnglesDegrees", "mod", "degreesA", "degreesB", "diff1", "diff2", "distanceOfAnglesRadians", "radiansA", "radiansB", "remapSaturate", "newRangeMin", "newRangeMax", "clamp", "value", "oldRangeMin", "oldRangeMax", "mix", "getAABB", "tlX", "tlY", "brX", "brY", "points", "getEdgeTiles", "tileIDs", "targetZ", "id", "minX", "maxX", "minY", "maxY", "projected", "px", "py", "edgeTiles", "easeCubicInOut", "t2", "t3", "bezier", "unitBezierFactory", "defaultEasing", "max", "min", "wrap", "extend", "sources", "src", "dest", "pick", "result", "properties", "uniqueId", "Et", "isPowerOfTwo", "nextPowerOfTwo", "zoomScale", "zoom", "scaleZoom", "evaluateZoomSnap", "zoomSnap", "inv", "delta", "mapObject", "output", "key", "input", "iterator", "filterObject", "deepEqual", "warnOnceHistory", "warnOnce", "message", "Lt", "isCounterClockwise", "findLineIntersection", "aDeltaY", "aDeltaX", "bDeltaY", "bDeltaX", "denominator", "originDeltaY", "originDeltaX", "aInterpolation", "sphericalToCartesian", "azimuthal", "polar", "isWorker", "self", "parseCacheControl", "re", "header", "cacheControl", "$2", "$3", "$1", "maxAge", "_isSafari", "isSafari", "userAgent", "scope", "Ut", "isImageBitmap", "image", "arrayBufferToImageBitmap", "blob", "options", "arrayBufferToImage", "img", "resolve", "reject", "computeVideoFrameParameters", "destRowOffset", "width", "sourceLeft", "sourceTop", "sourceRight", "sourceBottom", "height", "readImageUsingVideoFrame", "frame", "format", "swapBR", "tmp", "subscribe", "target", "listener", "degreesToRadians", "degrees", "radiansToDegrees", "rollPitchBearingEqual", "getRollPitchBearing", "rotation", "xAngle", "roll", "bearing", "getAngleDelta", "pointVect", "vec2.fromValues", "currentPoint", "center", "lastPointVec", "lastPoint", "crossProduct", "vec2.dot", "rollPitchBearingToQuat", "pitch", "MAX_VALID_LATITUDE", "touchableEvents", "pointableEvents", "isTouchableEvent", "eventType", "event", "isPointableEvent", "domEvent", "targetWindow", "isTouchableOrPointableType", "ABORT_ERROR", "AbortError", "messageOrError", "isAbortError", "error", "throwIfAborted", "signal", "linkEl", "reducedMotionQuery", "reducedMotionOverride", "browser", "win", "frameId", "unsubscribe", "paintStartTimestamp", "abortController", "padding", "canvas", "mn", "path", "hn", "gn", "timeManager", "timestamp", "now", "setNow", "restoreNow", "isTimeFrozen", "ALLOWED_TAGS", "ALLOWED_ATTRIBUTES", "URL_ATTRIBUTES", "ALLOWED_PROTOCOLS", "elementInternals", "getElementInternals", "Dn", "DOM", "el", "tagName", "className", "container", "namespaceURI", "rect", "element", "touch", "touches", "body", "str", "querySelectorAll", "remove", "fragment", "localName", "name", "getAttributeNames", "getAttribute", "removeAttribute", "config", "getProtocol", "url", "addProtocol", "kn", "customProtocol", "loadFn", "removeProtocol", "GLOBAL_DISPATCHER_ID", "AJAXError", "statusText", "status", "getReferrer", "isFileURL", "makeFetchRequest", "request", "requestParameters", "response", "parsePromise", "makeXMLHttpRequest", "xhr", "err", "makeRequest", "protocolLoadFn", "getJSON", "getArrayBuffer", "sameOrigin", "inComingUrl", "urlObj", "locationObj", "getVideo", "video", "urls", "_addEventListener", "listenerList", "type", "_removeEventListener", "index", "Event", "ErrorEvent", "Evented", "firedEvent", "listeners", "oneTimeListeners", "parent", "TransferableGridIndex", "cells", "extent", "array", "start", "end", "keysOffset", "bboxesOffset", "x1", "y1", "cellIndex", "uid", "intersectionTest", "cell", "keys", "bboxes", "seenUids", "cx1", "cy1", "cx2", "cy2", "arg1", "arg2", "metadataLength", "totalCellLength", "buffer", "grid", "transferables", "serialized", "v8_default", "\"version\"", "\"required\"", "\"type\"", "\"values\"", "\"name\"", "\"metadata\"", "\"center\"", "\"value\"", "\"length\"", "\"centerAltitude\"", "\"zoom\"", "\"bearing\"", "\"default\"", "\"period\"", "\"units\"", "\"pitch\"", "\"roll\"", "\"state\"", "\"light\"", "\"sky\"", "\"projection\"", "\"terrain\"", "\"sources\"", "\"sprite\"", "\"glyphs\"", "\"transition\"", "\"layers\"", "\"vector\"", "\"url\"", "\"tiles\"", "\"bounds\"", "\"scheme\"", "\"xyz\"", "\"tms\"", "\"emptyResponse\"", "\"blank\"", "\"missing\"", "\"minzoom\"", "\"maxzoom\"", "\"attribution\"", "\"promoteId\"", "\"volatile\"", "\"encoding\"", "\"mvt\"", "\"mlt\"", "\"raster\"", "\"tileSize\"", "\"terrarium\"", "\"mapbox\"", "\"custom\"", "\"redFactor\"", "\"blueFactor\"", "\"greenFactor\"", "\"baseShift\"", "\"geojson\"", "\"data\"", "\"buffer\"", "\"maximum\"", "\"minimum\"", "\"filter\"", "\"tolerance\"", "\"cluster\"", "\"clusterRadius\"", "\"clusterMaxZoom\"", "\"clusterMinPoints\"", "\"clusterProperties\"", "\"lineMetrics\"", "\"generateId\"", "\"video\"", "\"urls\"", "\"coordinates\"", "\"image\"", "\"id\"", "\"fill\"", "\"line\"", "\"symbol\"", "\"circle\"", "\"heatmap\"", "\"hillshade\"", "\"background\"", "\"source\"", "\"layout\"", "\"paint\"", "\"visibility\"", "\"visible\"", "\"none\"", "\"expression\"", "\"interpolated\"", "\"parameters\"", "\"butt\"", "\"round\"", "\"square\"", "\"bevel\"", "\"miter\"", "\"requires\"", "\"point\"", "\"auto\"", "\"never\"", "\"always\"", "\"cooperative\"", "\"map\"", "\"viewport\"", "\"width\"", "\"height\"", "\"both\"", "\"tokens\"", "\"left\"", "\"right\"", "\"top\"", "\"bottom\"", "\"horizontal\"", "\"vertical\"", "\"uppercase\"", "\"lowercase\"", "\"ground\"", "\"absolute\"", "\"in\"", "\"all\"", "\"any\"", "\"has\"", "\"Point\"", "\"LineString\"", "\"Polygon\"", "\"function\"", "\"stops\"", "\"base\"", "\"property\"", "\"identity\"", "\"exponential\"", "\"interval\"", "\"categorical\"", "\"colorSpace\"", "\"rgb\"", "\"lab\"", "\"hcl\"", "\"anchor\"", "\"position\"", "\"color\"", "\"intensity\"", "\"exaggeration\"", "\"normal\"", "\"multiply\"", "\"luminosity\"", "\"screen\"", "\"overlay\"", "\"overridable\"", "\"resampling\"", "\"linear\"", "\"nearest\"", "\"standard\"", "\"basic\"", "\"combined\"", "\"igor\"", "\"multidirectional\"", "\"duration\"", "\"delay\"", "\"constant\"", "\"syntax\"", "\"overloads\"", "latest", "refProperties", "deref", "layer", "derefLayers", "layers", "map", "addCommand", "commands", "command", "addSource", "sourceId", "after", "removeSource", "updateSource", "sourcesRemoved", "canUpdateGeoJSON", "prop", "before", "diffSources", "addPropertyCommand", "layerId", "diffLayerPropertyChanges", "pluckId", "indexById", "group", "diffLayers", "beforeOrder", "afterOrder", "beforeIndex", "afterIndex", "tracker", "clean", "beforeLayer", "afterLayer", "insertBeforeLayerId", "diff", "terrainChanged", "removeOrAddSourceCommands", "beforeLayers", "ValidationError", "identifier", "severity", "NullType", "NumberType", "StringType", "BooleanType", "ColorType", "ProjectionDefinitionType", "ObjectType", "ValueType", "ErrorType", "CollatorType", "FormattedType", "PaddingType", "ColorArrayType", "NumberArrayType", "ResolvedImageType", "VariableAnchorOffsetCollectionType", "typeToString", "itemType", "valueMemberTypes", "checkSubtype", "expected", "memberType", "isValidType", "allowedTypes", "provided", "isValidNativeType", "verifyType", "sample", "Xn", "Zn", "deg2rad", "rad2deg", "constrainAngle", "rgbToLab", "alpha", "rgb2xyz", "xyz2lab", "labToRgb", "lab2xyz", "xyz2rgb", "rgbToHcl", "rgbColor", "hclToRgb", "hslToRgb", "hasOwnProperty", "object", "getOwn", "parseCssColor", "namedColorsMatch", "namedColors", "step", "parseHex", "rgbMatch", "rp", "f1", "gp", "f2", "bp", "f3", "ap", "argFormat", "valFormat", "maxValue", "rgba", "parseAlpha", "validateNumbers", "hslMatch", "hsla", "hex", "asPercentage", "interpolateNumber", "from", "to", "interpolateArray", "isSupportedInterpolationColorSpace", "colorSpace", "Color", "premultiplied", "getterKey", "lazyValue", "spaceKey", "hue0", "chroma0", "light0", "alphaF", "hue1", "chroma1", "light1", "alphaT", "hue", "chroma", "dh", "VERTICAL_ALIGN_OPTIONS", "FormattedSection", "text", "fontStack", "textColor", "verticalAlign", "Formatted", "sections", "unformatted", "section", "Padding", "values", "val", "NumberArray", "ColorArray", "parsed_val", "colors", "RuntimeError", "anchors", "VariableAnchorOffsetCollection", "anchorValue", "offsetValue", "toValues", "fx", "fy", "ResolvedImage", "ProjectionDefinition", "transition", "Collator", "caseSensitive", "diacriticSensitive", "locale", "lhs", "rhs", "validateRGBA", "isValue", "mixed", "item", "typeOf", "valueToString", "Literal", "args", "geometryTypes", "EvaluationContext", "cached", "findStopLessThanOrEqualTo", "lastIndex", "stops", "lowerIndex", "upperIndex", "currentIndex", "currentValue", "nextValue", "Step", "label", "expression", "outputType", "labelKey", "valueKey", "parsed", "labels", "outputs", "ctx", "stopCount", "Interpolate", "operator", "interpolation", "exponentialInterpolation", "lower", "upper", "rest", "controlPoints", "outputLower", "outputUpper", "difference", "upperValue", "lowerValue", "progress", "interpolateFactory", "FormatExpression", "firstArg", "nextTokenMayBeObject", "font", "lastExpression", "content", "kind", "evaluatedContent", "quickselect", "arr", "defaultCompare", "sd", "compare", "swap$2", "swap", "classifyRings", "rings", "polygons", "polygon", "ccw", "ring", "area", "calculateSignedArea", "maxRings", "compareAreas", "p1", "p2", "types", "Assertion", "N", "Coercion", "pad", "coll", "num", "Let", "bindings", "binding", "Var", "boundExpression", "At", "In", "needle", "haystack", "IndexOf", "fromIndex", "rawIndex", "Match", "inputType", "cases", "otherwise", "labelContext", "Case", "branches", "test", "Slice", "beginIndex", "endIndex", "Coalesce", "expectedType", "parsedArgs", "argCount", "requestedImageName", "isComparableType", "op", "eq", "neq", "lt", "gt", "lteq", "gteq", "eqCollate", "neqCollate", "ltCollate", "gtCollate", "lteqCollate", "gteqCollate", "makeComparison", "isOrderComparison", "Comparison", "collator", "rt", "compareBasic", "compareWithCollator", "Equals", "NotEquals", "LessThan", "GreaterThan", "LessThanOrEqual", "GreaterThanOrEqual", "CollatorExpression", "\"locale\"", "NumberFormat", "number", "currency", "unit", "minFractionDigits", "maxFractionDigits", "\"currency\"", "\"unit\"", "ImageExpression", "evaluatedImageName", "Length", "getTileCoordinates", "mercatorXfromLng", "mercatorYfromLat", "tilesAtZoom", "canonical", "getLngLatFromTileCoord", "coord", "lngFromMercatorXfromLng", "latFromMercatorY", "lng", "mercatorX", "lat", "mercatorY", "updateBBox", "bbox", "boxWithinBox", "bbox1", "bbox2", "rayIntersect", "pointOnBoundary", "segmentIntersectSegment", "vectorP", "perp", "twoSided", "lineIntersectPolygon", "pointWithinPolygon", "inside", "trueIfOnBoundary", "pointWithinPolygons", "lineStringWithinPolygon", "line", "lineStringWithinPolygons", "v1", "v2", "q1", "x3", "q2", "y3", "det1", "det2", "getTilePolygon", "coordinates", "getTilePolygons", "updatePoint", "polyBBox", "halfWorldSize", "worldSize", "shift", "resetBBox", "getTilePoints", "shifts", "tilePoints", "geometry", "pointBBox", "getTileLines", "tileLines", "tileLine", "lineBBox", "pointsWithinPolygons", "polygonGeometry", "tilePolygon", "tilePolygons", "linesWithinPolygons", "Within", "geojson", "geometries", "polygonsCoords", "TinyQueue", "pos", "current", "halfLength", "bestChild", "RAD", "CheapRuler", "coslat", "w2", "minDist", "minI", "minT", "sqDist", "deg", "compareDistPair", "getRangeSize", "range", "isRangeSafe", "threshold", "splitRange", "size", "isLine", "size1", "getBBox", "coords", "getPolygonBBox", "isValidBBox", "bboxToBBoxDistance", "ruler", "pointToLineDistance", "nearestPoint", "segmentToSegmentDistance", "dist1", "dist2", "lineToLineDistance", "range1", "line1", "range2", "line2", "dist", "pointsToPointsDistance", "points1", "points2", "pointToPolygonDistance", "front", "back", "lineToPolygonDistance", "polygonIntersect", "poly1", "poly2", "polygonToPolygonDistance", "polygon1", "polygon2", "currentMiniDist", "ring1", "len1", "ring2", "len2", "updateQueue", "rangeA", "tempDist", "miniDist", "distQueue", "updateQueueTwoSets", "pointSet1", "pointSet2", "pointsToPolygonDistance", "distPair", "newRangesA", "pointSetToPointSetDistance", "rangeB", "threshold1", "isLine1", "threshold2", "isLine2", "sublibe", "newRangesB", "pointToGeometryDistance", "pointPosition", "lineStringToGeometryDistance", "linePositions", "polygonToGeometryDistance", "toSimpleGeometry", "lineString", "Distance", "feature", "Semiliteral", "elementType", "expr", "arrayContext", "GlobalState", "globalState", "expressions", "ExpressionParsingError", "Scope", "ParsingContext", "registry", "part", "errors", "isConstantFunc", "annotate", "typeAnnotation", "Expr", "actual", "ec", "CompoundExpression", "evaluate", "definition", "availableOverloads", "overloads", "signature", "signatureContext", "params", "isExpressionConstant", "argParseFailed", "signatures", "stringifySignature", "actualTypes", "definitions", "has", "obj", "get", "binarySearch", "varargs", "props", "isSupportedScript", "delim", "isTypeAnnotation", "childrenConstant", "child", "isFeatureConstant", "isGlobalPropertyConstant", "isStateConstant", "supportsPropertyExpression", "spec", "supportsZoomExpression", "supportsInterpolation", "transitionPropertyRegExp", "extendBy", "inputs", "getType", "isFunction", "identityFunction", "getParseFunction", "propertySpec", "getInnerFunction", "evaluateExponentialFunction", "evaluateIntervalFunction", "evaluateCategoricalFunction", "evaluateIdentityFunction", "createFunction", "zoomAndFeatureDependent", "parameters", "featureDependent", "zoomDependent", "parseFn", "stop", "innerFun", "hashedStops", "categoricalKeyType", "featureFunctions", "zoomStops", "featureFunctionStops", "interpolationType", "coalesce", "keyType", "interpolationFactor", "interp", "evaluatedLower", "evaluatedUpper", "success", "StyleExpression", "getDefaultValue", "rootKey", "addGlobalState", "globals", "featureState", "availableImages", "formattedSection", "dedupKey", "formatRuntimeWarning", "defaultValue", "assertRootKey", "isExpression", "createExpression", "parser", "getExpectedType", "ZoomConstantExpression", "findGlobalStateRefs", "ZoomDependentExpression", "isZoomExpression", "createPropertyExpression", "expressionInput", "isFeatureConstantResult", "isZoomConstant", "zoomCurve", "findZoomCurve", "StylePropertyFunction", "specification", "normalizePropertyExpression", "constant", "seen", "childResult", "results", "childExpression", "classifyChildren", "sawLegacy", "children", "classification", "classifyFilter", "filter", "isExpressionFilter", "getFilterPropertyExpression", "property", "getLegacyFilterExpressionSuggestion", "getMixedFilterMessage", "suggestion", "checkChild", "findMixedLegacyFilter", "diagnostic", "warnAboutMixedLegacyFilter", "filterSpec", "featureFilter", "convertFilter", "compiled", "globalProperties", "geometryNeeded", "convertComparisonOp", "convertNegation", "convertDisjunctionOp", "convertInOp", "convertHasOp", "filters", "emptyStyle", "style", "version", "\"$version\"", "styleKey", "\"$root\"", "validateConstants", "constants", "unbundle", "deepUnbundle", "unbundledValue", "validateObject", "elementSpecs", "elementValidators", "styleSpec", "validateSpec", "objectKey", "elementSpecKey", "elementSpec", "validateElement", "validateArray", "arraySpec", "validateArrayElement", "arrayElementSpec", "validateNumber", "valueSpec", "validateFunction", "functionValueSpec", "functionType", "stopKeyType", "stopDomainValues", "previousStopDomainValue", "previousStopDomainZoom", "isZoomFunction", "isPropertyFunction", "isZoomAndPropertyFunction", "validateFunctionStops", "validateFunctionDefault", "validateFunctionStop", "validateStopDomainValue", "reportValue", "validateExpression", "expressionObj", "validateBoolean", "validateColor", "validateEnum", "getValueAtPath", "validateNoMixedLegacyFilter", "validateFilter", "validateNonExpressionFilter", "validateProperty", "propertyKey", "layerSpec", "propertyType", "transitionMatch", "tokenMatch", "validatePaintProperty", "validateLayoutProperty", "validateLayer", "ref", "otherLayer", "source", "sourceType", "validateString", "validateRasterDEMSource", "sourceName", "rasterDEM", "rasterDEMSpec", "rootType", "isCustomEncoding", "customEncodingKeys", "encodingName", "objectElementValidators", "validatePromoteId", "validateSource", "lc", "mapExpr", "reduceExpr", "validateLight", "light", "lightSpec", "validateSky", "sky", "skySpec", "validateTerrain", "terrain", "terrainSpec", "validateFormatted", "validateImage", "validatePadding", "validateNumberArray", "validateColorArray", "validateVariableAnchorOffsetCollection", "\"layout_symbol\"", "validateSprite", "sprite", "allSpriteIds", "allSpriteURLs", "validateProjection", "projection", "projectionSpec", "validateProjectionDefinition", "isProjectionDefinitionValue", "isPropertyValueSpecification", "isObjectLiteral", "anything", "validateState", "MAX_CODE_POINT", "UNICODE_RANGE_REGEX", "validateUnicodeRange", "invalid", "match", "wildcard", "startCodePoint", "endCodePoint", "validateFontFaces", "fontName", "fontValue", "fontValueType", "fontFaceSpec", "fontFace", "fontFaceKey", "unicodeRanges", "unicodeRange", "VALIDATORS", "validate", "validateGlyphsUrl", "validateStyleMin", "\"constants\"", "sortErrors", "Fc", "wrapCleanErrors", "injectValidateSpec", "validator", "inner", "visibilitySpec", "VisibilityExpressionClass", "visibility", "createVisibility", "register", "klass", "Hc", "isArrayBuffer", "getClassRegistryKey", "isRegistered", "classRegistryKey", "isSerializeHandledByBuiltin", "serialize", "deserialize", "ThrottledInvoker", "methodToThrottle", "addEventDefaultOptions", "Actor", "mapId", "handler", "subscription", "cancelMessage", "reason", "buffers", "messageToPost", "SPECIAL_ORIGINS", "origins", "isSameOrigin", "hasSpecialOrigin", "task", "resolveReject", "responseMessage", "createActors", "workerErrorSubscriptions", "workers", "worker", "errorTarget", "actor", "isCrossOrigin", "loc", "defaultWorkerUrl", "moduleUrl", "import_meta", "workerName", "packageJSON.version", "isClassicWorkerUrl", "createWorker", "asModule", "fetchWorkerCode", "fetchAsBlobUrl", "hasOpaqueOrigin", "fetchAsDataUrl", "importAsBlobUrl", "workerFactory", "blobUrl", "PRELOAD_POOL_ID", "WorkerPool", "promises", "workersPromise", "promise", "availableLogicalProcessors", "ul", "globalWorkerPool", "getGlobalWorkerPool", "fl", "prewarm", "clearPrewarmedResources", "pool", "GlobalDispatcher", "workerPool", "actors", "actorsPromise", "workerUrl", "timer", "timeoutMs", "globalDispatcher", "getGlobalDispatcher", "_l", "ImageRequest", "imageRequestQueue", "currentParallelImageRequests", "throttleControlCallbackHandleCounter", "throttleControlCallbacks", "handle", "callback", "callbackHandle", "processQueue", "isThrottled", "transformAndGetImage", "requestManager", "resourceType", "supportImageRefresh", "imageBitmapOptions", "arrayBufferToCanvasImageSource", "doImageRequest", "itemInQueue", "canUseHTMLImageElement", "acc", "getImagePromise", "getImageUsingHtmlImage", "onSuccess", "onError", "maxImageRequests", "numImageRequests", "topItemInQueue", "credentials", "RequestManager", "transformRequestFn", "transformRequest", "MapLibreEvent", "MapMovementEvent", "MapStyleLoadEvent", "MapStyleDataEvent", "MapSourceDataEvent", "MapMouseEvent", "originalEvent", "lngLat", "MapTouchEvent", "lngLats", "prev", "curr", "MapWheelEvent", "MapBoxZoomEvent", "MapTerrainEvent", "MapProjectionEvent", "MapContextEvent", "MapStyleImageMissingEvent", "validateStyle", "SPEC_SOURCE_TYPES", "unjudgeableSourceKeys", "validateStyleAndEmit", "ignored", "emitValidationErrors", "emitter", "hasErrors", "validateAndEmit", "ZoomHistory", "floorZ", "EvaluationParameters", "fraction", "PropertyValue", "globalStateRefs", "refs", "TransitionablePropertyValue", "prior", "TransitioningPropertyValue", "Transitionable", "transitioning", "priorGlobalState", "changed", "Transitioning", "finalValue", "PossiblyEvaluated", "Layout", "PossiblyEvaluatedPropertyValue", "getArrayValueLength", "isNonInterpolableArrayChange", "lengthA", "lengthB", "DataConstantProperty", "interpolationFn", "interpolates", "DataDrivenProperty", "overrides", "interpolatedValue", "CrossFadedDataDrivenProperty", "evaluatedValue", "constantValue", "cameraVal", "mid", "CrossFadedProperty", "ColorRampProperty", "Properties", "defaultPropertyValue", "defaultTransitionablePropertyValue", "ERROR_PAINT_NOT_LAYOUT", "ERROR_LAYOUT_NOT_PAINT", "StyleLayer", "createVisibilityExpression", "globalStateRef", "propertyName", "baseName", "transitionable", "isCrossFadedProperty", "wasDataDriven", "oldValue", "newValue", "roundMinZoom", "paint", "getPaint", "iu", "\"paint_raster\"", "raster_style_layer_properties_g_default", "isRasterStyleLayer", "RasterStyleLayer", "viewTypes", "\"Int8\"", "\"Uint8\"", "\"Int16\"", "\"Uint16\"", "\"Int32\"", "\"Uint32\"", "\"Float32\"", "Struct", "structArray", "StructArray", "oldUint8Array", "createLayout", "maxSize", "members", "typeSize", "sizeOf", "member", "memberOffset", "align", "alignment", "components", "StructArrayLayout2i4", "v0", "o2", "hu", "StructArrayLayout3i6", "gu", "StructArrayLayout4i8", "v3", "_u", "StructArrayLayout2i4i12", "v4", "v5", "vu", "StructArrayLayout2i4ub2b10", "v6", "v7", "o1", "yu", "StructArrayLayout2f8", "o4", "bu", "StructArrayLayout10ui20", "v8", "v9", "xu", "StructArrayLayout8ui16", "Su", "StructArrayLayout4i4ui4i1f28", "v10", "v11", "v12", "Cu", "StructArrayLayout3f12", "wu", "StructArrayLayout1ul4", "Tu", "StructArrayLayout6i1ul2ui20", "Eu", "StructArrayLayout2i2i2i12", "Du", "StructArrayLayout2f1f2i16", "Ou", "StructArrayLayout2ub2f2i16", "ku", "StructArrayLayout3ui6", "Au", "StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52", "v13", "v14", "v15", "v16", "v17", "ju", "StructArrayLayout8i15ui1ul2f2ui1f68", "C", "T", "E", "D", "O", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "Mu", "StructArrayLayout1f4", "Nu", "StructArrayLayout1ui2f12", "Pu", "StructArrayLayout1ul2ui8", "Fu", "StructArrayLayout2ui4", "Iu", "StructArrayLayout1ui2", "Lu", "StructArrayLayout4f16", "Ru", "CollisionBoxStruct", "zu", "CollisionBoxArray", "PlacedSymbolStruct", "Vu", "PlacedSymbolArray", "SymbolInstanceStruct", "Uu", "SymbolInstanceArray", "GlyphOffsetArray", "SymbolLineVertexArray", "TextAnchorOffsetStruct", "qu", "TextAnchorOffsetArray", "FeatureIndexStruct", "Yu", "FeatureIndexArray", "PosArray", "Pos3dArray", "RasterBoundsArray", "CircleLayoutArray", "FillLayoutArray", "FillExtrusionLayoutArray", "LineLayoutArray", "LineExtLayoutArray", "PatternLayoutArray", "DashLayoutArray", "SymbolLayoutArray", "SymbolDynamicLayoutArray", "SymbolOpacityArray", "CollisionBoxLayoutArray", "CollisionCircleLayoutArray", "CollisionVertexArray", "QuadTriangleArray", "TriangleIndexArray", "LineIndexArray", "LineStripIndexArray", "layout", "SegmentVector", "segments", "lastSegment", "numVertices", "sortKey", "layoutVertexArray", "indexArray", "segment", "yd", "packUint8ToFloat", "patternAttributes", "dashAttributes", "Cd", "murmurhash3_32_gc", "remainder", "bytes", "h1", "seed", "h1b", "c1", "c2", "k1", "module", "murmurhash2_32_gc", "murmur3", "require_murmurhash3_gc", "murmur2", "require_murmurhash2_gc", "FeaturePositionMap", "getNumericId", "intId", "positions", "ids", "sort$1", "numValue", "sort", "pivot", "swap$1", "Uniform", "location", "Uniform1i", "Uniform1f", "Uniform2f", "Uniform3f", "Uniform4f", "UniformColor", "UniformColorArray", "UniformFloatArray", "emptyMat4", "UniformMatrix4f", "packColor", "color", "ConstantBinder", "names", "uniform", "CrossFadedConstantBinder", "posFrom", "posTo", "dashTo", "dashFrom", "uniformName", "SourceExpressionBinder", "PaintVertexArray", "newLength", "CompositeExpressionBinder", "useIntegerZoom", "minColor", "maxColor", "currentZoom", "factor", "CrossFadedBinder", "positionIds", "attributes", "CrossFadedPatternBinder", "fromPos", "toPos", "CrossFadedDasharrayBinder", "ProgramConfiguration", "filterProperties", "paintAttributeNames", "propType", "isCrossFaded", "StructArrayLayout", "layoutType", "binder", "dirty", "fs", "featureStates", "featureMap", "vtLayer", "attribute", "uniforms", "locations", "binderUniforms", "crossfade", "patternVertexBuffer", "ProgramConfigurationSet", "getLayoutException", "\"composite\"", "defaultLayouts", "\"number\"", "binderType", "MAX", "MIN", "loadGeometry", "toEvaluationFeature", "needGeometry", "Bounds", "amount", "EXTENT_BOUNDS", "isBoundaryEdge", "isEntirelyOutside", "isOutsideTile", "VERTEX_MIN_VALUE", "addCircleVertex", "extrudeX", "extrudeY", "CircleBucket", "styleLayer", "bucketFeatures", "circleSortKey", "sortFeaturesByKey", "subdivide", "circleStyle", "granularity", "features", "evaluationFeature", "bucketFeature", "sourceLayerIndex", "states", "layoutAttributes", "extrudes", "verticesPerAxis", "polygonIntersectsPolygon", "polygonA", "polygonContainsPoint", "polygonB", "lineIntersectsLine", "polygonIntersectsBufferedPoint", "pointIntersectsBufferedLine", "radius", "polygonIntersectsMultiPolygon", "multiPolygonContainsPoint", "multiPolygon", "polygonIntersectsBufferedMultiLine", "multiLine", "lineIntersectsBufferedLine", "lineA", "lineB", "lineSegmentIntersectsLineSegment", "radiusSquared", "distToSegmentSquared", "l2", "currentRing", "polygonIntersectsBox", "boxX1", "boxY1", "boxX2", "boxY2", "corners", "corner", "edgeIntersectsBox", "tl", "br", "e1", "e2", "dir", "getMaximumPaintValue", "bucket", "translateDistance", "queryGeometry", "pt", "translated", "_stripDuplicates", "filteredRing", "prevPoint", "offsetLine", "newRings", "rawRing", "newRing", "nextPoint", "unitNormalAB", "unitNormalBC", "bisectorDir", "cosHalfAngle", "intersectionTestMapMap", "intersectionTestMapViewport", "unwrappedTileID", "getElevation", "intersectionTestViewportMap", "adjustedSize", "projectPoint", "intersectionTestViewportViewport", "circleIntersection", "pitchAlignment", "pitchScale", "param", "clipPoint", "tilePoint", "projectQueryGeometry", "getLayout", "If", "\"layout_circle\"", "Rf", "\"paint_circle\"", "circle_style_layer_properties_g_default", "isCircleStyleLayer", "CircleStyleLayer", "circleBucket", "translatedPolygon", "transformedPolygon", "transformedSize", "HeatmapBucket", "Wf", "\"paint_heatmap\"", "heatmap_style_layer_properties_g_default", "createImage", "channels", "resizeImage", "newImage", "copyImage", "dstImg", "srcImg", "srcPt", "dstPt", "srcData", "dstData", "srcOffset", "dstOffset", "AlphaImage", "RGBAImage", "rLocation", "row", "col", "premultiplyAlpha", "renderColorRamp", "evaluationGlobals", "renderPixel", "pxColor", "clip", "evaluationProgress", "HEATMAP_FULL_RENDER_FBO_KEY", "isHeatmapStyleLayer", "HeatmapStyleLayer", "\"paint_hillshade\"", "hillshade_style_layer_properties_g_default", "isHillshadeStyleLayer", "HillshadeStyleLayer", "altitude", "highlightColor", "shadowColor", "numIlluminationSources", "altitudeRadians", "cp", "color_relief_style_layer_properties_g_default", "hasDataProperty", "Texture", "resize", "position", "gl", "wantPremultiply", "mipLevels", "minFilter", "effectiveMinFilter", "magFilter", "DEMData", "encoding", "dim", "redFactor", "greenFactor", "blueFactor", "baseShift", "pixels", "ele", "strideByteWidth", "z00", "z10", "z01", "z11", "packDEMData", "borderTile", "xMin", "xMax", "yMin", "yMax", "ox", "oy", "byteView", "unpackVector", "factors", "minScale", "vScaled", "packChannel", "isColorReliefStyleLayer", "ColorReliefStyleLayer", "colorRamp", "interpolater", "maxLength", "remappedColorRamp", "remapStepSize", "colorImage", "elevationImage", "elevationPacked", "hasPattern", "patterns", "patternProperty", "constantPattern", "addPatternDependencies", "patternPropertyValue", "patternFeature", "steiners", "filteredOut", "earcut", "hasHoles", "holeIndices", "outerLen", "outerNode", "linkedList", "triangles", "invSize", "eliminateHoles", "earcutLinked", "last", "clockwise", "signedArea", "insertNode", "removeNode", "filterPoints", "full", "again", "Sp", "indexCurve", "ear", "cured", "next", "isEarHashed", "isEar", "cureLocalIntersections", "splitEarcut", "x0", "y0", "pointInTriangle", "minZ", "zOrder", "maxZ", "intersects", "locallyInside", "isValidDiagonal", "splitPolygon", "indexActive", "queue", "list", "getLeftmost", "compareXYSlope", "buildBlockIndex", "indexSegment", "jp", "eliminateHole", "bridge", "findHoleBridge", "hole", "bridgeReverse", "bridge2", "blockBBox", "numBlocks", "blockHead", "blockStop", "maxBlocks", "maxNodes", "numHoles", "Fp", "Ip", "head", "Lp", "Rp", "growBlock", "tail", "liveBlockStop", "liveBlockHead", "hx", "hy", "mx", "my", "tminY", "tmaxY", "tanMin", "tan", "sectorContainsSector", "sortArr", "sortBuf", "zArr", "zBuf", "counts", "Kp", "sortNodes", "node", "Jp", "Yp", "qp", "radixPass", "Xp", "srcZ", "leftmost", "zeroLength", "intersectsPolygon", "middleInside", "o3", "includeBoundary", "onSegment", "createNode", "an", "SubdivisionGranularityExpression", "minGranularity", "baseZoomGranularity", "divisor", "zoomLevel", "SubdivisionGranularitySetting", "NORTH_POLE_Y", "SOUTH_POLE_Y", "Subdivider", "xInt", "yInt", "existing", "fixWindingOrder", "remapIndices", "inputIndices", "inputRemap", "finalIndices", "numIndices", "primitiveIndex", "triangleIndices", "triangleVertices", "cellXmin", "cellXmax", "cellYmin", "cellYmax", "cellRow", "scanlineTriangulateVertexRing", "cellRowYTop", "cellRowYBottom", "edgeIndex", "aX", "aY", "bX", "bY", "cX", "cY", "dirX", "dirY", "isParallelY", "isParallelX", "tTop", "tBottom", "tEnter", "tExit", "enterX", "exitX", "leftX", "rightX", "edgeSubdivisionLeftCellX", "edgeSubdivisionRightCellX", "cellX", "dir2X", "dir2Y", "t2Top", "t2Bottom", "t2Enter", "t2Exit", "enter2X", "boundarySubdivisionLeftCellX", "boundarySubdivisionRightCellX", "isBoundaryLeftToRight", "isParallelX2", "dir3X", "dir3Y", "t3Top", "t3Bottom", "enter3X", "boundaryY", "subdividedLines", "ringStart", "pathIndices", "subdivideVertexLine", "lineIndices", "indices", "ringIsOpen", "north", "south", "subdividedTriangles", "flattened", "v0x", "v1x", "poleY", "i1", "i0", "southEdge", "i2", "v0y", "v1y", "v2x", "v2y", "flatten", "earcutResult", "generateOutlineLines", "lines", "filtered", "subdividePolygon", "linePoints", "addLastToFirstSegment", "isRing", "cellSize", "finalLineVertices", "totalPoints", "pointIndex", "linePoint0", "linePoint1", "lineVertex0x", "lineVertex0y", "lineVertex1x", "lineVertex1y", "dirXnonZero", "dirYnonZero", "absDirX", "absDirY", "lastPointX", "lastPointY", "nextBoundaryX", "nextBoundaryY", "axisDistanceToBoundaryX", "axisDistanceToBoundaryY", "axisDistanceToEndX", "axisDistanceToEndY", "realDistanceToBoundaryX", "realDistanceToBoundaryY", "vertex", "remapped", "remap", "corrected", "e0x", "e0y", "e1x", "leftmostIndex", "leftmostX", "vertexBuffer", "ringVertexLength", "lastEdgeA", "lastEdgeB", "candidateIndexA", "candidateIndexB", "candidateAx", "candidateAy", "candidateBx", "candidateBy", "lastEdgeAx", "lastEdgeAy", "lastEdgeBx", "lastEdgeBy", "pickA", "nx", "ny", "sign", "fillLargeMeshArrays", "hasLines", "segmentsLines", "lineIndexArray", "lineList", "triangleSegment", "segmentsTriangles", "vertexArray", "triangleIndexArray", "triangleIndex", "lineIndicesStart", "lineSegment", "addVertex", "fillSegmentsTriangles", "fillSegmentsLines", "copyOrReuseVertex", "needsCopy", "newIndex", "totalVerticesCreated", "oldIndex", "actualVertexIndices", "currentSegmentCutoff", "baseVertex", "primitiveEndIndex", "i0needsVertexCopy", "i1needsVertexCopy", "i2needsVertexCopy", "vertexCopyCount", "actualIndex0", "actualIndex1", "actualIndex2", "currentLine", "lineVertex", "FillBucket", "fillSortKey", "patternMap", "patternPositions", "pattern", "imageMap", "isSdf", "EARCUT_MAX_RINGS", "subdivided", "subdivisionGranularity", "Nm", "\"layout_fill\"", "Fm", "\"paint_fill\"", "fill_style_layer_properties_g_default", "isFillStyleLayer", "FillStyleLayer", "outlineColor", "centroidAttributes", "VectorTileFeature", "pbf", "tag", "tagsEnd", "cmd", "cmdLen", "vtCoords", "projectLine", "Um", "VectorTileLayer", "readValueMessage", "VectorTile", "earthRadius", "LngLat", "lat1", "lat2", "EPSG3857_RADIUS", "mercatorTileMatrixSet", "earthCircumference", "circumferenceAtLatitude", "latitude", "mercatorZfromAltitude", "lngFromMercatorX", "altitudeFromMercatorZ", "mercatorScale", "MercatorCoordinate", "lngLatLike", "mercatorWorldCoordinateHelper", "MercatorWorldCoordinateHelper", "maxMercatorHorizonAngle", "tileCoordinatesToMercatorCoordinates", "canonicalTileID", "inTileX", "inTileY", "getMercatorTileCoordinates", "overscaledTileID", "tileCoordinatesToLocation", "projectToWorldCoordinates", "helper", "lnglat", "unprojectFromWorldCoordinates", "getMercatorHorizon", "calculateTileMatrix", "unwrappedX", "worldMatrix", "translate$1", "scale$3", "cameraMercatorCoordinateFromCenterAndRotation", "cameraDirectionFromPitchBearing", "dxMercator", "dMercator", "dyMercator", "dzMercator", "centerMercator", "cameraMercatorCoordinate", "worldCoordinateHelper", "mercUnitsPerMeter", "pixelPerMeter", "pitchRadians", "bearingRadians", "lngLatBoxToWorldSamples", "toPoint", "lngAt", "east", "west", "latAt", "column", "pointAt", "bulge", "lngHalfway", "latHalfway", "edges", "halfway", "chord", "toHalfway", "chordLength", "lngLatBoxToWorldBox", "worldBoxToLngLatBox", "DEGREE_STEP", "degreesPerWorldUnit", "latStep", "world", "alongLng", "alongLat", "worldUnits", "roundPolygonCornersIfNeeded", "distanceInTileUnits", "roundRing", "getTileUnitsForMeters", "centerLocation", "meterInMercator", "tileUnitsPerMercator", "distanceInMeters", "SMOOTH_WALL_MIN_DOT", "roundedWallNormals", "perps", "edge", "isWall", "isClosed", "normals", "previous", "smoothNormal", "neighbour", "neighbourLength", "vertexCount", "previousIsBoundary", "nextIsBoundary", "appendRoundCorner", "snapped", "snapToIntegerGrid", "ua", "ub", "lenA", "lenB", "maxEdgeLenPercent", "tangentA", "tangentB", "cosHalfTheta", "sweepAngle", "numSegments", "FACTOR", "nz", "FillExtrusionBucket", "roundedCornerDistanceInMeters", "roundedCornerDistance", "centroid", "oldVertexCount", "addedVertices", "centroidX", "centroidY", "accumulatePointsToCentroid", "segmentReference", "isPolygon", "subdividedRing", "subdividedPolygon", "addVertex$1", "edgeDistance", "wallNormals", "bottomRight", "Lh", "zh", "fill_extrusion_style_layer_properties_g_default", "isFillExtrusionStyleLayer", "FillExtrusionStyleLayer", "projectedQueryGeometry", "pixelPosMatrix", "projectExtrusion", "projectedBase", "projectedTop", "checkIntersection", "getIntersectionDistance", "projectedFace", "ab", "ac", "dotABAB", "dotABAC", "dotACAC", "dotAPAB", "dotAPAC", "denom", "closestDistance", "ringTop", "ringBase", "topA", "topB", "baseA", "face", "baseXZ", "zBase", "baseYZ", "baseZZ", "baseWZ", "topXZ", "zTop", "topYZ", "topZZ", "topWZ", "sX", "sY", "sZ", "sW", "baseX", "baseY", "baseZ", "baseW", "topX", "topY", "topZ", "topW", "IdentityWorldCoordinateHelper", "lineLayoutAttributes", "lineLayoutAttributesExt", "COS_HALF_SHARP_CORNER", "LINE_DISTANCE_SCALE", "MAX_LINE_DISTANCE", "LineBucket", "lineSortKey", "dashPositions", "layoutAttributesExt", "GEOJSONVT_CLIP_START", "GEOJSONVT_CLIP_END", "join", "cap", "miterLimit", "roundLimit", "vertices", "first", "sharpCornerOffset", "currentVertex", "prevVertex", "nextVertex", "prevNormal", "nextNormal", "joinNormal", "cosAngle", "miterLength", "approxAngle", "isSharpCorner", "lineTurnsLeft", "offsetNormal", "offsetFallback", "prevSegmentLength", "newPrevVertex", "middleVertex", "currentJoin", "bevelLength", "offsetA", "offsetB", "B", "extrude", "nextSegmentLength", "newCurrentVertex", "normal", "endLeft", "leftY", "endRight", "rightY", "offsetX", "offsetY", "round", "linesofarScaled", "uvX", "dasharrayProperty", "minKey", "midKey", "maxKey", "ag", "\"layout_line\"", "sg", "\"paint_line\"", "line_style_layer_properties_g_default", "LineFloorwidthProperty", "lineFloorwidthProperty", "isLineStyleLayer", "LineStyleLayer", "dg", "lineBucket", "getLineWidth", "halfWidth", "lineOffset", "lineGapWidth", "lineWidth", "symbolLayoutAttributes", "dynamicLayoutAttributes", "collisionVertexAttributes", "collisionBoxLayout", "collisionCircleLayout", "symbolInstance", "rtlWorkerPlugin", "state", "rtlTextPlugin", "incomingState", "urlToLoad", "loadScriptPromise", "dontWaitForeverTimeoutPromise", "loadScript", "loadedState", "codePointIsInCursiveScript", "codePoint", "codePointIsInRTLScript", "codePointIsInComplexShapingScript", "codePointUsesLocalIdeographFontFamily", "codePointAllowsIdeographicBreaking", "codePointHasUprightVerticalOrientation", "codePointHasNeutralVerticalOrientation", "textCanContainGraphemeClusters", "codePointIsWrittenWithoutSpaces", "canCombineGraphemes", "former", "latter", "ENCODED_JOINING_TYPES", "PRESENTATION_FORMS", "LIGATURES", "\"\u0644\u0622\"", "\"\u0644\u0623\"", "\"\u0644\u0625\"", "\"\u0644\u0627\"", "LAM", "ARABIC", "decodeRanges", "previousEnd", "encoded", "into", "joiningTypes", "joiningType", "joinsForward", "joinsBackward", "formFor", "joinedBefore", "joinedAfter", "toCharacters", "character", "assignLetterForms", "visible", "characters", "assignMarkForms", "letterJoinsForward", "applyLigatures", "lam", "alef", "ligature", "toPresentationForm", "forms", "applyArabicShaping", "transformTextInternal", "transformText", "getKey", "onRight", "joinChunks", "chunk", "at", "mergeFromRight", "rightIndex", "leftKey", "rightKey", "merged", "mergeFromLeft", "leftIndex", "mergeLines", "hasSegmenter", "graphemeSegmenter", "wordSegmenter", "toGraphemes", "r_", "graphemes", "wordBoundaries", "boundaries", "i_", "isCluster", "grapheme", "charIsWhitespace", "char", "charIsSymbolOrPunctuation", "allowsVerticalWritingMode", "chars", "allowsLetterSpacing", "charAllowsLetterSpacing", "charHasRotatedVerticalOrientation", "charInComplexShapingScript", "charInRTLScript", "stringContainsRTLText", "verticalizedCharacterMap", "\"$\"", "\"_\"", "verticalizePunctuation", "prevChar", "nextChars", "nextChar", "breakable", "breakableBefore", "getGlyphAdvance", "glyphMap", "glyph", "spacing", "advance", "fallback", "imagePosition", "imagePositions", "layoutTextSize", "calculateBadness", "raggedness", "targetWidth", "isLastBreak", "penalty", "isWhitespaceGrapheme", "calculatePenalty", "penalizableIdeographicBreak", "nextCodePoint", "evaluateBreak", "bestPriorBreak", "bestBreakBadness", "breakX", "potentialBreak", "potentialBreaks", "breakBadness", "breakIndex", "leastBadBreaks", "lastLineBreak", "TaggedString", "sectionIndex", "defaultFontStack", "vertical", "replacements", "replacement", "verticals", "graphemeIndex", "maxImageWidth", "maxImageHeight", "joined", "added", "imageName", "nextImageSectionCharCode", "totalWidth", "maxWidth", "potentialLineBreaks", "hasZeroWidthSpaces", "wordStarts", "currentX", "codeUnit", "previousCodePoint", "ideographicBreak", "withinAWordlessScript", "bidiFactory", "DATA", "\"R\"", "\"EN\"", "\"ES\"", "\"ET\"", "\"AN\"", "\"CS\"", "\"B\"", "\"S\"", "\"WS\"", "\"ON\"", "\"BN\"", "\"NSM\"", "\"AL\"", "\"LRO\"", "\"RLO\"", "\"LRE\"", "\"RLE\"", "\"PDF\"", "\"LRI\"", "\"RLI\"", "\"FSI\"", "\"PDI\"", "TYPES", "TYPES_TO_NAMES", "ISOLATE_INIT_TYPES", "STRONG_TYPES", "NEUTRAL_ISOLATE_TYPES", "BN_LIKE_TYPES", "TRAILING_TYPES", "parseData", "temp", "lastCode", "getBidiCharType", "getBidiCharTypeName", "data$1", "\"pairs\"", "\"canonical\"", "parseCharacterMap", "reverseMap", "includeReverse", "prevPair", "encodedString", "visit", "entry", "openToClose", "closeToOpen", "parse$1", "openingToClosingBracket", "closingToOpeningBracket", "getCanonicalBracket", "TYPE_L", "TYPE_R", "TYPE_EN", "TYPE_ES", "TYPE_ET", "TYPE_AN", "TYPE_CS", "TYPE_B", "TYPE_S", "TYPE_ON", "TYPE_BN", "TYPE_NSM", "TYPE_AL", "TYPE_LRO", "TYPE_RLO", "TYPE_LRE", "TYPE_RLE", "TYPE_PDF", "TYPE_LRI", "TYPE_RLI", "TYPE_FSI", "TYPE_PDI", "getEmbeddingLevels", "MAX_DEPTH", "charTypes", "string", "charTypeCounts", "changeCharType", "oldType", "embedLevels", "isolationPairs", "paragraphs", "paragraph", "i$1", "baseDirection", "determineAutoEmbedLevel", "FORMATTING_TYPES", "nextEven", "nextOdd", "paraIdx", "me", "statusStack", "stackTop", "overflowIsolateCount", "overflowEmbeddingCount", "validIsolateCount", "i$2", "ye", "charType", "ge", "level", "_e", "level$1", "be", "level$2", "ve", "M", "isolInitIndex", "levelRuns", "currentRun", "i$3", "De", "charType$1", "lvl", "isIsolInit", "isPDI", "Ee", "isolatingRunSeqs", "runIdx", "Ne", "run", "seqRuns", "pdiIndex", "Ie", "i$4", "Le", "seqIndices", "i$5", "ze", "run$1", "Ve", "firstLevel", "prevLevel", "i$6", "We", "Ue", "lastLevel", "nextLevel", "i$7", "Je", "qe", "seqIdx", "Ye", "seqIndices$1", "sosType", "eosType", "embedDirection", "si", "et", "i$8", "prevType", "sj", "nt", "P", "si$1", "i$9", "sj$1", "prevCharType", "si$2", "st", "i$10", "si$3", "i$11", "prevType$1", "nextType", "sj$2", "dt", "sj$3", "ft", "mt", "si$4", "ht", "sj$4", "si$5", "_t", "i$13", "sj$5", "yt", "sj$6", "si$6", "prevStrongType", "xt", "i$14", "St", "R_TYPES_FOR_N_STEPS", "STRONG_TYPES_FOR_N_STEPS", "bracketPairs", "openerStack", "si$7", "Dt", "oppositeBracket", "Ot", "kt", "stackIdx", "stackChar", "pairIdx", "Mt", "ref$1", "openSeqIdx", "closeSeqIdx", "foundStrongType", "useStrongType", "si$8", "L", "i$15", "It", "si$9", "Bt", "i$16", "lr$1", "si$10", "si$11", "Wt", "si$12", "Gt", "niRunStart", "niRunEnd", "prevType$2", "si2", "Yt", "Kt", "Jt", "nextType$1", "si2$1", "Zt", "qt", "Xt", "sj$7", "Qt", "i$17", "$t", "level$3", "type$1", "j$1", "nn", "isFSI", "pdi", "indexOfMatchingPDI", "isolationLevel", "isolateStart", "mirrorMap", "parse", "getMirroredCharacter", "getMirroredCharactersMap", "strLen", "embeddingLevels", "mirror", "getReorderSegments", "embeddingLevelsResult", "lineStart", "lineEnd", "lineLevels", "maxLevel", "minOddLevel", "segStart", "getReorderedString", "getReorderedIndices", "embedLevelsResult", "charIndex", "slice", "exports", "bidi", "BIDI_CONTROLS", "NEUTRAL_AT_END_OF_LINE", "ALWAYS_RESET", "toClusters", "clusters", "cluster", "levels", "resetTrailingNeutrals", "trailing", "paragraphLevel", "reorder", "highest", "lowestOdd", "ordered", "paragraphLevelAt", "reorderLine", "reorderedText", "sourceIndices", "mirrored", "lineRanges", "breakPoints", "bounds", "ranges", "processLines", "lineBreakPoints", "processBidirectionalText", "processStyledBidirectionalText", "styleIndices", "SHIFT_LEFT_32", "utf8TextDecoder", "PbfReader", "buf", "field", "readField", "readVarintRemainder", "isSigned", "TEXT_DECODER_MIN_LENGTH", "readUtf8", "toNum", "high", "low", "bytesPerSequence", "readFontstacks", "readFontstack", "glyphs", "readGlyph", "bitmap", "parseGlyphPbf", "isStyleImageWebGLData", "renderStyleImage", "userImage", "potpack", "box", "boxes", "spaces", "space", "ImagePosition", "paddedRect", "pixelRatio", "stretchX", "stretchY", "isWebGLImage", "textFitWidth", "textFitHeight", "ImageAtlas", "iconPositions", "bins", "icons", "bin", "images", "imageManager", "texture", "WritingMode", "\"horizontalOnly\"", "isEmpty", "positionedLines", "breakLines", "lineBreak", "COMBINING_MARK", "combiningMarksAfterTheirBase", "mark", "sectionForEachCodeUnit", "bidiLines", "codeUnitBreaks", "lineBreaks", "logicalInput", "plugin", "taggedLineFromPlugin", "taggedLine", "sectionForCodeUnit", "codeUnitOfEachCharacter", "tagged", "sectionOfChar", "offsets", "codeUnitOf", "shapeText", "writingMode", "shaping", "shapeLines", "glyphPositions", "lineHeight", "textAnchor", "textJustify", "allowVerticalPlacement", "layoutTextSizeThisZoom", "getAnchorAlignment", "horizontalAlign", "anchor", "calculateLineContentSize", "maxGlyphSize", "horizontalLineContentHeight", "layoutTextSizeFactor", "getVerticalAlignFactor", "getRectAndMetrics", "glyphPosition", "isLineVertical", "charIsDecimalDigit", "charIsUppercaseLetter", "runIsUpright", "isNumber", "isShortUppercaseCode", "charIsUprightInRun", "mayUseVerticalGlyph", "verticalizeSurroundedPunctuation", "replaced", "verticalizedChar", "verticalForms", "hasSidewaysTextBeside", "codePoints", "determineLineVerticals", "isRunCharacter", "upright", "punctuationOnly", "besideSidewaysText", "sideways", "form", "previousText", "maxLineLength", "maxLineHeight", "justify", "lineIndex", "lineMaxScale", "positionedLine", "positionedGlyphs", "imageOffset", "lineShapingSize", "lineVerticals", "positionedGlyph", "sectionAttributes", "shapeTextSection", "shapeImageSection", "baselineOffset", "metrics", "verticalAdvance", "lineLength", "justifyLine", "maxLineOffset", "currentLineHeight", "variant", "rectAndMetrics", "verticalAlignFactor", "lastPositionedGlyph", "lastAdvance", "lineIndent", "shiftX", "shiftY", "lineCount", "blockHeight", "shapeIcon", "iconAnchor", "iconOffset", "applyTextFit", "iconLeft", "shapedIcon", "iconTop", "iconWidth", "iconHeight", "contentWidth", "contentHeight", "contentAspectRatio", "newIconWidth", "newIconHeight", "fitIconToText", "collisionPadding", "textLeft", "shapedText", "fontScale", "textRight", "textFit", "textTop", "textBottom", "MAX_PACKED_SIZE", "getSizeData", "tileZoom", "getCoveringZoomStops", "sizes", "evaluateSizesAtZoomStops", "layoutSize", "zoomStop", "evaluateSizeForFeature", "sizeData", "lowerSize", "upperSize", "uSizeT", "uSize", "evaluateSizeForZoom", "evaluateCameraSize", "evaluateCompositeInterpolationFactor", "minZoom", "maxZoom", "Anchor", "checkMaxAngle", "labelLength", "anchorDistance", "recentCorners", "recentAngleDelta", "angleDelta", "windowSize", "maxAngle", "getLineLength", "getAngleWindowSize", "glyphSize", "boxScale", "getShapedLabelLength", "getCenterAnchor", "angleWindowSize", "prevDistance", "centerDistance", "segmentDistance", "getAnchors", "shapedLabelLength", "isLineContinued", "tileExtent", "fixedExtraOffset", "resample", "overscaling", "halfLabelLength", "markedDistance", "segmentDist", "placeAtMiddle", "clipLine", "clippedLines", "clippedLine", "p0", "getIconQuads", "quads", "imageWidth", "imageHeight", "icon", "reduceRanges", "stretchWidth", "stretchHeight", "fixedWidth", "fixedHeight", "stretchOffsetX", "stretchContentWidth", "stretchOffsetY", "stretchContentHeight", "fixedOffsetX", "fixedContentWidth", "fixedOffsetY", "fixedContentHeight", "hasIconTextFit", "sumWithinRange", "makeBox", "leftEm", "getEmOffset", "leftPx", "getPxOffset", "topEm", "topPx", "rightEm", "rightPx", "bottomEm", "bottomPx", "tr", "bl", "pixelOffsetTL", "pixelOffsetBR", "iconRotate", "matrix", "ee", "ne", "te", "ie", "isSDFIcon", "xCuts", "stretchZonesToCuts", "yCuts", "xi", "yi", "cuts", "stretchZones", "fixedSize", "stretchSize", "stretchOffset", "iconSize", "fixedOffset", "getGlyphQuads", "textRotate", "textureRect", "rectBuffer", "isSDF", "rotateVerticalGlyph", "alongLine", "halfAdvance", "scaledGlyphOffset", "glyphOffset", "builtInOffset", "textOffset", "verticalizedLabelOffset", "textureScale", "verticalRotation", "xHalfWidthOffsetCorrection", "yImageOffsetCorrection", "halfWidthOffsetCorrection", "verticalOffsetCorrection", "CollisionFeature", "collisionBoxArray", "alignLine", "shaped", "rotateRadians", "featureIndex", "bucketIndex", "findPoleOfInaccessibility", "polygonRings", "cellQueue", "Queue", "compareMax", "Cell", "centroidCell", "getCentroidCell", "bestCell", "precision", "pointToPolygonDist", "minDistSq", "TextAnchorEnum", "INVALID_TEXT_OFFSET", "evaluateVariableOffset", "fromRadialOffset", "radialOffset", "hypotenuse", "fromTextOffset", "getTextVariableAnchorOffset", "variableAnchorOffset", "sourceValues", "destValues", "variableAnchor", "anchorOffsets", "performSymbolLayout", "tileSize", "unevaluatedLayoutValues", "textAlongLine", "keepUpright", "textSize", "fontstack", "layoutIconSize", "shapedTextOrientations", "unformattedText", "spacingIfAllowed", "addVerticalShapingForPointLabelIfNeeded", "justifications", "getAnchorJustification", "singleLine", "justification", "getDefaultHorizontalShaping", "addFeature", "textMaxSize", "defaultHorizontalShaping", "textBoxScale", "textMaxBoxScale", "iconBoxScale", "symbolMinDistance", "textPadding", "iconPadding", "getIconPadding", "textMaxAngle", "iconAlongLine", "symbolPlacement", "textRepeatDistance", "iconTextFit", "verticallyShapedIcon", "addSymbolAtAnchor", "addSymbol", "hasPromoteId", "subdividedLine", "anchorIsTooClose", "poi", "addTextVariableAnchorOffsets", "startIndex", "textAnchorOffsets", "addTextVertices", "glyphQuads", "textSizeData", "lineArray", "placedIconIndex", "elevation", "placementType", "placementTypes", "horizontalShaping", "textCollisionFeature", "iconCollisionFeature", "verticalTextCollisionFeature", "verticalIconCollisionFeature", "numIconVertices", "numVerticalIconVertices", "numHorizontalGlyphVertices", "numVerticalGlyphVertices", "placedIconSymbolIndex", "verticalPlacedIconSymbolIndex", "placedTextSymbolIndices", "verticalTextRotation", "verticalShaping", "iconQuads", "verticalIconQuads", "iconSizeData", "ae", "se", "textBoxStartIndex", "textBoxEndIndex", "verticalTextBoxStartIndex", "verticalTextBoxEndIndex", "iconBoxStartIndex", "iconBoxEndIndex", "verticalIconBoxStartIndex", "verticalIconBoxEndIndex", "collisionCircleDiameter", "getCollisionCircleHeight", "prevHeight", "useRuntimeCollisionCircles", "textAnchorOffsetStartIndex", "textAnchorOffsetEndIndex", "keyWithFeatureId", "compareText", "otherAnchors", "repeatDistance", "getOverlapMode", "overlap", "overlapProp", "allowOverlapProp", "shaderOpacityAttributes", "aSizeX", "sizeVertex", "aSizeY", "anchorX", "anchorY", "pixelOffsetX", "pixelOffsetY", "minFontScaleX", "minFontScaleY", "addDynamicAttributes", "dynamicLayoutVertexArray", "containsRTLText", "formattedText", "SymbolBuffers", "programConfigurations", "upload", "dynamicIndexBuffer", "update", "CollisionBuffers", "LayoutArray", "IndexArray", "SymbolBucket", "zOrderByViewportY", "wm", "stack", "stacks", "needsVerticalGlyph", "needsVerticalForms", "verticalChar", "textFont", "textField", "iconImage", "hasText", "hasIcon", "symbolSortKey", "pointPlacement", "isEveryPointOutsideTile", "resolvedTokens", "symbolFeature", "iconMap", "lineStartIndex", "sumForwardLength", "sumBackwardLength", "arrays", "glyphOffsetArrayStart", "vertexStartIndex", "labelAnchor", "tex", "associatedIconIndex", "collisionVertexArray", "boxAnchorPoint", "isText", "collisionArrays", "textStartIndex", "textEndIndex", "verticalTextStartIndex", "verticalTextEndIndex", "iconStartIndex", "iconEndIndex", "verticalIconStartIndex", "verticalIconEndIndex", "placedSymbol", "iconOrText", "placedSymbolIndex", "vertexIndex", "rotatedYs", "featureIndexes", "aIndex", "bIndex", "symbolInstanceIndex", "textIndices", "resolveTokens", "Fy", "Ly", "\"paint_symbol\"", "symbol_style_layer_properties_g_default", "FormatSectionOverride", "isSymbolStyleLayer", "SymbolStyleLayer", "iconRotationAlignment", "writingModes", "deduped", "unevaluated", "overridable", "overridden", "styleExpression", "hasOverrides", "checkSections", "checkExpression", "formatted", "Wy", "\"paint_background\"", "background_style_layer_properties_g_default", "isBackgroundStyleLayer", "BackgroundStyleLayer", "validateCustomStyleLayer", "layerObject", "isCustomStyleLayer", "CustomStyleLayer", "implementation", "createStyleLayer", "coerceSpriteToArray", "resultArray", "dedupArray", "normalizeSpriteURL", "extension", "loadSprite", "spriteArray", "originalSprite", "jsonsMap", "imagesMap", "jsonRequestParameters", "imageRequestParameters", "doOnceCompleted", "spriteName", "json", "spriteData", "ImageManager", "loaded", "promiseResolve", "valid", "stretch", "oldImage", "oldData", "spriteId", "imageId", "previousIds", "loadedIds", "removed", "resolver", "hasAllDependencies", "unresolvedIds", "clonedImages", "PatternAtlas", "imagePosA", "imagePosB", "dst", "DEFAULT_UNICODE_RANGE", "nextFamilyId", "parseUnicodeRange", "prefix", "questionMarks", "clampRange", "explicit", "covers", "FontFaceManager", "declaration", "fontFaces", "declarations", "family", "sb", "description", "faces", "INF", "alphaTable", "pb", "TinySDF", "cutoff", "lang", "fontSize", "fontStyle", "fontWeight", "fontFamily", "gridDim", "glyphAdvance", "glyphTop", "actualBoundingBoxAscent", "glyphLeft", "actualBoundingBoxLeft", "glyphWidth", "actualBoundingBoxRight", "glyphHeight", "actualBoundingBoxDescent", "imgData", "gridOuter", "gridInner", "imgIdx", "edt", "skipCols", "edt1d", "gridSize", "fq", "qr", "defaultStack", "defaultCreateRasterizer", "tinySDF", "variantFeatures", "glyphsEqual", "GlyphManager", "localIdeographFontFamily", "createRasterizer", "glyphsPromises", "hasFontFaces", "yb", "updatedGlyphs", "fontFaceFamily", "alternateTinySDF", "defaultTinySDF", "begin", "isControl", "cache", "usesLocalIdeographFontFamily", "fontFamilies", "sniffFontStyles", "emsWide", "weightsByName", "weight", "getProperties", "Sb", "Light", "lightOptions", "Tb", "Sky", "calculateFogBlendOpacity", "LineAtlas", "dasharray", "oddDashArray", "isDash", "currentDashLength", "dashLength", "halfStretch", "currIndex", "distLeft", "distRight", "signedDistance", "distMiddle", "distEdge", "dash", "dashEntry", "Dispatcher", "mapRemoved", "getPixelPosMatrix", "mat4.create", "posMatrix", "tileID", "mat4.multiply", "queryIncludes3DLayer", "layerID", "styleLayers", "sourceID", "queryRenderedFeatures", "has3DLayer", "tileManager", "maxPitchScaleFactor", "tilesIn", "sortTilesIn", "renderedFeatureLayers", "tileIn", "serializedLayers", "convertFeaturesToMapFeatures", "mergeRenderedFeatureLayers", "queryRenderedSymbols", "renderedSymbols", "collisionIndex", "bucketQueryData", "bucketInstanceId", "retainedQueryData", "queryData", "bucketSymbols", "layerSymbols", "featureSortOrder", "sortedA", "convertFeaturesToMapFeaturesMultiple", "tileManagers", "querySourceFeatures", "tiles", "dataTiles", "dataID", "idA", "idB", "wrappedIDLayerMap", "wrappedTileID", "wrappedIDLayers", "queryResults", "tileFeatures", "wrappedIDFeatures", "tileFeature", "featureWrapper", "convertFeatureToMapFeature", "layerName", "loadTileJson", "tileJSON", "LngLatBounds", "sw", "sw2", "ne2", "lngLatBoundsObj", "lngLatObj", "containsLatitude", "containsLongitude", "thisSpan", "otherSpan", "thisWest", "thisEast", "otherWest", "otherEast", "thisWraps", "otherWraps", "latAccuracy", "lngAccuracy", "TileBounds", "minzoom", "maxzoom", "VectorTileSource", "dispatcher", "eventedParent", "messageType", "fetchedZ", "lowestZ", "TileManager", "ancestorID", "maxZoomTileID", "reloadPromise", "RasterTileSource", "premultiply", "isInBoundsForTileZoomXY", "isInBoundsForZoomLngLat", "CanonicalTileID", "calculateTileKey", "quadkey", "getQuadkey", "scheme", "getTileBBox", "tileMatrixSet", "dz", "UnwrappedTileID", "OverscaledTileID", "overscaledZ", "zDifference", "withWrap", "sourceMaxZoom", "tileOffsetX", "tileOffsetY", "newX", "newY", "newCanonicalY", "newCanonicalX", "newWrap", "gridMinX", "gridMaxY", "gridMinY", "rowFromBottom", "mask", "compareTileId", "aWrap", "bWrap", "RasterDEMTileSource", "rawImageData", "pxw", "nxw", "neighboringTiles", "getFeatureId", "promoteId", "toUpdateable", "updateable", "seenIds", "applySourceDiff", "affectedGeometries", "changeGeometry", "changeProps", "mergeSourceDiffs", "prevDiff", "nextDiff", "diffToHashed", "resolveMergeConflicts", "hashedToDiff", "nextUpdate", "prevUpdate", "mergeFeatureDiffs", "removedProperties", "hashed", "extractCoordinates", "getCoordinatesFromGeometry", "getGeoJSONBounds", "coordinate", "tileIdToLngLatBounds", "UpdateQueue", "handlers", "predicate", "CRSWorldCoordinateHelper", "crs", "crsX", "crsY", "insideX", "insideY", "forwardX", "forwardY", "answered", "unanswered", "maxStretch", "pole", "towardEquatorX", "towardEquatorY", "IdentityConversion", "identityCrs", "registeredProjections", "getRegisteredProjection", "addProjection", "removeProjection", "GeoJSONSource", "tileUnitValue", "effectiveClusterMaxZoom", "clusterMaxZoom", "waiting", "clusterOptions", "shouldReloadTileOptions", "eventData", "timingData", "resourceTiming", "tileBounds", "affectedBounds", "bilinearImageWarp", "rasterUniforms", "\"u_tl_parent\"", "\"u_scale_parent\"", "\"u_buffer_scale\"", "\"u_image_warp\"", "\"u_fade_t\"", "\"u_opacity\"", "\"u_image0\"", "\"u_image1\"", "\"u_brightness_low\"", "\"u_brightness_high\"", "\"u_saturation_factor\"", "\"u_contrast_factor\"", "\"u_spin_weights\"", "\"u_coords_top\"", "\"u_coords_bottom\"", "rasterUniformValues", "parentTL", "parentScaleBy", "imageWarp", "fade", "saturationFactor", "contrastFactor", "spinWeights", "cornerCoords", "contrast", "saturation", "Mesh", "indexBuffer", "posAttributes", "createTileMeshWithBuffers", "tileMesh", "createTileMesh", "quadsPerAxisX", "quadsPerAxisY", "verticesPerAxisX", "verticesPerAxisY", "endX", "endY", "indexCount", "overflows16bitIndices", "forceIndicesSize", "use32bitIndices", "vertexId", "indexId", "ImageSource", "newCoordinates", "projectionSubdividesTiles", "warp", "getCoordinatesCenterTileID", "calculateImageWarp", "isParallelogram", "hasWrongWindingOrder", "newTilesLoaded", "minTileX", "minTileY", "maxTileX", "maxTileY", "minTileXWrapped", "maxTileXWrapped", "minWrap", "maxWrap", "topLeft", "topRight", "bottomLeft", "sumX", "sumY", "basis", "downX", "downY", "mat2.determinant", "perspectiveX", "perspectiveY", "denominators", "foreshortening", "blend", "bilinearBlend", "ramp", "VideoSource", "seekableRange", "seconds", "CanvasSource", "registeredSources", "getSourceType", "setSourceType", "Vx", "addSourceType", "SourceType", "lId", "GEOJSON_TILE_LAYER_NAME", "DictionaryCoder", "strings", "GeoJSONFeature", "vectorTileFeature", "Vector", "_name", "dataBuffer", "sizeOrNullabilityBuffer", "FixedSizeVector", "Int32FlatVector", "DoubleFlatVector", "SequenceVector", "baseValueBuffer", "Int32SequenceVector", "baseValue", "Int32ConstVector", "FeatureTable", "_geometryVector", "_idVector", "_propertyVectors", "_extent", "vector", "idValue", "propertyColumn", "columnName", "propertyValue", "idVector", "ColumnScope", "ScalarType", "ComplexType", "LogicalScalarType", "IntWrapper", "LogicalLevelTechnique", "\"NONE\"", "\"DELTA\"", "\"COMPONENTWISE_DELTA\"", "\"MORTON\"", "PhysicalLevelTechnique", "\"FAST_PFOR\"", "\"VARINT\"", "masks", "uS", "bitWidth", "MASKS", "DEFAULT_PAGE_SIZE", "greatestMultiple", "roundUpToMultipleOf32", "normalizePageSize", "pageSize", "aligned", "bswap32", "fastUnpack32_2", "outPos", "in0", "inValues", "inPos", "in1", "fastUnpack32_3", "in2", "fastUnpack32_4", "in3", "fastUnpack32_5", "in4", "fastUnpack32_6", "in5", "fastUnpack32_7", "in6", "fastUnpack32_8", "in7", "fastUnpack32_9", "in8", "fastUnpack32_10", "in9", "fastUnpack32_11", "in10", "fastUnpack32_12", "in11", "fastUnpack32_16", "in12", "in13", "in14", "in15", "fastUnpack256_1", "ip", "fastUnpack256_2", "fastUnpack256_3", "fastUnpack256_4", "fastUnpack256_5", "fastUnpack256_6", "fastUnpack256_7", "fastUnpack256_8", "fastUnpack256_16", "fastUnpack256_Generic", "inputWordIndex", "bitOffset", "currentWord", "lowBits", "highBits", "highMask", "PAGE_SIZE", "BYTE_CONTAINER_SIZE", "createDecoderWorkspace", "byteContainer", "createFastPforWireDecodeWorkspace", "initialEncodedWordCapacity", "capacity", "ensureFastPforWireEncodedWordsCapacity", "requiredWordCount", "workspace", "materializeByteContainer", "byteSize", "numFullInts", "byteContainerStart", "intView", "lastVal", "unpackExceptionStreams", "dataToBePacked", "inExcept", "roundedUp", "wordsNeeded", "exceptionStream", "fastUnpack32", "overflow", "unpackBlock256", "readBlockHeader", "bytePosIn", "byteContainerLen", "block", "exceptionCount", "readBlockExceptionHeader", "maxBits", "exceptionBitWidth", "applyBlockExceptions", "afterHeaderPos", "blockOutPos", "exceptionValues", "exceptionPointers", "exPtr", "exSize", "decodePageBlocks", "tmpInPos", "blocks", "packedEnd", "pageStart", "decodePage", "whereMeta", "packedStart", "metaInts", "bitmapPos", "thisSize", "decodeAlignedPages", "finalOut", "outLength", "tmpOutPos", "decodeVByte", "expectedCount", "wordIndex", "finalWordIndex", "inLength", "outPos0", "targetOut", "accumulator", "accumulatorShift", "byte", "decodeFastPforInt32", "decoded", "numValues", "decoderWorkspace", "alignedLength", "remainingLength", "expectedTail", "valueMask", "decodeBigEndianInt32sInto", "byteLength", "numCompleteInts", "hasTrailingBytes", "numInts", "absoluteOffset", "u32", "remaining", "decodeVarintInt32", "bufferOffset", "decodeVarintInt64", "decodeVarintInt64Value", "decodeVarintFloat64", "decodeVarintFloat64Value", "decodeVarintRemainder", "decodeFastPfor", "decodeFastPforWithWorkspace", "encodedBytes", "expectedValueCount", "encodedByteLength", "inputByteOffset", "encodedWordCount", "encodedWordBuffer", "decodedValues", "decodeZigZagInt32Value", "decodeZigZagInt64Value", "decodeZigZagFloat64Value", "decodeZigZagInt32", "encodedData", "decodeZigZagInt64", "decodeZigZagFloat64", "decodeUnsignedRleInt32", "numTotalValues", "numRuns", "runLength", "decodeUnsignedRleInt64", "decodeUnsignedRleFloat64", "decodeZigZagDeltaInt32", "sz0", "data1", "data2", "data3", "data4", "decodeZigZagDeltaInt64", "decodeZigZagDeltaFloat64", "decodeZigZagRleInt32", "decodeZigZagRleInt64", "decodeZigZagRleFloat64", "fastInverseDelta", "inverseDelta", "prevValue", "decodeComponentwiseDeltaVec2", "decodedData", "decodeComponentwiseDeltaVec2Scaled", "previousVertexX", "previousVertexY", "currentVertexX", "currentVertexY", "decodeZigZagDeltaOfDeltaInt32", "deltaSum", "zigZagValue", "decodeZigZagRleDeltaInt32", "previousValue", "decodeRleDeltaInt32", "decodeDeltaRleInt32", "zigZagDelta", "decodeDeltaRleInt64", "decodeUnsignedZigZagDeltaInt32", "decodeUnsignedZigZagDeltaInt64", "decodeUnsignedComponentwiseDeltaVec2", "decodeUnsignedComponentwiseDeltaVec2Scaled", "scaledValues", "decodeUnsignedConstRleInt32", "decodeZigZagConstRleInt32", "decodeZigZagSequenceRleInt32", "decodeUnsignedConstRleInt64", "decodeZigZagConstRleInt64", "decodeZigZagSequenceRleInt64", "PhysicalStreamType", "\"PRESENT\"", "\"DATA\"", "\"OFFSET\"", "\"LENGTH\"", "DictionaryType", "\"SINGLE\"", "\"SHARED\"", "\"VERTEX\"", "\"FSST\"", "OffsetType", "\"INDEX\"", "\"STRING\"", "\"KEY\"", "LengthType", "\"VAR_BINARY\"", "\"GEOMETRIES\"", "\"PARTS\"", "\"RINGS\"", "\"TRIANGLES\"", "\"SYMBOL\"", "\"DICTIONARY\"", "PHYSICAL_STREAM_TYPE_BY_ID", "LOGICAL_LEVEL_TECHNIQUE_BY_ID", "PHYSICAL_LEVEL_TECHNIQUE_BY_ID", "DICTIONARY_TYPE_BY_ID", "OFFSET_TYPE_BY_ID", "LENGTH_TYPE_BY_ID", "decodeStreamMetadata", "streamMetadata", "decodeStreamMetadataInternal", "decodePartialMortonEncodedStreamMetadata", "decodePartialRleEncodedStreamMetadata", "mortonInfo", "rleInfo", "stream_type", "physicalStreamType", "logicalStreamType", "encodings_header", "llt1", "llt2", "plt", "sizeInfo", "VectorType", "\"FLAT\"", "\"CONST\"", "\"SEQUENCE\"", "\"FSST_DICTIONARY\"", "BitVector", "byteIndex", "bitIndex", "unpackNullable", "presentBits", "dataStream", "constructor", "counter", "unpackNullableBoolean", "numFeatures", "bitVector", "dataStreamSize", "skipColumn", "numStreams", "decodeBooleanRle", "decodeByteRle", "numBooleans", "nullabilityBuffer", "numBytes", "valueOffset", "streamEndPos", "endValueOffset", "numLiterals", "decodeFloatsLE", "currentPos", "newOffset", "newBuf", "encodedValues", "fb", "decodeDoublesLE", "decodeUint32sLE", "decodeUint64sLE", "decodeString", "decodeSignedInt32Stream", "decodeSignedInt32", "decodePhysicalLevelTechnique", "scalingData", "decodeUnsignedInt32Stream", "decodeUnsignedInt32", "decodeLengthStreamToOffsetBuffer", "decodeLengthToOffsetBuffer", "physicalLevelTechnique", "decodePhysicalLevelTechniqueInt64", "decodeSignedConstInt32Stream", "decodeUnsignedConstInt32Stream", "decodeSequenceInt32Stream", "decodeSequenceInt64Stream", "decodeSignedInt64Stream", "decodeSignedInt64", "decodeUnsignedInt64Stream", "decodeUnsignedInt64", "decodeUnsignedInt64AsFloat64Stream", "decodeInt64AsFloat64", "decodeFloat64Values", "decodeSignedConstInt64Stream", "decodeUnsignedConstInt64Stream", "rleMetadata", "decodeRleFloat64", "getVectorType", "logicalLevelTechnique1", "savedOffset", "isDeltaRleSequenceVarintWidth", "varintWidth", "byteOffset", "peekOffset", "Int64FlatVector", "Int64SequenceVector", "decodeZOrderCurve", "decodeMorton", "mortonCode", "numBits", "coordinateShift", "code", "GEOMETRY_TYPE", "\"POINT\"", "\"LINESTRING\"", "\"POLYGON\"", "\"MULTIPOINT\"", "\"MULTILINESTRING\"", "\"MULTIPOLYGON\"", "SINGLE_PART_GEOMETRY_TYPE", "VertexBufferType", "\"VEC_2\"", "\"VEC_3\"", "convertGeometryVector", "geometryVector", "partOffsetCounter", "ringOffsetsCounter", "geometryOffsetsCounter", "geometryCounter", "vertexBufferOffset", "vertexOffsetsOffset", "mortonSettings", "topologyVector", "geometryOffsets", "partOffsets", "ringOffsets", "vertexOffsets", "nonOffset", "containsPolygon", "geometryType", "numPoints", "decodeDictionaryEncodedVertices", "getLineStringOrRing", "numRings", "shell", "numLineStrings", "lineStrings", "numPolygons", "numRingVertices", "vertexBufferType", "decodeMortonDictionaryEncodedVertices", "vertexOffset", "decodeVec2DictionaryEncodedVertices", "mortonEncodedVertex", "GeometryVector", "_vertexBufferType", "_topologyVector", "_vertexOffsets", "_vertexBuffer", "_mortonSettings", "createConstGeometryVector", "ConstGeometryVector", "numGeometries", "createMortonEncodedConstGeometryVector", "_numGeometries", "_geometryType", "createFlatGeometryVector", "FlatGeometryVector", "createFlatGeometryVectorMortonEncoded", "_geometryTypes", "GpuVector", "_triangleOffsets", "_indexBuffer", "createConstGpuVector", "ConstGpuVector", "triangleOffsets", "createFlatGpuVector", "FlatGpuVector", "decodeGeometryColumn", "geometryTypeMetadata", "geometryTypesVectorType", "geometryStreamMetadata", "mortonMetadata", "geometryTypeVector", "geometryLengths", "partLengths", "ringLengths", "decodeRootLengthStream", "decodeLevel1LengthStream", "decodeLevel2LengthStream", "decodeLevel1WithoutRingBufferLengthStream", "rootBufferOffsets", "previousOffset", "rootLengthCounter", "bufferId", "rootLengthStream", "level1BufferOffsets", "rootOffsetBuffer", "level1BufferCounter", "level1LengthBufferCounter", "isLineStringPresent", "level1LengthBuffer", "level1OffsetBufferCounter", "level1LengthCounter", "level2BufferOffsets", "level1OffsetBuffer", "level2OffsetBufferCounter", "level2LengthBufferCounter", "numParts", "level2LengthBuffer", "BooleanFlatVector", "dataVector", "FloatFlatVector", "Int64ConstVector", "VariableSizeVector", "offsetBuffer", "StringFlatVector", "StringDictionaryVector", "dictionaryBuffer", "getDecodedLength", "decodedLength", "compressedData", "symbolIndex", "symbolLengths", "decodeFsst", "symbolOffsets", "decodedOffset", "symbolLength", "symbolOffset", "symbols", "StringFsstDictionaryVector", "symbolOffsetBuffer", "symbolTableBuffer", "sharedDictionaryCache", "lengthBuffer", "dictionaryLengthStream", "offsetStream", "dictionaryStream", "symbolLengthStream", "symbolTableStream", "plainLengthStream", "plainDataStream", "presentStream", "lengthStream", "dictType", "decodeFsstDictionaryVector", "decodeDictionaryVector", "decodePlainStringVector", "sparseOffsetStream", "valueIndex", "decodeSharedDictionary", "dictionaryOffsetBuffer", "dictionaryStreamDecoded", "childFields", "stringDictionaryVectors", "childField", "propertyColumnNames", "presentStreamBitVector", "presentStreamMetadata", "ObjectFlatVector", "MapMask", "\"INT32\"", "\"UINT32\"", "\"INT64\"", "\"UINT64\"", "\"FLOAT\"", "\"DOUBLE\"", "\"PRESENCE\"", "MapControlValue", "\"FALSE\"", "\"TRUE\"", "\"START_MAP\"", "\"START_LIST\"", "\"COUNT\"", "decodeMapPropertyColumn", "columnNames", "getMapColumnNames", "columnMetadata", "streams", "decodeMapStreams", "featureCount", "vectors", "countsCursor", "valuesCursor", "childIndex", "decodeChildColumn", "dictionaryMask", "remainingStreams", "dictionary", "decodeStringDictionary", "decodeIntegerDictionaries", "decodeFloatingPointDictionaries", "presentCount", "presence", "decodePresenceStream", "flattenedValues", "stringStreamCount", "consumed", "pushAll", "streamDataStart", "presentOffset", "presentInChild", "countsEnd", "countCursor", "flattenedIndex", "decodeFeatureValue", "childValueCount", "valuesEnd", "decodeValue", "decodeMapEntries", "decodeScalarByIndex", "token", "valueEndIndex", "decodeNestedPayloadEnd", "nested", "encodedLength", "dictionaryIndex", "decodePropertyColumn", "decodeScalarPropertyColumn", "presentVector", "decodeInt32Column", "stringDataStreams", "decodeBooleanColumn", "decodeInt64Column", "decodeFloatColumn", "decodeDoubleColumn", "dataStreamMetadata", "isNullabilityBuffer", "vectorType", "scalarColumn", "constValue", "ColumnTypeCode", "decodeColumnType", "typeCode", "mapScalarType", "columnTypeHasName", "columnTypeHasChildren", "hasStreamCount", "scalarCol", "complexCol", "isLogicalIdColumn", "isGeometryColumn", "physicalType", "textDecoder", "SUPPORTED_COLUMN_TYPES", "columnToField", "nullable", "decodeField", "childCount", "decodeColumn", "decodeEmbeddedTileSetMetadata", "meta", "table", "columnCount", "decodeTile", "featureTables", "blockLength", "blockEnd", "metadata", "featureTableMetadata", "propertyVectors", "idDataStreamMetadata", "decodeIdColumn", "idWithinMaxSafeInteger", "geometryScaling", "propertyVector", "featureTable", "idDataType", "MLTVectorTileFeature", "pointRing", "MLTVectorTileLayer", "MLTVectorTile", "is3D", "queryPadding", "matching", "cameraBounds", "matching3D", "bx1", "by1", "bx2", "by2", "topDownFeatureComparator", "previousIndex", "featureGeometry", "sourceFeatureState", "layerIDs", "filterLayerIDs", "sourceLayerName", "serializedLayer", "evaluateProperties", "intersectionZ", "geojsonFeature", "layerResult", "filterParams", "symbolFeatureIndex", "symbolFeatureIndexes", "propName", "sourceLayerId", "needsEvaluating", "serializedProperties", "styleLayerProperties", "RTLPluginLoadedEventName", "RTLMainThreadPlugin", "statusToSend", "deferred", "rtlMainThreadPlugin", "rtlMainThreadPluginFactory", "AE", "Tile", "symbolLayer", "fadingRole", "fadingDirection", "fadingParentID", "fadeEndTime", "painter", "deserializeBucket", "justReloaded", "vtLayers", "sourceLayer", "\"_geojsonTileLayer\"", "parsedCC", "isExpired", "revision", "\"sourceLayer\"", "sourceLayerStates", "duration", "dep", "dependencies", "namespace", "namespaces", "TileCache", "onRemove", "removedData", "dataWrapper", "expiryTimeout", "dataIndex", "filterFn", "featureStatesMapToArray", "SourceFeatureState", "featureId", "newState", "changes", "reconciledState", "featureDeletions", "layerStates", "featuresChangedMap", "featuresChanged", "inViewTiles", "Aabb", "min_", "max_", "vec3.add", "split", "qMin", "vec3.clone", "qMax", "fullyInside", "frustum", "planeIntersection", "distMin", "distMax", "Frustum", "planes", "aabb", "clipSpaceCorners", "frustumPlanePointIndices", "flippedNearFar", "frustumCoords", "unprojectClipSpacePoint", "invProj", "horizonPlane", "adjustFarPlaneByHorizonPlane", "frustumPlanes", "vec3.normalize", "vec3.sub", "vec4.transformMat4", "vec4.mul", "nearPlanePointsOffset", "farPlanePointsOffset", "maxDist", "cornerRayLengths", "cornerRayNormalizedDirections", "vec3.length", "nearPlaneNormalized", "getNormalizedNearPlane", "nearPlanePointsIndices", "idealFarPlaneDistanceFromNearPlane", "getIdealNearFarPlaneDistance", "idealCornerRayLength", "targetLength", "nearPlaneA", "nearPlaneB", "normalizedHorizonPlane", "vec4.scale", "projectedViewDirection", "projectedViewLength", "horizonCircleRadius", "isTileVisible", "frustumTest", "tileBoundingVolume", "planeTest", "integralOfCosXByP", "createCalculateTileZoomFunction", "pitchTileLoadingBehavior", "maxZoomLevelsOnScreen", "cameraVerticalFOV", "centerPitch", "distanceToTileZ", "distanceToCenter3D", "tileCountPitch0", "highestPitch", "lowestPitch", "tileCount", "thisTilePitch", "distanceToTile2D", "distanceToTile3D", "thisTileDesiredZ", "requestedCenterZoom", "tileCountMaxMinRatio", "defaultCalculateTileZoom", "coveringZoomLevel", "getElevationForTileCulling", "proximityToHorizon", "maxFeatureHeight", "maxContentElevation", "pushFrustumFarPlane", "distanceToFar", "ray", "cameraPos", "rayDotNormal", "expandCullingToContentElevation", "shellRadius", "horizonCos", "shellCos", "coveringTiles", "detailsProvider", "cameraCoord", "centerCoord", "elevationForTileCulling", "allowVariableZoom", "desiredZ", "nominalZ", "numTiles", "cameraPoint", "centerPoint", "distanceToCenter2d", "distanceZ", "distanceToCenter3d", "newRootTile", "it", "fullyVisible", "boundingVolume", "intersectResult", "distToTile2d", "vec2.sqrLen", "childX", "childY", "childZ", "isRasterType", "updateFadingTiles", "currentTime", "edgeTileIDs", "idealTileIDs", "idealID", "idealTile", "updateFadingAncestor", "retain", "maxFadingAncestorLevels", "sourceMinZoom", "rasterFadeDuration", "updateFadingDescendents", "updateFadingEdge", "minAncestorZ", "ancestorZ", "ancestorTile", "idealChildren", "hasFader", "updateFadingChildren", "childID", "childIDs", "foundFader", "childTile", "hasRasterTransition", "backfillDEM", "renderables", "borderId", "fillBorder", "InViewTiles", "wrapDelta", "sorted", "a_", "b_", "rotatedA", "bearingInRadians", "rotatedB", "createSource", "shouldReload", "hadData", "parentZ", "parentTile", "sourceDataChanged", "previousState", "loadedDescendents", "idealTilesWithoutData", "incomplete", "targetID", "descendents", "maxCoveringZoom", "candidates", "topZoom", "topIDs", "targetTileIDs", "generationIDs", "generationZ", "approxTilesInView", "commonZoomRange", "viewDependentMaxSize", "worldDifference", "maxElevation", "heightOffset", "unwrapped", "noPendingDataEmissions", "isRaster", "ancestors", "parent2", "retainTileMap", "tileIdsWithoutData", "checked", "minCoveringZoom", "parentWasRequested", "parentId", "hasData", "reload", "timeout", "tileIds", "tid", "tileResults", "allowWorldCopies", "cameraPointQueryGeometry", "pointQueryGeometry", "project", "cameraQueryGeometry", "tileSpaceBounds", "tileSpaceQueryGeometry", "tileSpaceCameraQueryGeometry", "transformed", "geom", "checkWrap", "fadeDuration", "tileKey", "PathInterpolator", "points_", "padding_", "distOfCurrentIdx", "distToTarget", "idxOfPrevPoint", "distOfPrevIdx", "segmentLength", "segmentT", "getSymbolElevation", "heightAnchorGround", "overlapAllowed", "allowed", "overlapA", "overlapB", "GridIndex", "boxCells", "circleCells", "hitTest", "boxUid", "circleUid", "queryArgs", "overlapMode", "boxCell", "circleCell", "circles", "circle", "bothRadii", "r1", "r2", "halfRectWidth", "distX", "circleX", "halfRectHeight", "distY", "circleY", "fastInvertTransformMat4", "sXYSqInv", "sZSqInv", "s0", "s4", "s8", "s1", "s5", "s9", "s2", "s6", "s10", "fastInvertProjMat4", "fastInvertSkewMat4", "invDetXY", "tmpMat4", "getPitchedLabelPlaneMatrix", "rotateWithMap", "getTileSkewVectors", "skew", "mat2.create", "vecEast", "vecSouth", "invert$1", "getGlCoordMatrix", "pitchWithMap", "cosRoll", "sinRoll", "cosPitch", "cosBearing", "sinBearing", "vec2.create", "vecSouthLen", "vec2.length", "vecEastLen", "elevationAt", "projectionContext", "projectWithMatrix", "xyTransformMat4", "getPerspectiveRatio", "cameraToCenterDistance", "signedDistanceFromCamera", "isVisible", "clippingBuffer", "updateLineLabels", "partiallyEvaluatedSize", "symbolSize.evaluateSizeForZoom", "lineVertexArray", "placedSymbols", "aspectRatio", "useVertical", "symbol", "hideGlyphs", "anchorPos", "projectTileCoordinatesToClipSpace", "cameraToAnchorDistance", "perspectiveRatio", "symbolSize.evaluateSizeForFeature", "pitchScaledFontSize", "placeUnflipped", "placeGlyphsAlongLine", "placeFirstAndLastGlyph", "glyphEndIndex", "lineEndIndex", "firstGlyphOffset", "glyphOffsetArray", "lastGlyphOffset", "firstPlacedGlyph", "placeGlyphAlongLine", "lineOffsetX", "lineOffsetY", "flip", "rotateToLine", "lastPlacedGlyph", "requiresOrientationChange", "firstPoint", "placedGlyphs", "firstAndLastGlyph", "projectFromLabelPlaneToClipSpace", "pitchedLabelPlaneMatrixInverse", "orientationChange", "glyphIndex", "placedGlyph", "projectTileCoordinatesToLabelPlane", "tileVertexIndex", "tileSegmentEnd", "projectedVertex", "projectTruncatedLineSegmentToLabelPlane", "clipSpaceA", "clipSpaceB", "singleGlyph", "unitVertexToBeProjected", "previousTilePoint", "currentTilePoint", "projectedUnitVertex", "projectedUnitSegment", "previousProjectedPoint", "minimumLength", "projectLineVertexToLabelPlane", "previousLineVertexIndex", "syntheticVertexArgs", "translatedX", "translatedY", "tileX", "tileY", "transformToOffsetNormal", "segmentVector", "findOffsetIntersectionPoint", "offsetCurrentVertex", "prevToCurrentOffsetNormal", "currentToNextOffsetNormal", "offsetNextSegmentBegin", "offsetNextSegmentEnd", "doublesBack", "isLineDoublingBack", "offsetPreviousVertex", "inX", "inY", "outX", "outY", "combinedOffsetX", "anchorSegment", "anchorPoint", "previousVertex", "offsetIntersectionPoint", "distanceFromAnchor", "currentSegmentDistance", "absOffsetX", "pathVertices", "currentLineSegment", "prevToCurrent", "segmentInterpolationT", "segmentAngle", "hiddenGlyphAttributes", "projectPathSpecialProjection", "inverseLabelPlaneMatrix", "projectedPath", "backProjected", "pathSlicedToLongestUnoccluded", "longestUnoccludedStart", "longestUnoccludedLength", "currentUnoccludedStart", "currentUnoccludedLength", "CollisionIndex", "ignoredGrid", "collisionBox", "translation", "projectedPoint", "simpleProjectionMatrix", "tileToViewport", "textPixelRatio", "projectedBox", "pointX", "pointY", "occluded", "unplaceable", "collisionGroupPredicate", "placedCollisionCircles", "tileUnitAnchorPoint", "labelPlaneFontScale", "projectionCache", "collisionDetected", "inGrid", "entirelyOffscreen", "circlePixelDiameter", "textPixelPadding", "screenPlaneMin", "screenPlaneMax", "interpolator", "circleDist", "screenSpacePath", "minPoint", "maxPoint", "seg", "numCircles", "circlePosition", "centerX", "centerY", "showCollisionCircles", "viewportQueryGeometry", "query", "gridPoint", "seenFeatures", "featureKey", "intersectionTests.polygonIntersectsPolygon", "ignorePlacement", "collisionCircles", "mat4.identity", "vecEastX", "vecEastY", "vecSouthX", "vecSouthY", "translatedAnchorX", "translatedAnchorY", "projectedEast", "toEastX", "toEastY", "basePointX", "basePointY", "distanceMultiplier", "offsetXmin", "offsetXmax", "offsetXhalf", "offsetYmin", "offsetYmax", "offsetYhalf", "offsetsArray", "anyPointVisible", "OpacityState", "prevState", "increment", "skipFade", "placed", "JointOpacityState", "placedText", "placedIcon", "JointPlacement", "RetainedQueryData", "CollisionGroups", "crossSourceCollisions", "nextGroupID", "calculateVariableLayoutShift", "CROSS_TILE_ID_UINT32_OFFSET", "symbolInstanceLayout", "Placement", "prevPlacement", "symbolBucket", "bucketFeatureIndex", "pixelsToTiles", "translationText", "translationIcon", "pitchedLabelPlaneMatrix", "projection.getPitchedLabelPlaneMatrix", "sortAcrossTiles", "textAnchorOffset", "placedGlyphBoxes", "textBox", "textOverlapMode", "collisionGroup", "iconBox", "prevAnchor", "orientation", "bucketPart", "textOptional", "iconOptional", "textAlwaysOverlap", "iconOverlapMode", "iconAlwaysOverlap", "alwaysShowText", "alwaysShowIcon", "placeSymbol", "seenCrossTileIDs", "holdingForFade", "symbolHeightOffset", "placeText", "placeIcon", "offscreen", "placedVerticalText", "placedGlyphCircles", "placedIconBoxes", "textFeatureIndex", "verticalTextFeatureIndex", "iconFeatureIndex", "ce", "updatePreviousOrientationIfNotPlaced", "previousOrientation", "isPlaced", "prevPlacedOrientation", "placeTextForPlacementModes", "placementMode", "placeVerticalFn", "placeHorizontalFn", "textAnchorOffsetStart", "textAnchorOffsetEnd", "placeBox", "placedFeature", "collisionTextBox", "verticalTextBox", "placeBoxForVariableAnchors", "variableIconBox", "collisionIconBox", "placedBox", "placementPasses", "pass", "showCollisionBoxes", "wasPlaced", "prevOrientation", "prevOffset", "partiallyEvaluatedTextSize", "le", "placeIconFeature", "oe", "iconWithoutText", "textWithoutIcon", "hasTextBox", "hasIconBox", "textVisible", "iconVisible", "symbolIndexes", "boxArray", "realCollisionBox", "circleArray", "autoIndex", "placedAnchor", "indexes", "horizontal", "horizontalIndexes", "placementChanged", "prevOpacities", "prevOffsets", "prevOrientations", "crossTileID", "jointPlacement", "prevOpacity", "jointOpacity", "hasDebugOutput", "duplicates", "uint32", "duplicate", "crossTileIDs", "duplicateOpacityState", "textAllowOverlap", "iconAllowOverlap", "hasVariablePlacement", "defaultOpacityState", "addOpacities", "opacity", "boxArrays", "isDuplicate", "opacityState", "placedOrientation", "horizontalHidden", "verticalHidden", "packedOpacity", "packOpacity", "horizontalOpacity", "verticalOpacity", "symbolHidden", "textSymbolIndexes", "useHorizontal", "realBoxes", "used", "variableOffset", "hidden", "updateCollisionVertices", "verticalIconUsed", "durationAdjustment", "realBox", "shift25", "shift24", "shift17", "shift16", "PACKED_VISIBLE_OPACITY", "targetBit", "opacityBits", "LayerPlacement", "bucketParts", "placement", "shouldPausePlacement", "PauseablePlacement", "forceFullPlacement", "startTime", "placementZoom", "layerTiles", "ARRAY_TYPES", "STACK", "KDBush", "magic", "versionAndType", "ArrayType", "nodeSize", "numItems", "arrayTypeIndex", "coordsByteSize", "idsByteSize", "padCoords", "ArrayBufferType", "numAdded", "oO", "sp", "select", "swapItem", "roundingFactor", "TileLayerIndex", "symbolInstancesByKey", "symbolInstances", "instances", "localX", "localY", "localZ", "childTileID", "xWorld", "yWorld", "xOffset", "yOffset", "tolerance", "newTileID", "scaledSymbolCoord", "zoomCrossTileIDs", "bestIndex", "candidate", "thisTileSymbol", "CrossTileIDs", "CrossTileSymbolLayerIndex", "zoomIndexes", "newZoomIndex", "parentIndex", "removedBucket", "tilesChanged", "currentIDs", "CrossTileSymbolIndex", "layerIndex", "symbolBucketsChanged", "currentBucketIDs", "usedLayerMap", "usedLayer", "usedLayers", "_prelude_fragment_glsl_g_default", "_prelude_vertex_glsl_g_default", "background_fragment_glsl_g_default", "background_vertex_glsl_g_default", "background_pattern_fragment_glsl_g_default", "background_pattern_vertex_glsl_g_default", "circle_fragment_glsl_g_default", "circle_vertex_glsl_g_default", "clipping_mask_fragment_glsl_g_default", "shaders", "prepare", "preludeFrag", "preludeVert", "projectionMercatorFrag", "projectionMercatorVert", "projectionGlobeFrag", "projectionGlobeVert", "backgroundFrag", "backgroundVert", "backgroundPatternFrag", "backgroundPatternVert", "circleFrag", "circleVert", "clippingMaskFrag", "clippingMaskVert", "heatmapFrag", "heatmapVert", "heatmapTextureFrag", "heatmapTextureVert", "collisionBoxFrag", "collisionBoxVert", "collisionCircleFrag", "collisionCircleVert", "colorReliefFrag", "colorReliefVert", "debugFrag", "debugVert", "depthVert", "fillFrag", "fillVert", "fillOutlineFrag", "fillOutlineVert", "fillOutlinePatternFrag", "fillOutlinePatternVert", "fillPatternFrag", "fillPatternVert", "fillExtrusionFrag", "fillExtrusionVert", "fillExtrusionPatternFrag", "fillExtrusionPatternVert", "hillshadePrepareFrag", "hillshadePrepareVert", "hillshadeFrag", "hillshadeVert", "lineFrag", "lineVert", "lineGradientFrag", "lineGradientVert", "linePatternFrag", "linePatternVert", "lineSDFFrag", "lineSDFVert", "lineGradientSDFFrag", "lineGradientSDFVert", "layerOpacityFrag", "layerOpacityVert", "rasterFrag", "rasterVert", "symbolIconFrag", "symbolIconVert", "symbolSDFFrag", "symbolSDFVert", "symbolTextAndIconFrag", "symbolTextAndIconVert", "terrainFrag", "terrainVert", "terrainDepthFrag", "terrainVertDepth", "terrainHeightFrag", "terrainHeightVert", "atmosphereFrag", "atmosphereVert", "skyFrag", "skyVert", "vertexAttributes", "vertexSource", "fragmentUniforms", "fragmentSource", "vertexUniforms", "shaderUniforms", "locationCounter", "fragmentPragmas", "operation", "attrType", "unpackType", "MercatorShaderDefine", "MercatorShaderVariantKey", "MercatorProjection", "tileExtentArray", "tileExtentBuffer", "tileExtentSegments", "quadTriangleIndices", "quadTriangleIndexBuffer", "EdgeInsets", "createCameraState", "getCenterPoint", "cameraState", "getCenterOffset", "getWorldSize", "getBearing", "getPitch", "getRoll", "getFov", "normalizeCenter", "getTileZoom", "TransformHelper", "callbacks", "thatI", "constrain", "unmodified", "renderWorldCopies", "fov", "constrainedZoom", "longitudeUnconstrained", "constrained", "halfFov", "cameraBearing", "cameraPitch", "alt", "cameraLngLat", "camMercator", "distanceToCenter", "clampedElevation", "originalCenterMercator", "originalMetersPerMercUnit", "dCamMercator", "previousZoom", "metersPerMercUnit", "cameraMercator", "centerMetersPerMercUnit", "nextStep", "dzNormalized", "altitudeAGL", "MercatorCoveringTilesDetailsProvider", "distanceX", "distanceY", "parentWrap", "minElevation", "minMax", "maxConstantZoomPitch", "MAX_TILE_COORD", "DEM_CELL_CENTER_OFFSET", "NOT_COVERED", "TerrainCoverage", "exaggeration", "getWorldCoordinateHelper", "ownDemOnly", "sampleAt", "cachedSampler", "sampler", "sourceTile", "dem", "tilesPerDemTile", "demPixelScale", "demPixelOffsetX", "demPixelOffsetY", "extentScale", "zooms", "samplerPerTile", "worldY", "wraps", "worldX", "wrappedX", "scaledX", "scaledY", "isBelowTerrainSample", "bisect", "hi", "lo", "isBelowTerrain", "MercatorTransform", "nearZ", "farZ", "lngRange", "scaleY", "scaleX", "screenWidth", "screenHeight", "latRange", "originalY", "modifiedX", "modifiedY", "originalX", "h2", "sharedHelper", "that", "utl", "utr", "ubl", "ubr", "w0", "w1", "camera", "wrapped", "distanceAtMaxZoom", "vec3.lerp", "tStart", "tEnd", "tHigh", "tLow", "horizontalLength", "samples", "previousT", "aboveTerrain", "mercatorIsBelowTerrain", "sampleLo", "mercatorSampleAt", "sampleHi", "fLo", "fHi", "hit", "coord0", "clipZ", "coord1", "pixelMatrix", "halfExtentX", "halfExtentY", "belowHorizon", "posMatrixKey", "matrices", "useFloat32", "tileMatrix", "multiply$2", "fogMatrix", "clampedX", "clampedY", "constrainedX", "constrainedY", "fromLngLat", "toLngLat", "fromWorld", "altitudeFrom", "toWorld", "altitudeTo", "distance3D", "groundDistance", "cameraToLowestPointDistance", "cameraToSeaLevelDistance", "limitedPitchRadians", "lowestPlane", "groundAngle", "fovAboveCenter", "topHalfSurfaceDistance", "horizon", "horizonAngle", "minFovCenterToHorizonRadians", "fovCenterToHorizon", "topHalfSurfaceDistanceHorizon", "topHalfMinDistance", "nearFarZ", "mat4.clone", "rotateZ$1", "rotateX$1", "mat4.scale", "mat4.invert", "xShift", "yShift", "angleCos", "angleSin", "alignedM", "cameraToCenterDistanceMeters", "mercatorTileCoordinates", "tilePosMatrix", "mainMatrix", "applyTerrainMatrix", "tLocation", "raySegmentParameter", "rendererProjectionData", "projectionMatrixScaled", "createMercatorTransform", "cameraBoundsWarning", "updateRotation", "startRotation", "endRotation", "eulerAngles", "cameraForBoxAndBearing", "nwWorld", "neWorld", "seWorld", "swWorld", "worldBulge", "upperRight", "lowerLeft", "availableWidth", "mapPadding", "fitPadding", "availableHeight", "rotatedPaddingOffset", "offsetAtFinalZoom", "middle", "MercatorCameraHelper", "offsetLength", "pan", "pixelsToHorizon", "deltas", "preZoomAroundLoc", "startZoom", "startPadding", "startEulerAngles", "endEulerAngles", "optionsZoom", "doPadding", "isZooming", "pointAtOffset", "locationAtOffset", "endZoom", "finalScale", "easeFunc", "speedup", "newCenterWorld", "newCenter", "endTransform", "constrainedCenter", "targetZoom", "startWorldSize", "pixelPathLength", "scaleOfZoom", "requestedMinZoom", "effectiveMinZoom", "minZoomPreConstrain", "scaleOfMinZoom", "centerFactor", "angles", "sk", "granularitySettingsGlobe", "VerticalPerspectiveProjection", "usage", "allowPoles", "hasBorder", "mesh", "GlobeProjection", "currentProjectionSpecValue", "_tileID", "_hasBorder", "_allowPoles", "_usage", "getGlobeCircumferencePixels", "getGlobeRadiusPixels", "globeDistanceOfLocationsPixels", "angularCoordinatesToSurfaceVector", "radians", "circumference", "mercatorCoordinatesToAngularCoordinatesRadians", "angularCoordinatesRadiansToVector", "latRadians", "lngRadians", "projectTileCoordinatesToSphere", "tileIdZ", "tileIdX", "tileIdY", "sphericalX", "sphericalY", "planetScaleAtLatitude", "latitudeDegrees", "getGlobeCenterInViewSpace", "sphereSurfacePointToCoordinates", "latDegrees", "surface", "lengthXZ", "projX", "projZ", "acosZ", "orientationFromLngLatBearing", "quat.fromEuler", "lngLatBearingFromOrientation", "PAN_MAX_ANGLE", "panSurfaceLocation", "lateral", "handoverAngle", "sinHandover", "targetAtHandover", "slopeAtHandover", "room", "excess", "versorSetLocationAtPoint", "pointLngLat", "sourceLngLat", "panDelta", "vecToPixelCurrent", "vecToTarget", "centerQuat", "quat.set", "quat.identity", "newCenterLng", "newCenterLat", "newBearing", "quat.multiply", "oldLat", "oldZoom", "finalLat", "fixedBearing", "fixedBearingLatitude", "finalLng", "fixedBearingLongitude", "getZoomAdjustment", "oldLng", "poleLat", "polePoint", "rx", "ry", "tRamp", "dial", "dLngSwing", "dLngDial", "dTheta", "horizonPlaneToCenterAndRadius", "clampToSphere", "relativeToCenter", "clamped", "oldCircumference", "newLat", "getDegreesPerPixel", "computeGlobePanCenter", "rotatedPanDelta", "normalizedGlobeZoom", "lngSpeed", "panningDegreesPerPixel", "integrateSecX", "xHalf", "interpolateLngLatForGlobe", "interpolatedLat", "deltaLat", "startLat", "endLat", "samplePointStart", "samplePointEnd", "valueT", "valueStart", "valueEnd", "newT", "deltaLng", "raySphereIntersection", "originDotDirection", "scaledDir", "discriminant", "tMax", "getAtmosphereAltitudeBlend", "atmosphereHeight", "globeRadius", "BoundingVolumeCache", "boundingVolumeFactory", "oldCache", "cachedPrevious", "ConvexVolume", "axisX", "vec3.transformQuat", "halfSize", "axisY", "axisZ", "boxPointCount", "boxPlaneCount", "frustumPlaneCount", "frustumPointCount", "boxPointsPassed", "frustumPointsPassed", "pointCount", "positivePoints", "distanceToTileSimple", "distanceToTileWrapX", "tileCornerToPointX", "tileCornerX", "tileCornerY", "GlobeCoveringTilesDetailsProvider", "tileMercatorSize", "halfWorld", "smallestDistance", "distanceCurrent", "distanceLeft", "distanceRight", "distanceSmallest", "extremesPoints", "aabbMin", "aabbMax", "centerEast", "axisEast", "axisWest", "upDownMinMax", "findAxisMinMax", "northSouthMinMax", "planeUp", "planeDown", "planeNorth", "planeSouth", "planeEast", "planeWest", "SAME_POINT_DISTANCE", "VerticalPerspectiveTransform", "maxLatitude", "distanceCameraToB", "globeRadiusPixels", "distanceCameraToA", "distanceAtoC", "tangentPlaneDistanceToC", "vectorCtoCamX", "vectorCtoCamY", "vectorCtoCamLength", "planeVector", "coverage", "raisedSurfaceVector", "rayParameter", "sphereX", "sphereY", "spherePos", "axisRight", "axisDown", "normalized", "mercator", "textAnchorX", "textAnchorY", "angular", "vectorMultiplier", "elevatedX", "elevatedY", "elevatedZ", "isOccluded", "cam", "lengthSq", "globeMatrix", "scaleVec", "rotateY$1", "xMid", "yMid", "testPoints", "projectedPoints", "mostEast", "mostWest", "mostNorth", "mostSouth", "dLng", "dLat", "boundsArray", "areaRadians", "areaPixels", "reachPixels", "centerPixels", "targetAtAltitude", "toCamera", "vec3.subtract", "vec3.distance", "zero$1", "rotatedPixelVector", "vecToTargetXZLengthSquared", "targetXSquared", "intersectionA", "intersectionB", "lngA", "lngB", "vecToTargetLngA", "latA", "vecToTargetLngB", "latB", "limit", "isValidA", "isValidB", "validLng", "validLat", "centerLngRadians", "centerLatRadians", "lngDistA", "latDistA", "lngDistB", "latDistB", "newLng", "moved", "adjustedZoom", "outer", "globeIsBelowTerrain", "globeSampleAt", "rayOrigin", "rayNormalized", "rayDirection", "intersection", "intersectionPoint", "sphereSurface", "directionDotPlaneXyz", "distanceToIntersection", "distantPoint", "distanceFromPlane", "horizonDisk", "globeData", "createVerticalPerspectiveTransform", "GlobeTransform", "constrainTransform", "globeness", "mercatorProjectionData", "verticalPerspectiveProjectionData", "verticalPerspective", "mercatorData", "applyGlobeMatrix", "createGlobeTransform", "VerticalPerspectiveCameraHelper", "panCenter", "zoomPixel", "zoomLoc", "oldZoomPreZoomDelta", "actualZoomDelta", "dLngRaw", "distanceToClosestPoint", "closestPoint", "rayDistanceFromGlobeCenter", "distanceFromSurface", "distanceFactor", "interpolationFactorHorizon", "radiusFactor", "slowingFactor", "oldCenterLat", "heuristicCenter", "exactCenter", "interpolationFactorLongitude", "heuristicFactor", "lngExactToHeuristic", "latExactToHeuristic", "xLeft", "xRight", "yTop", "yBottom", "flipEastWest", "lngWest", "lngEast", "latNorth", "latSouth", "lngMid", "latMid", "clonedTr", "testVectors", "vecToCenter", "smallestNeededScale", "startingLat", "startCenter", "preConstrainCenter", "clampedPoint", "endCenterWithShift", "endZoomWithShift", "normalizedStartZoom", "normalizedEndZoom", "interpolatedZoom", "targetCenter", "normalizedTargetZoom", "normalizedEffectiveMinZoom", "interpolatedCenter", "targetValue", "columnXorY", "targetDimension", "columnZ", "vecDotXY", "vecDotZ", "toCenterDotXY", "toCenter", "toCenterDotZ", "GlobeCameraHelper", "globe", "createProjectionFromName", "transformOptions", "transformConstrain", "registeredName", "findRegisteredProjectionName", "globeProjection", "registered", "empty", "Style", "glyphLang", "propertyNames", "newStylesheetState", "changedGlobalStateRefs", "sourceIdsToReload", "globalStateChange", "layoutAffectingGlobalStateRefs", "paintAffectingGlobalStateRefs", "visibilityAffectingGlobalStateRefs", "previousStyle", "nextState", "projectionObjects", "dereferencedLayers", "styledLayer", "isUpdate", "completion", "serializedLayersDictionary", "returnClone", "toPush", "allLayerIds", "updatedIds", "removedIds", "action", "managersUsedBefore", "changedImages", "serializedStyle", "diffStyles", "operations", "styleChangeOperation", "unimplemented", "glyphsUrl", "geojsonSource", "forbiddenStateKeys", "stateKey", "myStyleSheet", "isLayer3D", "features3D", "sourceResult", "sourceResults", "layerFeatures", "topmost3D", "includedSources", "layersAsSet", "paramsStrict", "_update", "resolvedProjection", "skyOptions", "lastPlacement", "mat4.exactEquals", "placementCommitted", "layerBucketsChanged", "placementInputsChanged", "placementSettled", "spriteToAdd", "updatedSprite", "internalSpriteRepresentation", "rasterBoundsAttributes", "IndexBuffer", "dynamicDraw", "AttributeType", "VertexBuffer", "program", "BaseValue", "ClearColor", "ClearDepth", "ClearStencil", "ColorMask", "DepthMask", "StencilMask", "StencilFunc", "StencilOp", "StencilTest", "DepthRange", "DepthTest", "DepthFunc", "Blend", "BlendFunc", "BlendColor", "BlendEquation", "CullFace", "CullFaceSide", "FrontFace", "ProgramValue", "ActiveTextureUnit", "Viewport", "BindFramebuffer", "BindRenderbuffer", "BindTexture", "BindVertexBuffer", "BindElementBuffer", "BindVertexArray", "PixelStoreUnpack", "PixelStoreUnpackPremultiplyAlpha", "PixelStoreUnpackFlipY", "FramebufferAttachment", "ColorAttachment", "DepthAttachment", "DepthStencilAttachment", "Framebuffer", "fbo", "hasDepth", "hasStencil", "renderbuffer", "UBO_BINDINGS", "applyUBOBindings", "STD140_SIZE_AND_ALIGNMENT_WORDS", "std140Layout", "words", "UniformBuffer", "uploadedWords", "boundUniformBuffers", "createProjectionUniformBuffer", "updateProjectionUniformBuffer", "f32", "projectionData", "bindProjectionUniformBuffer", "keyedBuffer", "releaseProjectionUniformBuffers", "destroyProjectionUniformBuffers", "createFrameUniformBuffer", "updateFrameUniformBuffer", "setFrameUniformWorldSize", "createTerrainUniformBuffer", "updateTerrainUniformBuffer", "ColorMode", "blendFunction", "blendColor", "pj", "Context", "rbo", "storageFormat", "depth", "stencil", "cullFaceMode", "depthMode", "stencilMode", "colorMode", "VertexArrayObject", "paintBuffersDiffer", "paintVertexBuffers", "layoutVertexBuffer", "dynamicVertexBuffer", "dynamicVertexBuffer2", "dynamicVertexBuffer3", "numNextAttributes", "terrainPreludeUniforms", "\"u_depth\"", "\"u_terrain\"", "terrainUniforms", "\"u_texture\"", "\"u_ele_delta\"", "\"u_fog_matrix\"", "\"u_fog_color\"", "\"u_fog_ground_blend\"", "\"u_fog_ground_blend_opacity\"", "\"u_horizon_color\"", "\"u_horizon_fog_blend\"", "\"u_is_globe_mode\"", "terrainDepthUniforms", "terrainHeightUniforms", "\"u_tile_bounds\"", "terrainUniformValues", "eleDelta", "isGlobeMode", "terrainDepthUniformValues", "terrainHeightUniformValues", "getTokenizedAttributesAndUniforms", "getIntegerAttributeNames", "integerTypes", "numActiveAttributes", "Program", "staticAttrInfo", "dynamicAttrInfo", "configuration", "allAttrInfo", "preludeUniformsInfo", "staticUniformsInfo", "dynamicUniformsInfo", "uniformList", "allUniformsInfo", "defines", "showOverdrawInspector", "useTerrain", "projectionDefine", "extraDefines", "projectionPrelude", "fragmentShader", "vertexShader", "uniformLocations", "integerAttributeNames", "uniformLocation", "fixedUniforms", "uniformValues", "currentProperties", "primitiveSize", "drawMode", "dynamicLayoutBuffer", "dynamicLayoutBuffer2", "dynamicLayoutBuffer3", "patternUniformValues", "tileRatio", "tileSizeAtNearestZoom", "pixelX", "pixelY", "\"u_image\"", "\"u_texsize\"", "\"u_scale\"", "\"u_fade\"", "\"u_pixel_coord_upper\"", "\"u_pixel_coord_lower\"", "bgPatternUniformValues", "patternAtlas", "\"u_pattern_tl_a\"", "\"u_pattern_br_a\"", "\"u_pattern_tl_b\"", "\"u_pattern_br_b\"", "\"u_mix\"", "\"u_pattern_size_a\"", "\"u_pattern_size_b\"", "\"u_scale_a\"", "\"u_scale_b\"", "\"u_tile_units_to_pixels\"", "fillExtrusionUniforms", "\"u_lightpos\"", "\"u_lightpos_globe\"", "\"u_lightintensity\"", "\"u_lightcolor\"", "\"u_vertical_gradient\"", "\"u_fill_translate\"", "fillExtrusionPatternUniforms", "\"u_height_factor\"", "fillExtrusionUniformValues", "lightPos", "lightMat", "transformedLightPos", "lightColor", "shouldUseVerticalGradient", "fillExtrusionPatternUniformValues", "fillUniforms", "fillPatternUniforms", "\"u_sdf_pattern\"", "fillOutlineUniforms", "fillOutlinePatternUniforms", "fillPatternUniformValues", "fillUniformValues", "fillOutlineUniformValues", "fillOutlinePatternUniformValues", "isSdfPattern", "circleUniforms", "\"u_scale_with_map\"", "\"u_pitch_with_map\"", "\"u_extrude_scale\"", "\"u_globe_extrude_scale\"", "\"u_translate\"", "circleUniformValues", "extrudeScale", "globeExtrudeScale", "radiusCorrectionFactor", "debugUniforms", "\"u_color\"", "\"u_overlay\"", "\"u_overlay_scale\"", "debugUniformValues", "scaleRatio", "heatmapUniforms", "\"u_intensity\"", "heatmapTextureUniforms", "\"u_matrix\"", "\"u_color_ramp\"", "heatmapUniformValues", "intensity", "heatmapTextureUniformValues", "textureUnit", "colorRampUnit", "hillshadeUniforms", "\"u_latrange\"", "\"u_exaggeration\"", "\"u_altitudes\"", "\"u_azimuths\"", "\"u_accent\"", "\"u_method\"", "\"u_shadows\"", "\"u_highlights\"", "hillshadePrepareUniforms", "\"u_dimension\"", "\"u_zoom\"", "\"u_unpack\"", "\"u_log2_world_width\"", "hillshadeUniformValues", "accent", "method", "illumination", "getTileLatRange", "hillshadeUniformPrepareValues", "getLog2WorldWidth", "colorReliefUniforms", "\"u_elevation_stops\"", "\"u_color_stops\"", "\"u_color_ramp_size\"", "colorReliefUniformValues", "colorRampSize", "lineUniforms", "\"u_translation\"", "\"u_ratio\"", "lineGradientUniforms", "\"u_image_height\"", "linePatternUniforms", "lineSDFUniforms", "\"u_tileratio\"", "\"u_crossfade_from\"", "\"u_crossfade_to\"", "\"u_lineatlas_width\"", "\"u_lineatlas_height\"", "lineGradientSDFUniforms", "\"u_image_dash\"", "lineUniformValues", "calculateTranslation", "ratioScale", "lineGradientUniformValues", "linePatternUniformValues", "tileZoomRatio", "calculateTileRatio", "lineSDFUniformValues", "lineAtlas", "lineGradientSDFUniformValues", "layerOpacityUniforms", "layerOpacityUniformValues", "symbolIconUniforms", "\"u_is_size_zoom_constant\"", "\"u_is_size_feature_constant\"", "\"u_size_t\"", "\"u_size\"", "\"u_rotate_symbol\"", "\"u_label_plane_matrix\"", "\"u_coord_matrix\"", "\"u_is_text\"", "\"u_is_along_line\"", "\"u_is_variable_anchor\"", "\"u_pitched_scale\"", "\"u_is_offset\"", "\"u_height_anchor_ground\"", "symbolSDFUniforms", "\"u_gamma_scale\"", "\"u_is_halo\"", "\"u_is_plain\"", "symbolTextAndIconUniforms", "\"u_texsize_icon\"", "\"u_texture_icon\"", "symbolIconUniformValues", "rotateInShader", "labelPlaneMatrix", "glCoordMatrix", "isAlongLine", "isVariableAnchor", "texSize", "pitchedScale", "isOffset", "symbolSDFUniformValues", "symbolTextAndIconUniformValues", "texSizeSDF", "texSizeIcon", "backgroundUniforms", "backgroundPatternUniforms", "backgroundUniformValues", "backgroundPatternUniformValues", "atmosphereUniforms", "\"u_sun_pos\"", "\"u_atmosphere_blend\"", "\"u_globe_position\"", "\"u_globe_radius\"", "\"u_inv_proj_matrix\"", "atmosphereUniformValues", "sunPos", "atmosphereBlend", "globePosition", "invProjMatrix", "skyUniforms", "\"u_sky_color\"", "\"u_horizon\"", "\"u_horizon_normal\"", "\"u_sky_horizon_blend\"", "\"u_sky_blend\"", "skyUniformValues", "mercatorHorizon", "skyBlend", "emptyUniforms", "programUniforms", "ProgramCache", "configurationKey", "projectionKey", "overdrawKey", "terrainKey", "definesKey", "KEEP", "StencilMode", "fail", "depthFail", "PM", "ALWAYS", "BACK", "CCW", "CullFaceMode", "enable", "mode", "frontFace", "LM", "DepthMode", "depthFunc", "depthMask", "depthRange", "RM", "quadTriangles", "drawCollisionDebug", "frameRenderContext", "tileBatches", "circleCount", "circleOffset", "circleProgram", "vertexData", "batch", "circleIdx", "collision", "zM", "createQuadTriangles", "triCount", "quadCount", "idx", "identityMat4", "drawSymbols", "updateVariableAnchors", "drawLayerSymbols", "calculateVariableRenderShift", "renderTextSize", "variableOffsets", "rotationAlignment", "updateTextFitIcon", "tileScale", "updateVariableAnchorsForBucket", "getShiftedAnchor", "translatedAnchor", "adjustedShift", "pitchedTextShiftCorrection", "transformAngle", "tileAnchorShifted", "projectedAnchorPoint", "dynamicTextLayoutVertexArray", "dynamicIconLayoutVertexArray", "placedTextShifts", "skipOrientation", "tileAnchor", "projectedAnchor", "pitchedTextCorrection", "shiftedAnchor", "placedIcons", "getSymbolProgramName", "hasSortKey", "tileRenderState", "pitchedTextRescaling", "programConfiguration", "terrainData", "atlasTexture", "atlasInterpolation", "atlasTextureIcon", "atlasInterpolationIcon", "zoomDependentSize", "iconScaled", "glCoordMatrixForShader", "hasVariableAnchors", "shaderVariableAnchor", "combinedLabelPlaneMatrix", "uLabelPlaneMatrix", "hasHalo", "oldSegments", "haloWidth", "isGlyphOverlap", "segmentState", "isHalo", "drawSymbolElements", "drawCircles", "strokeWidth", "strokeOpacity", "segmentsRenderStates", "translateForUniforms", "segmentsState", "drawHeatmap", "prepareHeatmapTerrain", "renderHeatmapTerrain", "prepareHeatmapFlat", "renderHeatmapFlat", "bindFramebuffer", "getColorRampTexture", "createHeatmapFbo", "colorRampTexture", "prepareDrawLayerOpacity", "compositeTarget", "compositeViewport", "bindLayerOpacity", "drawLayerOpacity", "prepareDrawLayerOpacityResult", "updateGradientTexture", "textureResolution", "potentialOverzoom", "layerGradient", "bindImagePatternTextures", "bindDasharrayTextures", "programChanged", "bindGradientTextures", "gradientTexture", "bindGradientAndDashTextures", "drawLine", "layerOpacity", "drawLineTiles", "gradient", "programId", "firstTile", "prevProgram", "constantDasharray", "atlas", "updatePatternPositionsInProgram", "transitioned", "drawFill", "drawFillAndOutline", "fillEligibleForOpaque", "drawFillTiles", "drawOutline", "fillPropertyName", "programName", "propertyFillTranslate", "propertyFillTranslateAnchor", "isOutline", "drawFillExtrusion", "drawExtrusionTiles", "drawHillshade", "prepareHillshade", "useSubdivision", "stencilBorderless", "stencilBorders", "renderHillshade", "useBorder", "stencilModes", "textureFilter", "hillshadeTextureSize", "textureStride", "pixelData", "demTexture", "renderTexture", "drawColorRelief", "renderColorRelief", "textureMaxSize", "DN", "elevationTexture", "colorTexture", "drawRaster", "drawTiles", "minTileZ", "rasterOpacity", "isTerrain", "getFadeProperties", "fadeValues", "parentTopLeft", "sourceMesh", "flipCullfaceMode", "defaults", "getCrossFadeValues", "getSelfFadeValues", "timeSinceTile", "timeSinceParent", "doFadeIn", "opacity1", "opacity2", "tileOpacity", "drawBackground", "topColor", "btmColor", "leftColor", "rightColor", "centerColor", "drawDebugPadding", "drawHorizontalLine", "drawVerticalLine", "drawCrosshair", "drawDebugSSRect", "drawDebug", "drawDebugTile", "tileByteLength", "tileSizeKb", "tileIdText", "drawTextToOverlay", "ctx2d", "selectDebugSource", "selectedSource", "vectorSources", "otherSources", "considerSource", "drawDepth", "drawTerrain", "isRenderingGlobe", "drawTerrainHeightMap", "framebuffer", "drawCustom", "drawCustomTerrainTile", "customLayerArgs", "projectionShaderVariant", "renderingMode", "prerender", "viewport", "drawSky", "getSunPos", "transformMat4$1", "drawAtmosphere", "altitudeBlend", "webglDrawFunctions", "NUM_SUBLAYERS", "DEPTH_EPSILON", "MERCATOR_SHADER_VARIANT", "FrameRenderContext", "forceSimpleProjection", "func", "layerCount", "stencilRefs", "stencilRef", "tileStencilRefs", "useBorders", "stencilValues", "zToStencilMode", "zToStencilModeHigh", "zToStencilModeLow", "Painter", "debugArray", "rasterBoundsArray", "viewportArray", "tileLineStripIndices", "skyArray", "skyIndices", "layerIds", "coordsAscending", "coordsDescending", "coordsDescendingSymbol", "globeDepthRendered", "prevMatrix", "currMatrix", "doUpdate", "mat4.equals", "draw", "textures", "depthRenderbuffer", "drawingBufferWidth", "drawingBufferHeight", "GPUInitializationError", "requestedAttributes", "creationEvent", "throttle", "pending", "timerId", "lastCallArgs", "later", "time", "Hash", "hash", "newHash", "replaceString", "hashName", "degreesPerWorld", "mapFeedback", "defaultInertiaOptions", "defaultPanInertiaOptions", "defaultZoomInertiaOptions", "defaultBearingInertiaOptions", "defaultPitchInertiaOptions", "defaultRollInertiaOptions", "HandlerInertia", "inertia", "windowStart", "firstIndex", "entries", "settings", "easeOptions", "calculateEasing", "panInertiaOptions", "finalPan", "computedEaseOptions", "extendDuration", "inertiaOptions", "speed", "linearity", "inertiaDuration", "maxSpeed", "deceleration", "MapEventHandler", "mapEvent", "BlockableMapEventHandler", "mapTouches", "BoxZoomHandler", "transformProvider", "indexTouches", "getCentroid", "SingleTapRecognizer", "newTouches", "prevPos", "TapRecognizer", "tap", "soonEnough", "closeEnough", "TapZoomHandler", "zoomInPoint", "zoomOutPoint", "DragHandler", "move", "movePoint", "BUTTONS_FLAGS", "LEFT_BUTTON", "RIGHT_BUTTON", "buttonNoLongerPressed", "flag", "button", "MouseMoveStateManager", "OneFingerTouchMoveStateManager", "MouseOrTouchMoveStateManager", "mouseMoveStateManager", "oneFingerTouchMoveStateManager", "onMouseEvent", "onTouchEvent", "aroundDragStart", "around", "startPoint", "assignEvents", "generateMousePanHandler", "LP", "generateMouseRotationHandler", "getAround", "rotateSpeed", "getCenter", "isCircular", "getMovement", "minPixelCenterThreshold", "bearingDelta", "generateMousePitchHandler", "pitchSpeed", "generateMouseRollHandler", "rollDelta", "rollDegreesPerPixelMoved", "TouchPanHandler", "touchesCount", "touchPointSum", "touchDeltaSum", "touchDeltaCount", "TwoFingersTouchHandler", "getTouchById", "pinchAround", "defaultZoomThreshold", "getZoomDelta", "lastDistance", "TwoFingersTouchZoomHandler", "defaultZoomRate", "zoomRate", "zoomThreshold", "getBearingDelta", "TwoFingersTouchRotateHandler", "lastVector", "bearingDeltaSinceStart", "isVertical", "TwoFingersTouchPitchHandler", "vectorA", "vectorB", "movedA", "movedB", "timeStamp", "isSameDirection", "defaultOptions", "KeyboardHandler", "stepOptions", "zoomDir", "bearingDir", "pitchDir", "xDir", "yDir", "easeOut", "wheelZoomDelta", "ScrollZoomHandler", "initialEvent", "triggerRenderFrame", "wheelZoomRate", "timeDelta", "externalZoomChange", "fromScale", "currentSnapped", "easing", "finished", "lastWheelEventTimeDiff", "currentEase", "DoubleClickZoomHandler", "clickZoom", "TapZoom", "ClickZoomHandler", "TapDragZoomHandler", "swipePoint", "newSwipePoint", "DragPanHandler", "mousePan", "touchPan", "DragRotateHandler", "mouseRotate", "mousePitch", "mouseRoll", "aroundCenter", "enableOptions", "TwoFingersTouchZoomRotateHandler", "touchZoom", "touchRotate", "tapDragZoom", "CooperativeGesturesHandler", "mapCanvasContainer", "desktopMessage", "mobileMessage", "desktopDiv", "mobileDiv", "TransformProvider", "isMoving", "RenderFrameEvent", "hasChange", "HandlerManager", "inputEvent", "mergedHandlerResult", "eventsInProgress", "activeHandlers", "handlerName", "eventName", "eventTouches", "deactivatedHandlers", "cameraAnimation", "listenerOptions", "boxZoom", "cooperativeGestures", "tapZoom", "touchPitch", "scrollZoom", "keyboard", "allowEndAnimation", "myName", "handlerResult", "combined", "combinedEventsInProgress", "combinedDeactivatedHandlers", "change", "combinedResult", "zoomDelta", "aroundElevation", "aroundOnSurface", "deltasForHelper", "aroundPreviousPoint", "cameraHelper", "wasMoving", "nowMoving", "newEventsInProgress", "startEvents", "endEvents", "originalEndEvent", "stillMoving", "finishedMoving", "tookDem", "inertialEase", "shouldSnapToNorth", "ElevationHold", "holder", "startedWithoutDem", "terrainBelowMaxZoomForCenter", "drawnElevation", "MOVEMENT_AXES", "idleMovementAxes", "CameraMovementScheduler", "renderLoop", "easeId", "continuing", "events", "scheduled", "axes", "MAX_ZOOM_FOR_CENTER_TOLERANCE_M", "Camera", "newTransform", "newCameraHelper", "requestedCameraState", "centerClampedToGround", "snap", "defaultPadding", "noPadding", "calculatedOptions", "bearingChanged", "pitchChanged", "rollChanged", "demState", "zoomChanged", "centerInfo", "cameraAlt", "startBearing", "startPitch", "startRoll", "offsetAsPoint", "aroundPoint", "easeHandler", "elevationHandler", "freeze", "atStart", "reached", "terrainAboveMaxZoomForCenter", "hold", "isGesture", "lift", "heightForMaxZoom", "heightForCamera", "p3", "w3", "distanceFractionAtMaxZoom", "isBelowHorizon", "distanceFromCamera", "holdPivot", "isAtScreenPoint", "nextTransform", "hadRequestedCameraState", "freezeElevation", "flyToHandler", "rho", "u1", "wMax", "rho2", "zoomOutFactor", "descent", "sinh", "cosh", "tanh", "r0", "V", "rotating", "pitching", "rolling", "paddingChanging", "allowGestures", "currentBearing", "span", "placePivot", "nextSpan", "isAtDistance", "reachedSpan", "reachedDistance", "positionOf", "defaultAttributionControlOptions", "AttributionControl", "title", "attributions", "attribution", "stylesheet", "attrib", "attribHTML", "isFirst", "sanitizedAttribution", "LogoControl", "containerChildren", "TaskQueue", "running", "failed", "firstError", "pos3dAttributes", "TerrainTileManager", "terrainTileRanges", "terrainTileID", "mat", "dx2", "dy2", "searchForDEM", "sourceTileID", "canonicalTileRanges", "Terrain", "terrainSkirtLength", "matrixKey", "cachedMatrix", "demMatrix", "mat4.fromScaling", "terrainMatrix", "\"u_terrain_dim\"", "\"u_terrain_matrix\"", "\"u_terrain_unpack\"", "\"u_terrain_exaggeration\"", "northPole", "globeEnabled", "tileId", "southPole", "meshSize", "meshSize2", "worldCoordinate", "offsetTop", "offsetBottom", "offsetBottomEdge", "northY", "northZ", "southY", "southZ", "offsetLeft", "offsetRight", "RTT_DIFFERENCES", "RTTFingerprint", "visibleLayerIds", "LAYERS_TO_TEXTURES", "rttFingerprintKey", "isRenderedToTexture", "getRenderStacks", "prevRenderedToTexture", "renderedToTexture", "RenderToTexture", "rttSourceIds", "fingerprints", "moving", "staleTileReleased", "changedStacks", "fingerprinted", "fingerprintKey", "frameFingerprint", "tileFingerprint", "worst", "isLastLayer", "defaultLocale", "Map", "snapshot", "resolvedOptions", "_n", "styleProjectionType", "shouldConstrainUsingMercatorTransform", "coercedOptions", "control", "controlElement", "positionContainer", "ci", "fireMoving", "maxCanvasWidth", "maxCanvasHeight", "canvasWidth", "canvasHeight", "widthScaleFactor", "heightScaleFactor", "scaleFactor", "zoomBefore", "minPitch", "pitchBefore", "maxPitch", "anisotropicFilterPitch", "mousein", "existingLayers", "delegate", "delegatedListener", "layerIdsOrListener", "isGeometry", "geometryOrOptions", "styleOptions", "thisLayer", "isTerrainSourceEvent", "terrainSourceId", "styleImage", "existingImage", "beforeId", "spriteUrl", "initialResizeEventCaptured", "throttledResizeCallback", "ResizeObserverClass", "dimensions", "clampedPixelRatio", "canvasContainer", "controlContainer", "positionName", "updateStyle", "isGlobeRendering", "paintStartTimeStamp", "crossFading", "globeRenderingChanged", "projectionTransition", "somethingDirty", "NavigationControl", "isMax", "isMin", "MouseRotateWrapper", "moveStateManager", "pitchDelta", "supportsGeolocation", "checkGeolocationSupport", "forceRecalculation", "YF", "smartWrap", "useNormalWrap", "originalLngLat", "priorPos", "anchorTranslate", "applyAnchorClass", "classList", "ARROW_KEY_DELTAS", "DEFAULT_MARKER_COLOR", "svgElement", "defaultMarkerTemplate", "getDefaultMarkerTemplate", "rI", "defaultMarkerFillGroup", "svg", "MarkerDragEvent", "MarkerClickEvent", "Marker", "targetElement", "covered", "clickTolerance", "popup", "linearOffset", "targetOpacity", "metersToCenter", "elevationToCenter", "shouldBeDraggable", "role", "opacityWhenCovered", "numberOfWatches", "noTimeout", "GeolocateEvent", "GeolocatePositionEvent", "GeolocateErrorEvent", "GeolocateControl", "newBounds", "fromResize", "supported", "uI", "dI", "userLocation", "screenPosition", "userLocationWith100Px", "pixelsToMeters", "circleDiameter", "positionOptions", "ScaleControl", "updateScale", "optWidth", "containerWidth", "containerHeight", "globeWidth", "maxMeters", "maxFeet", "setScale", "getRoundNum", "maxDistance", "ratio", "getDecimalRoundNum", "multiplier", "pow10", "FullscreenEvent", "FullscreenControl", "fullscreenElement", "TerrainControl", "GlobeControl", "currentProjection", "PopupEvent", "Popup", "hasPosition", "cursor", "normalizeOffset", "normalizePadding", "anchorComponents", "offsetedPos", "frag", "html", "htmlNode", "firstFocusable", "cornerOffset", "convertedOffset", "setRTLTextPlugin", "pluginURL", "lazy", "getRTLTextPluginStatus", "getVersion", "getWorkerCount", "setWorkerCount", "getMaxParallelImageRequests", "setMaxParallelImageRequests", "numRequests", "getWorkerUrl", "setWorkerUrl", "importScriptInWorkers", "workerUrl", "BI", "maplibre_default", "maplibre_gl_exports", "Controller", "maplibre_default", "_", "marker", "quote_component_exports", "thumbnails_component_exports", "breadcrumbs_component_exports", "bulletin_component_exports", "__export", "Controller", "_createClass", "defineProperties", "target", "props", "i", "descriptor", "Constructor", "protoProps", "staticProps", "_classCallCheck", "instance", "slice", "matches", "_focusableElementsString", "InertRoot", "rootElement", "inertManager", "inertNode", "startNode", "_this2", "composedTreeWalk", "node", "activeElement", "root", "element", "_this3", "inertSubroot", "savedInertNode", "records", "self", "record", "managedNode", "ariaHidden", "InertNode", "inertRoot", "tabIndex", "InertManager", "document", "addInertStyle", "inert", "parent", "_inertRoot", "inertElements", "inertElement", "_this", "callback", "shadowRootAncestor", "shadowRoot", "content", "distributedNodes", "slot", "_distributedNodes", "_i", "child", "style", "Controller", "alternateText", "currentText", "button_component_exports", "card_component_exports", "details_component_exports", "footer_component_exports", "group_component_exports", "menu_component_exports", "__export", "Controller", "Controller", "header_component_exports", "__export", "Controller", "Controller", "target", "src", "current", "open", "i", "icon_card_component_exports", "icon_component_exports", "link_component_exports", "activities_component_exports", "bulletins_component_exports", "heading_component_exports", "__export", "Controller", "Controller", "date", "options", "panel_component_exports", "road_conditions_component_exports", "snowfield_component_exports", "ticker_component_exports", "__export", "Controller", "Controller", "viewportHeight", "lastScrollPos", "ticking", "e", "date", "options", "weather_component_exports", "city_component_exports", "__export", "Controller", "Controller", "maplibre_default", "_", "station_component_exports", "__export", "Controller", "import_leaflet", "import_leaflet_rastercoords", "TILE_SETS", "Controller", "img", "map", "rc", "RasterCoords", "L", "width", "details_component_exports", "contact_component_exports", "nav_component_exports", "partners_component_exports", "notice_component_exports", "partners_component_exports", "pill_component_exports", "activities_grid_component_exports", "agenda_component_exports", "carousel_component_exports", "__export", "Controller", "import_flickity", "Controller", "Flickity", "features_grid_component_exports", "grid_component_exports", "hero_component_exports", "__export", "Controller", "Controller", "pixels", "decodeBlurHash", "canvas", "ctx", "imageData", "target", "lambda_component_exports", "slate_component_exports", "slate_component_exports", "switcher_component_exports", "thumbnail_component_exports", "toc_component_exports", "modules", "filters_component_exports", "brand_component_exports", "button_component_exports", "button_group_component_exports", "section_component_exports", "tile_component_exports", "actions_component_exports", "content_editor_component_exports", "fieldset_component_exports", "group_component_exports", "grouped_collection_select_component_exports", "image_field_component_exports", "link_select_component_exports", "switch_box_component_exports", "text_field_component_exports", "gate_component_exports", "header_component_exports", "heading_component_exports", "layout_component_exports", "item_component_exports", "tree_component_exports", "list_component_exports", "menu_component_exports", "activities_grid_component_exports", "agenda_component_exports", "features_grid_component_exports", "hero_component_exports", "slate_component_exports", "tabs_component_exports", "toast_component_exports", "toaster_component_exports", "article_component_exports", "figure_component_exports", "gallery_component_exports", "map_component_exports", "quote_component_exports", "thumbnails_component_exports", "breadcrumbs_component_exports", "bulletin_component_exports", "card_component_exports", "details_component_exports", "footer_component_exports", "icon_card_component_exports", "icon_component_exports", "link_component_exports", "activities_component_exports", "bulletins_component_exports", "panel_component_exports", "road_conditions_component_exports", "snowfield_component_exports", "ticker_component_exports", "weather_component_exports", "city_component_exports", "station_component_exports", "contact_component_exports", "nav_component_exports", "partners_component_exports", "notice_component_exports", "pill_component_exports", "carousel_component_exports", "grid_component_exports", "lambda_component_exports", "switcher_component_exports", "thumbnail_component_exports", "toc_component_exports", "component_default", "component_default", "component", "path", "identifier", "application"]
}
